@optique/config 1.0.0-dev.428 → 1.0.0-dev.431

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.
@@ -1,155 +0,0 @@
1
- import { StandardSchemaV1 } from "@standard-schema/spec";
2
- import { ParserValuePlaceholder, SourceContext } from "@optique/core/context";
3
- import { Parser } from "@optique/core/parser";
4
-
5
- //#region src/index.d.ts
6
-
7
- /**
8
- * Unique symbol for config data in annotations.
9
- * @since 0.10.0
10
- */
11
- declare const configKey: unique symbol;
12
- /**
13
- * Sets active config data for a context.
14
- * @internal
15
- */
16
- declare function setActiveConfig<T>(contextId: symbol, data: T): void;
17
- /**
18
- * Gets active config data for a context.
19
- * @internal
20
- */
21
- declare function getActiveConfig<T>(contextId: symbol): T | undefined;
22
- /**
23
- * Clears active config data for a context.
24
- * @internal
25
- */
26
- declare function clearActiveConfig(contextId: symbol): void;
27
- /**
28
- * Options for creating a config context.
29
- *
30
- * @template T The output type of the config schema.
31
- * @since 0.10.0
32
- */
33
- interface ConfigContextOptions<T> {
34
- /**
35
- * Standard Schema validator for the config file.
36
- * Accepts any Standard Schema-compatible library (Zod, Valibot, ArkType, etc.).
37
- */
38
- readonly schema: StandardSchemaV1<unknown, T>;
39
- }
40
- /**
41
- * Required options for ConfigContext when used with runWith().
42
- * The `ParserValuePlaceholder` will be substituted with the actual parser
43
- * result type by runWith().
44
- *
45
- * @since 0.10.0
46
- */
47
- interface ConfigContextRequiredOptions {
48
- /**
49
- * Function to extract config file path from parsed CLI arguments.
50
- * The `parsed` parameter is typed as the parser's result type.
51
- *
52
- * @param parsed The parsed CLI arguments (typed from parser).
53
- * @returns The config file path, or undefined if not specified.
54
- */
55
- readonly getConfigPath: (parsed: ParserValuePlaceholder) => string | undefined;
56
- }
57
- /**
58
- * A config context that provides configuration data via annotations.
59
- *
60
- * When used with `runWith()`, the options must include `getConfigPath` with
61
- * the correct parser result type. The `ParserValuePlaceholder` in
62
- * `ConfigContextRequiredOptions` is substituted with the actual parser type.
63
- *
64
- * @template T The validated config data type.
65
- * @since 0.10.0
66
- */
67
- interface ConfigContext<T> extends SourceContext<ConfigContextRequiredOptions> {
68
- /**
69
- * The Standard Schema validator for the config file.
70
- */
71
- readonly schema: StandardSchemaV1<unknown, T>;
72
- }
73
- /**
74
- * Creates a config context for use with Optique parsers.
75
- *
76
- * The config context implements the SourceContext interface and can be used
77
- * with runWith() or runWithConfig() to provide configuration file support.
78
- *
79
- * @template T The output type of the config schema.
80
- * @param options Configuration options including schema and optional parser.
81
- * @returns A config context that can be used with bindConfig() and runWithConfig().
82
- * @since 0.10.0
83
- *
84
- * @example
85
- * ```typescript
86
- * import { z } from "zod";
87
- * import { createConfigContext } from "@optique/config";
88
- *
89
- * const schema = z.object({
90
- * host: z.string(),
91
- * port: z.number(),
92
- * });
93
- *
94
- * const configContext = createConfigContext({ schema });
95
- * ```
96
- */
97
- declare function createConfigContext<T>(options: ConfigContextOptions<T>): ConfigContext<T>;
98
- /**
99
- * Options for binding a parser to config values.
100
- *
101
- * @template T The config data type.
102
- * @template TValue The value type extracted from config.
103
- * @since 0.10.0
104
- */
105
- interface BindConfigOptions<T, TValue> {
106
- /**
107
- * The config context to use for fallback values.
108
- */
109
- readonly context: ConfigContext<T>;
110
- /**
111
- * Key or accessor function to extract the value from config.
112
- * Can be a property key (for top-level config values) or a function
113
- * that extracts nested values.
114
- */
115
- readonly key: keyof T | ((config: T) => TValue);
116
- /**
117
- * Default value to use when neither CLI nor config provides a value.
118
- * If not specified, the parser will fail when no value is available.
119
- */
120
- readonly default?: TValue;
121
- }
122
- /**
123
- * Binds a parser to configuration values with fallback priority.
124
- *
125
- * The binding implements the following priority order:
126
- * 1. CLI argument (if provided)
127
- * 2. Config file value (if available)
128
- * 3. Default value (if specified)
129
- * 4. Error (if none of the above)
130
- *
131
- * @template M The parser mode (sync or async).
132
- * @template TValue The parser value type.
133
- * @template TState The parser state type.
134
- * @template T The config data type.
135
- * @param parser The parser to bind to config values.
136
- * @param options Binding options including context, key, and default.
137
- * @returns A new parser with config fallback behavior.
138
- * @since 0.10.0
139
- *
140
- * @example
141
- * ```typescript
142
- * import { bindConfig } from "@optique/config";
143
- * import { option } from "@optique/core/primitives";
144
- * import { string } from "@optique/core/valueparser";
145
- *
146
- * const hostParser = bindConfig(option("--host", string()), {
147
- * context: configContext,
148
- * key: "host",
149
- * default: "localhost",
150
- * });
151
- * ```
152
- */
153
- declare function bindConfig<M extends "sync" | "async", TValue, TState, T>(parser: Parser<M, TValue, TState>, options: BindConfigOptions<T, TValue>): Parser<M, TValue, TState>;
154
- //#endregion
155
- export { BindConfigOptions, ConfigContext, ConfigContextOptions, ConfigContextRequiredOptions, bindConfig, clearActiveConfig, configKey, createConfigContext, getActiveConfig, setActiveConfig };
@@ -1,155 +0,0 @@
1
- import { StandardSchemaV1 } from "@standard-schema/spec";
2
- import { ParserValuePlaceholder, SourceContext } from "@optique/core/context";
3
- import { Parser } from "@optique/core/parser";
4
-
5
- //#region src/index.d.ts
6
-
7
- /**
8
- * Unique symbol for config data in annotations.
9
- * @since 0.10.0
10
- */
11
- declare const configKey: unique symbol;
12
- /**
13
- * Sets active config data for a context.
14
- * @internal
15
- */
16
- declare function setActiveConfig<T>(contextId: symbol, data: T): void;
17
- /**
18
- * Gets active config data for a context.
19
- * @internal
20
- */
21
- declare function getActiveConfig<T>(contextId: symbol): T | undefined;
22
- /**
23
- * Clears active config data for a context.
24
- * @internal
25
- */
26
- declare function clearActiveConfig(contextId: symbol): void;
27
- /**
28
- * Options for creating a config context.
29
- *
30
- * @template T The output type of the config schema.
31
- * @since 0.10.0
32
- */
33
- interface ConfigContextOptions<T> {
34
- /**
35
- * Standard Schema validator for the config file.
36
- * Accepts any Standard Schema-compatible library (Zod, Valibot, ArkType, etc.).
37
- */
38
- readonly schema: StandardSchemaV1<unknown, T>;
39
- }
40
- /**
41
- * Required options for ConfigContext when used with runWith().
42
- * The `ParserValuePlaceholder` will be substituted with the actual parser
43
- * result type by runWith().
44
- *
45
- * @since 0.10.0
46
- */
47
- interface ConfigContextRequiredOptions {
48
- /**
49
- * Function to extract config file path from parsed CLI arguments.
50
- * The `parsed` parameter is typed as the parser's result type.
51
- *
52
- * @param parsed The parsed CLI arguments (typed from parser).
53
- * @returns The config file path, or undefined if not specified.
54
- */
55
- readonly getConfigPath: (parsed: ParserValuePlaceholder) => string | undefined;
56
- }
57
- /**
58
- * A config context that provides configuration data via annotations.
59
- *
60
- * When used with `runWith()`, the options must include `getConfigPath` with
61
- * the correct parser result type. The `ParserValuePlaceholder` in
62
- * `ConfigContextRequiredOptions` is substituted with the actual parser type.
63
- *
64
- * @template T The validated config data type.
65
- * @since 0.10.0
66
- */
67
- interface ConfigContext<T> extends SourceContext<ConfigContextRequiredOptions> {
68
- /**
69
- * The Standard Schema validator for the config file.
70
- */
71
- readonly schema: StandardSchemaV1<unknown, T>;
72
- }
73
- /**
74
- * Creates a config context for use with Optique parsers.
75
- *
76
- * The config context implements the SourceContext interface and can be used
77
- * with runWith() or runWithConfig() to provide configuration file support.
78
- *
79
- * @template T The output type of the config schema.
80
- * @param options Configuration options including schema and optional parser.
81
- * @returns A config context that can be used with bindConfig() and runWithConfig().
82
- * @since 0.10.0
83
- *
84
- * @example
85
- * ```typescript
86
- * import { z } from "zod";
87
- * import { createConfigContext } from "@optique/config";
88
- *
89
- * const schema = z.object({
90
- * host: z.string(),
91
- * port: z.number(),
92
- * });
93
- *
94
- * const configContext = createConfigContext({ schema });
95
- * ```
96
- */
97
- declare function createConfigContext<T>(options: ConfigContextOptions<T>): ConfigContext<T>;
98
- /**
99
- * Options for binding a parser to config values.
100
- *
101
- * @template T The config data type.
102
- * @template TValue The value type extracted from config.
103
- * @since 0.10.0
104
- */
105
- interface BindConfigOptions<T, TValue> {
106
- /**
107
- * The config context to use for fallback values.
108
- */
109
- readonly context: ConfigContext<T>;
110
- /**
111
- * Key or accessor function to extract the value from config.
112
- * Can be a property key (for top-level config values) or a function
113
- * that extracts nested values.
114
- */
115
- readonly key: keyof T | ((config: T) => TValue);
116
- /**
117
- * Default value to use when neither CLI nor config provides a value.
118
- * If not specified, the parser will fail when no value is available.
119
- */
120
- readonly default?: TValue;
121
- }
122
- /**
123
- * Binds a parser to configuration values with fallback priority.
124
- *
125
- * The binding implements the following priority order:
126
- * 1. CLI argument (if provided)
127
- * 2. Config file value (if available)
128
- * 3. Default value (if specified)
129
- * 4. Error (if none of the above)
130
- *
131
- * @template M The parser mode (sync or async).
132
- * @template TValue The parser value type.
133
- * @template TState The parser state type.
134
- * @template T The config data type.
135
- * @param parser The parser to bind to config values.
136
- * @param options Binding options including context, key, and default.
137
- * @returns A new parser with config fallback behavior.
138
- * @since 0.10.0
139
- *
140
- * @example
141
- * ```typescript
142
- * import { bindConfig } from "@optique/config";
143
- * import { option } from "@optique/core/primitives";
144
- * import { string } from "@optique/core/valueparser";
145
- *
146
- * const hostParser = bindConfig(option("--host", string()), {
147
- * context: configContext,
148
- * key: "host",
149
- * default: "localhost",
150
- * });
151
- * ```
152
- */
153
- declare function bindConfig<M extends "sync" | "async", TValue, TState, T>(parser: Parser<M, TValue, TState>, options: BindConfigOptions<T, TValue>): Parser<M, TValue, TState>;
154
- //#endregion
155
- export { BindConfigOptions, ConfigContext, ConfigContextOptions, ConfigContextRequiredOptions, bindConfig, clearActiveConfig, configKey, createConfigContext, getActiveConfig, setActiveConfig };
package/dist/run.cjs DELETED
@@ -1,189 +0,0 @@
1
- const require_src = require('./src-9MkUoh9z.cjs');
2
- const node_fs_promises = require_src.__toESM(require("node:fs/promises"));
3
- const node_path = require_src.__toESM(require("node:path"));
4
- const node_process = require_src.__toESM(require("node:process"));
5
- const __optique_core_facade = require_src.__toESM(require("@optique/core/facade"));
6
-
7
- //#region src/run.ts
8
- function isErrnoException(error) {
9
- return typeof error === "object" && error !== null && "code" in error;
10
- }
11
- /**
12
- * Helper function to create a wrapper SourceContext for config loading.
13
- * @internal
14
- */
15
- function createConfigSourceContext(context, options) {
16
- return {
17
- id: context.id,
18
- async getAnnotations(parsed) {
19
- if (!parsed) return {};
20
- let configData;
21
- if ("load" in options) {
22
- const customOptions = options;
23
- try {
24
- const rawData = await Promise.resolve(customOptions.load(parsed));
25
- const validation = context.schema["~standard"].validate(rawData);
26
- let validationResult;
27
- if (validation instanceof Promise) validationResult = await validation;
28
- else validationResult = validation;
29
- if (validationResult.issues) {
30
- const firstIssue = validationResult.issues[0];
31
- throw new Error(`Config validation failed: ${firstIssue?.message ?? "Unknown error"}`);
32
- }
33
- configData = validationResult.value;
34
- } catch (error) {
35
- if (error instanceof Error && error.message.includes("validation")) throw error;
36
- throw error;
37
- }
38
- } else {
39
- const singleFileOptions = options;
40
- const configPath = singleFileOptions.getConfigPath(parsed);
41
- if (configPath) try {
42
- const contents = await (0, node_fs_promises.readFile)(configPath);
43
- let rawData;
44
- if (singleFileOptions.fileParser) rawData = singleFileOptions.fileParser(contents);
45
- else {
46
- const text = new TextDecoder().decode(contents);
47
- rawData = JSON.parse(text);
48
- }
49
- const validation = context.schema["~standard"].validate(rawData);
50
- let validationResult;
51
- if (validation instanceof Promise) validationResult = await validation;
52
- else validationResult = validation;
53
- if (validationResult.issues) {
54
- const firstIssue = validationResult.issues[0];
55
- throw new Error(`Config validation failed: ${firstIssue?.message ?? "Unknown error"}`);
56
- }
57
- configData = validationResult.value;
58
- } catch (error) {
59
- if (isErrnoException(error) && error.code === "ENOENT") configData = void 0;
60
- else if (error instanceof SyntaxError) throw new Error(`Failed to parse config file ${configPath}: ${error.message}`);
61
- else throw error;
62
- }
63
- }
64
- if (configData !== void 0 && configData !== null) {
65
- require_src.setActiveConfig(context.id, configData);
66
- return { [require_src.configKey]: configData };
67
- }
68
- return {};
69
- }
70
- };
71
- }
72
- /**
73
- * Runs a parser with configuration file support using two-pass parsing.
74
- *
75
- * This function performs the following steps:
76
- * 1. First pass: Parse arguments to extract config path or data
77
- * 2. Load and validate: Load config file(s) and validate using Standard Schema
78
- * 3. Second pass: Parse arguments again with config data as annotations
79
- *
80
- * The priority order for values is: CLI > config file > default.
81
- *
82
- * The function also supports help, version, and completion features. When these
83
- * special commands are detected, config loading is skipped entirely, ensuring
84
- * these features work even when config files don't exist.
85
- *
86
- * @template M The parser mode (sync or async).
87
- * @template TValue The parser value type.
88
- * @template TState The parser state type.
89
- * @template T The config data type.
90
- * @template THelp The return type when help is shown.
91
- * @template TError The return type when an error occurs.
92
- * @param parser The parser to execute.
93
- * @param context The config context with schema.
94
- * @param options Run options - either SingleFileOptions or CustomLoadOptions.
95
- * @returns Promise that resolves to the parsed result.
96
- * @throws Error if config file validation fails.
97
- * @since 0.10.0
98
- *
99
- * @example Single file mode
100
- * ```typescript
101
- * import { z } from "zod";
102
- * import { runWithConfig } from "@optique/config/run";
103
- * import { createConfigContext, bindConfig } from "@optique/config";
104
- *
105
- * const schema = z.object({
106
- * host: z.string(),
107
- * port: z.number(),
108
- * });
109
- *
110
- * const context = createConfigContext({ schema });
111
- *
112
- * const parser = object({
113
- * config: option("--config", string()),
114
- * host: bindConfig(option("--host", string()), {
115
- * context,
116
- * key: "host",
117
- * default: "localhost",
118
- * }),
119
- * });
120
- *
121
- * const result = await runWithConfig(parser, context, {
122
- * getConfigPath: (parsed) => parsed.config,
123
- * args: process.argv.slice(2),
124
- * help: { mode: "option", onShow: () => process.exit(0) },
125
- * version: { value: "1.0.0", onShow: () => process.exit(0) },
126
- * });
127
- * ```
128
- *
129
- * @example Custom load mode (multi-file merging)
130
- * ```typescript
131
- * import { deepMerge } from "es-toolkit";
132
- *
133
- * const result = await runWithConfig(parser, context, {
134
- * load: async (parsed) => {
135
- * const configs = await Promise.all([
136
- * loadToml("/etc/app/config.toml").catch(() => ({})),
137
- * loadToml("~/.config/app/config.toml").catch(() => ({})),
138
- * loadToml("./.app.toml").catch(() => ({})),
139
- * ]);
140
- * return deepMerge(...configs);
141
- * },
142
- * args: process.argv.slice(2),
143
- * help: { mode: "option", onShow: () => process.exit(0) },
144
- * });
145
- * ```
146
- */
147
- async function runWithConfig(parser, context, options) {
148
- const effectiveProgramName = options.programName ?? (typeof node_process.default !== "undefined" && node_process.default.argv?.[1] ? (0, node_path.basename)(node_process.default.argv[1]) : "cli");
149
- const wrapperContext = createConfigSourceContext(context, options);
150
- try {
151
- return await (0, __optique_core_facade.runWith)(parser, effectiveProgramName, [wrapperContext], {
152
- args: options.args ?? [],
153
- help: options.help,
154
- version: options.version,
155
- completion: options.completion,
156
- stdout: options.stdout,
157
- stderr: options.stderr,
158
- colors: options.colors,
159
- maxWidth: options.maxWidth,
160
- showDefault: options.showDefault,
161
- showChoices: options.showChoices,
162
- aboveError: options.aboveError,
163
- brief: options.brief,
164
- description: options.description,
165
- examples: options.examples,
166
- author: options.author,
167
- bugs: options.bugs,
168
- footer: options.footer,
169
- onError: options.onError
170
- });
171
- } catch (error) {
172
- if (error instanceof Error && error.message.startsWith("Failed to parse config file ")) {
173
- const stderr = options.stderr ?? console.error;
174
- stderr(`Error: ${error.message}`);
175
- if (options.onError) try {
176
- options.onError(1);
177
- } catch {
178
- options.onError();
179
- }
180
- throw error;
181
- }
182
- throw error;
183
- } finally {
184
- require_src.clearActiveConfig(context.id);
185
- }
186
- }
187
-
188
- //#endregion
189
- exports.runWithConfig = runWithConfig;