envapt 4.1.1 → 5.0.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.
package/dist/index.cjs CHANGED
@@ -1,922 +1,2 @@
1
- 'use strict';
2
-
3
- var process = require('process');
4
- var dotenv = require('dotenv');
5
- var fs = require('fs');
6
-
7
- function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
-
9
- var process__default = /*#__PURE__*/_interopDefault(process);
10
- var fs__default = /*#__PURE__*/_interopDefault(fs);
11
-
12
- var __defProp = Object.defineProperty;
13
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
14
-
15
- // src/Error.ts
16
- var EnvaptErrorCodes = /* @__PURE__ */ (function(EnvaptErrorCodes2) {
17
- EnvaptErrorCodes2[EnvaptErrorCodes2["InvalidFallback"] = 101] = "InvalidFallback";
18
- EnvaptErrorCodes2[EnvaptErrorCodes2["InvalidFallbackType"] = 102] = "InvalidFallbackType";
19
- EnvaptErrorCodes2[EnvaptErrorCodes2["ArrayFallbackElementTypeMismatch"] = 103] = "ArrayFallbackElementTypeMismatch";
20
- EnvaptErrorCodes2[EnvaptErrorCodes2["FallbackConverterTypeMismatch"] = 104] = "FallbackConverterTypeMismatch";
21
- EnvaptErrorCodes2[EnvaptErrorCodes2["InvalidArrayConverterType"] = 201] = "InvalidArrayConverterType";
22
- EnvaptErrorCodes2[EnvaptErrorCodes2["InvalidBuiltInConverter"] = 202] = "InvalidBuiltInConverter";
23
- EnvaptErrorCodes2[EnvaptErrorCodes2["InvalidCustomConverter"] = 203] = "InvalidCustomConverter";
24
- EnvaptErrorCodes2[EnvaptErrorCodes2["InvalidConverterType"] = 204] = "InvalidConverterType";
25
- EnvaptErrorCodes2[EnvaptErrorCodes2["PrimitiveCoercionFailed"] = 205] = "PrimitiveCoercionFailed";
26
- EnvaptErrorCodes2[EnvaptErrorCodes2["MissingDelimiter"] = 301] = "MissingDelimiter";
27
- EnvaptErrorCodes2[EnvaptErrorCodes2["InvalidUserDefinedConfig"] = 302] = "InvalidUserDefinedConfig";
28
- EnvaptErrorCodes2[EnvaptErrorCodes2["EnvFilesNotFound"] = 303] = "EnvFilesNotFound";
29
- EnvaptErrorCodes2[EnvaptErrorCodes2["InvalidKeyInput"] = 304] = "InvalidKeyInput";
30
- return EnvaptErrorCodes2;
31
- })({});
32
- var EnvaptError = class extends Error {
33
- static {
34
- __name(this, "EnvaptError");
35
- }
36
- code;
37
- constructor(code, message) {
38
- super(message);
39
- this.name = `EnvaptError [${code}]`;
40
- this.code = code;
41
- }
42
- };
43
-
44
- // src/ListOfBuiltInConverters.ts
45
- var ListOfBuiltInConverters = [
46
- "string",
47
- "number",
48
- "boolean",
49
- "bigint",
50
- "symbol",
51
- "integer",
52
- "float",
53
- "json",
54
- "array",
55
- "url",
56
- "regexp",
57
- "date",
58
- "time"
59
- ];
60
- var BuiltInConverterTypeCheckers = {
61
- string: /* @__PURE__ */ __name((value) => typeof value === "string", "string"),
62
- number: /* @__PURE__ */ __name((value) => typeof value === "number", "number"),
63
- boolean: /* @__PURE__ */ __name((value) => typeof value === "boolean", "boolean"),
64
- bigint: /* @__PURE__ */ __name((value) => typeof value === "bigint", "bigint"),
65
- symbol: /* @__PURE__ */ __name((value) => typeof value === "symbol", "symbol"),
66
- integer: /* @__PURE__ */ __name((value) => typeof value === "number" && Number.isInteger(value), "integer"),
67
- float: /* @__PURE__ */ __name((value) => typeof value === "number", "float"),
68
- json: /* @__PURE__ */ __name((value) => {
69
- try {
70
- JSON.parse(JSON.stringify(value));
71
- return true;
72
- } catch {
73
- return false;
74
- }
75
- }, "json"),
76
- array: /* @__PURE__ */ __name((value) => Array.isArray(value), "array"),
77
- url: /* @__PURE__ */ __name((value) => value instanceof URL, "url"),
78
- regexp: /* @__PURE__ */ __name((value) => value instanceof RegExp, "regexp"),
79
- date: /* @__PURE__ */ __name((value) => value instanceof Date, "date"),
80
- time: /* @__PURE__ */ __name((value) => typeof value === "number", "time")
81
- };
82
-
83
- // src/Validators.ts
84
- var Validator = class {
85
- static {
86
- __name(this, "Validator");
87
- }
88
- /**
89
- * Check if a value is a built-in converter type
90
- */
91
- static isBuiltInConverter(value) {
92
- if (typeof value === "string") return ListOfBuiltInConverters.includes(value);
93
- return false;
94
- }
95
- /**
96
- * Check if a value is an ArrayConverter configuration object
97
- */
98
- static isArrayConverter(value) {
99
- return typeof value === "object" && value !== null && "delimiter" in value && typeof value.delimiter === "string";
100
- }
101
- /**
102
- * Check if a value is a valid ArrayConverter type
103
- */
104
- static isValidArrayConverterType(value) {
105
- if (typeof value !== "string") return false;
106
- const invalidTypes = [
107
- "array",
108
- "json",
109
- "regexp"
110
- ];
111
- if (invalidTypes.includes(value)) return false;
112
- const validTypes = ListOfBuiltInConverters.filter((type) => !invalidTypes.includes(type));
113
- return validTypes.includes(value);
114
- }
115
- static customConvertor(converter) {
116
- if (typeof converter !== "function") {
117
- throw new EnvaptError(EnvaptErrorCodes.InvalidCustomConverter, `Custom converter must be a function, got ${typeof converter}.`);
118
- }
119
- }
120
- /**
121
- * Validate ArrayConverter configuration with runtime checks
122
- */
123
- static arrayConverter(value) {
124
- if (!this.isArrayConverter(value)) {
125
- throw new EnvaptError(EnvaptErrorCodes.MissingDelimiter, "Must have delimiter property");
126
- }
127
- if (value.type !== void 0 && !this.isValidArrayConverterType(value.type)) {
128
- throw new EnvaptError(EnvaptErrorCodes.InvalidArrayConverterType, `"${value.type}" is not a valid converter type`);
129
- }
130
- }
131
- /**
132
- * Validate that a string is a valid built-in converter type
133
- */
134
- static builtInConverter(value) {
135
- if (typeof value !== "string") {
136
- throw new EnvaptError(EnvaptErrorCodes.InvalidConverterType, `Expected string, got ${typeof value}`);
137
- }
138
- if (!ListOfBuiltInConverters.includes(value)) {
139
- throw new EnvaptError(EnvaptErrorCodes.InvalidBuiltInConverter, `"${value}" is not a valid converter type. Valid types are: ${ListOfBuiltInConverters.join(",")}`);
140
- }
141
- }
142
- /**
143
- * Validate that fallback type matches the converter's return type for built-in converters
144
- */
145
- static validateBuiltInConverterFallback(converter, fallback) {
146
- const typeChecker = BuiltInConverterTypeCheckers[converter];
147
- if (!typeChecker(fallback)) {
148
- throw new EnvaptError(EnvaptErrorCodes.FallbackConverterTypeMismatch, `Fallback type does not match converter "${converter}". Expected ${converter} compatible type.`);
149
- }
150
- }
151
- /**
152
- * Validate that all elements in an array fallback have consistent types
153
- */
154
- static validateArrayFallbackElementTypes(fallback) {
155
- if (fallback.length === 0) return;
156
- const firstElementType = typeof fallback[0];
157
- const hasInconsistentTypes = fallback.some((element, index) => {
158
- if (index === 0) return false;
159
- return typeof element !== firstElementType;
160
- });
161
- if (hasInconsistentTypes) {
162
- throw new EnvaptError(EnvaptErrorCodes.ArrayFallbackElementTypeMismatch, `All elements in array fallback must have the same type. Found mixed types.`);
163
- }
164
- }
165
- /**
166
- * Validate that array converter type matches fallback element types
167
- */
168
- static validateArrayConverterElementTypeMatch(converterType, fallback) {
169
- if (fallback.length === 0) return;
170
- const firstElement = fallback[0];
171
- const typeChecker = BuiltInConverterTypeCheckers[converterType];
172
- if (!typeChecker(firstElement)) {
173
- throw new EnvaptError(EnvaptErrorCodes.ArrayFallbackElementTypeMismatch, `Array converter type "${converterType}" does not match fallback element type. Expected ${converterType} compatible elements.`);
174
- }
175
- }
176
- /**
177
- * Check if a value is a primitive constructor
178
- */
179
- static isPrimitiveConstructor(value) {
180
- return value === String || value === Number || value === Boolean || value === BigInt || value === Symbol;
181
- }
182
- /**
183
- * Safely coerce a fallback value using a primitive constructor
184
- */
185
- static coercePrimitiveFallback(converter, fallback) {
186
- if (this.isCorrectPrimitiveType(converter, fallback)) return fallback;
187
- return this.performPrimitiveCoercion(converter, fallback);
188
- }
189
- /**
190
- * Check if fallback is already the correct primitive type
191
- */
192
- static isCorrectPrimitiveType(converter, fallback) {
193
- if (converter === String && typeof fallback === "string") return true;
194
- if (converter === Number && typeof fallback === "number") return true;
195
- if (converter === Boolean && typeof fallback === "boolean") return true;
196
- if (converter === BigInt && typeof fallback === "bigint") return true;
197
- if (converter === Symbol && typeof fallback === "symbol") return true;
198
- return false;
199
- }
200
- /**
201
- * Perform the actual primitive coercion
202
- */
203
- static performPrimitiveCoercion(converter, fallback) {
204
- try {
205
- if (converter === String) return String(fallback);
206
- if (converter === Number) return Number(fallback);
207
- if (converter === Boolean) return Boolean(fallback);
208
- if (converter === BigInt) return BigInt(fallback);
209
- if (converter === Symbol) return Symbol.for(String(fallback));
210
- } catch (error) {
211
- throw new EnvaptError(EnvaptErrorCodes.PrimitiveCoercionFailed, `Failed to coerce fallback value using ${converter.name}: ${error.message}`);
212
- }
213
- throw new EnvaptError(EnvaptErrorCodes.PrimitiveCoercionFailed, `Unknown primitive converter: ${converter.name}`);
214
- }
215
- /**
216
- * Make sure the user hasn't provided prohibited options in their dotenv config
217
- */
218
- static validateDotenvConfig(config2) {
219
- if ("path" in config2 || "processEnv" in config2) {
220
- throw new EnvaptError(EnvaptErrorCodes.InvalidUserDefinedConfig, 'Custom dotenvConfig should not include "path" or "processEnv" options. Those are managed by Envapter.');
221
- }
222
- const validKeys = /* @__PURE__ */ new Set([
223
- "encoding",
224
- "quiet",
225
- "debug",
226
- "override",
227
- "DOTENV_KEY"
228
- ]);
229
- const invalidKeys = Object.keys(config2).filter((key) => !validKeys.has(key));
230
- if (invalidKeys.length > 0) {
231
- throw new EnvaptError(EnvaptErrorCodes.InvalidUserDefinedConfig, `Invalid dotenvConfig options: ${invalidKeys.join(", ")}. Allowed options: ${Array.from(validKeys).join(", ")}`);
232
- }
233
- return true;
234
- }
235
- /**
236
- * Check if each provided path resolves to an env file by trying to access it
237
- */
238
- static validateEnvFilesExist(paths) {
239
- const missing = paths.filter((p) => {
240
- try {
241
- fs__default.default.accessSync(p, fs__default.default.constants.F_OK);
242
- return false;
243
- } catch {
244
- return true;
245
- }
246
- });
247
- if (missing.length > 0) {
248
- throw new EnvaptError(EnvaptErrorCodes.EnvFilesNotFound, `Environment file not found at path: ${missing.join(", ")}`);
249
- }
250
- }
251
- };
252
-
253
- // src/core/EnvapterBase.ts
254
- var EnvaptCache = /* @__PURE__ */ new Map();
255
- var EnvapterBase = class _EnvapterBase {
256
- static {
257
- __name(this, "EnvapterBase");
258
- }
259
- static _envPaths = [
260
- ".env"
261
- ];
262
- static _userDefinedDotenvConfig = {
263
- quiet: true
264
- };
265
- /**
266
- * Set custom .env file paths. Accepts either a single path or array of paths.
267
- * Setting new paths clears the cache and reloads environment variables.
268
- */
269
- static set envPaths(paths) {
270
- const newPaths = Array.isArray(paths) ? paths : [
271
- paths
272
- ];
273
- Validator.validateEnvFilesExist(newPaths);
274
- this._envPaths = newPaths;
275
- this.refreshCache();
276
- }
277
- /**
278
- * Get currently configured .env file paths
279
- */
280
- static get envPaths() {
281
- return this._envPaths;
282
- }
283
- /**
284
- * Set custom dotenv configuration options.
285
- */
286
- static set dotenvConfig(config2) {
287
- Validator.validateDotenvConfig(config2);
288
- this._userDefinedDotenvConfig = config2;
289
- this.refreshCache();
290
- }
291
- /**
292
- * Get current dotenv configuration options
293
- */
294
- static get dotenvConfig() {
295
- return this._userDefinedDotenvConfig;
296
- }
297
- static refreshCache() {
298
- EnvaptCache.clear();
299
- void this.config;
300
- }
301
- static resolveKeyInput(keyInput) {
302
- const keys = Array.isArray(keyInput) ? keyInput : [
303
- keyInput
304
- ];
305
- const normalizedKeys = keys;
306
- if (normalizedKeys.length === 0) {
307
- throw new EnvaptError(EnvaptErrorCodes.InvalidKeyInput, "At least one environment key must be provided.");
308
- }
309
- if (normalizedKeys.some((k) => typeof k !== "string")) {
310
- throw new EnvaptError(EnvaptErrorCodes.InvalidKeyInput, "Environment keys must be strings.");
311
- }
312
- if (normalizedKeys.some((k) => k.trim() === "")) {
313
- throw new EnvaptError(EnvaptErrorCodes.InvalidKeyInput, "Environment keys cannot be empty strings.");
314
- }
315
- for (const candidate of normalizedKeys) {
316
- const value = this.config.get(candidate);
317
- if (value !== void 0) {
318
- return {
319
- key: candidate,
320
- value
321
- };
322
- }
323
- }
324
- return {
325
- key: normalizedKeys[0],
326
- value: void 0
327
- };
328
- }
329
- static get config() {
330
- if (EnvaptCache.size === 0) {
331
- const isolatedEnv = {
332
- ...process__default.default.env
333
- };
334
- try {
335
- dotenv.config({
336
- path: this._envPaths,
337
- processEnv: isolatedEnv,
338
- ...this._userDefinedDotenvConfig
339
- });
340
- } catch {
341
- }
342
- for (const [key, value] of Object.entries(isolatedEnv)) EnvaptCache.set(key, value);
343
- }
344
- return EnvaptCache;
345
- }
346
- /**
347
- * Get raw environment variable value without parsing or conversion.
348
- */
349
- getRaw(key) {
350
- return _EnvapterBase.resolveKeyInput(key).value;
351
- }
352
- };
353
-
354
- // src/BuiltInConverters.ts
355
- var BuiltInConverters = class _BuiltInConverters {
356
- static {
357
- __name(this, "BuiltInConverters");
358
- }
359
- static string(raw, _fallback) {
360
- return String(raw);
361
- }
362
- static number(raw, fallback) {
363
- const parsed = Number(raw);
364
- return Number.isNaN(parsed) ? fallback : parsed;
365
- }
366
- static boolean(raw, fallback) {
367
- const lower = raw.toLowerCase().trim();
368
- const truthyValues = [
369
- "1",
370
- "yes",
371
- "true",
372
- "on"
373
- ];
374
- const falsyValues = [
375
- "0",
376
- "no",
377
- "false",
378
- "off"
379
- ];
380
- if (truthyValues.includes(lower)) return true;
381
- if (falsyValues.includes(lower)) return false;
382
- return fallback;
383
- }
384
- static bigint(raw, fallback) {
385
- try {
386
- return BigInt(raw);
387
- } catch {
388
- return fallback;
389
- }
390
- }
391
- static symbol(raw, fallback) {
392
- try {
393
- return raw ? Symbol.for(raw) : fallback;
394
- } catch {
395
- return fallback;
396
- }
397
- }
398
- static integer(raw, fallback) {
399
- const parsed = Number.parseInt(raw, 10);
400
- return Number.isNaN(parsed) ? fallback : parsed;
401
- }
402
- static float(raw, fallback) {
403
- const parsed = Number.parseFloat(raw);
404
- return Number.isNaN(parsed) ? fallback : parsed;
405
- }
406
- static json(raw, fallback) {
407
- try {
408
- return JSON.parse(raw);
409
- } catch {
410
- return fallback;
411
- }
412
- }
413
- static array(raw, fallback, delimiter = ",") {
414
- if (raw.trim() === "") return [];
415
- const arr = raw.split(delimiter).map((item) => item.trim()).filter(Boolean);
416
- return arr.length ? arr : fallback;
417
- }
418
- static url(raw, fallback) {
419
- try {
420
- return new URL(raw);
421
- } catch {
422
- return fallback;
423
- }
424
- }
425
- static regexp(raw, fallback) {
426
- try {
427
- const match = raw.match(new RegExp(String.raw`^\/(.+)\/([gimsuvy]*)$`));
428
- if (match) return new RegExp(match[1], match[2]);
429
- return new RegExp(raw);
430
- } catch {
431
- return fallback;
432
- }
433
- }
434
- static date(raw, fallback) {
435
- if (new RegExp(String.raw`^\d+$`).test(raw)) {
436
- const timestamp = parseInt(raw, 10);
437
- const parsed2 = new Date(timestamp);
438
- return Number.isNaN(parsed2.getTime()) ? fallback : parsed2;
439
- }
440
- const isoRegex = new RegExp(String.raw`^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$`, "u");
441
- if (!isoRegex.test(raw)) return fallback;
442
- const parsed = new Date(raw);
443
- return Number.isNaN(parsed.getTime()) ? fallback : parsed;
444
- }
445
- static time(raw, fallback) {
446
- const match = raw.match(new RegExp(String.raw`^(\d+(?:\.\d+)?)(ms|s|m|h)?$`, "u"));
447
- if (!match) return fallback;
448
- const [, numStr, capturedUnit] = match;
449
- if (!numStr) return fallback;
450
- const value = Number.parseFloat(numStr);
451
- if (Number.isNaN(value)) return fallback;
452
- const unit = capturedUnit ?? "ms";
453
- const SECONDS_TO_MS = 1e3;
454
- const SECONDS_PER_MINUTE = 60;
455
- const MINUTES_PER_HOUR = 60;
456
- const MINUTES_TO_MS = SECONDS_PER_MINUTE * SECONDS_TO_MS;
457
- const HOURS_TO_MS = MINUTES_PER_HOUR * MINUTES_TO_MS;
458
- if (unit === "ms") return value;
459
- if (unit === "s") return value * SECONDS_TO_MS;
460
- if (unit === "m") return value * MINUTES_TO_MS;
461
- return value * HOURS_TO_MS;
462
- }
463
- /**
464
- * Process array with custom converter config
465
- */
466
- static processArrayConverter(raw, fallback, config2) {
467
- if (raw.trim() === "") return [];
468
- const items = raw.split(config2.delimiter).map((item) => String(item).trim()).filter(Boolean);
469
- if (!items.length) return fallback ? fallback : void 0;
470
- const type = config2.type;
471
- if (!type) return items;
472
- const converter = _BuiltInConverters.getConverter(type);
473
- return items.map((item) => {
474
- const converted = converter(item, void 0);
475
- return converted ?? item;
476
- });
477
- }
478
- /**
479
- * Get the converter function for a built-in converter type
480
- */
481
- static getConverter(type) {
482
- const converters = {
483
- string: _BuiltInConverters.string,
484
- number: _BuiltInConverters.number,
485
- boolean: _BuiltInConverters.boolean,
486
- integer: _BuiltInConverters.integer,
487
- bigint: _BuiltInConverters.bigint,
488
- symbol: _BuiltInConverters.symbol,
489
- float: _BuiltInConverters.float,
490
- json: _BuiltInConverters.json,
491
- array: _BuiltInConverters.array,
492
- url: _BuiltInConverters.url,
493
- regexp: _BuiltInConverters.regexp,
494
- date: _BuiltInConverters.date,
495
- time: _BuiltInConverters.time
496
- };
497
- return converters[type];
498
- }
499
- };
500
-
501
- // src/Parser.ts
502
- var Parser = class {
503
- static {
504
- __name(this, "Parser");
505
- }
506
- envService;
507
- TEMPLATE_REGEX = /\${\w*}/g;
508
- constructor(envService) {
509
- this.envService = envService;
510
- }
511
- /**
512
- * Resolve template variables in a string while handling circular references and missing variables
513
- * @internal
514
- */
515
- resolveTemplate(key, value, stack = /* @__PURE__ */ new Set()) {
516
- stack.add(key);
517
- const out = value.replace(this.TEMPLATE_REGEX, (template) => {
518
- const variable = template.slice(2, -1);
519
- if (stack.has(variable)) return template;
520
- const raw = this.envService.getRaw(variable);
521
- if (!raw || raw === "") return template;
522
- const resolved = this.resolveTemplate(variable, raw, new Set(stack));
523
- if (resolved.includes(`\${${key}}`)) return template;
524
- if (resolved === raw && /\$\{[^}]*\}/.test(resolved)) return template;
525
- return resolved;
526
- });
527
- stack.delete(key);
528
- return out;
529
- }
530
- convertValue(key, fallback, converter, hasFallback) {
531
- const resolvedConverter = this.resolveConverter(converter, fallback);
532
- const processedFallback = this.processFallbackForConverter(resolvedConverter, fallback);
533
- if (Validator.isArrayConverter(resolvedConverter)) {
534
- return this.processArrayConverter(key, processedFallback, resolvedConverter, hasFallback);
535
- }
536
- if (Validator.isPrimitiveConstructor(resolvedConverter)) {
537
- const stringConverter = this.convertPrimitiveToString(resolvedConverter);
538
- return this.processBuiltInConverter(key, processedFallback, stringConverter, hasFallback, true);
539
- }
540
- if (Validator.isBuiltInConverter(resolvedConverter)) {
541
- return this.processBuiltInConverter(key, processedFallback, resolvedConverter, hasFallback, false);
542
- }
543
- return this.processCustomConverter(key, processedFallback, resolvedConverter, hasFallback);
544
- }
545
- processFallbackForConverter(converter, fallback) {
546
- if (Validator.isPrimitiveConstructor(converter) && fallback !== void 0) {
547
- return Validator.coercePrimitiveFallback(converter, fallback);
548
- }
549
- return fallback;
550
- }
551
- convertPrimitiveToString(primitiveConstructor) {
552
- if (primitiveConstructor === String) return "string";
553
- if (primitiveConstructor === Number) return "number";
554
- if (primitiveConstructor === Boolean) return "boolean";
555
- if (primitiveConstructor === BigInt) return "bigint";
556
- if (primitiveConstructor === Symbol) return "symbol";
557
- throw new EnvaptError(EnvaptErrorCodes.InvalidConverterType, `Unknown primitive constructor`);
558
- }
559
- processBuiltInConverter(key, fallback, resolvedConverter, hasFallback, wasOriginallyConstructor) {
560
- Validator.builtInConverter(resolvedConverter);
561
- if (hasFallback && fallback !== void 0 && !wasOriginallyConstructor) {
562
- Validator.validateBuiltInConverterFallback(resolvedConverter, fallback);
563
- if (resolvedConverter === "array" && Array.isArray(fallback)) {
564
- Validator.validateArrayFallbackElementTypes(fallback);
565
- }
566
- }
567
- const parsed = this.envService.get(key, void 0);
568
- if (parsed === void 0) return hasFallback ? fallback : null;
569
- const converterFn = BuiltInConverters.getConverter(resolvedConverter);
570
- const result = converterFn(parsed, fallback);
571
- if (result === void 0 && !hasFallback) return null;
572
- return result;
573
- }
574
- processArrayConverter(key, fallback, resolvedConverter, hasFallback) {
575
- Validator.arrayConverter(resolvedConverter);
576
- if (hasFallback && fallback !== void 0 && !Array.isArray(fallback)) {
577
- throw new EnvaptError(EnvaptErrorCodes.InvalidFallback, `ArrayConverter requires that the fallback be an array, got ${typeof fallback}`);
578
- }
579
- if (hasFallback && Array.isArray(fallback)) {
580
- Validator.validateArrayFallbackElementTypes(fallback);
581
- if (resolvedConverter.type) {
582
- Validator.validateArrayConverterElementTypeMatch(resolvedConverter.type, fallback);
583
- }
584
- }
585
- const parsed = this.envService.get(key, void 0);
586
- if (parsed === void 0) return hasFallback ? fallback : null;
587
- const result = BuiltInConverters.processArrayConverter(parsed, fallback, resolvedConverter);
588
- if (result === void 0 && !hasFallback) return null;
589
- return result;
590
- }
591
- processCustomConverter(key, fallback, resolvedConverter, _hasFallback) {
592
- Validator.customConvertor(resolvedConverter);
593
- const raw = this.envService.get(key, void 0);
594
- return resolvedConverter(raw, fallback);
595
- }
596
- resolveConverter(converter, fallback) {
597
- if (converter) return converter;
598
- const fallbackType = typeof fallback;
599
- if (fallbackType === "number") return "number";
600
- if (fallbackType === "boolean") return "boolean";
601
- if (fallbackType === "bigint") return "bigint";
602
- if (fallbackType === "symbol") return "symbol";
603
- return "string";
604
- }
605
- };
606
-
607
- // src/core/EnvironmentMethods.ts
608
- var Environment = /* @__PURE__ */ (function(Environment2) {
609
- Environment2[Environment2["Development"] = 0] = "Development";
610
- Environment2[Environment2["Staging"] = 1] = "Staging";
611
- Environment2[Environment2["Production"] = 2] = "Production";
612
- return Environment2;
613
- })({});
614
- var EnvironmentMethods = class _EnvironmentMethods extends EnvapterBase {
615
- static {
616
- __name(this, "EnvironmentMethods");
617
- }
618
- static _environment;
619
- static determineEnvironment(env) {
620
- const environment = env ?? this.getRawValue("ENVIRONMENT", this.getRawValue("ENV", this.getRawValue("NODE_ENV", "development")));
621
- if (typeof environment === "string") {
622
- this._environment = environment.toLowerCase() === "production" ? 2 : environment === "staging" ? 1 : 0;
623
- } else {
624
- this._environment = environment;
625
- }
626
- }
627
- static getRawValue(key, fallback) {
628
- return this.config.get(key) || fallback;
629
- }
630
- /**
631
- * Get the current application environment
632
- */
633
- static get environment() {
634
- if (this._environment === void 0) {
635
- this.determineEnvironment();
636
- }
637
- return this._environment;
638
- }
639
- /**
640
- * Set the application environment. Accepts either Environment enum or string value.
641
- */
642
- static set environment(env) {
643
- this.determineEnvironment(env);
644
- }
645
- /**
646
- * @see {@link EnvironmentMethods.environment}
647
- */
648
- get environment() {
649
- return _EnvironmentMethods.environment;
650
- }
651
- /**
652
- * @see {@link EnvironmentMethods.environment}
653
- */
654
- set environment(env) {
655
- _EnvironmentMethods.determineEnvironment(env);
656
- }
657
- /**
658
- * Check if the current environment is production
659
- */
660
- static get isProduction() {
661
- return this.environment === 2;
662
- }
663
- /**
664
- * @see {@link EnvironmentMethods.isProduction}
665
- */
666
- get isProduction() {
667
- return _EnvironmentMethods.environment === 2;
668
- }
669
- /**
670
- * Check if the current environment is staging
671
- */
672
- static get isStaging() {
673
- return this.environment === 1;
674
- }
675
- /**
676
- * @see {@link EnvironmentMethods.isStaging}
677
- */
678
- get isStaging() {
679
- return _EnvironmentMethods.environment === 1;
680
- }
681
- /**
682
- * Check if the current environment is development
683
- */
684
- static get isDevelopment() {
685
- return this.environment === 0;
686
- }
687
- /**
688
- * @see {@link EnvironmentMethods.isDevelopment}
689
- */
690
- get isDevelopment() {
691
- return _EnvironmentMethods.environment === 0;
692
- }
693
- static refreshCache() {
694
- super.refreshCache();
695
- this._environment = void 0;
696
- }
697
- };
698
-
699
- // src/core/PrimitiveMethods.ts
700
- var PrimitiveMethods = class _PrimitiveMethods extends EnvironmentMethods {
701
- static {
702
- __name(this, "PrimitiveMethods");
703
- }
704
- static parser = new Parser(new _PrimitiveMethods());
705
- static _get(key, type, def) {
706
- const { key: resolvedKey, value } = this.resolveKeyInput(key);
707
- const rawVal = value;
708
- if (!rawVal) return def;
709
- const parsed = this.parser.resolveTemplate(resolvedKey, String(rawVal));
710
- let result;
711
- if (type === 1) result = BuiltInConverters.number(parsed, def);
712
- else if (type === 2) result = BuiltInConverters.boolean(parsed, def);
713
- else if (type === 3) result = BuiltInConverters.bigint(parsed, def);
714
- else if (type === 4) result = BuiltInConverters.symbol(parsed, def);
715
- else result = BuiltInConverters.string(parsed, def);
716
- return result;
717
- }
718
- /**
719
- * Get a string environment variable with optional fallback.
720
- * Supports template variable resolution using `${VAR}` syntax.
721
- * Accepts a single key or an ordered array of keys (first match wins).
722
- */
723
- static get(key, def) {
724
- return this._get(key, 0, def);
725
- }
726
- get(key, def) {
727
- return _PrimitiveMethods._get(key, 0, def);
728
- }
729
- /**
730
- * Get a number environment variable with optional fallback.
731
- * Automatically converts string values to numbers.
732
- * Accepts a single key or an ordered array of keys (first match wins).
733
- */
734
- static getNumber(key, def) {
735
- return this._get(key, 1, def);
736
- }
737
- /**
738
- * @see {@link PrimitiveMethods.getNumber}
739
- */
740
- getNumber(key, def) {
741
- return _PrimitiveMethods._get(key, 1, def);
742
- }
743
- /**
744
- * Get a boolean environment variable with optional fallback.
745
- * Recognizes: `1`, `yes`, `true`, 'on' as **true**; `0`, `no`, `false`, 'off' as **false** (case-insensitive).
746
- * Accepts a single key or an ordered array of keys (first match wins).
747
- */
748
- static getBoolean(key, def) {
749
- return this._get(key, 2, def);
750
- }
751
- /**
752
- * @see {@link PrimitiveMethods.getBoolean}
753
- */
754
- getBoolean(key, def) {
755
- return _PrimitiveMethods._get(key, 2, def);
756
- }
757
- /**
758
- * Get a bigint environment variable with optional fallback.
759
- * Automatically converts string values to bigint.
760
- * Accepts a single key or an ordered array of keys (first match wins).
761
- */
762
- static getBigInt(key, def) {
763
- return this._get(key, 3, def);
764
- }
765
- /**
766
- * @see {@link PrimitiveMethods.getBigInt}
767
- */
768
- getBigInt(key, def) {
769
- return _PrimitiveMethods._get(key, 3, def);
770
- }
771
- /**
772
- * Get a symbol environment variable with optional fallback.
773
- * Creates a symbol from the string value.
774
- * Accepts a single key or an ordered array of keys (first match wins).
775
- */
776
- static getSymbol(key, def) {
777
- return this._get(key, 4, def);
778
- }
779
- /**
780
- * @see {@link PrimitiveMethods.getSymbol}
781
- */
782
- getSymbol(key, def) {
783
- return _PrimitiveMethods._get(key, 4, def);
784
- }
785
- };
786
-
787
- // src/core/AdvancedMethods.ts
788
- var AdvancedMethods = class _AdvancedMethods extends PrimitiveMethods {
789
- static {
790
- __name(this, "AdvancedMethods");
791
- }
792
- static getUsing(key, converter, fallback) {
793
- const { key: resolvedKey, value } = this.resolveKeyInput(key);
794
- if (!value) return fallback;
795
- const hasFallback = fallback !== void 0;
796
- const result = this.parser.convertValue(resolvedKey, fallback, converter, hasFallback);
797
- return result;
798
- }
799
- getUsing(key, converter, fallback) {
800
- return _AdvancedMethods.getUsing(key, converter, fallback);
801
- }
802
- /**
803
- * Get an environment variable using a custom converter function.
804
- * Accepts a single key or an ordered list for automatic fallback.
805
- */
806
- static getWith(key, converter, fallback) {
807
- const { key: resolvedKey, value } = this.resolveKeyInput(key);
808
- if (!value) return fallback;
809
- const hasFallback = fallback !== void 0;
810
- const result = this.parser.convertValue(resolvedKey, fallback, converter, hasFallback);
811
- return result;
812
- }
813
- /**
814
- * @see {@link AdvancedMethods.getWith}
815
- */
816
- getWith(key, converter, fallback) {
817
- return _AdvancedMethods.getWith(key, converter, fallback);
818
- }
819
- };
820
-
821
- // src/Envapter.ts
822
- var Envapter = class _Envapter extends AdvancedMethods {
823
- static {
824
- __name(this, "Envapter");
825
- }
826
- /**
827
- * Tagged template literal for resolving environment variables in template strings.
828
- *
829
- * @example
830
- * ```ts
831
- * // Given API_HOST=api.example.com and API_PORT=8080 in environment
832
- * const endpoint = Envapter.resolve`Connecting to ${'API_HOST'}:${'API_PORT'}`;
833
- * // Returns: "Connecting to api.example.com:8080"
834
- *
835
- * // Works with template variables in .env too:
836
- * // API_URL=https://${API_HOST}:${API_PORT}
837
- * const message = Envapter.resolve`Service endpoint: ${'API_URL'}`;
838
- * // Returns: "Service endpoint: https://api.example.com:8080"
839
- * ```
840
- */
841
- static resolve(strings, ...keys) {
842
- return strings.reduce((result, string, i) => {
843
- const envKey = keys[i];
844
- const envValue = envKey ? super.get(envKey, "") : "";
845
- return result + string + envValue;
846
- }, "");
847
- }
848
- /**
849
- * @see {@link Envapter.resolve}
850
- */
851
- resolve(strings, ...keys) {
852
- return _Envapter.resolve(strings, ...keys);
853
- }
854
- };
855
-
856
- // src/Envapt.ts
857
- function createPropertyDecorator(key, fallback, converter, hasFallback) {
858
- return function(target, prop) {
859
- const propKey = String(prop);
860
- const className = typeof target === "function" ? target.name : target.constructor.name;
861
- const cacheKey = `${className}.${propKey}`;
862
- Object.defineProperty(target, propKey, {
863
- get: /* @__PURE__ */ __name(function() {
864
- let value = EnvaptCache.get(cacheKey);
865
- if (value === void 0) {
866
- const parser = new Parser(new Envapter());
867
- value = parser.convertValue(key, fallback, converter, hasFallback);
868
- EnvaptCache.set(cacheKey, value);
869
- }
870
- return value;
871
- }, "get"),
872
- configurable: false,
873
- enumerable: true
874
- });
875
- };
876
- }
877
- __name(createPropertyDecorator, "createPropertyDecorator");
878
- function Envapt(key, fallbackOrOptions, converter) {
879
- let fallback;
880
- let actualConverter;
881
- let hasFallback = true;
882
- if (fallbackOrOptions && typeof fallbackOrOptions === "object" && ("fallback" in fallbackOrOptions || "converter" in fallbackOrOptions)) {
883
- const options = fallbackOrOptions;
884
- fallback = options.fallback;
885
- actualConverter = options.converter;
886
- hasFallback = "fallback" in options;
887
- } else {
888
- fallback = fallbackOrOptions;
889
- actualConverter = converter;
890
- hasFallback = arguments.length > 1;
891
- }
892
- return createPropertyDecorator(key, fallback, actualConverter, hasFallback);
893
- }
894
- __name(Envapt, "Envapt");
895
-
896
- // src/Converters.ts
897
- var Converters = /* @__PURE__ */ (function(Converters2) {
898
- Converters2["String"] = "string";
899
- Converters2["Number"] = "number";
900
- Converters2["Boolean"] = "boolean";
901
- Converters2["Bigint"] = "bigint";
902
- Converters2["Symbol"] = "symbol";
903
- Converters2["Integer"] = "integer";
904
- Converters2["Float"] = "float";
905
- Converters2["Json"] = "json";
906
- Converters2["Array"] = "array";
907
- Converters2["Url"] = "url";
908
- Converters2["Regexp"] = "regexp";
909
- Converters2["Date"] = "date";
910
- Converters2["Time"] = "time";
911
- return Converters2;
912
- })({});
913
- /* v8 ignore next -- @preserve */
914
-
915
- exports.Converters = Converters;
916
- exports.Envapt = Envapt;
917
- exports.EnvaptError = EnvaptError;
918
- exports.EnvaptErrorCodes = EnvaptErrorCodes;
919
- exports.Envapter = Envapter;
920
- exports.Environment = Environment;
921
- //# sourceMappingURL=index.cjs.map
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./Envapter-CBSM3v-5.cjs");function t(e){return Array.isArray(e)?`[${e.join(`, `)}]`:String(e)}function n(n,r){let{fallback:i,converter:a,hasFallback:o,required:s,schema:c}=r;return function(r,l){let u=String(l),d=`${typeof r==`function`?r.name:r.constructor.name}.${u}`;Object.defineProperty(r,u,{get:function(){let r=e.r.get(d);if(r===void 0){let l=new e.t;if(s&&c===void 0){let r=l.getRaw(n);if(r===void 0||r.trim()===``)throw new e.o(305,`Required environment variable "${t(n)}" is missing or empty.`)}let u=new e.i(l);r=c===void 0?u.convertValue(n,i,a,o):u.convertWithSchema(n,c,i,o),e.r.set(d,r)}return r},configurable:!1,enumerable:!0})}}function r(t,r,i){let a,o,s,c=!0,l=!1;if(r&&typeof r==`object`&&(`fallback`in r||`converter`in r||`required`in r||`schema`in r)){let t=r;if(a=t.fallback,o=t.converter,c=`fallback`in t,l=t.required===!0,l&&c&&a!==void 0)throw new e.o(302,"`required: true` and `fallback` are mutually exclusive on @Envapt options. Drop the fallback or call `Envapter.require()` separately.");if(`schema`in t&&t.schema!==void 0){if(!e.a.isStandardSchema(t.schema))throw new e.o(302,"`schema` must be a Standard Schema v1 object (zod, valibot, arktype, or any `~standard`-conformant value).");if(o!==void 0)throw new e.o(302,"`schema` and `converter` are mutually exclusive on @Envapt options. Drop one as they both turn a raw env string into a typed value.");s=t.schema}}else a=r,o=i,c=arguments.length>1;return n(t,{fallback:a,converter:o,hasFallback:c,required:l,schema:s})}function i(e,t,r){return n(t,{converter:e,fallback:r,hasFallback:r!==void 0,required:!1,schema:void 0})}function a(t,n){return i(e.c.Boolean,t,n)}function o(t,n){return i(e.c.Number,t,n)}function s(t,n){return i(e.c.String,t,n)}function c(t,n){return i(e.c.Time,t,n)}function l(t,n){return i(e.c.Url,t,n)}exports.Converters=e.c,exports.EnvBool=a,exports.EnvNum=o,exports.EnvStr=s,exports.EnvTime=c,exports.EnvUrl=l,exports.Envapt=r,exports.EnvaptError=e.o,exports.EnvaptErrorCodes=e.s,exports.Envapter=e.t,exports.Environment=e.n,exports.isArrayOf=e.l;
922
2
  //# sourceMappingURL=index.cjs.map