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