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
@@ -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,WAAW,eAAe,EA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AU,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,YAAY,EAAS,CA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AAI,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 [...profilePaths.map((p) => this.resolve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,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,CAAA,EAGA,MAA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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
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "envapt",
3
3
  "type": "module",
4
- "version": "5.2.0",
4
+ "version": "6.0.0",
5
5
  "description": "Type-safe environment variables for TypeScript. Zero-dependency .env loader and parser with one API across Node, Bun, Deno, Cloudflare Workers, and the Browser. Decorators, converters, Standard Schema (zod/valibot/arktype) validation, and much more.",
6
6
  "types": "./dist/node/index.d.mts",
7
7
  "exports": {
@@ -111,11 +111,11 @@
111
111
  },
112
112
  "devDependencies": {
113
113
  "@cloudflare/vitest-pool-workers": "0.16.14",
114
- "@cloudflare/workers-types": "^4.20260609.1",
114
+ "@cloudflare/workers-types": "^4.20260613.1",
115
115
  "@vitest/browser": "4.1.7",
116
116
  "@vitest/browser-playwright": "4.1.7",
117
117
  "arktype": "^2.2.0",
118
- "esbuild": "^0.28.0",
118
+ "esbuild": "^0.28.1",
119
119
  "playwright": "1.60.0",
120
120
  "valibot": "^1.4.1",
121
121
  "zod": "4.4.3"