envapt 5.2.0 → 6.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.
Files changed (157) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/browser/Debug.mjs.map +1 -1
  3. package/dist/browser/Dotenv.mjs.map +1 -1
  4. package/dist/browser/Validators.mjs.map +1 -1
  5. package/dist/browser/converters/BuiltInConverters.mjs.map +1 -1
  6. package/dist/browser/converters/ValueConverter.mjs.map +1 -1
  7. package/dist/browser/core/EnvapterBase.mjs.map +1 -1
  8. package/dist/browser/core/EnvironmentMethods.mjs.map +1 -1
  9. package/dist/browser/decorators/Envapt.d.mts +2 -27
  10. package/dist/browser/decorators/Envapt.mjs +1 -1
  11. package/dist/browser/decorators/Envapt.mjs.map +1 -1
  12. package/dist/browser/index.d.mts +2 -2
  13. package/dist/browser/types/Conversion.d.mts +1 -6
  14. package/dist/node/Debug.cjs +1 -1
  15. package/dist/node/Debug.cjs.map +1 -1
  16. package/dist/node/Debug.d.mts +2 -0
  17. package/dist/node/Debug.mjs +1 -1
  18. package/dist/node/Debug.mjs.map +1 -1
  19. package/dist/node/Dotenv.cjs +1 -1
  20. package/dist/node/Dotenv.cjs.map +1 -1
  21. package/dist/node/Dotenv.d.mts +2 -0
  22. package/dist/node/Dotenv.mjs +1 -1
  23. package/dist/node/Dotenv.mjs.map +1 -1
  24. package/dist/node/Envapter.cjs +1 -1
  25. package/dist/node/Envapter.cjs.map +1 -1
  26. package/dist/node/Envapter.d.mts +2 -0
  27. package/dist/node/Envapter.mjs +1 -1
  28. package/dist/node/Envapter.mjs.map +1 -1
  29. package/dist/node/Error.cjs +1 -1
  30. package/dist/node/Error.cjs.map +1 -1
  31. package/dist/node/Error.d.mts +2 -0
  32. package/dist/node/Error.mjs +1 -1
  33. package/dist/node/Error.mjs.map +1 -1
  34. package/dist/node/NodeEnvapter.cjs +1 -1
  35. package/dist/node/NodeEnvapter.cjs.map +1 -1
  36. package/dist/node/NodeEnvapter.d.mts +2 -0
  37. package/dist/node/NodeEnvapter.mjs +1 -1
  38. package/dist/node/NodeEnvapter.mjs.map +1 -1
  39. package/dist/node/StandardSchema.d.mts +2 -0
  40. package/dist/node/TemplateResolver.cjs +1 -1
  41. package/dist/node/TemplateResolver.cjs.map +1 -1
  42. package/dist/node/TemplateResolver.d.mts +2 -0
  43. package/dist/node/TemplateResolver.mjs +1 -1
  44. package/dist/node/TemplateResolver.mjs.map +1 -1
  45. package/dist/node/Validators.cjs +1 -1
  46. package/dist/node/Validators.cjs.map +1 -1
  47. package/dist/node/Validators.mjs +1 -1
  48. package/dist/node/Validators.mjs.map +1 -1
  49. package/dist/node/_virtual/_rolldown/runtime.cjs +1 -1
  50. package/dist/node/config.cjs +1 -1
  51. package/dist/node/config.cjs.map +1 -1
  52. package/dist/node/config.d.mts +2 -1
  53. package/dist/node/config.mjs +1 -1
  54. package/dist/node/config.mjs.map +1 -1
  55. package/dist/node/converters/BuiltInConverters.cjs +1 -1
  56. package/dist/node/converters/BuiltInConverters.cjs.map +1 -1
  57. package/dist/node/converters/BuiltInConverters.mjs +1 -1
  58. package/dist/node/converters/BuiltInConverters.mjs.map +1 -1
  59. package/dist/node/converters/Converters.cjs +1 -1
  60. package/dist/node/converters/Converters.cjs.map +1 -1
  61. package/dist/node/converters/Converters.d.mts +2 -0
  62. package/dist/node/converters/Converters.mjs +1 -1
  63. package/dist/node/converters/Converters.mjs.map +1 -1
  64. package/dist/node/converters/ListOfBuiltInConverters.cjs +1 -1
  65. package/dist/node/converters/ListOfBuiltInConverters.cjs.map +1 -1
  66. package/dist/node/converters/ListOfBuiltInConverters.mjs +1 -1
  67. package/dist/node/converters/ListOfBuiltInConverters.mjs.map +1 -1
  68. package/dist/node/converters/ValueConverter.cjs +1 -1
  69. package/dist/node/converters/ValueConverter.cjs.map +1 -1
  70. package/dist/node/converters/ValueConverter.d.mts +2 -0
  71. package/dist/node/converters/ValueConverter.mjs +1 -1
  72. package/dist/node/converters/ValueConverter.mjs.map +1 -1
  73. package/dist/node/core/AdvancedMethods.cjs +1 -1
  74. package/dist/node/core/AdvancedMethods.cjs.map +1 -1
  75. package/dist/node/core/AdvancedMethods.d.mts +2 -0
  76. package/dist/node/core/AdvancedMethods.mjs +1 -1
  77. package/dist/node/core/AdvancedMethods.mjs.map +1 -1
  78. package/dist/node/core/EnvapterBase.cjs +1 -1
  79. package/dist/node/core/EnvapterBase.cjs.map +1 -1
  80. package/dist/node/core/EnvapterBase.d.mts +2 -0
  81. package/dist/node/core/EnvapterBase.mjs +1 -1
  82. package/dist/node/core/EnvapterBase.mjs.map +1 -1
  83. package/dist/node/core/EnvironmentMethods.cjs +1 -1
  84. package/dist/node/core/EnvironmentMethods.cjs.map +1 -1
  85. package/dist/node/core/EnvironmentMethods.d.mts +2 -0
  86. package/dist/node/core/EnvironmentMethods.mjs +1 -1
  87. package/dist/node/core/EnvironmentMethods.mjs.map +1 -1
  88. package/dist/node/core/PrimitiveMethods.cjs +1 -1
  89. package/dist/node/core/PrimitiveMethods.cjs.map +1 -1
  90. package/dist/node/core/PrimitiveMethods.d.mts +2 -0
  91. package/dist/node/core/PrimitiveMethods.mjs +1 -1
  92. package/dist/node/core/PrimitiveMethods.mjs.map +1 -1
  93. package/dist/node/decorators/Envapt.cjs +1 -1
  94. package/dist/node/decorators/Envapt.cjs.map +1 -1
  95. package/dist/node/decorators/Envapt.d.cts +2 -27
  96. package/dist/node/decorators/Envapt.d.mts +4 -27
  97. package/dist/node/decorators/Envapt.mjs +1 -1
  98. package/dist/node/decorators/Envapt.mjs.map +1 -1
  99. package/dist/node/decorators/SugarDecorators.cjs +1 -1
  100. package/dist/node/decorators/SugarDecorators.cjs.map +1 -1
  101. package/dist/node/decorators/SugarDecorators.d.mts +2 -0
  102. package/dist/node/decorators/SugarDecorators.mjs +1 -1
  103. package/dist/node/decorators/SugarDecorators.mjs.map +1 -1
  104. package/dist/node/decorators/createPropertyDecorator.cjs +1 -1
  105. package/dist/node/decorators/createPropertyDecorator.cjs.map +1 -1
  106. package/dist/node/decorators/createPropertyDecorator.mjs +1 -1
  107. package/dist/node/decorators/createPropertyDecorator.mjs.map +1 -1
  108. package/dist/node/index.cjs +1 -1
  109. package/dist/node/index.d.cts +2 -2
  110. package/dist/node/index.d.mts +4 -2
  111. package/dist/node/index.mjs +1 -1
  112. package/dist/node/runtime.cjs +1 -1
  113. package/dist/node/runtime.cjs.map +1 -1
  114. package/dist/node/runtime.mjs +1 -1
  115. package/dist/node/runtime.mjs.map +1 -1
  116. package/dist/node/sources/ManualEnvSource.cjs +1 -1
  117. package/dist/node/sources/ManualEnvSource.cjs.map +1 -1
  118. package/dist/node/sources/ManualEnvSource.d.mts +2 -0
  119. package/dist/node/sources/ManualEnvSource.mjs +1 -1
  120. package/dist/node/sources/ManualEnvSource.mjs.map +1 -1
  121. package/dist/node/sources/NodeEnvSource.cjs +1 -1
  122. package/dist/node/sources/NodeEnvSource.cjs.map +1 -1
  123. package/dist/node/sources/NodeEnvSource.d.mts +2 -0
  124. package/dist/node/sources/NodeEnvSource.mjs +1 -1
  125. package/dist/node/sources/NodeEnvSource.mjs.map +1 -1
  126. package/dist/node/sources/UnboundEnvSource.cjs +1 -1
  127. package/dist/node/sources/UnboundEnvSource.cjs.map +1 -1
  128. package/dist/node/sources/UnboundEnvSource.mjs +1 -1
  129. package/dist/node/sources/UnboundEnvSource.mjs.map +1 -1
  130. package/dist/node/sources/WorkerEnvSource.cjs +1 -1
  131. package/dist/node/sources/WorkerEnvSource.cjs.map +1 -1
  132. package/dist/node/sources/WorkerEnvSource.d.mts +2 -0
  133. package/dist/node/sources/WorkerEnvSource.mjs +1 -1
  134. package/dist/node/sources/WorkerEnvSource.mjs.map +1 -1
  135. package/dist/node/sources/coerce.cjs +1 -1
  136. package/dist/node/sources/coerce.cjs.map +1 -1
  137. package/dist/node/sources/coerce.mjs +1 -1
  138. package/dist/node/sources/coerce.mjs.map +1 -1
  139. package/dist/node/types/Conversion.d.cts +1 -6
  140. package/dist/node/types/Conversion.d.mts +3 -6
  141. package/dist/node/types/Env.d.mts +2 -0
  142. package/dist/node/types/Options.d.mts +2 -0
  143. package/dist/node/types/Schema.d.mts +2 -0
  144. package/dist/node/types/Source.d.mts +2 -0
  145. package/dist/workerd/Debug.mjs.map +1 -1
  146. package/dist/workerd/Dotenv.mjs.map +1 -1
  147. package/dist/workerd/Validators.mjs.map +1 -1
  148. package/dist/workerd/converters/BuiltInConverters.mjs.map +1 -1
  149. package/dist/workerd/converters/ValueConverter.mjs.map +1 -1
  150. package/dist/workerd/core/EnvapterBase.mjs.map +1 -1
  151. package/dist/workerd/core/EnvironmentMethods.mjs.map +1 -1
  152. package/dist/workerd/decorators/Envapt.d.mts +2 -27
  153. package/dist/workerd/decorators/Envapt.mjs +1 -1
  154. package/dist/workerd/decorators/Envapt.mjs.map +1 -1
  155. package/dist/workerd/index.d.mts +2 -2
  156. package/dist/workerd/types/Conversion.d.mts +1 -6
  157. package/package.json +3 -3
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # envapt
2
2
 
