envapt 7.0.3 → 8.0.0-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +32 -101
- package/README.md +5 -5
- package/dist/node/converters/BuiltInConverters.cjs +1 -1
- package/dist/node/converters/BuiltInConverters.cjs.map +1 -1
- package/dist/node/converters/BuiltInConverters.mjs +1 -1
- package/dist/node/converters/BuiltInConverters.mjs.map +1 -1
- package/dist/node/converters/Converters.cjs.map +1 -1
- package/dist/node/converters/Converters.mjs.map +1 -1
- package/dist/node/converters/ValueConverter.cjs +1 -1
- package/dist/node/converters/ValueConverter.cjs.map +1 -1
- package/dist/node/converters/ValueConverter.mjs +1 -1
- package/dist/node/converters/ValueConverter.mjs.map +1 -1
- package/dist/node/core/AdvancedMethods.cjs +1 -1
- package/dist/node/core/AdvancedMethods.cjs.map +1 -1
- package/dist/node/core/AdvancedMethods.mjs +1 -1
- package/dist/node/core/AdvancedMethods.mjs.map +1 -1
- package/dist/node/core/EnvapterBase.cjs +1 -1
- package/dist/node/core/EnvapterBase.cjs.map +1 -1
- package/dist/node/core/EnvapterBase.mjs +1 -1
- package/dist/node/core/EnvapterBase.mjs.map +1 -1
- package/dist/node/core/Environment.cjs +2 -0
- package/dist/node/core/Environment.cjs.map +1 -0
- package/dist/node/core/Environment.mjs +2 -0
- package/dist/node/core/Environment.mjs.map +1 -0
- package/dist/node/core/EnvironmentMethods.cjs +1 -1
- package/dist/node/core/EnvironmentMethods.cjs.map +1 -1
- package/dist/node/core/EnvironmentMethods.mjs +1 -1
- package/dist/node/core/EnvironmentMethods.mjs.map +1 -1
- package/dist/node/core/PrimitiveMethods.cjs +1 -1
- package/dist/node/core/PrimitiveMethods.cjs.map +1 -1
- package/dist/node/core/PrimitiveMethods.mjs +1 -1
- package/dist/node/core/PrimitiveMethods.mjs.map +1 -1
- package/dist/node/core/engine.cjs +2 -0
- package/dist/node/core/engine.cjs.map +1 -0
- package/dist/node/core/engine.mjs +2 -0
- package/dist/node/core/engine.mjs.map +1 -0
- package/dist/node/core/paths.cjs +2 -0
- package/dist/node/core/paths.cjs.map +1 -0
- package/dist/node/core/paths.mjs +2 -0
- package/dist/node/core/paths.mjs.map +1 -0
- package/dist/node/core/state.cjs +2 -0
- package/dist/node/core/state.cjs.map +1 -0
- package/dist/node/core/state.mjs +2 -0
- package/dist/node/core/state.mjs.map +1 -0
- package/dist/node/decorators/resolveDecoratorValue.cjs +1 -1
- package/dist/node/decorators/resolveDecoratorValue.cjs.map +1 -1
- package/dist/node/decorators/resolveDecoratorValue.mjs +1 -1
- package/dist/node/decorators/resolveDecoratorValue.mjs.map +1 -1
- package/dist/node/engine/Envapter.cjs +1 -1
- package/dist/node/engine/Envapter.cjs.map +1 -1
- package/dist/node/engine/Envapter.mjs +1 -1
- package/dist/node/engine/Envapter.mjs.map +1 -1
- package/dist/node/engine/NodeEnvapter.cjs +1 -1
- package/dist/node/engine/NodeEnvapter.cjs.map +1 -1
- package/dist/node/engine/NodeEnvapter.mjs +1 -1
- package/dist/node/engine/NodeEnvapter.mjs.map +1 -1
- package/dist/node/engine/TemplateResolver.cjs +1 -1
- package/dist/node/engine/TemplateResolver.cjs.map +1 -1
- package/dist/node/engine/TemplateResolver.mjs +1 -1
- package/dist/node/engine/TemplateResolver.mjs.map +1 -1
- package/dist/node/engine/Validators.cjs +1 -1
- package/dist/node/engine/Validators.cjs.map +1 -1
- package/dist/node/engine/Validators.mjs +1 -1
- package/dist/node/engine/Validators.mjs.map +1 -1
- package/dist/node/index.cjs +1 -1
- package/dist/node/index.mjs +1 -1
- package/dist/node/infra/Error.cjs +1 -1
- package/dist/node/infra/Error.cjs.map +1 -1
- package/dist/node/infra/Error.mjs +1 -1
- package/dist/node/infra/Error.mjs.map +1 -1
- package/dist/node/infra/recase.cjs +2 -0
- package/dist/node/infra/recase.cjs.map +1 -0
- package/dist/node/infra/recase.mjs +2 -0
- package/dist/node/infra/recase.mjs.map +1 -0
- package/dist/node/infra/runtime.cjs.map +1 -1
- package/dist/node/infra/runtime.mjs.map +1 -1
- package/dist/node/sources/{NodeEnvSource.cjs → FileSource.cjs} +2 -2
- package/dist/node/sources/FileSource.cjs.map +1 -0
- package/dist/node/sources/{NodeEnvSource.mjs → FileSource.mjs} +2 -2
- package/dist/node/sources/FileSource.mjs.map +1 -0
- package/dist/node/sources/{ManualEnvSource.cjs → PortableSource.cjs} +2 -2
- package/dist/node/sources/PortableSource.cjs.map +1 -0
- package/dist/{browser/sources/ManualEnvSource.mjs → node/sources/PortableSource.mjs} +2 -2
- package/dist/node/sources/PortableSource.mjs.map +1 -0
- package/dist/node/sources/{UnboundEnvSource.cjs → UnboundSource.cjs} +2 -2
- package/dist/node/sources/UnboundSource.cjs.map +1 -0
- package/dist/{browser/sources/UnboundEnvSource.mjs → node/sources/UnboundSource.mjs} +2 -2
- package/dist/node/sources/UnboundSource.mjs.map +1 -0
- package/dist/node/sources/coerce.cjs.map +1 -1
- package/dist/node/sources/coerce.mjs.map +1 -1
- package/dist/node/sources/merge.cjs +2 -0
- package/dist/node/sources/merge.cjs.map +1 -0
- package/dist/node/sources/merge.mjs +2 -0
- package/dist/node/sources/merge.mjs.map +1 -0
- package/dist/portable/converters/BuiltInConverters.mjs +2 -0
- package/dist/portable/converters/BuiltInConverters.mjs.map +1 -0
- package/dist/portable/converters/Converters.mjs.map +1 -0
- package/dist/portable/converters/ValueConverter.mjs +2 -0
- package/dist/portable/converters/ValueConverter.mjs.map +1 -0
- package/dist/portable/core/AdvancedMethods.mjs +2 -0
- package/dist/portable/core/AdvancedMethods.mjs.map +1 -0
- package/dist/portable/core/EnvapterBase.mjs +2 -0
- package/dist/portable/core/EnvapterBase.mjs.map +1 -0
- package/dist/portable/core/Environment.mjs +2 -0
- package/dist/portable/core/Environment.mjs.map +1 -0
- package/dist/portable/core/EnvironmentMethods.mjs +2 -0
- package/dist/portable/core/EnvironmentMethods.mjs.map +1 -0
- package/dist/portable/core/PrimitiveMethods.mjs +2 -0
- package/dist/portable/core/PrimitiveMethods.mjs.map +1 -0
- package/dist/portable/core/engine.mjs +2 -0
- package/dist/portable/core/engine.mjs.map +1 -0
- package/dist/portable/core/paths.mjs +2 -0
- package/dist/portable/core/paths.mjs.map +1 -0
- package/dist/portable/core/state.mjs +2 -0
- package/dist/portable/core/state.mjs.map +1 -0
- package/dist/portable/decorators/resolveDecoratorValue.mjs +2 -0
- package/dist/portable/decorators/resolveDecoratorValue.mjs.map +1 -0
- package/dist/portable/engine/Envapter.mjs +2 -0
- package/dist/portable/engine/Envapter.mjs.map +1 -0
- package/dist/portable/engine/PortableEnvapter.mjs +2 -0
- package/dist/portable/engine/PortableEnvapter.mjs.map +1 -0
- package/dist/portable/engine/TemplateResolver.mjs +2 -0
- package/dist/portable/engine/TemplateResolver.mjs.map +1 -0
- package/dist/portable/engine/Validators.mjs +2 -0
- package/dist/portable/engine/Validators.mjs.map +1 -0
- package/dist/portable/engine/fileApiStub.mjs +2 -0
- package/dist/portable/engine/fileApiStub.mjs.map +1 -0
- package/dist/portable/index.mjs +1 -0
- package/dist/{browser → portable}/infra/Error.mjs +1 -1
- package/dist/{browser → portable}/infra/Error.mjs.map +1 -1
- package/dist/portable/infra/recase.mjs +2 -0
- package/dist/portable/infra/recase.mjs.map +1 -0
- package/dist/portable/infra/runtime.mjs.map +1 -0
- package/dist/{browser/sources/WorkerEnvSource.mjs → portable/sources/PortableSource.mjs} +2 -2
- package/dist/portable/sources/PortableSource.mjs.map +1 -0
- package/dist/{node/sources/UnboundEnvSource.mjs → portable/sources/UnboundSource.mjs} +2 -2
- package/dist/portable/sources/UnboundSource.mjs.map +1 -0
- package/dist/portable/sources/coerce.mjs.map +1 -0
- package/dist/portable/sources/merge.mjs +2 -0
- package/dist/portable/sources/merge.mjs.map +1 -0
- package/dist/types/converters/Converters.d.mts +1 -15
- package/dist/types/core/AdvancedMethods.d.mts +31 -19
- package/dist/types/core/EnvapterBase.d.mts +16 -30
- package/dist/types/core/Environment.d.mts +25 -0
- package/dist/types/core/EnvironmentMethods.d.mts +2 -67
- package/dist/types/core/PrimitiveMethods.d.mts +2 -10
- package/dist/types/engine/Envapter.d.mts +2 -3
- package/dist/types/engine/NodeEnvapter.d.mts +4 -7
- package/dist/types/engine/PortableEnvapter.d.mts +17 -5
- package/dist/types/index.d.mts +10 -13
- package/dist/types/index.portable.d.mts +9 -12
- package/dist/types/infra/Error.d.mts +3 -1
- package/dist/types/infra/StandardSchema.d.mts +1 -12
- package/dist/types/sources/{NodeEnvSource.d.mts → FileSource.d.mts} +5 -5
- package/dist/types/sources/PortableSource.d.mts +24 -0
- package/dist/types/sources/merge.d.mts +13 -0
- package/dist/types/types/Casing.d.mts +8 -0
- package/dist/types/types/Conversion.d.mts +9 -66
- package/dist/types/types/Decorator.d.mts +0 -14
- package/dist/types/types/Env.d.mts +1 -10
- package/dist/types/types/Options.d.mts +9 -2
- package/dist/types/types/Schema.d.mts +1 -13
- package/dist/types/types/Source.d.mts +8 -28
- package/package.json +62 -19
- package/aliases/browser.d.mts +0 -7
- package/aliases/browser.mjs +0 -4
- package/aliases/workerd.d.mts +0 -7
- package/aliases/workerd.mjs +0 -4
- package/dist/browser/converters/BuiltInConverters.mjs +0 -2
- package/dist/browser/converters/BuiltInConverters.mjs.map +0 -1
- package/dist/browser/converters/Converters.mjs.map +0 -1
- package/dist/browser/converters/ValueConverter.mjs +0 -2
- package/dist/browser/converters/ValueConverter.mjs.map +0 -1
- package/dist/browser/core/AdvancedMethods.mjs +0 -2
- package/dist/browser/core/AdvancedMethods.mjs.map +0 -1
- package/dist/browser/core/EnvapterBase.mjs +0 -2
- package/dist/browser/core/EnvapterBase.mjs.map +0 -1
- package/dist/browser/core/EnvironmentMethods.mjs +0 -2
- package/dist/browser/core/EnvironmentMethods.mjs.map +0 -1
- package/dist/browser/core/PrimitiveMethods.mjs +0 -2
- package/dist/browser/core/PrimitiveMethods.mjs.map +0 -1
- package/dist/browser/decorators/resolveDecoratorValue.mjs +0 -2
- package/dist/browser/decorators/resolveDecoratorValue.mjs.map +0 -1
- package/dist/browser/engine/Envapter.mjs +0 -2
- package/dist/browser/engine/Envapter.mjs.map +0 -1
- package/dist/browser/engine/PortableEnvapter.mjs +0 -2
- package/dist/browser/engine/PortableEnvapter.mjs.map +0 -1
- package/dist/browser/engine/TemplateResolver.mjs +0 -2
- package/dist/browser/engine/TemplateResolver.mjs.map +0 -1
- package/dist/browser/engine/Validators.mjs +0 -2
- package/dist/browser/engine/Validators.mjs.map +0 -1
- package/dist/browser/engine/installFileApiStubs.mjs +0 -2
- package/dist/browser/engine/installFileApiStubs.mjs.map +0 -1
- package/dist/browser/index.mjs +0 -1
- package/dist/browser/infra/runtime.mjs.map +0 -1
- package/dist/browser/sources/ManualEnvSource.mjs.map +0 -1
- package/dist/browser/sources/UnboundEnvSource.mjs.map +0 -1
- package/dist/browser/sources/WorkerEnvSource.mjs.map +0 -1
- package/dist/browser/sources/coerce.mjs.map +0 -1
- package/dist/node/sources/ManualEnvSource.cjs.map +0 -1
- package/dist/node/sources/ManualEnvSource.mjs +0 -2
- package/dist/node/sources/ManualEnvSource.mjs.map +0 -1
- package/dist/node/sources/NodeEnvSource.cjs.map +0 -1
- package/dist/node/sources/NodeEnvSource.mjs.map +0 -1
- package/dist/node/sources/UnboundEnvSource.cjs.map +0 -1
- package/dist/node/sources/UnboundEnvSource.mjs.map +0 -1
- package/dist/node/sources/WorkerEnvSource.cjs +0 -2
- package/dist/node/sources/WorkerEnvSource.cjs.map +0 -1
- package/dist/node/sources/WorkerEnvSource.mjs +0 -2
- package/dist/node/sources/WorkerEnvSource.mjs.map +0 -1
- package/dist/types/converters/ValueConverter.d.mts +0 -25
- package/dist/types/engine/TemplateResolver.d.mts +0 -17
- package/dist/types/sources/ManualEnvSource.d.mts +0 -22
- package/dist/types/sources/WorkerEnvSource.d.mts +0 -22
- package/dist/workerd/converters/BuiltInConverters.mjs +0 -2
- package/dist/workerd/converters/BuiltInConverters.mjs.map +0 -1
- package/dist/workerd/converters/Converters.mjs +0 -2
- package/dist/workerd/converters/Converters.mjs.map +0 -1
- package/dist/workerd/converters/ListOfBuiltInConverters.mjs +0 -2
- package/dist/workerd/converters/ListOfBuiltInConverters.mjs.map +0 -1
- package/dist/workerd/converters/ValueConverter.mjs +0 -2
- package/dist/workerd/converters/ValueConverter.mjs.map +0 -1
- package/dist/workerd/core/AdvancedMethods.mjs +0 -2
- package/dist/workerd/core/AdvancedMethods.mjs.map +0 -1
- package/dist/workerd/core/EnvapterBase.mjs +0 -2
- package/dist/workerd/core/EnvapterBase.mjs.map +0 -1
- package/dist/workerd/core/EnvironmentMethods.mjs +0 -2
- package/dist/workerd/core/EnvironmentMethods.mjs.map +0 -1
- package/dist/workerd/core/PrimitiveMethods.mjs +0 -2
- package/dist/workerd/core/PrimitiveMethods.mjs.map +0 -1
- package/dist/workerd/decorators/legacy/Envapt.mjs +0 -2
- package/dist/workerd/decorators/legacy/Envapt.mjs.map +0 -1
- package/dist/workerd/decorators/legacy/SugarDecorators.mjs +0 -2
- package/dist/workerd/decorators/legacy/SugarDecorators.mjs.map +0 -1
- package/dist/workerd/decorators/legacy/createPropertyDecorator.mjs +0 -2
- package/dist/workerd/decorators/legacy/createPropertyDecorator.mjs.map +0 -1
- package/dist/workerd/decorators/modern/Envapt.mjs +0 -2
- package/dist/workerd/decorators/modern/Envapt.mjs.map +0 -1
- package/dist/workerd/decorators/modern/SugarDecorators.mjs +0 -2
- package/dist/workerd/decorators/modern/SugarDecorators.mjs.map +0 -1
- package/dist/workerd/decorators/modern/createAccessorDecorator.mjs +0 -2
- package/dist/workerd/decorators/modern/createAccessorDecorator.mjs.map +0 -1
- package/dist/workerd/decorators/parseEnvaptOptions.mjs +0 -2
- package/dist/workerd/decorators/parseEnvaptOptions.mjs.map +0 -1
- package/dist/workerd/decorators/resolveDecoratorValue.mjs +0 -2
- package/dist/workerd/decorators/resolveDecoratorValue.mjs.map +0 -1
- package/dist/workerd/engine/Envapter.mjs +0 -2
- package/dist/workerd/engine/Envapter.mjs.map +0 -1
- package/dist/workerd/engine/PortableEnvapter.mjs +0 -2
- package/dist/workerd/engine/PortableEnvapter.mjs.map +0 -1
- package/dist/workerd/engine/TemplateResolver.mjs +0 -2
- package/dist/workerd/engine/TemplateResolver.mjs.map +0 -1
- package/dist/workerd/engine/Validators.mjs +0 -2
- package/dist/workerd/engine/Validators.mjs.map +0 -1
- package/dist/workerd/engine/installFileApiStubs.mjs +0 -2
- package/dist/workerd/engine/installFileApiStubs.mjs.map +0 -1
- package/dist/workerd/index.mjs +0 -1
- package/dist/workerd/infra/Debug.mjs +0 -2
- package/dist/workerd/infra/Debug.mjs.map +0 -1
- package/dist/workerd/infra/Dotenv.mjs +0 -3
- package/dist/workerd/infra/Dotenv.mjs.map +0 -1
- package/dist/workerd/infra/Error.mjs +0 -2
- package/dist/workerd/infra/Error.mjs.map +0 -1
- package/dist/workerd/infra/runtime.mjs +0 -2
- package/dist/workerd/infra/runtime.mjs.map +0 -1
- package/dist/workerd/legacy.mjs +0 -1
- package/dist/workerd/sources/ManualEnvSource.mjs +0 -2
- package/dist/workerd/sources/ManualEnvSource.mjs.map +0 -1
- package/dist/workerd/sources/UnboundEnvSource.mjs +0 -2
- package/dist/workerd/sources/UnboundEnvSource.mjs.map +0 -1
- package/dist/workerd/sources/WorkerEnvSource.mjs +0 -2
- package/dist/workerd/sources/WorkerEnvSource.mjs.map +0 -1
- package/dist/workerd/sources/coerce.mjs +0 -2
- package/dist/workerd/sources/coerce.mjs.map +0 -1
- /package/dist/{browser → portable}/converters/Converters.mjs +0 -0
- /package/dist/{browser → portable}/converters/ListOfBuiltInConverters.mjs +0 -0
- /package/dist/{browser → portable}/converters/ListOfBuiltInConverters.mjs.map +0 -0
- /package/dist/{browser → portable}/decorators/legacy/Envapt.mjs +0 -0
- /package/dist/{browser → portable}/decorators/legacy/Envapt.mjs.map +0 -0
- /package/dist/{browser → portable}/decorators/legacy/SugarDecorators.mjs +0 -0
- /package/dist/{browser → portable}/decorators/legacy/SugarDecorators.mjs.map +0 -0
- /package/dist/{browser → portable}/decorators/legacy/createPropertyDecorator.mjs +0 -0
- /package/dist/{browser → portable}/decorators/legacy/createPropertyDecorator.mjs.map +0 -0
- /package/dist/{browser → portable}/decorators/modern/Envapt.mjs +0 -0
- /package/dist/{browser → portable}/decorators/modern/Envapt.mjs.map +0 -0
- /package/dist/{browser → portable}/decorators/modern/SugarDecorators.mjs +0 -0
- /package/dist/{browser → portable}/decorators/modern/SugarDecorators.mjs.map +0 -0
- /package/dist/{browser → portable}/decorators/modern/createAccessorDecorator.mjs +0 -0
- /package/dist/{browser → portable}/decorators/modern/createAccessorDecorator.mjs.map +0 -0
- /package/dist/{browser → portable}/decorators/parseEnvaptOptions.mjs +0 -0
- /package/dist/{browser → portable}/decorators/parseEnvaptOptions.mjs.map +0 -0
- /package/dist/{browser → portable}/infra/Debug.mjs +0 -0
- /package/dist/{browser → portable}/infra/Debug.mjs.map +0 -0
- /package/dist/{browser → portable}/infra/Dotenv.mjs +0 -0
- /package/dist/{browser → portable}/infra/Dotenv.mjs.map +0 -0
- /package/dist/{browser → portable}/infra/runtime.mjs +0 -0
- /package/dist/{browser → portable}/legacy.mjs +0 -0
- /package/dist/{browser → portable}/sources/coerce.mjs +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"PortableEnvapter.mjs","names":[],"sources":["../../../src/engine/PortableEnvapter.ts"],"sourcesContent":["import { Envapter } from './Envapter';\nimport { installFileApiStubs } from './installFileApiStubs';\n\n/**\n * The browser/Workers facade. {@link Envapter} with the filesystem-only configuration APIs\n * (`envPaths`, `baseDir`, `envFileOptions`, `configureProfiles`, `resetProfiles`) stubbed to throw\n * {@link EnvaptError}. The portable types omit those APIs, so the stubs only guard JS callers that\n * bypass the types.\n * @public\n */\nexport class PortableEnvapter extends Envapter {\n // A static block (not a top-level statement in a separate entry) keeps the stub install intrinsic to\n // this class, so it tree-shakes out of a leaf import and needs no sideEffects entry. Depends on the\n // es2022 native static-block emit, lowering the target defeats it.\n static {\n installFileApiStubs(PortableEnvapter);\n }\n}\n"],"mappings":"0GAUA,IAAa,EAAb,MAAa,UAAyB,CAAS,CAI3C,OACI,EAAoB,CAAgB,CACxC,CACJ"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{EnvaptError as e}from"../infra/Error.mjs";import{debugWarn as t}from"../infra/Debug.mjs";var n=class{envService;TEMPLATE_REGEX=/\${\w*}/g;constructor(e){this.envService=e}resolveTemplate(n,r,i=new Set){i.add(n);let a=this.envService.isStrict(),o=r.replace(this.TEMPLATE_REGEX,r=>{let o=r.slice(2,-1);if(i.has(o))return r;let s=this.envService.getRaw(o);if(s===void 0||s===``||a&&s.trim()===``){if(a)throw new e(305,`Cannot resolve template variable "\${${o}}": value is missing or empty.`);return t(`unresolved template \${${o}} preserved as literal`),r}let c=this.resolveTemplate(o,s,new Set(i));return c.includes(`\${${n}}`)||c===s&&/\$\{[^}]*\}/.test(c)?r:c});return i.delete(n),o}};export{n as TemplateResolver};
|
|
2
|
-
//# sourceMappingURL=TemplateResolver.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"TemplateResolver.mjs","names":[],"sources":["../../../src/engine/TemplateResolver.ts"],"sourcesContent":["import { debugWarn } from '../infra/Debug';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { EnvapterService } from '../types/Env';\n\n/**\n * Resolve `${VAR}` template references in environment values, guarding against circular\n * references and missing variables.\n * @internal\n */\nexport class TemplateResolver {\n private readonly TEMPLATE_REGEX = /\\${\\w*}/g;\n\n constructor(private readonly envService: EnvapterService) {}\n\n resolveTemplate(key: string, value: string, stack: Set<string> = new Set<string>()): string {\n stack.add(key);\n const strict = this.envService.isStrict();\n\n const out = value.replace(this.TEMPLATE_REGEX, (template) => {\n const variable = template.slice(2, -1);\n\n if (stack.has(variable)) return template; // cycle, preserve\n\n const raw = this.envService.getRaw(variable);\n const isMissing = raw === undefined || raw === '' || (strict && raw.trim() === '');\n if (isMissing) {\n if (strict) {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Cannot resolve template variable \"\\${${variable}}\": value is missing or empty.`\n );\n }\n debugWarn(`unresolved template \\${${variable}} preserved as literal`);\n return template; // missing or empty, preserve\n }\n\n const resolved = this.resolveTemplate(variable, raw, new Set(stack));\n\n // If resolution still references the current key, skip replacement (indirect cycle)\n if (resolved.includes(`\\${${key}}`)) return template;\n\n // If nothing changed (unresolved placeholders stayed), also preserve original template\n if (resolved === raw && /\\$\\{[^}]*\\}/.test(resolved)) return template;\n\n return resolved;\n });\n\n stack.delete(key);\n return out;\n }\n}\n"],"mappings":"gGAUA,IAAa,EAAb,KAA8B,CAGG,WAF7B,eAAkC,WAElC,YAAY,EAA8C,CAA7B,KAAA,WAAA,CAA8B,CAE3D,gBAAgB,EAAa,EAAe,EAAqB,IAAI,IAAuB,CACxF,EAAM,IAAI,CAAG,EACb,IAAM,EAAS,KAAK,WAAW,SAAS,EAElC,EAAM,EAAM,QAAQ,KAAK,eAAiB,GAAa,CACzD,IAAM,EAAW,EAAS,MAAM,EAAG,EAAE,EAErC,GAAI,EAAM,IAAI,CAAQ,EAAG,OAAO,EAEhC,IAAM,EAAM,KAAK,WAAW,OAAO,CAAQ,EAE3C,GADkB,IAAQ,IAAA,IAAa,IAAQ,IAAO,GAAU,EAAI,KAAK,IAAM,GAChE,CACX,GAAI,EACA,MAAM,IAAI,EAAA,IAEN,wCAAwC,EAAS,+BACrD,EAGJ,OADA,EAAU,0BAA0B,EAAS,uBAAuB,EAC7D,CACX,CAEA,IAAM,EAAW,KAAK,gBAAgB,EAAU,EAAK,IAAI,IAAI,CAAK,CAAC,EAQnE,OALI,EAAS,SAAS,MAAM,EAAI,EAAE,GAG9B,IAAa,GAAO,cAAc,KAAK,CAAQ,EAAU,EAEtD,CACX,CAAC,EAGD,OADA,EAAM,OAAO,CAAG,EACT,CACX,CACJ"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{isArrayOf as e}from"../converters/Converters.mjs";import{BuiltInConverterTypeCheckers as t,ListOfBuiltInConverters as n}from"../converters/ListOfBuiltInConverters.mjs";import{EnvaptError as r}from"../infra/Error.mjs";var i=class{static isBuiltInConverter(e){return typeof e==`string`?n.includes(e):!1}static isArrayConverter(t){return e(t)}static isStandardSchema(e){if(typeof e!=`object`||!e||!(`~standard`in e))return!1;let t=e[`~standard`];if(typeof t!=`object`||!t)return!1;let n=t;return n.version===1&&typeof n.validate==`function`}static customConvertor(e){if(typeof e!=`function`)throw new r(203,`Custom converter must be a function, got ${typeof e}.`)}static arrayConverter(t){if(!e(t))throw new r(201,`Expected an ArrayOf<...> token produced by Converters.array(...)`);if(typeof t.delimiter!=`string`||t.delimiter.length===0)throw new r(301,`ArrayOf<...> requires a non-empty string delimiter, got ${typeof t.delimiter}`);let i=t.of;if(!(typeof i==`string`&&n.includes(i))&&typeof i!=`function`)throw new r(201,`ArrayOf<...> element ("of") must be a built-in scalar token or a function, got ${typeof i}`)}static builtInConverter(e){if(typeof e!=`string`)throw new r(204,`Expected string, got ${typeof e}`);if(!n.includes(e))throw new r(202,`"${e}" is not a valid converter type. Valid types are: ${n.join(`,`)}`)}static validateBuiltInConverterFallback(e,n){let i=t[e];if(!i(n))throw new r(104,`Fallback type does not match converter "${e}". Expected ${e} compatible type.`)}static validateArrayFallbackElementTypes(e){if(e.length===0)return;let t=typeof e[0];if(e.some((e,n)=>n===0?!1:typeof e!==t))throw new r(103,`All elements in array fallback must have the same type. Found mixed types.`)}static validateArrayConverterElementTypeMatch(e,n){if(n.length===0||typeof e==`function`)return;let i=e;if(i===`time`){let e=n.every(e=>typeof e==`number`),t=n.every(e=>typeof e==`string`);if(!e&&!t)throw new r(103,`Time array fallback must be all numbers or all time-string entries.`);return}let a=t[i],o=n[0];if(!a(o))throw new r(103,`Array converter type "${i}" does not match fallback element type. Expected ${i} compatible elements.`)}static isPrimitiveConstructor(e){return e===String||e===Number||e===Boolean||e===BigInt||e===Symbol}static coercePrimitiveFallback(e,t){return this.isCorrectPrimitiveType(e,t)?t:this.performPrimitiveCoercion(e,t)}static isCorrectPrimitiveType(e,t){return e===String&&typeof t==`string`||e===Number&&typeof t==`number`||e===Boolean&&typeof t==`boolean`||e===BigInt&&typeof t==`bigint`||e===Symbol&&typeof t==`symbol`}static performPrimitiveCoercion(e,t){try{if(e===String)return String(t);if(e===Number)return Number(t);if(e===Boolean)return!!t;if(e===BigInt)return BigInt(t);if(e===Symbol)return Symbol.for(String(t))}catch(t){throw new r(205,`Failed to coerce fallback value using ${e.name}: ${t.message}`)}throw new r(205,`Unknown primitive converter: ${e.name}`)}static validateSyncProcessEnv(e){if(typeof e!=`boolean`)throw new r(302,`Envapter.syncProcessEnv must be a boolean, got ${typeof e}.`)}static validateEnvFileOptions(e){let t=new Set([`encoding`,`override`]),n=Object.keys(e).filter(e=>!t.has(e));if(n.length>0)throw new r(302,`Invalid envFileOptions: ${n.join(`, `)}. Allowed options: ${Array.from(t).join(`, `)}. For debug output, use Envapter.debug or the ENVAPT_DEBUG env var.`);return!0}static validateEnvFilesExist(e,t){let n=e.filter(e=>!t(e));if(n.length>0)throw new r(303,`Environment file not found at path: ${n.join(`, `)}`)}};export{i as Validator};
|
|
2
|
-
//# sourceMappingURL=Validators.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Validators.mjs","names":[],"sources":["../../../src/engine/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 '../infra/Error';\n\nimport type { ArrayOf, ConverterToken } from '../converters/Converters';\nimport type { EnvFileOptions } from '../infra/Dotenv';\nimport type { StandardSchemaV1 } from '../infra/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":"gOAYA,IAAa,EAAb,KAAuB,CAInB,OAAO,mBAA8B,EAA8D,CAE/F,OADI,O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OAAO,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,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,2 +0,0 @@
|
|
|
1
|
-
import{EnvaptError as e}from"../infra/Error.mjs";const t=[`envPaths`,`baseDir`,`envFileOptions`,`configureProfiles`,`resetProfiles`];function n(t){throw new e(306,`Envapter.${t} requires a filesystem-backed source and is not available in this build.`)}function r(e){for(let r of t)Object.defineProperty(e,r,{configurable:!0,get:()=>n(r),set:()=>n(r)})}export{r as installFileApiStubs};
|
|
2
|
-
//# sourceMappingURL=installFileApiStubs.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"installFileApiStubs.mjs","names":[],"sources":["../../../src/engine/installFileApiStubs.ts"],"sourcesContent":["import { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nconst FILE_ONLY_APIS = ['envPaths', 'baseDir', 'envFileOptions', 'configureProfiles', 'resetProfiles'] as const;\n\nfunction fileApiUnsupported(api: string): never {\n throw new EnvaptError(\n EnvaptErrorCodes.FileApiUnsupported,\n `Envapter.${api} requires a filesystem-backed source and is not available in this build.`\n );\n}\n\n// Call from a class static block, not an entry top level, or the build drops the stubs from a\n// re-exported entry as a tree-shaken side effect.\nexport function installFileApiStubs(target: object): void {\n for (const api of FILE_ONLY_APIS) {\n Object.defineProperty(target, api, {\n configurable: true,\n get: () => fileApiUnsupported(api),\n set: () => fileApiUnsupported(api)\n });\n }\n}\n"],"mappings":"iDAEA,MAAM,EAAiB,CAAC,WAAY,UAAW,iBAAkB,oBAAqB,eAAe,EAErG,SAAS,EAAmB,EAAoB,CAC5C,MAAM,IAAI,EAAA,IAEN,YAAY,EAAI,yEACpB,CACJ,CAIA,SAAgB,EAAoB,EAAsB,CACtD,IAAK,IAAM,KAAO,EACd,OAAO,eAAe,EAAQ,EAAK,CAC/B,aAAc,GACd,QAAW,EAAmB,CAAG,EACjC,QAAW,EAAmB,CAAG,CACrC,CAAC,CAET"}
|
package/dist/browser/index.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Converters as e,isArrayOf as t}from"./converters/Converters.mjs";import{EnvaptError as n,EnvaptErrorCodes as r}from"./infra/Error.mjs";import{Environment as i}from"./core/EnvironmentMethods.mjs";import{ManualEnvSource as a}from"./sources/ManualEnvSource.mjs";import{WorkerEnvSource as o}from"./sources/WorkerEnvSource.mjs";import{Envapt as s}from"./decorators/modern/Envapt.mjs";import{EnvBool as c,EnvNum as l,EnvStr as u,EnvTime as d,EnvUrl as f}from"./decorators/modern/SugarDecorators.mjs";import{PortableEnvapter as p}from"./engine/PortableEnvapter.mjs";export{e as Converters,c as EnvBool,l as EnvNum,u as EnvStr,d as EnvTime,f as EnvUrl,s as Envapt,n as EnvaptError,r as EnvaptErrorCodes,p as Envapter,i as Environment,a as ManualEnvSource,o as WorkerEnvSource,t as isArrayOf};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"runtime.mjs","names":[],"sources":["../../../src/infra/runtime.ts"],"sourcesContent":["import type { EnvSource } from '../types';\n\n// EnvapterBase imports Debug; importing it back would cycle, so the source/sink are injected via the setters below.\n/* v8 ignore start -- @preserve replaced at load on Node; the Node suite never runs these defaults */\nlet sink: (line: string) => void = (line) => {\n // eslint-disable-next-line no-console -- the off-Node fallback log sink\n console.error(line);\n};\nlet envReader: () => Record<string, string> = () => ({});\n/* v8 ignore stop */\n\nexport function setRuntimeSink(fn: (line: string) => void): void {\n sink = fn;\n}\n\nexport function writeRuntimeLine(line: string): void {\n sink(line);\n}\n\nexport function readRuntimeEnv(): Record<string, string> {\n return envReader();\n}\n\nexport function bindRuntimeFromSource(source: EnvSource): void {\n envReader = (): Record<string, string> => source.readVars();\n}\n"],"mappings":"AAIA,IAAI,EAAgC,GAAS,CAEzC,QAAQ,MAAM,CAAI,CACtB,EACI,OAAiD,CAAC,GAOtD,SAAgB,EAAiB,EAAoB,CACjD,EAAK,CAAI,CACb,CAEA,SAAgB,GAAyC,CACrD,OAAO,EAAU,CACrB,CAEA,SAAgB,EAAsB,EAAyB,CAC3D,MAA0C,EAAO,SAAS,CAC9D"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ManualEnvSource.mjs","names":[],"sources":["../../../src/sources/ManualEnvSource.ts"],"sourcesContent":["import { coerceToStringRecord } from './coerce';\n\nimport type { BareEnvSource } from '../types';\n\n/**\n * Environment source seeded from an object you provide: the config your bundler injects into a browser\n * build (Vite's `import.meta.env`, a webpack `DefinePlugin` global), a test fixture, or any other plain\n * object. Pass it straight through; non-string values are JSON-stringified so the converters still apply.\n * It has no filesystem, so the `.env` cascade and file-based APIs do not apply.\n * @public\n */\nexport class ManualEnvSource implements BareEnvSource {\n /** Always `false`. With no filesystem, the `.env` cascade and file APIs do not apply. */\n readonly supportsFiles = false;\n private readonly vars: Record<string, string>;\n\n /** Seed the source from `vars`. Non-string values are JSON-stringified so the converters still apply. */\n constructor(vars: Record<string, unknown>) {\n this.vars = coerceToStringRecord(vars);\n }\n\n /** Returns a snapshot clone of the provided object as plain strings. */\n readVars(): Record<string, string> {\n return { ...this.vars };\n }\n}\n"],"mappings":"oDAWA,IAAa,EAAb,KAAsD,CAElD,cAAyB,GACzB,KAGA,YAAY,EAA+B,CACvC,KAAK,KAAO,EAAqB,CAAI,CACzC,CAGA,UAAmC,CAC/B,MAAO,CAAE,GAAG,KAAK,IAAK,CAC1B,CACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"UnboundEnvSource.mjs","names":[],"sources":["../../../src/sources/UnboundEnvSource.ts"],"sourcesContent":["import { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { BareEnvSource } from '../types';\n\n/**\n * The default source until one is bound. Every read throws NoSourceBound so a forgotten `useSource`\n * surfaces at read time instead of silently yielding nothing. The Node entry binds {@link NodeEnvSource}\n * at load; browser and Workers bundles must call `Envapter.useSource(...)` before reading.\n * @internal\n */\nexport class UnboundEnvSource implements BareEnvSource {\n readonly supportsFiles = false;\n\n readVars(): Record<string, string> {\n throw new EnvaptError(\n EnvaptErrorCodes.NoSourceBound,\n 'No environment source is bound. Call Envapter.useSource(...) with a source such as new ManualEnvSource({...}) or new WorkerEnvSource(env) before reading.'\n );\n }\n}\n"],"mappings":"iDAUA,IAAa,EAAb,KAAuD,CACnD,cAAyB,GAEzB,UAAmC,CAC/B,MAAM,IAAI,EAAA,IAEN,2JACJ,CACJ,CACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"WorkerEnvSource.mjs","names":[],"sources":["../../../src/sources/WorkerEnvSource.ts"],"sourcesContent":["import { coerceToStringRecord } from './coerce';\n\nimport type { BareEnvSource } from '../types';\n\n/**\n * Environment source for Cloudflare Workers, seeded from the `env` binding. String bindings pass\n * through; non-string bindings are JSON-stringified so the converters still apply, and so must be\n * JSON-serializable (a `bigint` or circular value throws). No filesystem, so the `.env` cascade and\n * file-based APIs do not apply.\n * @public\n */\nexport class WorkerEnvSource implements BareEnvSource {\n /** Always `false`. With no filesystem, the `.env` cascade and file APIs do not apply. */\n readonly supportsFiles = false;\n private readonly vars: Record<string, string>;\n\n /** Seed the source from the Workers `env` binding. Non-string values are JSON-stringified, so they must be JSON-serializable. */\n constructor(env: Record<string, unknown>) {\n this.vars = coerceToStringRecord(env);\n }\n\n /** Returns a snapshot clone of the `env` binding as plain strings. */\n readVars(): Record<string, string> {\n return { ...this.vars };\n }\n}\n"],"mappings":"oDAWA,IAAa,EAAb,KAAsD,CAElD,cAAyB,GACzB,KAGA,YAAY,EAA8B,CACtC,KAAK,KAAO,EAAqB,CAAG,CACxC,CAGA,UAAmC,CAC/B,MAAO,CAAE,GAAG,KAAK,IAAK,CAC1B,CACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"coerce.mjs","names":[],"sources":["../../../src/sources/coerce.ts"],"sourcesContent":["// Shared by ManualEnvSource and WorkerEnvSource. The returned record is fresh, so a caller mutating its\n// object later can't leak into the source; non-string values are JSON-stringified.\nexport function coerceToStringRecord(env: Record<string, unknown>): Record<string, string> {\n const snapshot: Record<string, string> = {};\n for (const [key, value] of Object.entries(env)) {\n if (typeof value === 'string') {\n snapshot[key] = value;\n continue;\n }\n const encoded = JSON.stringify(value);\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- TS lib mistypes JSON.stringify's return as always-string; it is string | undefined at runtime\n if (encoded !== undefined) snapshot[key] = encoded;\n }\n return snapshot;\n}\n"],"mappings":"AAEA,SAAgB,EAAqB,EAAsD,CACvF,IAAM,EAAmC,CAAC,EAC1C,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAG,EAAG,CAC5C,GAAI,OAAO,GAAU,SAAU,CAC3B,EAAS,GAAO,EAChB,QACJ,CACA,IAAM,EAAU,KAAK,UAAU,CAAK,EAEhC,IAAY,IAAA,KAAW,EAAS,GAAO,EAC/C,CACA,OAAO,CACX"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ManualEnvSource.cjs","names":["coerceToStringRecord"],"sources":["../../../src/sources/ManualEnvSource.ts"],"sourcesContent":["import { coerceToStringRecord } from './coerce';\n\nimport type { BareEnvSource } from '../types';\n\n/**\n * Environment source seeded from an object you provide: the config your bundler injects into a browser\n * build (Vite's `import.meta.env`, a webpack `DefinePlugin` global), a test fixture, or any other plain\n * object. Pass it straight through; non-string values are JSON-stringified so the converters still apply.\n * It has no filesystem, so the `.env` cascade and file-based APIs do not apply.\n * @public\n */\nexport class ManualEnvSource implements BareEnvSource {\n /** Always `false`. With no filesystem, the `.env` cascade and file APIs do not apply. */\n readonly supportsFiles = false;\n private readonly vars: Record<string, string>;\n\n /** Seed the source from `vars`. Non-string values are JSON-stringified so the converters still apply. */\n constructor(vars: Record<string, unknown>) {\n this.vars = coerceToStringRecord(vars);\n }\n\n /** Returns a snapshot clone of the provided object as plain strings. */\n readVars(): Record<string, string> {\n return { ...this.vars };\n }\n}\n"],"mappings":"gCAWA,IAAa,EAAb,KAAsD,CAElD,cAAyB,GACzB,KAGA,YAAY,EAA+B,CACvC,KAAK,KAAOA,EAAAA,qBAAqB,CAAI,CACzC,CAGA,UAAmC,CAC/B,MAAO,CAAE,GAAG,KAAK,IAAK,CAC1B,CACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ManualEnvSource.mjs","names":[],"sources":["../../../src/sources/ManualEnvSource.ts"],"sourcesContent":["import { coerceToStringRecord } from './coerce';\n\nimport type { BareEnvSource } from '../types';\n\n/**\n * Environment source seeded from an object you provide: the config your bundler injects into a browser\n * build (Vite's `import.meta.env`, a webpack `DefinePlugin` global), a test fixture, or any other plain\n * object. Pass it straight through; non-string values are JSON-stringified so the converters still apply.\n * It has no filesystem, so the `.env` cascade and file-based APIs do not apply.\n * @public\n */\nexport class ManualEnvSource implements BareEnvSource {\n /** Always `false`. With no filesystem, the `.env` cascade and file APIs do not apply. */\n readonly supportsFiles = false;\n private readonly vars: Record<string, string>;\n\n /** Seed the source from `vars`. Non-string values are JSON-stringified so the converters still apply. */\n constructor(vars: Record<string, unknown>) {\n this.vars = coerceToStringRecord(vars);\n }\n\n /** Returns a snapshot clone of the provided object as plain strings. */\n readVars(): Record<string, string> {\n return { ...this.vars };\n }\n}\n"],"mappings":"oDAWA,IAAa,EAAb,KAAsD,CAElD,cAAyB,GACzB,KAGA,YAAY,EAA+B,CACvC,KAAK,KAAO,EAAqB,CAAI,CACzC,CAGA,UAAmC,CAC/B,MAAO,CAAE,GAAG,KAAK,IAAK,CAC1B,CACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"NodeEnvSource.cjs","names":["process","fs"],"sources":["../../../src/sources/NodeEnvSource.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { dirname, isAbsolute, join, resolve } from 'node:path';\nimport process from 'node:process';\nimport { fileURLToPath } from 'node:url';\n\nimport type { FileEnvSource } from '../types';\n\n/**\n * Default environment source on Node, Bun, and Deno: a snapshot of `process.env`. Its\n * `supportsFiles` is `true`, so the engine also layers the `.env` cascade on top, resolves\n * `baseDir`, and can mirror loaded keys back to `process.env`.\n * @public\n */\nexport class NodeEnvSource implements FileEnvSource {\n /** Always `true`. The engine layers the `.env` cascade and `baseDir` on top of `process.env`. */\n readonly supportsFiles = true;\n\n /** Returns a snapshot clone of `process.env` as plain strings. */\n readVars(): Record<string, string> {\n // Clone so the loader and downstream reads never mutate process.env.\n return { ...(process.env as Record<string, string>) };\n }\n\n /** Reads a file with `fs.readFileSync`, or `undefined` when it is missing or unreadable. */\n readFile(path: string, encoding: string): string | undefined {\n try {\n // justified: our public encoding type is `string`; fs needs the BufferEncoding subset.\n return fs.readFileSync(path, encoding as BufferEncoding);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Resolves a directory path or a module / `file:` URL to an absolute directory. A `file:` URL\n * resolves to its containing directory, and a plain path (`import.meta.dirname`, `__dirname`) is\n * taken as the directory itself.\n */\n normalizeBaseDir(value: string | URL): string {\n if (value instanceof URL) return dirname(fileURLToPath(value));\n if (value.startsWith('file:')) return dirname(fileURLToPath(value));\n return resolve(value);\n }\n\n /** Joins a relative `.env` path onto `baseDir`. Absolute paths pass through unchanged. */\n resolvePath(baseDir: string, candidate: string): string {\n if (isAbsolute(candidate)) return candidate;\n return join(baseDir, candidate);\n }\n\n /** Writes each key to `process.env`, backing `Envapter.syncProcessEnv`. */\n writeVars(vars: Record<string, string>): void {\n for (const [key, value] of Object.entries(vars)) {\n process.env[key] = value;\n }\n }\n}\n"],"mappings":"+LAaA,IAAa,EAAb,KAAoD,CAEhD,cAAyB,GAGzB,UAAmC,CAE/B,MAAO,CAAE,GAAIA,EAAAA,QAAQ,GAA+B,CACxD,CAGA,SAAS,EAAc,EAAsC,CACzD,GAAI,CAEA,OAAOC,EAAAA,QAAG,aAAa,EAAM,CAA0B,CAC3D,MAAQ,CACJ,MACJ,CACJ,CAOA,iBAAiB,EAA6B,CAG1C,OAFI,aAAiB,KACjB,EAAM,WAAW,OAAO,GAAG,EAAA,EAAA,QAAA,EAAA,EAAA,EAAA,cAAA,CAA6B,CAAK,CAAC,GAClE,EAAA,EAAA,QAAA,CAAe,CAAK,CACxB,CAGA,YAAY,EAAiB,EAA2B,CAEpD,OADA,EAAA,EAAA,WAAA,CAAe,CAAS,EAAU,GAClC,EAAA,EAAA,KAAA,CAAY,EAAS,CAAS,CAClC,CAGA,UAAU,EAAoC,CAC1C,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAI,EAC1C,EAAA,QAAQ,IAAI,GAAO,CAE3B,CACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"NodeEnvSource.mjs","names":[],"sources":["../../../src/sources/NodeEnvSource.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { dirname, isAbsolute, join, resolve } from 'node:path';\nimport process from 'node:process';\nimport { fileURLToPath } from 'node:url';\n\nimport type { FileEnvSource } from '../types';\n\n/**\n * Default environment source on Node, Bun, and Deno: a snapshot of `process.env`. Its\n * `supportsFiles` is `true`, so the engine also layers the `.env` cascade on top, resolves\n * `baseDir`, and can mirror loaded keys back to `process.env`.\n * @public\n */\nexport class NodeEnvSource implements FileEnvSource {\n /** Always `true`. The engine layers the `.env` cascade and `baseDir` on top of `process.env`. */\n readonly supportsFiles = true;\n\n /** Returns a snapshot clone of `process.env` as plain strings. */\n readVars(): Record<string, string> {\n // Clone so the loader and downstream reads never mutate process.env.\n return { ...(process.env as Record<string, string>) };\n }\n\n /** Reads a file with `fs.readFileSync`, or `undefined` when it is missing or unreadable. */\n readFile(path: string, encoding: string): string | undefined {\n try {\n // justified: our public encoding type is `string`; fs needs the BufferEncoding subset.\n return fs.readFileSync(path, encoding as BufferEncoding);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Resolves a directory path or a module / `file:` URL to an absolute directory. A `file:` URL\n * resolves to its containing directory, and a plain path (`import.meta.dirname`, `__dirname`) is\n * taken as the directory itself.\n */\n normalizeBaseDir(value: string | URL): string {\n if (value instanceof URL) return dirname(fileURLToPath(value));\n if (value.startsWith('file:')) return dirname(fileURLToPath(value));\n return resolve(value);\n }\n\n /** Joins a relative `.env` path onto `baseDir`. Absolute paths pass through unchanged. */\n resolvePath(baseDir: string, candidate: string): string {\n if (isAbsolute(candidate)) return candidate;\n return join(baseDir, candidate);\n }\n\n /** Writes each key to `process.env`, backing `Envapter.syncProcessEnv`. */\n writeVars(vars: Record<string, string>): void {\n for (const [key, value] of Object.entries(vars)) {\n process.env[key] = value;\n }\n }\n}\n"],"mappings":"uKAaA,IAAa,EAAb,KAAoD,CAEhD,cAAyB,GAGzB,UAAmC,CAE/B,MAAO,CAAE,GAAI,EAAQ,GAA+B,CACxD,CAGA,SAAS,EAAc,EAAsC,CACzD,GAAI,CAEA,OAAO,EAAG,aAAa,EAAM,CAA0B,CAC3D,MAAQ,CACJ,MACJ,CACJ,CAOA,iBAAiB,EAA6B,CAG1C,OAFI,aAAiB,KACjB,EAAM,WAAW,OAAO,EAAU,EAAQ,EAAc,CAAK,CAAC,EAC3D,EAAQ,CAAK,CACxB,CAGA,YAAY,EAAiB,EAA2B,CAEpD,OADI,EAAW,CAAS,EAAU,EAC3B,EAAK,EAAS,CAAS,CAClC,CAGA,UAAU,EAAoC,CAC1C,IAAK,GAAM,CAAC,EAAK,KAAU,OAAO,QAAQ,CAAI,EAC1C,EAAQ,IAAI,GAAO,CAE3B,CACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"UnboundEnvSource.cjs","names":["EnvaptError"],"sources":["../../../src/sources/UnboundEnvSource.ts"],"sourcesContent":["import { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { BareEnvSource } from '../types';\n\n/**\n * The default source until one is bound. Every read throws NoSourceBound so a forgotten `useSource`\n * surfaces at read time instead of silently yielding nothing. The Node entry binds {@link NodeEnvSource}\n * at load; browser and Workers bundles must call `Envapter.useSource(...)` before reading.\n * @internal\n */\nexport class UnboundEnvSource implements BareEnvSource {\n readonly supportsFiles = false;\n\n readVars(): Record<string, string> {\n throw new EnvaptError(\n EnvaptErrorCodes.NoSourceBound,\n 'No environment source is bound. Call Envapter.useSource(...) with a source such as new ManualEnvSource({...}) or new WorkerEnvSource(env) before reading.'\n );\n }\n}\n"],"mappings":"sCAUA,IAAa,EAAb,KAAuD,CACnD,cAAyB,GAEzB,UAAmC,CAC/B,MAAM,IAAIA,EAAAA,YAAAA,IAEN,2JACJ,CACJ,CACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"UnboundEnvSource.mjs","names":[],"sources":["../../../src/sources/UnboundEnvSource.ts"],"sourcesContent":["import { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { BareEnvSource } from '../types';\n\n/**\n * The default source until one is bound. Every read throws NoSourceBound so a forgotten `useSource`\n * surfaces at read time instead of silently yielding nothing. The Node entry binds {@link NodeEnvSource}\n * at load; browser and Workers bundles must call `Envapter.useSource(...)` before reading.\n * @internal\n */\nexport class UnboundEnvSource implements BareEnvSource {\n readonly supportsFiles = false;\n\n readVars(): Record<string, string> {\n throw new EnvaptError(\n EnvaptErrorCodes.NoSourceBound,\n 'No environment source is bound. Call Envapter.useSource(...) with a source such as new ManualEnvSource({...}) or new WorkerEnvSource(env) before reading.'\n );\n }\n}\n"],"mappings":"iDAUA,IAAa,EAAb,KAAuD,CACnD,cAAyB,GAEzB,UAAmC,CAC/B,MAAM,IAAI,EAAA,IAEN,2JACJ,CACJ,CACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"WorkerEnvSource.cjs","names":["coerceToStringRecord"],"sources":["../../../src/sources/WorkerEnvSource.ts"],"sourcesContent":["import { coerceToStringRecord } from './coerce';\n\nimport type { BareEnvSource } from '../types';\n\n/**\n * Environment source for Cloudflare Workers, seeded from the `env` binding. String bindings pass\n * through; non-string bindings are JSON-stringified so the converters still apply, and so must be\n * JSON-serializable (a `bigint` or circular value throws). No filesystem, so the `.env` cascade and\n * file-based APIs do not apply.\n * @public\n */\nexport class WorkerEnvSource implements BareEnvSource {\n /** Always `false`. With no filesystem, the `.env` cascade and file APIs do not apply. */\n readonly supportsFiles = false;\n private readonly vars: Record<string, string>;\n\n /** Seed the source from the Workers `env` binding. Non-string values are JSON-stringified, so they must be JSON-serializable. */\n constructor(env: Record<string, unknown>) {\n this.vars = coerceToStringRecord(env);\n }\n\n /** Returns a snapshot clone of the `env` binding as plain strings. */\n readVars(): Record<string, string> {\n return { ...this.vars };\n }\n}\n"],"mappings":"gCAWA,IAAa,EAAb,KAAsD,CAElD,cAAyB,GACzB,KAGA,YAAY,EAA8B,CACtC,KAAK,KAAOA,EAAAA,qBAAqB,CAAG,CACxC,CAGA,UAAmC,CAC/B,MAAO,CAAE,GAAG,KAAK,IAAK,CAC1B,CACJ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"WorkerEnvSource.mjs","names":[],"sources":["../../../src/sources/WorkerEnvSource.ts"],"sourcesContent":["import { coerceToStringRecord } from './coerce';\n\nimport type { BareEnvSource } from '../types';\n\n/**\n * Environment source for Cloudflare Workers, seeded from the `env` binding. String bindings pass\n * through; non-string bindings are JSON-stringified so the converters still apply, and so must be\n * JSON-serializable (a `bigint` or circular value throws). No filesystem, so the `.env` cascade and\n * file-based APIs do not apply.\n * @public\n */\nexport class WorkerEnvSource implements BareEnvSource {\n /** Always `false`. With no filesystem, the `.env` cascade and file APIs do not apply. */\n readonly supportsFiles = false;\n private readonly vars: Record<string, string>;\n\n /** Seed the source from the Workers `env` binding. Non-string values are JSON-stringified, so they must be JSON-serializable. */\n constructor(env: Record<string, unknown>) {\n this.vars = coerceToStringRecord(env);\n }\n\n /** Returns a snapshot clone of the `env` binding as plain strings. */\n readVars(): Record<string, string> {\n return { ...this.vars };\n }\n}\n"],"mappings":"oDAWA,IAAa,EAAb,KAAsD,CAElD,cAAyB,GACzB,KAGA,YAAY,EAA8B,CACtC,KAAK,KAAO,EAAqB,CAAG,CACxC,CAGA,UAAmC,CAC/B,MAAO,CAAE,GAAG,KAAK,IAAK,CAC1B,CACJ"}
|
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import { EnvaptConverter } from "../types/Conversion.mjs";
|
|
2
|
-
import { StandardSchemaV1 } from "../infra/StandardSchema.mjs";
|
|
3
|
-
import { EnvKeyInput, EnvapterService } from "../types/Env.mjs";
|
|
4
|
-
|
|
5
|
-
//#region src/converters/ValueConverter.d.ts
|
|
6
|
-
/**
|
|
7
|
-
* Convert a resolved environment value to its declared type via built-in, primitive, array,
|
|
8
|
-
* custom, or Standard Schema converters.
|
|
9
|
-
* @internal
|
|
10
|
-
*/
|
|
11
|
-
declare class ValueConverter {
|
|
12
|
-
private readonly envService;
|
|
13
|
-
constructor(envService: EnvapterService);
|
|
14
|
-
convertValue<TFallback>(key: EnvKeyInput, fallback: TFallback | undefined, converter: EnvaptConverter<TFallback> | undefined, hasFallback: boolean): TFallback | null | undefined;
|
|
15
|
-
private processFallbackForConverter;
|
|
16
|
-
private convertPrimitiveToString;
|
|
17
|
-
private processBuiltInConverter;
|
|
18
|
-
private processArrayConverter;
|
|
19
|
-
private processCustomConverter;
|
|
20
|
-
private resolveConverter;
|
|
21
|
-
convertWithSchema(key: EnvKeyInput, schema: StandardSchemaV1, fallback: unknown, hasFallback: boolean): unknown;
|
|
22
|
-
}
|
|
23
|
-
//#endregion
|
|
24
|
-
export { ValueConverter };
|
|
25
|
-
//# sourceMappingURL=ValueConverter.d.mts.map
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { EnvapterService } from "../types/Env.mjs";
|
|
2
|
-
|
|
3
|
-
//#region src/engine/TemplateResolver.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* Resolve `${VAR}` template references in environment values, guarding against circular
|
|
6
|
-
* references and missing variables.
|
|
7
|
-
* @internal
|
|
8
|
-
*/
|
|
9
|
-
declare class TemplateResolver {
|
|
10
|
-
private readonly envService;
|
|
11
|
-
private readonly TEMPLATE_REGEX;
|
|
12
|
-
constructor(envService: EnvapterService);
|
|
13
|
-
resolveTemplate(key: string, value: string, stack?: Set<string>): string;
|
|
14
|
-
}
|
|
15
|
-
//#endregion
|
|
16
|
-
export { TemplateResolver };
|
|
17
|
-
//# sourceMappingURL=TemplateResolver.d.mts.map
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { BareEnvSource } from "../types/Source.mjs";
|
|
2
|
-
|
|
3
|
-
//#region src/sources/ManualEnvSource.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* Environment source seeded from an object you provide: the config your bundler injects into a browser
|
|
6
|
-
* build (Vite's `import.meta.env`, a webpack `DefinePlugin` global), a test fixture, or any other plain
|
|
7
|
-
* object. Pass it straight through; non-string values are JSON-stringified so the converters still apply.
|
|
8
|
-
* It has no filesystem, so the `.env` cascade and file-based APIs do not apply.
|
|
9
|
-
* @public
|
|
10
|
-
*/
|
|
11
|
-
declare class ManualEnvSource implements BareEnvSource {
|
|
12
|
-
/** Always `false`. With no filesystem, the `.env` cascade and file APIs do not apply. */
|
|
13
|
-
readonly supportsFiles = false;
|
|
14
|
-
private readonly vars;
|
|
15
|
-
/** Seed the source from `vars`. Non-string values are JSON-stringified so the converters still apply. */
|
|
16
|
-
constructor(vars: Record<string, unknown>);
|
|
17
|
-
/** Returns a snapshot clone of the provided object as plain strings. */
|
|
18
|
-
readVars(): Record<string, string>;
|
|
19
|
-
}
|
|
20
|
-
//#endregion
|
|
21
|
-
export { ManualEnvSource };
|
|
22
|
-
//# sourceMappingURL=ManualEnvSource.d.mts.map
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import { BareEnvSource } from "../types/Source.mjs";
|
|
2
|
-
|
|
3
|
-
//#region src/sources/WorkerEnvSource.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* Environment source for Cloudflare Workers, seeded from the `env` binding. String bindings pass
|
|
6
|
-
* through; non-string bindings are JSON-stringified so the converters still apply, and so must be
|
|
7
|
-
* JSON-serializable (a `bigint` or circular value throws). No filesystem, so the `.env` cascade and
|
|
8
|
-
* file-based APIs do not apply.
|
|
9
|
-
* @public
|
|
10
|
-
*/
|
|
11
|
-
declare class WorkerEnvSource implements BareEnvSource {
|
|
12
|
-
/** Always `false`. With no filesystem, the `.env` cascade and file APIs do not apply. */
|
|
13
|
-
readonly supportsFiles = false;
|
|
14
|
-
private readonly vars;
|
|
15
|
-
/** Seed the source from the Workers `env` binding. Non-string values are JSON-stringified, so they must be JSON-serializable. */
|
|
16
|
-
constructor(env: Record<string, unknown>);
|
|
17
|
-
/** Returns a snapshot clone of the `env` binding as plain strings. */
|
|
18
|
-
readVars(): Record<string, string>;
|
|
19
|
-
}
|
|
20
|
-
//#endregion
|
|
21
|
-
export { WorkerEnvSource };
|
|
22
|
-
//# sourceMappingURL=WorkerEnvSource.d.mts.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{EnvaptError as e}from"../infra/Error.mjs";const t=1e3,n=60*t,r=60*n,i=24*r,a={ms:1,s:t,m:n,h:r,d:i,w:7*i},o=new RegExp(String.raw`^(\d+(?:\.\d+)?)(ms|s|m|h|d|w)?$`,`u`),s=new RegExp(String.raw`^(\d+(?:\.\d+)?)(ms|s|m|h|d|w)$`,`u`);function c(e,t=!1){let n=e.match(t?s:o);if(!n)return;let[,r,i]=n;if(!r)return;let c=Number.parseFloat(r);if(!Number.isNaN(c))return c*a[i??`ms`]}var l=class t{static string(e,t){return String(e)}static number(e,t){let n=Number(e);return Number.isNaN(n)?t:n}static boolean(e,t){let n=e.toLowerCase().trim();return[`1`,`yes`,`true`,`on`].includes(n)?!0:[`0`,`no`,`false`,`off`].includes(n)?!1:t}static bigint(e,t){try{return BigInt(e)}catch{return t}}static symbol(e,t){try{return e?Symbol.for(e):t}catch{return t}}static integer(e,t){let n=Number.parseInt(e,10);return Number.isNaN(n)?t:n}static float(e,t){let n=Number.parseFloat(e);return Number.isNaN(n)?t:n}static json(e,t){try{return JSON.parse(e)}catch{return t}}static url(e,t){try{return new URL(e)}catch{return t}}static regexp(e,t){try{let t=e.match(new RegExp(String.raw`^\/(.+)\/([gimsuvy]*)$`));return t?new RegExp(t[1],t[2]):new RegExp(e)}catch{return t}}static date(e,t){if(new RegExp(String.raw`^\d+$`).test(e)){let n=new Date(parseInt(e,10));return Number.isNaN(n.getTime())?t:n}if(!new RegExp(String.raw`^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$`,`u`).test(e))return t;let n=new Date(e);return Number.isNaN(n.getTime())?t:n}static time(t,n){let r=c(t);if(r!==void 0)return r;if(typeof n==`number`)return n;if(typeof n==`string`){let t=c(n,!0);if(t===void 0)throw new e(105,`Time-string fallback "${n}" is not a valid format. Expected <number><unit> where unit is one of: ms, s, m, h, d, w.`);return t}}static processArrayConverter(n,r,i=!1){if(n.trim()===``)return[];let a=n.split(r.delimiter).map(e=>String(e).trim());if(i){let t=a.findIndex(e=>e===``);if(t!==-1)throw new e(207,`Array element at index ${t} is empty or whitespace only (strict mode).`)}let o=a.filter(Boolean);if(!o.length)return[];let s=r.of;if(typeof s==`function`)return o.map((t,n)=>{let r=s(t);if(r===void 0)throw new e(206,`Custom element converter returned undefined for item "${t}" at index ${n}.`);return r});let c=t.getConverter(s);return o.map((t,n)=>{let r=c(t,void 0);if(r===void 0)throw new e(206,`Element "${t}" at index ${n} could not be converted to ${s}.`);return r})}static getConverter(e){return{string:t.string,number:t.number,boolean:t.boolean,integer:t.integer,bigint:t.bigint,symbol:t.symbol,float:t.float,json:t.json,url:t.url,regexp:t.regexp,date:t.date,time:t.time}[e]}};export{l as BuiltInConverters};
|
|
2
|
-
//# sourceMappingURL=BuiltInConverters.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
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 '../infra/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":"iDAcA,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,CAAM,EAAI,EAAW,CAC7C,CAEA,OAAO,QAAQ,E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,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,2 +0,0 @@
|
|
|
1
|
-
const e={String:`string`,Number:`number`,Boolean:`boolean`,Bigint:`bigint`,Symbol:`symbol`,Integer:`integer`,Float:`float`,Json:`json`,Url:`url`,Regexp:`regexp`,Date:`date`,Time:`time`};function t(e){return typeof e==`object`&&!!e&&`__envaptKind`in e&&e.__envaptKind===`array`}function n(t){return{__envaptKind:`array`,of:t?.of??e.String,delimiter:t?.delimiter??`,`}}const r={...e,array:n};export{r as Converters,t as isArrayOf};
|
|
2
|
-
//# sourceMappingURL=Converters.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Converters.mjs","names":[],"sources":["../../../src/converters/Converters.ts"],"sourcesContent":["const SCALAR = {\n String: 'string',\n Number: 'number',\n Boolean: 'boolean',\n Bigint: 'bigint',\n Symbol: 'symbol',\n Integer: 'integer',\n Float: 'float',\n Json: 'json',\n Url: 'url',\n Regexp: 'regexp',\n Date: 'date',\n Time: 'time'\n} as const;\n\n/**\n * String tokens for every built-in scalar converter.\n * @public\n */\nexport type ConverterToken = (typeof SCALAR)[keyof typeof SCALAR];\n\n/**\n * Custom element converter for use inside {@link Converters.array}. Receives the trimmed,\n * non-empty raw string for one array slot and returns the parsed value.\n * @public\n */\nexport type CustomElementConverter<TReturn = unknown> = (raw: string) => TReturn;\n\n/**\n * Valid element converters for {@link Converters.array}: any scalar token except\n * `json` and `regexp` (those don't compose as array elements), or a custom function.\n * @public\n */\nexport type ArrayElement = Exclude<ConverterToken, 'json' | 'regexp'> | CustomElementConverter;\n\n/**\n * Phantom-branded token produced by {@link Converters.array}. The `T` type parameter carries\n * the element converter through any variable indirection so inference survives. The\n * `__envaptKind` discriminant is present at runtime for dispatch.\n * @public\n */\nexport interface ArrayOf<TElement extends ArrayElement = ArrayElement> {\n /** Runtime discriminant marking this token as an array converter. Don't use directly. */\n readonly __envaptKind: 'array';\n /** The element converter applied to each split slot. */\n readonly of: TElement;\n /** The string the raw value is split on. */\n readonly delimiter: string;\n}\n\n/**\n * Runtime type guard for tokens produced by {@link Converters.array}.\n * @internal\n */\nexport function isArrayOf(value: unknown): value is ArrayOf {\n return typeof value === 'object' && value !== null && '__envaptKind' in value && value.__envaptKind === 'array';\n}\n\ntype ArrayScalarElement = Exclude<ConverterToken, 'json' | 'regexp'>;\n\n// Overloads. The function-element overload must come first so it wins inference when `of`\n// is a function, otherwise TS picks the scalar branch and `raw` defaults to `any`.\nfunction buildArrayConverter<TReturn>(opts: {\n of: CustomElementConverter<TReturn>;\n delimiter?: string;\n}): ArrayOf<CustomElementConverter<TReturn>>;\nfunction buildArrayConverter<TToken extends ArrayScalarElement>(opts: {\n of: TToken;\n delimiter?: string;\n}): ArrayOf<TToken>;\nfunction buildArrayConverter(opts?: { delimiter?: string }): ArrayOf<'string'>;\nfunction buildArrayConverter(opts?: { of?: ArrayElement; delimiter?: string }): ArrayOf<ArrayElement> {\n return {\n __envaptKind: 'array',\n of: opts?.of ?? SCALAR.String,\n delimiter: opts?.delimiter ?? ','\n };\n}\n\n/**\n * Built-in converters for environment variables. Use the scalar tokens (e.g. `Converters.Number`)\n * for primitive types and the {@link Converters.array} builder for delimited lists.\n *\n * @example\n * ```ts\n * \\@Envapt('PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * \\@Envapt('TAGS', { converter: Converters.array({ of: Converters.String, delimiter: ' ' }) })\n * static readonly tags: string[];\n * ```\n *\n * @public\n */\nexport const Converters = {\n ...SCALAR,\n array: buildArrayConverter\n} as const;\n"],"mappings":"AAAA,MAAM,EAAS,CACX,OAAQ,SACR,OAAQ,SACR,QAAS,UACT,OAAQ,SACR,OAAQ,SACR,QAAS,UACT,MAAO,QACP,KAAM,OACN,IAAK,MACL,OAAQ,SACR,KAAM,OACN,KAAM,MACV,EAyCA,SAAgB,EAAU,EAAkC,CACxD,OAAO,OAAO,GAAU,YAAY,GAAkB,iBAAkB,GAAS,EAAM,eAAiB,OAC5G,CAeA,SAAS,EAAoB,EAAyE,CAClG,MAAO,CACH,aAAc,QACd,GAAI,GAAM,IAAM,EAAO,OACvB,UAAW,GAAM,WAAa,GAClC,CACJ,CAiBA,MAAa,EAAa,CACtB,GAAG,EACH,MAAO,CACX"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=[`string`,`number`,`boolean`,`bigint`,`symbol`,`integer`,`float`,`json`,`url`,`regexp`,`date`,`time`],t={string:e=>typeof e==`string`,number:e=>typeof e==`number`,boolean:e=>typeof e==`boolean`,bigint:e=>typeof e==`bigint`,symbol:e=>typeof e==`symbol`,integer:e=>typeof e==`number`&&Number.isInteger(e),float:e=>typeof e==`number`,json:e=>{try{return JSON.parse(JSON.stringify(e)),!0}catch{return!1}},url:e=>e instanceof URL,regexp:e=>e instanceof RegExp,date:e=>e instanceof Date,time:e=>typeof e==`number`||typeof e==`string`};export{t as BuiltInConverterTypeCheckers,e as ListOfBuiltInConverters};
|
|
2
|
-
//# sourceMappingURL=ListOfBuiltInConverters.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ListOfBuiltInConverters.mjs","names":[],"sources":["../../../src/converters/ListOfBuiltInConverters.ts"],"sourcesContent":["import type { ConverterToken } from './Converters';\nimport type { JsonValue } from '../types';\n\n/**\n * List of built-in scalar converters for Envapt. Arrays are handled separately via\n * the {@link Converters.array} builder and the `ArrayOf<...>` brand.\n * @internal\n */\nexport const ListOfBuiltInConverters: ConverterToken[] = [\n 'string',\n 'number',\n 'boolean',\n 'bigint',\n 'symbol',\n 'integer',\n 'float',\n 'json',\n 'url',\n 'regexp',\n 'date',\n 'time'\n] as const;\n\n/**\n * Type checking functions for built-in scalar converter return types.\n * @internal\n */\nexport const BuiltInConverterTypeCheckers: Record<ConverterToken, (value: unknown) => boolean> = {\n string: (value: unknown): value is string => typeof value === 'string',\n number: (value: unknown): value is number => typeof value === 'number',\n boolean: (value: unknown): value is boolean => typeof value === 'boolean',\n bigint: (value: unknown): value is bigint => typeof value === 'bigint',\n symbol: (value: unknown): value is symbol => typeof value === 'symbol',\n integer: (value: unknown): value is number => typeof value === 'number' && Number.isInteger(value),\n float: (value: unknown): value is number => typeof value === 'number',\n json: (value: unknown): value is JsonValue => {\n try {\n JSON.parse(JSON.stringify(value));\n return true;\n } catch {\n return false;\n }\n },\n url: (value: unknown): value is URL => value instanceof URL,\n regexp: (value: unknown): value is RegExp => value instanceof RegExp,\n date: (value: unknown): value is Date => value instanceof Date,\n time: (value: unknown): value is number | string => typeof value === 'number' || typeof value === 'string'\n};\n"],"mappings":"AAQA,MAAa,EAA4C,CACrD,SACA,SACA,UACA,SACA,SACA,UACA,QACA,OACA,MACA,SACA,OACA,MACJ,EAMa,EAAoF,CAC7F,OAAS,GAAoC,OAAO,GAAU,SAC9D,OAAS,GAAoC,OAAO,GAAU,SAC9D,QAAU,GAAqC,OAAO,GAAU,UAChE,OAAS,GAAoC,OAAO,GAAU,SAC9D,OAAS,GAAoC,OAAO,GAAU,SAC9D,QAAU,GAAoC,OAAO,GAAU,UAAY,OAAO,UAAU,CAAK,EACjG,MAAQ,GAAoC,OAAO,GAAU,SAC7D,KAAO,GAAuC,CAC1C,GAAI,CAEA,OADA,KAAK,MAAM,KAAK,UAAU,CAAK,CAAC,EACzB,EACX,MAAQ,CACJ,MAAO,EACX,CACJ,EACA,IAAM,GAAiC,aAAiB,IACxD,OAAS,GAAoC,aAAiB,OAC9D,KAAO,GAAkC,aAAiB,KAC1D,KAAO,GAA6C,OAAO,GAAU,UAAY,OAAO,GAAU,QACtG"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{EnvaptError as e}from"../infra/Error.mjs";import{Validator as t}from"../engine/Validators.mjs";import{BuiltInConverters as n}from"./BuiltInConverters.mjs";function r(e){return Array.isArray(e)?`[${e.join(`, `)}]`:String(e)}var i=class{envService;constructor(e){this.envService=e}convertValue(e,n,r,i){let a=this.resolveConverter(r,n),o=this.processFallbackForConverter(a,n);if(t.isArrayConverter(a))return this.processArrayConverter(e,o,a,i);if(t.isPrimitiveConstructor(a)){let t=this.convertPrimitiveToString(a);return this.processBuiltInConverter(e,o,t,i,!0)}return t.isBuiltInConverter(a)?this.processBuiltInConverter(e,o,a,i,!1):this.processCustomConverter(e,o,a,i)}processFallbackForConverter(e,n){return t.isPrimitiveConstructor(e)&&n!==void 0?t.coercePrimitiveFallback(e,n):n}convertPrimitiveToString(t){if(t===String)return`string`;if(t===Number)return`number`;if(t===Boolean)return`boolean`;if(t===BigInt)return`bigint`;if(t===Symbol)return`symbol`;throw new e(204,`Unknown primitive constructor`)}processBuiltInConverter(e,r,i,a,o){t.builtInConverter(i),a&&r!==void 0&&!o&&t.validateBuiltInConverterFallback(i,r);let s=this.envService.get(e,void 0);if(s===void 0)return a?i===`time`&&typeof r==`string`?n.getConverter(i)(``,r):r:null;let c=n.getConverter(i)(s,r);return c===void 0&&!a?null:c}processArrayConverter(r,i,a,o){if(t.arrayConverter(a),o&&i!==void 0&&!Array.isArray(i))throw new e(101,`ArrayOf<...> requires that the fallback be an array, got ${typeof i}`);o&&Array.isArray(i)&&(t.validateArrayFallbackElementTypes(i),t.validateArrayConverterElementTypeMatch(a.of,i));let s=this.envService.get(r,void 0);if(s===void 0){if(!o)return null;if(a.of===`time`&&Array.isArray(i)&&i.every(e=>typeof e==`string`)){let e=n.getConverter(`time`);return i.map(t=>e(``,t))}return i}return n.processArrayConverter(s,a,this.envService.isStrict())}processCustomConverter(e,n,r,i){return t.customConvertor(r),r(this.envService.get(e,void 0),n)}resolveConverter(e,t){if(e)return e;let n=typeof t;return n===`number`?`number`:n===`boolean`?`boolean`:n===`bigint`?`bigint`:n===`symbol`?`symbol`:`string`}convertWithSchema(t,n,i,a){let o=this.envService.get(t,void 0);if(o===void 0){if(a)return i;throw new e(305,`Required environment variable "${r(t)}" is missing or empty.`)}let s;try{s=n[`~standard`].validate(o)}catch(n){throw new e(209,`Schema for "${r(t)}" threw during validation: ${n.message}`,{cause:n})}if(s instanceof Promise)throw new e(302,`Schema for "${r(t)}" returned a Promise. envapt requires synchronous schemas; use a sync validator or perform async checks outside the env layer.`);if(s.issues!==void 0){let n=s.issues[0]?.message??`no issue message`;throw new e(208,`Schema validation failed for "${r(t)}": ${n}`,{issues:s.issues})}return s.value}};export{i as ValueConverter};
|
|
2
|
-
//# sourceMappingURL=ValueConverter.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ValueConverter.mjs","names":[],"sources":["../../../src/converters/ValueConverter.ts"],"sourcesContent":["import { BuiltInConverters } from './BuiltInConverters';\nimport { Validator } from '../engine/Validators';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { ArrayOf } from './Converters';\nimport type { StandardSchemaV1 } from '../infra/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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AAM,EAAe,OAAO,EAK5B,OAJI,IAAiB,SAAiB,SAClC,IAAiB,UAAkB,UACnC,IAAiB,SAAiB,SAClC,IAAiB,SAAiB,SAC/B,QACX,CAIA,kBAAkB,EAAkB,EAA0B,EAAmB,EAA+B,CAC5G,IAAM,EAAM,KAAK,WAAW,IAAI,EAAK,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,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,2 +0,0 @@
|
|
|
1
|
-
import{EnvaptError as e}from"../infra/Error.mjs";import{debugWarn as t}from"../infra/Debug.mjs";import{PrimitiveMethods as n}from"./PrimitiveMethods.mjs";function r(e){return typeof e==`object`&&!!e&&`converter`in e}function i(e){return Array.isArray(e)?`[${e.join(`, `)}]`:String(e)}var a=class a extends n{static getUsing(n,a,o){if(r(a)){let t=a,{key:r,value:o}=this.resolveKeyInput(n);if(o===void 0||o.trim()===``)throw new e(305,`Required environment variable "${i(n)}" is missing or empty.`);return this.valueConverter.convertValue(r,void 0,t.converter,!1)}let s=a,{key:c,value:l}=this.resolveKeyInput(n);if(this.treatAsMissing(l)&&o===void 0){t(`${c} is missing or empty`);return}let u=o!==void 0;return this.valueConverter.convertValue(c,o,s,u)}getUsing(e,t,n){return a.getUsing(e,t,n)}static getWith(n,a,o){if(r(a)){let t=a,{key:r,value:o}=this.resolveKeyInput(n);if(o===void 0||o.trim()===``)throw new e(305,`Required environment variable "${i(n)}" is missing or empty.`);return this.valueConverter.convertValue(r,void 0,t.converter,!1)}let{key:s,value:c}=this.resolveKeyInput(n);if(this.treatAsMissing(c))return t(`${s} is missing or empty`),o;let l=o!==void 0;return this.valueConverter.convertValue(s,o,a,l)}getWith(e,t,n){return a.getWith(e,t,n)}static parse(e,t,n){let r=arguments.length>2;return this.valueConverter.convertWithSchema(e,t,n,r)}parse(e,t,n){let r=arguments.length>2;return a.valueConverter.convertWithSchema(e,t,n,r)}};export{a as AdvancedMethods};
|
|
2
|
-
//# sourceMappingURL=AdvancedMethods.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"AdvancedMethods.mjs","names":[],"sources":["../../../src/core/AdvancedMethods.ts"],"sourcesContent":["import { PrimitiveMethods } from './PrimitiveMethods';\nimport { debugWarn } from '../infra/Debug';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { ArrayOf } from '../converters';\nimport type { InferSchemaOutput, StandardSchemaV1 } from '../infra/StandardSchema';\nimport type {\n AdvancedConverterReturn,\n BuiltInConverter,\n ConditionalReturn,\n ConverterFunction,\n EnvKeyInput,\n InferConverterReturnType,\n SchemaConstraint,\n TimeFallback\n} from '../types';\n\ninterface GetUsingRequiredOptions<TConverter> {\n converter: TConverter;\n required: true;\n}\n\ninterface GetWithRequiredOptions<TReturnType> {\n converter: ConverterFunction<TReturnType>;\n required: true;\n}\n\nfunction isOptionsBag(value: unknown): value is { converter: unknown; required?: boolean; fallback?: unknown } {\n // `ArrayOf` tokens have `of`/`delimiter` but no `converter` key, so the presence of\n // `converter` discriminates the options-bag form from a positional converter token.\n return typeof value === 'object' && value !== null && 'converter' in value;\n}\n\nfunction formatKeyForError(key: EnvKeyInput): string {\n return Array.isArray(key) ? `[${key.join(', ')}]` : String(key);\n}\n\n/**\n * Mixin for advanced methods for environment variable conversion using built-in and custom converters\n * @internal\n */\nexport class AdvancedMethods extends PrimitiveMethods {\n /**\n * Get an environment variable using a built-in converter.\n *\n * Supports both scalar tokens (e.g. `Converters.Number`) and `ArrayOf<...>` tokens\n * produced by `Converters.array(...)`. The key can be a single name or an ordered list;\n * the first defined value wins.\n */\n // Time-specific overload must precede the generic BuiltInConverter overload so it wins\n // overload resolution (TimeFallback accepts time-strings like `'10s'`).\n static getUsing<TFallback extends TimeFallback | undefined = undefined>(\n key: EnvKeyInput,\n converter: 'time',\n fallback?: TFallback\n ): ConditionalReturn<number, TFallback>;\n static getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converter: TConverter,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback>;\n static getUsing<TReturn>(key: EnvKeyInput, converter: BuiltInConverter | ArrayOf, fallback?: TReturn): TReturn;\n static getUsing(key: EnvKeyInput, options: GetUsingRequiredOptions<'time'>): number;\n static getUsing<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options: GetUsingRequiredOptions<TConverter>\n ): InferConverterReturnType<TConverter>;\n static getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converterOrOptions: TConverter | GetUsingRequiredOptions<TConverter>,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback> {\n if (isOptionsBag(converterOrOptions)) {\n const options = converterOrOptions;\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n\n if (value === undefined || value.trim() === '') {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Required environment variable \"${formatKeyForError(key)}\" is missing or empty.`\n );\n }\n\n const result = this.valueConverter.convertValue(\n resolvedKey,\n undefined,\n options.converter as TConverter,\n false\n );\n return result as AdvancedConverterReturn<TConverter, TFallback>;\n }\n\n const converter = converterOrOptions as TConverter;\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n\n // No env value AND no fallback: return undefined to match primitive-method semantics.\n // Otherwise route through the parser so asymmetric fallback types (TimeFallback,\n // TimeFallback[] for `of: time` arrays) get coerced to the declared return type.\n if (this.treatAsMissing(value) && fallback === undefined) {\n debugWarn(`${resolvedKey} is missing or empty`);\n return undefined as AdvancedConverterReturn<TConverter, TFallback>;\n }\n\n const hasFallback = fallback !== undefined;\n const result = this.valueConverter.convertValue(resolvedKey, fallback, converter, hasFallback);\n\n return result as AdvancedConverterReturn<TConverter, TFallback>;\n }\n\n /**\n * @see {@link AdvancedMethods.getUsing}\n */\n getUsing<TFallback extends TimeFallback | undefined = undefined>(\n key: EnvKeyInput,\n converter: 'time',\n fallback?: TFallback\n ): ConditionalReturn<number, TFallback>;\n getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converter: TConverter,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback>;\n getUsing<TReturn>(key: EnvKeyInput, converter: BuiltInConverter | ArrayOf, fallback?: TReturn): TReturn;\n getUsing(key: EnvKeyInput, options: GetUsingRequiredOptions<'time'>): number;\n getUsing<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options: GetUsingRequiredOptions<TConverter>\n ): InferConverterReturnType<TConverter>;\n getUsing<TConverter extends BuiltInConverter | ArrayOf, TFallback = undefined>(\n key: EnvKeyInput,\n converterOrOptions: TConverter | GetUsingRequiredOptions<TConverter>,\n fallback?: TFallback\n ): AdvancedConverterReturn<TConverter, TFallback> {\n return AdvancedMethods.getUsing(key, converterOrOptions as TConverter, fallback);\n }\n\n /**\n * Get an environment variable using a custom converter function.\n * Accepts a single key or an ordered list for automatic fallback.\n */\n static getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converter: ConverterFunction<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback>;\n static getWith<TReturnType>(key: EnvKeyInput, options: GetWithRequiredOptions<TReturnType>): TReturnType;\n static getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converterOrOptions: ConverterFunction<TReturnType> | GetWithRequiredOptions<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback> {\n if (isOptionsBag(converterOrOptions)) {\n const options = converterOrOptions;\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n\n if (value === undefined || value.trim() === '') {\n throw new EnvaptError(\n EnvaptErrorCodes.MissingEnvValue,\n `Required environment variable \"${formatKeyForError(key)}\" is missing or empty.`\n );\n }\n\n const result = this.valueConverter.convertValue(\n resolvedKey,\n undefined,\n options.converter as ConverterFunction<undefined>,\n false\n );\n return result as ConditionalReturn<TReturnType, TFallback>;\n }\n\n // Check if variable exists first, for consistency with primitive methods\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n if (this.treatAsMissing(value)) {\n debugWarn(`${resolvedKey} is missing or empty`);\n return fallback as ConditionalReturn<TReturnType, TFallback>;\n }\n\n const hasFallback = fallback !== undefined;\n // Convert the converter to match the expected signature via unknown\n const result = this.valueConverter.convertValue(\n resolvedKey,\n fallback,\n converterOrOptions as unknown as ConverterFunction<TFallback>,\n hasFallback\n );\n\n return result as ConditionalReturn<TReturnType, TFallback>;\n }\n\n /**\n * @see {@link AdvancedMethods.getWith}\n */\n getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converter: ConverterFunction<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback>;\n getWith<TReturnType>(key: EnvKeyInput, options: GetWithRequiredOptions<TReturnType>): TReturnType;\n getWith<TReturnType, TFallback extends TReturnType | undefined = undefined>(\n key: EnvKeyInput,\n converterOrOptions: ConverterFunction<TReturnType> | GetWithRequiredOptions<TReturnType>,\n fallback?: TFallback\n ): ConditionalReturn<TReturnType, TFallback> {\n return AdvancedMethods.getWith(key, converterOrOptions as ConverterFunction<TReturnType>, fallback);\n }\n\n /**\n * Validate an environment variable through a {@link StandardSchemaV1}-conformant schema\n * (zod, valibot, arktype, etc). Throws `MissingEnvValue` if the env value is absent and\n * no fallback is provided. The fallback, when provided, is returned as-is on missing;\n * it does NOT pass through the schema (mirrors custom-converter behavior).\n *\n * Synchronous schemas only. A Promise-returning `validate` triggers an\n * `InvalidUserDefinedConfig` throw at the call site.\n *\n * @example\n * ```ts\n * import { z } from 'zod';\n * const port = Envapter.parse('PORT', z.coerce.number().min(1024).max(65535), 3000);\n * ```\n */\n static parse<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n schema: SchemaConstraint<Schema>,\n fallback?: InferSchemaOutput<Schema>\n ): InferSchemaOutput<Schema> {\n const hasFallback = arguments.length > 2;\n // SchemaConstraint resolves to the unsatisfiable SchemaMustBeSync brand for async\n // schemas, so reaching this body means the input is structurally a sync Schema.\n const result = this.valueConverter.convertWithSchema(\n key,\n schema as unknown as StandardSchemaV1,\n fallback,\n hasFallback\n );\n return result;\n }\n\n /**\n * @see {@link AdvancedMethods.parse}\n */\n parse<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n schema: SchemaConstraint<Schema>,\n fallback?: InferSchemaOutput<Schema>\n ): InferSchemaOutput<Schema> {\n const hasFallback = arguments.length > 2;\n const result = AdvancedMethods.valueConverter.convertWithSchema(\n key,\n schema as unknown as StandardSchemaV1,\n fallback,\n hasFallback\n );\n return result;\n }\n}\n"],"mappings":"0JA2BA,SAAS,EAAa,EAAyF,CAG3G,OAAO,OAAO,GAAU,YAAY,GAAkB,cAAe,CACzE,CAEA,SAAS,EAAkB,EAA0B,CACjD,OAAO,MAAM,QAAQ,CAAG,EAAI,IAAI,EAAI,KAAK,IAAI,EAAE,GAAK,OAAO,CAAG,CAClE,CAMA,IAAa,EAAb,MAAa,UAAwB,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,EACyC,CACzC,OAAO,EAAgB,QAAQ,EAAK,EAAsD,CAAQ,CACtG,CAiBA,OAAO,MACH,EACA,EACA,EACyB,CACzB,IAAM,EAAc,UAAU,OAAS,EASvC,OANe,KAAK,eAAe,kBAC/B,EACA,EACA,EACA,CAEQ,CAChB,CAKA,MACI,EACA,EACA,EACyB,CACzB,IAAM,EAAc,UAAU,OAAS,EAOvC,OANe,EAAgB,eAAe,kBAC1C,EACA,EACA,EACA,CAEQ,CAChB,CACJ"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{EnvaptError as e}from"../infra/Error.mjs";import{Validator as t}from"../engine/Validators.mjs";import{bindRuntimeFromSource as n}from"../infra/runtime.mjs";import{debugVerbose as r,getDebugLevel as i,setDebugLevel as a}from"../infra/Debug.mjs";import{loadDotenv as o}from"../infra/Dotenv.mjs";import{UnboundEnvSource as s}from"../sources/UnboundEnvSource.mjs";const c=new Map;var l=class l{static _envPaths=[`.env`];static _envPathsExplicitlySet=!1;static _baseDir=void 0;static _userDefinedEnvFileOptions={};static _strict=!1;static _syncProcessEnv=!1;static _dotenvAddedKeys=new Set;static _source=new s;static set strict(e){l._strict=e,this.refreshCache()}static get strict(){return l._strict}static set debug(e){a(e)}static get debug(){return i()}static set syncProcessEnv(e){t.validateSyncProcessEnv(e);let n=l._syncProcessEnv;l._syncProcessEnv=e,!n&&e&&c.size>0&&this.mirrorToProcessEnv()}static get syncProcessEnv(){return l._syncProcessEnv}static treatAsMissing(e){return!!(e===void 0||e===``||l._strict&&e.trim()===``)}static resolveAgainstBase(e){let t=l._baseDir;if(t===void 0)return e;let n=l._source;return n.supportsFiles?n.resolvePath(t,e):e}static assertFileApiSupported(t,n){if(!n.supportsFiles)throw new e(306,`${t} requires a filesystem-backed source; the bound source does not support .env files.`)}static sourceFileExists(e){let t=l._source;return t.supportsFiles?t.readFile(e,`utf8`)!==void 0:!1}static refreshCache(){c.clear(),l._dotenvAddedKeys=new Set,r(`cache cleared, reloading config`),this.config}static mirrorToProcessEnv(){if(l._dotenvAddedKeys.size===0)return;let e=l._source;if(!e.supportsFiles)return;let t={};for(let e of l._dotenvAddedKeys){let n=c.get(e);typeof n==`string`&&(t[e]=this.resolveForMirror(e,n),r(`mirrored ${e} to the ambient environment`))}e.writeVars(t),r(`mirrored ${l._dotenvAddedKeys.size} keys to the ambient environment`)}static resolveForMirror(e,t){return t}static resolveEffectivePaths(){return this._envPaths.map(e=>this.resolveAgainstBase(e))}static resolveKeyInput(t){let n=Array.isArray(t)?t:[t];if(n.length===0)throw new e(304,`At least one environment key must be provided.`);if(n.some(e=>typeof e!=`string`))throw new e(304,`Environment keys must be strings.`);if(n.some(e=>e.trim()===``))throw new e(304,`Environment keys cannot be empty strings.`);for(let e of n){let t=this.config.get(e);if(t!==void 0)return{key:e,value:t}}return{key:n[0],value:void 0}}static get config(){if(c.size===0){let e=l._source,t={...e.readVars()},n=new Set;if(e.supportsFiles){r(`base dir: ${l._baseDir??`working directory`}`);let i=this.resolveEffectivePaths();r(`effective .env paths: ${i.length===0?`(none)`:i.join(`, `)}`);try{n=o({...this._userDefinedEnvFileOptions,path:i,processEnv:t,readFile:e.readFile.bind(e)})}catch{}}l._dotenvAddedKeys=n;for(let[e,n]of Object.entries(t))c.set(e,n);r(`cache populated: ${c.size} keys total`),l._syncProcessEnv&&this.mirrorToProcessEnv()}return c}static load(){this.config}static useSource(e){l._source=e,n(e),this.refreshCache()}getRaw(e){return l.resolveKeyInput(e).value}};export{c as EnvaptCache,l as EnvapterBase};
|
|
2
|
-
//# sourceMappingURL=EnvapterBase.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"EnvapterBase.mjs","names":[],"sources":["../../../src/core/EnvapterBase.ts"],"sourcesContent":["import { Validator } from '../engine/Validators';\nimport { debugVerbose, getDebugLevel, setDebugLevel } from '../infra/Debug';\nimport { loadDotenv } from '../infra/Dotenv';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\nimport { bindRuntimeFromSource } from '../infra/runtime';\nimport { UnboundEnvSource } from '../sources/UnboundEnvSource';\n\nimport type { DebugLevel } from '../infra/Debug';\nimport type { EnvFileOptions } from '../infra/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] = this.resolveForMirror(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 // The template resolver is defined in PrimitiveMethods, and EnvapterBase can't call it without an\n // import cycle, so the mirror expands ${VAR} through this override.\n protected static resolveForMirror(_key: string, value: string): string {\n /* v8 ignore next -- @preserve overridden by PrimitiveMethods on every concrete class */\n return value;\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 debugVerbose(`base dir: ${EnvapterBase._baseDir ?? 'working directory'}`);\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":"+WAYA,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,CAAS,EADV,CAEtC,CAKA,OAAiB,uBAAuB,EAAa,EAAoD,CACrG,GAAI,CAAC,EAAO,cACR,MAAM,IAAI,EAAA,IAEN,GAAG,EAAI,oFACX,CAER,CAIA,OAAiB,iBA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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,CACtB,EAAa,aAAa,EAAa,UAAY,qBAAqB,EAExE,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,2 +0,0 @@
|
|
|
1
|
-
import{EnvaptError as e}from"../infra/Error.mjs";import{debugWarn as t}from"../infra/Debug.mjs";import{EnvapterBase as n}from"./EnvapterBase.mjs";let r=function(e){return e[e.Development=0]=`Development`,e[e.Staging=1]=`Staging`,e[e.Production=2]=`Production`,e[e.Test=3]=`Test`,e}({});const i=[`ENVIRONMENT`,`ENV`,`NODE_ENV`,`MODE`];function a(e){switch(e.toLowerCase()){case`production`:return 2;case`staging`:return 1;case`test`:return 3;case`development`:return 0;default:return}}var o=class o extends n{static _environment;static _environmentExplicitlySet=!1;static _profiles;static determineEnvironment(e){if(typeof e==`number`){this._environment=e,this._environmentExplicitlySet=!0;return}if(typeof e==`string`){this._environment=a(e)??0,this._environmentExplicitlySet=!0;return}let n=this.firstEnvKeyValue(e=>{let t=this.config.get(e);return typeof t==`string`?t:void 0});if(n===void 0){t(`no environment set (looked for ${i.join(`, `)}); defaulting to development`),this._environment=0;return}let r=a(n);if(r===void 0){t(`unrecognized environment "${n}"; defaulting to development`),this._environment=0;return}this._environment=r}static firstEnvKeyValue(e){for(let t of i){let n=e(t);if(n!==void 0&&n.length>0)return n}}static get environment(){return this._environment===void 0&&this.determineEnvironment(),this._environment}static set environment(e){this.determineEnvironment(e)}get environment(){return o.environment}set environment(e){o.determineEnvironment(e)}static get isProduction(){return this.environment===2}get isProduction(){return o.environment===2}static get isStaging(){return this.environment===1}get isStaging(){return o.environment===1}static get isDevelopment(){return this.environment===0}get isDevelopment(){return o.environment===0}static get isTest(){return this.environment===3}get isTest(){return o.environment===3}static refreshCache(){this._environmentExplicitlySet||(this._environment=void 0),super.refreshCache()}static getCascadeEnvironment(){if(this._environment!==void 0)return this._environment;let e=n._source.readVars(),t=this.firstEnvKeyValue(t=>e[t]);return t===void 0?0:a(t)??0}static buildCascadePaths(e){let t=r[e].toLowerCase();return[`.env.${t}.local`,`.env.${t}`,`.env.local`,`.env`].map(e=>this.resolveAgainstBase(e)).filter(e=>this.sourceFileExists(e))}static normalizeProfilePaths(e){return e?Array.isArray(e.paths)?e.paths:[e.paths]:[]}static resolveEffectivePaths(){if(this._envPathsExplicitlySet)return this._envPaths.map(e=>this.resolveAgainstBase(e));let t=this.getCascadeEnvironment(),n=this._profiles?.[t],r=this.normalizeProfilePaths(n);if(r.length>0){let t=r.filter(e=>!this.sourceFileExists(this.resolveAgainstBase(e)));if(t.length>0)throw new e(303,`Environment file not found at path: ${t.join(`, `)}`)}let i=this._profiles?.useDefaults===!1?[]:this.buildCascadePaths(t);return[...r.map(e=>this.resolveAgainstBase(e)),...i]}};export{r as Environment,o as EnvironmentMethods};
|
|
2
|
-
//# sourceMappingURL=EnvironmentMethods.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"EnvironmentMethods.mjs","names":[],"sources":["../../../src/core/EnvironmentMethods.ts"],"sourcesContent":["import { EnvapterBase } from './EnvapterBase';\nimport { debugWarn } from '../infra/Debug';\nimport { EnvaptError, EnvaptErrorCodes } from '../infra/Error';\n\nimport type { EnvProfile, ProfilesConfig } from '../types';\n\n/**\n * Environment types supported by Envapter\n *\n * The following keys are checked in order until the first with a non-empty value is found, or defaulting to development if none are set:\n * - `ENVIRONMENT`\n * - `ENV`\n * - `NODE_ENV`\n * - `MODE`\n *\n * @public\n */\nexport enum Environment {\n /** The default when no environment variable names a known environment. */\n Development,\n /** Selected when an environment variable reads `staging`. */\n Staging,\n /** Selected when an environment variable reads `production`. */\n Production,\n /** Selected when an environment variable reads `test`. */\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":"kJAiBA,IAAY,EAAL,SAAA,EAAA,OAEH,GAAA,EAAA,YAAA,GAAA,cAEA,EAAA,EAAA,QAAA,GAAA,UAEA,EAAA,EAAA,WAAA,GAAA,aAEA,EAAA,EAAA,KAAA,GAAA,QACJ,EAAA,CAAA,CAAA,EAGA,MAAM,EAAW,CAAC,cAAe,MAAO,WAAY,MAAM,EAE1D,SAAS,EAAiB,EAAsC,CAC5D,OAAQ,EAAI,YAAY,EAAxB,CACI,IAAK,aACD,MAAA,GACJ,IAAK,UACD,MAAA,GACJ,IAAK,OACD,MAAA,GACJ,IAAK,cACD,MAAA,GACJ,QACI,MACR,CACJ,CAMA,IAAa,EAAb,MAAa,UAA2B,CAAa,CACjD,OAAiB,aACjB,OAAiB,0BAA4B,GAC7C,OAAiB,UAEjB,OAAiB,qBAAqB,EAAkC,CACpE,GAAI,OAAO,GAAQ,SAAU,CACzB,KAAK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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,2 +0,0 @@
|
|
|
1
|
-
import{debugWarn as e}from"../infra/Debug.mjs";import{EnvapterBase as t}from"./EnvapterBase.mjs";import{EnvironmentMethods as n}from"./EnvironmentMethods.mjs";import{BuiltInConverters as r}from"../converters/BuiltInConverters.mjs";import{ValueConverter as i}from"../converters/ValueConverter.mjs";import{TemplateResolver as a}from"../engine/TemplateResolver.mjs";var o=class o extends n{static service=new o;static templateResolver=new a(o.service);static valueConverter=new i(o.service);isStrict(){return t.strict}static resolveForMirror(e,t){return this.templateResolver.resolveTemplate(e,t)}static _get(t,n,i){let{key:a,value:o}=this.resolveKeyInput(t);if(this.treatAsMissing(o))return e(i===void 0?`${a} is missing or empty`:`${a} is missing or empty, using fallback ${String(i)}`),i;let s=o,c=this.templateResolver.resolveTemplate(a,String(s)),l;return l=n===1?r.number(c,i):n===2?r.boolean(c,i):n===3?r.bigint(c,i):n===4?r.symbol(c,i):r.string(c,i),l}static get(e,t){return this._get(e,0,t)}get(e,t){return o._get(e,0,t)}static getNumber(e,t){return this._get(e,1,t)}getNumber(e,t){return o._get(e,1,t)}static getBoolean(e,t){return this._get(e,2,t)}getBoolean(e,t){return o._get(e,2,t)}static getBigInt(e,t){return this._get(e,3,t)}getBigInt(e,t){return o._get(e,3,t)}static getSymbol(e,t){return this._get(e,4,t)}getSymbol(e,t){return o._get(e,4,t)}};export{o as PrimitiveMethods};
|
|
2
|
-
//# sourceMappingURL=PrimitiveMethods.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"PrimitiveMethods.mjs","names":[],"sources":["../../../src/core/PrimitiveMethods.ts"],"sourcesContent":["import { BuiltInConverters, ValueConverter } from '../converters';\nimport { EnvapterBase } from './EnvapterBase';\nimport { EnvironmentMethods } from './EnvironmentMethods';\nimport { TemplateResolver } from '../engine/TemplateResolver';\nimport { debugWarn } from '../infra/Debug';\n\nimport type { ConditionalReturn, EnvKeyInput } from '../types';\nimport type { EnvapterService } from '../types/Env';\n\n/**\n * @internal\n */\nenum Primitive {\n String,\n Number,\n Boolean,\n BigInt,\n Symbol\n}\n\n/**\n * @internal\n */\nexport class PrimitiveMethods extends EnvironmentMethods implements EnvapterService {\n private static readonly service = new PrimitiveMethods();\n protected static readonly templateResolver: TemplateResolver = new TemplateResolver(PrimitiveMethods.service);\n protected static readonly valueConverter: ValueConverter = new ValueConverter(PrimitiveMethods.service);\n\n // Read `EnvapterBase.strict` directly: `PrimitiveMethods._strict` would resolve to the\n // BaseClass default because a `Envapter.strict = true` write lands as an own-property\n // on `Envapter`, which is a descendant of `PrimitiveMethods`, not an ancestor.\n isStrict(): boolean {\n return EnvapterBase.strict;\n }\n\n protected static override resolveForMirror(key: string, value: string): string {\n return this.templateResolver.resolveTemplate(key, value);\n }\n\n private static _get<EnvVarReturnType, DefaultType extends EnvVarReturnType | undefined = undefined>(\n key: EnvKeyInput,\n type: Primitive,\n def?: DefaultType\n ): ConditionalReturn<EnvVarReturnType, DefaultType> {\n const { key: resolvedKey, value } = this.resolveKeyInput(key);\n if (this.treatAsMissing(value)) {\n if (def !== undefined) debugWarn(`${resolvedKey} is missing or empty, using fallback ${String(def)}`);\n else debugWarn(`${resolvedKey} is missing or empty`);\n return def as ConditionalReturn<EnvVarReturnType, DefaultType>;\n }\n const rawVal = value as string | number | boolean | undefined;\n\n const parsed = this.templateResolver.resolveTemplate(resolvedKey, String(rawVal));\n\n let result: EnvVarReturnType;\n if (type === Primitive.Number) result = BuiltInConverters.number(parsed, def as number) as EnvVarReturnType;\n else if (type === Primitive.Boolean)\n result = BuiltInConverters.boolean(parsed, def as boolean) as EnvVarReturnType;\n else if (type === Primitive.BigInt)\n result = BuiltInConverters.bigint(parsed, def as bigint) as EnvVarReturnType;\n else if (type === Primitive.Symbol)\n result = BuiltInConverters.symbol(parsed, def as symbol) as EnvVarReturnType;\n else result = BuiltInConverters.string(parsed, def as string) as EnvVarReturnType;\n\n return result;\n }\n\n /**\n * Get a string environment variable with optional fallback.\n * Supports template variable resolution using `${VAR}` syntax.\n * Accepts a single key or an ordered array of keys (first match wins).\n */\n static get<Default extends string | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<string, Default> {\n return this._get(key, Primitive.String, def);\n }\n\n /**\n * @see {@link PrimitiveMethods.get}\n */\n get<Default extends string | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<string, Default> {\n return PrimitiveMethods._get(key, Primitive.String, def);\n }\n\n /**\n * Get a number environment variable with optional fallback.\n * Automatically converts string values to numbers.\n * Accepts a single key or an ordered array of keys (first match wins).\n */\n static getNumber<Default extends number | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<number, Default> {\n return this._get(key, Primitive.Number, def);\n }\n\n /**\n * @see {@link PrimitiveMethods.getNumber}\n */\n getNumber<Default extends number | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<number, Default> {\n return PrimitiveMethods._get(key, Primitive.Number, def);\n }\n\n /**\n * Get a boolean environment variable with optional fallback.\n * Recognizes: `1`, `yes`, `true`, `on` as **true**; `0`, `no`, `false`, `off` as **false** (case-insensitive).\n * Accepts a single key or an ordered array of keys (first match wins).\n */\n static getBoolean<Default extends boolean | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<boolean, Default> {\n return this._get(key, Primitive.Boolean, def);\n }\n\n /**\n * @see {@link PrimitiveMethods.getBoolean}\n */\n getBoolean<Default extends boolean | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<boolean, Default> {\n return PrimitiveMethods._get(key, Primitive.Boolean, def);\n }\n\n /**\n * Get a bigint environment variable with optional fallback.\n * Automatically converts string values to bigint.\n * Accepts a single key or an ordered array of keys (first match wins).\n */\n static getBigInt<Default extends bigint | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<bigint, Default> {\n return this._get(key, Primitive.BigInt, def);\n }\n\n /**\n * @see {@link PrimitiveMethods.getBigInt}\n */\n getBigInt<Default extends bigint | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<bigint, Default> {\n return PrimitiveMethods._get(key, Primitive.BigInt, def);\n }\n\n /**\n * Get a symbol environment variable with optional fallback.\n * Creates a symbol from the string value.\n * Accepts a single key or an ordered array of keys (first match wins).\n */\n static getSymbol<Default extends symbol | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<symbol, Default> {\n return this._get(key, Primitive.Symbol, def);\n }\n\n /**\n * @see {@link PrimitiveMethods.getSymbol}\n */\n getSymbol<Default extends symbol | undefined = undefined>(\n key: EnvKeyInput,\n def?: Default\n ): ConditionalReturn<symbol, Default> {\n return PrimitiveMethods._get(key, Primitive.Symbol, def);\n }\n}\n"],"mappings":"2WAuBA,IAAa,EAAb,MAAa,UAAyB,CAA8C,CAChF,OAAwB,QAAU,IAAI,EACtC,OAA0B,iBAAqC,IAAI,EAAiB,EAAiB,OAAO,EAC5G,OAA0B,eAAiC,IAAI,EAAe,EAAiB,OAAO,EAKtG,UAAoB,CAChB,OAAO,EAAa,MACxB,CAEA,OAA0B,iBAAiB,EAAa,EAAuB,CAC3E,OAAO,KAAK,iBAAiB,gBAAgB,EAAK,CAAK,CAC3D,CAEA,OAAe,KACX,EACA,EACA,EACgD,CAChD,GAAM,CAAE,IAAK,EAAa,SAAU,KAAK,gBAAgB,CAAG,EAC5D,GAAI,KAAK,eAAe,CAAK,EAGzB,OADK,EADD,IAAQ,IAAA,GACG,GAAG,EAAY,sBADG,GAAG,EAAY,uCAAuC,OAAO,CAAG,GAC9C,EAC5C,EAEX,IAAM,EAAS,EAET,EAAS,KAAK,iBAAiB,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