@optique/env 1.0.0-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright 2025–2026 Hong Minhee
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,86 @@
1
+ @optique/env
2
+ ============
3
+
4
+ Environment variable support for [Optique].
5
+
6
+ This package provides a type-safe way to bind CLI parsers to environment
7
+ variables with clear fallback behavior:
8
+
9
+ CLI arguments > environment variables > defaults.
10
+
11
+ [Optique]: https://optique.dev/
12
+
13
+
14
+ Installation
15
+ ------------
16
+
17
+ ~~~~ bash
18
+ deno add jsr:@optique/env
19
+ npm add @optique/env
20
+ pnpm add @optique/env
21
+ yarn add @optique/env
22
+ bun add @optique/env
23
+ ~~~~
24
+
25
+
26
+ Quick start
27
+ -----------
28
+
29
+ ~~~~ typescript
30
+ import { object } from "@optique/core/constructs";
31
+ import { option } from "@optique/core/primitives";
32
+ import { integer, string } from "@optique/core/valueparser";
33
+ import { runAsync } from "@optique/run";
34
+ import { bindEnv, bool, createEnvContext } from "@optique/env";
35
+
36
+ const envContext = createEnvContext({ prefix: "MYAPP_" });
37
+
38
+ const parser = object({
39
+ host: bindEnv(option("--host", string()), {
40
+ context: envContext,
41
+ key: "HOST",
42
+ parser: string(),
43
+ default: "localhost",
44
+ }),
45
+ port: bindEnv(option("--port", integer()), {
46
+ context: envContext,
47
+ key: "PORT",
48
+ parser: integer(),
49
+ default: 3000,
50
+ }),
51
+ verbose: bindEnv(option("--verbose", bool()), {
52
+ context: envContext,
53
+ key: "VERBOSE",
54
+ parser: bool(),
55
+ default: false,
56
+ }),
57
+ });
58
+
59
+ const result = await runAsync(parser, {
60
+ contexts: [envContext],
61
+ });
62
+
63
+ console.log(result);
64
+ ~~~~
65
+
66
+
67
+ Features
68
+ --------
69
+
70
+ - *Type-safe env parsing* with any Optique `ValueParser`
71
+ - *Common Boolean parser* via `bool()`
72
+ - *Prefix support* for namespaced environment variables
73
+ - *Custom env source* for Deno, tests, and custom runtimes
74
+ - *Composable contexts* with `run()` / `runAsync()` / `runWith()`
75
+
76
+
77
+ Documentation
78
+ -------------
79
+
80
+ For full documentation, visit <https://optique.dev/integrations/env>.
81
+
82
+
83
+ License
84
+ -------
85
+
86
+ MIT License. See [LICENSE](../../LICENSE) for details.
package/dist/index.cjs ADDED
@@ -0,0 +1,260 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+
23
+ //#endregion
24
+ const __optique_core_annotations = __toESM(require("@optique/core/annotations"));
25
+ const __optique_core_message = __toESM(require("@optique/core/message"));
26
+ const __optique_core_valueparser = __toESM(require("@optique/core/valueparser"));
27
+
28
+ //#region src/index.ts
29
+ const activeEnvSourceRegistry = /* @__PURE__ */ new Map();
30
+ /**
31
+ * Sets active environment source data for a context.
32
+ *
33
+ * @internal
34
+ */
35
+ function setActiveEnvSource(contextId, sourceData) {
36
+ activeEnvSourceRegistry.set(contextId, sourceData);
37
+ }
38
+ /**
39
+ * Gets active environment source data for a context.
40
+ *
41
+ * @internal
42
+ */
43
+ function getActiveEnvSource(contextId) {
44
+ return activeEnvSourceRegistry.get(contextId);
45
+ }
46
+ /**
47
+ * Clears active environment source data for a context.
48
+ *
49
+ * @internal
50
+ */
51
+ function clearActiveEnvSource(contextId) {
52
+ activeEnvSourceRegistry.delete(contextId);
53
+ }
54
+ function defaultEnvSource(key) {
55
+ const denoGlobal = globalThis.Deno;
56
+ if (typeof denoGlobal?.env?.get === "function") return denoGlobal.env.get(key);
57
+ const processGlobal = globalThis.process;
58
+ return processGlobal?.env?.[key];
59
+ }
60
+ /**
61
+ * Creates an environment context for use with Optique runners.
62
+ *
63
+ * @param options Environment context options.
64
+ * @returns A context that provides environment source annotations.
65
+ * @since 1.0.0
66
+ */
67
+ function createEnvContext(options = {}) {
68
+ const contextId = Symbol(`@optique/env context:${Math.random()}`);
69
+ const source = options.source ?? defaultEnvSource;
70
+ const prefix = options.prefix ?? "";
71
+ return {
72
+ id: contextId,
73
+ prefix,
74
+ source,
75
+ getAnnotations() {
76
+ const sourceData = {
77
+ prefix,
78
+ source
79
+ };
80
+ setActiveEnvSource(contextId, sourceData);
81
+ return { [contextId]: sourceData };
82
+ },
83
+ [Symbol.dispose]() {
84
+ clearActiveEnvSource(contextId);
85
+ }
86
+ };
87
+ }
88
+ /**
89
+ * Binds a parser to environment variables with fallback behavior.
90
+ *
91
+ * Priority order:
92
+ *
93
+ * 1. CLI argument value
94
+ * 2. Environment variable value
95
+ * 3. Default value
96
+ * 4. Error
97
+ *
98
+ * @param parser Parser that reads CLI values.
99
+ * @param options Environment binding options.
100
+ * @returns A parser with environment fallback behavior.
101
+ * @since 1.0.0
102
+ */
103
+ function bindEnv(parser, options) {
104
+ const envBindStateKey = Symbol("@optique/env/bindState");
105
+ function isEnvBindState(value) {
106
+ return value != null && typeof value === "object" && envBindStateKey in value;
107
+ }
108
+ return {
109
+ $mode: parser.$mode,
110
+ $valueType: parser.$valueType,
111
+ $stateType: parser.$stateType,
112
+ priority: parser.priority,
113
+ usage: options.default !== void 0 ? [{
114
+ type: "optional",
115
+ terms: parser.usage
116
+ }] : parser.usage,
117
+ initialState: parser.initialState,
118
+ parse: (context) => {
119
+ const annotations = (0, __optique_core_annotations.getAnnotations)(context.state);
120
+ const innerState = isEnvBindState(context.state) ? context.state.hasCliValue ? context.state.cliState : parser.initialState : context.state;
121
+ const innerContext = innerState !== context.state ? {
122
+ ...context,
123
+ state: innerState
124
+ } : context;
125
+ const processResult = (result$1) => {
126
+ if (result$1.success) {
127
+ const cliConsumed = result$1.consumed.length > 0;
128
+ const nextState$1 = {
129
+ [envBindStateKey]: true,
130
+ hasCliValue: cliConsumed,
131
+ cliState: result$1.next.state,
132
+ ...annotations && { [__optique_core_annotations.annotationKey]: annotations }
133
+ };
134
+ return {
135
+ success: true,
136
+ next: {
137
+ ...result$1.next,
138
+ state: nextState$1
139
+ },
140
+ consumed: result$1.consumed
141
+ };
142
+ }
143
+ if (result$1.consumed > 0) return result$1;
144
+ const nextState = {
145
+ [envBindStateKey]: true,
146
+ hasCliValue: false,
147
+ ...annotations && { [__optique_core_annotations.annotationKey]: annotations }
148
+ };
149
+ return {
150
+ success: true,
151
+ next: {
152
+ ...innerContext,
153
+ state: nextState
154
+ },
155
+ consumed: []
156
+ };
157
+ };
158
+ const result = parser.parse(innerContext);
159
+ if (result instanceof Promise) return result.then(processResult);
160
+ return processResult(result);
161
+ },
162
+ complete: (state) => {
163
+ if (isEnvBindState(state) && state.hasCliValue) return parser.complete(state.cliState);
164
+ return getEnvOrDefault(state, options, parser.$mode, parser, isEnvBindState(state) ? state.cliState : void 0);
165
+ },
166
+ suggest: parser.suggest,
167
+ getDocFragments(state, upperDefaultValue) {
168
+ const defaultValue = upperDefaultValue ?? options.default;
169
+ return parser.getDocFragments(state, defaultValue);
170
+ }
171
+ };
172
+ }
173
+ function wrapForMode(mode, value) {
174
+ if (mode === "async") return Promise.resolve(value);
175
+ return value;
176
+ }
177
+ function getEnvOrDefault(state, options, mode, innerParser, innerState) {
178
+ const annotations = (0, __optique_core_annotations.getAnnotations)(state);
179
+ const sourceData = annotations?.[options.context.id] ?? getActiveEnvSource(options.context.id);
180
+ const fullKey = `${sourceData?.prefix ?? options.context.prefix}${options.key}`;
181
+ const rawValue = sourceData?.source(fullKey);
182
+ if (rawValue !== void 0) {
183
+ const parsed = options.parser.parse(rawValue);
184
+ if (parsed instanceof Promise) return parsed;
185
+ return wrapForMode(mode, parsed);
186
+ }
187
+ if (options.default !== void 0) return wrapForMode(mode, {
188
+ success: true,
189
+ value: options.default
190
+ });
191
+ if (innerParser != null) {
192
+ const completeState = innerState ?? innerParser.initialState;
193
+ const result = innerParser.complete(completeState);
194
+ if (result instanceof Promise) return result;
195
+ return wrapForMode(mode, result);
196
+ }
197
+ return wrapForMode(mode, {
198
+ success: false,
199
+ error: __optique_core_message.message`Missing required environment variable: ${fullKey}.`
200
+ });
201
+ }
202
+ const TRUE_LITERALS = [
203
+ "true",
204
+ "1",
205
+ "yes",
206
+ "on"
207
+ ];
208
+ const FALSE_LITERALS = [
209
+ "false",
210
+ "0",
211
+ "no",
212
+ "off"
213
+ ];
214
+ /**
215
+ * Creates a Boolean value parser that accepts common true/false literals.
216
+ *
217
+ * Accepted values (case-insensitive):
218
+ *
219
+ * - True: `true`, `1`, `yes`, `on`
220
+ * - False: `false`, `0`, `no`, `off`
221
+ *
222
+ * @param options Parser configuration options.
223
+ * @returns A value parser for Boolean values.
224
+ * @since 1.0.0
225
+ */
226
+ function bool(options = {}) {
227
+ const metavar = options.metavar ?? "BOOLEAN";
228
+ (0, __optique_core_valueparser.ensureNonEmptyString)(metavar);
229
+ return {
230
+ $mode: "sync",
231
+ metavar,
232
+ choices: [true, false],
233
+ parse(input) {
234
+ const normalized = input.trim().toLowerCase();
235
+ if (TRUE_LITERALS.includes(normalized)) return {
236
+ success: true,
237
+ value: true
238
+ };
239
+ if (FALSE_LITERALS.includes(normalized)) return {
240
+ success: true,
241
+ value: false
242
+ };
243
+ return {
244
+ success: false,
245
+ error: options.errors?.invalidFormat ? typeof options.errors.invalidFormat === "function" ? options.errors.invalidFormat(input) : options.errors.invalidFormat : __optique_core_message.message`Invalid Boolean value: ${input}. Expected one of ${(0, __optique_core_message.valueSet)([...TRUE_LITERALS, ...FALSE_LITERALS], { locale: "en-US" })}`
246
+ };
247
+ },
248
+ format(value) {
249
+ return value ? "true" : "false";
250
+ }
251
+ };
252
+ }
253
+
254
+ //#endregion
255
+ exports.bindEnv = bindEnv;
256
+ exports.bool = bool;
257
+ exports.clearActiveEnvSource = clearActiveEnvSource;
258
+ exports.createEnvContext = createEnvContext;
259
+ exports.getActiveEnvSource = getActiveEnvSource;
260
+ exports.setActiveEnvSource = setActiveEnvSource;
@@ -0,0 +1,154 @@
1
+ import { SourceContext } from "@optique/core/context";
2
+ import { Message } from "@optique/core/message";
3
+ import { Mode, Parser } from "@optique/core/parser";
4
+ import { NonEmptyString, ValueParser } from "@optique/core/valueparser";
5
+
6
+ //#region src/index.d.ts
7
+
8
+ /**
9
+ * Function type for reading environment variable values.
10
+ *
11
+ * @since 1.0.0
12
+ */
13
+ type EnvSource = (key: string) => string | undefined;
14
+ interface EnvSourceData {
15
+ readonly prefix: string;
16
+ readonly source: EnvSource;
17
+ }
18
+ /**
19
+ * Context for environment-variable-based fallback values.
20
+ *
21
+ * @since 1.0.0
22
+ */
23
+ interface EnvContext extends SourceContext {
24
+ /**
25
+ * Prefix added to all bound keys.
26
+ */
27
+ readonly prefix: string;
28
+ /**
29
+ * Environment value source for this context.
30
+ */
31
+ readonly source: EnvSource;
32
+ }
33
+ /**
34
+ * Options for creating an environment context.
35
+ *
36
+ * @since 1.0.0
37
+ */
38
+ interface EnvContextOptions {
39
+ /**
40
+ * Optional prefix added to all environment keys.
41
+ *
42
+ * @default ""
43
+ */
44
+ readonly prefix?: string;
45
+ /**
46
+ * Custom environment source function.
47
+ *
48
+ * @default Runtime-specific source (`Deno.env.get` or `process.env`)
49
+ */
50
+ readonly source?: EnvSource;
51
+ }
52
+ /**
53
+ * Sets active environment source data for a context.
54
+ *
55
+ * @internal
56
+ */
57
+ declare function setActiveEnvSource(contextId: symbol, sourceData: EnvSourceData): void;
58
+ /**
59
+ * Gets active environment source data for a context.
60
+ *
61
+ * @internal
62
+ */
63
+ declare function getActiveEnvSource(contextId: symbol): EnvSourceData | undefined;
64
+ /**
65
+ * Clears active environment source data for a context.
66
+ *
67
+ * @internal
68
+ */
69
+ declare function clearActiveEnvSource(contextId: symbol): void;
70
+ /**
71
+ * Creates an environment context for use with Optique runners.
72
+ *
73
+ * @param options Environment context options.
74
+ * @returns A context that provides environment source annotations.
75
+ * @since 1.0.0
76
+ */
77
+ declare function createEnvContext(options?: EnvContextOptions): EnvContext;
78
+ /**
79
+ * Options for binding a parser to environment values.
80
+ *
81
+ * @template TValue The parser value type.
82
+ * @since 1.0.0
83
+ */
84
+ interface BindEnvOptions<M extends Mode, TValue> {
85
+ /**
86
+ * The environment context to read from.
87
+ */
88
+ readonly context: EnvContext;
89
+ /**
90
+ * Environment variable key without prefix.
91
+ */
92
+ readonly key: string;
93
+ /**
94
+ * Value parser used to parse the environment variable string value.
95
+ */
96
+ readonly parser: ValueParser<M extends "sync" ? "sync" : Mode, TValue>;
97
+ /**
98
+ * Default value used when neither CLI nor environment provides a value.
99
+ */
100
+ readonly default?: TValue;
101
+ }
102
+ /**
103
+ * Binds a parser to environment variables with fallback behavior.
104
+ *
105
+ * Priority order:
106
+ *
107
+ * 1. CLI argument value
108
+ * 2. Environment variable value
109
+ * 3. Default value
110
+ * 4. Error
111
+ *
112
+ * @param parser Parser that reads CLI values.
113
+ * @param options Environment binding options.
114
+ * @returns A parser with environment fallback behavior.
115
+ * @since 1.0.0
116
+ */
117
+ declare function bindEnv<M extends Mode, TValue, TState>(parser: Parser<M, TValue, TState>, options: BindEnvOptions<M, TValue>): Parser<M, TValue, TState>;
118
+ /**
119
+ * Options for the {@link bool} parser.
120
+ *
121
+ * @since 1.0.0
122
+ */
123
+ interface BoolOptions {
124
+ /**
125
+ * The metavariable name shown in help text.
126
+ *
127
+ * @default "BOOLEAN"
128
+ */
129
+ readonly metavar?: NonEmptyString;
130
+ /**
131
+ * Custom error messages for invalid Boolean input.
132
+ */
133
+ readonly errors?: {
134
+ /**
135
+ * Custom error when input is not a recognized Boolean literal.
136
+ */
137
+ readonly invalidFormat?: Message | ((input: string) => Message);
138
+ };
139
+ }
140
+ /**
141
+ * Creates a Boolean value parser that accepts common true/false literals.
142
+ *
143
+ * Accepted values (case-insensitive):
144
+ *
145
+ * - True: `true`, `1`, `yes`, `on`
146
+ * - False: `false`, `0`, `no`, `off`
147
+ *
148
+ * @param options Parser configuration options.
149
+ * @returns A value parser for Boolean values.
150
+ * @since 1.0.0
151
+ */
152
+ declare function bool(options?: BoolOptions): ValueParser<"sync", boolean>;
153
+ //#endregion
154
+ export { BindEnvOptions, BoolOptions, EnvContext, EnvContextOptions, EnvSource, bindEnv, bool, clearActiveEnvSource, createEnvContext, getActiveEnvSource, setActiveEnvSource };
@@ -0,0 +1,154 @@
1
+ import { Message } from "@optique/core/message";
2
+ import { NonEmptyString, ValueParser } from "@optique/core/valueparser";
3
+ import { SourceContext } from "@optique/core/context";
4
+ import { Mode, Parser } from "@optique/core/parser";
5
+
6
+ //#region src/index.d.ts
7
+
8
+ /**
9
+ * Function type for reading environment variable values.
10
+ *
11
+ * @since 1.0.0
12
+ */
13
+ type EnvSource = (key: string) => string | undefined;
14
+ interface EnvSourceData {
15
+ readonly prefix: string;
16
+ readonly source: EnvSource;
17
+ }
18
+ /**
19
+ * Context for environment-variable-based fallback values.
20
+ *
21
+ * @since 1.0.0
22
+ */
23
+ interface EnvContext extends SourceContext {
24
+ /**
25
+ * Prefix added to all bound keys.
26
+ */
27
+ readonly prefix: string;
28
+ /**
29
+ * Environment value source for this context.
30
+ */
31
+ readonly source: EnvSource;
32
+ }
33
+ /**
34
+ * Options for creating an environment context.
35
+ *
36
+ * @since 1.0.0
37
+ */
38
+ interface EnvContextOptions {
39
+ /**
40
+ * Optional prefix added to all environment keys.
41
+ *
42
+ * @default ""
43
+ */
44
+ readonly prefix?: string;
45
+ /**
46
+ * Custom environment source function.
47
+ *
48
+ * @default Runtime-specific source (`Deno.env.get` or `process.env`)
49
+ */
50
+ readonly source?: EnvSource;
51
+ }
52
+ /**
53
+ * Sets active environment source data for a context.
54
+ *
55
+ * @internal
56
+ */
57
+ declare function setActiveEnvSource(contextId: symbol, sourceData: EnvSourceData): void;
58
+ /**
59
+ * Gets active environment source data for a context.
60
+ *
61
+ * @internal
62
+ */
63
+ declare function getActiveEnvSource(contextId: symbol): EnvSourceData | undefined;
64
+ /**
65
+ * Clears active environment source data for a context.
66
+ *
67
+ * @internal
68
+ */
69
+ declare function clearActiveEnvSource(contextId: symbol): void;
70
+ /**
71
+ * Creates an environment context for use with Optique runners.
72
+ *
73
+ * @param options Environment context options.
74
+ * @returns A context that provides environment source annotations.
75
+ * @since 1.0.0
76
+ */
77
+ declare function createEnvContext(options?: EnvContextOptions): EnvContext;
78
+ /**
79
+ * Options for binding a parser to environment values.
80
+ *
81
+ * @template TValue The parser value type.
82
+ * @since 1.0.0
83
+ */
84
+ interface BindEnvOptions<M extends Mode, TValue> {
85
+ /**
86
+ * The environment context to read from.
87
+ */
88
+ readonly context: EnvContext;
89
+ /**
90
+ * Environment variable key without prefix.
91
+ */
92
+ readonly key: string;
93
+ /**
94
+ * Value parser used to parse the environment variable string value.
95
+ */
96
+ readonly parser: ValueParser<M extends "sync" ? "sync" : Mode, TValue>;
97
+ /**
98
+ * Default value used when neither CLI nor environment provides a value.
99
+ */
100
+ readonly default?: TValue;
101
+ }
102
+ /**
103
+ * Binds a parser to environment variables with fallback behavior.
104
+ *
105
+ * Priority order:
106
+ *
107
+ * 1. CLI argument value
108
+ * 2. Environment variable value
109
+ * 3. Default value
110
+ * 4. Error
111
+ *
112
+ * @param parser Parser that reads CLI values.
113
+ * @param options Environment binding options.
114
+ * @returns A parser with environment fallback behavior.
115
+ * @since 1.0.0
116
+ */
117
+ declare function bindEnv<M extends Mode, TValue, TState>(parser: Parser<M, TValue, TState>, options: BindEnvOptions<M, TValue>): Parser<M, TValue, TState>;
118
+ /**
119
+ * Options for the {@link bool} parser.
120
+ *
121
+ * @since 1.0.0
122
+ */
123
+ interface BoolOptions {
124
+ /**
125
+ * The metavariable name shown in help text.
126
+ *
127
+ * @default "BOOLEAN"
128
+ */
129
+ readonly metavar?: NonEmptyString;
130
+ /**
131
+ * Custom error messages for invalid Boolean input.
132
+ */
133
+ readonly errors?: {
134
+ /**
135
+ * Custom error when input is not a recognized Boolean literal.
136
+ */
137
+ readonly invalidFormat?: Message | ((input: string) => Message);
138
+ };
139
+ }
140
+ /**
141
+ * Creates a Boolean value parser that accepts common true/false literals.
142
+ *
143
+ * Accepted values (case-insensitive):
144
+ *
145
+ * - True: `true`, `1`, `yes`, `on`
146
+ * - False: `false`, `0`, `no`, `off`
147
+ *
148
+ * @param options Parser configuration options.
149
+ * @returns A value parser for Boolean values.
150
+ * @since 1.0.0
151
+ */
152
+ declare function bool(options?: BoolOptions): ValueParser<"sync", boolean>;
153
+ //#endregion
154
+ export { BindEnvOptions, BoolOptions, EnvContext, EnvContextOptions, EnvSource, bindEnv, bool, clearActiveEnvSource, createEnvContext, getActiveEnvSource, setActiveEnvSource };
package/dist/index.js ADDED
@@ -0,0 +1,232 @@
1
+ import { annotationKey, getAnnotations } from "@optique/core/annotations";
2
+ import { message, valueSet } from "@optique/core/message";
3
+ import { ensureNonEmptyString } from "@optique/core/valueparser";
4
+
5
+ //#region src/index.ts
6
+ const activeEnvSourceRegistry = /* @__PURE__ */ new Map();
7
+ /**
8
+ * Sets active environment source data for a context.
9
+ *
10
+ * @internal
11
+ */
12
+ function setActiveEnvSource(contextId, sourceData) {
13
+ activeEnvSourceRegistry.set(contextId, sourceData);
14
+ }
15
+ /**
16
+ * Gets active environment source data for a context.
17
+ *
18
+ * @internal
19
+ */
20
+ function getActiveEnvSource(contextId) {
21
+ return activeEnvSourceRegistry.get(contextId);
22
+ }
23
+ /**
24
+ * Clears active environment source data for a context.
25
+ *
26
+ * @internal
27
+ */
28
+ function clearActiveEnvSource(contextId) {
29
+ activeEnvSourceRegistry.delete(contextId);
30
+ }
31
+ function defaultEnvSource(key) {
32
+ const denoGlobal = globalThis.Deno;
33
+ if (typeof denoGlobal?.env?.get === "function") return denoGlobal.env.get(key);
34
+ const processGlobal = globalThis.process;
35
+ return processGlobal?.env?.[key];
36
+ }
37
+ /**
38
+ * Creates an environment context for use with Optique runners.
39
+ *
40
+ * @param options Environment context options.
41
+ * @returns A context that provides environment source annotations.
42
+ * @since 1.0.0
43
+ */
44
+ function createEnvContext(options = {}) {
45
+ const contextId = Symbol(`@optique/env context:${Math.random()}`);
46
+ const source = options.source ?? defaultEnvSource;
47
+ const prefix = options.prefix ?? "";
48
+ return {
49
+ id: contextId,
50
+ prefix,
51
+ source,
52
+ getAnnotations() {
53
+ const sourceData = {
54
+ prefix,
55
+ source
56
+ };
57
+ setActiveEnvSource(contextId, sourceData);
58
+ return { [contextId]: sourceData };
59
+ },
60
+ [Symbol.dispose]() {
61
+ clearActiveEnvSource(contextId);
62
+ }
63
+ };
64
+ }
65
+ /**
66
+ * Binds a parser to environment variables with fallback behavior.
67
+ *
68
+ * Priority order:
69
+ *
70
+ * 1. CLI argument value
71
+ * 2. Environment variable value
72
+ * 3. Default value
73
+ * 4. Error
74
+ *
75
+ * @param parser Parser that reads CLI values.
76
+ * @param options Environment binding options.
77
+ * @returns A parser with environment fallback behavior.
78
+ * @since 1.0.0
79
+ */
80
+ function bindEnv(parser, options) {
81
+ const envBindStateKey = Symbol("@optique/env/bindState");
82
+ function isEnvBindState(value) {
83
+ return value != null && typeof value === "object" && envBindStateKey in value;
84
+ }
85
+ return {
86
+ $mode: parser.$mode,
87
+ $valueType: parser.$valueType,
88
+ $stateType: parser.$stateType,
89
+ priority: parser.priority,
90
+ usage: options.default !== void 0 ? [{
91
+ type: "optional",
92
+ terms: parser.usage
93
+ }] : parser.usage,
94
+ initialState: parser.initialState,
95
+ parse: (context) => {
96
+ const annotations = getAnnotations(context.state);
97
+ const innerState = isEnvBindState(context.state) ? context.state.hasCliValue ? context.state.cliState : parser.initialState : context.state;
98
+ const innerContext = innerState !== context.state ? {
99
+ ...context,
100
+ state: innerState
101
+ } : context;
102
+ const processResult = (result$1) => {
103
+ if (result$1.success) {
104
+ const cliConsumed = result$1.consumed.length > 0;
105
+ const nextState$1 = {
106
+ [envBindStateKey]: true,
107
+ hasCliValue: cliConsumed,
108
+ cliState: result$1.next.state,
109
+ ...annotations && { [annotationKey]: annotations }
110
+ };
111
+ return {
112
+ success: true,
113
+ next: {
114
+ ...result$1.next,
115
+ state: nextState$1
116
+ },
117
+ consumed: result$1.consumed
118
+ };
119
+ }
120
+ if (result$1.consumed > 0) return result$1;
121
+ const nextState = {
122
+ [envBindStateKey]: true,
123
+ hasCliValue: false,
124
+ ...annotations && { [annotationKey]: annotations }
125
+ };
126
+ return {
127
+ success: true,
128
+ next: {
129
+ ...innerContext,
130
+ state: nextState
131
+ },
132
+ consumed: []
133
+ };
134
+ };
135
+ const result = parser.parse(innerContext);
136
+ if (result instanceof Promise) return result.then(processResult);
137
+ return processResult(result);
138
+ },
139
+ complete: (state) => {
140
+ if (isEnvBindState(state) && state.hasCliValue) return parser.complete(state.cliState);
141
+ return getEnvOrDefault(state, options, parser.$mode, parser, isEnvBindState(state) ? state.cliState : void 0);
142
+ },
143
+ suggest: parser.suggest,
144
+ getDocFragments(state, upperDefaultValue) {
145
+ const defaultValue = upperDefaultValue ?? options.default;
146
+ return parser.getDocFragments(state, defaultValue);
147
+ }
148
+ };
149
+ }
150
+ function wrapForMode(mode, value) {
151
+ if (mode === "async") return Promise.resolve(value);
152
+ return value;
153
+ }
154
+ function getEnvOrDefault(state, options, mode, innerParser, innerState) {
155
+ const annotations = getAnnotations(state);
156
+ const sourceData = annotations?.[options.context.id] ?? getActiveEnvSource(options.context.id);
157
+ const fullKey = `${sourceData?.prefix ?? options.context.prefix}${options.key}`;
158
+ const rawValue = sourceData?.source(fullKey);
159
+ if (rawValue !== void 0) {
160
+ const parsed = options.parser.parse(rawValue);
161
+ if (parsed instanceof Promise) return parsed;
162
+ return wrapForMode(mode, parsed);
163
+ }
164
+ if (options.default !== void 0) return wrapForMode(mode, {
165
+ success: true,
166
+ value: options.default
167
+ });
168
+ if (innerParser != null) {
169
+ const completeState = innerState ?? innerParser.initialState;
170
+ const result = innerParser.complete(completeState);
171
+ if (result instanceof Promise) return result;
172
+ return wrapForMode(mode, result);
173
+ }
174
+ return wrapForMode(mode, {
175
+ success: false,
176
+ error: message`Missing required environment variable: ${fullKey}.`
177
+ });
178
+ }
179
+ const TRUE_LITERALS = [
180
+ "true",
181
+ "1",
182
+ "yes",
183
+ "on"
184
+ ];
185
+ const FALSE_LITERALS = [
186
+ "false",
187
+ "0",
188
+ "no",
189
+ "off"
190
+ ];
191
+ /**
192
+ * Creates a Boolean value parser that accepts common true/false literals.
193
+ *
194
+ * Accepted values (case-insensitive):
195
+ *
196
+ * - True: `true`, `1`, `yes`, `on`
197
+ * - False: `false`, `0`, `no`, `off`
198
+ *
199
+ * @param options Parser configuration options.
200
+ * @returns A value parser for Boolean values.
201
+ * @since 1.0.0
202
+ */
203
+ function bool(options = {}) {
204
+ const metavar = options.metavar ?? "BOOLEAN";
205
+ ensureNonEmptyString(metavar);
206
+ return {
207
+ $mode: "sync",
208
+ metavar,
209
+ choices: [true, false],
210
+ parse(input) {
211
+ const normalized = input.trim().toLowerCase();
212
+ if (TRUE_LITERALS.includes(normalized)) return {
213
+ success: true,
214
+ value: true
215
+ };
216
+ if (FALSE_LITERALS.includes(normalized)) return {
217
+ success: true,
218
+ value: false
219
+ };
220
+ return {
221
+ success: false,
222
+ error: options.errors?.invalidFormat ? typeof options.errors.invalidFormat === "function" ? options.errors.invalidFormat(input) : options.errors.invalidFormat : message`Invalid Boolean value: ${input}. Expected one of ${valueSet([...TRUE_LITERALS, ...FALSE_LITERALS], { locale: "en-US" })}`
223
+ };
224
+ },
225
+ format(value) {
226
+ return value ? "true" : "false";
227
+ }
228
+ };
229
+ }
230
+
231
+ //#endregion
232
+ export { bindEnv, bool, clearActiveEnvSource, createEnvContext, getActiveEnvSource, setActiveEnvSource };
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "@optique/env",
3
+ "version": "1.0.0-dev.0",
4
+ "description": "Environment variable support for Optique",
5
+ "keywords": [
6
+ "CLI",
7
+ "command-line",
8
+ "commandline",
9
+ "parser",
10
+ "environment",
11
+ "env"
12
+ ],
13
+ "license": "MIT",
14
+ "author": {
15
+ "name": "Hong Minhee",
16
+ "email": "hong@minhee.org",
17
+ "url": "https://hongminhee.org/"
18
+ },
19
+ "homepage": "https://optique.dev/",
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/dahlia/optique.git",
23
+ "directory": "packages/env/"
24
+ },
25
+ "bugs": {
26
+ "url": "https://github.com/dahlia/optique/issues"
27
+ },
28
+ "funding": [
29
+ "https://github.com/sponsors/dahlia"
30
+ ],
31
+ "engines": {
32
+ "node": ">=20.0.0",
33
+ "bun": ">=1.2.0",
34
+ "deno": ">=2.3.0"
35
+ },
36
+ "files": [
37
+ "dist/",
38
+ "package.json",
39
+ "README.md"
40
+ ],
41
+ "type": "module",
42
+ "module": "./dist/index.js",
43
+ "main": "./dist/index.cjs",
44
+ "types": "./dist/index.d.ts",
45
+ "exports": {
46
+ ".": {
47
+ "types": {
48
+ "import": "./dist/index.d.ts",
49
+ "require": "./dist/index.d.cts"
50
+ },
51
+ "import": "./dist/index.js",
52
+ "require": "./dist/index.cjs"
53
+ }
54
+ },
55
+ "sideEffects": false,
56
+ "dependencies": {
57
+ "@optique/core": "1.0.0"
58
+ },
59
+ "devDependencies": {
60
+ "@types/node": "^20.19.9",
61
+ "tsdown": "^0.13.0",
62
+ "typescript": "^5.8.3"
63
+ },
64
+ "scripts": {
65
+ "build": "tsdown",
66
+ "prepublish": "tsdown",
67
+ "test": "node --experimental-transform-types --test",
68
+ "test:bun": "bun test",
69
+ "test:deno": "deno test",
70
+ "test-all": "tsdown && node --experimental-transform-types --test && bun test && deno test"
71
+ }
72
+ }