@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.
package/dist/run.js DELETED
@@ -1,189 +0,0 @@
1
- import { clearActiveConfig, configKey, setActiveConfig } from "./src-Dm_17c1d.js";
2
- import { readFile } from "node:fs/promises";
3
- import { basename } from "node:path";
4
- import process from "node:process";
5
- import { runWith } from "@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 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
- setActiveConfig(context.id, configData);
66
- return { [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 process !== "undefined" && process.argv?.[1] ? basename(process.argv[1]) : "cli");
149
- const wrapperContext = createConfigSourceContext(context, options);
150
- try {
151
- return await 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
- clearActiveConfig(context.id);
185
- }
186
- }
187
-
188
- //#endregion
189
- export { runWithConfig };
@@ -1,301 +0,0 @@
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
-
27
- //#region src/index.ts
28
- /**
29
- * Unique symbol for config data in annotations.
30
- * @since 0.10.0
31
- */
32
- const configKey = Symbol.for("@optique/config");
33
- /**
34
- * Internal registry for active config data during runWithConfig execution.
35
- * This is a workaround for the limitation that object() doesn't propagate
36
- * annotations to child field parsers.
37
- * @internal
38
- */
39
- const activeConfigRegistry = /* @__PURE__ */ new Map();
40
- /**
41
- * Sets active config data for a context.
42
- * @internal
43
- */
44
- function setActiveConfig(contextId, data) {
45
- activeConfigRegistry.set(contextId, data);
46
- }
47
- /**
48
- * Gets active config data for a context.
49
- * @internal
50
- */
51
- function getActiveConfig(contextId) {
52
- return activeConfigRegistry.get(contextId);
53
- }
54
- /**
55
- * Clears active config data for a context.
56
- * @internal
57
- */
58
- function clearActiveConfig(contextId) {
59
- activeConfigRegistry.delete(contextId);
60
- }
61
- /**
62
- * Creates a config context for use with Optique parsers.
63
- *
64
- * The config context implements the SourceContext interface and can be used
65
- * with runWith() or runWithConfig() to provide configuration file support.
66
- *
67
- * @template T The output type of the config schema.
68
- * @param options Configuration options including schema and optional parser.
69
- * @returns A config context that can be used with bindConfig() and runWithConfig().
70
- * @since 0.10.0
71
- *
72
- * @example
73
- * ```typescript
74
- * import { z } from "zod";
75
- * import { createConfigContext } from "@optique/config";
76
- *
77
- * const schema = z.object({
78
- * host: z.string(),
79
- * port: z.number(),
80
- * });
81
- *
82
- * const configContext = createConfigContext({ schema });
83
- * ```
84
- */
85
- function createConfigContext(options) {
86
- const contextId = Symbol.for(`@optique/config:${Math.random()}`);
87
- return {
88
- id: contextId,
89
- schema: options.schema,
90
- getAnnotations(parsed) {
91
- if (!parsed) return {};
92
- return {};
93
- }
94
- };
95
- }
96
- /**
97
- * Binds a parser to configuration values with fallback priority.
98
- *
99
- * The binding implements the following priority order:
100
- * 1. CLI argument (if provided)
101
- * 2. Config file value (if available)
102
- * 3. Default value (if specified)
103
- * 4. Error (if none of the above)
104
- *
105
- * @template M The parser mode (sync or async).
106
- * @template TValue The parser value type.
107
- * @template TState The parser state type.
108
- * @template T The config data type.
109
- * @param parser The parser to bind to config values.
110
- * @param options Binding options including context, key, and default.
111
- * @returns A new parser with config fallback behavior.
112
- * @since 0.10.0
113
- *
114
- * @example
115
- * ```typescript
116
- * import { bindConfig } from "@optique/config";
117
- * import { option } from "@optique/core/primitives";
118
- * import { string } from "@optique/core/valueparser";
119
- *
120
- * const hostParser = bindConfig(option("--host", string()), {
121
- * context: configContext,
122
- * key: "host",
123
- * default: "localhost",
124
- * });
125
- * ```
126
- */
127
- function bindConfig(parser, options) {
128
- return {
129
- $mode: parser.$mode,
130
- $valueType: parser.$valueType,
131
- $stateType: parser.$stateType,
132
- priority: parser.priority,
133
- usage: options.default !== void 0 ? [{
134
- type: "optional",
135
- terms: parser.usage
136
- }] : parser.usage,
137
- initialState: parser.initialState,
138
- parse: (context) => {
139
- const annotations = (0, __optique_core_annotations.getAnnotations)(context.state);
140
- const result = parser.parse(context);
141
- if (!(result instanceof Promise)) {
142
- if (result.success) {
143
- const newState$1 = {
144
- hasCliValue: true,
145
- cliState: result.next.state,
146
- ...annotations && { [__optique_core_annotations.annotationKey]: annotations }
147
- };
148
- return {
149
- success: true,
150
- next: {
151
- ...result.next,
152
- state: newState$1
153
- },
154
- consumed: result.consumed
155
- };
156
- }
157
- const newState = {
158
- hasCliValue: false,
159
- ...annotations && { [__optique_core_annotations.annotationKey]: annotations }
160
- };
161
- return {
162
- success: true,
163
- next: {
164
- ...context,
165
- state: newState
166
- },
167
- consumed: []
168
- };
169
- }
170
- return result.then((res) => {
171
- if (res.success) {
172
- const newState$1 = {
173
- hasCliValue: true,
174
- cliState: res.next.state,
175
- ...annotations && { [__optique_core_annotations.annotationKey]: annotations }
176
- };
177
- return {
178
- success: true,
179
- next: {
180
- ...res.next,
181
- state: newState$1
182
- },
183
- consumed: res.consumed
184
- };
185
- }
186
- const newState = {
187
- hasCliValue: false,
188
- ...annotations && { [__optique_core_annotations.annotationKey]: annotations }
189
- };
190
- return {
191
- success: true,
192
- next: {
193
- ...context,
194
- state: newState
195
- },
196
- consumed: []
197
- };
198
- });
199
- },
200
- complete: (state) => {
201
- const bindState = state;
202
- if (bindState?.hasCliValue && bindState.cliState !== void 0) {
203
- const innerResult = parser.complete(bindState.cliState);
204
- if (innerResult instanceof Promise) return innerResult.then((res) => {
205
- if (res.success) return {
206
- success: true,
207
- value: res.value
208
- };
209
- return res;
210
- });
211
- if (innerResult.success) return {
212
- success: true,
213
- value: innerResult.value
214
- };
215
- return innerResult;
216
- }
217
- return getConfigOrDefault(state, options);
218
- },
219
- suggest: parser.suggest,
220
- getDocFragments(state, upperDefaultValue) {
221
- const defaultValue = upperDefaultValue ?? options.default;
222
- return parser.getDocFragments(state, defaultValue);
223
- }
224
- };
225
- }
226
- /**
227
- * Helper function to get value from config or default.
228
- * Checks both annotations (for top-level parsers) and the active config
229
- * registry (for parsers nested inside object() when used with runWithConfig).
230
- */
231
- function getConfigOrDefault(state, options) {
232
- const annotations = (0, __optique_core_annotations.getAnnotations)(state);
233
- let configData = annotations?.[configKey];
234
- if (configData === void 0 || configData === null) {
235
- const contextId = options.context.id;
236
- configData = getActiveConfig(contextId);
237
- }
238
- let configValue;
239
- if (configData !== void 0 && configData !== null) if (typeof options.key === "function") try {
240
- configValue = options.key(configData);
241
- } catch {
242
- configValue = void 0;
243
- }
244
- else configValue = configData[options.key];
245
- if (configValue !== void 0) return {
246
- success: true,
247
- value: configValue
248
- };
249
- if (options.default !== void 0) return {
250
- success: true,
251
- value: options.default
252
- };
253
- return {
254
- success: false,
255
- error: __optique_core_message.message`Missing required configuration value.`
256
- };
257
- }
258
-
259
- //#endregion
260
- Object.defineProperty(exports, '__toESM', {
261
- enumerable: true,
262
- get: function () {
263
- return __toESM;
264
- }
265
- });
266
- Object.defineProperty(exports, 'bindConfig', {
267
- enumerable: true,
268
- get: function () {
269
- return bindConfig;
270
- }
271
- });
272
- Object.defineProperty(exports, 'clearActiveConfig', {
273
- enumerable: true,
274
- get: function () {
275
- return clearActiveConfig;
276
- }
277
- });
278
- Object.defineProperty(exports, 'configKey', {
279
- enumerable: true,
280
- get: function () {
281
- return configKey;
282
- }
283
- });
284
- Object.defineProperty(exports, 'createConfigContext', {
285
- enumerable: true,
286
- get: function () {
287
- return createConfigContext;
288
- }
289
- });
290
- Object.defineProperty(exports, 'getActiveConfig', {
291
- enumerable: true,
292
- get: function () {
293
- return getActiveConfig;
294
- }
295
- });
296
- Object.defineProperty(exports, 'setActiveConfig', {
297
- enumerable: true,
298
- get: function () {
299
- return setActiveConfig;
300
- }
301
- });