envapt 6.0.0 → 6.0.2
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 +12 -0
- package/README.md +17 -13
- package/dist/browser/StandardSchema.d.mts +1 -1
- package/dist/browser/decorators/Envapt.d.mts +3 -3
- package/dist/browser/decorators/Envapt.mjs.map +1 -1
- package/dist/node/StandardSchema.d.cts +1 -1
- package/dist/node/StandardSchema.d.mts +1 -1
- package/dist/node/decorators/Envapt.cjs.map +1 -1
- package/dist/node/decorators/Envapt.d.cts +3 -3
- package/dist/node/decorators/Envapt.d.mts +3 -3
- package/dist/node/decorators/Envapt.mjs.map +1 -1
- package/dist/workerd/StandardSchema.d.mts +1 -1
- package/dist/workerd/decorators/Envapt.d.mts +3 -3
- package/dist/workerd/decorators/Envapt.mjs.map +1 -1
- package/package.json +6 -5
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# envapt
|
|
2
2
|
|
|
3
|
+
## 6.0.2
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 7a97ce3: Fix the documented static decorator convention. A `@Envapt` (or sugar `@EnvNum`/`@EnvStr`/...) field declared as `declare static readonly` reads `undefined` when the consumer compiles with tsc, because tsc emits the decorator against the prototype where a static read never reaches the getter. Static decorated fields now use a plain `static readonly` (no `declare`), and instance fields keep `declare readonly`. The docstrings, README, and examples ship the corrected forms, and a tsc compile-and-run test guards both forms.
|
|
8
|
+
|
|
9
|
+
## 6.0.1
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 40c3e4b: Reword the package description to lead with typed config from any source rather than .env loading, because that's what envapt is about and the .env cascade is just one feature of the default Node source.
|
|
14
|
+
|
|
3
15
|
## 6.0.0
|
|
4
16
|
|
|
5
17
|
### Major Changes
|
package/README.md
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
<h3>envapt</h3>
|
|
4
4
|
|
|
5
5
|
<p>
|
|
6
|
-
<strong>The apt way to
|
|
7
|
-
Read
|
|
6
|
+
<strong>The apt way to read typed config.</strong><br/>
|
|
7
|
+
Read config from any source as real typed values, with zero runtime dependencies.
|
|
8
8
|
</p>
|
|
9
9
|
|
|
10
10
|
<p>
|
|
@@ -17,9 +17,10 @@
|
|
|
17
17
|
|
|
18
18
|
<br clear="left"/>
|
|
19
19
|
|
|
20
|
-
|
|
21
|
-
fallback that removes `undefined` from the return type.
|
|
22
|
-
|
|
20
|
+
envapt returns config as the type you asked for instead of the `string | undefined` you get raw, with
|
|
21
|
+
a fallback that removes `undefined` from the return type. It reads from whatever source you bind. On
|
|
22
|
+
Node, Bun, and Deno that is `process.env` and your `.env` files, bound on import. On Cloudflare
|
|
23
|
+
Workers, in the browser, or for a secrets object you fetched at boot, you bind the source with
|
|
23
24
|
`Envapter.useSource(...)`.
|
|
24
25
|
|
|
25
26
|
```ts
|
|
@@ -35,14 +36,17 @@ const port = Envapter.getNumber('PORT', 3000); // number, not string | undefined
|
|
|
35
36
|
- **Typed values.** A fallback removes `undefined` from the return type. Built-in converters cover
|
|
36
37
|
numbers, booleans, bigint, JSON, URLs, regular expressions, dates, durations, and arrays, or pass
|
|
37
38
|
your own function or a Standard Schema validator (zod, valibot, arktype).
|
|
38
|
-
- **
|
|
39
|
-
|
|
39
|
+
- **Any source.** A source is any object with a `readVars()` method, so you can bind `process.env`, a
|
|
40
|
+
Cloudflare Workers binding, a browser bundle, or a secrets payload you fetched from a store at boot.
|
|
41
|
+
On Node, Bun, and Deno one binds on import.
|
|
42
|
+
- **Zero runtime dependencies.** The reader, converters, and built-in `.env` parser are self-contained,
|
|
43
|
+
so nothing is added to your dependency tree.
|
|
40
44
|
- **Runs on Node, Bun, Deno, Cloudflare Workers, and the browser.** Node `>=20`, Bun `>=1.3`, Deno
|
|
41
|
-
`>=2.5` (ESM and CJS)
|
|
45
|
+
`>=2.5` (ESM and CJS). The Workers and browser builds resolve through the package `exports`
|
|
42
46
|
conditions.
|
|
43
|
-
- **`.env` loading on Node
|
|
44
|
-
strict / required checks. Off Node there is no filesystem, so you bind
|
|
45
|
-
`Envapter.useSource(...)` and read with the same typed API.
|
|
47
|
+
- **`.env` loading built in on Node.** The default Node source adds a per-environment file cascade,
|
|
48
|
+
`${VAR}` templates, and strict / required checks. Off Node there is no filesystem, so you bind
|
|
49
|
+
another source with `Envapter.useSource(...)` and read with the same typed API.
|
|
46
50
|
|
|
47
51
|
## Install
|
|
48
52
|
|
|
@@ -62,7 +66,7 @@ Both share the same parsing, converters, and cache.
|
|
|
62
66
|
### Functional
|
|
63
67
|
|
|
64
68
|
Read a value from any call site, in JavaScript or TypeScript. No build step. On Node the source is
|
|
65
|
-
bound for you
|
|
69
|
+
bound for you. On Workers and in the browser, call `Envapter.useSource(...)` first.
|
|
66
70
|
|
|
67
71
|
```ts
|
|
68
72
|
import { Envapter, Converters } from 'envapt';
|
|
@@ -92,7 +96,7 @@ import { Envapt, Converters } from 'envapt';
|
|
|
92
96
|
|
|
93
97
|
class Config {
|
|
94
98
|
@Envapt('PORT', { converter: Converters.Number, fallback: 3000 })
|
|
95
|
-
|
|
99
|
+
static readonly port: number;
|
|
96
100
|
}
|
|
97
101
|
```
|
|
98
102
|
|
|
@@ -44,7 +44,7 @@ declare namespace StandardSchemaV1 {
|
|
|
44
44
|
}
|
|
45
45
|
/**
|
|
46
46
|
* Envapt-side alias for {@link StandardSchemaV1.InferOutput}. Re-exported under a friendlier
|
|
47
|
-
* name so consumers writing `
|
|
47
|
+
* name so consumers writing `static readonly x: InferSchemaOutput<typeof mySchema>`
|
|
48
48
|
* don't need the namespace path.
|
|
49
49
|
* @public
|
|
50
50
|
*/
|
|
@@ -62,7 +62,7 @@ declare function Envapt<TFallback>(key: EnvKeyInput, options: {
|
|
|
62
62
|
* converter: (raw) => Buffer.from(raw ?? '', 'base64'),
|
|
63
63
|
* required: true
|
|
64
64
|
* })
|
|
65
|
-
*
|
|
65
|
+
* static readonly jwtSecret: Buffer;
|
|
66
66
|
* }
|
|
67
67
|
* ```
|
|
68
68
|
*/
|
|
@@ -114,7 +114,7 @@ declare function Envapt<TReturnType>(key: EnvKeyInput, options: {
|
|
|
114
114
|
* static readonly allowedOrigins: string[];
|
|
115
115
|
*
|
|
116
116
|
* \@Envapt('DATABASE_URL', { converter: Converters.Url, required: true })
|
|
117
|
-
*
|
|
117
|
+
* static readonly databaseUrl: URL;
|
|
118
118
|
* }
|
|
119
119
|
* ```
|
|
120
120
|
*/
|
|
@@ -165,7 +165,7 @@ declare function Envapt<TConstructor extends PrimitiveConstructor>(key: EnvKeyIn
|
|
|
165
165
|
* ```ts
|
|
166
166
|
* class Config extends Envapter {
|
|
167
167
|
* \@Envapt('API_KEY', { required: true })
|
|
168
|
-
*
|
|
168
|
+
* static readonly apiKey: string;
|
|
169
169
|
* }
|
|
170
170
|
* ```
|
|
171
171
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Envapt.mjs","names":[],"sources":["../../../src/decorators/Envapt.ts"],"sourcesContent":["import { createPropertyDecorator } from './createPropertyDecorator';\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\nimport { Validator } from '../Validators';\n\nimport type { ArrayOf } from '../converters';\nimport type { InferSchemaOutput, StandardSchemaV1 } from '../StandardSchema';\nimport type {\n BuiltInConverter,\n ConverterFunction,\n EnvKeyInput,\n EnvaptConverter,\n InferConverterFallbackType,\n InferPrimitiveReturnType,\n PrimitiveConstructor,\n SchemaConstraint\n} from '../types';\n\n/**\n * Usage 1: Either a custom converter function + fallback (both required), OR a fallback\n * only (no converter).\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * // Custom converter that validates a non-empty API key\n * \\@Envapt('API_KEY', {\n * fallback: 'default-key',\n * converter(raw, _fallback) {\n * if (!raw || raw.trim() === '') throw new Error('API_KEY required');\n * return raw.trim();\n * }\n * })\n * static readonly apiKey: string;\n *\n * // Fallback-only (no converter): string fallback\n * \\@Envapt('LOG_FILE', { fallback: '/var/log/app.log' })\n * static readonly logFile: string;\n *\n * // Fallback-only: arbitrary object fallback\n * \\@Envapt('RETRY_POLICY', { fallback: { retries: 3, backoff: 'exponential' } })\n * static readonly retryPolicy: unknown;\n * }\n * ```\n */\nexport function Envapt<TFallback>(\n key: EnvKeyInput,\n options:\n | { converter: (raw: string | undefined, fallback: TFallback) => TFallback; fallback: TFallback }\n | { fallback: TFallback; converter?: undefined }\n): PropertyDecorator;\n\n/**\n * Usage 2: Custom converter function without fallback. Either omit `required` (returns the\n * converter's output, possibly `undefined`) or pass `required: true` to throw `MissingEnvValue`\n * on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with custom converter only, with optional `required: true`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('FEATURE_FLAGS', { converter(raw) {\n * return raw ? raw.split('|').map(s => s.trim()) : [];\n * } })\n * static readonly featureFlags: string[];\n *\n * \\@Envapt('JWT_SECRET', {\n * converter: (raw) => Buffer.from(raw ?? '', 'base64'),\n * required: true\n * })\n * declare static readonly jwtSecret: Buffer;\n * }\n * ```\n */\nexport function Envapt<TReturnType>(\n key: EnvKeyInput,\n options:\n | { converter: ConverterFunction<TReturnType>; required?: false }\n | { converter: ConverterFunction<TReturnType>; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 3: Built-in or array converter with optional fallback OR `required: true`.\n *\n * `InferConverterFallbackType` handles asymmetric cases: scalar `Converters.Time` accepts\n * `TimeFallback`, and `ArrayOf<'time'>` accepts `TimeFallback[]`. Every other converter\n * reduces to `InferConverterReturnType`. The two object-shape branches are mutually\n * exclusive: either provide a `fallback`, or pass `required: true` to throw\n * `MissingEnvValue` on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * import { Converters } from 'envapt';\n *\n * class Config extends Envapter {\n * // Use built-in Number converter with a numeric fallback\n * \\@Envapt('APP_PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * // Url converter: the fallback is a URL instance, not a string\n * \\@Envapt('APP_URL', { converter: Converters.Url, fallback: new URL('http://localhost:3000') })\n * static readonly url: URL;\n *\n * // Prefer CANARY_URL when present, otherwise fall back to APP_URL\n * \\@Envapt(['CANARY_URL', 'APP_URL'], { converter: Converters.Url })\n * static readonly canaryUrl: URL | null;\n *\n * // `Converters.Time` accepts either a number (milliseconds) or a time-string fallback (`<number><unit>`).\n * \\@Envapt('REQUEST_TIMEOUT', { converter: Converters.Time, fallback: '10s' })\n * static readonly requestTimeout: number;\n *\n * // Array converter: comma-separated list of origins -> string[]\n * \\@Envapt('ALLOWED_ORIGINS', {\n * converter: Converters.array({ of: Converters.String }),\n * fallback: ['https://example.com']\n * })\n * static readonly allowedOrigins: string[];\n *\n * \\@Envapt('DATABASE_URL', { converter: Converters.Url, required: true })\n * declare static readonly databaseUrl: URL;\n * }\n * ```\n */\nexport function Envapt<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options:\n | { converter: TConverter; fallback?: InferConverterFallbackType<TConverter> | undefined; required?: false }\n | { converter: TConverter; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 4: Primitive constructor with optional fallback\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with primitive constructor\n * @public\n * @example\n * ```ts\n * // Use primitive constructors to coerce values\n * class Config extends Envapter {\n * \\@Envapt('MAX_CONNECTIONS', { converter: Number, fallback: 100 })\n * static readonly maxConnections: number;\n *\n * \\@Envapt('FEATURE_ENABLED', { converter: Boolean, fallback: false })\n * static readonly featureEnabled: boolean;\n * }\n * ```\n */\nexport function Envapt<TConstructor extends PrimitiveConstructor>(\n key: EnvKeyInput,\n options:\n | { converter: TConstructor; fallback?: InferPrimitiveReturnType<TConstructor>; required?: false }\n | { converter: TConstructor; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 5: Required, no converter (raw string). Throws `MissingEnvValue` on first access if\n * the env value is missing or empty (post-trim). Independent of global `Envapter.strict`.\n * Combining `required: true` with `fallback` fails to match any overload at compile time;\n * the runtime Validator catches dynamic objects that bypass the types.\n *\n * @param key - Environment variable name(s) to load\n * @param options - `{ required: true }`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('API_KEY', { required: true })\n * declare static readonly apiKey: string;\n * }\n * ```\n */\nexport function Envapt(key: EnvKeyInput, options: { required: true }): PropertyDecorator;\n\n/**\n * No-fallback form. The property resolves from env or `null`.\n *\n * @param key - Environment variable name(s) to load\n * @public\n * @example\n * ```ts\n * // Classic API: no fallback — property will resolve from env or be null\n * class Config extends Envapter {\n * \\@Envapt('SIMPLE_VALUE')\n * static readonly simple?: string | null;\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function Envapt<_TReturnType = string | null>(key: EnvKeyInput): PropertyDecorator;\n\n/**\n * Usage 6: Standard Schema v1 adapter (zod, valibot, arktype, hand-rolled). Synchronous\n * schemas only; a Promise-returning `validate` triggers a runtime\n * `InvalidUserDefinedConfig` throw. Combining `schema` with `converter` fails to match any\n * overload at compile time; the runtime Validator catches dynamic objects that bypass the\n * types.\n * @public\n */\nexport function Envapt<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n options:\n | { schema: SchemaConstraint<Schema>; fallback?: InferSchemaOutput<Schema>; required?: false }\n | { schema: SchemaConstraint<Schema>; required: true }\n): PropertyDecorator;\n\n/**\n * Instance/Static Property decorator that automatically loads and converts environment variables.\n */\nexport function Envapt<TFallback = unknown>(key: EnvKeyInput, options?: unknown): PropertyDecorator {\n let fallback: TFallback | undefined;\n let actualConverter: EnvaptConverter<TFallback> | undefined;\n let actualSchema: StandardSchemaV1 | undefined;\n let hasFallback = false;\n let required = false;\n\n if (options !== undefined) {\n if (\n typeof options !== 'object' ||\n options === null ||\n !('fallback' in options || 'converter' in options || 'required' in options || 'schema' in options)\n ) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n 'The positional `@Envapt(key, fallback, converter)` form was removed in v6. Pass an options object instead, like `@Envapt(key, { converter, fallback })`, or use one of the sugar decorators.'\n );\n }\n\n const opts = options as {\n fallback?: TFallback;\n converter?: EnvaptConverter<TFallback>;\n required?: boolean;\n schema?: unknown;\n };\n fallback = opts.fallback;\n actualConverter = opts.converter;\n hasFallback = 'fallback' in opts;\n required = opts.required === true;\n\n if (required && hasFallback && fallback !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`required: true` and `fallback` are mutually exclusive on @Envapt options. Drop the fallback or call `Envapter.require()` separately.'\n );\n }\n\n if ('schema' in opts && opts.schema !== undefined) {\n if (!Validator.isStandardSchema(opts.schema)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` must be a Standard Schema v1 object (zod, valibot, arktype, or any `~standard`-conformant value).'\n );\n }\n if (actualConverter !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` and `converter` are mutually exclusive on @Envapt options. Drop one as they both turn a raw env string into a typed value.'\n );\n }\n actualSchema = opts.schema;\n }\n }\n\n return createPropertyDecorator(key, {\n fallback,\n converter: actualConverter,\n hasFallback,\n required,\n schema: actualSchema\n });\n}\n"],"mappings":"iKAwNA,SAAgB,EAA4B,EAAkB,EAAsC,CAChG,IAAI,EACA,EACA,EACA,EAAc,GACd,EAAW,GAEf,GAAI,IAAY,IAAA,GAAW,CACvB,GACI,OAAO,GAAY,WACnB,GACA,EAAE,aAAc,GAAW,cAAe,GAAW,aAAc,GAAW,WAAY,GAE1F,MAAM,IAAI,EAAA,IAEN,8LACJ,EAGJ,IAAM,EAAO,EAWb,GALA,EAAW,EAAK,SAChB,EAAkB,EAAK,UACvB,EAAc,aAAc,EAC5B,EAAW,EAAK,WAAa,GAEzB,GAAY,GAAe,IAAa,IAAA,GACxC,MAAM,IAAI,EAAA,IAEN,uIACJ,EAGJ,GAAI,WAAY,GAAQ,EAAK,SAAW,IAAA,GAAW,CAC/C,GAAI,CAAC,EAAU,iBAAiB,EAAK,MAAM,EACvC,MAAM,IAAI,EAAA,IAEN,4GACJ,EAEJ,GAAI,IAAoB,IAAA,GACpB,MAAM,IAAI,EAAA,IAEN,qIACJ,EAEJ,EAAe,EAAK,MACxB,CACJ,CAEA,OAAO,EAAwB,EAAK,CAChC,WACA,UAAW,EACX,cACA,WACA,OAAQ,CACZ,CAAC,CACL"}
|
|
1
|
+
{"version":3,"file":"Envapt.mjs","names":[],"sources":["../../../src/decorators/Envapt.ts"],"sourcesContent":["import { createPropertyDecorator } from './createPropertyDecorator';\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\nimport { Validator } from '../Validators';\n\nimport type { ArrayOf } from '../converters';\nimport type { InferSchemaOutput, StandardSchemaV1 } from '../StandardSchema';\nimport type {\n BuiltInConverter,\n ConverterFunction,\n EnvKeyInput,\n EnvaptConverter,\n InferConverterFallbackType,\n InferPrimitiveReturnType,\n PrimitiveConstructor,\n SchemaConstraint\n} from '../types';\n\n/**\n * Usage 1: Either a custom converter function + fallback (both required), OR a fallback\n * only (no converter).\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * // Custom converter that validates a non-empty API key\n * \\@Envapt('API_KEY', {\n * fallback: 'default-key',\n * converter(raw, _fallback) {\n * if (!raw || raw.trim() === '') throw new Error('API_KEY required');\n * return raw.trim();\n * }\n * })\n * static readonly apiKey: string;\n *\n * // Fallback-only (no converter): string fallback\n * \\@Envapt('LOG_FILE', { fallback: '/var/log/app.log' })\n * static readonly logFile: string;\n *\n * // Fallback-only: arbitrary object fallback\n * \\@Envapt('RETRY_POLICY', { fallback: { retries: 3, backoff: 'exponential' } })\n * static readonly retryPolicy: unknown;\n * }\n * ```\n */\nexport function Envapt<TFallback>(\n key: EnvKeyInput,\n options:\n | { converter: (raw: string | undefined, fallback: TFallback) => TFallback; fallback: TFallback }\n | { fallback: TFallback; converter?: undefined }\n): PropertyDecorator;\n\n/**\n * Usage 2: Custom converter function without fallback. Either omit `required` (returns the\n * converter's output, possibly `undefined`) or pass `required: true` to throw `MissingEnvValue`\n * on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with custom converter only, with optional `required: true`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('FEATURE_FLAGS', { converter(raw) {\n * return raw ? raw.split('|').map(s => s.trim()) : [];\n * } })\n * static readonly featureFlags: string[];\n *\n * \\@Envapt('JWT_SECRET', {\n * converter: (raw) => Buffer.from(raw ?? '', 'base64'),\n * required: true\n * })\n * static readonly jwtSecret: Buffer;\n * }\n * ```\n */\nexport function Envapt<TReturnType>(\n key: EnvKeyInput,\n options:\n | { converter: ConverterFunction<TReturnType>; required?: false }\n | { converter: ConverterFunction<TReturnType>; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 3: Built-in or array converter with optional fallback OR `required: true`.\n *\n * `InferConverterFallbackType` handles asymmetric cases: scalar `Converters.Time` accepts\n * `TimeFallback`, and `ArrayOf<'time'>` accepts `TimeFallback[]`. Every other converter\n * reduces to `InferConverterReturnType`. The two object-shape branches are mutually\n * exclusive: either provide a `fallback`, or pass `required: true` to throw\n * `MissingEnvValue` on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * import { Converters } from 'envapt';\n *\n * class Config extends Envapter {\n * // Use built-in Number converter with a numeric fallback\n * \\@Envapt('APP_PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * // Url converter: the fallback is a URL instance, not a string\n * \\@Envapt('APP_URL', { converter: Converters.Url, fallback: new URL('http://localhost:3000') })\n * static readonly url: URL;\n *\n * // Prefer CANARY_URL when present, otherwise fall back to APP_URL\n * \\@Envapt(['CANARY_URL', 'APP_URL'], { converter: Converters.Url })\n * static readonly canaryUrl: URL | null;\n *\n * // `Converters.Time` accepts either a number (milliseconds) or a time-string fallback (`<number><unit>`).\n * \\@Envapt('REQUEST_TIMEOUT', { converter: Converters.Time, fallback: '10s' })\n * static readonly requestTimeout: number;\n *\n * // Array converter: comma-separated list of origins -> string[]\n * \\@Envapt('ALLOWED_ORIGINS', {\n * converter: Converters.array({ of: Converters.String }),\n * fallback: ['https://example.com']\n * })\n * static readonly allowedOrigins: string[];\n *\n * \\@Envapt('DATABASE_URL', { converter: Converters.Url, required: true })\n * static readonly databaseUrl: URL;\n * }\n * ```\n */\nexport function Envapt<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options:\n | { converter: TConverter; fallback?: InferConverterFallbackType<TConverter> | undefined; required?: false }\n | { converter: TConverter; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 4: Primitive constructor with optional fallback\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with primitive constructor\n * @public\n * @example\n * ```ts\n * // Use primitive constructors to coerce values\n * class Config extends Envapter {\n * \\@Envapt('MAX_CONNECTIONS', { converter: Number, fallback: 100 })\n * static readonly maxConnections: number;\n *\n * \\@Envapt('FEATURE_ENABLED', { converter: Boolean, fallback: false })\n * static readonly featureEnabled: boolean;\n * }\n * ```\n */\nexport function Envapt<TConstructor extends PrimitiveConstructor>(\n key: EnvKeyInput,\n options:\n | { converter: TConstructor; fallback?: InferPrimitiveReturnType<TConstructor>; required?: false }\n | { converter: TConstructor; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 5: Required, no converter (raw string). Throws `MissingEnvValue` on first access if\n * the env value is missing or empty (post-trim). Independent of global `Envapter.strict`.\n * Combining `required: true` with `fallback` fails to match any overload at compile time;\n * the runtime Validator catches dynamic objects that bypass the types.\n *\n * @param key - Environment variable name(s) to load\n * @param options - `{ required: true }`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('API_KEY', { required: true })\n * static readonly apiKey: string;\n * }\n * ```\n */\nexport function Envapt(key: EnvKeyInput, options: { required: true }): PropertyDecorator;\n\n/**\n * No-fallback form. The property resolves from env or `null`.\n *\n * @param key - Environment variable name(s) to load\n * @public\n * @example\n * ```ts\n * // Classic API: no fallback — property will resolve from env or be null\n * class Config extends Envapter {\n * \\@Envapt('SIMPLE_VALUE')\n * static readonly simple?: string | null;\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function Envapt<_TReturnType = string | null>(key: EnvKeyInput): PropertyDecorator;\n\n/**\n * Usage 6: Standard Schema v1 adapter (zod, valibot, arktype, hand-rolled). Synchronous\n * schemas only; a Promise-returning `validate` triggers a runtime\n * `InvalidUserDefinedConfig` throw. Combining `schema` with `converter` fails to match any\n * overload at compile time; the runtime Validator catches dynamic objects that bypass the\n * types.\n * @public\n */\nexport function Envapt<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n options:\n | { schema: SchemaConstraint<Schema>; fallback?: InferSchemaOutput<Schema>; required?: false }\n | { schema: SchemaConstraint<Schema>; required: true }\n): PropertyDecorator;\n\n/**\n * Instance/Static Property decorator that automatically loads and converts environment variables.\n */\nexport function Envapt<TFallback = unknown>(key: EnvKeyInput, options?: unknown): PropertyDecorator {\n let fallback: TFallback | undefined;\n let actualConverter: EnvaptConverter<TFallback> | undefined;\n let actualSchema: StandardSchemaV1 | undefined;\n let hasFallback = false;\n let required = false;\n\n if (options !== undefined) {\n if (\n typeof options !== 'object' ||\n options === null ||\n !('fallback' in options || 'converter' in options || 'required' in options || 'schema' in options)\n ) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n 'The positional `@Envapt(key, fallback, converter)` form was removed in v6. Pass an options object instead, like `@Envapt(key, { converter, fallback })`, or use one of the sugar decorators.'\n );\n }\n\n const opts = options as {\n fallback?: TFallback;\n converter?: EnvaptConverter<TFallback>;\n required?: boolean;\n schema?: unknown;\n };\n fallback = opts.fallback;\n actualConverter = opts.converter;\n hasFallback = 'fallback' in opts;\n required = opts.required === true;\n\n if (required && hasFallback && fallback !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`required: true` and `fallback` are mutually exclusive on @Envapt options. Drop the fallback or call `Envapter.require()` separately.'\n );\n }\n\n if ('schema' in opts && opts.schema !== undefined) {\n if (!Validator.isStandardSchema(opts.schema)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` must be a Standard Schema v1 object (zod, valibot, arktype, or any `~standard`-conformant value).'\n );\n }\n if (actualConverter !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` and `converter` are mutually exclusive on @Envapt options. Drop one as they both turn a raw env string into a typed value.'\n );\n }\n actualSchema = opts.schema;\n }\n }\n\n return createPropertyDecorator(key, {\n fallback,\n converter: actualConverter,\n hasFallback,\n required,\n schema: actualSchema\n });\n}\n"],"mappings":"iKAwNA,SAAgB,EAA4B,EAAkB,EAAsC,CAChG,IAAI,EACA,EACA,EACA,EAAc,GACd,EAAW,GAEf,GAAI,IAAY,IAAA,GAAW,CACvB,GACI,OAAO,GAAY,WACnB,GACA,EAAE,aAAc,GAAW,cAAe,GAAW,aAAc,GAAW,WAAY,GAE1F,MAAM,IAAI,EAAA,IAEN,8LACJ,EAGJ,IAAM,EAAO,EAWb,GALA,EAAW,EAAK,SAChB,EAAkB,EAAK,UACvB,EAAc,aAAc,EAC5B,EAAW,EAAK,WAAa,GAEzB,GAAY,GAAe,IAAa,IAAA,GACxC,MAAM,IAAI,EAAA,IAEN,uIACJ,EAGJ,GAAI,WAAY,GAAQ,EAAK,SAAW,IAAA,GAAW,CAC/C,GAAI,CAAC,EAAU,iBAAiB,EAAK,MAAM,EACvC,MAAM,IAAI,EAAA,IAEN,4GACJ,EAEJ,GAAI,IAAoB,IAAA,GACpB,MAAM,IAAI,EAAA,IAEN,qIACJ,EAEJ,EAAe,EAAK,MACxB,CACJ,CAEA,OAAO,EAAwB,EAAK,CAChC,WACA,UAAW,EACX,cACA,WACA,OAAQ,CACZ,CAAC,CACL"}
|
|
@@ -44,7 +44,7 @@ declare namespace StandardSchemaV1 {
|
|
|
44
44
|
}
|
|
45
45
|
/**
|
|
46
46
|
* Envapt-side alias for {@link StandardSchemaV1.InferOutput}. Re-exported under a friendlier
|
|
47
|
-
* name so consumers writing `
|
|
47
|
+
* name so consumers writing `static readonly x: InferSchemaOutput<typeof mySchema>`
|
|
48
48
|
* don't need the namespace path.
|
|
49
49
|
* @public
|
|
50
50
|
*/
|
|
@@ -46,7 +46,7 @@ declare namespace StandardSchemaV1 {
|
|
|
46
46
|
}
|
|
47
47
|
/**
|
|
48
48
|
* Envapt-side alias for {@link StandardSchemaV1.InferOutput}. Re-exported under a friendlier
|
|
49
|
-
* name so consumers writing `
|
|
49
|
+
* name so consumers writing `static readonly x: InferSchemaOutput<typeof mySchema>`
|
|
50
50
|
* don't need the namespace path.
|
|
51
51
|
* @public
|
|
52
52
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Envapt.cjs","names":["EnvaptError","Validator","createPropertyDecorator"],"sources":["../../../src/decorators/Envapt.ts"],"sourcesContent":["import { createPropertyDecorator } from './createPropertyDecorator';\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\nimport { Validator } from '../Validators';\n\nimport type { ArrayOf } from '../converters';\nimport type { InferSchemaOutput, StandardSchemaV1 } from '../StandardSchema';\nimport type {\n BuiltInConverter,\n ConverterFunction,\n EnvKeyInput,\n EnvaptConverter,\n InferConverterFallbackType,\n InferPrimitiveReturnType,\n PrimitiveConstructor,\n SchemaConstraint\n} from '../types';\n\n/**\n * Usage 1: Either a custom converter function + fallback (both required), OR a fallback\n * only (no converter).\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * // Custom converter that validates a non-empty API key\n * \\@Envapt('API_KEY', {\n * fallback: 'default-key',\n * converter(raw, _fallback) {\n * if (!raw || raw.trim() === '') throw new Error('API_KEY required');\n * return raw.trim();\n * }\n * })\n * static readonly apiKey: string;\n *\n * // Fallback-only (no converter): string fallback\n * \\@Envapt('LOG_FILE', { fallback: '/var/log/app.log' })\n * static readonly logFile: string;\n *\n * // Fallback-only: arbitrary object fallback\n * \\@Envapt('RETRY_POLICY', { fallback: { retries: 3, backoff: 'exponential' } })\n * static readonly retryPolicy: unknown;\n * }\n * ```\n */\nexport function Envapt<TFallback>(\n key: EnvKeyInput,\n options:\n | { converter: (raw: string | undefined, fallback: TFallback) => TFallback; fallback: TFallback }\n | { fallback: TFallback; converter?: undefined }\n): PropertyDecorator;\n\n/**\n * Usage 2: Custom converter function without fallback. Either omit `required` (returns the\n * converter's output, possibly `undefined`) or pass `required: true` to throw `MissingEnvValue`\n * on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with custom converter only, with optional `required: true`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('FEATURE_FLAGS', { converter(raw) {\n * return raw ? raw.split('|').map(s => s.trim()) : [];\n * } })\n * static readonly featureFlags: string[];\n *\n * \\@Envapt('JWT_SECRET', {\n * converter: (raw) => Buffer.from(raw ?? '', 'base64'),\n * required: true\n * })\n * declare static readonly jwtSecret: Buffer;\n * }\n * ```\n */\nexport function Envapt<TReturnType>(\n key: EnvKeyInput,\n options:\n | { converter: ConverterFunction<TReturnType>; required?: false }\n | { converter: ConverterFunction<TReturnType>; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 3: Built-in or array converter with optional fallback OR `required: true`.\n *\n * `InferConverterFallbackType` handles asymmetric cases: scalar `Converters.Time` accepts\n * `TimeFallback`, and `ArrayOf<'time'>` accepts `TimeFallback[]`. Every other converter\n * reduces to `InferConverterReturnType`. The two object-shape branches are mutually\n * exclusive: either provide a `fallback`, or pass `required: true` to throw\n * `MissingEnvValue` on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * import { Converters } from 'envapt';\n *\n * class Config extends Envapter {\n * // Use built-in Number converter with a numeric fallback\n * \\@Envapt('APP_PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * // Url converter: the fallback is a URL instance, not a string\n * \\@Envapt('APP_URL', { converter: Converters.Url, fallback: new URL('http://localhost:3000') })\n * static readonly url: URL;\n *\n * // Prefer CANARY_URL when present, otherwise fall back to APP_URL\n * \\@Envapt(['CANARY_URL', 'APP_URL'], { converter: Converters.Url })\n * static readonly canaryUrl: URL | null;\n *\n * // `Converters.Time` accepts either a number (milliseconds) or a time-string fallback (`<number><unit>`).\n * \\@Envapt('REQUEST_TIMEOUT', { converter: Converters.Time, fallback: '10s' })\n * static readonly requestTimeout: number;\n *\n * // Array converter: comma-separated list of origins -> string[]\n * \\@Envapt('ALLOWED_ORIGINS', {\n * converter: Converters.array({ of: Converters.String }),\n * fallback: ['https://example.com']\n * })\n * static readonly allowedOrigins: string[];\n *\n * \\@Envapt('DATABASE_URL', { converter: Converters.Url, required: true })\n * declare static readonly databaseUrl: URL;\n * }\n * ```\n */\nexport function Envapt<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options:\n | { converter: TConverter; fallback?: InferConverterFallbackType<TConverter> | undefined; required?: false }\n | { converter: TConverter; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 4: Primitive constructor with optional fallback\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with primitive constructor\n * @public\n * @example\n * ```ts\n * // Use primitive constructors to coerce values\n * class Config extends Envapter {\n * \\@Envapt('MAX_CONNECTIONS', { converter: Number, fallback: 100 })\n * static readonly maxConnections: number;\n *\n * \\@Envapt('FEATURE_ENABLED', { converter: Boolean, fallback: false })\n * static readonly featureEnabled: boolean;\n * }\n * ```\n */\nexport function Envapt<TConstructor extends PrimitiveConstructor>(\n key: EnvKeyInput,\n options:\n | { converter: TConstructor; fallback?: InferPrimitiveReturnType<TConstructor>; required?: false }\n | { converter: TConstructor; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 5: Required, no converter (raw string). Throws `MissingEnvValue` on first access if\n * the env value is missing or empty (post-trim). Independent of global `Envapter.strict`.\n * Combining `required: true` with `fallback` fails to match any overload at compile time;\n * the runtime Validator catches dynamic objects that bypass the types.\n *\n * @param key - Environment variable name(s) to load\n * @param options - `{ required: true }`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('API_KEY', { required: true })\n * declare static readonly apiKey: string;\n * }\n * ```\n */\nexport function Envapt(key: EnvKeyInput, options: { required: true }): PropertyDecorator;\n\n/**\n * No-fallback form. The property resolves from env or `null`.\n *\n * @param key - Environment variable name(s) to load\n * @public\n * @example\n * ```ts\n * // Classic API: no fallback — property will resolve from env or be null\n * class Config extends Envapter {\n * \\@Envapt('SIMPLE_VALUE')\n * static readonly simple?: string | null;\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function Envapt<_TReturnType = string | null>(key: EnvKeyInput): PropertyDecorator;\n\n/**\n * Usage 6: Standard Schema v1 adapter (zod, valibot, arktype, hand-rolled). Synchronous\n * schemas only; a Promise-returning `validate` triggers a runtime\n * `InvalidUserDefinedConfig` throw. Combining `schema` with `converter` fails to match any\n * overload at compile time; the runtime Validator catches dynamic objects that bypass the\n * types.\n * @public\n */\nexport function Envapt<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n options:\n | { schema: SchemaConstraint<Schema>; fallback?: InferSchemaOutput<Schema>; required?: false }\n | { schema: SchemaConstraint<Schema>; required: true }\n): PropertyDecorator;\n\n/**\n * Instance/Static Property decorator that automatically loads and converts environment variables.\n */\nexport function Envapt<TFallback = unknown>(key: EnvKeyInput, options?: unknown): PropertyDecorator {\n let fallback: TFallback | undefined;\n let actualConverter: EnvaptConverter<TFallback> | undefined;\n let actualSchema: StandardSchemaV1 | undefined;\n let hasFallback = false;\n let required = false;\n\n if (options !== undefined) {\n if (\n typeof options !== 'object' ||\n options === null ||\n !('fallback' in options || 'converter' in options || 'required' in options || 'schema' in options)\n ) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n 'The positional `@Envapt(key, fallback, converter)` form was removed in v6. Pass an options object instead, like `@Envapt(key, { converter, fallback })`, or use one of the sugar decorators.'\n );\n }\n\n const opts = options as {\n fallback?: TFallback;\n converter?: EnvaptConverter<TFallback>;\n required?: boolean;\n schema?: unknown;\n };\n fallback = opts.fallback;\n actualConverter = opts.converter;\n hasFallback = 'fallback' in opts;\n required = opts.required === true;\n\n if (required && hasFallback && fallback !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`required: true` and `fallback` are mutually exclusive on @Envapt options. Drop the fallback or call `Envapter.require()` separately.'\n );\n }\n\n if ('schema' in opts && opts.schema !== undefined) {\n if (!Validator.isStandardSchema(opts.schema)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` must be a Standard Schema v1 object (zod, valibot, arktype, or any `~standard`-conformant value).'\n );\n }\n if (actualConverter !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` and `converter` are mutually exclusive on @Envapt options. Drop one as they both turn a raw env string into a typed value.'\n );\n }\n actualSchema = opts.schema;\n }\n }\n\n return createPropertyDecorator(key, {\n fallback,\n converter: actualConverter,\n hasFallback,\n required,\n schema: actualSchema\n });\n}\n"],"mappings":"6JAwNA,SAAgB,EAA4B,EAAkB,EAAsC,CAChG,IAAI,EACA,EACA,EACA,EAAc,GACd,EAAW,GAEf,GAAI,IAAY,IAAA,GAAW,CACvB,GACI,OAAO,GAAY,WACnB,GACA,EAAE,aAAc,GAAW,cAAe,GAAW,aAAc,GAAW,WAAY,GAE1F,MAAM,IAAIA,EAAAA,YAAAA,IAEN,8LACJ,EAGJ,IAAM,EAAO,EAWb,GALA,EAAW,EAAK,SAChB,EAAkB,EAAK,UACvB,EAAc,aAAc,EAC5B,EAAW,EAAK,WAAa,GAEzB,GAAY,GAAe,IAAa,IAAA,GACxC,MAAM,IAAIA,EAAAA,YAAAA,IAEN,uIACJ,EAGJ,GAAI,WAAY,GAAQ,EAAK,SAAW,IAAA,GAAW,CAC/C,GAAI,CAACC,EAAAA,UAAU,iBAAiB,EAAK,MAAM,EACvC,MAAM,IAAID,EAAAA,YAAAA,IAEN,4GACJ,EAEJ,GAAI,IAAoB,IAAA,GACpB,MAAM,IAAIA,EAAAA,YAAAA,IAEN,qIACJ,EAEJ,EAAe,EAAK,MACxB,CACJ,CAEA,OAAOE,EAAAA,wBAAwB,EAAK,CAChC,WACA,UAAW,EACX,cACA,WACA,OAAQ,CACZ,CAAC,CACL"}
|
|
1
|
+
{"version":3,"file":"Envapt.cjs","names":["EnvaptError","Validator","createPropertyDecorator"],"sources":["../../../src/decorators/Envapt.ts"],"sourcesContent":["import { createPropertyDecorator } from './createPropertyDecorator';\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\nimport { Validator } from '../Validators';\n\nimport type { ArrayOf } from '../converters';\nimport type { InferSchemaOutput, StandardSchemaV1 } from '../StandardSchema';\nimport type {\n BuiltInConverter,\n ConverterFunction,\n EnvKeyInput,\n EnvaptConverter,\n InferConverterFallbackType,\n InferPrimitiveReturnType,\n PrimitiveConstructor,\n SchemaConstraint\n} from '../types';\n\n/**\n * Usage 1: Either a custom converter function + fallback (both required), OR a fallback\n * only (no converter).\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * // Custom converter that validates a non-empty API key\n * \\@Envapt('API_KEY', {\n * fallback: 'default-key',\n * converter(raw, _fallback) {\n * if (!raw || raw.trim() === '') throw new Error('API_KEY required');\n * return raw.trim();\n * }\n * })\n * static readonly apiKey: string;\n *\n * // Fallback-only (no converter): string fallback\n * \\@Envapt('LOG_FILE', { fallback: '/var/log/app.log' })\n * static readonly logFile: string;\n *\n * // Fallback-only: arbitrary object fallback\n * \\@Envapt('RETRY_POLICY', { fallback: { retries: 3, backoff: 'exponential' } })\n * static readonly retryPolicy: unknown;\n * }\n * ```\n */\nexport function Envapt<TFallback>(\n key: EnvKeyInput,\n options:\n | { converter: (raw: string | undefined, fallback: TFallback) => TFallback; fallback: TFallback }\n | { fallback: TFallback; converter?: undefined }\n): PropertyDecorator;\n\n/**\n * Usage 2: Custom converter function without fallback. Either omit `required` (returns the\n * converter's output, possibly `undefined`) or pass `required: true` to throw `MissingEnvValue`\n * on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with custom converter only, with optional `required: true`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('FEATURE_FLAGS', { converter(raw) {\n * return raw ? raw.split('|').map(s => s.trim()) : [];\n * } })\n * static readonly featureFlags: string[];\n *\n * \\@Envapt('JWT_SECRET', {\n * converter: (raw) => Buffer.from(raw ?? '', 'base64'),\n * required: true\n * })\n * static readonly jwtSecret: Buffer;\n * }\n * ```\n */\nexport function Envapt<TReturnType>(\n key: EnvKeyInput,\n options:\n | { converter: ConverterFunction<TReturnType>; required?: false }\n | { converter: ConverterFunction<TReturnType>; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 3: Built-in or array converter with optional fallback OR `required: true`.\n *\n * `InferConverterFallbackType` handles asymmetric cases: scalar `Converters.Time` accepts\n * `TimeFallback`, and `ArrayOf<'time'>` accepts `TimeFallback[]`. Every other converter\n * reduces to `InferConverterReturnType`. The two object-shape branches are mutually\n * exclusive: either provide a `fallback`, or pass `required: true` to throw\n * `MissingEnvValue` on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * import { Converters } from 'envapt';\n *\n * class Config extends Envapter {\n * // Use built-in Number converter with a numeric fallback\n * \\@Envapt('APP_PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * // Url converter: the fallback is a URL instance, not a string\n * \\@Envapt('APP_URL', { converter: Converters.Url, fallback: new URL('http://localhost:3000') })\n * static readonly url: URL;\n *\n * // Prefer CANARY_URL when present, otherwise fall back to APP_URL\n * \\@Envapt(['CANARY_URL', 'APP_URL'], { converter: Converters.Url })\n * static readonly canaryUrl: URL | null;\n *\n * // `Converters.Time` accepts either a number (milliseconds) or a time-string fallback (`<number><unit>`).\n * \\@Envapt('REQUEST_TIMEOUT', { converter: Converters.Time, fallback: '10s' })\n * static readonly requestTimeout: number;\n *\n * // Array converter: comma-separated list of origins -> string[]\n * \\@Envapt('ALLOWED_ORIGINS', {\n * converter: Converters.array({ of: Converters.String }),\n * fallback: ['https://example.com']\n * })\n * static readonly allowedOrigins: string[];\n *\n * \\@Envapt('DATABASE_URL', { converter: Converters.Url, required: true })\n * static readonly databaseUrl: URL;\n * }\n * ```\n */\nexport function Envapt<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options:\n | { converter: TConverter; fallback?: InferConverterFallbackType<TConverter> | undefined; required?: false }\n | { converter: TConverter; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 4: Primitive constructor with optional fallback\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with primitive constructor\n * @public\n * @example\n * ```ts\n * // Use primitive constructors to coerce values\n * class Config extends Envapter {\n * \\@Envapt('MAX_CONNECTIONS', { converter: Number, fallback: 100 })\n * static readonly maxConnections: number;\n *\n * \\@Envapt('FEATURE_ENABLED', { converter: Boolean, fallback: false })\n * static readonly featureEnabled: boolean;\n * }\n * ```\n */\nexport function Envapt<TConstructor extends PrimitiveConstructor>(\n key: EnvKeyInput,\n options:\n | { converter: TConstructor; fallback?: InferPrimitiveReturnType<TConstructor>; required?: false }\n | { converter: TConstructor; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 5: Required, no converter (raw string). Throws `MissingEnvValue` on first access if\n * the env value is missing or empty (post-trim). Independent of global `Envapter.strict`.\n * Combining `required: true` with `fallback` fails to match any overload at compile time;\n * the runtime Validator catches dynamic objects that bypass the types.\n *\n * @param key - Environment variable name(s) to load\n * @param options - `{ required: true }`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('API_KEY', { required: true })\n * static readonly apiKey: string;\n * }\n * ```\n */\nexport function Envapt(key: EnvKeyInput, options: { required: true }): PropertyDecorator;\n\n/**\n * No-fallback form. The property resolves from env or `null`.\n *\n * @param key - Environment variable name(s) to load\n * @public\n * @example\n * ```ts\n * // Classic API: no fallback — property will resolve from env or be null\n * class Config extends Envapter {\n * \\@Envapt('SIMPLE_VALUE')\n * static readonly simple?: string | null;\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function Envapt<_TReturnType = string | null>(key: EnvKeyInput): PropertyDecorator;\n\n/**\n * Usage 6: Standard Schema v1 adapter (zod, valibot, arktype, hand-rolled). Synchronous\n * schemas only; a Promise-returning `validate` triggers a runtime\n * `InvalidUserDefinedConfig` throw. Combining `schema` with `converter` fails to match any\n * overload at compile time; the runtime Validator catches dynamic objects that bypass the\n * types.\n * @public\n */\nexport function Envapt<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n options:\n | { schema: SchemaConstraint<Schema>; fallback?: InferSchemaOutput<Schema>; required?: false }\n | { schema: SchemaConstraint<Schema>; required: true }\n): PropertyDecorator;\n\n/**\n * Instance/Static Property decorator that automatically loads and converts environment variables.\n */\nexport function Envapt<TFallback = unknown>(key: EnvKeyInput, options?: unknown): PropertyDecorator {\n let fallback: TFallback | undefined;\n let actualConverter: EnvaptConverter<TFallback> | undefined;\n let actualSchema: StandardSchemaV1 | undefined;\n let hasFallback = false;\n let required = false;\n\n if (options !== undefined) {\n if (\n typeof options !== 'object' ||\n options === null ||\n !('fallback' in options || 'converter' in options || 'required' in options || 'schema' in options)\n ) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n 'The positional `@Envapt(key, fallback, converter)` form was removed in v6. Pass an options object instead, like `@Envapt(key, { converter, fallback })`, or use one of the sugar decorators.'\n );\n }\n\n const opts = options as {\n fallback?: TFallback;\n converter?: EnvaptConverter<TFallback>;\n required?: boolean;\n schema?: unknown;\n };\n fallback = opts.fallback;\n actualConverter = opts.converter;\n hasFallback = 'fallback' in opts;\n required = opts.required === true;\n\n if (required && hasFallback && fallback !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`required: true` and `fallback` are mutually exclusive on @Envapt options. Drop the fallback or call `Envapter.require()` separately.'\n );\n }\n\n if ('schema' in opts && opts.schema !== undefined) {\n if (!Validator.isStandardSchema(opts.schema)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` must be a Standard Schema v1 object (zod, valibot, arktype, or any `~standard`-conformant value).'\n );\n }\n if (actualConverter !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` and `converter` are mutually exclusive on @Envapt options. Drop one as they both turn a raw env string into a typed value.'\n );\n }\n actualSchema = opts.schema;\n }\n }\n\n return createPropertyDecorator(key, {\n fallback,\n converter: actualConverter,\n hasFallback,\n required,\n schema: actualSchema\n });\n}\n"],"mappings":"6JAwNA,SAAgB,EAA4B,EAAkB,EAAsC,CAChG,IAAI,EACA,EACA,EACA,EAAc,GACd,EAAW,GAEf,GAAI,IAAY,IAAA,GAAW,CACvB,GACI,OAAO,GAAY,WACnB,GACA,EAAE,aAAc,GAAW,cAAe,GAAW,aAAc,GAAW,WAAY,GAE1F,MAAM,IAAIA,EAAAA,YAAAA,IAEN,8LACJ,EAGJ,IAAM,EAAO,EAWb,GALA,EAAW,EAAK,SAChB,EAAkB,EAAK,UACvB,EAAc,aAAc,EAC5B,EAAW,EAAK,WAAa,GAEzB,GAAY,GAAe,IAAa,IAAA,GACxC,MAAM,IAAIA,EAAAA,YAAAA,IAEN,uIACJ,EAGJ,GAAI,WAAY,GAAQ,EAAK,SAAW,IAAA,GAAW,CAC/C,GAAI,CAACC,EAAAA,UAAU,iBAAiB,EAAK,MAAM,EACvC,MAAM,IAAID,EAAAA,YAAAA,IAEN,4GACJ,EAEJ,GAAI,IAAoB,IAAA,GACpB,MAAM,IAAIA,EAAAA,YAAAA,IAEN,qIACJ,EAEJ,EAAe,EAAK,MACxB,CACJ,CAEA,OAAOE,EAAAA,wBAAwB,EAAK,CAChC,WACA,UAAW,EACX,cACA,WACA,OAAQ,CACZ,CAAC,CACL"}
|
|
@@ -62,7 +62,7 @@ declare function Envapt<TFallback>(key: EnvKeyInput, options: {
|
|
|
62
62
|
* converter: (raw) => Buffer.from(raw ?? '', 'base64'),
|
|
63
63
|
* required: true
|
|
64
64
|
* })
|
|
65
|
-
*
|
|
65
|
+
* static readonly jwtSecret: Buffer;
|
|
66
66
|
* }
|
|
67
67
|
* ```
|
|
68
68
|
*/
|
|
@@ -114,7 +114,7 @@ declare function Envapt<TReturnType>(key: EnvKeyInput, options: {
|
|
|
114
114
|
* static readonly allowedOrigins: string[];
|
|
115
115
|
*
|
|
116
116
|
* \@Envapt('DATABASE_URL', { converter: Converters.Url, required: true })
|
|
117
|
-
*
|
|
117
|
+
* static readonly databaseUrl: URL;
|
|
118
118
|
* }
|
|
119
119
|
* ```
|
|
120
120
|
*/
|
|
@@ -165,7 +165,7 @@ declare function Envapt<TConstructor extends PrimitiveConstructor>(key: EnvKeyIn
|
|
|
165
165
|
* ```ts
|
|
166
166
|
* class Config extends Envapter {
|
|
167
167
|
* \@Envapt('API_KEY', { required: true })
|
|
168
|
-
*
|
|
168
|
+
* static readonly apiKey: string;
|
|
169
169
|
* }
|
|
170
170
|
* ```
|
|
171
171
|
*/
|
|
@@ -64,7 +64,7 @@ declare function Envapt<TFallback>(key: EnvKeyInput, options: {
|
|
|
64
64
|
* converter: (raw) => Buffer.from(raw ?? '', 'base64'),
|
|
65
65
|
* required: true
|
|
66
66
|
* })
|
|
67
|
-
*
|
|
67
|
+
* static readonly jwtSecret: Buffer;
|
|
68
68
|
* }
|
|
69
69
|
* ```
|
|
70
70
|
*/
|
|
@@ -116,7 +116,7 @@ declare function Envapt<TReturnType>(key: EnvKeyInput, options: {
|
|
|
116
116
|
* static readonly allowedOrigins: string[];
|
|
117
117
|
*
|
|
118
118
|
* \@Envapt('DATABASE_URL', { converter: Converters.Url, required: true })
|
|
119
|
-
*
|
|
119
|
+
* static readonly databaseUrl: URL;
|
|
120
120
|
* }
|
|
121
121
|
* ```
|
|
122
122
|
*/
|
|
@@ -167,7 +167,7 @@ declare function Envapt<TConstructor extends PrimitiveConstructor>(key: EnvKeyIn
|
|
|
167
167
|
* ```ts
|
|
168
168
|
* class Config extends Envapter {
|
|
169
169
|
* \@Envapt('API_KEY', { required: true })
|
|
170
|
-
*
|
|
170
|
+
* static readonly apiKey: string;
|
|
171
171
|
* }
|
|
172
172
|
* ```
|
|
173
173
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Envapt.mjs","names":[],"sources":["../../../src/decorators/Envapt.ts"],"sourcesContent":["import { createPropertyDecorator } from './createPropertyDecorator';\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\nimport { Validator } from '../Validators';\n\nimport type { ArrayOf } from '../converters';\nimport type { InferSchemaOutput, StandardSchemaV1 } from '../StandardSchema';\nimport type {\n BuiltInConverter,\n ConverterFunction,\n EnvKeyInput,\n EnvaptConverter,\n InferConverterFallbackType,\n InferPrimitiveReturnType,\n PrimitiveConstructor,\n SchemaConstraint\n} from '../types';\n\n/**\n * Usage 1: Either a custom converter function + fallback (both required), OR a fallback\n * only (no converter).\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * // Custom converter that validates a non-empty API key\n * \\@Envapt('API_KEY', {\n * fallback: 'default-key',\n * converter(raw, _fallback) {\n * if (!raw || raw.trim() === '') throw new Error('API_KEY required');\n * return raw.trim();\n * }\n * })\n * static readonly apiKey: string;\n *\n * // Fallback-only (no converter): string fallback\n * \\@Envapt('LOG_FILE', { fallback: '/var/log/app.log' })\n * static readonly logFile: string;\n *\n * // Fallback-only: arbitrary object fallback\n * \\@Envapt('RETRY_POLICY', { fallback: { retries: 3, backoff: 'exponential' } })\n * static readonly retryPolicy: unknown;\n * }\n * ```\n */\nexport function Envapt<TFallback>(\n key: EnvKeyInput,\n options:\n | { converter: (raw: string | undefined, fallback: TFallback) => TFallback; fallback: TFallback }\n | { fallback: TFallback; converter?: undefined }\n): PropertyDecorator;\n\n/**\n * Usage 2: Custom converter function without fallback. Either omit `required` (returns the\n * converter's output, possibly `undefined`) or pass `required: true` to throw `MissingEnvValue`\n * on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with custom converter only, with optional `required: true`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('FEATURE_FLAGS', { converter(raw) {\n * return raw ? raw.split('|').map(s => s.trim()) : [];\n * } })\n * static readonly featureFlags: string[];\n *\n * \\@Envapt('JWT_SECRET', {\n * converter: (raw) => Buffer.from(raw ?? '', 'base64'),\n * required: true\n * })\n * declare static readonly jwtSecret: Buffer;\n * }\n * ```\n */\nexport function Envapt<TReturnType>(\n key: EnvKeyInput,\n options:\n | { converter: ConverterFunction<TReturnType>; required?: false }\n | { converter: ConverterFunction<TReturnType>; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 3: Built-in or array converter with optional fallback OR `required: true`.\n *\n * `InferConverterFallbackType` handles asymmetric cases: scalar `Converters.Time` accepts\n * `TimeFallback`, and `ArrayOf<'time'>` accepts `TimeFallback[]`. Every other converter\n * reduces to `InferConverterReturnType`. The two object-shape branches are mutually\n * exclusive: either provide a `fallback`, or pass `required: true` to throw\n * `MissingEnvValue` on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * import { Converters } from 'envapt';\n *\n * class Config extends Envapter {\n * // Use built-in Number converter with a numeric fallback\n * \\@Envapt('APP_PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * // Url converter: the fallback is a URL instance, not a string\n * \\@Envapt('APP_URL', { converter: Converters.Url, fallback: new URL('http://localhost:3000') })\n * static readonly url: URL;\n *\n * // Prefer CANARY_URL when present, otherwise fall back to APP_URL\n * \\@Envapt(['CANARY_URL', 'APP_URL'], { converter: Converters.Url })\n * static readonly canaryUrl: URL | null;\n *\n * // `Converters.Time` accepts either a number (milliseconds) or a time-string fallback (`<number><unit>`).\n * \\@Envapt('REQUEST_TIMEOUT', { converter: Converters.Time, fallback: '10s' })\n * static readonly requestTimeout: number;\n *\n * // Array converter: comma-separated list of origins -> string[]\n * \\@Envapt('ALLOWED_ORIGINS', {\n * converter: Converters.array({ of: Converters.String }),\n * fallback: ['https://example.com']\n * })\n * static readonly allowedOrigins: string[];\n *\n * \\@Envapt('DATABASE_URL', { converter: Converters.Url, required: true })\n * declare static readonly databaseUrl: URL;\n * }\n * ```\n */\nexport function Envapt<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options:\n | { converter: TConverter; fallback?: InferConverterFallbackType<TConverter> | undefined; required?: false }\n | { converter: TConverter; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 4: Primitive constructor with optional fallback\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with primitive constructor\n * @public\n * @example\n * ```ts\n * // Use primitive constructors to coerce values\n * class Config extends Envapter {\n * \\@Envapt('MAX_CONNECTIONS', { converter: Number, fallback: 100 })\n * static readonly maxConnections: number;\n *\n * \\@Envapt('FEATURE_ENABLED', { converter: Boolean, fallback: false })\n * static readonly featureEnabled: boolean;\n * }\n * ```\n */\nexport function Envapt<TConstructor extends PrimitiveConstructor>(\n key: EnvKeyInput,\n options:\n | { converter: TConstructor; fallback?: InferPrimitiveReturnType<TConstructor>; required?: false }\n | { converter: TConstructor; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 5: Required, no converter (raw string). Throws `MissingEnvValue` on first access if\n * the env value is missing or empty (post-trim). Independent of global `Envapter.strict`.\n * Combining `required: true` with `fallback` fails to match any overload at compile time;\n * the runtime Validator catches dynamic objects that bypass the types.\n *\n * @param key - Environment variable name(s) to load\n * @param options - `{ required: true }`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('API_KEY', { required: true })\n * declare static readonly apiKey: string;\n * }\n * ```\n */\nexport function Envapt(key: EnvKeyInput, options: { required: true }): PropertyDecorator;\n\n/**\n * No-fallback form. The property resolves from env or `null`.\n *\n * @param key - Environment variable name(s) to load\n * @public\n * @example\n * ```ts\n * // Classic API: no fallback — property will resolve from env or be null\n * class Config extends Envapter {\n * \\@Envapt('SIMPLE_VALUE')\n * static readonly simple?: string | null;\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function Envapt<_TReturnType = string | null>(key: EnvKeyInput): PropertyDecorator;\n\n/**\n * Usage 6: Standard Schema v1 adapter (zod, valibot, arktype, hand-rolled). Synchronous\n * schemas only; a Promise-returning `validate` triggers a runtime\n * `InvalidUserDefinedConfig` throw. Combining `schema` with `converter` fails to match any\n * overload at compile time; the runtime Validator catches dynamic objects that bypass the\n * types.\n * @public\n */\nexport function Envapt<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n options:\n | { schema: SchemaConstraint<Schema>; fallback?: InferSchemaOutput<Schema>; required?: false }\n | { schema: SchemaConstraint<Schema>; required: true }\n): PropertyDecorator;\n\n/**\n * Instance/Static Property decorator that automatically loads and converts environment variables.\n */\nexport function Envapt<TFallback = unknown>(key: EnvKeyInput, options?: unknown): PropertyDecorator {\n let fallback: TFallback | undefined;\n let actualConverter: EnvaptConverter<TFallback> | undefined;\n let actualSchema: StandardSchemaV1 | undefined;\n let hasFallback = false;\n let required = false;\n\n if (options !== undefined) {\n if (\n typeof options !== 'object' ||\n options === null ||\n !('fallback' in options || 'converter' in options || 'required' in options || 'schema' in options)\n ) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n 'The positional `@Envapt(key, fallback, converter)` form was removed in v6. Pass an options object instead, like `@Envapt(key, { converter, fallback })`, or use one of the sugar decorators.'\n );\n }\n\n const opts = options as {\n fallback?: TFallback;\n converter?: EnvaptConverter<TFallback>;\n required?: boolean;\n schema?: unknown;\n };\n fallback = opts.fallback;\n actualConverter = opts.converter;\n hasFallback = 'fallback' in opts;\n required = opts.required === true;\n\n if (required && hasFallback && fallback !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`required: true` and `fallback` are mutually exclusive on @Envapt options. Drop the fallback or call `Envapter.require()` separately.'\n );\n }\n\n if ('schema' in opts && opts.schema !== undefined) {\n if (!Validator.isStandardSchema(opts.schema)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` must be a Standard Schema v1 object (zod, valibot, arktype, or any `~standard`-conformant value).'\n );\n }\n if (actualConverter !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` and `converter` are mutually exclusive on @Envapt options. Drop one as they both turn a raw env string into a typed value.'\n );\n }\n actualSchema = opts.schema;\n }\n }\n\n return createPropertyDecorator(key, {\n fallback,\n converter: actualConverter,\n hasFallback,\n required,\n schema: actualSchema\n });\n}\n"],"mappings":"oNAwNA,SAAgB,EAA4B,EAAkB,EAAsC,CAChG,IAAI,EACA,EACA,EACA,EAAc,GACd,EAAW,GAEf,GAAI,IAAY,IAAA,GAAW,CACvB,GACI,OAAO,GAAY,WACnB,GACA,EAAE,aAAc,GAAW,cAAe,GAAW,aAAc,GAAW,WAAY,GAE1F,MAAM,IAAI,EAAA,IAEN,8LACJ,EAGJ,IAAM,EAAO,EAWb,GALA,EAAW,EAAK,SAChB,EAAkB,EAAK,UACvB,EAAc,aAAc,EAC5B,EAAW,EAAK,WAAa,GAEzB,GAAY,GAAe,IAAa,IAAA,GACxC,MAAM,IAAI,EAAA,IAEN,uIACJ,EAGJ,GAAI,WAAY,GAAQ,EAAK,SAAW,IAAA,GAAW,CAC/C,GAAI,CAAC,EAAU,iBAAiB,EAAK,MAAM,EACvC,MAAM,IAAI,EAAA,IAEN,4GACJ,EAEJ,GAAI,IAAoB,IAAA,GACpB,MAAM,IAAI,EAAA,IAEN,qIACJ,EAEJ,EAAe,EAAK,MACxB,CACJ,CAEA,OAAO,EAAwB,EAAK,CAChC,WACA,UAAW,EACX,cACA,WACA,OAAQ,CACZ,CAAC,CACL"}
|
|
1
|
+
{"version":3,"file":"Envapt.mjs","names":[],"sources":["../../../src/decorators/Envapt.ts"],"sourcesContent":["import { createPropertyDecorator } from './createPropertyDecorator';\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\nimport { Validator } from '../Validators';\n\nimport type { ArrayOf } from '../converters';\nimport type { InferSchemaOutput, StandardSchemaV1 } from '../StandardSchema';\nimport type {\n BuiltInConverter,\n ConverterFunction,\n EnvKeyInput,\n EnvaptConverter,\n InferConverterFallbackType,\n InferPrimitiveReturnType,\n PrimitiveConstructor,\n SchemaConstraint\n} from '../types';\n\n/**\n * Usage 1: Either a custom converter function + fallback (both required), OR a fallback\n * only (no converter).\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * // Custom converter that validates a non-empty API key\n * \\@Envapt('API_KEY', {\n * fallback: 'default-key',\n * converter(raw, _fallback) {\n * if (!raw || raw.trim() === '') throw new Error('API_KEY required');\n * return raw.trim();\n * }\n * })\n * static readonly apiKey: string;\n *\n * // Fallback-only (no converter): string fallback\n * \\@Envapt('LOG_FILE', { fallback: '/var/log/app.log' })\n * static readonly logFile: string;\n *\n * // Fallback-only: arbitrary object fallback\n * \\@Envapt('RETRY_POLICY', { fallback: { retries: 3, backoff: 'exponential' } })\n * static readonly retryPolicy: unknown;\n * }\n * ```\n */\nexport function Envapt<TFallback>(\n key: EnvKeyInput,\n options:\n | { converter: (raw: string | undefined, fallback: TFallback) => TFallback; fallback: TFallback }\n | { fallback: TFallback; converter?: undefined }\n): PropertyDecorator;\n\n/**\n * Usage 2: Custom converter function without fallback. Either omit `required` (returns the\n * converter's output, possibly `undefined`) or pass `required: true` to throw `MissingEnvValue`\n * on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with custom converter only, with optional `required: true`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('FEATURE_FLAGS', { converter(raw) {\n * return raw ? raw.split('|').map(s => s.trim()) : [];\n * } })\n * static readonly featureFlags: string[];\n *\n * \\@Envapt('JWT_SECRET', {\n * converter: (raw) => Buffer.from(raw ?? '', 'base64'),\n * required: true\n * })\n * static readonly jwtSecret: Buffer;\n * }\n * ```\n */\nexport function Envapt<TReturnType>(\n key: EnvKeyInput,\n options:\n | { converter: ConverterFunction<TReturnType>; required?: false }\n | { converter: ConverterFunction<TReturnType>; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 3: Built-in or array converter with optional fallback OR `required: true`.\n *\n * `InferConverterFallbackType` handles asymmetric cases: scalar `Converters.Time` accepts\n * `TimeFallback`, and `ArrayOf<'time'>` accepts `TimeFallback[]`. Every other converter\n * reduces to `InferConverterReturnType`. The two object-shape branches are mutually\n * exclusive: either provide a `fallback`, or pass `required: true` to throw\n * `MissingEnvValue` on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * import { Converters } from 'envapt';\n *\n * class Config extends Envapter {\n * // Use built-in Number converter with a numeric fallback\n * \\@Envapt('APP_PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * // Url converter: the fallback is a URL instance, not a string\n * \\@Envapt('APP_URL', { converter: Converters.Url, fallback: new URL('http://localhost:3000') })\n * static readonly url: URL;\n *\n * // Prefer CANARY_URL when present, otherwise fall back to APP_URL\n * \\@Envapt(['CANARY_URL', 'APP_URL'], { converter: Converters.Url })\n * static readonly canaryUrl: URL | null;\n *\n * // `Converters.Time` accepts either a number (milliseconds) or a time-string fallback (`<number><unit>`).\n * \\@Envapt('REQUEST_TIMEOUT', { converter: Converters.Time, fallback: '10s' })\n * static readonly requestTimeout: number;\n *\n * // Array converter: comma-separated list of origins -> string[]\n * \\@Envapt('ALLOWED_ORIGINS', {\n * converter: Converters.array({ of: Converters.String }),\n * fallback: ['https://example.com']\n * })\n * static readonly allowedOrigins: string[];\n *\n * \\@Envapt('DATABASE_URL', { converter: Converters.Url, required: true })\n * static readonly databaseUrl: URL;\n * }\n * ```\n */\nexport function Envapt<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options:\n | { converter: TConverter; fallback?: InferConverterFallbackType<TConverter> | undefined; required?: false }\n | { converter: TConverter; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 4: Primitive constructor with optional fallback\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with primitive constructor\n * @public\n * @example\n * ```ts\n * // Use primitive constructors to coerce values\n * class Config extends Envapter {\n * \\@Envapt('MAX_CONNECTIONS', { converter: Number, fallback: 100 })\n * static readonly maxConnections: number;\n *\n * \\@Envapt('FEATURE_ENABLED', { converter: Boolean, fallback: false })\n * static readonly featureEnabled: boolean;\n * }\n * ```\n */\nexport function Envapt<TConstructor extends PrimitiveConstructor>(\n key: EnvKeyInput,\n options:\n | { converter: TConstructor; fallback?: InferPrimitiveReturnType<TConstructor>; required?: false }\n | { converter: TConstructor; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 5: Required, no converter (raw string). Throws `MissingEnvValue` on first access if\n * the env value is missing or empty (post-trim). Independent of global `Envapter.strict`.\n * Combining `required: true` with `fallback` fails to match any overload at compile time;\n * the runtime Validator catches dynamic objects that bypass the types.\n *\n * @param key - Environment variable name(s) to load\n * @param options - `{ required: true }`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('API_KEY', { required: true })\n * static readonly apiKey: string;\n * }\n * ```\n */\nexport function Envapt(key: EnvKeyInput, options: { required: true }): PropertyDecorator;\n\n/**\n * No-fallback form. The property resolves from env or `null`.\n *\n * @param key - Environment variable name(s) to load\n * @public\n * @example\n * ```ts\n * // Classic API: no fallback — property will resolve from env or be null\n * class Config extends Envapter {\n * \\@Envapt('SIMPLE_VALUE')\n * static readonly simple?: string | null;\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function Envapt<_TReturnType = string | null>(key: EnvKeyInput): PropertyDecorator;\n\n/**\n * Usage 6: Standard Schema v1 adapter (zod, valibot, arktype, hand-rolled). Synchronous\n * schemas only; a Promise-returning `validate` triggers a runtime\n * `InvalidUserDefinedConfig` throw. Combining `schema` with `converter` fails to match any\n * overload at compile time; the runtime Validator catches dynamic objects that bypass the\n * types.\n * @public\n */\nexport function Envapt<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n options:\n | { schema: SchemaConstraint<Schema>; fallback?: InferSchemaOutput<Schema>; required?: false }\n | { schema: SchemaConstraint<Schema>; required: true }\n): PropertyDecorator;\n\n/**\n * Instance/Static Property decorator that automatically loads and converts environment variables.\n */\nexport function Envapt<TFallback = unknown>(key: EnvKeyInput, options?: unknown): PropertyDecorator {\n let fallback: TFallback | undefined;\n let actualConverter: EnvaptConverter<TFallback> | undefined;\n let actualSchema: StandardSchemaV1 | undefined;\n let hasFallback = false;\n let required = false;\n\n if (options !== undefined) {\n if (\n typeof options !== 'object' ||\n options === null ||\n !('fallback' in options || 'converter' in options || 'required' in options || 'schema' in options)\n ) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n 'The positional `@Envapt(key, fallback, converter)` form was removed in v6. Pass an options object instead, like `@Envapt(key, { converter, fallback })`, or use one of the sugar decorators.'\n );\n }\n\n const opts = options as {\n fallback?: TFallback;\n converter?: EnvaptConverter<TFallback>;\n required?: boolean;\n schema?: unknown;\n };\n fallback = opts.fallback;\n actualConverter = opts.converter;\n hasFallback = 'fallback' in opts;\n required = opts.required === true;\n\n if (required && hasFallback && fallback !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`required: true` and `fallback` are mutually exclusive on @Envapt options. Drop the fallback or call `Envapter.require()` separately.'\n );\n }\n\n if ('schema' in opts && opts.schema !== undefined) {\n if (!Validator.isStandardSchema(opts.schema)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` must be a Standard Schema v1 object (zod, valibot, arktype, or any `~standard`-conformant value).'\n );\n }\n if (actualConverter !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` and `converter` are mutually exclusive on @Envapt options. Drop one as they both turn a raw env string into a typed value.'\n );\n }\n actualSchema = opts.schema;\n }\n }\n\n return createPropertyDecorator(key, {\n fallback,\n converter: actualConverter,\n hasFallback,\n required,\n schema: actualSchema\n });\n}\n"],"mappings":"oNAwNA,SAAgB,EAA4B,EAAkB,EAAsC,CAChG,IAAI,EACA,EACA,EACA,EAAc,GACd,EAAW,GAEf,GAAI,IAAY,IAAA,GAAW,CACvB,GACI,OAAO,GAAY,WACnB,GACA,EAAE,aAAc,GAAW,cAAe,GAAW,aAAc,GAAW,WAAY,GAE1F,MAAM,IAAI,EAAA,IAEN,8LACJ,EAGJ,IAAM,EAAO,EAWb,GALA,EAAW,EAAK,SAChB,EAAkB,EAAK,UACvB,EAAc,aAAc,EAC5B,EAAW,EAAK,WAAa,GAEzB,GAAY,GAAe,IAAa,IAAA,GACxC,MAAM,IAAI,EAAA,IAEN,uIACJ,EAGJ,GAAI,WAAY,GAAQ,EAAK,SAAW,IAAA,GAAW,CAC/C,GAAI,CAAC,EAAU,iBAAiB,EAAK,MAAM,EACvC,MAAM,IAAI,EAAA,IAEN,4GACJ,EAEJ,GAAI,IAAoB,IAAA,GACpB,MAAM,IAAI,EAAA,IAEN,qIACJ,EAEJ,EAAe,EAAK,MACxB,CACJ,CAEA,OAAO,EAAwB,EAAK,CAChC,WACA,UAAW,EACX,cACA,WACA,OAAQ,CACZ,CAAC,CACL"}
|
|
@@ -44,7 +44,7 @@ declare namespace StandardSchemaV1 {
|
|
|
44
44
|
}
|
|
45
45
|
/**
|
|
46
46
|
* Envapt-side alias for {@link StandardSchemaV1.InferOutput}. Re-exported under a friendlier
|
|
47
|
-
* name so consumers writing `
|
|
47
|
+
* name so consumers writing `static readonly x: InferSchemaOutput<typeof mySchema>`
|
|
48
48
|
* don't need the namespace path.
|
|
49
49
|
* @public
|
|
50
50
|
*/
|
|
@@ -62,7 +62,7 @@ declare function Envapt<TFallback>(key: EnvKeyInput, options: {
|
|
|
62
62
|
* converter: (raw) => Buffer.from(raw ?? '', 'base64'),
|
|
63
63
|
* required: true
|
|
64
64
|
* })
|
|
65
|
-
*
|
|
65
|
+
* static readonly jwtSecret: Buffer;
|
|
66
66
|
* }
|
|
67
67
|
* ```
|
|
68
68
|
*/
|
|
@@ -114,7 +114,7 @@ declare function Envapt<TReturnType>(key: EnvKeyInput, options: {
|
|
|
114
114
|
* static readonly allowedOrigins: string[];
|
|
115
115
|
*
|
|
116
116
|
* \@Envapt('DATABASE_URL', { converter: Converters.Url, required: true })
|
|
117
|
-
*
|
|
117
|
+
* static readonly databaseUrl: URL;
|
|
118
118
|
* }
|
|
119
119
|
* ```
|
|
120
120
|
*/
|
|
@@ -165,7 +165,7 @@ declare function Envapt<TConstructor extends PrimitiveConstructor>(key: EnvKeyIn
|
|
|
165
165
|
* ```ts
|
|
166
166
|
* class Config extends Envapter {
|
|
167
167
|
* \@Envapt('API_KEY', { required: true })
|
|
168
|
-
*
|
|
168
|
+
* static readonly apiKey: string;
|
|
169
169
|
* }
|
|
170
170
|
* ```
|
|
171
171
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Envapt.mjs","names":[],"sources":["../../../src/decorators/Envapt.ts"],"sourcesContent":["import { createPropertyDecorator } from './createPropertyDecorator';\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\nimport { Validator } from '../Validators';\n\nimport type { ArrayOf } from '../converters';\nimport type { InferSchemaOutput, StandardSchemaV1 } from '../StandardSchema';\nimport type {\n BuiltInConverter,\n ConverterFunction,\n EnvKeyInput,\n EnvaptConverter,\n InferConverterFallbackType,\n InferPrimitiveReturnType,\n PrimitiveConstructor,\n SchemaConstraint\n} from '../types';\n\n/**\n * Usage 1: Either a custom converter function + fallback (both required), OR a fallback\n * only (no converter).\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * // Custom converter that validates a non-empty API key\n * \\@Envapt('API_KEY', {\n * fallback: 'default-key',\n * converter(raw, _fallback) {\n * if (!raw || raw.trim() === '') throw new Error('API_KEY required');\n * return raw.trim();\n * }\n * })\n * static readonly apiKey: string;\n *\n * // Fallback-only (no converter): string fallback\n * \\@Envapt('LOG_FILE', { fallback: '/var/log/app.log' })\n * static readonly logFile: string;\n *\n * // Fallback-only: arbitrary object fallback\n * \\@Envapt('RETRY_POLICY', { fallback: { retries: 3, backoff: 'exponential' } })\n * static readonly retryPolicy: unknown;\n * }\n * ```\n */\nexport function Envapt<TFallback>(\n key: EnvKeyInput,\n options:\n | { converter: (raw: string | undefined, fallback: TFallback) => TFallback; fallback: TFallback }\n | { fallback: TFallback; converter?: undefined }\n): PropertyDecorator;\n\n/**\n * Usage 2: Custom converter function without fallback. Either omit `required` (returns the\n * converter's output, possibly `undefined`) or pass `required: true` to throw `MissingEnvValue`\n * on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with custom converter only, with optional `required: true`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('FEATURE_FLAGS', { converter(raw) {\n * return raw ? raw.split('|').map(s => s.trim()) : [];\n * } })\n * static readonly featureFlags: string[];\n *\n * \\@Envapt('JWT_SECRET', {\n * converter: (raw) => Buffer.from(raw ?? '', 'base64'),\n * required: true\n * })\n * declare static readonly jwtSecret: Buffer;\n * }\n * ```\n */\nexport function Envapt<TReturnType>(\n key: EnvKeyInput,\n options:\n | { converter: ConverterFunction<TReturnType>; required?: false }\n | { converter: ConverterFunction<TReturnType>; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 3: Built-in or array converter with optional fallback OR `required: true`.\n *\n * `InferConverterFallbackType` handles asymmetric cases: scalar `Converters.Time` accepts\n * `TimeFallback`, and `ArrayOf<'time'>` accepts `TimeFallback[]`. Every other converter\n * reduces to `InferConverterReturnType`. The two object-shape branches are mutually\n * exclusive: either provide a `fallback`, or pass `required: true` to throw\n * `MissingEnvValue` on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * import { Converters } from 'envapt';\n *\n * class Config extends Envapter {\n * // Use built-in Number converter with a numeric fallback\n * \\@Envapt('APP_PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * // Url converter: the fallback is a URL instance, not a string\n * \\@Envapt('APP_URL', { converter: Converters.Url, fallback: new URL('http://localhost:3000') })\n * static readonly url: URL;\n *\n * // Prefer CANARY_URL when present, otherwise fall back to APP_URL\n * \\@Envapt(['CANARY_URL', 'APP_URL'], { converter: Converters.Url })\n * static readonly canaryUrl: URL | null;\n *\n * // `Converters.Time` accepts either a number (milliseconds) or a time-string fallback (`<number><unit>`).\n * \\@Envapt('REQUEST_TIMEOUT', { converter: Converters.Time, fallback: '10s' })\n * static readonly requestTimeout: number;\n *\n * // Array converter: comma-separated list of origins -> string[]\n * \\@Envapt('ALLOWED_ORIGINS', {\n * converter: Converters.array({ of: Converters.String }),\n * fallback: ['https://example.com']\n * })\n * static readonly allowedOrigins: string[];\n *\n * \\@Envapt('DATABASE_URL', { converter: Converters.Url, required: true })\n * declare static readonly databaseUrl: URL;\n * }\n * ```\n */\nexport function Envapt<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options:\n | { converter: TConverter; fallback?: InferConverterFallbackType<TConverter> | undefined; required?: false }\n | { converter: TConverter; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 4: Primitive constructor with optional fallback\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with primitive constructor\n * @public\n * @example\n * ```ts\n * // Use primitive constructors to coerce values\n * class Config extends Envapter {\n * \\@Envapt('MAX_CONNECTIONS', { converter: Number, fallback: 100 })\n * static readonly maxConnections: number;\n *\n * \\@Envapt('FEATURE_ENABLED', { converter: Boolean, fallback: false })\n * static readonly featureEnabled: boolean;\n * }\n * ```\n */\nexport function Envapt<TConstructor extends PrimitiveConstructor>(\n key: EnvKeyInput,\n options:\n | { converter: TConstructor; fallback?: InferPrimitiveReturnType<TConstructor>; required?: false }\n | { converter: TConstructor; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 5: Required, no converter (raw string). Throws `MissingEnvValue` on first access if\n * the env value is missing or empty (post-trim). Independent of global `Envapter.strict`.\n * Combining `required: true` with `fallback` fails to match any overload at compile time;\n * the runtime Validator catches dynamic objects that bypass the types.\n *\n * @param key - Environment variable name(s) to load\n * @param options - `{ required: true }`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('API_KEY', { required: true })\n * declare static readonly apiKey: string;\n * }\n * ```\n */\nexport function Envapt(key: EnvKeyInput, options: { required: true }): PropertyDecorator;\n\n/**\n * No-fallback form. The property resolves from env or `null`.\n *\n * @param key - Environment variable name(s) to load\n * @public\n * @example\n * ```ts\n * // Classic API: no fallback — property will resolve from env or be null\n * class Config extends Envapter {\n * \\@Envapt('SIMPLE_VALUE')\n * static readonly simple?: string | null;\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function Envapt<_TReturnType = string | null>(key: EnvKeyInput): PropertyDecorator;\n\n/**\n * Usage 6: Standard Schema v1 adapter (zod, valibot, arktype, hand-rolled). Synchronous\n * schemas only; a Promise-returning `validate` triggers a runtime\n * `InvalidUserDefinedConfig` throw. Combining `schema` with `converter` fails to match any\n * overload at compile time; the runtime Validator catches dynamic objects that bypass the\n * types.\n * @public\n */\nexport function Envapt<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n options:\n | { schema: SchemaConstraint<Schema>; fallback?: InferSchemaOutput<Schema>; required?: false }\n | { schema: SchemaConstraint<Schema>; required: true }\n): PropertyDecorator;\n\n/**\n * Instance/Static Property decorator that automatically loads and converts environment variables.\n */\nexport function Envapt<TFallback = unknown>(key: EnvKeyInput, options?: unknown): PropertyDecorator {\n let fallback: TFallback | undefined;\n let actualConverter: EnvaptConverter<TFallback> | undefined;\n let actualSchema: StandardSchemaV1 | undefined;\n let hasFallback = false;\n let required = false;\n\n if (options !== undefined) {\n if (\n typeof options !== 'object' ||\n options === null ||\n !('fallback' in options || 'converter' in options || 'required' in options || 'schema' in options)\n ) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n 'The positional `@Envapt(key, fallback, converter)` form was removed in v6. Pass an options object instead, like `@Envapt(key, { converter, fallback })`, or use one of the sugar decorators.'\n );\n }\n\n const opts = options as {\n fallback?: TFallback;\n converter?: EnvaptConverter<TFallback>;\n required?: boolean;\n schema?: unknown;\n };\n fallback = opts.fallback;\n actualConverter = opts.converter;\n hasFallback = 'fallback' in opts;\n required = opts.required === true;\n\n if (required && hasFallback && fallback !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`required: true` and `fallback` are mutually exclusive on @Envapt options. Drop the fallback or call `Envapter.require()` separately.'\n );\n }\n\n if ('schema' in opts && opts.schema !== undefined) {\n if (!Validator.isStandardSchema(opts.schema)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` must be a Standard Schema v1 object (zod, valibot, arktype, or any `~standard`-conformant value).'\n );\n }\n if (actualConverter !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` and `converter` are mutually exclusive on @Envapt options. Drop one as they both turn a raw env string into a typed value.'\n );\n }\n actualSchema = opts.schema;\n }\n }\n\n return createPropertyDecorator(key, {\n fallback,\n converter: actualConverter,\n hasFallback,\n required,\n schema: actualSchema\n });\n}\n"],"mappings":"iKAwNA,SAAgB,EAA4B,EAAkB,EAAsC,CAChG,IAAI,EACA,EACA,EACA,EAAc,GACd,EAAW,GAEf,GAAI,IAAY,IAAA,GAAW,CACvB,GACI,OAAO,GAAY,WACnB,GACA,EAAE,aAAc,GAAW,cAAe,GAAW,aAAc,GAAW,WAAY,GAE1F,MAAM,IAAI,EAAA,IAEN,8LACJ,EAGJ,IAAM,EAAO,EAWb,GALA,EAAW,EAAK,SAChB,EAAkB,EAAK,UACvB,EAAc,aAAc,EAC5B,EAAW,EAAK,WAAa,GAEzB,GAAY,GAAe,IAAa,IAAA,GACxC,MAAM,IAAI,EAAA,IAEN,uIACJ,EAGJ,GAAI,WAAY,GAAQ,EAAK,SAAW,IAAA,GAAW,CAC/C,GAAI,CAAC,EAAU,iBAAiB,EAAK,MAAM,EACvC,MAAM,IAAI,EAAA,IAEN,4GACJ,EAEJ,GAAI,IAAoB,IAAA,GACpB,MAAM,IAAI,EAAA,IAEN,qIACJ,EAEJ,EAAe,EAAK,MACxB,CACJ,CAEA,OAAO,EAAwB,EAAK,CAChC,WACA,UAAW,EACX,cACA,WACA,OAAQ,CACZ,CAAC,CACL"}
|
|
1
|
+
{"version":3,"file":"Envapt.mjs","names":[],"sources":["../../../src/decorators/Envapt.ts"],"sourcesContent":["import { createPropertyDecorator } from './createPropertyDecorator';\nimport { EnvaptError, EnvaptErrorCodes } from '../Error';\nimport { Validator } from '../Validators';\n\nimport type { ArrayOf } from '../converters';\nimport type { InferSchemaOutput, StandardSchemaV1 } from '../StandardSchema';\nimport type {\n BuiltInConverter,\n ConverterFunction,\n EnvKeyInput,\n EnvaptConverter,\n InferConverterFallbackType,\n InferPrimitiveReturnType,\n PrimitiveConstructor,\n SchemaConstraint\n} from '../types';\n\n/**\n * Usage 1: Either a custom converter function + fallback (both required), OR a fallback\n * only (no converter).\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * // Custom converter that validates a non-empty API key\n * \\@Envapt('API_KEY', {\n * fallback: 'default-key',\n * converter(raw, _fallback) {\n * if (!raw || raw.trim() === '') throw new Error('API_KEY required');\n * return raw.trim();\n * }\n * })\n * static readonly apiKey: string;\n *\n * // Fallback-only (no converter): string fallback\n * \\@Envapt('LOG_FILE', { fallback: '/var/log/app.log' })\n * static readonly logFile: string;\n *\n * // Fallback-only: arbitrary object fallback\n * \\@Envapt('RETRY_POLICY', { fallback: { retries: 3, backoff: 'exponential' } })\n * static readonly retryPolicy: unknown;\n * }\n * ```\n */\nexport function Envapt<TFallback>(\n key: EnvKeyInput,\n options:\n | { converter: (raw: string | undefined, fallback: TFallback) => TFallback; fallback: TFallback }\n | { fallback: TFallback; converter?: undefined }\n): PropertyDecorator;\n\n/**\n * Usage 2: Custom converter function without fallback. Either omit `required` (returns the\n * converter's output, possibly `undefined`) or pass `required: true` to throw `MissingEnvValue`\n * on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with custom converter only, with optional `required: true`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('FEATURE_FLAGS', { converter(raw) {\n * return raw ? raw.split('|').map(s => s.trim()) : [];\n * } })\n * static readonly featureFlags: string[];\n *\n * \\@Envapt('JWT_SECRET', {\n * converter: (raw) => Buffer.from(raw ?? '', 'base64'),\n * required: true\n * })\n * static readonly jwtSecret: Buffer;\n * }\n * ```\n */\nexport function Envapt<TReturnType>(\n key: EnvKeyInput,\n options:\n | { converter: ConverterFunction<TReturnType>; required?: false }\n | { converter: ConverterFunction<TReturnType>; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 3: Built-in or array converter with optional fallback OR `required: true`.\n *\n * `InferConverterFallbackType` handles asymmetric cases: scalar `Converters.Time` accepts\n * `TimeFallback`, and `ArrayOf<'time'>` accepts `TimeFallback[]`. Every other converter\n * reduces to `InferConverterReturnType`. The two object-shape branches are mutually\n * exclusive: either provide a `fallback`, or pass `required: true` to throw\n * `MissingEnvValue` on missing/empty values.\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options\n * @public\n * @example\n * ```ts\n * import { Converters } from 'envapt';\n *\n * class Config extends Envapter {\n * // Use built-in Number converter with a numeric fallback\n * \\@Envapt('APP_PORT', { converter: Converters.Number, fallback: 3000 })\n * static readonly port: number;\n *\n * // Url converter: the fallback is a URL instance, not a string\n * \\@Envapt('APP_URL', { converter: Converters.Url, fallback: new URL('http://localhost:3000') })\n * static readonly url: URL;\n *\n * // Prefer CANARY_URL when present, otherwise fall back to APP_URL\n * \\@Envapt(['CANARY_URL', 'APP_URL'], { converter: Converters.Url })\n * static readonly canaryUrl: URL | null;\n *\n * // `Converters.Time` accepts either a number (milliseconds) or a time-string fallback (`<number><unit>`).\n * \\@Envapt('REQUEST_TIMEOUT', { converter: Converters.Time, fallback: '10s' })\n * static readonly requestTimeout: number;\n *\n * // Array converter: comma-separated list of origins -> string[]\n * \\@Envapt('ALLOWED_ORIGINS', {\n * converter: Converters.array({ of: Converters.String }),\n * fallback: ['https://example.com']\n * })\n * static readonly allowedOrigins: string[];\n *\n * \\@Envapt('DATABASE_URL', { converter: Converters.Url, required: true })\n * static readonly databaseUrl: URL;\n * }\n * ```\n */\nexport function Envapt<TConverter extends BuiltInConverter | ArrayOf>(\n key: EnvKeyInput,\n options:\n | { converter: TConverter; fallback?: InferConverterFallbackType<TConverter> | undefined; required?: false }\n | { converter: TConverter; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 4: Primitive constructor with optional fallback\n *\n * @param key - Environment variable name(s) to load\n * @param options - Configuration options with primitive constructor\n * @public\n * @example\n * ```ts\n * // Use primitive constructors to coerce values\n * class Config extends Envapter {\n * \\@Envapt('MAX_CONNECTIONS', { converter: Number, fallback: 100 })\n * static readonly maxConnections: number;\n *\n * \\@Envapt('FEATURE_ENABLED', { converter: Boolean, fallback: false })\n * static readonly featureEnabled: boolean;\n * }\n * ```\n */\nexport function Envapt<TConstructor extends PrimitiveConstructor>(\n key: EnvKeyInput,\n options:\n | { converter: TConstructor; fallback?: InferPrimitiveReturnType<TConstructor>; required?: false }\n | { converter: TConstructor; required: true }\n): PropertyDecorator;\n\n/**\n * Usage 5: Required, no converter (raw string). Throws `MissingEnvValue` on first access if\n * the env value is missing or empty (post-trim). Independent of global `Envapter.strict`.\n * Combining `required: true` with `fallback` fails to match any overload at compile time;\n * the runtime Validator catches dynamic objects that bypass the types.\n *\n * @param key - Environment variable name(s) to load\n * @param options - `{ required: true }`\n * @public\n * @example\n * ```ts\n * class Config extends Envapter {\n * \\@Envapt('API_KEY', { required: true })\n * static readonly apiKey: string;\n * }\n * ```\n */\nexport function Envapt(key: EnvKeyInput, options: { required: true }): PropertyDecorator;\n\n/**\n * No-fallback form. The property resolves from env or `null`.\n *\n * @param key - Environment variable name(s) to load\n * @public\n * @example\n * ```ts\n * // Classic API: no fallback — property will resolve from env or be null\n * class Config extends Envapter {\n * \\@Envapt('SIMPLE_VALUE')\n * static readonly simple?: string | null;\n * }\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/naming-convention\nexport function Envapt<_TReturnType = string | null>(key: EnvKeyInput): PropertyDecorator;\n\n/**\n * Usage 6: Standard Schema v1 adapter (zod, valibot, arktype, hand-rolled). Synchronous\n * schemas only; a Promise-returning `validate` triggers a runtime\n * `InvalidUserDefinedConfig` throw. Combining `schema` with `converter` fails to match any\n * overload at compile time; the runtime Validator catches dynamic objects that bypass the\n * types.\n * @public\n */\nexport function Envapt<Schema extends StandardSchemaV1>(\n key: EnvKeyInput,\n options:\n | { schema: SchemaConstraint<Schema>; fallback?: InferSchemaOutput<Schema>; required?: false }\n | { schema: SchemaConstraint<Schema>; required: true }\n): PropertyDecorator;\n\n/**\n * Instance/Static Property decorator that automatically loads and converts environment variables.\n */\nexport function Envapt<TFallback = unknown>(key: EnvKeyInput, options?: unknown): PropertyDecorator {\n let fallback: TFallback | undefined;\n let actualConverter: EnvaptConverter<TFallback> | undefined;\n let actualSchema: StandardSchemaV1 | undefined;\n let hasFallback = false;\n let required = false;\n\n if (options !== undefined) {\n if (\n typeof options !== 'object' ||\n options === null ||\n !('fallback' in options || 'converter' in options || 'required' in options || 'schema' in options)\n ) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n 'The positional `@Envapt(key, fallback, converter)` form was removed in v6. Pass an options object instead, like `@Envapt(key, { converter, fallback })`, or use one of the sugar decorators.'\n );\n }\n\n const opts = options as {\n fallback?: TFallback;\n converter?: EnvaptConverter<TFallback>;\n required?: boolean;\n schema?: unknown;\n };\n fallback = opts.fallback;\n actualConverter = opts.converter;\n hasFallback = 'fallback' in opts;\n required = opts.required === true;\n\n if (required && hasFallback && fallback !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`required: true` and `fallback` are mutually exclusive on @Envapt options. Drop the fallback or call `Envapter.require()` separately.'\n );\n }\n\n if ('schema' in opts && opts.schema !== undefined) {\n if (!Validator.isStandardSchema(opts.schema)) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` must be a Standard Schema v1 object (zod, valibot, arktype, or any `~standard`-conformant value).'\n );\n }\n if (actualConverter !== undefined) {\n throw new EnvaptError(\n EnvaptErrorCodes.InvalidUserDefinedConfig,\n '`schema` and `converter` are mutually exclusive on @Envapt options. Drop one as they both turn a raw env string into a typed value.'\n );\n }\n actualSchema = opts.schema;\n }\n }\n\n return createPropertyDecorator(key, {\n fallback,\n converter: actualConverter,\n hasFallback,\n required,\n schema: actualSchema\n });\n}\n"],"mappings":"iKAwNA,SAAgB,EAA4B,EAAkB,EAAsC,CAChG,IAAI,EACA,EACA,EACA,EAAc,GACd,EAAW,GAEf,GAAI,IAAY,IAAA,GAAW,CACvB,GACI,OAAO,GAAY,WACnB,GACA,EAAE,aAAc,GAAW,cAAe,GAAW,aAAc,GAAW,WAAY,GAE1F,MAAM,IAAI,EAAA,IAEN,8LACJ,EAGJ,IAAM,EAAO,EAWb,GALA,EAAW,EAAK,SAChB,EAAkB,EAAK,UACvB,EAAc,aAAc,EAC5B,EAAW,EAAK,WAAa,GAEzB,GAAY,GAAe,IAAa,IAAA,GACxC,MAAM,IAAI,EAAA,IAEN,uIACJ,EAGJ,GAAI,WAAY,GAAQ,EAAK,SAAW,IAAA,GAAW,CAC/C,GAAI,CAAC,EAAU,iBAAiB,EAAK,MAAM,EACvC,MAAM,IAAI,EAAA,IAEN,4GACJ,EAEJ,GAAI,IAAoB,IAAA,GACpB,MAAM,IAAI,EAAA,IAEN,qIACJ,EAEJ,EAAe,EAAK,MACxB,CACJ,CAEA,OAAO,EAAwB,EAAK,CAChC,WACA,UAAW,EACX,cACA,WACA,OAAQ,CACZ,CAAC,CACL"}
|
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "envapt",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "6.0.
|
|
5
|
-
"description": "Type-safe
|
|
4
|
+
"version": "6.0.2",
|
|
5
|
+
"description": "Type-safe config for TypeScript. Read typed values from any source, process.env, .env files, Cloudflare Workers bindings, browser bundles, or any object you supply. Zero runtime dependencies, one API across Node, Bun, Deno, Workers, and the browser. Decorators, converters, and Standard Schema (zod/valibot/arktype) validation.",
|
|
6
6
|
"types": "./dist/node/index.d.mts",
|
|
7
7
|
"exports": {
|
|
8
8
|
".": {
|
|
@@ -112,8 +112,8 @@
|
|
|
112
112
|
"devDependencies": {
|
|
113
113
|
"@cloudflare/vitest-pool-workers": "0.16.14",
|
|
114
114
|
"@cloudflare/workers-types": "^4.20260613.1",
|
|
115
|
-
"@vitest/browser": "4.1.
|
|
116
|
-
"@vitest/browser-playwright": "4.1.
|
|
115
|
+
"@vitest/browser": "4.1.9",
|
|
116
|
+
"@vitest/browser-playwright": "4.1.9",
|
|
117
117
|
"arktype": "^2.2.0",
|
|
118
118
|
"esbuild": "^0.28.1",
|
|
119
119
|
"playwright": "1.60.0",
|
|
@@ -138,6 +138,7 @@
|
|
|
138
138
|
"test:workers": "tsc --noEmit -p tests/workers/tsconfig.json && vitest run --config vitest.workers.config.ts",
|
|
139
139
|
"test:browser": "tsc --noEmit -p tests/browser/tsconfig.json && vitest run --config vitest.browser.config.ts",
|
|
140
140
|
"test:consumer-build": "node tests/consumer-build/run.mjs",
|
|
141
|
+
"test:tsc-emit": "node tests/tsc-emit/run.mjs",
|
|
141
142
|
"test:all": "node ../../scripts/test-all.mjs",
|
|
142
143
|
"coverage": "pnpm run test --coverage",
|
|
143
144
|
"cs": "changeset",
|
|
@@ -146,5 +147,5 @@
|
|
|
146
147
|
"bump": "pnpm tsx ../../scripts/bump-jsr.ts",
|
|
147
148
|
"release": "pnpm run cs:publish"
|
|
148
149
|
},
|
|
149
|
-
"readme": "<img src=\"https://raw.githubusercontent.com/materwelonDhruv/envapt/main/.github/assets/logo.png\" width=\"120\" align=\"left\" alt=\"envapt logo\" />\n\n<h3>envapt</h3>\n\n<p>\n <strong>The apt way to
|
|
150
|
+
"readme": "<img src=\"https://raw.githubusercontent.com/materwelonDhruv/envapt/main/.github/assets/logo.png\" width=\"120\" align=\"left\" alt=\"envapt logo\" />\n\n<h3>envapt</h3>\n\n<p>\n <strong>The apt way to read typed config.</strong><br/>\n Read config from any source as real typed values, with zero runtime dependencies.\n</p>\n\n<p>\n <a href=\"https://www.npmjs.com/package/envapt\"><img alt=\"npm\" src=\"https://img.shields.io/npm/v/envapt?logo=npm&logoColor=cb3838&label=%20&labelColor=103544&color=cb3838\"></a>\n <a href=\"https://www.npmjs.com/package/envapt\"><img alt=\"downloads\" src=\"https://img.shields.io/npm/dm/envapt?style=flat&color=f7f6e8&labelColor=103544&label=downloads\"></a>\n <a href=\"https://jsr.io/@materwelon/envapt\"><img alt=\"jsr\" src=\"https://jsr.io/badges/@materwelon/envapt\"></a>\n <img alt=\"CI\" src=\"https://img.shields.io/github/actions/workflow/status/materwelonDhruv/envapt/checks.yml?branch=main&label=tests&style=flat&logo=github&color=3fb950&labelColor=103544\">\n <a href=\"LICENSE\"><img alt=\"License\" src=\"https://img.shields.io/npm/l/envapt?style=flat&color=e97826&logo=apache&label=\"></a>\n</p>\n\n<br clear=\"left\"/>\n\nenvapt returns config as the type you asked for instead of the `string | undefined` you get raw, with\na fallback that removes `undefined` from the return type. It reads from whatever source you bind. On\nNode, Bun, and Deno that is `process.env` and your `.env` files, bound on import. On Cloudflare\nWorkers, in the browser, or for a secrets object you fetched at boot, you bind the source with\n`Envapter.useSource(...)`.\n\n```ts\nimport { Envapter } from 'envapt';\n\nconst port = Envapter.getNumber('PORT', 3000); // number, not string | undefined\n```\n\n**[Read the docs →](https://envapt.materwelon.dev)**\n\n## What you get\n\n- **Typed values.** A fallback removes `undefined` from the return type. Built-in converters cover\n numbers, booleans, bigint, JSON, URLs, regular expressions, dates, durations, and arrays, or pass\n your own function or a Standard Schema validator (zod, valibot, arktype).\n- **Any source.** A source is any object with a `readVars()` method, so you can bind `process.env`, a\n Cloudflare Workers binding, a browser bundle, or a secrets payload you fetched from a store at boot.\n On Node, Bun, and Deno one binds on import.\n- **Zero runtime dependencies.** The reader, converters, and built-in `.env` parser are self-contained,\n so nothing is added to your dependency tree.\n- **Runs on Node, Bun, Deno, Cloudflare Workers, and the browser.** Node `>=20`, Bun `>=1.3`, Deno\n `>=2.5` (ESM and CJS). The Workers and browser builds resolve through the package `exports`\n conditions.\n- **`.env` loading built in on Node.** The default Node source adds a per-environment file cascade,\n `${VAR}` templates, and strict / required checks. Off Node there is no filesystem, so you bind\n another source with `Envapter.useSource(...)` and read with the same typed API.\n\n## Install\n\n```sh\nnpm install envapt\npnpm add envapt\nyarn add envapt\nbun add envapt\ndeno add jsr:@materwelon/envapt\n```\n\n## Quick start\n\nRead values functionally with `Envapter`, or bind them to class fields with the `@Envapt` decorator.\nBoth share the same parsing, converters, and cache.\n\n### Functional\n\nRead a value from any call site, in JavaScript or TypeScript. No build step. On Node the source is\nbound for you. On Workers and in the browser, call `Envapter.useSource(...)` first.\n\n```ts\nimport { Envapter, Converters } from 'envapt';\n\nconst port = Envapter.getNumber('PORT', 3000);\nconst origins = Envapter.getUsing('ALLOWED_ORIGINS', Converters.array(), []);\n```\n\nOn Cloudflare Workers, `env` is importable at module scope, so bind it once in a config module; in the\nbrowser, seed a `ManualEnvSource` from the object your bundler injects.\n\n```ts\nimport { env } from 'cloudflare:workers';\nimport { Envapter, WorkerEnvSource } from 'envapt';\n\nEnvapter.useSource(new WorkerEnvSource(env));\n\nexport const apiToken = Envapter.get('API_TOKEN');\n```\n\n### Decorator\n\nBind a value to a class field. TypeScript, with `experimentalDecorators` in your `tsconfig.json`.\n\n```ts\nimport { Envapt, Converters } from 'envapt';\n\nclass Config {\n @Envapt('PORT', { converter: Converters.Number, fallback: 3000 })\n static readonly port: number;\n}\n```\n\n## Documentation\n\nThe guide, converter reference, validation, configuration, and the v4 to v5 migration live at\n**[envapt.materwelon.dev](https://envapt.materwelon.dev)**.\n\n## Agent skill\n\nInstall the envapt agent skill so AI coding tools use the correct API:\n\n```sh\nnpx skills add materwelonDhruv/envapt\n```\n\n---\n\n<p align=\"center\"><sub>Built by <a href=\"https://github.com/materwelondhruv\">@materwelonDhruv</a> · Apache 2.0</sub></p>\n"
|
|
150
151
|
}
|