3
+ ## 6.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - 140826e: Remove the deprecated positional `@Envapt('KEY', fallback, converter)` form. Pass an options object instead, like `@Envapt('KEY', { converter, fallback })`. The no-argument `@Envapt('KEY')` form is unchanged. A second argument that is not an options object now throws `EnvaptError` with `InvalidUserDefinedConfig`, and the internal `InferPrimitiveFallbackType` type is removed.
8
+
9
+ This major also documents the test-environment detection as an intended part of the API. `NODE_ENV=test` (and Vite's `MODE=test`) resolve to `Environment.Test`, so `isDevelopment` returns false under a test runner. That behavior first shipped by mistake in the 5.2.0 minor, which is deprecated on npm. Pin 5.1.1 for the old behavior, or move to 6.0.0 where it is documented.
10
+
3
11
  ## 5.2.0
4
12
 
5
13
  ### Minor Changes
@@ -1 +1 @@
1
- {"version":3,"file":"Debug.mjs","names":[],"sources":["../../src/Debug.ts"],"sourcesContent":["import { EnvaptError, EnvaptErrorCodes } from './Error';\nimport { readRuntimeEnv, writeRuntimeLine } from './runtime';\n\n/**\n * Debug log levels for {@link Envapter.debug}. `silent` (default) emits nothing.\n * `warn` covers signals that might indicate misconfiguration: failed file reads,\n * unresolved templates (when not strict), fallback values used in place of missing\n * env. `verbose` adds every loaded file, per-file key count, per-key load lines, and\n * effective-paths / cache-rebuild notices.\n * @public\n */\nexport type DebugLevel = 'silent' | 'warn' | 'verbose';\n\nconst VALID_LEVELS: ReadonlySet<string> = new Set<DebugLevel>(['silent', 'warn', 'verbose']);\n\nlet currentLevel: DebugLevel = 'silent';\nlet initialized = false;\n\nfunction isDebugLevel(value: string | undefined): value is DebugLevel {\n return value !== undefined && VALID_LEVELS.has(value);\n}\n\n// Reads `ENVAPT_DEBUG` lazily on first access. Setter wins after that.\nfunction resolveLevel(): DebugLevel {\n if (!initialized) {\n const fromEnv = readRuntimeEnv().ENVAPT_DEBUG;\n currentLevel = isDebugLevel(fromEnv) ? fromEnv : 'silent';\n initialized = true;\n }\n return currentLevel;\n}\n\n/** @internal */\nexport function setDebugLevel(level: DebugLevel): void {\n if (!isDebugLevel(level)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Invalid debug level \"${String(level)}\". Expected 'silent' | 'warn' | 'verbose'.`\n );\n }\n currentLevel = level;\n initialized = true;\n}\n\n/** @internal */\nexport function getDebugLevel(): DebugLevel {\n return resolveLevel();\n}\n\n/** @internal */\nexport function resetDebugForTesting(): void {\n currentLevel = 'silent';\n initialized = false;\n}\n\n/** @internal */\nexport function debugWarn(message: string): void {\n const level = resolveLevel();\n if (level === 'warn' || level === 'verbose') {\n writeRuntimeLine(`[envapt] ${message}`);\n }\n}\n\n/** @internal */\nexport function debugVerbose(message: string): void {\n if (resolveLevel() === 'verbose') {\n writeRuntimeLine(`[envapt] ${message}`);\n }\n}\n"],"mappings":"+GAaA,MAAM,EAAoC,IAAI,IAAgB,CAAC,SAAU,OAAQ,SAAS,CAAC,EAE3F,IAAI,EAA2B,SAC3B,EAAc,GAElB,SAAS,EAAa,EAAgD,CAClE,OAAO,IAAU,IAAA,IAAa,EAAa,IAAI,CAAK,CACxD,CAGA,SAAS,GAA2B,CAChC,GAAI,CAAC,EAAa,CACd,IAAM,EAAU,EAAe,EAAE,aACjC,EAAe,EAAa,CAAO,EAAI,EAAU,SACjD,EAAc,EAClB,CACA,OAAO,CACX,CAGA,SAAgB,EAAc,EAAyB,CACnD,GAAI,CAAC,EAAa,CAAK,EACnB,MAAM,IAAI,EAAA,IAEN,wBAAwB,OAAO,CAAK,EAAE,2CAC1C,EAEJ,EAAe,EACf,EAAc,EAClB,CAGA,SAAgB,GAA4B,CACxC,OAAO,EAAa,CACxB,CASA,SAAgB,EAAU,EAAuB,CAC7C,IAAM,EAAQ,EAAa,GACvB,IAAU,QAAU,IAAU,YAC9B,EAAiB,YAAY,GAAS,CAE9C,CAGA,SAAgB,EAAa,EAAuB,CAC5C,EAAa,IAAM,WACnB,EAAiB,YAAY,GAAS,CAE9C"}
1
+ {"version":3,"file":"Debug.mjs","names":[],"sources":["../../src/Debug.ts"],"sourcesContent":["import { EnvaptError, EnvaptErrorCodes } from './Error';\nimport { readRuntimeEnv, writeRuntimeLine } from './runtime';\n\n/**\n * Debug log levels for {@link Envapter.debug}. `silent` (default) emits nothing.\n * `warn` covers signals that might indicate misconfiguration: failed file reads,\n * unresolved templates (when not strict), fallback values used in place of missing\n * env. `verbose` adds every loaded file, per-file key count, per-key load lines, and\n * effective-paths / cache-rebuild notices.\n * @public\n */\nexport type DebugLevel = 'silent' | 'warn' | 'verbose';\n\nconst VALID_LEVELS: ReadonlySet<string> = new Set<DebugLevel>(['silent', 'warn', 'verbose']);\n\nlet currentLevel: DebugLevel = 'silent';\nlet initialized = false;\n\nfunction isDebugLevel(value: string | undefined): value is DebugLevel {\n return value !== undefined && VALID_LEVELS.has(value);\n}\n\n// Reads `ENVAPT_DEBUG` lazily on first access. Setter wins after that.\nfunction resolveLevel(): DebugLevel {\n if (!initialized) {\n const fromEnv = readRuntimeEnv().ENVAPT_DEBUG;\n currentLevel = isDebugLevel(fromEnv) ? fromEnv : 'silent';\n initialized = true;\n }\n return currentLevel;\n}\n\n/** @internal */\nexport function setDebugLevel(level: DebugLevel): void {\n if (!isDebugLevel(level)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Invalid debug level \"${String(level)}\". Expected 'silent' | 'warn' | 'verbose'.`\n );\n }\n currentLevel = level;\n initialized = true;\n}\n\n/** @internal */\nexport function getDebugLevel(): DebugLevel {\n return resolveLevel();\n}\n\n/** @internal */\nexport function resetDebugForTesting(): void {\n currentLevel = 'silent';\n initialized = false;\n}\n\n/** @internal */\nexport function debugWarn(message: string): void {\n const level = resolveLevel();\n if (level === 'warn' || level === 'verbose') {\n writeRuntimeLine(`[envapt] ${message}`);\n }\n}\n\n/** @internal */\nexport function debugVerbose(message: string): void {\n if (resolveLevel() === 'verbose') {\n writeRuntimeLine(`[envapt] ${message}`);\n }\n}\n"],"mappings":"+GAaA,MAAM,EAAoC,IAAI,IAAgB,CAAC,SAAU,OAAQ,SAAS,CAAC,EAE3F,IAAI,EAA2B,SAC3B,EAAc,GAElB,SAAS,EAAa,EAAgD,CAClE,OAAO,IAAU,IAAA,IAAa,EAAa,IAAI,CAAK,CACxD,CAGA,SAAS,GAA2B,CAChC,GAAI,CAAC,EAAa,CACd,IAAM,EAAU,EAAe,CAAC,CAAC,aACjC,EAAe,EAAa,CAAO,EAAI,EAAU,SACjD,EAAc,EAClB,CACA,OAAO,CACX,CAGA,SAAgB,EAAc,EAAyB,CACnD,GAAI,CAAC,EAAa,CAAK,EACnB,MAAM,IAAI,EAAA,IAEN,wBAAwB,OAAO,CAAK,EAAE,2CAC1C,EAEJ,EAAe,EACf,EAAc,EAClB,CAGA,SAAgB,GAA4B,CACxC,OAAO,EAAa,CACxB,CASA,SAAgB,EAAU,EAAuB,CAC7C,IAAM,EAAQ,EAAa,GACvB,IAAU,QAAU,IAAU,YAC9B,EAAiB,YAAY,GAAS,CAE9C,CAGA,SAAgB,EAAa,EAAuB,CAC5C,EAAa,IAAM,WACnB,EAAiB,YAAY,GAAS,CAE9C"}
@@ -1 +1 @@
1
- {"version":3,"file":"Dotenv.mjs","names":[],"sources":["../../src/Dotenv.ts"],"sourcesContent":["import { debugVerbose, debugWarn } from './Debug';\n\n/**\n * Public options for the internal `.env` loader. Mirrors the subset of dotenv's\n * `config()` options that envapt actually supports (no DOTENV_KEY, no quiet).\n * For debug output, use `Envapter.debug` (or the `ENVAPT_DEBUG` env var).\n *\n * @public\n */\nexport interface EnvFileOptions {\n /** Encoding for reading .env files. Defaults to 'utf8'. */\n encoding?: string;\n /** When true, later files override earlier ones (and existing processEnv values). Default false (first-wins). */\n override?: boolean;\n}\n\n/**\n * Internal call signature used by `EnvapterBase`. The `path` and `processEnv`\n * fields are managed by envapt and never user-supplied.\n * @internal\n */\nexport interface LoadDotenvInput extends EnvFileOptions {\n path: string | string[];\n processEnv: Record<string, string>;\n // Injected so the loader stays free of `node:fs`. Returns `undefined` when the file is absent.\n readFile(path: string, encoding: string): string | undefined;\n}\n\n// Matches: optional `export`, KEY name, optional whitespace, `=`, optional whitespace, value tail.\n// Multi-line quoted values are handled by re-buffering subsequent lines below.\n// Bounded by anchors with linear-time quantifiers; no catastrophic backtracking risk -- justified\n// eslint-disable-next-line security/detect-unsafe-regex\nconst KEY_LINE_RE = /^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=(.*)$/u;\n\n/**\n * Parse a `.env` text blob into a `Map<string, string>`.\n *\n * Supported syntax:\n * - `KEY=value` and `export KEY=value`\n * - blank lines and full-line `# comments`\n * - single-quoted `'literal'` values (no escape interpretation)\n * - double-quoted `\"value\"` values (interprets `\\n`, `\\r`, `\\t`, `\\\\`, `\\\"`)\n * - backtick-quoted values (literal, like single quotes)\n * - quoted values may span multiple lines\n * - inline `# comment` after an unquoted value (requires whitespace before `#`)\n * - empty values resolve to `\"\"`\n *\n * Mirrors dotenv's quirk where unescaped inner quotes inside a quoted value\n * are tolerated by greedy-matching to the rightmost matching quote on the\n * (possibly multi-line) value buffer. This is what lets a value like\n * `JSON=\"{\"name\":\"x\"}\"` round-trip without escaping.\n *\n * Does NOT perform `${VAR}` expansion — envapt's `Parser` handles that downstream.\n * @internal\n */\nexport function parseDotenv(src: string): Map<string, string> {\n const out = new Map<string, string>();\n const lines = src.split(/\\r?\\n/u);\n\n for (let i = 0; i < lines.length; i++) {\n const consumed = parseEntry(lines, i);\n i = consumed.endLine;\n if (consumed.entry) out.set(consumed.entry.key, consumed.entry.value);\n }\n\n return out;\n}\n\ninterface ParsedEntry {\n key: string;\n value: string;\n}\n\nfunction parseEntry(lines: string[], start: number): { entry: ParsedEntry | undefined; endLine: number } {\n /* v8 ignore next -- @preserve caller bounds-checks start so this never falls back */\n const line = lines[start] ?? '';\n const trimmedLine = line.trim();\n if (trimmedLine === '' || trimmedLine.startsWith('#')) return { entry: undefined, endLine: start };\n\n const match = line.match(KEY_LINE_RE);\n if (!match) return { entry: undefined, endLine: start };\n\n const key = match[1] as string;\n // Drop only leading whitespace before the value; trailing whitespace and inline comments\n // are dealt with below depending on whether the value is quoted.\n /* v8 ignore next -- @preserve regex group 2 always matches via `(.*)`, fallback is defensive */\n const rest = (match[2] ?? '').replace(/^\\s+/u, '');\n const firstChar = rest[0];\n\n if (firstChar === '\"' || firstChar === \"'\" || firstChar === '`') {\n const consumed = consumeQuotedValue(rest, lines, start, firstChar);\n return { entry: { key, value: consumed.value }, endLine: consumed.endLine };\n }\n\n return { entry: { key, value: stripInlineComment(rest) }, endLine: start };\n}\n\nfunction consumeQuotedValue(\n firstLineRest: string,\n lines: string[],\n startLine: number,\n quote: string\n): { value: string; endLine: number } {\n let buffer = firstLineRest;\n let cursor = startLine;\n let closeIdx = findLastUnescapedQuote(buffer, quote);\n\n while (closeIdx < 0 && cursor < lines.length - 1) {\n cursor++;\n /* v8 ignore next -- @preserve cursor is bounded by the while condition above */\n buffer += `\\n${lines[cursor] ?? ''}`;\n closeIdx = findLastUnescapedQuote(buffer, quote);\n }\n\n const inner = closeIdx > 0 ? buffer.slice(1, closeIdx) : buffer.slice(1);\n return { value: quote === '\"' ? unescapeDouble(inner) : inner, endLine: cursor };\n}\n\nfunction stripInlineComment(value: string): string {\n const hashIdx = findInlineCommentStart(value);\n const stripped = hashIdx === -1 ? value : value.slice(0, hashIdx);\n return stripped.trimEnd();\n}\n\nfunction findInlineCommentStart(value: string): number {\n for (let i = 0; i < value.length; i++) {\n if (value[i] === '#' && (i === 0 || /\\s/u.test(value[i - 1] as string))) return i;\n }\n return -1;\n}\n\n/**\n * Find the rightmost matching closing quote in `buffer` (skipping index 0 which is the\n * opening quote). For `\"`, a quote preceded by an odd number of backslashes is escaped\n * and ignored. Single and backtick quotes do not unescape.\n */\nfunction findLastUnescapedQuote(buffer: string, quote: string): number {\n for (let i = buffer.length - 1; i > 0; i--) {\n if (buffer[i] !== quote) continue;\n if (quote === '\"') {\n let backslashes = 0;\n let k = i - 1;\n while (k >= 0 && buffer[k] === '\\\\') {\n backslashes++;\n k--;\n }\n if (backslashes % 2 === 1) continue; // escaped\n }\n return i;\n }\n return -1;\n}\n\nfunction unescapeDouble(raw: string): string {\n let out = '';\n for (let i = 0; i < raw.length; i++) {\n const ch = raw[i];\n if (ch !== '\\\\' || i === raw.length - 1) {\n out += ch;\n continue;\n }\n const next = raw[i + 1];\n i++;\n switch (next) {\n case 'n':\n out += '\\n';\n break;\n case 'r':\n out += '\\r';\n break;\n case 't':\n out += '\\t';\n break;\n case '\\\\':\n out += '\\\\';\n break;\n case '\"':\n out += '\"';\n break;\n default:\n /* v8 ignore next -- @preserve `next` is always defined when this branch is reached (guarded above) */\n out += `\\\\${next ?? ''}`;\n }\n }\n return out;\n}\n\n/**\n * Load one or more `.env` files into a target `processEnv` map. Mirrors the\n * subset of dotenv's `config()` semantics that envapt depends on: first-wins\n * across multiple paths by default, optional `override: true`, optional\n * non-UTF8 encoding, missing files are skipped silently.\n *\n * Returns the set of keys actually written into `input.processEnv`. Skipped\n * collisions (under default `override: false`) are NOT included.\n * @internal\n */\nexport function loadDotenv(input: LoadDotenvInput): Set<string> {\n const paths = Array.isArray(input.path) ? input.path : [input.path];\n const encoding = input.encoding ?? 'utf8';\n const override = input.override ?? false;\n const written = new Set<string>();\n\n for (const filePath of paths) {\n const src = input.readFile(filePath, encoding);\n if (src === undefined) {\n debugWarn(`could not read ${filePath}`);\n continue;\n }\n\n const parsed = parseDotenv(src);\n debugVerbose(`loaded ${filePath}: ${parsed.size} ${parsed.size === 1 ? 'key' : 'keys'}`);\n for (const [key, value] of parsed) {\n const exists = Object.prototype.hasOwnProperty.call(input.processEnv, key);\n if (!exists || override) {\n input.processEnv[key] = value;\n written.add(key);\n debugVerbose(`${filePath} -> ${key}`);\n }\n }\n }\n\n return written;\n}\n"],"mappings":"0DAgCA,MAAM,EAAc,uDAuBpB,SAAgB,EAAY,EAAkC,CAC1D,IAAM,EAAM,IAAI,IACV,EAAQ,EAAI,MAAM,QAAQ,EAEhC,IAAK,IAAI,EAAI,EAAG,EAAI,EAAM,OAAQ,IAAK,CACnC,IAAM,EAAW,EAAW,EAAO,CAAC,EACpC,EAAI,EAAS,QACT,EAAS,OAAO,EAAI,IAAI,EAAS,MAAM,IAAK,EAAS,MAAM,KAAK,CACxE,CAEA,OAAO,CACX,CAOA,SAAS,EAAW,EAAiB,EAAoE,CAErG,IAAM,EAAO,EAAM,IAAU,GACvB,EAAc,EAAK,KAAK,EAC9B,GAAI,IAAgB,IAAM,EAAY,WAAW,GAAG,EAAG,MAAO,CAAE,MAAO,IAAA,GAAW,QAAS,CAAM,EAEjG,IAAM,EAAQ,EAAK,MAAM,CAAW,EACpC,GAAI,CAAC,EAAO,MAAO,CAAE,MAAO,IAAA,GAAW,QAAS,CAAM,EAEtD,IAAM,EAAM,EAAM,GAIZ,GAAQ,EAAM,IAAM,IAAI,QAAQ,QAAS,EAAE,EAC3C,EAA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ADP,CAGJ,MAAO,EACX,CAEA,SAAS,EAAe,EAAqB,CACzC,IAAI,EAAM,GACV,IAAK,IAAI,EAAI,EAAG,EAAI,EAAI,OAAQ,IAAK,CACjC,IAAM,EAAK,EAAI,GACf,GAAI,IAAO,MAAQ,IAAM,EAAI,OAAS,EAAG,CACrC,GAAO,EACP,QACJ,CACA,IAAM,EAAO,EAAI,EAAI,GAErB,OADA,IACQ,EAAR,CACI,IAAK,IACD,GAAO;EACP,MACJ,IAAK,IACD,GAAO,KACP,MACJ,IAAK,IACD,GAAO,IACP,MACJ,IAAK,KACD,GAAO,KACP,MACJ,IAAK,IACD,GAAO,IACP,MACJ,QAEI,GAAO,KAAK,GAAQ,IAC5B,CACJ,CACA,OAAO,CACX,CAYA,SAAgB,EAAW,EAAqC,CAC5D,IAAM,EAAQ,MAAM,QAAQ,EAAM,IAAI,EAAI,EAAM,KAAO,CAAC,EAAM,IAAI,EAC5D,EAAW,EAAM,UAAY,OAC7B,EAAW,EAAM,UAAY,GAC7B,EAAU,IAAI,IAEpB,IAAK,IAAM,KAAY,EAAO,CAC1B,IAAM,EAAM,EAAM,SAAS,EAAU,CAAQ,EAC7C,GAAI,IAAQ,IAAA,GAAW,CACnB,EAAU,kBAAkB,GAAU,EACtC,QACJ,CAEA,IAAM,EAAS,EAAY,CAAG,EAC9B,EAAa,UAAU,EAAS,IAAI,EAAO,KAAK,GAAG,EAAO,OAAS,EAAI,MAAQ,QAAQ,EACvF,IAAK,GAAM,CAAC,EAAK,KAAU,GAEnB,CADW,OAAO,UAAU,eAAe,KAAK,EAAM,WAAY,CAC5D,GAAK,KACX,EAAM,WAAW,GAAO,EACxB,EAAQ,IAAI,CAAG,EACf,EAAa,GAAG,EAAS,MAAM,GAAK,EAGhD,CAEA,OAAO,CACX"}
1
+ {"version":3,"file":"Dotenv.mjs","names":[],"sources":["../../src/Dotenv.ts"],"sourcesContent":["import { debugVerbose, debugWarn } from './Debug';\n\n/**\n * Public options for the internal `.env` loader. Mirrors the subset of dotenv's\n * `config()` options that envapt actually supports (no DOTENV_KEY, no quiet).\n * For debug output, use `Envapter.debug` (or the `ENVAPT_DEBUG` env var).\n *\n * @public\n */\nexport interface EnvFileOptions {\n /** Encoding for reading .env files. Defaults to 'utf8'. */\n encoding?: string;\n /** When true, later files override earlier ones (and existing processEnv values). Default false (first-wins). */\n override?: boolean;\n}\n\n/**\n * Internal call signature used by `EnvapterBase`. The `path` and `processEnv`\n * fields are managed by envapt and never user-supplied.\n * @internal\n */\nexport interface LoadDotenvInput extends EnvFileOptions {\n path: string | string[];\n processEnv: Record<string, string>;\n // Injected so the loader stays free of `node:fs`. Returns `undefined` when the file is absent.\n readFile(path: string, encoding: string): string | undefined;\n}\n\n// Matches: optional `export`, KEY name, optional whitespace, `=`, optional whitespace, value tail.\n// Multi-line quoted values are handled by re-buffering subsequent lines below.\n// Bounded by anchors with linear-time quantifiers; no catastrophic backtracking risk -- justified\n// eslint-disable-next-line security/detect-unsafe-regex\nconst KEY_LINE_RE = /^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=(.*)$/u;\n\n/**\n * Parse a `.env` text blob into a `Map<string, string>`.\n *\n * Supported syntax:\n * - `KEY=value` and `export KEY=value`\n * - blank lines and full-line `# comments`\n * - single-quoted `'literal'` values (no escape interpretation)\n * - double-quoted `\"value\"` values (interprets `\\n`, `\\r`, `\\t`, `\\\\`, `\\\"`)\n * - backtick-quoted values (literal, like single quotes)\n * - quoted values may span multiple lines\n * - inline `# comment` after an unquoted value (requires whitespace before `#`)\n * - empty values resolve to `\"\"`\n *\n * Mirrors dotenv's quirk where unescaped inner quotes inside a quoted value\n * are tolerated by greedy-matching to the rightmost matching quote on the\n * (possibly multi-line) value buffer. This is what lets a value like\n * `JSON=\"{\"name\":\"x\"}\"` round-trip without escaping.\n *\n * Does NOT perform `${VAR}` expansion — envapt's `Parser` handles that downstream.\n * @internal\n */\nexport function parseDotenv(src: string): Map<string, string> {\n const out = new Map<string, string>();\n const lines = src.split(/\\r?\\n/u);\n\n for (let i = 0; i < lines.length; i++) {\n const consumed = parseEntry(lines, i);\n i = consumed.endLine;\n if (consumed.entry) out.set(consumed.entry.key, consumed.entry.value);\n }\n\n return out;\n}\n\ninterface ParsedEntry {\n key: string;\n value: string;\n}\n\nfunction parseEntry(lines: string[], start: number): { entry: ParsedEntry | undefined; endLine: number } {\n /* v8 ignore next -- @preserve caller bounds-checks start so this never falls back */\n const line = lines[start] ?? '';\n const trimmedLine = line.trim();\n if (trimmedLine === '' || trimmedLine.startsWith('#')) return { entry: undefined, endLine: start };\n\n const match = line.match(KEY_LINE_RE);\n if (!match) return { entry: undefined, endLine: start };\n\n const key = match[1] as string;\n // Drop only leading whitespace before the value; trailing whitespace and inline comments\n // are dealt with below depending on whether the value is quoted.\n /* v8 ignore next -- @preserve regex group 2 always matches via `(.*)`, fallback is defensive */\n const rest = (match[2] ?? '').replace(/^\\s+/u, '');\n const firstChar = rest[0];\n\n if (firstChar === '\"' || firstChar === \"'\" || firstChar === '`') {\n const consumed = consumeQuotedValue(rest, lines, start, firstChar);\n return { entry: { key, value: consumed.value }, endLine: consumed.endLine };\n }\n\n return { entry: { key, value: stripInlineComment(rest) }, endLine: start };\n}\n\nfunction consumeQuotedValue(\n firstLineRest: string,\n lines: string[],\n startLine: number,\n quote: string\n): { value: string; endLine: number } {\n let buffer = firstLineRest;\n let cursor = startLine;\n let closeIdx = findLastUnescapedQuote(buffer, quote);\n\n while (closeIdx < 0 && cursor < lines.length - 1) {\n cursor++;\n /* v8 ignore next -- @preserve cursor is bounded by the while condition above */\n buffer += `\\n${lines[cursor] ?? ''}`;\n closeIdx = findLastUnescapedQuote(buffer, quote);\n }\n\n const inner = closeIdx > 0 ? buffer.slice(1, closeIdx) : buffer.slice(1);\n return { value: quote === '\"' ? unescapeDouble(inner) : inner, endLine: cursor };\n}\n\nfunction stripInlineComment(value: string): string {\n const hashIdx = findInlineCommentStart(value);\n const stripped = hashIdx === -1 ? value : value.slice(0, hashIdx);\n return stripped.trimEnd();\n}\n\nfunction findInlineCommentStart(value: string): number {\n for (let i = 0; i < value.length; i++) {\n if (value[i] === '#' && (i === 0 || /\\s/u.test(value[i - 1] as string))) return i;\n }\n return -1;\n}\n\n/**\n * Find the rightmost matching closing quote in `buffer` (skipping index 0 which is the\n * opening quote). For `\"`, a quote preceded by an odd number of backslashes is escaped\n * and ignored. Single and backtick quotes do not unescape.\n */\nfunction findLastUnescapedQuote(buffer: string, quote: string): number {\n for (let i = buffer.length - 1; i > 0; i--) {\n if (buffer[i] !== quote) continue;\n if (quote === '\"') {\n let backslashes = 0;\n let k = i - 1;\n while (k >= 0 && buffer[k] === '\\\\') {\n backslashes++;\n k--;\n }\n if (backslashes % 2 === 1) continue; // escaped\n }\n return i;\n }\n return -1;\n}\n\nfunction unescapeDouble(raw: string): string {\n let out = '';\n for (let i = 0; i < raw.length; i++) {\n const ch = raw[i];\n if (ch !== '\\\\' || i === raw.length - 1) {\n out += ch;\n continue;\n }\n const next = raw[i + 1];\n i++;\n switch (next) {\n case 'n':\n out += '\\n';\n break;\n case 'r':\n out += '\\r';\n break;\n case 't':\n out += '\\t';\n break;\n case '\\\\':\n out += '\\\\';\n break;\n case '\"':\n out += '\"';\n break;\n default:\n /* v8 ignore next -- @preserve `next` is always defined when this branch is reached (guarded above) */\n out += `\\\\${next ?? ''}`;\n }\n }\n return out;\n}\n\n/**\n * Load one or more `.env` files into a target `processEnv` map. Mirrors the\n * subset of dotenv's `config()` semantics that envapt depends on: first-wins\n * across multiple paths by default, optional `override: true`, optional\n * non-UTF8 encoding, missing files are skipped silently.\n *\n * Returns the set of keys actually written into `input.processEnv`. Skipped\n * collisions (under default `override: false`) are NOT included.\n * @internal\n */\nexport function loadDotenv(input: LoadDotenvInput): Set<string> {\n const paths = Array.isArray(input.path) ? input.path : [input.path];\n const encoding = input.encoding ?? 'utf8';\n const override = input.override ?? false;\n const written = new Set<string>();\n\n for (const filePath of paths) {\n const src = input.readFile(filePath, encoding);\n if (src === undefined) {\n debugWarn(`could not read ${filePath}`);\n continue;\n }\n\n const parsed = parseDotenv(src);\n debugVerbose(`loaded ${filePath}: ${parsed.size} ${parsed.size === 1 ? 'key' : 'keys'}`);\n for (const [key, value] of parsed) {\n const exists = Object.prototype.hasOwnProperty.call(input.processEnv, key);\n if (!exists || override) {\n input.processEnv[key] = value;\n written.add(key);\n debugVerbose(`${filePath} -> ${key}`);\n }\n }\n }\n\n return written;\n}\n"],"mappings":"0DAgCA,MAAM,EAAc,uDAuBpB,SAAgB,EAAY,EAAkC,CAC1D,IAAM,EAAM,IAAI,IACV,EAAQ,EAAI,MAAM,QAAQ,EAEhC,IAAK,IAAI,EAAI,EAAG,EAAI,EAAM,OAAQ,IAAK,CACnC,IAAM,EAAW,EAAW,EAAO,CAAC,EACpC,EAAI,EAAS,QACT,EAAS,OAAO,EAAI,IAAI,EAAS,MAAM,IAAK,EAAS,MAAM,KAAK,CACxE,CAEA,OAAO,CACX,CAOA,SAAS,EAAW,EAAiB,EAAoE,CAErG,IAAM,EAAO,EAAM,IAAU,GACvB,EAAc,EAAK,KAAK,EAC9B,GAAI,IAAgB,IAAM,EAAY,WAAW,GAAG,EAAG,MAAO,CAAE,MAAO,IAAA,GAAW,QAAS,CAAM,EAEjG,IAAM,EAAQ,EAAK,MAAM,CAAW,EACpC,GAAI,CAAC,EAAO,MAAO,CAAE,MAAO,IAAA,GAAW,QAAS,CAAM,EAEtD,IAAM,EAAM,EAAM,GAIZ,GAAQ,EAAM,IAAM,GAAA,CAAI,QAAQ,QAAS,EAAE,EAC3C,EAAY,EAAK,GAEvB,GAAI,IAAc,KAAO,IAAc,KAAO,IAAc,IAAK,CAC7D,IAAM,EAAW,EAAmB,EAAM,EAAO,EAAO,CAAS,EACjE,MAAO,CAAE,MAAO,CAAE,MAAK,MAAO,EAAS,KAAM,EAAG,QAAS,EAAS,OAAQ,CAC9E,CAEA,MAAO,CAAE,MAAO,CAAE,MAAK,MAAO,EAAmB,CAAI,CA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B,OADA,IACQ,EAAR,CACI,IAAK,IACD,GAAO;EACP,MACJ,IAAK,IACD,GAAO,KACP,MACJ,IAAK,IACD,GAAO,IACP,MACJ,IAAK,KACD,GAAO,KACP,MACJ,IAAK,IACD,GAAO,IACP,MACJ,QAEI,GAAO,KAAK,GAAQ,IAC5B,CACJ,CACA,OAAO,CACX,CAYA,SAAgB,EAAW,EAAqC,CAC5D,IAAM,EAAQ,MAAM,QAAQ,EAAM,IAAI,EAAI,EAAM,KAAO,CAAC,EAAM,IAAI,EAC5D,EAAW,EAAM,UAAY,OAC7B,EAAW,EAAM,UAAY,GAC7B,EAAU,IAAI,IAEpB,IAAK,IAAM,KAAY,EAAO,CAC1B,IAAM,EAAM,EAAM,SAAS,EAAU,CAAQ,EAC7C,GAAI,IAAQ,IAAA,GAAW,CACnB,EAAU,kBAAkB,GAAU,EACtC,QACJ,CAEA,IAAM,EAAS,EAAY,CAAG,EAC9B,EAAa,UAAU,EAAS,IAAI,EAAO,KAAK,GAAG,EAAO,OAAS,EAAI,MAAQ,QAAQ,EACvF,IAAK,GAAM,CAAC,EAAK,KAAU,GAEnB,CADW,OAAO,UAAU,eAAe,KAAK,EAAM,WAAY,CAC5D,GAAK,KACX,EAAM,WAAW,GAAO,EACxB,EAAQ,IAAI,CAAG,EACf,EAAa,GAAG,EAAS,MAAM,GAAK,EAGhD,CAEA,OAAO,CACX"}
@@ -1 +1 @@
1
- {"version":3,"file":"Validators.mjs","names":[],"sources":["../../src/Validators.ts"],"sourcesContent":["// Import the converter modules directly, not via the `./converters` barrel: that barrel pulls in\n// ValueConverter, which imports this Validator, so a barrel import here would cycle.\nimport { isArrayOf } from './converters/Converters';\nimport { ListOfBuiltInConverters, BuiltInConverterTypeCheckers } from './converters/ListOfBuiltInConverters';\nimport { EnvaptError, EnvaptErrorCodes } from './Error';\n\nimport type { ArrayOf, ConverterToken } from './converters/Converters';\nimport type { EnvFileOptions } from './Dotenv';\nimport type { StandardSchemaV1 } from './StandardSchema';\nimport type { BuiltInConverter, ConverterFunction, EnvaptConverter } from './types';\n\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class -- cohesive dispatch of stateless type guards, same shape as BuiltInConverters\nexport class Validator {\n /**\n * Check if a value is a built-in scalar converter token\n */\n static isBuiltInConverter<TFallback>(value: EnvaptConverter<TFallback>): value is BuiltInConverter {\n if (typeof value === 'string') return ListOfBuiltInConverters.includes(value);\n return false;\n }\n\n /**\n * Check if a value is an `ArrayOf<...>` token produced by {@link Converters.array}.\n */\n static isArrayConverter(value: unknown): value is ArrayOf {\n return isArrayOf(value);\n }\n\n // Structural check: `version === 1` + callable `validate` is the minimum dispatchable\n // shape per the Standard Schema spec.\n static isStandardSchema(value: unknown): value is StandardSchemaV1 {\n if (typeof value !== 'object' || value === null) return false;\n if (!('~standard' in value)) return false;\n const slot = value['~standard'];\n if (typeof slot !== 'object' || slot === null) return false;\n const props = slot as { version?: unknown; validate?: unknown };\n return props.version === 1 && typeof props.validate === 'function';\n }\n\n static customConvertor<TFallback>(\n converter: EnvaptConverter<TFallback>\n ): asserts converter is ConverterFunction<TFallback> {\n if (typeof converter !== 'function') {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidCustomConverter,\n `Custom converter must be a function, got ${typeof converter}.`\n );\n }\n }\n\n /**\n * Runtime validation that the `ArrayOf<...>` configuration is well-formed.\n */\n static arrayConverter(value: unknown): asserts value is ArrayOf {\n if (!isArrayOf(value)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidArrayConverterType,\n 'Expected an ArrayOf<...> token produced by Converters.array(...)'\n );\n }\n\n if (typeof value.delimiter !== 'string' || value.delimiter.length === 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingDelimiter,\n `ArrayOf<...> requires a non-empty string delimiter, got ${typeof value.delimiter}`\n );\n }\n\n const elementOf = value.of;\n const isScalar = typeof elementOf === 'string' && ListOfBuiltInConverters.includes(elementOf);\n const isCustomFn = typeof elementOf === 'function';\n if (!isScalar && !isCustomFn) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidArrayConverterType,\n `ArrayOf<...> element (\"of\") must be a built-in scalar token or a function, got ${typeof elementOf}`\n );\n }\n }\n\n /**\n * Validate that a string is a valid built-in scalar converter token\n */\n static builtInConverter(value: unknown): asserts value is BuiltInConverter {\n if (typeof value !== 'string') {\n throw new EnvaptError(EnvaptErrorCodes.InvalidConverterType, `Expected string, got ${typeof value}`);\n }\n\n if (!ListOfBuiltInConverters.includes(value as ConverterToken)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidBuiltInConverter,\n `\"${value}\" is not a valid converter type. Valid types are: ${ListOfBuiltInConverters.join(',')}`\n );\n }\n }\n\n /**\n * Validate that fallback type matches the converter's return type for built-in converters\n */\n static validateBuiltInConverterFallback(converter: BuiltInConverter, fallback: unknown): void {\n const typeChecker = BuiltInConverterTypeCheckers[converter];\n if (!typeChecker(fallback)) {\n throw new EnvaptError(\n EnvaptErrorCodes.FallbackConverterTypeMismatch,\n `Fallback type does not match converter \"${converter}\". Expected ${converter} compatible type.`\n );\n }\n }\n\n /**\n * Validate that all elements in an array fallback have consistent types\n */\n static validateArrayFallbackElementTypes(fallback: unknown[]): void {\n if (fallback.length === 0) return;\n\n const firstElementType = typeof fallback[0];\n const hasInconsistentTypes = fallback.some((element, index) => {\n if (index === 0) return false;\n return typeof element !== firstElementType;\n });\n\n if (hasInconsistentTypes) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n `All elements in array fallback must have the same type. Found mixed types.`\n );\n }\n }\n\n /**\n * Validate that an `ArrayOf<...>` element converter matches the runtime types of its\n * fallback elements. For `Converters.Time` arrays the element-time-string format is also\n * checked here.\n */\n static validateArrayConverterElementTypeMatch(elementOf: ArrayOf['of'], fallback: unknown[]): void {\n if (fallback.length === 0) return;\n\n if (typeof elementOf === 'function') {\n // Custom element converters can return anything; we can't statically validate the fallback shape.\n return;\n }\n\n const elementToken = elementOf;\n\n // Time array fallbacks may be number[] OR string[] (TimeFallback[]).\n if (elementToken === 'time') {\n const everyNumber = fallback.every((v) => typeof v === 'number');\n const everyString = fallback.every((v) => typeof v === 'string');\n if (!everyNumber && !everyString) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n 'Time array fallback must be all numbers or all time-string entries.'\n );\n }\n return;\n }\n\n const typeChecker = BuiltInConverterTypeCheckers[elementToken];\n const firstElement = fallback[0];\n if (!typeChecker(firstElement)) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n `Array converter type \"${elementToken}\" does not match fallback element type. Expected ${elementToken} compatible elements.`\n );\n }\n }\n\n /**\n * Check if a value is a primitive constructor\n */\n static isPrimitiveConstructor(\n value: unknown\n ): value is typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol {\n return value === String || value === Number || value === Boolean || value === BigInt || value === Symbol;\n }\n\n /**\n * Safely coerce a fallback value using a primitive constructor\n */\n static coercePrimitiveFallback<CoercedType>(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): CoercedType {\n if (this.isCorrectPrimitiveType(converter, fallback)) return fallback as CoercedType;\n return this.performPrimitiveCoercion<CoercedType>(converter, fallback);\n }\n\n private static isCorrectPrimitiveType(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): boolean {\n if (converter === String && typeof fallback === 'string') return true;\n if (converter === Number && typeof fallback === 'number') return true;\n if (converter === Boolean && typeof fallback === 'boolean') return true;\n if (converter === BigInt && typeof fallback === 'bigint') return true;\n if (converter === Symbol && typeof fallback === 'symbol') return true;\n return false;\n }\n\n private static performPrimitiveCoercion<CoercedType>(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): CoercedType {\n try {\n if (converter === String) return String(fallback) as CoercedType;\n if (converter === Number) return Number(fallback) as CoercedType;\n if (converter === Boolean) return Boolean(fallback) as CoercedType;\n if (converter === BigInt) return BigInt(fallback as string | number | bigint) as CoercedType;\n /* v8 ignore next -- @preserve */\n if (converter === Symbol) return Symbol.for(String(fallback)) as CoercedType;\n } catch (error) {\n throw new EnvaptError(\n EnvaptErrorCodes.PrimitiveCoercionFailed,\n `Failed to coerce fallback value using ${converter.name}: ${(error as Error).message}`\n );\n }\n\n /* v8 ignore next -- @preserve */\n throw new EnvaptError(\n EnvaptErrorCodes.PrimitiveCoercionFailed,\n `Unknown primitive converter: ${converter.name}`\n );\n }\n\n /**\n * Reject non-boolean inputs to `Envapter.syncProcessEnv` so a truthy typo\n * (`'true'`, `1`, etc.) does not silently enable the mirror.\n */\n static validateSyncProcessEnv(value: unknown): asserts value is boolean {\n if (typeof value !== 'boolean') {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Envapter.syncProcessEnv must be a boolean, got ${typeof value}.`\n );\n }\n }\n\n /**\n * Make sure the user hasn't provided prohibited options in their dotenv config\n */\n static validateEnvFileOptions(config: object): config is EnvFileOptions {\n const validKeys = new Set(['encoding', 'override']);\n const invalidKeys = Object.keys(config).filter((key) => !validKeys.has(key));\n\n if (invalidKeys.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Invalid envFileOptions: ${invalidKeys.join(', ')}. Allowed options: ${Array.from(validKeys).join(', ')}. For debug output, use Envapter.debug or the ENVAPT_DEBUG env var.`\n );\n }\n\n return true;\n }\n\n // Existence is probed through the caller-supplied `fileExists` (backed by the bound source) so\n // this stays free of `node:fs`.\n static validateEnvFilesExist(paths: string[], fileExists: (path: string) => boolean): void {\n const missing = paths.filter((p) => !fileExists(p));\n\n if (missing.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.EnvFilesNotFound,\n `Environment file not found at path: ${missing.join(', ')}`\n );\n }\n }\n}\n"],"mappings":"uNAYA,IAAa,EAAb,KAAuB,CAInB,OAAO,mBAA8B,EAA8D,CAE/F,OADI,OAAO,G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OAAO,CAAoC,EAE5E,GAAI,IAAc,OAAQ,OAAO,OAAO,IAAI,OAAO,CAAQ,CAAC,CAChE,OAAS,EAAO,CACZ,MAAM,IAAI,EAAA,IAEN,yCAAyC,EAAU,KAAK,IAAK,EAAgB,SACjF,CACJ,CAGA,MAAM,IAAI,EAAA,IAEN,gCAAgC,EAAU,MAC9C,CACJ,CAMA,OAAO,uBAAuB,EAA0C,CACpE,GAAI,OAAO,GAAU,UACjB,MAAM,IAAI,EAAA,IAEN,kDAAkD,OAAO,EAAM,EACnE,CAER,CAKA,OAAO,uBAAuB,EAA0C,CACpE,IAAM,EAAY,IAAI,IAAI,CAAC,WAAY,UAAU,CAAC,EAC5C,EAAc,OAAO,KAAK,CAAM,EAAE,OAAQ,GAAQ,CAAC,EAAU,IAAI,CAAG,CAAC,EAE3E,GAAI,EAAY,OAAS,EACrB,MAAM,IAAI,EAAA,IAEN,2BAA2B,EAAY,KAAK,IAAI,EAAE,qBAAqB,MAAM,KAAK,CAAS,EAAE,KAAK,IAAI,EAAE,oEAC5G,EAGJ,MAAO,EACX,CAIA,OAAO,sBAAsB,EAAiB,EAA6C,CACvF,IAAM,EAAU,EAAM,OAAQ,GAAM,CAAC,EAAW,CAAC,CAAC,EAElD,GAAI,EAAQ,OAAS,EACjB,MAAM,IAAI,EAAA,IAEN,uCAAuC,EAAQ,KAAK,IAAI,GAC5D,CAER,CACJ"}
1
+ {"version":3,"file":"Validators.mjs","names":[],"sources":["../../src/Validators.ts"],"sourcesContent":["// Import the converter modules directly, not via the `./converters` barrel: that barrel pulls in\n// ValueConverter, which imports this Validator, so a barrel import here would cycle.\nimport { isArrayOf } from './converters/Converters';\nimport { ListOfBuiltInConverters, BuiltInConverterTypeCheckers } from './converters/ListOfBuiltInConverters';\nimport { EnvaptError, EnvaptErrorCodes } from './Error';\n\nimport type { ArrayOf, ConverterToken } from './converters/Converters';\nimport type { EnvFileOptions } from './Dotenv';\nimport type { StandardSchemaV1 } from './StandardSchema';\nimport type { BuiltInConverter, ConverterFunction, EnvaptConverter } from './types';\n\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class -- cohesive dispatch of stateless type guards, same shape as BuiltInConverters\nexport class Validator {\n /**\n * Check if a value is a built-in scalar converter token\n */\n static isBuiltInConverter<TFallback>(value: EnvaptConverter<TFallback>): value is BuiltInConverter {\n if (typeof value === 'string') return ListOfBuiltInConverters.includes(value);\n return false;\n }\n\n /**\n * Check if a value is an `ArrayOf<...>` token produced by {@link Converters.array}.\n */\n static isArrayConverter(value: unknown): value is ArrayOf {\n return isArrayOf(value);\n }\n\n // Structural check: `version === 1` + callable `validate` is the minimum dispatchable\n // shape per the Standard Schema spec.\n static isStandardSchema(value: unknown): value is StandardSchemaV1 {\n if (typeof value !== 'object' || value === null) return false;\n if (!('~standard' in value)) return false;\n const slot = value['~standard'];\n if (typeof slot !== 'object' || slot === null) return false;\n const props = slot as { version?: unknown; validate?: unknown };\n return props.version === 1 && typeof props.validate === 'function';\n }\n\n static customConvertor<TFallback>(\n converter: EnvaptConverter<TFallback>\n ): asserts converter is ConverterFunction<TFallback> {\n if (typeof converter !== 'function') {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidCustomConverter,\n `Custom converter must be a function, got ${typeof converter}.`\n );\n }\n }\n\n /**\n * Runtime validation that the `ArrayOf<...>` configuration is well-formed.\n */\n static arrayConverter(value: unknown): asserts value is ArrayOf {\n if (!isArrayOf(value)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidArrayConverterType,\n 'Expected an ArrayOf<...> token produced by Converters.array(...)'\n );\n }\n\n if (typeof value.delimiter !== 'string' || value.delimiter.length === 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingDelimiter,\n `ArrayOf<...> requires a non-empty string delimiter, got ${typeof value.delimiter}`\n );\n }\n\n const elementOf = value.of;\n const isScalar = typeof elementOf === 'string' && ListOfBuiltInConverters.includes(elementOf);\n const isCustomFn = typeof elementOf === 'function';\n if (!isScalar && !isCustomFn) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidArrayConverterType,\n `ArrayOf<...> element (\"of\") must be a built-in scalar token or a function, got ${typeof elementOf}`\n );\n }\n }\n\n /**\n * Validate that a string is a valid built-in scalar converter token\n */\n static builtInConverter(value: unknown): asserts value is BuiltInConverter {\n if (typeof value !== 'string') {\n throw new EnvaptError(EnvaptErrorCodes.InvalidConverterType, `Expected string, got ${typeof value}`);\n }\n\n if (!ListOfBuiltInConverters.includes(value as ConverterToken)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidBuiltInConverter,\n `\"${value}\" is not a valid converter type. Valid types are: ${ListOfBuiltInConverters.join(',')}`\n );\n }\n }\n\n /**\n * Validate that fallback type matches the converter's return type for built-in converters\n */\n static validateBuiltInConverterFallback(converter: BuiltInConverter, fallback: unknown): void {\n const typeChecker = BuiltInConverterTypeCheckers[converter];\n if (!typeChecker(fallback)) {\n throw new EnvaptError(\n EnvaptErrorCodes.FallbackConverterTypeMismatch,\n `Fallback type does not match converter \"${converter}\". Expected ${converter} compatible type.`\n );\n }\n }\n\n /**\n * Validate that all elements in an array fallback have consistent types\n */\n static validateArrayFallbackElementTypes(fallback: unknown[]): void {\n if (fallback.length === 0) return;\n\n const firstElementType = typeof fallback[0];\n const hasInconsistentTypes = fallback.some((element, index) => {\n if (index === 0) return false;\n return typeof element !== firstElementType;\n });\n\n if (hasInconsistentTypes) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n `All elements in array fallback must have the same type. Found mixed types.`\n );\n }\n }\n\n /**\n * Validate that an `ArrayOf<...>` element converter matches the runtime types of its\n * fallback elements. For `Converters.Time` arrays the element-time-string format is also\n * checked here.\n */\n static validateArrayConverterElementTypeMatch(elementOf: ArrayOf['of'], fallback: unknown[]): void {\n if (fallback.length === 0) return;\n\n if (typeof elementOf === 'function') {\n // Custom element converters can return anything; we can't statically validate the fallback shape.\n return;\n }\n\n const elementToken = elementOf;\n\n // Time array fallbacks may be number[] OR string[] (TimeFallback[]).\n if (elementToken === 'time') {\n const everyNumber = fallback.every((v) => typeof v === 'number');\n const everyString = fallback.every((v) => typeof v === 'string');\n if (!everyNumber && !everyString) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n 'Time array fallback must be all numbers or all time-string entries.'\n );\n }\n return;\n }\n\n const typeChecker = BuiltInConverterTypeCheckers[elementToken];\n const firstElement = fallback[0];\n if (!typeChecker(firstElement)) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayFallbackElementTypeMismatch,\n `Array converter type \"${elementToken}\" does not match fallback element type. Expected ${elementToken} compatible elements.`\n );\n }\n }\n\n /**\n * Check if a value is a primitive constructor\n */\n static isPrimitiveConstructor(\n value: unknown\n ): value is typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol {\n return value === String || value === Number || value === Boolean || value === BigInt || value === Symbol;\n }\n\n /**\n * Safely coerce a fallback value using a primitive constructor\n */\n static coercePrimitiveFallback<CoercedType>(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): CoercedType {\n if (this.isCorrectPrimitiveType(converter, fallback)) return fallback as CoercedType;\n return this.performPrimitiveCoercion<CoercedType>(converter, fallback);\n }\n\n private static isCorrectPrimitiveType(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): boolean {\n if (converter === String && typeof fallback === 'string') return true;\n if (converter === Number && typeof fallback === 'number') return true;\n if (converter === Boolean && typeof fallback === 'boolean') return true;\n if (converter === BigInt && typeof fallback === 'bigint') return true;\n if (converter === Symbol && typeof fallback === 'symbol') return true;\n return false;\n }\n\n private static performPrimitiveCoercion<CoercedType>(\n converter: typeof String | typeof Number | typeof Boolean | typeof BigInt | typeof Symbol,\n fallback: unknown\n ): CoercedType {\n try {\n if (converter === String) return String(fallback) as CoercedType;\n if (converter === Number) return Number(fallback) as CoercedType;\n if (converter === Boolean) return Boolean(fallback) as CoercedType;\n if (converter === BigInt) return BigInt(fallback as string | number | bigint) as CoercedType;\n /* v8 ignore next -- @preserve */\n if (converter === Symbol) return Symbol.for(String(fallback)) as CoercedType;\n } catch (error) {\n throw new EnvaptError(\n EnvaptErrorCodes.PrimitiveCoercionFailed,\n `Failed to coerce fallback value using ${converter.name}: ${(error as Error).message}`\n );\n }\n\n /* v8 ignore next -- @preserve */\n throw new EnvaptError(\n EnvaptErrorCodes.PrimitiveCoercionFailed,\n `Unknown primitive converter: ${converter.name}`\n );\n }\n\n /**\n * Reject non-boolean inputs to `Envapter.syncProcessEnv` so a truthy typo\n * (`'true'`, `1`, etc.) does not silently enable the mirror.\n */\n static validateSyncProcessEnv(value: unknown): asserts value is boolean {\n if (typeof value !== 'boolean') {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Envapter.syncProcessEnv must be a boolean, got ${typeof value}.`\n );\n }\n }\n\n /**\n * Make sure the user hasn't provided prohibited options in their dotenv config\n */\n static validateEnvFileOptions(config: object): config is EnvFileOptions {\n const validKeys = new Set(['encoding', 'override']);\n const invalidKeys = Object.keys(config).filter((key) => !validKeys.has(key));\n\n if (invalidKeys.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Invalid envFileOptions: ${invalidKeys.join(', ')}. Allowed options: ${Array.from(validKeys).join(', ')}. For debug output, use Envapter.debug or the ENVAPT_DEBUG env var.`\n );\n }\n\n return true;\n }\n\n // Existence is probed through the caller-supplied `fileExists` (backed by the bound source) so\n // this stays free of `node:fs`.\n static validateEnvFilesExist(paths: string[], fileExists: (path: string) => boolean): void {\n const missing = paths.filter((p) => !fileExists(p));\n\n if (missing.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.EnvFilesNotFound,\n `Environment file not found at path: ${missing.join(', ')}`\n );\n }\n }\n}\n"],"mappings":"uNAYA,IAAa,EAAb,KAAuB,CAInB,OAAO,mBAA8B,EAA8D,CAE/F,OADI,OAAO,GAAU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O,CAAoC,EAE5E,GAAI,IAAc,OAAQ,OAAO,OAAO,IAAI,OAAO,CAAQ,CAAC,CAChE,OAAS,EAAO,CACZ,MAAM,IAAI,EAAA,IAEN,yCAAyC,EAAU,KAAK,IAAK,EAAgB,SACjF,CACJ,CAGA,MAAM,IAAI,EAAA,IAEN,gCAAgC,EAAU,MAC9C,CACJ,CAMA,OAAO,uBAAuB,EAA0C,CACpE,GAAI,OAAO,GAAU,UACjB,MAAM,IAAI,EAAA,IAEN,kDAAkD,OAAO,EAAM,EACnE,CAER,CAKA,OAAO,uBAAuB,EAA0C,CACpE,IAAM,EAAY,IAAI,IAAI,CAAC,WAAY,UAAU,CAAC,EAC5C,EAAc,OAAO,KAAK,CAAM,CAAC,CAAC,OAAQ,GAAQ,CAAC,EAAU,IAAI,CAAG,CAAC,EAE3E,GAAI,EAAY,OAAS,EACrB,MAAM,IAAI,EAAA,IAEN,2BAA2B,EAAY,KAAK,IAAI,EAAE,qBAAqB,MAAM,KAAK,CAAS,CAAC,CAAC,KAAK,IAAI,EAAE,oEAC5G,EAGJ,MAAO,EACX,CAIA,OAAO,sBAAsB,EAAiB,EAA6C,CACvF,IAAM,EAAU,EAAM,OAAQ,GAAM,CAAC,EAAW,CAAC,CAAC,EAElD,GAAI,EAAQ,OAAS,EACjB,MAAM,IAAI,EAAA,IAEN,uCAAuC,EAAQ,KAAK,IAAI,GAC5D,CAER,CACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"BuiltInConverters.mjs","names":["converter"],"sources":["../../../src/converters/BuiltInConverters.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\n\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\n\nimport type { ArrayOf, CustomElementConverter } from './Converters';\nimport type {\n BuiltInConverter,\n BuiltInConverterFunction,\n JsonValue,\n MapOfConverterFunctions,\n TimeFallback,\n TimeUnit\n} from '../types';\n\nconst MS_PER_SECOND = 1000;\nconst SECONDS_PER_MINUTE = 60;\nconst MINUTES_PER_HOUR = 60;\nconst HOURS_PER_DAY = 24;\nconst DAYS_PER_WEEK = 7;\nconst MS_PER_MINUTE = SECONDS_PER_MINUTE * MS_PER_SECOND;\nconst MS_PER_HOUR = MINUTES_PER_HOUR * MS_PER_MINUTE;\nconst MS_PER_DAY = HOURS_PER_DAY * MS_PER_HOUR;\nconst MS_PER_WEEK = DAYS_PER_WEEK * MS_PER_DAY;\n\nconst TIME_UNIT_MS: Record<TimeUnit, number> = {\n ms: 1,\n s: MS_PER_SECOND,\n m: MS_PER_MINUTE,\n h: MS_PER_HOUR,\n d: MS_PER_DAY,\n w: MS_PER_WEEK\n};\n\nconst TIME_LOOSE_RE = new RegExp(String.raw`^(\\d+(?:\\.\\d+)?)(ms|s|m|h|d|w)?$`, 'u');\nconst TIME_STRICT_RE = new RegExp(String.raw`^(\\d+(?:\\.\\d+)?)(ms|s|m|h|d|w)$`, 'u');\n\n/**\n * Parse a time string (e.g. `\"30s\"`, `\"1.5h\"`) into milliseconds.\n *\n * @param input - The string to parse.\n * @param strict - When `true`, require an explicit unit (used for fallback strings).\n * When `false` (default), treat a missing unit as `ms` (used for raw env values). Both allow decimals.\n * @returns The duration in milliseconds, or `undefined` if the input does not match the expected format.\n * @internal\n */\nfunction parseTimeString(input: string, strict = false): number | undefined {\n const match = input.match(strict ? TIME_STRICT_RE : TIME_LOOSE_RE);\n if (!match) return undefined;\n\n const [, numStr, capturedUnit] = match;\n if (!numStr) return undefined;\n\n const value = Number.parseFloat(numStr);\n if (Number.isNaN(value)) return undefined;\n\n const unit = (capturedUnit ?? 'ms') as TimeUnit;\n return value * TIME_UNIT_MS[unit];\n}\n\n/**\n * Built-in converter implementations\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class -- dispatch-table helper, the documented exception to the no-static-class rule\nexport class BuiltInConverters {\n static string(raw: string, _fallback?: string): string | undefined {\n return String(raw);\n }\n\n static number(raw: string, fallback?: number): number | undefined {\n const parsed = Number(raw);\n return Number.isNaN(parsed) ? fallback : parsed;\n }\n\n static boolean(raw: string, fallback?: boolean): boolean | undefined {\n const lower = raw.toLowerCase().trim();\n\n const truthyValues = ['1', 'yes', 'true', 'on'];\n const falsyValues = ['0', 'no', 'false', 'off'];\n\n if (truthyValues.includes(lower)) return true;\n if (falsyValues.includes(lower)) return false;\n return fallback;\n }\n\n static bigint(raw: string, fallback?: bigint): bigint | undefined {\n try {\n return BigInt(raw);\n } catch {\n return fallback;\n }\n }\n\n static symbol(raw: string, fallback?: symbol): symbol | undefined {\n try {\n return raw ? Symbol.for(raw) : fallback;\n } catch {\n return fallback;\n }\n }\n\n static integer(raw: string, fallback?: number): number | undefined {\n const parsed = Number.parseInt(raw, 10);\n return Number.isNaN(parsed) ? fallback : parsed;\n }\n\n static float(raw: string, fallback?: number): number | undefined {\n const parsed = Number.parseFloat(raw);\n return Number.isNaN(parsed) ? fallback : parsed;\n }\n\n static json(raw: string, fallback?: JsonValue): JsonValue | undefined {\n try {\n return JSON.parse(raw) as JsonValue;\n } catch {\n return fallback;\n }\n }\n\n static url(raw: string, fallback?: URL): URL | undefined {\n try {\n return new URL(raw);\n } catch {\n return fallback;\n }\n }\n\n static regexp(raw: string, fallback?: RegExp): RegExp | undefined {\n try {\n // Handle flags if provided in format: /pattern/flags\n const match = raw.match(new RegExp(String.raw`^\\/(.+)\\/([gimsuvy]*)$`));\n if (match) return new RegExp(match[1] as string, match[2]);\n\n return new RegExp(raw);\n } catch {\n return fallback;\n }\n }\n\n static date(raw: string, fallback?: Date): Date | undefined {\n // Try parsing as timestamp first (if it's all digits)\n if (new RegExp(String.raw`^\\d+$`).test(raw)) {\n const timestamp = parseInt(raw, 10);\n const parsed = new Date(timestamp);\n return Number.isNaN(parsed.getTime()) ? fallback : parsed;\n }\n\n // Only accept ISO 8601 date strings (strict format)\n const isoRegex = new RegExp(String.raw`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{3})?Z$`, 'u');\n if (!isoRegex.test(raw)) return fallback;\n\n const parsed = new Date(raw);\n return Number.isNaN(parsed.getTime()) ? fallback : parsed;\n }\n\n static time(raw: string, fallback?: TimeFallback): number | undefined {\n const parsedRaw = parseTimeString(raw);\n if (parsedRaw !== undefined) return parsedRaw;\n\n // Raw didn't parse so apply fallback\n if (typeof fallback === 'number') return fallback;\n if (typeof fallback === 'string') {\n // A string fallback must name a unit; a unitless number is expressed as a number fallback, not a string.\n const parsedFallback = parseTimeString(fallback, true);\n if (parsedFallback === undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.MalformedTimeFallback,\n `Time-string fallback \"${fallback}\" is not a valid format. Expected <number><unit> where unit is one of: ms, s, m, h, d, w.`\n );\n }\n return parsedFallback;\n }\n return undefined;\n }\n\n /**\n * Process the raw env value for an {@link ArrayOf} configuration.\n *\n * Behaviour:\n * - Splits on `config.delimiter`, trims each item, and filters out empty entries.\n * - With a scalar element token: runs each item through the matching built-in converter.\n * If any element returns `undefined`, throws `ArrayElementConversionFailed` with positional info.\n * - With a custom function element: runs each item through the function. Propagates user\n * exceptions; treats `undefined` returns as conversion failures (same throw as scalar path).\n * - Returns `[]` when the raw value is empty/whitespace.\n * - When `strict` is true, throws `EmptyArrayElement` on any empty/whitespace item instead\n * of silently filtering it out.\n */\n static processArrayConverter(raw: string, config: ArrayOf, strict = false): unknown[] {\n if (raw.trim() === '') return [];\n\n const trimmedItems = raw.split(config.delimiter).map((item) => String(item).trim());\n\n if (strict) {\n const emptyIdx = trimmedItems.findIndex((item) => item === '');\n if (emptyIdx !== -1) {\n throw new EnvaptError(\n EnvaptErrorCodes.EmptyArrayElement,\n `Array element at index ${emptyIdx} is empty or whitespace only (strict mode).`\n );\n }\n }\n\n const items = trimmedItems.filter(Boolean);\n\n if (!items.length) return [];\n\n const elementOf = config.of;\n\n if (typeof elementOf === 'function') {\n return items.map((item, index) => {\n const converter = elementOf as CustomElementConverter;\n const result = converter(item);\n if (result === undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayElementConversionFailed,\n `Custom element converter returned undefined for item \"${item}\" at index ${index}.`\n );\n }\n return result;\n });\n }\n\n const converter = BuiltInConverters.getConverter(elementOf);\n return items.map((item, index) => {\n const converted = converter(item, undefined);\n if (converted === undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayElementConversionFailed,\n `Element \"${item}\" at index ${index} could not be converted to ${elementOf}.`\n );\n }\n return converted;\n });\n }\n\n /**\n * Get the converter function for a built-in converter type\n */\n static getConverter<TFallback extends BuiltInConverter>(type: TFallback): BuiltInConverterFunction {\n const converters: MapOfConverterFunctions = {\n string: BuiltInConverters.string,\n number: BuiltInConverters.number,\n boolean: BuiltInConverters.boolean,\n integer: BuiltInConverters.integer,\n bigint: BuiltInConverters.bigint,\n symbol: BuiltInConverters.symbol,\n float: BuiltInConverters.float,\n json: BuiltInConverters.json,\n url: BuiltInConverters.url,\n regexp: BuiltInConverters.regexp,\n date: BuiltInConverters.date,\n time: BuiltInConverters.time\n } as const;\n\n return converters[type];\n }\n}\n"],"mappings":"2CAcA,MAAM,EAAgB,IAKhB,EAAgB,GAAqB,EACrC,EAAc,GAAmB,EACjC,EAAa,GAAgB,EAG7B,EAAyC,CAC3C,GAAI,EACJ,EAAG,EACH,EAAG,EACH,EAAG,EACH,EAAG,EACH,EARgB,EAAgB,CASpC,EAEM,EAAgB,IAAI,OAAO,OAAO,GAAG,mCAAoC,GAAG,EAC5E,EAAiB,IAAI,OAAO,OAAO,GAAG,kCAAmC,GAAG,EAWlF,SAAS,EAAgB,EAAe,EAAS,GAA2B,CACxE,IAAM,EAAQ,EAAM,MAAM,EAAS,EAAiB,CAAa,EACjE,GAAI,CAAC,EAAO,OAEZ,GAAM,EAAG,EAAQ,GAAgB,EACjC,GAAI,CAAC,EAAQ,OAEb,IAAM,EAAQ,OAAO,WAAW,CAAM,EAClC,WAAO,MAAM,CAAK,EAGtB,OAAO,EAAQ,EADD,GAAgB,KAElC,CAOA,IAAa,EAAb,MAAa,CAAkB,CAC3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O,GAAc,WACrB,OAAO,EAAM,KAAK,EAAM,IAAU,CAE9B,IAAM,EAASA,EAAU,CAAI,EAC7B,GAAI,IAAW,IAAA,GACX,MAAM,IAAI,EAAA,IAEN,yDAAyD,EAAK,aAAa,EAAM,EACrF,EAEJ,OAAO,CACX,CAAC,EAGL,IAAM,EAAY,EAAkB,aAAa,CAAS,EAC1D,OAAO,EAAM,KAAK,EAAM,IAAU,CAC9B,IAAM,EAAY,EAAU,EAAM,IAAA,EAAS,EAC3C,GAAI,IAAc,IAAA,GACd,MAAM,IAAI,EAAA,IAEN,YAAY,EAAK,aAAa,EAAM,6BAA6B,EAAU,EAC/E,EAEJ,OAAO,CACX,CAAC,CACL,CAKA,OAAO,aAAiD,EAA2C,CAgB/F,MAAO,CAdH,OAAQ,EAAkB,OAC1B,OAAQ,EAAkB,OAC1B,QAAS,EAAkB,QAC3B,QAAS,EAAkB,QAC3B,OAAQ,EAAkB,OAC1B,OAAQ,EAAkB,OAC1B,MAAO,EAAkB,MACzB,KAAM,EAAkB,KACxB,IAAK,EAAkB,IACvB,OAAQ,EAAkB,OAC1B,KAAM,EAAkB,KACxB,KAAM,EAAkB,IAGZ,EAAE,EACtB,CACJ"}
1
+ {"version":3,"file":"BuiltInConverters.mjs","names":["converter"],"sources":["../../../src/converters/BuiltInConverters.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\n\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\n\nimport type { ArrayOf, CustomElementConverter } from './Converters';\nimport type {\n BuiltInConverter,\n BuiltInConverterFunction,\n JsonValue,\n MapOfConverterFunctions,\n TimeFallback,\n TimeUnit\n} from '../types';\n\nconst MS_PER_SECOND = 1000;\nconst SECONDS_PER_MINUTE = 60;\nconst MINUTES_PER_HOUR = 60;\nconst HOURS_PER_DAY = 24;\nconst DAYS_PER_WEEK = 7;\nconst MS_PER_MINUTE = SECONDS_PER_MINUTE * MS_PER_SECOND;\nconst MS_PER_HOUR = MINUTES_PER_HOUR * MS_PER_MINUTE;\nconst MS_PER_DAY = HOURS_PER_DAY * MS_PER_HOUR;\nconst MS_PER_WEEK = DAYS_PER_WEEK * MS_PER_DAY;\n\nconst TIME_UNIT_MS: Record<TimeUnit, number> = {\n ms: 1,\n s: MS_PER_SECOND,\n m: MS_PER_MINUTE,\n h: MS_PER_HOUR,\n d: MS_PER_DAY,\n w: MS_PER_WEEK\n};\n\nconst TIME_LOOSE_RE = new RegExp(String.raw`^(\\d+(?:\\.\\d+)?)(ms|s|m|h|d|w)?$`, 'u');\nconst TIME_STRICT_RE = new RegExp(String.raw`^(\\d+(?:\\.\\d+)?)(ms|s|m|h|d|w)$`, 'u');\n\n/**\n * Parse a time string (e.g. `\"30s\"`, `\"1.5h\"`) into milliseconds.\n *\n * @param input - The string to parse.\n * @param strict - When `true`, require an explicit unit (used for fallback strings).\n * When `false` (default), treat a missing unit as `ms` (used for raw env values). Both allow decimals.\n * @returns The duration in milliseconds, or `undefined` if the input does not match the expected format.\n * @internal\n */\nfunction parseTimeString(input: string, strict = false): number | undefined {\n const match = input.match(strict ? TIME_STRICT_RE : TIME_LOOSE_RE);\n if (!match) return undefined;\n\n const [, numStr, capturedUnit] = match;\n if (!numStr) return undefined;\n\n const value = Number.parseFloat(numStr);\n if (Number.isNaN(value)) return undefined;\n\n const unit = (capturedUnit ?? 'ms') as TimeUnit;\n return value * TIME_UNIT_MS[unit];\n}\n\n/**\n * Built-in converter implementations\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-extraneous-class -- dispatch-table helper, the documented exception to the no-static-class rule\nexport class BuiltInConverters {\n static string(raw: string, _fallback?: string): string | undefined {\n return String(raw);\n }\n\n static number(raw: string, fallback?: number): number | undefined {\n const parsed = Number(raw);\n return Number.isNaN(parsed) ? fallback : parsed;\n }\n\n static boolean(raw: string, fallback?: boolean): boolean | undefined {\n const lower = raw.toLowerCase().trim();\n\n const truthyValues = ['1', 'yes', 'true', 'on'];\n const falsyValues = ['0', 'no', 'false', 'off'];\n\n if (truthyValues.includes(lower)) return true;\n if (falsyValues.includes(lower)) return false;\n return fallback;\n }\n\n static bigint(raw: string, fallback?: bigint): bigint | undefined {\n try {\n return BigInt(raw);\n } catch {\n return fallback;\n }\n }\n\n static symbol(raw: string, fallback?: symbol): symbol | undefined {\n try {\n return raw ? Symbol.for(raw) : fallback;\n } catch {\n return fallback;\n }\n }\n\n static integer(raw: string, fallback?: number): number | undefined {\n const parsed = Number.parseInt(raw, 10);\n return Number.isNaN(parsed) ? fallback : parsed;\n }\n\n static float(raw: string, fallback?: number): number | undefined {\n const parsed = Number.parseFloat(raw);\n return Number.isNaN(parsed) ? fallback : parsed;\n }\n\n static json(raw: string, fallback?: JsonValue): JsonValue | undefined {\n try {\n return JSON.parse(raw) as JsonValue;\n } catch {\n return fallback;\n }\n }\n\n static url(raw: string, fallback?: URL): URL | undefined {\n try {\n return new URL(raw);\n } catch {\n return fallback;\n }\n }\n\n static regexp(raw: string, fallback?: RegExp): RegExp | undefined {\n try {\n // Handle flags if provided in format: /pattern/flags\n const match = raw.match(new RegExp(String.raw`^\\/(.+)\\/([gimsuvy]*)$`));\n if (match) return new RegExp(match[1] as string, match[2]);\n\n return new RegExp(raw);\n } catch {\n return fallback;\n }\n }\n\n static date(raw: string, fallback?: Date): Date | undefined {\n // Try parsing as timestamp first (if it's all digits)\n if (new RegExp(String.raw`^\\d+$`).test(raw)) {\n const timestamp = parseInt(raw, 10);\n const parsed = new Date(timestamp);\n return Number.isNaN(parsed.getTime()) ? fallback : parsed;\n }\n\n // Only accept ISO 8601 date strings (strict format)\n const isoRegex = new RegExp(String.raw`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{3})?Z$`, 'u');\n if (!isoRegex.test(raw)) return fallback;\n\n const parsed = new Date(raw);\n return Number.isNaN(parsed.getTime()) ? fallback : parsed;\n }\n\n static time(raw: string, fallback?: TimeFallback): number | undefined {\n const parsedRaw = parseTimeString(raw);\n if (parsedRaw !== undefined) return parsedRaw;\n\n // Raw didn't parse so apply fallback\n if (typeof fallback === 'number') return fallback;\n if (typeof fallback === 'string') {\n // A string fallback must name a unit; a unitless number is expressed as a number fallback, not a string.\n const parsedFallback = parseTimeString(fallback, true);\n if (parsedFallback === undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.MalformedTimeFallback,\n `Time-string fallback \"${fallback}\" is not a valid format. Expected <number><unit> where unit is one of: ms, s, m, h, d, w.`\n );\n }\n return parsedFallback;\n }\n return undefined;\n }\n\n /**\n * Process the raw env value for an {@link ArrayOf} configuration.\n *\n * Behaviour:\n * - Splits on `config.delimiter`, trims each item, and filters out empty entries.\n * - With a scalar element token: runs each item through the matching built-in converter.\n * If any element returns `undefined`, throws `ArrayElementConversionFailed` with positional info.\n * - With a custom function element: runs each item through the function. Propagates user\n * exceptions; treats `undefined` returns as conversion failures (same throw as scalar path).\n * - Returns `[]` when the raw value is empty/whitespace.\n * - When `strict` is true, throws `EmptyArrayElement` on any empty/whitespace item instead\n * of silently filtering it out.\n */\n static processArrayConverter(raw: string, config: ArrayOf, strict = false): unknown[] {\n if (raw.trim() === '') return [];\n\n const trimmedItems = raw.split(config.delimiter).map((item) => String(item).trim());\n\n if (strict) {\n const emptyIdx = trimmedItems.findIndex((item) => item === '');\n if (emptyIdx !== -1) {\n throw new EnvaptError(\n EnvaptErrorCodes.EmptyArrayElement,\n `Array element at index ${emptyIdx} is empty or whitespace only (strict mode).`\n );\n }\n }\n\n const items = trimmedItems.filter(Boolean);\n\n if (!items.length) return [];\n\n const elementOf = config.of;\n\n if (typeof elementOf === 'function') {\n return items.map((item, index) => {\n const converter = elementOf as CustomElementConverter;\n const result = converter(item);\n if (result === undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayElementConversionFailed,\n `Custom element converter returned undefined for item \"${item}\" at index ${index}.`\n );\n }\n return result;\n });\n }\n\n const converter = BuiltInConverters.getConverter(elementOf);\n return items.map((item, index) => {\n const converted = converter(item, undefined);\n if (converted === undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.ArrayElementConversionFailed,\n `Element \"${item}\" at index ${index} could not be converted to ${elementOf}.`\n );\n }\n return converted;\n });\n }\n\n /**\n * Get the converter function for a built-in converter type\n */\n static getConverter<TFallback extends BuiltInConverter>(type: TFallback): BuiltInConverterFunction {\n const converters: MapOfConverterFunctions = {\n string: BuiltInConverters.string,\n number: BuiltInConverters.number,\n boolean: BuiltInConverters.boolean,\n integer: BuiltInConverters.integer,\n bigint: BuiltInConverters.bigint,\n symbol: BuiltInConverters.symbol,\n float: BuiltInConverters.float,\n json: BuiltInConverters.json,\n url: BuiltInConverters.url,\n regexp: BuiltInConverters.regexp,\n date: BuiltInConverters.date,\n time: BuiltInConverters.time\n } as const;\n\n return converters[type];\n }\n}\n"],"mappings":"2CAcA,MAAM,EAAgB,IAKhB,EAAgB,GAAqB,EACrC,EAAc,GAAmB,EACjC,EAAa,GAAgB,EAG7B,EAAyC,CAC3C,GAAI,EACJ,EAAG,EACH,EAAG,EACH,EAAG,EACH,EAAG,EACH,EARgB,EAAgB,CASpC,EAEM,EAAgB,IAAI,OAAO,OAAO,GAAG,mCAAoC,GAAG,EAC5E,EAAiB,IAAI,OAAO,OAAO,GAAG,kCAAmC,GAAG,EAWlF,SAAS,EAAgB,EAAe,EAAS,GAA2B,CACxE,IAAM,EAAQ,EAAM,MAAM,EAAS,EAAiB,CAAa,EACjE,GAAI,CAAC,EAAO,OAEZ,GAAM,EAAG,EAAQ,GAAgB,EACjC,GAAI,CAAC,EAAQ,OAEb,IAAM,EAAQ,OAAO,WAAW,CAAM,EAClC,WAAO,MAAM,CAAK,EAGtB,OAAO,EAAQ,EADD,GAAgB,KAElC,CAOA,IAAa,EAAb,MAAa,CAAkB,CAC3B,OAAO,OAAO,EAAa,EAAwC,CAC/D,OAAO,OAAO,CAAG,CACrB,CAEA,OAAO,OAAO,EAAa,EAAuC,CAC9D,IAAM,EAAS,OAAO,CAAG,EACzB,OAAO,OAAO,MAAM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ACX,MAAM,IAAI,EAAA,IAEN,yDAAyD,EAAK,aAAa,EAAM,EACrF,EAEJ,OAAO,CACX,CAAC,EAGL,IAAM,EAAY,EAAkB,aAAa,CAAS,EAC1D,OAAO,EAAM,KAAK,EAAM,IAAU,CAC9B,IAAM,EAAY,EAAU,EAAM,IAAA,EAAS,EAC3C,GAAI,IAAc,IAAA,GACd,MAAM,IAAI,EAAA,IAEN,YAAY,EAAK,aAAa,EAAM,6BAA6B,EAAU,EAC/E,EAEJ,OAAO,CACX,CAAC,CACL,CAKA,OAAO,aAAiD,EAA2C,CAgB/F,MAAO,CAdH,OAAQ,EAAkB,OAC1B,OAAQ,EAAkB,OAC1B,QAAS,EAAkB,QAC3B,QAAS,EAAkB,QAC3B,OAAQ,EAAkB,OAC1B,OAAQ,EAAkB,OAC1B,MAAO,EAAkB,MACzB,KAAM,EAAkB,KACxB,IAAK,EAAkB,IACvB,OAAQ,EAAkB,OAC1B,KAAM,EAAkB,KACxB,KAAM,EAAkB,IAGZ,EAAE,EACtB,CACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"ValueConverter.mjs","names":[],"sources":["../../../src/converters/ValueConverter.ts"],"sourcesContent":["import { BuiltInConverters } from './BuiltInConverters';\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\nimport { Validator } from '../Validators';\n\nimport type { ArrayOf } from './Converters';\nimport type { StandardSchemaV1 } from '../StandardSchema';\nimport type { BuiltInConverter, EnvKeyInput, EnvaptConverter, PrimitiveConstructor } from '../types';\nimport type { EnvapterService } from '../types/Env';\n\nfunction formatKeyForError(key: EnvKeyInput): string {\n return Array.isArray(key) ? `[${key.join(', ')}]` : String(key);\n}\n\n/**\n * Convert a resolved environment value to its declared type via built-in, primitive, array,\n * custom, or Standard Schema converters.\n * @internal\n */\nexport class ValueConverter {\n constructor(private readonly envService: EnvapterService) {}\n\n convertValue<TFallback>(\n key: EnvKeyInput,\n fallback: TFallback | undefined,\n converter: EnvaptConverter<TFallback> | undefined,\n hasFallback: boolean\n ): TFallback | null | undefined {\n const resolvedConverter = this.resolveConverter(converter, fallback);\n const processedFallback = this.processFallbackForConverter(resolvedConverter, fallback);\n\n if (Validator.isArrayConverter(resolvedConverter)) {\n return this.processArrayConverter(key, processedFallback, resolvedConverter, hasFallback);\n }\n\n if (Validator.isPrimitiveConstructor(resolvedConverter)) {\n const stringConverter = this.convertPrimitiveToString(resolvedConverter);\n return this.processBuiltInConverter(key, processedFallback, stringConverter, hasFallback, true);\n }\n\n if (Validator.isBuiltInConverter(resolvedConverter)) {\n return this.processBuiltInConverter(key, processedFallback, resolvedConverter, hasFallback, false);\n }\n\n return this.processCustomConverter(key, processedFallback, resolvedConverter, hasFallback);\n }\n\n private processFallbackForConverter<TFallback>(\n converter: EnvaptConverter<TFallback>,\n fallback: TFallback | undefined\n ): TFallback | undefined {\n if (Validator.isPrimitiveConstructor(converter) && fallback !== undefined) {\n return Validator.coercePrimitiveFallback<TFallback>(converter, fallback);\n }\n return fallback;\n }\n\n private convertPrimitiveToString(primitiveConstructor: PrimitiveConstructor): BuiltInConverter {\n if (primitiveConstructor === String) return 'string';\n if (primitiveConstructor === Number) return 'number';\n if (primitiveConstructor === Boolean) return 'boolean';\n if (primitiveConstructor === BigInt) return 'bigint';\n /* v8 ignore next -- @preserve */\n if (primitiveConstructor === Symbol) return 'symbol';\n\n /* v8 ignore next -- @preserve */\n throw new EnvaptError(EnvaptErrorCodes.InvalidConverterType, `Unknown primitive constructor`);\n }\n\n private processBuiltInConverter<TFallback>(\n key: EnvKeyInput,\n fallback: TFallback | undefined,\n resolvedConverter: BuiltInConverter,\n hasFallback: boolean,\n wasOriginallyConstructor: boolean\n ): TFallback | null | undefined {\n Validator.builtInConverter(resolvedConverter);\n\n if (hasFallback && fallback !== undefined && !wasOriginallyConstructor) {\n Validator.validateBuiltInConverterFallback(resolvedConverter, fallback);\n }\n\n const parsed = this.envService.get(key, undefined);\n\n if (parsed === undefined) {\n if (!hasFallback) return null;\n // For converters with asymmetric fallback / return types — currently only `time`,\n // whose fallback may be a string while the return type is `number` — route the\n // fallback through the converter so it gets coerced to the return type.\n if (resolvedConverter === 'time' && typeof fallback === 'string') {\n const timeFn = BuiltInConverters.getConverter(resolvedConverter);\n return timeFn('', fallback) as TFallback;\n }\n return fallback;\n }\n\n const converterFn = BuiltInConverters.getConverter(resolvedConverter);\n const result = converterFn(parsed, fallback);\n\n if (result === undefined && !hasFallback) return null;\n\n return result as TFallback;\n }\n\n private processArrayConverter<TFallback>(\n key: EnvKeyInput,\n fallback: TFallback | undefined,\n resolvedConverter: ArrayOf,\n hasFallback: boolean\n ): TFallback | null | undefined {\n Validator.arrayConverter(resolvedConverter);\n\n if (hasFallback && fallback !== undefined && !Array.isArray(fallback)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidFallback,\n `ArrayOf<...> requires that the fallback be an array, got ${typeof fallback}`\n );\n }\n\n if (hasFallback && Array.isArray(fallback)) {\n Validator.validateArrayFallbackElementTypes(fallback);\n Validator.validateArrayConverterElementTypeMatch(resolvedConverter.of, fallback);\n }\n\n const parsed = this.envService.get(key, undefined);\n\n if (parsed === undefined) {\n if (!hasFallback) return null;\n // When the array element is `time` and the fallback is a list of time-strings,\n // coerce each entry through the time converter so the returned array is\n // `number[]` matching the declared return type.\n if (\n resolvedConverter.of === 'time' &&\n Array.isArray(fallback) &&\n fallback.every((v) => typeof v === 'string')\n ) {\n const timeFn = BuiltInConverters.getConverter('time');\n return fallback.map((v) => timeFn('', v as string)) as TFallback;\n }\n return fallback;\n }\n\n const result = BuiltInConverters.processArrayConverter(parsed, resolvedConverter, this.envService.isStrict());\n return result as TFallback;\n }\n\n private processCustomConverter<TFallback>(\n key: EnvKeyInput,\n fallback: TFallback | undefined,\n resolvedConverter: EnvaptConverter<TFallback>,\n _hasFallback: boolean // hasFallback is not needed because customConverter is called even if the raw value is undefined\n ): TFallback | null | undefined {\n Validator.customConvertor(resolvedConverter);\n\n const raw = this.envService.get(key, undefined);\n\n return resolvedConverter(raw, fallback);\n }\n\n private resolveConverter<TFallback>(\n converter: EnvaptConverter<TFallback> | undefined,\n fallback: TFallback | undefined\n ): EnvaptConverter<TFallback> {\n if (converter) return converter;\n\n const fallbackType = typeof fallback;\n if (fallbackType === 'number') return 'number';\n if (fallbackType === 'boolean') return 'boolean';\n if (fallbackType === 'bigint') return 'bigint';\n if (fallbackType === 'symbol') return 'symbol';\n return 'string';\n }\n\n // Single dispatch site for decorator + `Envapter.parse()` so error codes (208 / 209 / 305)\n // stay consistent. Missing+no-fallback throws here so callers don't duplicate the check.\n convertWithSchema(key: EnvKeyInput, schema: StandardSchemaV1, fallback: unknown, hasFallback: boolean): unknown {\n const raw = this.envService.get(key, undefined);\n\n if (raw === undefined) {\n if (hasFallback) return fallback;\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Required environment variable \"${formatKeyForError(key)}\" is missing or empty.`\n );\n }\n\n let outcome: StandardSchemaV1.Result<unknown> | Promise<StandardSchemaV1.Result<unknown>>;\n try {\n outcome = schema['~standard'].validate(raw);\n } catch (cause) {\n throw new EnvaptError(\n EnvaptErrorCodes.SchemaThrew,\n `Schema for \"${formatKeyForError(key)}\" threw during validation: ${(cause as Error).message}`,\n { cause }\n );\n }\n\n if (outcome instanceof Promise) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Schema for \"${formatKeyForError(key)}\" returned a Promise. envapt requires synchronous schemas; use a sync validator or perform async checks outside the env layer.`\n );\n }\n\n if (outcome.issues !== undefined) {\n const first = outcome.issues[0];\n const firstMessage = first?.message ?? 'no issue message';\n throw new EnvaptError(\n EnvaptErrorCodes.SchemaValidationFailed,\n `Schema validation failed for \"${formatKeyForError(key)}\": ${firstMessage}`,\n { issues: outcome.issues }\n );\n }\n\n return outcome.value;\n }\n}\n"],"mappings":"qJASA,SAAS,EAAkB,EAA0B,CACjD,OAAO,MAAM,QAAQ,CAAG,EAAI,IAAI,EAAI,KAAK,IAAI,EAAE,GAAK,O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,IAAA,EAAS,EAE9C,GAAI,IAAQ,IAAA,GAAW,CACnB,GAAI,EAAa,OAAO,EACxB,MAAM,IAAI,EAAA,IAEN,kCAAkC,EAAkB,CAAG,EAAE,uBAC7D,CACJ,CAEA,IAAI,EACJ,GAAI,CACA,EAAU,EAAO,aAAa,SAAS,CAAG,CAC9C,OAAS,EAAO,CACZ,MAAM,IAAI,EAAA,IAEN,eAAe,EAAkB,CAAG,EAAE,6BAA8B,EAAgB,UACpF,CAAE,OAAM,CACZ,CACJ,CAEA,GAAI,aAAmB,QACnB,MAAM,IAAI,EAAA,IAEN,eAAe,EAAkB,CAAG,EAAE,+HAC1C,EAGJ,GAAI,EAAQ,SAAW,IAAA,GAAW,CAE9B,IAAM,EADQ,EAAQ,OAAO,IACD,SAAW,mBACvC,MAAM,IAAI,EAAA,IAEN,iCAAiC,EAAkB,CAAG,EAAE,KAAK,IAC7D,CAAE,OAAQ,EAAQ,MAAO,CAC7B,CACJ,CAEA,OAAO,EAAQ,KACnB,CACJ"}
1
+ {"version":3,"file":"ValueConverter.mjs","names":[],"sources":["../../../src/converters/ValueConverter.ts"],"sourcesContent":["import { BuiltInConverters } from './BuiltInConverters';\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\nimport { Validator } from '../Validators';\n\nimport type { ArrayOf } from './Converters';\nimport type { StandardSchemaV1 } from '../StandardSchema';\nimport type { BuiltInConverter, EnvKeyInput, EnvaptConverter, PrimitiveConstructor } from '../types';\nimport type { EnvapterService } from '../types/Env';\n\nfunction formatKeyForError(key: EnvKeyInput): string {\n return Array.isArray(key) ? `[${key.join(', ')}]` : String(key);\n}\n\n/**\n * Convert a resolved environment value to its declared type via built-in, primitive, array,\n * custom, or Standard Schema converters.\n * @internal\n */\nexport class ValueConverter {\n constructor(private readonly envService: EnvapterService) {}\n\n convertValue<TFallback>(\n key: EnvKeyInput,\n fallback: TFallback | undefined,\n converter: EnvaptConverter<TFallback> | undefined,\n hasFallback: boolean\n ): TFallback | null | undefined {\n const resolvedConverter = this.resolveConverter(converter, fallback);\n const processedFallback = this.processFallbackForConverter(resolvedConverter, fallback);\n\n if (Validator.isArrayConverter(resolvedConverter)) {\n return this.processArrayConverter(key, processedFallback, resolvedConverter, hasFallback);\n }\n\n if (Validator.isPrimitiveConstructor(resolvedConverter)) {\n const stringConverter = this.convertPrimitiveToString(resolvedConverter);\n return this.processBuiltInConverter(key, processedFallback, stringConverter, hasFallback, true);\n }\n\n if (Validator.isBuiltInConverter(resolvedConverter)) {\n return this.processBuiltInConverter(key, processedFallback, resolvedConverter, hasFallback, false);\n }\n\n return this.processCustomConverter(key, processedFallback, resolvedConverter, hasFallback);\n }\n\n private processFallbackForConverter<TFallback>(\n converter: EnvaptConverter<TFallback>,\n fallback: TFallback | undefined\n ): TFallback | undefined {\n if (Validator.isPrimitiveConstructor(converter) && fallback !== undefined) {\n return Validator.coercePrimitiveFallback<TFallback>(converter, fallback);\n }\n return fallback;\n }\n\n private convertPrimitiveToString(primitiveConstructor: PrimitiveConstructor): BuiltInConverter {\n if (primitiveConstructor === String) return 'string';\n if (primitiveConstructor === Number) return 'number';\n if (primitiveConstructor === Boolean) return 'boolean';\n if (primitiveConstructor === BigInt) return 'bigint';\n /* v8 ignore next -- @preserve */\n if (primitiveConstructor === Symbol) return 'symbol';\n\n /* v8 ignore next -- @preserve */\n throw new EnvaptError(EnvaptErrorCodes.InvalidConverterType, `Unknown primitive constructor`);\n }\n\n private processBuiltInConverter<TFallback>(\n key: EnvKeyInput,\n fallback: TFallback | undefined,\n resolvedConverter: BuiltInConverter,\n hasFallback: boolean,\n wasOriginallyConstructor: boolean\n ): TFallback | null | undefined {\n Validator.builtInConverter(resolvedConverter);\n\n if (hasFallback && fallback !== undefined && !wasOriginallyConstructor) {\n Validator.validateBuiltInConverterFallback(resolvedConverter, fallback);\n }\n\n const parsed = this.envService.get(key, undefined);\n\n if (parsed === undefined) {\n if (!hasFallback) return null;\n // For converters with asymmetric fallback / return types — currently only `time`,\n // whose fallback may be a string while the return type is `number` — route the\n // fallback through the converter so it gets coerced to the return type.\n if (resolvedConverter === 'time' && typeof fallback === 'string') {\n const timeFn = BuiltInConverters.getConverter(resolvedConverter);\n return timeFn('', fallback) as TFallback;\n }\n return fallback;\n }\n\n const converterFn = BuiltInConverters.getConverter(resolvedConverter);\n const result = converterFn(parsed, fallback);\n\n if (result === undefined && !hasFallback) return null;\n\n return result as TFallback;\n }\n\n private processArrayConverter<TFallback>(\n key: EnvKeyInput,\n fallback: TFallback | undefined,\n resolvedConverter: ArrayOf,\n hasFallback: boolean\n ): TFallback | null | undefined {\n Validator.arrayConverter(resolvedConverter);\n\n if (hasFallback && fallback !== undefined && !Array.isArray(fallback)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidFallback,\n `ArrayOf<...> requires that the fallback be an array, got ${typeof fallback}`\n );\n }\n\n if (hasFallback && Array.isArray(fallback)) {\n Validator.validateArrayFallbackElementTypes(fallback);\n Validator.validateArrayConverterElementTypeMatch(resolvedConverter.of, fallback);\n }\n\n const parsed = this.envService.get(key, undefined);\n\n if (parsed === undefined) {\n if (!hasFallback) return null;\n // When the array element is `time` and the fallback is a list of time-strings,\n // coerce each entry through the time converter so the returned array is\n // `number[]` matching the declared return type.\n if (\n resolvedConverter.of === 'time' &&\n Array.isArray(fallback) &&\n fallback.every((v) => typeof v === 'string')\n ) {\n const timeFn = BuiltInConverters.getConverter('time');\n return fallback.map((v) => timeFn('', v as string)) as TFallback;\n }\n return fallback;\n }\n\n const result = BuiltInConverters.processArrayConverter(parsed, resolvedConverter, this.envService.isStrict());\n return result as TFallback;\n }\n\n private processCustomConverter<TFallback>(\n key: EnvKeyInput,\n fallback: TFallback | undefined,\n resolvedConverter: EnvaptConverter<TFallback>,\n _hasFallback: boolean // hasFallback is not needed because customConverter is called even if the raw value is undefined\n ): TFallback | null | undefined {\n Validator.customConvertor(resolvedConverter);\n\n const raw = this.envService.get(key, undefined);\n\n return resolvedConverter(raw, fallback);\n }\n\n private resolveConverter<TFallback>(\n converter: EnvaptConverter<TFallback> | undefined,\n fallback: TFallback | undefined\n ): EnvaptConverter<TFallback> {\n if (converter) return converter;\n\n const fallbackType = typeof fallback;\n if (fallbackType === 'number') return 'number';\n if (fallbackType === 'boolean') return 'boolean';\n if (fallbackType === 'bigint') return 'bigint';\n if (fallbackType === 'symbol') return 'symbol';\n return 'string';\n }\n\n // Single dispatch site for decorator + `Envapter.parse()` so error codes (208 / 209 / 305)\n // stay consistent. Missing+no-fallback throws here so callers don't duplicate the check.\n convertWithSchema(key: EnvKeyInput, schema: StandardSchemaV1, fallback: unknown, hasFallback: boolean): unknown {\n const raw = this.envService.get(key, undefined);\n\n if (raw === undefined) {\n if (hasFallback) return fallback;\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Required environment variable \"${formatKeyForError(key)}\" is missing or empty.`\n );\n }\n\n let outcome: StandardSchemaV1.Result<unknown> | Promise<StandardSchemaV1.Result<unknown>>;\n try {\n outcome = schema['~standard'].validate(raw);\n } catch (cause) {\n throw new EnvaptError(\n EnvaptErrorCodes.SchemaThrew,\n `Schema for \"${formatKeyForError(key)}\" threw during validation: ${(cause as Error).message}`,\n { cause }\n );\n }\n\n if (outcome instanceof Promise) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n `Schema for \"${formatKeyForError(key)}\" returned a Promise. envapt requires synchronous schemas; use a sync validator or perform async checks outside the env layer.`\n );\n }\n\n if (outcome.issues !== undefined) {\n const first = outcome.issues[0];\n const firstMessage = first?.message ?? 'no issue message';\n throw new EnvaptError(\n EnvaptErrorCodes.SchemaValidationFailed,\n `Schema validation failed for \"${formatKeyForError(key)}\": ${firstMessage}`,\n { issues: outcome.issues }\n );\n }\n\n return outcome.value;\n }\n}\n"],"mappings":"qJASA,SAAS,EAAkB,EAA0B,CACjD,OAAO,MAAM,QAAQ,CAAG,EAAI,IAAI,EAAI,KAAK,IAAI,EAAE,GAAK,OAAO,CAAG,CAClE,CAOA,IAA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AE9C,GAAI,IAAQ,IAAA,GAAW,CACnB,GAAI,EAAa,OAAO,EACxB,MAAM,IAAI,EAAA,IAEN,kCAAkC,EAAkB,CAAG,EAAE,uBAC7D,CACJ,CAEA,IAAI,EACJ,GAAI,CACA,EAAU,EAAO,YAAY,CAAC,SAAS,CAAG,CAC9C,OAAS,EAAO,CACZ,MAAM,IAAI,EAAA,IAEN,eAAe,EAAkB,CAAG,EAAE,6BAA8B,EAAgB,UACpF,CAAE,OAAM,CACZ,CACJ,CAEA,GAAI,aAAmB,QACnB,MAAM,IAAI,EAAA,IAEN,eAAe,EAAkB,CAAG,EAAE,+HAC1C,EAGJ,GAAI,EAAQ,SAAW,IAAA,GAAW,CAE9B,IAAM,EADQ,EAAQ,OAAO,EACH,EAAE,SAAW,mBACvC,MAAM,IAAI,EAAA,IAEN,iCAAiC,EAAkB,CAAG,EAAE,KAAK,IAC7D,CAAE,OAAQ,EAAQ,MAAO,CAC7B,CACJ,CAEA,OAAO,EAAQ,KACnB,CACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"EnvapterBase.mjs","names":[],"sources":["../../../src/core/EnvapterBase.ts"],"sourcesContent":["import { debugVerbose, getDebugLevel, setDebugLevel } from '../Debug';\nimport { loadDotenv } from '../Dotenv';\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\nimport { bindRuntimeFromSource } from '../runtime';\nimport { UnboundEnvSource } from '../sources/UnboundEnvSource';\nimport { Validator } from '../Validators';\n\nimport type { DebugLevel } from '../Debug';\nimport type { EnvFileOptions } from '../Dotenv';\nimport type { EnvKeyInput, EnvSource, FileEnvSource } from '../types';\n\n/** @internal */\nexport const EnvaptCache = new Map<string, unknown>();\n\n/** @internal */\nexport abstract class EnvapterBase {\n protected static _envPaths: string[] = ['.env'];\n protected static _envPathsExplicitlySet = false;\n protected static _baseDir: string | undefined = undefined;\n protected static _userDefinedEnvFileOptions: EnvFileOptions = {};\n protected static _strict = false;\n protected static _syncProcessEnv = false;\n // Loader-written keys only (collisions skipped). Refilled on every cache rebuild.\n protected static _dotenvAddedKeys: Set<string> = new Set<string>();\n // Unbound by default so non-Node builds throw NoSourceBound on read until useSource() is called.\n // NodeEnvapter's static block binds NodeEnvSource when referenced, so `import 'envapt'` needs no setup.\n protected static _source: EnvSource = new UnboundEnvSource();\n\n /**\n * Enable or disable strict mode. Default `false`. Setting refreshes the cache so\n * previously-cached converted values get re-evaluated under the new rule.\n */\n static set strict(value: boolean) {\n // Anchored to EnvapterBase: `this._strict` would write an own-property on the subclass that base readers miss.\n EnvapterBase._strict = value;\n // `this`, not EnvapterBase: rebuild via the subclass so its `resolveEffectivePaths` override is honored.\n this.refreshCache();\n }\n\n static get strict(): boolean {\n return EnvapterBase._strict;\n }\n\n /**\n * Set the debug log level. Defaults to `silent`. When unset, reads `ENVAPT_DEBUG` from the\n * bound source on first access; the setter overrides any env-var value. Output goes to stderr\n * on Node (the console elsewhere), prefixed with `[envapt]`.\n */\n static set debug(level: DebugLevel) {\n setDebugLevel(level);\n }\n\n static get debug(): DebugLevel {\n return getDebugLevel();\n }\n\n /**\n * Opt-in mirror of dotenv-loaded keys back to `process.env`. Default `false`.\n *\n * Only keys the loader actually wrote are mirrored, so collision behavior follows\n * `envFileOptions.override`: with the default `false`, pre-existing `process.env` values\n * are preserved; with `true`, the file value wins in both the cache and the mirror.\n *\n * Flipping `false → true` mirrors the existing tracked delta immediately (no cache\n * refresh). Flipping `true → false` is one-way: previously mirrored keys remain in\n * `process.env` until the process exits.\n */\n static set syncProcessEnv(value: boolean) {\n Validator.validateSyncProcessEnv(value);\n const previous = EnvapterBase._syncProcessEnv;\n // Anchored to EnvapterBase: `this._syncProcessEnv` would write an own-property on the subclass that base readers miss.\n EnvapterBase._syncProcessEnv = value;\n if (!previous && value && EnvaptCache.size > 0) this.mirrorToProcessEnv();\n }\n\n static get syncProcessEnv(): boolean {\n return EnvapterBase._syncProcessEnv;\n }\n\n protected static treatAsMissing(value: string | undefined): boolean {\n if (value === undefined || value === '') return true;\n if (EnvapterBase._strict && value.trim() === '') return true;\n return false;\n }\n\n // No baseDir: candidate returned unchanged so the source resolves it against its own default\n // (process.cwd() on Node). Resolution goes through the source to keep this class node-free.\n protected static resolveAgainstBase(candidate: string): string {\n const baseDir = EnvapterBase._baseDir;\n if (baseDir === undefined) return candidate;\n const source = EnvapterBase._source;\n /* v8 ignore next -- @preserve callers are all file-gated, so the source is never bare here */\n if (!source.supportsFiles) return candidate;\n return source.resolvePath(baseDir, candidate);\n }\n\n // File-based config (envPaths/baseDir/configureProfiles) is meaningless without a filesystem;\n // throw instead of silently ignoring it on the browser or Workers. Narrows the source so callers\n // can reach the file capabilities (resolvePath/normalizeBaseDir) after the check.\n protected static assertFileApiSupported(api: string, source: EnvSource): asserts source is FileEnvSource {\n if (!source.supportsFiles) {\n throw new EnvaptError(\n EnvaptErrorCodes.FileApiUnsupported,\n `${api} requires a filesystem-backed source; the bound source does not support .env files.`\n );\n }\n }\n\n // Existence via the bound source instead of fs.existsSync/accessSync: a file \"exists\" when the\n // source can read it.\n protected static sourceFileExists(path: string): boolean {\n const source = EnvapterBase._source;\n /* v8 ignore next -- @preserve every caller is file-gated, so this never sees a bare source */\n if (!source.supportsFiles) return false;\n return source.readFile(path, 'utf8') !== undefined;\n }\n\n protected static refreshCache(): void {\n EnvaptCache.clear();\n EnvapterBase._dotenvAddedKeys = new Set();\n debugVerbose('cache cleared, reloading config');\n void this.config; // getter rebuilds the cache as a side effect\n }\n\n protected static mirrorToProcessEnv(): void {\n if (EnvapterBase._dotenvAddedKeys.size === 0) return;\n const source = EnvapterBase._source;\n /* v8 ignore next -- @preserve dotenv keys only accumulate under a file source, so the delta implies supportsFiles here */\n if (!source.supportsFiles) return;\n const mirrored: Record<string, string> = {};\n for (const key of EnvapterBase._dotenvAddedKeys) {\n const value = EnvaptCache.get(key);\n /* v8 ignore next -- @preserve loader only writes strings; defensive against future cache contents */\n if (typeof value !== 'string') continue;\n mirrored[key] = value;\n debugVerbose(`mirrored ${key} to the ambient environment`);\n }\n source.writeVars(mirrored);\n debugVerbose(`mirrored ${EnvapterBase._dotenvAddedKeys.size} keys to the ambient environment`);\n }\n\n // Default returns the explicit `_envPaths`; EnvironmentMethods overrides to layer the dotenv-flow\n // cascade + configureProfiles when envPaths was never explicitly set.\n protected static resolveEffectivePaths(): string[] {\n /* v8 ignore next -- @preserve */\n return this._envPaths.map((p) => this.resolveAgainstBase(p));\n }\n\n protected static resolveKeyInput(keyInput: EnvKeyInput): { key: string; value: string | undefined } {\n const keys = Array.isArray(keyInput) ? keyInput : [keyInput];\n const normalizedKeys = keys as readonly string[];\n\n if (normalizedKeys.length === 0) {\n throw new EnvaptError(EnvaptErrorCodes.InvalidKeyInput, 'At least one environment key must be provided.');\n }\n\n if (normalizedKeys.some((k) => typeof k !== 'string')) {\n throw new EnvaptError(EnvaptErrorCodes.InvalidKeyInput, 'Environment keys must be strings.');\n }\n\n if (normalizedKeys.some((k) => k.trim() === '')) {\n throw new EnvaptError(EnvaptErrorCodes.InvalidKeyInput, 'Environment keys cannot be empty strings.');\n }\n\n for (const candidate of normalizedKeys) {\n const value = this.config.get(candidate) as string | undefined;\n if (value !== undefined) {\n return { key: candidate, value };\n }\n }\n\n return { key: normalizedKeys[0] as string, value: undefined };\n }\n\n protected static get config(): Map<string, unknown> {\n if (EnvaptCache.size === 0) {\n const source = EnvapterBase._source;\n // Clone so the loader and downstream reads never mutate the source's backing object.\n const isolatedEnv: Record<string, string> = { ...source.readVars() };\n\n let added = new Set<string>();\n // Sources without a filesystem (injected objects on the browser or Workers) skip the\n // .env cascade, profiles, and envPaths; only the readVars() snapshot populates the cache.\n if (source.supportsFiles) {\n // Outside the try below so a missing configured profile path surfaces its EnvaptError; only dotenv parse errors stay caught.\n const effectivePaths = this.resolveEffectivePaths();\n debugVerbose(\n `effective .env paths: ${effectivePaths.length === 0 ? '(none)' : effectivePaths.join(', ')}`\n );\n try {\n added = loadDotenv({\n ...this._userDefinedEnvFileOptions,\n path: effectivePaths,\n processEnv: isolatedEnv,\n readFile: source.readFile.bind(source)\n });\n } catch {}\n }\n EnvapterBase._dotenvAddedKeys = added;\n for (const [key, value] of Object.entries(isolatedEnv)) EnvaptCache.set(key, value);\n debugVerbose(`cache populated: ${EnvaptCache.size} keys total`);\n if (EnvapterBase._syncProcessEnv) this.mirrorToProcessEnv();\n }\n\n return EnvaptCache;\n }\n\n /**\n * Eagerly load the `.env` cascade now instead of lazily on the first read. Idempotent: a no-op\n * once the cache is built. Useful before mirroring to `process.env` (see {@link syncProcessEnv}),\n * which is what the `envapt/config` side-effect entry does.\n */\n static load(): void {\n void this.config;\n }\n\n /**\n * Bind the environment {@link EnvSource}. On Node the entry binds {@link NodeEnvSource} for you\n * (a `process.env` snapshot plus the `.env` cascade); on the browser or Workers, pass a\n * `ManualEnvSource` / `WorkerEnvSource` (or any `EnvSource`) before reading. Clears and rebuilds\n * the cache.\n */\n static useSource(source: EnvSource): void {\n EnvapterBase._source = source;\n bindRuntimeFromSource(source);\n this.refreshCache();\n }\n\n /**\n * Read an environment variable as its raw string, skipping parsing and conversion.\n */\n getRaw(key: EnvKeyInput): string | undefined {\n return EnvapterBase.resolveKeyInput(key).value;\n }\n}\n"],"mappings":"gVAYA,MAAa,EAAc,IAAI,IAG/B,IAAsB,EAAtB,MAAsB,CAAa,CAC/B,OAAiB,UAAsB,CAAC,MAAM,EAC9C,OAAiB,uBAAyB,GAC1C,OAAiB,SAA+B,IAAA,GAChD,OAAiB,2BAA6C,CAAC,EAC/D,OAAiB,QAAU,GAC3B,OAAiB,gBAAkB,GAEnC,OAAiB,iBAAgC,IAAI,IAGrD,OAAiB,QAAqB,IAAI,EAM1C,WAAW,OAAO,EAAgB,CAE9B,EAAa,QAAU,EAEvB,KAAK,aAAa,CACtB,CAEA,WAAW,QAAkB,CACzB,OAAO,EAAa,OACxB,CAOA,WAAW,MAAM,EAAmB,CAChC,EAAc,CAAK,CACvB,CAEA,WAAW,OAAoB,CAC3B,OAAO,EAAc,CACzB,CAaA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,MAAa,CAChB,KAAU,MACd,CAQA,OAAO,UAAU,EAAyB,CACtC,EAAa,QAAU,EACvB,EAAsB,CAAM,EAC5B,KAAK,aAAa,CACtB,CAKA,OAAO,EAAsC,CACzC,OAAO,EAAa,gBAAgB,CAAG,EAAE,KAC7C,CACJ"}
1
+ {"version":3,"file":"EnvapterBase.mjs","names":[],"sources":["../../../src/core/EnvapterBase.ts"],"sourcesContent":["import { debugVerbose, getDebugLevel, setDebugLevel } from '../Debug';\nimport { loadDotenv } from '../Dotenv';\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\nimport { bindRuntimeFromSource } from '../runtime';\nimport { UnboundEnvSource } from '../sources/UnboundEnvSource';\nimport { Validator } from '../Validators';\n\nimport type { DebugLevel } from '../Debug';\nimport type { EnvFileOptions } from '../Dotenv';\nimport type { EnvKeyInput, EnvSource, FileEnvSource } from '../types';\n\n/** @internal */\nexport const EnvaptCache = new Map<string, unknown>();\n\n/** @internal */\nexport abstract class EnvapterBase {\n protected static _envPaths: string[] = ['.env'];\n protected static _envPathsExplicitlySet = false;\n protected static _baseDir: string | undefined = undefined;\n protected static _userDefinedEnvFileOptions: EnvFileOptions = {};\n protected static _strict = false;\n protected static _syncProcessEnv = false;\n // Loader-written keys only (collisions skipped). Refilled on every cache rebuild.\n protected static _dotenvAddedKeys: Set<string> = new Set<string>();\n // Unbound by default so non-Node builds throw NoSourceBound on read until useSource() is called.\n // NodeEnvapter's static block binds NodeEnvSource when referenced, so `import 'envapt'` needs no setup.\n protected static _source: EnvSource = new UnboundEnvSource();\n\n /**\n * Enable or disable strict mode. Default `false`. Setting refreshes the cache so\n * previously-cached converted values get re-evaluated under the new rule.\n */\n static set strict(value: boolean) {\n // Anchored to EnvapterBase: `this._strict` would write an own-property on the subclass that base readers miss.\n EnvapterBase._strict = value;\n // `this`, not EnvapterBase: rebuild via the subclass so its `resolveEffectivePaths` override is honored.\n this.refreshCache();\n }\n\n static get strict(): boolean {\n return EnvapterBase._strict;\n }\n\n /**\n * Set the debug log level. Defaults to `silent`. When unset, reads `ENVAPT_DEBUG` from the\n * bound source on first access; the setter overrides any env-var value. Output goes to stderr\n * on Node (the console elsewhere), prefixed with `[envapt]`.\n */\n static set debug(level: DebugLevel) {\n setDebugLevel(level);\n }\n\n static get debug(): DebugLevel {\n return getDebugLevel();\n }\n\n /**\n * Opt-in mirror of dotenv-loaded keys back to `process.env`. Default `false`.\n *\n * Only keys the loader actually wrote are mirrored, so collision behavior follows\n * `envFileOptions.override`: with the default `false`, pre-existing `process.env` values\n * are preserved; with `true`, the file value wins in both the cache and the mirror.\n *\n * Flipping `false → true` mirrors the existing tracked delta immediately (no cache\n * refresh). Flipping `true → false` is one-way: previously mirrored keys remain in\n * `process.env` until the process exits.\n */\n static set syncProcessEnv(value: boolean) {\n Validator.validateSyncProcessEnv(value);\n const previous = EnvapterBase._syncProcessEnv;\n // Anchored to EnvapterBase: `this._syncProcessEnv` would write an own-property on the subclass that base readers miss.\n EnvapterBase._syncProcessEnv = value;\n if (!previous && value && EnvaptCache.size > 0) this.mirrorToProcessEnv();\n }\n\n static get syncProcessEnv(): boolean {\n return EnvapterBase._syncProcessEnv;\n }\n\n protected static treatAsMissing(value: string | undefined): boolean {\n if (value === undefined || value === '') return true;\n if (EnvapterBase._strict && value.trim() === '') return true;\n return false;\n }\n\n // No baseDir: candidate returned unchanged so the source resolves it against its own default\n // (process.cwd() on Node). Resolution goes through the source to keep this class node-free.\n protected static resolveAgainstBase(candidate: string): string {\n const baseDir = EnvapterBase._baseDir;\n if (baseDir === undefined) return candidate;\n const source = EnvapterBase._source;\n /* v8 ignore next -- @preserve callers are all file-gated, so the source is never bare here */\n if (!source.supportsFiles) return candidate;\n return source.resolvePath(baseDir, candidate);\n }\n\n // File-based config (envPaths/baseDir/configureProfiles) is meaningless without a filesystem;\n // throw instead of silently ignoring it on the browser or Workers. Narrows the source so callers\n // can reach the file capabilities (resolvePath/normalizeBaseDir) after the check.\n protected static assertFileApiSupported(api: string, source: EnvSource): asserts source is FileEnvSource {\n if (!source.supportsFiles) {\n throw new EnvaptError(\n EnvaptErrorCodes.FileApiUnsupported,\n `${api} requires a filesystem-backed source; the bound source does not support .env files.`\n );\n }\n }\n\n // Existence via the bound source instead of fs.existsSync/accessSync: a file \"exists\" when the\n // source can read it.\n protected static sourceFileExists(path: string): boolean {\n const source = EnvapterBase._source;\n /* v8 ignore next -- @preserve every caller is file-gated, so this never sees a bare source */\n if (!source.supportsFiles) return false;\n return source.readFile(path, 'utf8') !== undefined;\n }\n\n protected static refreshCache(): void {\n EnvaptCache.clear();\n EnvapterBase._dotenvAddedKeys = new Set();\n debugVerbose('cache cleared, reloading config');\n void this.config; // getter rebuilds the cache as a side effect\n }\n\n protected static mirrorToProcessEnv(): void {\n if (EnvapterBase._dotenvAddedKeys.size === 0) return;\n const source = EnvapterBase._source;\n /* v8 ignore next -- @preserve dotenv keys only accumulate under a file source, so the delta implies supportsFiles here */\n if (!source.supportsFiles) return;\n const mirrored: Record<string, string> = {};\n for (const key of EnvapterBase._dotenvAddedKeys) {\n const value = EnvaptCache.get(key);\n /* v8 ignore next -- @preserve loader only writes strings; defensive against future cache contents */\n if (typeof value !== 'string') continue;\n mirrored[key] = value;\n debugVerbose(`mirrored ${key} to the ambient environment`);\n }\n source.writeVars(mirrored);\n debugVerbose(`mirrored ${EnvapterBase._dotenvAddedKeys.size} keys to the ambient environment`);\n }\n\n // Default returns the explicit `_envPaths`; EnvironmentMethods overrides to layer the dotenv-flow\n // cascade + configureProfiles when envPaths was never explicitly set.\n protected static resolveEffectivePaths(): string[] {\n /* v8 ignore next -- @preserve */\n return this._envPaths.map((p) => this.resolveAgainstBase(p));\n }\n\n protected static resolveKeyInput(keyInput: EnvKeyInput): { key: string; value: string | undefined } {\n const keys = Array.isArray(keyInput) ? keyInput : [keyInput];\n const normalizedKeys = keys as readonly string[];\n\n if (normalizedKeys.length === 0) {\n throw new EnvaptError(EnvaptErrorCodes.InvalidKeyInput, 'At least one environment key must be provided.');\n }\n\n if (normalizedKeys.some((k) => typeof k !== 'string')) {\n throw new EnvaptError(EnvaptErrorCodes.InvalidKeyInput, 'Environment keys must be strings.');\n }\n\n if (normalizedKeys.some((k) => k.trim() === '')) {\n throw new EnvaptError(EnvaptErrorCodes.InvalidKeyInput, 'Environment keys cannot be empty strings.');\n }\n\n for (const candidate of normalizedKeys) {\n const value = this.config.get(candidate) as string | undefined;\n if (value !== undefined) {\n return { key: candidate, value };\n }\n }\n\n return { key: normalizedKeys[0] as string, value: undefined };\n }\n\n protected static get config(): Map<string, unknown> {\n if (EnvaptCache.size === 0) {\n const source = EnvapterBase._source;\n // Clone so the loader and downstream reads never mutate the source's backing object.\n const isolatedEnv: Record<string, string> = { ...source.readVars() };\n\n let added = new Set<string>();\n // Sources without a filesystem (injected objects on the browser or Workers) skip the\n // .env cascade, profiles, and envPaths; only the readVars() snapshot populates the cache.\n if (source.supportsFiles) {\n // Outside the try below so a missing configured profile path surfaces its EnvaptError; only dotenv parse errors stay caught.\n const effectivePaths = this.resolveEffectivePaths();\n debugVerbose(\n `effective .env paths: ${effectivePaths.length === 0 ? '(none)' : effectivePaths.join(', ')}`\n );\n try {\n added = loadDotenv({\n ...this._userDefinedEnvFileOptions,\n path: effectivePaths,\n processEnv: isolatedEnv,\n readFile: source.readFile.bind(source)\n });\n } catch {}\n }\n EnvapterBase._dotenvAddedKeys = added;\n for (const [key, value] of Object.entries(isolatedEnv)) EnvaptCache.set(key, value);\n debugVerbose(`cache populated: ${EnvaptCache.size} keys total`);\n if (EnvapterBase._syncProcessEnv) this.mirrorToProcessEnv();\n }\n\n return EnvaptCache;\n }\n\n /**\n * Eagerly load the `.env` cascade now instead of lazily on the first read. Idempotent: a no-op\n * once the cache is built. Useful before mirroring to `process.env` (see {@link syncProcessEnv}),\n * which is what the `envapt/config` side-effect entry does.\n */\n static load(): void {\n void this.config;\n }\n\n /**\n * Bind the environment {@link EnvSource}. On Node the entry binds {@link NodeEnvSource} for you\n * (a `process.env` snapshot plus the `.env` cascade); on the browser or Workers, pass a\n * `ManualEnvSource` / `WorkerEnvSource` (or any `EnvSource`) before reading. Clears and rebuilds\n * the cache.\n */\n static useSource(source: EnvSource): void {\n EnvapterBase._source = source;\n bindRuntimeFromSource(source);\n this.refreshCache();\n }\n\n /**\n * Read an environment variable as its raw string, skipping parsing and conversion.\n */\n getRaw(key: EnvKeyInput): string | undefined {\n return EnvapterBase.resolveKeyInput(key).value;\n }\n}\n"],"mappings":"gVAYA,MAAa,EAAc,IAAI,IAG/B,IAAsB,EAAtB,MAAsB,CAAa,CAC/B,OAAiB,UAAsB,CAAC,MAAM,EAC9C,OAAiB,uBAAyB,GAC1C,OAAiB,SAA+B,IAAA,GAChD,OAAiB,2BAA6C,CAAC,EAC/D,OAAiB,QAAU,GAC3B,OAAiB,gBAAkB,GAEnC,OAAiB,iBAAgC,IAAI,IAGrD,OAAiB,QAAqB,IAAI,EAM1C,WAAW,OAAO,EAAgB,CAE9B,EAAa,QAAU,EAEvB,KAAK,aAAa,CACtB,CAEA,WAAW,QAAkB,CACzB,OAAO,EAAa,OACxB,CAOA,WAAW,MAAM,EAAmB,CAChC,EAAc,CAAK,CACvB,CAEA,WAAW,OAAoB,CAC3B,OAAO,EAAc,CACzB,CAaA,WAAW,eAAe,EAAgB,CACtC,EAAU,uBAAuB,CAAK,EACtC,IAAM,EAAW,EAAa,gBAE9B,EAAa,gBAAkB,EAC3B,CAAC,GAAY,GAAS,EAAY,KAAO,GAAG,KAAK,mBAAmB,CAC5E,CAEA,WAAW,gBAA0B,CACjC,OAAO,EAAa,eACxB,CAEA,OAAiB,eAAe,EAAoC,CAGhE,MADA,GADI,IAAU,IAAA,IAAa,IAAU,IACjC,EAAa,SAAW,EAAM,KAAK,IAAM,GAEjD,CAIA,OAAiB,mBAAmB,EAA2B,CAC3D,IAAM,EAAU,EAAa,SAC7B,GAAI,IAAY,IAAA,GAAW,OAAO,EAClC,IAAM,EAAS,EAAa,QAG5B,OADK,EAAO,cACL,EAAO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,KAAK,OAAO,IAAI,CAAS,EACvC,GAAI,IAAU,IAAA,GACV,MAAO,CAAE,IAAK,EAAW,OAAM,CAEvC,CAEA,MAAO,CAAE,IAAK,EAAe,GAAc,MAAO,IAAA,EAAU,CAChE,CAEA,WAAqB,QAA+B,CAChD,GAAI,EAAY,OAAS,EAAG,CACxB,IAAM,EAAS,EAAa,QAEtB,EAAsC,CAAE,GAAG,EAAO,SAAS,CAAE,EAE/D,EAAQ,IAAI,IAGhB,GAAI,EAAO,cAAe,CAEtB,IAAM,EAAiB,KAAK,sBAAsB,EAClD,EACI,yBAAyB,EAAe,SAAW,EAAI,SAAW,EAAe,KAAK,IAAI,GAC9F,EACA,GAAI,CACA,EAAQ,EAAW,CACf,GAAG,KAAK,2BACR,KAAM,EACN,WAAY,EACZ,SAAU,EAAO,SAAS,KAAK,CAAM,CACzC,CAAC,CACL,MAAQ,CAAC,CACb,CACA,EAAa,iBAAmB,EAChC,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAW,EAAG,EAAY,IAAI,EAAK,CAAK,EAClF,EAAa,oBAAoB,EAAY,KAAK,YAAY,EAC1D,EAAa,iBAAiB,KAAK,mBAAmB,CAC9D,CAEA,OAAO,CACX,CAOA,OAAO,MAAa,CAChB,KAAU,MACd,CAQA,OAAO,UAAU,EAAyB,CACtC,EAAa,QAAU,EACvB,EAAsB,CAAM,EAC5B,KAAK,aAAa,CACtB,CAKA,OAAO,EAAsC,CACzC,OAAO,EAAa,gBAAgB,CAAG,CAAC,CAAC,KAC7C,CACJ"}
@@ -1 +1 @@
1
- {"version":3,"file":"EnvironmentMethods.mjs","names":[],"sources":["../../../src/core/EnvironmentMethods.ts"],"sourcesContent":["import { debugWarn } from '../Debug';\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\nimport { EnvapterBase } from './EnvapterBase';\n\nimport type { EnvProfile, ProfilesConfig } from '../types';\n\n/**\n * Environment types supported by Envapter\n * @public\n */\nexport enum Environment {\n Development,\n Staging,\n Production,\n Test\n}\n\n// Keys carrying the environment name, highest precedence first. Checked in order until the first with a non-empty value is found, or defaulting to development if none are set.\nconst ENV_KEYS = ['ENVIRONMENT', 'ENV', 'NODE_ENV', 'MODE'] as const;\n\nfunction parseEnvironment(raw: string): Environment | undefined {\n switch (raw.toLowerCase()) {\n case 'production':\n return Environment.Production;\n case 'staging':\n return Environment.Staging;\n case 'test':\n return Environment.Test;\n case 'development':\n return Environment.Development;\n default:\n return undefined;\n }\n}\n\n/**\n * Mixin for environment detection and checking methods\n * @internal\n */\nexport class EnvironmentMethods extends EnvapterBase {\n protected static _environment: Environment | undefined;\n protected static _environmentExplicitlySet = false;\n protected static _profiles: ProfilesConfig | undefined;\n\n protected static determineEnvironment(env?: string | Environment): void {\n if (typeof env === 'number') {\n this._environment = env;\n this._environmentExplicitlySet = true;\n return;\n }\n if (typeof env === 'string') {\n this._environment = parseEnvironment(env) ?? Environment.Development;\n this._environmentExplicitlySet = true;\n return;\n }\n\n const raw = this.firstEnvKeyValue((key) => {\n const value = this.config.get(key);\n return typeof value === 'string' ? value : undefined;\n });\n if (raw === undefined) {\n debugWarn(`no environment set (looked for ${ENV_KEYS.join(', ')}); defaulting to development`);\n this._environment = Environment.Development;\n return;\n }\n const parsed = parseEnvironment(raw);\n if (parsed === undefined) {\n debugWarn(`unrecognized environment \"${raw}\"; defaulting to development`);\n this._environment = Environment.Development;\n return;\n }\n this._environment = parsed;\n }\n\n private static firstEnvKeyValue(read: (key: string) => string | undefined): string | undefined {\n for (const key of ENV_KEYS) {\n const value = read(key);\n if (value !== undefined && value.length > 0) return value;\n }\n return undefined;\n }\n\n /**\n * Get the current application environment\n */\n static get environment(): Environment {\n if (this._environment === undefined) {\n this.determineEnvironment();\n }\n return this._environment as Environment;\n }\n\n /**\n * Set the application environment. Accepts either Environment enum or string value.\n */\n static set environment(env: string | Environment) {\n this.determineEnvironment(env);\n }\n\n /**\n * @see {@link EnvironmentMethods.environment}\n */\n get environment(): Environment {\n return EnvironmentMethods.environment;\n }\n\n /**\n * @see {@link EnvironmentMethods.environment}\n */\n set environment(env: string | Environment) {\n EnvironmentMethods.determineEnvironment(env);\n }\n\n /**\n * Check if the current environment is production\n */\n static get isProduction(): boolean {\n return this.environment === Environment.Production;\n }\n\n /**\n * @see {@link EnvironmentMethods.isProduction}\n */\n get isProduction(): boolean {\n return EnvironmentMethods.environment === Environment.Production;\n }\n\n /**\n * Check if the current environment is staging\n */\n static get isStaging(): boolean {\n return this.environment === Environment.Staging;\n }\n\n /**\n * @see {@link EnvironmentMethods.isStaging}\n */\n get isStaging(): boolean {\n return EnvironmentMethods.environment === Environment.Staging;\n }\n\n /**\n * Check if the current environment is development\n */\n static get isDevelopment(): boolean {\n return this.environment === Environment.Development;\n }\n\n /**\n * @see {@link EnvironmentMethods.isDevelopment}\n */\n get isDevelopment(): boolean {\n return EnvironmentMethods.environment === Environment.Development;\n }\n\n /**\n * Check if the current environment is test\n */\n static get isTest(): boolean {\n return this.environment === Environment.Test;\n }\n\n /**\n * @see {@link EnvironmentMethods.isTest}\n */\n get isTest(): boolean {\n return EnvironmentMethods.environment === Environment.Test;\n }\n\n protected static override refreshCache(): void {\n // If the env was inferred (not user-set), reset it so re-hydration re-determines\n // from current state. If the user explicitly set Envapter.environment = X, preserve\n // that value through the refresh. The immediate re-hydration inside super.refreshCache()\n // will use it for cascade selection.\n if (!this._environmentExplicitlySet) this._environment = undefined;\n super.refreshCache();\n }\n\n /**\n * Reads the source's raw vars (not `this.config`, which would recurse: cascade selection runs\n * before the `.env` load). `Envapter.environment` may differ post-load if a file sets `ENVIRONMENT`.\n * @internal\n */\n protected static getCascadeEnvironment(): Environment {\n if (this._environment !== undefined) return this._environment;\n\n const vars = EnvapterBase._source.readVars();\n const raw = this.firstEnvKeyValue((key) => vars[key]);\n return raw === undefined ? Environment.Development : (parseEnvironment(raw) ?? Environment.Development);\n }\n\n /**\n * Build the dotenv-flow cascade for a given environment, in dotenv first-wins precedence\n * order (highest precedence first). Missing files are silently filtered.\n *\n * Precedence is **most-specific-wins** (matches Vite / Astro / Vocs):\n * `.env.${env}.local` \\> `.env.${env}` \\> `.env.local` \\> `.env`\n *\n * This differs from dotenv-flow / Next.js convention which puts `.env.local` above\n * `.env.${env}`. We chose the most-specific-wins order so committed env-specific files\n * (`.env.production`) are authoritative for that environment regardless of whether a\n * stray `.env.local` is present.\n * @internal\n */\n protected static buildCascadePaths(env: Environment): string[] {\n const envName = Environment[env].toLowerCase();\n return [`.env.${envName}.local`, `.env.${envName}`, '.env.local', '.env']\n .map((name) => this.resolveAgainstBase(name))\n .filter((p) => this.sourceFileExists(p));\n }\n\n private static normalizeProfilePaths(profile: EnvProfile | undefined): string[] {\n if (!profile) return [];\n return Array.isArray(profile.paths) ? profile.paths : [profile.paths];\n }\n\n /**\n * Override the base implementation to layer the dotenv-flow cascade + any\n * `Envapter.configureProfiles` overrides on top of `_envPaths` when the user has NOT\n * explicitly set `envPaths`.\n *\n * Precedence (passed to dotenv with first-wins semantics):\n * 1. profile-configured paths for the current env (if any)\n * 2. `.env.${env}.local`\n * 3. `.env.${env}`\n * 4. `.env.local`\n * 5. `.env`\n *\n * If `useDefaults: false` is set on the profiles config, only (1) is loaded, no cascade.\n * If `envPaths` was explicitly set, only `envPaths` is loaded (everything else ignored).\n * @internal\n */\n protected static override resolveEffectivePaths(): string[] {\n if (this._envPathsExplicitlySet) return this._envPaths.map((p) => this.resolveAgainstBase(p));\n\n const env = this.getCascadeEnvironment();\n const profileEntry = this._profiles?.[env];\n const profilePaths = this.normalizeProfilePaths(profileEntry);\n\n // Validate that explicitly configured profile paths exist for the active env.\n if (profilePaths.length > 0) {\n const missing = profilePaths.filter((p) => !this.sourceFileExists(this.resolveAgainstBase(p)));\n if (missing.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.EnvFilesNotFound,\n `Environment file not found at path: ${missing.join(', ')}`\n );\n }\n }\n\n const cascade = this._profiles?.useDefaults === false ? [] : this.buildCascadePaths(env);\n return [...profileP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M,KAAK,iBAAiB,CAAC,CAAC,CAC/C,CAEA,OAAe,sBAAsB,EAA2C,CAE5E,OADK,EACE,MAAM,QAAQ,EAAQ,KAAK,EAAI,EAAQ,MAAQ,CAAC,EAAQ,KAAK,EAD/C,CAAC,CAE1B,CAkBA,OAA0B,uBAAkC,CACxD,GAAI,KAAK,uBAAwB,OAAO,KAAK,UAAU,IAAK,GAAM,KAAK,mBAAmB,CAAC,CAAC,EAE5F,IAAM,EAAM,KAAK,sBAAsB,EACjC,EAAe,KAAK,YAAY,GAChC,EAAe,KAAK,sBAAsB,CAAY,EAG5D,GAAI,EAAa,OAAS,EAAG,CACzB,IAAM,EAAU,EAAa,OAAQ,GAAM,CAAC,KAAK,iBAAiB,KAAK,mBAAmB,CAAC,CAAC,CAAC,EAC7F,GAAI,EAAQ,OAAS,EACjB,MAAM,IAAI,EAAA,IAEN,uCAAuC,EAAQ,KAAK,IAAI,GAC5D,CAER,CAEA,IAAM,EAAU,KAAK,WAAW,cAAgB,GAAQ,CAAC,EAAI,KAAK,kBAAkB,CAAG,EACvF,MAAO,CAAC,GAAG,EAAa,IAAK,GAAM,KAAK,mBAAmB,CAAC,CAAC,EAAG,GAAG,CAAO,CAC9E,CACJ"}
1
+ {"version":3,"file":"EnvironmentMethods.mjs","names":[],"sources":["../../../src/core/EnvironmentMethods.ts"],"sourcesContent":["import { debugWarn } from '../Debug';\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\nimport { EnvapterBase } from './EnvapterBase';\n\nimport type { EnvProfile, ProfilesConfig } from '../types';\n\n/**\n * Environment types supported by Envapter\n * @public\n */\nexport enum Environment {\n Development,\n Staging,\n Production,\n Test\n}\n\n// Keys carrying the environment name, highest precedence first. Checked in order until the first with a non-empty value is found, or defaulting to development if none are set.\nconst ENV_KEYS = ['ENVIRONMENT', 'ENV', 'NODE_ENV', 'MODE'] as const;\n\nfunction parseEnvironment(raw: string): Environment | undefined {\n switch (raw.toLowerCase()) {\n case 'production':\n return Environment.Production;\n case 'staging':\n return Environment.Staging;\n case 'test':\n return Environment.Test;\n case 'development':\n return Environment.Development;\n default:\n return undefined;\n }\n}\n\n/**\n * Mixin for environment detection and checking methods\n * @internal\n */\nexport class EnvironmentMethods extends EnvapterBase {\n protected static _environment: Environment | undefined;\n protected static _environmentExplicitlySet = false;\n protected static _profiles: ProfilesConfig | undefined;\n\n protected static determineEnvironment(env?: string | Environment): void {\n if (typeof env === 'number') {\n this._environment = env;\n this._environmentExplicitlySet = true;\n return;\n }\n if (typeof env === 'string') {\n this._environment = parseEnvironment(env) ?? Environment.Development;\n this._environmentExplicitlySet = true;\n return;\n }\n\n const raw = this.firstEnvKeyValue((key) => {\n const value = this.config.get(key);\n return typeof value === 'string' ? value : undefined;\n });\n if (raw === undefined) {\n debugWarn(`no environment set (looked for ${ENV_KEYS.join(', ')}); defaulting to development`);\n this._environment = Environment.Development;\n return;\n }\n const parsed = parseEnvironment(raw);\n if (parsed === undefined) {\n debugWarn(`unrecognized environment \"${raw}\"; defaulting to development`);\n this._environment = Environment.Development;\n return;\n }\n this._environment = parsed;\n }\n\n private static firstEnvKeyValue(read: (key: string) => string | undefined): string | undefined {\n for (const key of ENV_KEYS) {\n const value = read(key);\n if (value !== undefined && value.length > 0) return value;\n }\n return undefined;\n }\n\n /**\n * Get the current application environment\n */\n static get environment(): Environment {\n if (this._environment === undefined) {\n this.determineEnvironment();\n }\n return this._environment as Environment;\n }\n\n /**\n * Set the application environment. Accepts either Environment enum or string value.\n */\n static set environment(env: string | Environment) {\n this.determineEnvironment(env);\n }\n\n /**\n * @see {@link EnvironmentMethods.environment}\n */\n get environment(): Environment {\n return EnvironmentMethods.environment;\n }\n\n /**\n * @see {@link EnvironmentMethods.environment}\n */\n set environment(env: string | Environment) {\n EnvironmentMethods.determineEnvironment(env);\n }\n\n /**\n * Check if the current environment is production\n */\n static get isProduction(): boolean {\n return this.environment === Environment.Production;\n }\n\n /**\n * @see {@link EnvironmentMethods.isProduction}\n */\n get isProduction(): boolean {\n return EnvironmentMethods.environment === Environment.Production;\n }\n\n /**\n * Check if the current environment is staging\n */\n static get isStaging(): boolean {\n return this.environment === Environment.Staging;\n }\n\n /**\n * @see {@link EnvironmentMethods.isStaging}\n */\n get isStaging(): boolean {\n return EnvironmentMethods.environment === Environment.Staging;\n }\n\n /**\n * Check if the current environment is development\n */\n static get isDevelopment(): boolean {\n return this.environment === Environment.Development;\n }\n\n /**\n * @see {@link EnvironmentMethods.isDevelopment}\n */\n get isDevelopment(): boolean {\n return EnvironmentMethods.environment === Environment.Development;\n }\n\n /**\n * Check if the current environment is test\n */\n static get isTest(): boolean {\n return this.environment === Environment.Test;\n }\n\n /**\n * @see {@link EnvironmentMethods.isTest}\n */\n get isTest(): boolean {\n return EnvironmentMethods.environment === Environment.Test;\n }\n\n protected static override refreshCache(): void {\n // If the env was inferred (not user-set), reset it so re-hydration re-determines\n // from current state. If the user explicitly set Envapter.environment = X, preserve\n // that value through the refresh. The immediate re-hydration inside super.refreshCache()\n // will use it for cascade selection.\n if (!this._environmentExplicitlySet) this._environment = undefined;\n super.refreshCache();\n }\n\n /**\n * Reads the source's raw vars (not `this.config`, which would recurse: cascade selection runs\n * before the `.env` load). `Envapter.environment` may differ post-load if a file sets `ENVIRONMENT`.\n * @internal\n */\n protected static getCascadeEnvironment(): Environment {\n if (this._environment !== undefined) return this._environment;\n\n const vars = EnvapterBase._source.readVars();\n const raw = this.firstEnvKeyValue((key) => vars[key]);\n return raw === undefined ? Environment.Development : (parseEnvironment(raw) ?? Environment.Development);\n }\n\n /**\n * Build the dotenv-flow cascade for a given environment, in dotenv first-wins precedence\n * order (highest precedence first). Missing files are silently filtered.\n *\n * Precedence is **most-specific-wins** (matches Vite / Astro / Vocs):\n * `.env.${env}.local` \\> `.env.${env}` \\> `.env.local` \\> `.env`\n *\n * This differs from dotenv-flow / Next.js convention which puts `.env.local` above\n * `.env.${env}`. We chose the most-specific-wins order so committed env-specific files\n * (`.env.production`) are authoritative for that environment regardless of whether a\n * stray `.env.local` is present.\n * @internal\n */\n protected static buildCascadePaths(env: Environment): string[] {\n const envName = Environment[env].toLowerCase();\n return [`.env.${envName}.local`, `.env.${envName}`, '.env.local', '.env']\n .map((name) => this.resolveAgainstBase(name))\n .filter((p) => this.sourceFileExists(p));\n }\n\n private static normalizeProfilePaths(profile: EnvProfile | undefined): string[] {\n if (!profile) return [];\n return Array.isArray(profile.paths) ? profile.paths : [profile.paths];\n }\n\n /**\n * Override the base implementation to layer the dotenv-flow cascade + any\n * `Envapter.configureProfiles` overrides on top of `_envPaths` when the user has NOT\n * explicitly set `envPaths`.\n *\n * Precedence (passed to dotenv with first-wins semantics):\n * 1. profile-configured paths for the current env (if any)\n * 2. `.env.${env}.local`\n * 3. `.env.${env}`\n * 4. `.env.local`\n * 5. `.env`\n *\n * If `useDefaults: false` is set on the profiles config, only (1) is loaded, no cascade.\n * If `envPaths` was explicitly set, only `envPaths` is loaded (everything else ignored).\n * @internal\n */\n protected static override resolveEffectivePaths(): string[] {\n if (this._envPathsExplicitlySet) return this._envPaths.map((p) => this.resolveAgainstBase(p));\n\n const env = this.getCascadeEnvironment();\n const profileEntry = this._profiles?.[env];\n const profilePaths = this.normalizeProfilePaths(profileEntry);\n\n // Validate that explicitly configured profile paths exist for the active env.\n if (profilePaths.length > 0) {\n const missing = profilePaths.filter((p) => !this.sourceFileExists(this.resolveAgainstBase(p)));\n if (missing.length > 0) {\n throw new EnvaptError(\n EnvaptErrorCodes.EnvFilesNotFound,\n `Environment file not found at path: ${missing.join(', ')}`\n );\n }\n }\n\n const cascade = this._profiles?.useDefaults === false ? [] : this.buildCascadePaths(env);\n return [...profilePaths.map((p) => this.resolveAgainstBase(p)), ...cascade];\n }\n}\n"],"mappings":"sIAUA,IAAY,EAAL,SAAA,EAAA,OACH,GAAA,EAAA,YAAA,GAAA,cACA,EAAA,EAAA,QAAA,GAAA,UACA,EAAA,EAAA,WAAA,GAAA,aACA,EAAA,EAAA,KAAA,GAAA,QACJ,EAAA,CAAA,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,KAAK,uBAAwB,OAAO,KAAK,UAAU,IAAK,GAAM,KAAK,mBAAmB,CAAC,CAAC,EAE5F,IAAM,EAAM,KAAK,sBAAsB,EACjC,EAAe,KAAK,YAAY,GAChC,EAAe,KAAK,sBAAsB,CAAY,EAG5D,GAAI,EAAa,OAAS,EAAG,CACzB,IAAM,EAAU,EAAa,OAAQ,GAAM,CAAC,KAAK,iBAAiB,KAAK,mBAAmB,CAAC,CAAC,CAAC,EAC7F,GAAI,EAAQ,OAAS,EACjB,MAAM,IAAI,EAAA,IAEN,uCAAuC,EAAQ,KAAK,IAAI,GAC5D,CAER,CAEA,IAAM,EAAU,KAAK,WAAW,cAAgB,GAAQ,CAAC,EAAI,KAAK,kBAAkB,CAAG,EACvF,MAAO,CAAC,GAAG,EAAa,IAAK,GAAM,KAAK,mBAAmB,CAAC,CAAC,EAAG,GAAG,CAAO,CAC9E,CACJ"}
@@ -1,5 +1,5 @@
1
1
  import { ArrayOf } from "../converters/Converters.mjs";
2
- import { BuiltInConverter, ConverterFunction, InferConverterFallbackType, InferPrimitiveFallbackType, InferPrimitiveReturnType, PrimitiveConstructor } from "../types/Conversion.mjs";
2
+ import { BuiltInConverter, ConverterFunction, InferConverterFallbackType, InferPrimitiveReturnType, PrimitiveConstructor } from "../types/Conversion.mjs";
3
3
  import { InferSchemaOutput, StandardSchemaV1 } from "../StandardSchema.mjs";
4
4
  import { SchemaConstraint } from "../types/Schema.mjs";
5
5
  import { EnvKeyInput } from "../types/Env.mjs";
@@ -173,7 +173,7 @@ declare function Envapt(key: EnvKeyInput, options: {
173
173
  required: true;
174
174
  }): PropertyDecorator;
175
175
  /**
176
- * Classic API: No fallback
176
+ * No-fallback form. The property resolves from env or `null`.
177
177
  *
178
178
  * @param key - Environment variable name(s) to load
179
179
  * @public
@@ -187,31 +187,6 @@ declare function Envapt(key: EnvKeyInput, options: {
187
187
  * ```
188
188
  */
189
189
  declare function Envapt<_TReturnType = string | null>(key: EnvKeyInput): PropertyDecorator;
190
- /**
191
- * Classic API: Primitive fallback only
192
- *
193
- * @param key - Environment variable name(s) to load
194
- * @param fallback - Default primitive value
195
- * @param converter - Optional primitive constructor (String, Number, etc.)
196
- * @public
197
- * @deprecated - Use the options object: `@Envapt('KEY', { converter, fallback })`. The positional
198
- * form only accepts primitive constructors and cannot express built-in tokens, array/custom
199
- * converters, `schema`, or `required`. Deprecated in v5, removed in v6.
200
- * @example
201
- * ```ts
202
- * // Classic API with primitive fallback and optional primitive converter
203
- * class Config extends Envapter {
204
- * // Provide fallback only
205
- * \@Envapt('HOST', 'localhost')
206
- * static readonly host: string;
207
- *
208
- * // Provide fallback and converter
209
- * \@Envapt('PORT', 8080, Number)
210
- * static readonly port: number;
211
- * }
212
- * ```
213
- */
214
- declare function Envapt<TFallback extends string | number | boolean | bigint | symbol | undefined>(key: EnvKeyInput, fallback: InferPrimitiveFallbackType<TFallback>, converter?: PrimitiveConstructor): PropertyDecorator;
215
190
  /**
216
191
  * Usage 6: Standard Schema v1 adapter (zod, valibot, arktype, hand-rolled). Synchronous
217
192
  * schemas only; a Promise-returning `validate` triggers a runtime
@@ -1,2 +1,2 @@
1
- import{EnvaptError as e}from"../Error.mjs";import{Validator as t}from"../Validators.mjs";import{createPropertyDecorator as n}from"./createPropertyDecorator.mjs";function r(r,i,a){let o,s,c,l=!0,u=!1;if(i&&typeof i==`object`&&(`fallback`in i||`converter`in i||`required`in i||`schema`in i)){let n=i;if(o=n.fallback,s=n.converter,l=`fallback`in n,u=n.required===!0,u&&l&&o!==void 0)throw new e(302,"`required: true` and `fallback` are mutually exclusive on @Envapt options. Drop the fallback or call `Envapter.require()` separately.");if(`schema`in n&&n.schema!==void 0){if(!t.isStandardSchema(n.schema))throw new e(302,"`schema` must be a Standard Schema v1 object (zod, valibot, arktype, or any `~standard`-conformant value).");if(s!==void 0)throw new e(302,"`schema` and `converter` are mutually exclusive on @Envapt options. Drop one as they both turn a raw env string into a typed value.");c=n.schema}}else o=i,s=a,l=arguments.length>1;return n(r,{fallback:o,converter:s,hasFallback:l,required:u,schema:c})}export{r as Envapt};
1
+ import{EnvaptError as e}from"../Error.mjs";import{Validator as t}from"../Validators.mjs";import{createPropertyDecorator as n}from"./createPropertyDecorator.mjs";function r(r,i){let a,o,s,c=!1,l=!1;if(i!==void 0){if(typeof i!=`object`||!i||!(`fallback`in i||`converter`in i||`required`in i||`schema`in i))throw new e(302,"The positional `@Envapt(key, fallback, converter)` form was removed in v6. Pass an options object instead, like `@Envapt(key, { converter, fallback })`, or use one of the sugar decorators.");let n=i;if(a=n.fallback,o=n.converter,c=`fallback`in n,l=n.required===!0,l&&c&&a!==void 0)throw new e(302,"`required: true` and `fallback` are mutually exclusive on @Envapt options. Drop the fallback or call `Envapter.require()` separately.");if(`schema`in n&&n.schema!==void 0){if(!t.isStandardSchema(n.schema))throw new e(302,"`schema` must be a Standard Schema v1 object (zod, valibot, arktype, or any `~standard`-conformant value).");if(o!==void 0)throw new e(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=n.schema}}return n(r,{fallback:a,converter:o,hasFallback:c,required:l,schema:s})}export{r as Envapt};
2
2
  //# sourceMappingURL=Envapt.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"Envapt.mjs","names":[],"sources":["../../../src/decorators/Envapt.ts"],"sourcesContent":["import { createPropertyDecorator } from './createPropertyDecorator';\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\nimport { Validator } from '../Validators';\n\nimport type { ArrayOf } from '../converters';\nimport type { InferSchemaOutput, StandardSchemaV1 } from '../StandardSchema';\nimport type {\n BuiltInConverter,\n ConverterFunction,\n EnvKeyInput,\n EnvaptConverter,\n EnvaptOptions,\n InferConverterFallbackType,\n InferPrimitiveFallbackType,\n InferPrimitiveReturnType,\n PrimitiveConstructor,\n SchemaConstraint\n} from '../types';\n\n/**\n * Usage 1: Either a custom converter function + fallback (both required), OR a fallback\n * only (no converter).\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * // Custom converter that validates a non-empty API key\n * \\@Envapt('API_KEY', {\n * fallback: 'default-key',\n * converter(raw, _fallback) {\n * if (!raw || raw.trim() === '') throw new Error('API_KEY required');\n * return raw.trim();\n * }\n * })\n * static readonly apiKey: string;\n *\n * // Fallback-only (no converter): string fallback\n * \\@Envapt('LOG_FILE', { fallback: '/var/log/app.log' })\n * static readonly logFile: string;\n *\n * // Fallback-only: arbitrary object fallback\n * \\@Envapt('RETRY_POLICY', { fallback: { retries: 3, backoff: 'exponential' } })\n * static readonly retryPolicy: unknown;\n * }\n * ```\n */\nexport function Envapt<TFallback>(\n key: EnvKeyInput,\n options:\n | { converter: (raw: string | undefined, fallback: TFallback) => TFallback; fallback: TFallback }\n | { fallback: TFallback; converter?: undefined }\n): PropertyDecorator;\n\n/**\n * Usage 2: Custom converter function without fallback. Either omit `required` (returns the\n * converter's output, possibly `undefined`) or pass `required: true` to throw `MissingEnvValue`\n * on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with custom converter only, with optional `required: true`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('FEATURE_FLAGS', { converter(raw) {\n * return raw ? raw.split('|').map(s => s.trim()) : [];\n * } })\n * static readonly featureFlags: string[];\n *\n * \\@Envapt('JWT_SECRET', {\n * converter: (raw) => Buffer.from(raw ?? '', 'base64'),\n * required: true\n * })\n * declare static readonly jwtSecret: Buffer;\n * }\n * ```\n */\nexport function Envapt<TReturnType>(\n key: EnvKeyInput,\n options:\n | { converter: ConverterFunction<TReturnType>; required?: false }\n | { converter: ConverterFunction<TReturnType>; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 3: Built-in or array converter with optional fallback OR `required: true`.\n *\n * `InferConverterFallbackType` handles asymmetric cases: scalar `Converters.Time` accepts\n * `TimeFallback`, and `ArrayOf<'time'>` accepts `TimeFallback[]`. Every other converter\n * reduces to `InferConverterReturnType`. The two object-shape branches are mutually\n * exclusive: either provide a `fallback`, or pass `required: true` to throw\n * `MissingEnvValue` on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * import { Converters } from 'envapt';\n *\n * class Config extends Envapter {\n * // Use built-in Number converter with a numeric fallback\n * \\@Envapt('APP_PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * // Url converter: the fallback is a URL instance, not a string\n * \\@Envapt('APP_URL', { converter: Converters.Url, fallback: new URL('http://localhost:3000') })\n * static readonly url: URL;\n *\n * // Prefer CANARY_URL when present, otherwise fall back to APP_URL\n * \\@Envapt(['CANARY_URL', 'APP_URL'], { converter: Converters.Url })\n * static readonly canaryUrl: URL | null;\n *\n * // `Converters.Time` accepts either a number (milliseconds) or a time-string fallback (`<number><unit>`).\n * \\@Envapt('REQUEST_TIMEOUT', { converter: Converters.Time, fallback: '10s' })\n * static readonly requestTimeout: number;\n *\n * // Array converter: comma-separated list of origins -> string[]\n * \\@Envapt('ALLOWED_ORIGINS', {\n * converter: Converters.array({ of: Converters.String }),\n * fallback: ['https://example.com']\n * })\n * static readonly allowedOrigins: string[];\n *\n * \\@Envapt('DATABASE_URL', { converter: Converters.Url, required: true })\n * declare static readonly databaseUrl: URL;\n * }\n * ```\n */\nexport function Envapt<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options:\n | { converter: TConverter; fallback?: InferConverterFallbackType<TConverter> | undefined; required?: false }\n | { converter: TConverter; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 4: Primitive constructor with optional fallback\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with primitive constructor\n * @public\n * @example\n * ```ts\n * // Use primitive constructors to coerce values\n * class Config extends Envapter {\n * \\@Envapt('MAX_CONNECTIONS', { converter: Number, fallback: 100 })\n * static readonly maxConnections: number;\n *\n * \\@Envapt('FEATURE_ENABLED', { converter: Boolean, fallback: false })\n * static readonly featureEnabled: boolean;\n * }\n * ```\n */\nexport function Envapt<TConstructor extends PrimitiveConstructor>(\n key: EnvKeyInput,\n options:\n | { converter: TConstructor; fallback?: InferPrimitiveReturnType<TConstructor>; required?: false }\n | { converter: TConstructor; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 5: Required, no converter (raw string). Throws `MissingEnvValue` on first access if\n * the env value is missing or empty (post-trim). Independent of global `Envapter.strict`.\n * Combining `required: true` with `fallback` fails to match any overload at compile time;\n * the runtime Validator catches dynamic objects that bypass the types.\n *\n * @param key - Environment variable name(s) to load\n * @param options - `{ required: true }`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('API_KEY', { required: true })\n * declare static readonly apiKey: string;\n * }\n * ```\n */\nexport function Envapt(key: EnvKeyInput, options: { required: true }): PropertyDecorator;\n\n/**\n * Classic API: No fallback\n *\n * @param key - Environment variable name(s) to load\n * @public\n * @example\n * ```ts\n * // Classic API: no fallback — property will resolve from env or be null\n * class Config extends Envapter {\n * \\@Envapt('SIMPLE_VALUE')\n * static readonly simple?: string | null;\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function Envapt<_TReturnType = string | null>(key: EnvKeyInput): PropertyDecorator;\n\n/**\n * Classic API: Primitive fallback only\n *\n * @param key - Environment variable name(s) to load\n * @param fallback - Default primitive value\n * @param converter - Optional primitive constructor (String, Number, etc.)\n * @public\n * @deprecated - Use the options object: `@Envapt('KEY', { converter, fallback })`. The positional\n * form only accepts primitive constructors and cannot express built-in tokens, array/custom\n * converters, `schema`, or `required`. Deprecated in v5, removed in v6.\n * @example\n * ```ts\n * // Classic API with primitive fallback and optional primitive converter\n * class Config extends Envapter {\n * // Provide fallback only\n * \\@Envapt('HOST', 'localhost')\n * static readonly host: string;\n *\n * // Provide fallback and converter\n * \\@Envapt('PORT', 8080, Number)\n * static readonly port: number;\n * }\n * ```\n */\nexport function Envapt<TFallback extends string | number | boolean | bigint | symbol | undefined>(\n key: EnvKeyInput,\n fallback: InferPrimitiveFallbackType<TFallback>,\n converter?: PrimitiveConstructor\n): PropertyDecorator;\n\n/**\n * Usage 6: Standard Schema v1 adapter (zod, valibot, arktype, hand-rolled). Synchronous\n * schemas only; a Promise-returning `validate` triggers a runtime\n * `InvalidUserDefinedConfig` throw. Combining `schema` with `converter` fails to match any\n * overload at compile time; the runtime Validator catches dynamic objects that bypass the\n * types.\n * @public\n */\nexport function Envapt<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n options:\n | { schema: SchemaConstraint<Schema>; fallback?: InferSchemaOutput<Schema>; required?: false }\n | { schema: SchemaConstraint<Schema>; required: true }\n): PropertyDecorator;\n\n/**\n * Instance/Static Property decorator that automatically loads and converts environment variables.\n */\nexport function Envapt<TFallback = unknown>(\n key: EnvKeyInput,\n fallbackOrOptions?: TFallback | EnvaptOptions<TFallback>,\n converter?: EnvaptConverter<TFallback>\n): PropertyDecorator {\n // Determine if using new options API or classic API\n let fallback: TFallback | undefined;\n let actualConverter: EnvaptConverter<TFallback> | undefined;\n let actualSchema: StandardSchemaV1 | undefined;\n let hasFallback = true;\n let required = false;\n\n if (\n fallbackOrOptions &&\n typeof fallbackOrOptions === 'object' &&\n ('fallback' in fallbackOrOptions ||\n 'converter' in fallbackOrOptions ||\n 'required' in fallbackOrOptions ||\n 'schema' in fallbackOrOptions)\n ) {\n const options = fallbackOrOptions as {\n fallback?: TFallback;\n converter?: EnvaptConverter<TFallback>;\n required?: boolean;\n schema?: unknown;\n };\n fallback = options.fallback;\n actualConverter = options.converter;\n hasFallback = 'fallback' in options;\n required = options.required === true;\n\n if (required && hasFallback && fallback !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`required: true` and `fallback` are mutually exclusive on @Envapt options. Drop the fallback or call `Envapter.require()` separately.'\n );\n }\n\n if ('schema' in options && options.schema !== undefined) {\n if (!Validator.isStandardSchema(options.schema)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` must be a Standard Schema v1 object (zod, valibot, arktype, or any `~standard`-conformant value).'\n );\n }\n if (actualConverter !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` and `converter` are mutually exclusive on @Envapt options. Drop one as they both turn a raw env string into a typed value.'\n );\n }\n actualSchema = options.schema;\n }\n } else {\n // Classic API\n fallback = fallbackOrOptions as TFallback;\n actualConverter = converter;\n hasFallback = arguments.length > 1;\n }\n\n return createPropertyDecorator(key, {\n fallback,\n converter: actualConverter,\n hasFallback,\n required,\n schema: actualSchema\n });\n}\n"],"mappings":"iKAwPA,SAAgB,EACZ,EACA,EACA,EACiB,CAEjB,IAAI,EACA,EACA,EACA,EAAc,GACd,EAAW,GAEf,GACI,GACA,OAAO,GAAsB,WAC5B,aAAc,GACX,cAAe,GACf,aAAc,GACd,WAAY,GAClB,CACE,IAAM,EAAU,EAWhB,GALA,EAAW,EAAQ,SACnB,EAAkB,EAAQ,UAC1B,EAAc,aAAc,EAC5B,EAAW,EAAQ,WAAa,GAE5B,GAAY,GAAe,IAAa,IAAA,GACxC,MAAM,IAAI,EAAA,IAEN,uIACJ,EAGJ,GAAI,WAAY,GAAW,EAAQ,SAAW,IAAA,GAAW,CACrD,GAAI,CAAC,EAAU,iBAAiB,EAAQ,MAAM,EAC1C,MAAM,IAAI,EAAA,IAEN,4GACJ,EAEJ,GAAI,IAAoB,IAAA,GACpB,MAAM,IAAI,EAAA,IAEN,qIACJ,EAEJ,EAAe,EAAQ,MAC3B,CACJ,MAEI,EAAW,EACX,EAAkB,EAClB,EAAc,UAAU,OAAS,EAGrC,OAAO,EAAwB,EAAK,CAChC,WACA,UAAW,EACX,cACA,WACA,OAAQ,CACZ,CAAC,CACL"}
1
+ {"version":3,"file":"Envapt.mjs","names":[],"sources":["../../../src/decorators/Envapt.ts"],"sourcesContent":["import { createPropertyDecorator } from './createPropertyDecorator';\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\nimport { Validator } from '../Validators';\n\nimport type { ArrayOf } from '../converters';\nimport type { InferSchemaOutput, StandardSchemaV1 } from '../StandardSchema';\nimport type {\n BuiltInConverter,\n ConverterFunction,\n EnvKeyInput,\n EnvaptConverter,\n InferConverterFallbackType,\n InferPrimitiveReturnType,\n PrimitiveConstructor,\n SchemaConstraint\n} from '../types';\n\n/**\n * Usage 1: Either a custom converter function + fallback (both required), OR a fallback\n * only (no converter).\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * // Custom converter that validates a non-empty API key\n * \\@Envapt('API_KEY', {\n * fallback: 'default-key',\n * converter(raw, _fallback) {\n * if (!raw || raw.trim() === '') throw new Error('API_KEY required');\n * return raw.trim();\n * }\n * })\n * static readonly apiKey: string;\n *\n * // Fallback-only (no converter): string fallback\n * \\@Envapt('LOG_FILE', { fallback: '/var/log/app.log' })\n * static readonly logFile: string;\n *\n * // Fallback-only: arbitrary object fallback\n * \\@Envapt('RETRY_POLICY', { fallback: { retries: 3, backoff: 'exponential' } })\n * static readonly retryPolicy: unknown;\n * }\n * ```\n */\nexport function Envapt<TFallback>(\n key: EnvKeyInput,\n options:\n | { converter: (raw: string | undefined, fallback: TFallback) => TFallback; fallback: TFallback }\n | { fallback: TFallback; converter?: undefined }\n): PropertyDecorator;\n\n/**\n * Usage 2: Custom converter function without fallback. Either omit `required` (returns the\n * converter's output, possibly `undefined`) or pass `required: true` to throw `MissingEnvValue`\n * on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with custom converter only, with optional `required: true`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('FEATURE_FLAGS', { converter(raw) {\n * return raw ? raw.split('|').map(s => s.trim()) : [];\n * } })\n * static readonly featureFlags: string[];\n *\n * \\@Envapt('JWT_SECRET', {\n * converter: (raw) => Buffer.from(raw ?? '', 'base64'),\n * required: true\n * })\n * declare static readonly jwtSecret: Buffer;\n * }\n * ```\n */\nexport function Envapt<TReturnType>(\n key: EnvKeyInput,\n options:\n | { converter: ConverterFunction<TReturnType>; required?: false }\n | { converter: ConverterFunction<TReturnType>; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 3: Built-in or array converter with optional fallback OR `required: true`.\n *\n * `InferConverterFallbackType` handles asymmetric cases: scalar `Converters.Time` accepts\n * `TimeFallback`, and `ArrayOf<'time'>` accepts `TimeFallback[]`. Every other converter\n * reduces to `InferConverterReturnType`. The two object-shape branches are mutually\n * exclusive: either provide a `fallback`, or pass `required: true` to throw\n * `MissingEnvValue` on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * import { Converters } from 'envapt';\n *\n * class Config extends Envapter {\n * // Use built-in Number converter with a numeric fallback\n * \\@Envapt('APP_PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * // Url converter: the fallback is a URL instance, not a string\n * \\@Envapt('APP_URL', { converter: Converters.Url, fallback: new URL('http://localhost:3000') })\n * static readonly url: URL;\n *\n * // Prefer CANARY_URL when present, otherwise fall back to APP_URL\n * \\@Envapt(['CANARY_URL', 'APP_URL'], { converter: Converters.Url })\n * static readonly canaryUrl: URL | null;\n *\n * // `Converters.Time` accepts either a number (milliseconds) or a time-string fallback (`<number><unit>`).\n * \\@Envapt('REQUEST_TIMEOUT', { converter: Converters.Time, fallback: '10s' })\n * static readonly requestTimeout: number;\n *\n * // Array converter: comma-separated list of origins -> string[]\n * \\@Envapt('ALLOWED_ORIGINS', {\n * converter: Converters.array({ of: Converters.String }),\n * fallback: ['https://example.com']\n * })\n * static readonly allowedOrigins: string[];\n *\n * \\@Envapt('DATABASE_URL', { converter: Converters.Url, required: true })\n * declare static readonly databaseUrl: URL;\n * }\n * ```\n */\nexport function Envapt<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options:\n | { converter: TConverter; fallback?: InferConverterFallbackType<TConverter> | undefined; required?: false }\n | { converter: TConverter; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 4: Primitive constructor with optional fallback\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with primitive constructor\n * @public\n * @example\n * ```ts\n * // Use primitive constructors to coerce values\n * class Config extends Envapter {\n * \\@Envapt('MAX_CONNECTIONS', { converter: Number, fallback: 100 })\n * static readonly maxConnections: number;\n *\n * \\@Envapt('FEATURE_ENABLED', { converter: Boolean, fallback: false })\n * static readonly featureEnabled: boolean;\n * }\n * ```\n */\nexport function Envapt<TConstructor extends PrimitiveConstructor>(\n key: EnvKeyInput,\n options:\n | { converter: TConstructor; fallback?: InferPrimitiveReturnType<TConstructor>; required?: false }\n | { converter: TConstructor; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 5: Required, no converter (raw string). Throws `MissingEnvValue` on first access if\n * the env value is missing or empty (post-trim). Independent of global `Envapter.strict`.\n * Combining `required: true` with `fallback` fails to match any overload at compile time;\n * the runtime Validator catches dynamic objects that bypass the types.\n *\n * @param key - Environment variable name(s) to load\n * @param options - `{ required: true }`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('API_KEY', { required: true })\n * declare static readonly apiKey: string;\n * }\n * ```\n */\nexport function Envapt(key: EnvKeyInput, options: { required: true }): PropertyDecorator;\n\n/**\n * No-fallback form. The property resolves from env or `null`.\n *\n * @param key - Environment variable name(s) to load\n * @public\n * @example\n * ```ts\n * // Classic API: no fallback — property will resolve from env or be null\n * class Config extends Envapter {\n * \\@Envapt('SIMPLE_VALUE')\n * static readonly simple?: string | null;\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function Envapt<_TReturnType = string | null>(key: EnvKeyInput): PropertyDecorator;\n\n/**\n * Usage 6: Standard Schema v1 adapter (zod, valibot, arktype, hand-rolled). Synchronous\n * schemas only; a Promise-returning `validate` triggers a runtime\n * `InvalidUserDefinedConfig` throw. Combining `schema` with `converter` fails to match any\n * overload at compile time; the runtime Validator catches dynamic objects that bypass the\n * types.\n * @public\n */\nexport function Envapt<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n options:\n | { schema: SchemaConstraint<Schema>; fallback?: InferSchemaOutput<Schema>; required?: false }\n | { schema: SchemaConstraint<Schema>; required: true }\n): PropertyDecorator;\n\n/**\n * Instance/Static Property decorator that automatically loads and converts environment variables.\n */\nexport function Envapt<TFallback = unknown>(key: EnvKeyInput, options?: unknown): PropertyDecorator {\n let fallback: TFallback | undefined;\n let actualConverter: EnvaptConverter<TFallback> | undefined;\n let actualSchema: StandardSchemaV1 | undefined;\n let hasFallback = false;\n let required = false;\n\n if (options !== undefined) {\n if (\n typeof options !== 'object' ||\n options === null ||\n !('fallback' in options || 'converter' in options || 'required' in options || 'schema' in options)\n ) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n 'The positional `@Envapt(key, fallback, converter)` form was removed in v6. Pass an options object instead, like `@Envapt(key, { converter, fallback })`, or use one of the sugar decorators.'\n );\n }\n\n const opts = options as {\n fallback?: TFallback;\n converter?: EnvaptConverter<TFallback>;\n required?: boolean;\n schema?: unknown;\n };\n fallback = opts.fallback;\n actualConverter = opts.converter;\n hasFallback = 'fallback' in opts;\n required = opts.required === true;\n\n if (required && hasFallback && fallback !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`required: true` and `fallback` are mutually exclusive on @Envapt options. Drop the fallback or call `Envapter.require()` separately.'\n );\n }\n\n if ('schema' in opts && opts.schema !== undefined) {\n if (!Validator.isStandardSchema(opts.schema)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` must be a Standard Schema v1 object (zod, valibot, arktype, or any `~standard`-conformant value).'\n );\n }\n if (actualConverter !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` and `converter` are mutually exclusive on @Envapt options. Drop one as they both turn a raw env string into a typed value.'\n );\n }\n actualSchema = opts.schema;\n }\n }\n\n return createPropertyDecorator(key, {\n fallback,\n converter: actualConverter,\n hasFallback,\n required,\n schema: actualSchema\n });\n}\n"],"mappings":"iKAwNA,SAAgB,EAA4B,EAAkB,EAAsC,CAChG,IAAI,EACA,EACA,EACA,EAAc,GACd,EAAW,GAEf,GAAI,IAAY,IAAA,GAAW,CACvB,GACI,OAAO,GAAY,WACnB,GACA,EAAE,aAAc,GAAW,cAAe,GAAW,aAAc,GAAW,WAAY,GAE1F,MAAM,IAAI,EAAA,IAEN,8LACJ,EAGJ,IAAM,EAAO,EAWb,GALA,EAAW,EAAK,SAChB,EAAkB,EAAK,UACvB,EAAc,aAAc,EAC5B,EAAW,EAAK,WAAa,GAEzB,GAAY,GAAe,IAAa,IAAA,GACxC,MAAM,IAAI,EAAA,IAEN,uIACJ,EAGJ,GAAI,WAAY,GAAQ,EAAK,SAAW,IAAA,GAAW,CAC/C,GAAI,CAAC,EAAU,iBAAiB,EAAK,MAAM,EACvC,MAAM,IAAI,EAAA,IAEN,4GACJ,EAEJ,GAAI,IAAoB,IAAA,GACpB,MAAM,IAAI,EAAA,IAEN,qIACJ,EAEJ,EAAe,EAAK,MACxB,CACJ,CAEA,OAAO,EAAwB,EAAK,CAChC,WACA,UAAW,EACX,cACA,WACA,OAAQ,CACZ,CAAC,CACL"}
@@ -1,7 +1,7 @@
1
1
  import { DebugLevel } from "./Debug.mjs";
2
2
  import { EnvFileOptions } from "./Dotenv.mjs";
3
3
  import { ArrayElement, ArrayOf, ConverterToken, Converters, CustomElementConverter, isArrayOf } from "./converters/Converters.mjs";
4
- import { AdvancedConverterReturn, BuiltInConverter, BuiltInConverterFunction, ConditionalReturn, ConverterFunction, EnvaptConverter, InferConverterFallbackType, InferConverterReturnType, InferPrimitiveFallbackType, InferPrimitiveReturnType, JsonValue, MapOfConverterFunctions, PrimitiveConstructor, TimeFallback, TimeUnit } from "./types/Conversion.mjs";
4
+ import { AdvancedConverterReturn, BuiltInConverter, BuiltInConverterFunction, ConditionalReturn, ConverterFunction, EnvaptConverter, InferConverterFallbackType, InferConverterReturnType, InferPrimitiveReturnType, JsonValue, MapOfConverterFunctions, PrimitiveConstructor, TimeFallback, TimeUnit } from "./types/Conversion.mjs";
5
5
  import { InferSchemaInput, InferSchemaOutput, StandardSchemaV1 } from "./StandardSchema.mjs";
6
6
  import { Err, SchemaConstraint, SchemaMustBeSync } from "./types/Schema.mjs";
7
7
  import { Environment } from "./core/EnvironmentMethods.mjs";
@@ -14,4 +14,4 @@ import { EnvBool, EnvNum, EnvStr, EnvTime, EnvUrl } from "./decorators/SugarDeco
14
14
  import { ManualEnvSource } from "./sources/ManualEnvSource.mjs";
15
15
  import { WorkerEnvSource } from "./sources/WorkerEnvSource.mjs";
16
16
  import { EnvaptError, EnvaptErrorCodes } from "./Error.mjs";
17
- export { type AdvancedConverterReturn, type ArrayElement, type ArrayOf, type BareEnvSource, type BuiltInConverter, type BuiltInConverterFunction, type ConditionalReturn, type ConverterFunction, type ConverterToken, Converters, type CustomElementConverter, type DebugLevel, EnvBool, type EnvFileOptions, type EnvKeyInput, EnvNum, type EnvProfile, type EnvSource, EnvStr, EnvTime, EnvUrl, Envapt, type EnvaptConverter, EnvaptError, EnvaptErrorCodes, type EnvaptOptions, Envapter, Environment, type Err, type FileEnvSource, type InferConverterFallbackType, type InferConverterReturnType, type InferPrimitiveFallbackType, type InferPrimitiveReturnType, type InferSchemaInput, type InferSchemaOutput, type JsonValue, ManualEnvSource, type MapOfConverterFunctions, type PrimitiveConstructor, type ProfilesConfig, type SchemaConstraint, type SchemaMustBeSync, type StandardSchemaV1, type TimeFallback, type TimeUnit, WorkerEnvSource, isArrayOf };
17
+ export { type AdvancedConverterReturn, type ArrayElement, type ArrayOf, type BareEnvSource, type BuiltInConverter, type BuiltInConverterFunction, type ConditionalReturn, type ConverterFunction, type ConverterToken, Converters, type CustomElementConverter, type DebugLevel, EnvBool, type EnvFileOptions, type EnvKeyInput, EnvNum, type EnvProfile, type EnvSource, EnvStr, EnvTime, EnvUrl, Envapt, type EnvaptConverter, EnvaptError, EnvaptErrorCodes, type EnvaptOptions, Envapter, Environment, type Err, type FileEnvSource, type InferConverterFallbackType, type InferConverterReturnType, type InferPrimitiveReturnType, type InferSchemaInput, type InferSchemaOutput, type JsonValue, ManualEnvSource, type MapOfConverterFunctions, type PrimitiveConstructor, type ProfilesConfig, type SchemaConstraint, type SchemaMustBeSync, type StandardSchemaV1, type TimeFallback, type TimeUnit, WorkerEnvSource, isArrayOf };
@@ -118,11 +118,6 @@ type AdvancedConverterReturn<TConverter, TFallback = undefined> = ConditionalRet
118
118
  * @internal
119
119
  */
120
120
  type InferPrimitiveReturnType<TConstructor extends PrimitiveConstructor> = TConstructor extends typeof String ? string : TConstructor extends typeof Number ? number : TConstructor extends typeof Boolean ? boolean : TConstructor extends typeof BigInt ? bigint : TConstructor extends typeof Symbol ? symbol : never;
121
- /**
122
- * Type inference for primitive fallback values
123
- * @internal
124
- */
125
- type InferPrimitiveFallbackType<TFallback extends string | number | boolean | bigint | symbol | undefined> = TFallback extends string ? string : TFallback extends number ? number : TFallback extends boolean ? boolean : TFallback extends bigint ? bigint : TFallback extends symbol ? symbol : undefined;
126
121
  //#endregion
127
- export type { AdvancedConverterReturn, BuiltInConverter, BuiltInConverterFunction, ConditionalReturn, ConverterFunction, EnvaptConverter, InferConverterFallbackType, InferConverterReturnType, InferPrimitiveFallbackType, InferPrimitiveReturnType, JsonValue, MapOfConverterFunctions, PrimitiveConstructor, TimeFallback, TimeUnit };
122
+ export type { AdvancedConverterReturn, BuiltInConverter, BuiltInConverterFunction, ConditionalReturn, ConverterFunction, EnvaptConverter, InferConverterFallbackType, InferConverterReturnType, InferPrimitiveReturnType, JsonValue, MapOfConverterFunctions, PrimitiveConstructor, TimeFallback, TimeUnit };
128
123
  //# sourceMappingURL=Conversion.d.mts.map
@@ -1,2 +1,2 @@
1
- const e=require("./Error.cjs"),t=require("./runtime.cjs"),n=new Set([`silent`,`warn`,`verbose`]);let r=`silent`,i=!1;function a(e){return e!==void 0&&n.has(e)}function o(){if(!i){let e=t.readRuntimeEnv().ENVAPT_DEBUG;r=a(e)?e:`silent`,i=!0}return r}function s(t){if(!a(t))throw new e.EnvaptError(302,`Invalid debug level "${String(t)}". Expected 'silent' | 'warn' | 'verbose'.`);r=t,i=!0}function c(){return o()}function l(e){let n=o();(n===`warn`||n===`verbose`)&&t.writeRuntimeLine(`[envapt] ${e}`)}function u(e){o()===`verbose`&&t.writeRuntimeLine(`[envapt] ${e}`)}exports.debugVerbose=u,exports.debugWarn=l,exports.getDebugLevel=c,exports.setDebugLevel=s;
1
+ import"node:path";import"node:url";import.meta.url;const e=require("./Error.cjs"),t=require("./runtime.cjs"),n=new Set([`silent`,`warn`,`verbose`]);let r=`silent`,i=!1;function a(e){return e!==void 0&&n.has(e)}function o(){if(!i){let e=t.readRuntimeEnv().ENVAPT_DEBUG;r=a(e)?e:`silent`,i=!0}return r}function s(t){if(!a(t))throw new e.EnvaptError(302,`Invalid debug level "${String(t)}". Expected 'silent' | 'warn' | 'verbose'.`);r=t,i=!0}function c(){return o()}function l(e){let n=o();(n===`warn`||n===`verbose`)&&t.writeRuntimeLine(`[envapt] ${e}`)}function u(e){o()===`verbose`&&t.writeRuntimeLine(`[envapt] ${e}`)}exports.debugVerbose=u,exports.debugWarn=l,exports.getDebugLevel=c,exports.setDebugLevel=s;
2
2
  //# sourceMappingURL=Debug.cjs.map