@catbee/utils 2.0.0-next.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +1 -1
- package/README.md +102 -52
- package/array/index.cjs +215 -74
- package/array/index.d.ts +345 -2
- package/array/index.mjs +201 -74
- package/async/index.cjs +116 -39
- package/async/index.d.ts +292 -2
- package/async/index.mjs +116 -40
- package/cache/index.cjs +2 -2
- package/cache/index.d.ts +156 -2
- package/cache/index.mjs +3 -3
- package/config/index.cjs +80 -66
- package/config/index.d.ts +65 -3
- package/config/index.mjs +77 -65
- package/context-store/index.cjs +2 -3
- package/context-store/index.d.ts +193 -2
- package/context-store/index.mjs +2 -3
- package/crypto/index.cjs +55 -5
- package/crypto/index.d.ts +225 -2
- package/crypto/index.mjs +52 -7
- package/date/index.cjs +676 -2
- package/date/index.d.ts +676 -2
- package/date/index.mjs +665 -3
- package/decorator/index.cjs +2172 -0
- package/{decorators/decorators.utils.d.ts → decorator/index.d.ts} +58 -54
- package/decorator/index.mjs +2131 -0
- package/{dir → directory}/index.cjs +5 -4
- package/{dir/dir.utils.d.ts → directory/index.d.ts} +24 -21
- package/{dir → directory}/index.mjs +5 -4
- package/env/index.cjs +100 -68
- package/env/index.d.ts +391 -2
- package/env/index.mjs +100 -68
- package/exception/index.cjs +1 -1
- package/exception/index.d.ts +233 -2
- package/exception/index.mjs +1 -1
- package/fs/index.cjs +71 -37
- package/fs/index.d.ts +206 -2
- package/fs/index.mjs +65 -35
- package/http-status-codes/index.cjs +1 -1
- package/http-status-codes/index.d.ts +268 -2
- package/http-status-codes/index.mjs +1 -1
- package/id/index.cjs +1 -1
- package/id/index.d.ts +38 -2
- package/id/index.mjs +1 -1
- package/index.cjs +13 -13
- package/index.d.ts +5 -5
- package/index.mjs +5 -5
- package/logger/index.cjs +13 -15
- package/logger/index.d.ts +190 -2
- package/logger/index.mjs +14 -16
- package/middleware/index.cjs +1 -1
- package/middleware/index.d.ts +104 -2
- package/middleware/index.mjs +1 -1
- package/object/index.cjs +379 -0
- package/{obj/obj.utils.d.ts → object/index.d.ts} +73 -33
- package/object/index.mjs +360 -0
- package/package.json +41 -23
- package/performance/index.cjs +4 -4
- package/performance/index.d.ts +139 -2
- package/performance/index.mjs +4 -4
- package/request/index.cjs +37 -25
- package/request/index.d.ts +242 -3
- package/request/index.mjs +37 -25
- package/response/index.cjs +1 -1
- package/response/index.d.ts +319 -3
- package/response/index.mjs +1 -1
- package/server/index.cjs +249 -146
- package/server/index.d.ts +866 -5
- package/server/index.mjs +248 -144
- package/stream/index.cjs +1 -1
- package/stream/index.d.ts +91 -2
- package/stream/index.mjs +1 -1
- package/string/index.cjs +34 -1
- package/string/index.d.ts +146 -2
- package/string/index.mjs +31 -2
- package/type/index.cjs +19 -2
- package/type/index.d.ts +144 -2
- package/type/index.mjs +17 -3
- package/types/index.cjs +1 -1
- package/types/index.d.ts +775 -5
- package/types/index.mjs +1 -1
- package/url/index.cjs +63 -5
- package/url/index.d.ts +200 -2
- package/url/index.mjs +59 -6
- package/{validate → validation}/index.cjs +91 -44
- package/{validate/validate.utils.d.ts → validation/index.d.ts} +33 -24
- package/{validate → validation}/index.mjs +87 -44
- package/array/array.utils.d.ts +0 -191
- package/async/async.utils.d.ts +0 -296
- package/cache/cache.utils.d.ts +0 -176
- package/config/config.d.ts +0 -57
- package/context-store/context-store.utils.d.ts +0 -212
- package/crypto/crypto.utils.d.ts +0 -183
- package/date/date.utils.d.ts +0 -190
- package/decorators/index.cjs +0 -913
- package/decorators/index.d.ts +0 -25
- package/decorators/index.mjs +0 -872
- package/dir/index.d.ts +0 -25
- package/env/env.utils.d.ts +0 -400
- package/exception/exception.utils.d.ts +0 -253
- package/fs/fs.utils.d.ts +0 -196
- package/http-status-codes/http-status-codes.d.ts +0 -289
- package/id/id.utils.d.ts +0 -59
- package/logger/logger.utils.d.ts +0 -210
- package/middleware/middleware.utils.d.ts +0 -123
- package/obj/index.cjs +0 -317
- package/obj/index.d.ts +0 -25
- package/obj/index.mjs +0 -301
- package/performance/performance.utils.d.ts +0 -159
- package/request/request.utils.d.ts +0 -109
- package/response/response.utils.d.ts +0 -186
- package/server/server.builder.d.ts +0 -531
- package/server/server.d.ts +0 -303
- package/stream/stream.utils.d.ts +0 -111
- package/string/string.utils.d.ts +0 -124
- package/type/type.utils.d.ts +0 -129
- package/types/api-response.d.ts +0 -175
- package/types/common.d.ts +0 -148
- package/types/config.d.ts +0 -88
- package/types/server.d.ts +0 -291
- package/url/url.utils.d.ts +0 -164
- package/validate/index.d.ts +0 -25
package/env/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*
|
|
2
2
|
* The MIT License
|
|
3
3
|
*
|
|
4
|
-
* Copyright (c)
|
|
4
|
+
* Copyright (c) 2026 Catbee Technologies. https://catbee.in/license
|
|
5
5
|
*
|
|
6
6
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
7
|
* of this software and associated documentation files (the "Software"), to deal
|
|
@@ -22,4 +22,393 @@
|
|
|
22
22
|
* SOFTWARE.
|
|
23
23
|
*/
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
/**
|
|
26
|
+
* Enum representing valid application environments.
|
|
27
|
+
*/
|
|
28
|
+
declare enum Environment {
|
|
29
|
+
PRODUCTION = "production",
|
|
30
|
+
DEVELOPMENT = "development",
|
|
31
|
+
STAGING = "staging",
|
|
32
|
+
TESTING = "testing"
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Options for validating URL environment variables
|
|
36
|
+
*/
|
|
37
|
+
interface UrlOptions {
|
|
38
|
+
/** List of allowed protocols (e.g., ['http', 'https']) */
|
|
39
|
+
protocols?: string[];
|
|
40
|
+
/** Whether a top-level domain is required (default: true) */
|
|
41
|
+
requireTld?: boolean;
|
|
42
|
+
/** Whether to allow IP addresses (default: true) */
|
|
43
|
+
allowIp?: boolean;
|
|
44
|
+
/** Whether to allow localhost (default: true) */
|
|
45
|
+
allowLocalhost?: boolean;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Options for validating path environment variables
|
|
49
|
+
*/
|
|
50
|
+
interface PathOptions {
|
|
51
|
+
/** Whether the path must exist on the filesystem (default: false) */
|
|
52
|
+
mustExist?: boolean;
|
|
53
|
+
/** Whether to convert relative paths to absolute (default: true) */
|
|
54
|
+
makeAbsolute?: boolean;
|
|
55
|
+
/** List of allowed file extensions */
|
|
56
|
+
allowedExtensions?: string[];
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Utility class for accessing and managing environment variables.
|
|
60
|
+
* Provides typed getters with fallback defaults and validation.
|
|
61
|
+
*/
|
|
62
|
+
declare class Env {
|
|
63
|
+
private static readonly cache;
|
|
64
|
+
/**
|
|
65
|
+
* Checks if the current NODE_ENV is 'development'.
|
|
66
|
+
*
|
|
67
|
+
* @returns {boolean} `true` if NODE_ENV is 'development', else `false`.
|
|
68
|
+
*/
|
|
69
|
+
static isDev(): boolean;
|
|
70
|
+
/**
|
|
71
|
+
* Checks if the current NODE_ENV is 'production'.
|
|
72
|
+
*
|
|
73
|
+
* @returns {boolean} `true` if NODE_ENV is 'production', else `false`.
|
|
74
|
+
*/
|
|
75
|
+
static isProd(): boolean;
|
|
76
|
+
/**
|
|
77
|
+
* Checks if the current NODE_ENV is 'testing'.
|
|
78
|
+
*
|
|
79
|
+
* @returns {boolean} `true` if NODE_ENV is 'testing', else `false`.
|
|
80
|
+
*/
|
|
81
|
+
static isTest(): boolean;
|
|
82
|
+
/**
|
|
83
|
+
* Checks if the current NODE_ENV is 'staging'.
|
|
84
|
+
*
|
|
85
|
+
* @returns {boolean} `true` if NODE_ENV is 'staging', else `false`.
|
|
86
|
+
*/
|
|
87
|
+
static isStaging(): boolean;
|
|
88
|
+
/**
|
|
89
|
+
* Sets an environment variable (only affects runtime memory).
|
|
90
|
+
*
|
|
91
|
+
* @param {string} key - The environment variable key.
|
|
92
|
+
* @param {string} value - The value to set.
|
|
93
|
+
*/
|
|
94
|
+
static set(key: string, value: string): void;
|
|
95
|
+
/**
|
|
96
|
+
* Returns all environment variables as an object.
|
|
97
|
+
*
|
|
98
|
+
* @returns {object} The current `process.env` object.
|
|
99
|
+
*/
|
|
100
|
+
static getAll(): object;
|
|
101
|
+
/**
|
|
102
|
+
* Retrieves a string environment variable with a fallback default.
|
|
103
|
+
* Supports variable expansion with ${VAR_NAME} syntax.
|
|
104
|
+
*
|
|
105
|
+
* @param {string} key - The environment variable key.
|
|
106
|
+
* @param {string} [defaultValue] - Value to return if the key is missing.
|
|
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"
|
|
113
|
+
*/
|
|
114
|
+
static get(key: string, defaultValue: string): string;
|
|
115
|
+
/**
|
|
116
|
+
* Retrieves a string environment variable and throws if it's missing.
|
|
117
|
+
*
|
|
118
|
+
* @param {string} key - The environment variable key.
|
|
119
|
+
* @returns {string} The environment variable's value.
|
|
120
|
+
* @throws {Error} If the variable is not defined.
|
|
121
|
+
*/
|
|
122
|
+
static getRequired(key: string): string;
|
|
123
|
+
/**
|
|
124
|
+
* Retrieves a value using a default generating function if the key doesn't exist.
|
|
125
|
+
* Useful for expensive default calculations.
|
|
126
|
+
*
|
|
127
|
+
* @param {string} key - The environment variable key.
|
|
128
|
+
* @param {() => string} defaultFn - Function that generates default value.
|
|
129
|
+
* @returns {string} The environment value or generated default.
|
|
130
|
+
*
|
|
131
|
+
* @example
|
|
132
|
+
* const hostname = Env.getWithDefault('HOSTNAME', () => {
|
|
133
|
+
* // Only called if HOSTNAME is not set
|
|
134
|
+
* return require('os').hostname();
|
|
135
|
+
* });
|
|
136
|
+
*/
|
|
137
|
+
static getWithDefault(key: string, defaultFn: () => string): string;
|
|
138
|
+
/**
|
|
139
|
+
* Retrieves an environment variable as a number, or returns a default.
|
|
140
|
+
*
|
|
141
|
+
* @param {string} key - The environment variable key.
|
|
142
|
+
* @param {number} defaultValue - Fallback number if key is not present.
|
|
143
|
+
* @returns {number} Parsed numeric value or default.
|
|
144
|
+
* @throws {Error} If the value is not a valid number.
|
|
145
|
+
*/
|
|
146
|
+
static getNumber(key: string, defaultValue: number): number;
|
|
147
|
+
/**
|
|
148
|
+
* Retrieves a required environment variable as a number.
|
|
149
|
+
*
|
|
150
|
+
* @param {string} key - The environment variable key.
|
|
151
|
+
* @returns {number} Parsed number.
|
|
152
|
+
* @throws {Error} If the value is missing or not a number.
|
|
153
|
+
*/
|
|
154
|
+
static getNumberRequired(key: string): number;
|
|
155
|
+
/**
|
|
156
|
+
* Retrieves an integer environment variable and validates it.
|
|
157
|
+
*
|
|
158
|
+
* @param {string} key - The environment variable key.
|
|
159
|
+
* @param {number} defaultValue - Fallback number if key is not present.
|
|
160
|
+
* @param {object} [options] - Validation options.
|
|
161
|
+
* @param {number} [options.min] - Minimum allowed value.
|
|
162
|
+
* @param {number} [options.max] - Maximum allowed value.
|
|
163
|
+
* @returns {number} The parsed integer.
|
|
164
|
+
*
|
|
165
|
+
* @example
|
|
166
|
+
* // Require PORT to be between 1000 and 9999
|
|
167
|
+
* const port = Env.getInteger('PORT', 3000, { min: 1000, max: 9999 });
|
|
168
|
+
*/
|
|
169
|
+
static getInteger(key: string, defaultValue: number, options?: {
|
|
170
|
+
min?: number;
|
|
171
|
+
max?: number;
|
|
172
|
+
}): number;
|
|
173
|
+
/**
|
|
174
|
+
* Retrieves an environment variable as a boolean.
|
|
175
|
+
* Accepts `true`, `1`, `yes`, `on` as true; `false`, `0`, `no`, `off` as false.
|
|
176
|
+
*
|
|
177
|
+
* @param {string} key - The environment variable key.
|
|
178
|
+
* @param {boolean} [defaultValue=false] - Optional fallback value if key is missing.
|
|
179
|
+
* @returns {boolean} Parsed boolean.
|
|
180
|
+
* @throws {Error} If the value is not a recognized boolean string.
|
|
181
|
+
*
|
|
182
|
+
* @example
|
|
183
|
+
* // If DEBUG=yes
|
|
184
|
+
* const isDebug = Env.getBoolean('DEBUG', false); // true
|
|
185
|
+
*/
|
|
186
|
+
static getBoolean(key: string, defaultValue?: boolean): boolean;
|
|
187
|
+
/**
|
|
188
|
+
* Retrieves a required environment variable as a boolean.
|
|
189
|
+
*
|
|
190
|
+
* @param {string} key - The environment variable key.
|
|
191
|
+
* @returns {boolean} Parsed boolean value.
|
|
192
|
+
* @throws {Error} If missing or invalid.
|
|
193
|
+
*/
|
|
194
|
+
static getBooleanRequired(key: string): boolean;
|
|
195
|
+
/**
|
|
196
|
+
* Parses a stringified JSON object from an environment variable.
|
|
197
|
+
*
|
|
198
|
+
* @typeParam T - The type to parse as (defaults to `object`).
|
|
199
|
+
* @param {string} key - The environment variable key.
|
|
200
|
+
* @param {T} defaultValue - Value to return if key is missing.
|
|
201
|
+
* @returns {T} Parsed object or default.
|
|
202
|
+
* @throws {Error} If the value is not valid JSON.
|
|
203
|
+
*
|
|
204
|
+
* @example
|
|
205
|
+
* // If CONFIG='{"debug":true,"api":{"url":"https://api.example.com"}}'
|
|
206
|
+
* const config = Env.getJSON('CONFIG', { debug: false });
|
|
207
|
+
* // { debug: true, api: { url: "https://api.example.com" }}
|
|
208
|
+
*/
|
|
209
|
+
static getJSON<T extends object = object>(key: string, defaultValue: T): T;
|
|
210
|
+
/**
|
|
211
|
+
* Parses a comma-separated string as an array.
|
|
212
|
+
*
|
|
213
|
+
* @typeParam T - The item type (optional, defaults to string).
|
|
214
|
+
* @param {string} key - The environment variable key.
|
|
215
|
+
* @param {T[]} [defaultValue=[]] - Array to return if value is empty or missing.
|
|
216
|
+
* @param {string} [splitter=','] - Delimiter to split on.
|
|
217
|
+
* @param {(item: string) => T} [transform] - Optional function to transform each item.
|
|
218
|
+
* @returns {T[]} An array of items.
|
|
219
|
+
*
|
|
220
|
+
* @example
|
|
221
|
+
* // If ALLOWED_IPS=127.0.0.1,192.168.1.1,10.0.0.1
|
|
222
|
+
* const ips = Env.getArray('ALLOWED_IPS');
|
|
223
|
+
* // ["127.0.0.1", "192.168.1.1", "10.0.0.1"]
|
|
224
|
+
*
|
|
225
|
+
* // With transformation function
|
|
226
|
+
* const ports = Env.getArray('PORTS', [], ',', (p) => parseInt(p, 10));
|
|
227
|
+
*/
|
|
228
|
+
static getArray<T = string>(key: string, defaultValue?: T[], splitter?: string, transform?: (item: string) => T): T[];
|
|
229
|
+
/**
|
|
230
|
+
* Parses a comma-separated list of numbers.
|
|
231
|
+
*
|
|
232
|
+
* @param {string} key - The environment variable key.
|
|
233
|
+
* @param {number[]} [defaultValue=[]] - Default value if not present.
|
|
234
|
+
* @param {string} [splitter=','] - Delimiter to split on.
|
|
235
|
+
* @returns {number[]} Array of parsed numbers.
|
|
236
|
+
*
|
|
237
|
+
* @example
|
|
238
|
+
* // If ALLOWED_PORTS=80,443,3000,8080
|
|
239
|
+
* const ports = Env.getNumberArray('ALLOWED_PORTS');
|
|
240
|
+
* // [80, 443, 3000, 8080]
|
|
241
|
+
*/
|
|
242
|
+
static getNumberArray(key: string, defaultValue?: number[], splitter?: string): number[];
|
|
243
|
+
/**
|
|
244
|
+
* Retrieves an enum-like environment variable value, validating against allowed values.
|
|
245
|
+
*
|
|
246
|
+
* @typeParam T - The allowed value type (string literal types).
|
|
247
|
+
* @param {string} key - The environment variable key.
|
|
248
|
+
* @param {T} [defaultValue] - Optional fallback value.
|
|
249
|
+
* @param {T[]} allowedValues - Array of accepted string values.
|
|
250
|
+
* @returns {T} The validated environment value.
|
|
251
|
+
* @throws {Error} If missing or invalid.
|
|
252
|
+
*
|
|
253
|
+
* @example
|
|
254
|
+
* // If LOG_LEVEL=debug
|
|
255
|
+
* const level = Env.getEnum('LOG_LEVEL', 'info', ['debug', 'info', 'warn', 'error'] as const);
|
|
256
|
+
* // 'debug' (typed as 'debug' | 'info' | 'warn' | 'error')
|
|
257
|
+
*/
|
|
258
|
+
static getEnum<T extends string>(key: string, defaultValue: T, allowedValues: readonly T[]): T;
|
|
259
|
+
/**
|
|
260
|
+
* Retrieves an enum-like numeric environment variable.
|
|
261
|
+
*
|
|
262
|
+
* @param {string} key - The environment variable key.
|
|
263
|
+
* @param {number} defaultValue - Default value if not present.
|
|
264
|
+
* @param {number[]} allowedValues - Array of accepted values.
|
|
265
|
+
* @returns {number} The validated value.
|
|
266
|
+
*
|
|
267
|
+
* @example
|
|
268
|
+
* // If NODE_VERSION=16
|
|
269
|
+
* const version = Env.getNumberEnum('NODE_VERSION', 16, [14, 16, 18]);
|
|
270
|
+
*/
|
|
271
|
+
static getNumberEnum(key: string, defaultValue: number, allowedValues: number[]): number;
|
|
272
|
+
/**
|
|
273
|
+
* Retrieves a URL environment variable and validates it.
|
|
274
|
+
*
|
|
275
|
+
* @param {string} key - The environment variable key.
|
|
276
|
+
* @param {string} [defaultValue] - Optional fallback value.
|
|
277
|
+
* @param {UrlOptions} [options] - Validation options.
|
|
278
|
+
* @returns {string} The validated URL.
|
|
279
|
+
* @throws {Error} If URL is invalid.
|
|
280
|
+
*
|
|
281
|
+
* @example
|
|
282
|
+
* // Validate API URL requires HTTPS
|
|
283
|
+
* const apiUrl = Env.getUrl('API_URL', 'https://api.example.com', {
|
|
284
|
+
* protocols: ['https'],
|
|
285
|
+
* requireTld: true,
|
|
286
|
+
* allowIp: false
|
|
287
|
+
* });
|
|
288
|
+
*/
|
|
289
|
+
static getUrl(key: string, defaultValue: string, options?: UrlOptions): string;
|
|
290
|
+
private static parseUrl;
|
|
291
|
+
private static validateProtocol;
|
|
292
|
+
private static isIp;
|
|
293
|
+
private static validateHostname;
|
|
294
|
+
/**
|
|
295
|
+
* Retrieves an email environment variable and validates it.
|
|
296
|
+
*
|
|
297
|
+
* @param {string} key - The environment variable key.
|
|
298
|
+
* @param {string} [defaultValue] - Optional fallback value.
|
|
299
|
+
* @returns {string} The validated email address.
|
|
300
|
+
* @throws {Error} If email is invalid.
|
|
301
|
+
*
|
|
302
|
+
* @example
|
|
303
|
+
* const supportEmail = Env.getEmail('SUPPORT_EMAIL', 'support@example.com');
|
|
304
|
+
*/
|
|
305
|
+
static getEmail(key: string, defaultValue: string): string;
|
|
306
|
+
/**
|
|
307
|
+
* Retrieves a path environment variable and validates it exists.
|
|
308
|
+
*
|
|
309
|
+
* @param {string} key - The environment variable key.
|
|
310
|
+
* @param {string} [defaultValue] - Optional fallback value.
|
|
311
|
+
* @param {PathOptions} [options] - Validation options.
|
|
312
|
+
* @returns {string} The validated path.
|
|
313
|
+
* @throws {Error} If path is invalid.
|
|
314
|
+
*
|
|
315
|
+
* @example
|
|
316
|
+
* // Require that the path exists and is a .json file
|
|
317
|
+
* const configPath = Env.getPath('CONFIG_PATH', './config.json', {
|
|
318
|
+
* mustExist: true,
|
|
319
|
+
* allowedExtensions: ['.json', '.yaml']
|
|
320
|
+
* });
|
|
321
|
+
*/
|
|
322
|
+
static getPath(key: string, defaultValue: string, options?: PathOptions): string;
|
|
323
|
+
/**
|
|
324
|
+
* Retrieves a port environment variable and validates it.
|
|
325
|
+
*
|
|
326
|
+
* @param {string} key - The environment variable key.
|
|
327
|
+
* @param {number} [defaultValue] - Optional fallback value.
|
|
328
|
+
* @returns {number} The validated port number.
|
|
329
|
+
* @throws {Error} If port is invalid.
|
|
330
|
+
*
|
|
331
|
+
* @example
|
|
332
|
+
* const serverPort = Env.getPort('PORT', 3000);
|
|
333
|
+
*/
|
|
334
|
+
static getPort(key: string, defaultValue: number): number;
|
|
335
|
+
/**
|
|
336
|
+
* Retrieves an ISO date string and converts it to a Date object.
|
|
337
|
+
*
|
|
338
|
+
* @param {string} key - The environment variable key.
|
|
339
|
+
* @param {string|Date} [defaultValue] - Optional fallback value.
|
|
340
|
+
* @returns {Date} The parsed Date object.
|
|
341
|
+
*
|
|
342
|
+
* @example
|
|
343
|
+
* // If EXPIRY_DATE=2023-12-31T23:59:59Z
|
|
344
|
+
* const expiryDate = Env.getDate('EXPIRY_DATE', new Date());
|
|
345
|
+
*/
|
|
346
|
+
static getDate(key: string, defaultValue?: string | Date): Date;
|
|
347
|
+
/**
|
|
348
|
+
* Retrieves a duration string and converts it to milliseconds.
|
|
349
|
+
* Supports formats like "1d", "2h", "30m", "45s", "100ms" or combinations like "1h30m".
|
|
350
|
+
*
|
|
351
|
+
* @param {string} key - The environment variable key.
|
|
352
|
+
* @param {string|number} [defaultValue='0'] - Optional fallback value.
|
|
353
|
+
* @returns {number} The duration in milliseconds.
|
|
354
|
+
* @throws {Error} If duration format is invalid.
|
|
355
|
+
*
|
|
356
|
+
* @example
|
|
357
|
+
* // If CACHE_TTL=2h30m
|
|
358
|
+
* const cacheTtlMs = Env.getDuration('CACHE_TTL', '1h');
|
|
359
|
+
* // 9000000 (2.5 hours in milliseconds)
|
|
360
|
+
*/
|
|
361
|
+
static getDuration(key: string, defaultValue?: string | number): number;
|
|
362
|
+
/**
|
|
363
|
+
* Gets all environment variables with sensitive values masked for safe logging.
|
|
364
|
+
*
|
|
365
|
+
* @param {string[]} [sensitiveKeys=['password', 'secret', 'key', 'token', 'auth']] - Keys to mask.
|
|
366
|
+
* @returns {Record<string, string>} Environment variables with sensitive values masked.
|
|
367
|
+
*
|
|
368
|
+
* @example
|
|
369
|
+
* console.log(Env.getSafeEnv(['password', 'secret', 'key']));
|
|
370
|
+
* // { DATABASE_URL: "postgres://...", API_KEY: "******", ... }
|
|
371
|
+
*/
|
|
372
|
+
static getSafeEnv(sensitiveKeys?: string[]): Record<string, string>;
|
|
373
|
+
/**
|
|
374
|
+
* Loads environment variables from a .env file.
|
|
375
|
+
* Does not override existing variables.
|
|
376
|
+
*
|
|
377
|
+
* @param {string} [path='.env'] - Path to the .env file.
|
|
378
|
+
* @returns {Record<string, string>} Loaded environment variables.
|
|
379
|
+
*
|
|
380
|
+
* @example
|
|
381
|
+
* // Load variables from .env.development
|
|
382
|
+
* Env.loadFromFile('.env.development');
|
|
383
|
+
*/
|
|
384
|
+
static loadFromFile(path?: string): Record<string, string>;
|
|
385
|
+
private static parseEnvContent;
|
|
386
|
+
private static isCommentOrEmpty;
|
|
387
|
+
private static extractKeyValue;
|
|
388
|
+
private static isQuoted;
|
|
389
|
+
private static stripInlineComment;
|
|
390
|
+
private static parseQuotedValue;
|
|
391
|
+
private static parseUnquotedMultiline;
|
|
392
|
+
/**
|
|
393
|
+
* Checks whether the specified environment variable exists.
|
|
394
|
+
*
|
|
395
|
+
* @param {string} key - The environment variable key.
|
|
396
|
+
* @returns {boolean} `true` if the variable is defined, otherwise `false`.
|
|
397
|
+
*/
|
|
398
|
+
static has(key: string): boolean;
|
|
399
|
+
/**
|
|
400
|
+
* Deletes the given environment variable (useful in tests).
|
|
401
|
+
*
|
|
402
|
+
* @param {string} key - The environment variable key to delete.
|
|
403
|
+
* @returns {void}
|
|
404
|
+
*/
|
|
405
|
+
static delete(key: string): void;
|
|
406
|
+
/**
|
|
407
|
+
* Clears the internal cache of parsed environment values.
|
|
408
|
+
* Useful for testing or when environment variables might change.
|
|
409
|
+
*/
|
|
410
|
+
static clearCache(): void;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
export { Env, Environment };
|
|
414
|
+
export type { PathOptions, UrlOptions };
|
package/env/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*
|
|
2
2
|
* The MIT License
|
|
3
3
|
*
|
|
4
|
-
* Copyright (c)
|
|
4
|
+
* Copyright (c) 2026 Catbee Technologies. https://catbee.in/license
|
|
5
5
|
*
|
|
6
6
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
7
|
* of this software and associated documentation files (the "Software"), to deal
|
|
@@ -24,6 +24,8 @@
|
|
|
24
24
|
|
|
25
25
|
import { existsSync, readFileSync } from 'fs';
|
|
26
26
|
import { isAbsolute, resolve } from 'path';
|
|
27
|
+
import { parseDuration } from '@catbee/utils/date';
|
|
28
|
+
import { isEmail } from '@catbee/utils/validation';
|
|
27
29
|
|
|
28
30
|
var __defProp = Object.defineProperty;
|
|
29
31
|
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
|
|
@@ -81,9 +83,7 @@ var Env = class _Env {
|
|
|
81
83
|
static set(key, value) {
|
|
82
84
|
process.env[key] = value;
|
|
83
85
|
this.cache.delete(key);
|
|
84
|
-
for (const cacheKey of
|
|
85
|
-
...this.cache.keys()
|
|
86
|
-
]) {
|
|
86
|
+
for (const cacheKey of this.cache.keys()) {
|
|
87
87
|
if (cacheKey.includes(`:${key}`)) {
|
|
88
88
|
this.cache.delete(cacheKey);
|
|
89
89
|
}
|
|
@@ -112,7 +112,7 @@ var Env = class _Env {
|
|
|
112
112
|
*/
|
|
113
113
|
static get(key, defaultValue) {
|
|
114
114
|
let value = process.env[key] ?? defaultValue;
|
|
115
|
-
if (value
|
|
115
|
+
if (value?.includes("${")) {
|
|
116
116
|
value = value.replace(/\${([A-Za-z0-9_]+)}/g, (_, varName) => {
|
|
117
117
|
return process.env[varName] ?? "";
|
|
118
118
|
});
|
|
@@ -170,7 +170,7 @@ var Env = class _Env {
|
|
|
170
170
|
return defaultValue;
|
|
171
171
|
}
|
|
172
172
|
const numberValue = Number(value);
|
|
173
|
-
if (isNaN(numberValue)) {
|
|
173
|
+
if (Number.isNaN(numberValue)) {
|
|
174
174
|
throw new Error(`Environment variable '${key}' is not a valid number, got: "${value}"`);
|
|
175
175
|
}
|
|
176
176
|
this.cache.set(`number:${key}`, numberValue);
|
|
@@ -361,7 +361,7 @@ var Env = class _Env {
|
|
|
361
361
|
static getNumberArray(key, defaultValue = [], splitter = ",") {
|
|
362
362
|
return _Env.getArray(key, defaultValue, splitter, (item) => {
|
|
363
363
|
const num = Number(item);
|
|
364
|
-
if (isNaN(num)) {
|
|
364
|
+
if (Number.isNaN(num)) {
|
|
365
365
|
throw new Error(`Value "${item}" in array '${key}' is not a valid number`);
|
|
366
366
|
}
|
|
367
367
|
return num;
|
|
@@ -437,20 +437,33 @@ var Env = class _Env {
|
|
|
437
437
|
if (!value) {
|
|
438
438
|
throw new Error(`URL environment variable '${key}' is missing or empty`);
|
|
439
439
|
}
|
|
440
|
-
|
|
440
|
+
const url = this.parseUrl(value, key);
|
|
441
|
+
this.validateProtocol(url, key, options);
|
|
442
|
+
this.validateHostname(url, key, options);
|
|
443
|
+
this.cache.set(cacheKey, value);
|
|
444
|
+
return value;
|
|
445
|
+
}
|
|
446
|
+
static parseUrl(value, key) {
|
|
441
447
|
try {
|
|
442
|
-
|
|
448
|
+
return new URL(value);
|
|
443
449
|
} catch {
|
|
444
450
|
throw new Error(`Environment variable '${key}' is not a valid URL: "${value}"`);
|
|
445
451
|
}
|
|
452
|
+
}
|
|
453
|
+
static validateProtocol(url, key, options) {
|
|
446
454
|
if (options.protocols && options.protocols.length > 0) {
|
|
447
455
|
const protocol = url.protocol.replace(":", "");
|
|
448
456
|
if (!options.protocols.includes(protocol)) {
|
|
449
457
|
throw new Error(`Environment variable '${key}' must use one of the protocols: ${options.protocols.join(", ")}. Got: ${protocol}`);
|
|
450
458
|
}
|
|
451
459
|
}
|
|
460
|
+
}
|
|
461
|
+
static isIp(hostname) {
|
|
462
|
+
return /^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$/.test(hostname);
|
|
463
|
+
}
|
|
464
|
+
static validateHostname(url, key, options) {
|
|
452
465
|
const { hostname } = url;
|
|
453
|
-
const isIp =
|
|
466
|
+
const isIp = _Env.isIp(hostname);
|
|
454
467
|
const isLocalhost = hostname === "localhost";
|
|
455
468
|
if (isIp && options.allowIp === false) {
|
|
456
469
|
throw new Error(`Environment variable '${key}' cannot be an IP address: "${hostname}"`);
|
|
@@ -463,8 +476,6 @@ var Env = class _Env {
|
|
|
463
476
|
throw new Error(`Environment variable '${key}' must have a valid host with TLD: "${hostname}"`);
|
|
464
477
|
}
|
|
465
478
|
}
|
|
466
|
-
this.cache.set(cacheKey, value);
|
|
467
|
-
return value;
|
|
468
479
|
}
|
|
469
480
|
/**
|
|
470
481
|
* Retrieves an email environment variable and validates it.
|
|
@@ -488,8 +499,7 @@ var Env = class _Env {
|
|
|
488
499
|
}
|
|
489
500
|
return defaultValue;
|
|
490
501
|
}
|
|
491
|
-
|
|
492
|
-
if (!emailRegex.test(value)) {
|
|
502
|
+
if (!isEmail(value)) {
|
|
493
503
|
throw new Error(`Environment variable '${key}' is not a valid email address: "${value}"`);
|
|
494
504
|
}
|
|
495
505
|
this.cache.set(`email:${key}`, value);
|
|
@@ -577,7 +587,7 @@ var Env = class _Env {
|
|
|
577
587
|
return defaultValue instanceof Date ? defaultValue : /* @__PURE__ */ new Date();
|
|
578
588
|
}
|
|
579
589
|
const date = new Date(value);
|
|
580
|
-
if (isNaN(date.getTime())) {
|
|
590
|
+
if (Number.isNaN(date.getTime())) {
|
|
581
591
|
throw new Error(`Environment variable '${key}' is not a valid date: "${value}"`);
|
|
582
592
|
}
|
|
583
593
|
return date;
|
|
@@ -601,26 +611,9 @@ var Env = class _Env {
|
|
|
601
611
|
if (this.cache.has(cacheKey)) {
|
|
602
612
|
return this.cache.get(cacheKey);
|
|
603
613
|
}
|
|
604
|
-
const
|
|
605
|
-
if (!
|
|
606
|
-
|
|
607
|
-
const ms2 = parseInt(value, 10);
|
|
608
|
-
this.cache.set(cacheKey, ms2);
|
|
609
|
-
return ms2;
|
|
610
|
-
}
|
|
611
|
-
const durationRegex = /^(?:(\d+)y)?(?:(\d+)w)?(?:(\d+)d)?(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?(?:(\d+)ms)?$/;
|
|
612
|
-
const matches = value.match(durationRegex);
|
|
613
|
-
if (!matches || matches[0] === "") {
|
|
614
|
-
throw new Error(`Environment variable '${key}' has invalid duration format: "${value}". Use formats like 1y, 2w, 3d, 4h, 5m, 6s, or 7ms.`);
|
|
615
|
-
}
|
|
616
|
-
let ms = 0;
|
|
617
|
-
if (matches[1]) ms += parseInt(matches[1], 10) * 31536e6;
|
|
618
|
-
if (matches[2]) ms += parseInt(matches[2], 10) * 6048e5;
|
|
619
|
-
if (matches[3]) ms += parseInt(matches[3], 10) * 864e5;
|
|
620
|
-
if (matches[4]) ms += parseInt(matches[4], 10) * 36e5;
|
|
621
|
-
if (matches[5]) ms += parseInt(matches[5], 10) * 6e4;
|
|
622
|
-
if (matches[6]) ms += parseInt(matches[6], 10) * 1e3;
|
|
623
|
-
if (matches[7]) ms += parseInt(matches[7], 10);
|
|
614
|
+
const raw = _Env.get(key, String(defaultValue));
|
|
615
|
+
if (!raw) return 0;
|
|
616
|
+
const ms = parseDuration(raw);
|
|
624
617
|
this.cache.set(cacheKey, ms);
|
|
625
618
|
return ms;
|
|
626
619
|
}
|
|
@@ -665,63 +658,102 @@ var Env = class _Env {
|
|
|
665
658
|
throw new Error(`Environment file not found: "${path}"`);
|
|
666
659
|
}
|
|
667
660
|
const content = readFileSync(path, "utf8");
|
|
661
|
+
const variables = this.parseEnvContent(content);
|
|
662
|
+
for (const [k, v] of Object.entries(variables)) {
|
|
663
|
+
if (!process.env[k]) {
|
|
664
|
+
process.env[k] = v;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
return variables;
|
|
668
|
+
}
|
|
669
|
+
static parseEnvContent(content) {
|
|
668
670
|
const variables = {};
|
|
669
671
|
const lines = content.split(/\r?\n/);
|
|
670
672
|
let i = 0;
|
|
671
673
|
while (i < lines.length) {
|
|
672
674
|
let line = lines[i].trim();
|
|
673
|
-
if (
|
|
675
|
+
if (this.isCommentOrEmpty(line)) {
|
|
674
676
|
i++;
|
|
675
677
|
continue;
|
|
676
678
|
}
|
|
677
|
-
const match =
|
|
679
|
+
const match = this.extractKeyValue(line);
|
|
678
680
|
if (!match) {
|
|
679
681
|
i++;
|
|
680
682
|
continue;
|
|
681
683
|
}
|
|
682
684
|
const key = match[1].trim();
|
|
683
685
|
let value = match[2].trim();
|
|
684
|
-
if (
|
|
685
|
-
|
|
686
|
-
if (hashIndex !== -1) {
|
|
687
|
-
value = value.slice(0, hashIndex).trim();
|
|
688
|
-
}
|
|
686
|
+
if (!this.isQuoted(value)) {
|
|
687
|
+
value = this.stripInlineComment(value);
|
|
689
688
|
}
|
|
690
|
-
if (
|
|
691
|
-
const
|
|
692
|
-
|
|
693
|
-
|
|
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
|
-
} else {
|
|
701
|
-
multilineValue += "\n" + nextLine;
|
|
702
|
-
}
|
|
703
|
-
i++;
|
|
704
|
-
}
|
|
705
|
-
value = multilineValue;
|
|
706
|
-
} else {
|
|
707
|
-
value = value.slice(1, -1);
|
|
708
|
-
}
|
|
689
|
+
if (this.isQuoted(value) && value.length > 1) {
|
|
690
|
+
const result = this.parseQuotedValue(lines, i, value);
|
|
691
|
+
value = result.value;
|
|
692
|
+
i = result.nextIndex;
|
|
709
693
|
} else {
|
|
710
|
-
i
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
i++;
|
|
714
|
-
}
|
|
715
|
-
i--;
|
|
694
|
+
const result = this.parseUnquotedMultiline(lines, i, value);
|
|
695
|
+
value = result.value;
|
|
696
|
+
i = result.nextIndex;
|
|
716
697
|
}
|
|
717
698
|
if (!process.env[key]) {
|
|
718
|
-
process.env[key] = value;
|
|
719
699
|
variables[key] = value;
|
|
720
700
|
}
|
|
721
701
|
i++;
|
|
722
702
|
}
|
|
723
703
|
return variables;
|
|
724
704
|
}
|
|
705
|
+
static isCommentOrEmpty(line) {
|
|
706
|
+
return !line || line.startsWith("#");
|
|
707
|
+
}
|
|
708
|
+
static extractKeyValue(line) {
|
|
709
|
+
return line.match(/^([^=]+)=(.*)$/);
|
|
710
|
+
}
|
|
711
|
+
static isQuoted(value) {
|
|
712
|
+
return /^['"]/.test(value);
|
|
713
|
+
}
|
|
714
|
+
static stripInlineComment(value) {
|
|
715
|
+
const hashIndex = value.indexOf(" #");
|
|
716
|
+
if (hashIndex !== -1) {
|
|
717
|
+
return value.slice(0, hashIndex).trim();
|
|
718
|
+
}
|
|
719
|
+
return value;
|
|
720
|
+
}
|
|
721
|
+
static parseQuotedValue(lines, currentIndex, value) {
|
|
722
|
+
const quote = value[0];
|
|
723
|
+
if (!value.endsWith(quote) || value.length === 1) {
|
|
724
|
+
let multilineValue = value.slice(1);
|
|
725
|
+
let i = currentIndex + 1;
|
|
726
|
+
while (i < lines.length) {
|
|
727
|
+
const nextLine = lines[i];
|
|
728
|
+
if (nextLine.endsWith(quote)) {
|
|
729
|
+
multilineValue += "\n" + nextLine.slice(0, -1);
|
|
730
|
+
break;
|
|
731
|
+
} else {
|
|
732
|
+
multilineValue += "\n" + nextLine;
|
|
733
|
+
}
|
|
734
|
+
i++;
|
|
735
|
+
}
|
|
736
|
+
return {
|
|
737
|
+
value: multilineValue,
|
|
738
|
+
nextIndex: i
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
return {
|
|
742
|
+
value: value.slice(1, -1),
|
|
743
|
+
nextIndex: currentIndex
|
|
744
|
+
};
|
|
745
|
+
}
|
|
746
|
+
static parseUnquotedMultiline(lines, currentIndex, value) {
|
|
747
|
+
let i = currentIndex + 1;
|
|
748
|
+
while (i < lines.length && !lines[i].includes("=") && lines[i].trim() !== "") {
|
|
749
|
+
value += "\n" + lines[i];
|
|
750
|
+
i++;
|
|
751
|
+
}
|
|
752
|
+
return {
|
|
753
|
+
value,
|
|
754
|
+
nextIndex: i - 1
|
|
755
|
+
};
|
|
756
|
+
}
|
|
725
757
|
/**
|
|
726
758
|
* Checks whether the specified environment variable exists.
|
|
727
759
|
*
|
package/exception/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*
|
|
2
2
|
* The MIT License
|
|
3
3
|
*
|
|
4
|
-
* Copyright (c)
|
|
4
|
+
* Copyright (c) 2026 Catbee Technologies. https://catbee.in/license
|
|
5
5
|
*
|
|
6
6
|
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
7
|
* of this software and associated documentation files (the "Software"), to deal
|