@kjanat/dreamcli 3.0.1 → 4.0.0-rc.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.
Files changed (137) hide show
  1. package/CHANGELOG.md +962 -1
  2. package/README.md +7 -3
  3. package/dist/core/cli/builtins.d.mts +47 -0
  4. package/dist/core/cli/builtins.mjs +135 -0
  5. package/dist/core/cli/compiled.d.mts +29 -0
  6. package/dist/core/cli/compiled.mjs +76 -0
  7. package/dist/core/cli/dispatch.d.mts +9 -85
  8. package/dist/core/cli/help-links.d.mts +2 -14
  9. package/dist/core/cli/index.d.mts +282 -101
  10. package/dist/core/cli/index.mjs +497 -264
  11. package/dist/core/cli/planner.d.mts +13 -86
  12. package/dist/core/cli/planner.mjs +47 -30
  13. package/dist/core/cli/plugin.d.mts +1 -1
  14. package/dist/core/cli/propagate.mjs +1 -1
  15. package/dist/core/cli/reserved-flags.d.mts +1 -0
  16. package/dist/core/cli/reserved-flags.mjs +158 -0
  17. package/dist/core/cli/root-help.d.mts +1 -47
  18. package/dist/core/cli/root-help.mjs +37 -47
  19. package/dist/core/cli/root-output-flags.d.mts +1 -0
  20. package/dist/core/cli/root-output-flags.mjs +169 -0
  21. package/dist/core/cli/root-surface.d.mts +1 -68
  22. package/dist/core/cli/root-surface.mjs +2 -2
  23. package/dist/core/cli/runtime-preflight.d.mts +1 -199
  24. package/dist/core/cli/runtime-preflight.mjs +67 -17
  25. package/dist/core/completion/index.d.mts +2 -2
  26. package/dist/core/completion/shells/bash.d.mts +0 -1
  27. package/dist/core/completion/shells/bash.mjs +2 -1
  28. package/dist/core/completion/shells/fish.d.mts +0 -1
  29. package/dist/core/completion/shells/fish.mjs +2 -1
  30. package/dist/core/completion/shells/powershell.d.mts +0 -1
  31. package/dist/core/completion/shells/powershell.mjs +2 -1
  32. package/dist/core/completion/shells/shared.d.mts +3 -114
  33. package/dist/core/completion/shells/shared.mjs +9 -39
  34. package/dist/core/completion/shells/zsh.d.mts +0 -1
  35. package/dist/core/completion/shells/zsh.mjs +2 -1
  36. package/dist/core/config/index.d.mts +3 -3
  37. package/dist/core/config/index.mjs +2 -2
  38. package/dist/core/config/package-json.d.mts +2 -33
  39. package/dist/core/config/package-json.mjs +1 -34
  40. package/dist/core/errors/index.d.mts +7 -7
  41. package/dist/core/execution/index.d.mts +1 -48
  42. package/dist/core/execution/index.mjs +42 -27
  43. package/dist/core/help/ansi.d.mts +0 -11
  44. package/dist/core/help/index.d.mts +3 -35
  45. package/dist/core/help/index.mjs +29 -6
  46. package/dist/core/help/theme.d.mts +1 -21
  47. package/dist/core/json-schema/index.d.mts +279 -10
  48. package/dist/core/json-schema/index.mjs +482 -237
  49. package/dist/core/json-schema/meta-descriptions.generated.d.mts +79 -7
  50. package/dist/core/json-schema/meta-descriptions.generated.mjs +40 -6
  51. package/dist/core/output/activity.d.mts +1 -193
  52. package/dist/core/output/activity.mjs +1 -1
  53. package/dist/core/output/bind.d.mts +1 -37
  54. package/dist/core/output/contracts.d.mts +7 -13
  55. package/dist/core/output/contracts.mjs +1 -1
  56. package/dist/core/output/display-value.d.mts +1 -19
  57. package/dist/core/output/index.d.mts +5 -187
  58. package/dist/core/output/index.mjs +44 -9
  59. package/dist/core/output/renderers.d.mts +1 -45
  60. package/dist/core/output/writer.d.mts +0 -1
  61. package/dist/core/parse/index.d.mts +27 -5
  62. package/dist/core/parse/index.mjs +350 -227
  63. package/dist/core/parse/occurrences.d.mts +89 -0
  64. package/dist/core/parse/occurrences.mjs +114 -0
  65. package/dist/core/prompt/index.d.mts +3 -3
  66. package/dist/core/read-flags/index.d.mts +150 -0
  67. package/dist/core/read-flags/index.mjs +217 -0
  68. package/dist/core/resolve/args.d.mts +35 -4
  69. package/dist/core/resolve/args.mjs +132 -55
  70. package/dist/core/resolve/coerce.d.mts +66 -9
  71. package/dist/core/resolve/coerce.mjs +834 -270
  72. package/dist/core/resolve/config.d.mts +1 -10
  73. package/dist/core/resolve/contracts.d.mts +67 -44
  74. package/dist/core/resolve/errors.mjs +29 -21
  75. package/dist/core/resolve/flags.d.mts +36 -9
  76. package/dist/core/resolve/flags.mjs +129 -151
  77. package/dist/core/resolve/index.d.mts +8 -6
  78. package/dist/core/resolve/index.mjs +51 -18
  79. package/dist/core/resolve/path-checks.d.mts +47 -0
  80. package/dist/core/resolve/path-checks.mjs +102 -0
  81. package/dist/core/resolve/redaction.d.mts +12 -0
  82. package/dist/core/resolve/redaction.mjs +14 -0
  83. package/dist/core/resolve/stages.d.mts +85 -0
  84. package/dist/core/resolve/stages.mjs +170 -0
  85. package/dist/core/resolve/standard.d.mts +1 -24
  86. package/dist/core/resolve/standard.mjs +141 -43
  87. package/dist/core/schema/activity.d.mts +16 -16
  88. package/dist/core/schema/arg.d.mts +849 -71
  89. package/dist/core/schema/arg.mjs +727 -54
  90. package/dist/core/schema/brand.d.mts +17 -0
  91. package/dist/core/schema/cardinality.d.mts +301 -0
  92. package/dist/core/schema/cardinality.mjs +514 -0
  93. package/dist/core/schema/command.d.mts +173 -119
  94. package/dist/core/schema/command.mjs +305 -42
  95. package/dist/core/schema/flag.d.mts +515 -173
  96. package/dist/core/schema/flag.mjs +576 -78
  97. package/dist/core/schema/index.d.mts +11 -8
  98. package/dist/core/schema/index.mjs +10 -0
  99. package/dist/core/schema/middleware.d.mts +15 -12
  100. package/dist/core/schema/number-constraints.d.mts +5 -5
  101. package/dist/core/schema/prompt.d.mts +4 -4
  102. package/dist/core/schema/provenance.d.mts +99 -0
  103. package/dist/core/schema/provenance.mjs +28 -0
  104. package/dist/core/schema/run.d.mts +21 -60
  105. package/dist/core/schema/source.d.mts +179 -0
  106. package/dist/core/schema/source.mjs +206 -0
  107. package/dist/core/schema/standard.d.mts +12 -19
  108. package/dist/core/schema/stdin.d.mts +87 -0
  109. package/dist/core/schema/stdin.mjs +91 -0
  110. package/dist/core/schema/string-constraints.d.mts +16 -5
  111. package/dist/core/schema/string-constraints.mjs +18 -1
  112. package/dist/core/schema/value-parsers.d.mts +81 -9
  113. package/dist/core/schema/value-parsers.mjs +19 -1
  114. package/dist/core/schema/value.d.mts +242 -0
  115. package/dist/core/schema/value.mjs +573 -0
  116. package/dist/core/testkit/index.d.mts +30 -3
  117. package/dist/core/testkit/index.mjs +40 -26
  118. package/dist/index.d.mts +21 -16
  119. package/dist/index.mjs +10 -6
  120. package/dist/runtime/adapter.d.mts +3 -3
  121. package/dist/runtime/deno.d.mts +3 -3
  122. package/dist/runtime/detect.d.mts +2 -2
  123. package/dist/runtime/node.d.mts +3 -3
  124. package/dist/runtime/paths.d.mts +1 -31
  125. package/dist/runtime.d.mts +4 -4
  126. package/dist/strings.d.mts +1 -16
  127. package/dist/testkit.d.mts +2 -2
  128. package/dist/testkit.mjs +1 -1
  129. package/dist/version.d.mts +0 -13
  130. package/dist/version.mjs +2 -2
  131. package/dreamcli.schema.json +368 -78
  132. package/examples/interactive.ts +6 -5
  133. package/package.json +12 -11
  134. package/skills/cli-creation/SKILL.md +72 -16
  135. package/skills/cli-creation/references/pattern-cookbook.md +169 -11
  136. package/dist/core/resolve/property.d.mts +0 -51
  137. package/dist/core/resolve/property.mjs +0 -53
@@ -1,10 +1 @@
1
- //#region src/core/resolve/config.d.ts
2
- /**
3
- * Internal resolver config helpers.
4
- *
5
- * @module dreamcli/core/resolve/config
6
- * @internal
7
- */
8
- declare function resolveConfigPath(config: Readonly<Record<string, unknown>>, path: string): unknown;
9
- //#endregion
10
- export { resolveConfigPath };
1
+ export {}
@@ -1,38 +1,42 @@
1
- import { PromptEngine } from "../prompt/index.mjs";
1
+ import { ResolutionProvenance } from "../schema/provenance.mjs";
2
2
  import { CommandSchema } from "../schema/command.mjs";
3
+ import { PromptEngine } from "../prompt/index.mjs";
3
4
  import "../schema/index.mjs";
4
- import { ParseResult } from "../parse/index.mjs";
5
+ import { RESOLUTION_ORDER, ResolutionStage } from "../schema/source.mjs";
5
6
  //#region src/core/resolve/contracts.d.ts
6
- /** Ordered flag resolution stages owned by the resolver. */
7
- declare const FLAG_RESOLUTION_ORDER: readonly ["cli", "env", "config", "prompt", "default"];
8
- /** Ordered arg resolution stages owned by the resolver. */
9
- declare const ARG_RESOLUTION_ORDER: readonly ["cli", "stdin", "env", "default"];
10
- /** Stable flag-source labels for precedence and diagnostics. */
11
- type FlagResolutionStage = (typeof FLAG_RESOLUTION_ORDER)[number];
12
- /** Stable arg-source labels for precedence and diagnostics. */
13
- type ArgResolutionStage = (typeof ARG_RESOLUTION_ORDER)[number];
14
7
  /**
15
- * Source-aware diagnostic context for flag resolution failures.
8
+ * Source-aware diagnostic context for a resolution failure.
16
9
  *
17
- * CLI/default failures currently surface as missing-value validation errors,
18
- * so only env/config/prompt need explicit source payloads here.
10
+ * `'cli'` covers the tokens the user typed, which a message names by the input
11
+ * alone; the other stages each carry what a message needs to point at the value
12
+ * they produced. Both surfaces read the same set.
19
13
  */
20
- type FlagDiagnosticSource = {
21
- readonly kind: 'env';
14
+ type ResolutionDiagnosticSource = {
15
+ readonly kind: "cli";
16
+ } | {
17
+ readonly kind: "stdin";
18
+ } | {
19
+ readonly kind: "env";
22
20
  readonly envVar: string;
23
21
  } | {
24
- readonly kind: 'config';
22
+ readonly kind: "config";
25
23
  readonly configPath: string;
26
24
  } | {
27
- readonly kind: 'prompt';
25
+ readonly kind: "prompt";
28
26
  };
27
+ /**
28
+ * The sources whose raw values a resolution stage decodes.
29
+ *
30
+ * A CLI token is decoded at the parse boundary, so it never reaches the
31
+ * coercion diagnostics these name.
32
+ */
33
+ type DecodedDiagnosticSource = Exclude<ResolutionDiagnosticSource, {
34
+ readonly kind: "cli";
35
+ }>;
36
+ /** Source-aware diagnostic context for flag resolution failures. */
37
+ type FlagDiagnosticSource = DecodedDiagnosticSource;
29
38
  /** Source-aware diagnostic context for arg resolution failures. */
30
- type ArgDiagnosticSource = {
31
- readonly kind: 'env';
32
- readonly envVar: string;
33
- } | {
34
- readonly kind: 'stdin';
35
- };
39
+ type ArgDiagnosticSource = DecodedDiagnosticSource;
36
40
  /**
37
41
  * External state the resolver may consult after parsing.
38
42
  *
@@ -49,25 +53,39 @@ interface ResolveOptions {
49
53
  /** Interactive prompt engine; absent in non-TTY / CI contexts. */
50
54
  readonly prompter?: PromptEngine;
51
55
  /**
52
- * Filesystem probe for `flag.path()` checks: what exists at the path, or
53
- * `null` when nothing does. When absent, path checks are skipped.
56
+ * Filesystem probe for `flag.path()` and `arg.path()` checks: what exists
57
+ * at the path, or `null` when nothing does. When absent, path checks are
58
+ * skipped.
54
59
  */
55
- readonly stat?: (path: string) => Promise<'file' | 'directory' | null>;
60
+ readonly stat?: (path: string) => Promise<"file" | "directory" | null>;
56
61
  /**
57
- * Recursive directory creation for `flag.path()` `create` checks. When
58
- * absent, missing paths are not created and existence rules apply as-is.
62
+ * Recursive directory creation for `flag.path()` and `arg.path()` `create`
63
+ * checks. When absent, missing paths are not created and existence rules
64
+ * apply as-is.
59
65
  */
60
66
  readonly mkdir?: (path: string) => Promise<void>;
61
67
  }
62
68
  /** Structured deprecation notice emitted for explicitly sourced values. */
63
69
  interface DeprecationWarning {
64
70
  /** Whether this deprecation targets a flag or a positional arg. */
65
- readonly kind: 'flag' | 'arg';
71
+ readonly kind: "flag" | "arg";
66
72
  /** Name of the deprecated flag or arg. */
67
73
  readonly name: string;
68
74
  /** Custom deprecation message, or `true` for the generic warning. */
69
75
  readonly message: string | true;
70
76
  }
77
+ /**
78
+ * Which stage produced each resolved value of one command.
79
+ *
80
+ * The erased form of {@link InputSources}: same records, keyed by plain strings
81
+ * because `resolve()` takes a `CommandSchema` rather than typed builders.
82
+ */
83
+ interface ResolutionProvenanceRecord {
84
+ /** Provenance of every declared flag, keyed by flag name. */
85
+ readonly flags: Readonly<Record<string, ResolutionProvenance>>;
86
+ /** Provenance of every declared arg, keyed by arg name. */
87
+ readonly args: Readonly<Record<string, ResolutionProvenance>>;
88
+ }
71
89
  /** Fully resolved command input handed to the executor layer. */
72
90
  interface ResolveResult {
73
91
  /** Fully resolved flag values keyed by flag name. */
@@ -76,6 +94,11 @@ interface ResolveResult {
76
94
  readonly args: Readonly<Record<string, unknown>>;
77
95
  /** Deprecation notices collected during resolution (may be empty). */
78
96
  readonly deprecations: readonly DeprecationWarning[];
97
+ /**
98
+ * Which stage produced each value. Present only for inputs that resolved a
99
+ * value, so an unset optional input has no entry.
100
+ */
101
+ readonly provenance: ResolutionProvenanceRecord;
79
102
  }
80
103
  /** Explicit invocation boundary between parser output and resolved values. */
81
104
  interface ResolverInvocation {
@@ -93,30 +116,30 @@ interface ResolverInvocation {
93
116
  * extraction and diagnostic redesign work lands.
94
117
  */
95
118
  interface ResolverContract {
96
- /** Ordered stages for flag resolution: cli -> env -> config -> prompt -> default. */
97
- readonly flagPrecedence: readonly FlagResolutionStage[];
98
- /** Ordered stages for arg resolution: cli -> stdin -> env -> default. */
99
- readonly argPrecedence: readonly ArgResolutionStage[];
119
+ /** Ordered stages both surfaces walk: cli -> stdin -> env -> config -> prompt -> default. */
120
+ readonly precedence: readonly ResolutionStage[];
121
+ /** Flags and args resolve through the same ordered stages. */
122
+ readonly flagPrecedence: readonly ResolutionStage[];
123
+ /** Flags and args resolve through the same ordered stages. */
124
+ readonly argPrecedence: readonly ResolutionStage[];
100
125
  /** Prompt stage runs only after env and config have been attempted. */
101
126
  readonly promptRunsAfterFlagConfig: true;
127
+ /** The implicit stdin fallback runs before env, so stdin outranks the environment. */
128
+ readonly stdinFallbackRunsBeforeEnv: true;
129
+ /** An explicit `-` is CLI-sourced with bytes from stdin and keeps CLI precedence. */
130
+ readonly dashIsCliSourced: true;
102
131
  /** All validation errors are collected before throwing a single aggregate. */
103
132
  readonly aggregatesValidationErrors: true;
104
133
  /** Aggregate error details include per-issue structured summaries. */
105
134
  readonly aggregateDiagnosticsIncludePerIssueSummary: true;
106
- /** A coercion failure at env/config stops fallback to later stages for that flag. */
135
+ /** A coercion failure at any sourced stage stops fallback to later stages for that input. */
107
136
  readonly hardCoercionErrorsStopFallback: true;
108
137
  /** Deprecation warnings are emitted only when a value was actually sourced. */
109
138
  readonly collectsDeprecationsFromExplicitSources: true;
139
+ /** Every resolved value records the stage that produced it. */
140
+ readonly recordsProvenancePerInput: true;
110
141
  }
111
142
  /** Runtime-accessible resolution contract — documents the resolver's invariants for tests and diagnostics. */
112
- declare const resolverContract: {
113
- flagPrecedence: readonly ["cli", "env", "config", "prompt", "default"];
114
- argPrecedence: readonly ["cli", "stdin", "env", "default"];
115
- promptRunsAfterFlagConfig: true;
116
- aggregatesValidationErrors: true;
117
- aggregateDiagnosticsIncludePerIssueSummary: true;
118
- hardCoercionErrorsStopFallback: true;
119
- collectsDeprecationsFromExplicitSources: true;
120
- };
143
+ declare const resolverContract: ResolverContract;
121
144
  //#endregion
122
- export { ARG_RESOLUTION_ORDER, type ArgDiagnosticSource, type ArgResolutionStage, type DeprecationWarning, FLAG_RESOLUTION_ORDER, type FlagDiagnosticSource, type FlagResolutionStage, type ResolveOptions, type ResolveResult, type ResolverContract, type ResolverInvocation, resolverContract };
145
+ export { type ArgDiagnosticSource, type DecodedDiagnosticSource, type DeprecationWarning, type FlagDiagnosticSource, RESOLUTION_ORDER, type ResolutionDiagnosticSource, type ResolutionProvenance, type ResolutionProvenanceRecord, type ResolveOptions, type ResolveResult, type ResolverContract, type ResolverInvocation, resolverContract };
@@ -7,30 +7,38 @@ function readStringProperty(record, key) {
7
7
  const value = Reflect.get(record, key);
8
8
  return typeof value === "string" ? value : void 0;
9
9
  }
10
- function hasValueProperty(record, key) {
11
- return Object.hasOwn(record, key);
12
- }
10
+ /**
11
+ * Name the stage a failure came from, for the aggregate's per-issue label.
12
+ *
13
+ * Only a failure to read a value carries `source`. A missing required input
14
+ * names the env var it would have accepted without claiming the environment
15
+ * produced anything.
16
+ */
13
17
  function describeIssueSource(details) {
14
- const explicitSource = readStringProperty(details, "source");
15
- if (explicitSource === "stdin") return {
16
- kind: "stdin",
17
- label: "stdin"
18
- };
19
- if (explicitSource === "prompt") return {
20
- kind: "prompt",
21
- label: "prompt"
22
- };
23
- if (hasValueProperty(details, "value")) {
24
- const envVar = readStringProperty(details, "envVar");
25
- if (envVar !== void 0) return {
26
- kind: "env",
27
- label: `env ${envVar}`
18
+ switch (readStringProperty(details, "source")) {
19
+ case "stdin": return {
20
+ kind: "stdin",
21
+ label: "stdin"
28
22
  };
29
- const configPath = readStringProperty(details, "configPath");
30
- if (configPath !== void 0) return {
31
- kind: "config",
32
- label: `config ${configPath}`
23
+ case "prompt": return {
24
+ kind: "prompt",
25
+ label: "prompt"
33
26
  };
27
+ case "env": {
28
+ const envVar = readStringProperty(details, "envVar");
29
+ return envVar === void 0 ? void 0 : {
30
+ kind: "env",
31
+ label: `env ${envVar}`
32
+ };
33
+ }
34
+ case "config": {
35
+ const configPath = readStringProperty(details, "configPath");
36
+ return configPath === void 0 ? void 0 : {
37
+ kind: "config",
38
+ label: `config ${configPath}`
39
+ };
40
+ }
41
+ default: return;
34
42
  }
35
43
  }
36
44
  function summarizeValidationError(error) {
@@ -1,20 +1,47 @@
1
1
  import { PromptKind } from "../schema/prompt.mjs";
2
2
  import { FlagKind, FlagSchema } from "../schema/flag.mjs";
3
+ import { ResolutionProvenance } from "../schema/provenance.mjs";
4
+ import { ErasedInteractiveResolver } from "../schema/command.mjs";
3
5
  import { PromptEngine } from "../prompt/index.mjs";
4
6
  import { DeprecationWarning } from "./contracts.mjs";
5
- import { ErasedInteractiveResolver } from "../schema/command.mjs";
7
+ import { MkdirFn, StatFn } from "./path-checks.mjs";
6
8
  //#region src/core/resolve/flags.d.ts
9
+ /** External state and collectors one flag-resolution pass shares. */
10
+ interface FlagResolutionOptions {
11
+ /** Environment variable snapshot. */
12
+ readonly env: Readonly<Record<string, string | undefined>>;
13
+ /** Parsed config file contents. */
14
+ readonly config: Readonly<Record<string, unknown>>;
15
+ /** Pre-read stdin content, or `null`/`undefined` when nothing was piped. */
16
+ readonly stdinData: string | null | undefined;
17
+ /** Interactive prompt engine, absent in non-TTY contexts. */
18
+ readonly prompter: PromptEngine | undefined;
19
+ /** Per-invocation prompt overrides declared by `.interactive()`. */
20
+ readonly interactive: ErasedInteractiveResolver | undefined;
21
+ /** Collector for notices produced by `.deprecated()` flags. */
22
+ readonly deprecations: DeprecationWarning[];
23
+ /** Filesystem probe for `flag.path()` checks. */
24
+ readonly stat: StatFn | undefined;
25
+ /** Directory creation for `flag.path()` `create` checks. */
26
+ readonly mkdir: MkdirFn | undefined;
27
+ /** Receiver for the stage that produced each resolved flag. */
28
+ readonly provenance: Record<string, ResolutionProvenance>;
29
+ }
7
30
  /**
8
- * Filesystem probe injected by the caller for `flag.path()` checks.
31
+ * Walk every declared flag through the resolution chain
32
+ * (cli -> stdin -> env -> config -> prompt -> default), collecting deprecations
33
+ * and throwing aggregated errors.
34
+ *
35
+ * The chain runs in two passes so `.interactive()` sees what the non-interactive
36
+ * sources produced before it decides which flags to prompt for.
9
37
  *
10
- * Returns what exists at the path, or `null` when nothing does.
38
+ * @param flagSchemas - Declared flags keyed by canonical name.
39
+ * @param parsedFlags - Values the parser read off argv.
40
+ * @param options - External state and collectors for this pass.
41
+ * @returns Fully resolved flag values keyed by flag name.
11
42
  */
12
- type StatFn = (path: string) => Promise<'file' | 'directory' | null>;
13
- /** Recursive directory creation injected by the caller for `flag.path()` `create` checks. */
14
- type MkdirFn = (path: string) => Promise<void>;
15
- /** Walk every declared flag through the resolution chain (cli -> env -> config -> prompt -> default), collecting deprecations and throwing aggregated errors. */
16
- declare function resolveFlags(flagSchemas: Readonly<Record<string, FlagSchema>>, parsedFlags: Readonly<Record<string, unknown>>, env: Readonly<Record<string, string | undefined>>, config: Readonly<Record<string, unknown>>, prompter: PromptEngine | undefined, interactive: ErasedInteractiveResolver | undefined, deprecations: DeprecationWarning[], stat: StatFn | undefined, mkdir: MkdirFn | undefined): Promise<Readonly<Record<string, unknown>>>;
43
+ declare function resolveFlags(flagSchemas: Readonly<Record<string, FlagSchema>>, parsedFlags: Readonly<Record<string, unknown>>, options: FlagResolutionOptions): Promise<Readonly<Record<string, unknown>>>;
17
44
  /** Maps each flag kind to the prompt kinds that produce compatible values. */
18
45
  declare const COMPATIBLE_PROMPT_KINDS: Record<FlagKind, readonly PromptKind[]>;
19
46
  //#endregion
20
- export { COMPATIBLE_PROMPT_KINDS, resolveFlags };
47
+ export { COMPATIBLE_PROMPT_KINDS, type FlagResolutionOptions, resolveFlags };
@@ -1,8 +1,13 @@
1
1
  import { ValidationError } from "../errors/index.mjs";
2
+ import { flagValueSchema, valueEnumValues } from "../schema/value.mjs";
3
+ import { dedupe } from "../schema/cardinality.mjs";
4
+ import { bindingsBeforePrompt, bindingsFromPrompt, sourceBindings, withPromptBinding } from "../schema/source.mjs";
2
5
  import { resolvePromptConfig } from "../prompt/index.mjs";
3
- import { coerceValue } from "./coerce.mjs";
6
+ import { echoesValue } from "./redaction.mjs";
7
+ import { coerceValue, finishCliFlagValue } from "./coerce.mjs";
4
8
  import { isNonEmpty, throwAggregatedErrors } from "./errors.mjs";
5
- import { resolveConfigPath } from "./config.mjs";
9
+ import { pathValuesOf, validatePathChecks } from "./path-checks.mjs";
10
+ import { readCliValue, runStages } from "./stages.mjs";
6
11
  //#region src/core/resolve/flags.ts
7
12
  /**
8
13
  * Internal flag resolution helpers.
@@ -10,99 +15,47 @@ import { resolveConfigPath } from "./config.mjs";
10
15
  * @module dreamcli/core/resolve/flags
11
16
  * @internal
12
17
  */
13
- /** Walk every declared flag through the resolution chain (cli -> env -> config -> prompt -> default), collecting deprecations and throwing aggregated errors. */
14
- async function resolveFlags(flagSchemas, parsedFlags, env, config, prompter, interactive, deprecations, stat, mkdir) {
18
+ /**
19
+ * Walk every declared flag through the resolution chain
20
+ * (cli -> stdin -> env -> config -> prompt -> default), collecting deprecations
21
+ * and throwing aggregated errors.
22
+ *
23
+ * The chain runs in two passes so `.interactive()` sees what the non-interactive
24
+ * sources produced before it decides which flags to prompt for.
25
+ *
26
+ * @param flagSchemas - Declared flags keyed by canonical name.
27
+ * @param parsedFlags - Values the parser read off argv.
28
+ * @param options - External state and collectors for this pass.
29
+ * @returns Fully resolved flag values keyed by flag name.
30
+ */
31
+ async function resolveFlags(flagSchemas, parsedFlags, options) {
15
32
  const resolved = {};
16
33
  const errors = [];
17
34
  const hardErrorFlags = /* @__PURE__ */ new Set();
35
+ const state = {
36
+ env: options.env,
37
+ config: options.config,
38
+ stdinData: options.stdinData,
39
+ canPrompt: options.prompter !== void 0
40
+ };
18
41
  for (const [name, schema] of Object.entries(flagSchemas)) {
19
- const hasParsedValue = Object.hasOwn(parsedFlags, name);
20
- const parsedValue = parsedFlags[name];
21
- if (hasParsedValue && parsedValue !== void 0) {
22
- if (schema.deprecated !== void 0) deprecations.push({
23
- kind: "flag",
24
- name,
25
- message: schema.deprecated
26
- });
27
- resolved[name] = parsedValue;
28
- continue;
29
- }
30
- if (schema.envVar !== void 0) {
31
- const envValue = env[schema.envVar];
32
- if (envValue !== void 0) {
33
- const coerced = coerceValue(name, {
34
- kind: "env",
35
- envVar: schema.envVar
36
- }, envValue, schema);
37
- if (coerced.ok) {
38
- if (schema.deprecated !== void 0) deprecations.push({
39
- kind: "flag",
40
- name,
41
- message: schema.deprecated
42
- });
43
- resolved[name] = coerced.value;
44
- continue;
45
- }
46
- errors.push(coerced.error);
47
- hardErrorFlags.add(name);
48
- continue;
49
- }
50
- }
51
- if (schema.configPath !== void 0) {
52
- const configValue = resolveConfigPath(config, schema.configPath);
53
- if (configValue !== void 0) {
54
- const coerced = coerceValue(name, {
55
- kind: "config",
56
- configPath: schema.configPath
57
- }, configValue, schema);
58
- if (coerced.ok) {
59
- if (schema.deprecated !== void 0) deprecations.push({
60
- kind: "flag",
61
- name,
62
- message: schema.deprecated
63
- });
64
- resolved[name] = coerced.value;
65
- continue;
66
- }
67
- errors.push(coerced.error);
68
- hardErrorFlags.add(name);
69
- }
70
- }
42
+ const bindings = sourceBindings(schema);
43
+ record(name, schema, await runStages(bindingsBeforePrompt(bindings), stageInput(name, schema, parsedFlags, bindings, options.prompter), state), resolved, errors, hardErrorFlags, options);
71
44
  }
72
- const interactiveConfigs = interactive !== void 0 ? interactive({ flags: resolved }) : void 0;
45
+ const interactiveConfigs = options.interactive !== void 0 ? options.interactive({ flags: resolved }) : void 0;
73
46
  for (const [name, schema] of Object.entries(flagSchemas)) {
74
47
  if (Object.hasOwn(resolved, name) || hardErrorFlags.has(name)) continue;
75
- const interactiveConfig = interactiveConfigs?.[name];
76
- let effectivePromptConfig;
77
- if (interactiveConfig !== void 0 && interactiveConfig !== null && interactiveConfig !== false && interactiveConfig !== 0 && interactiveConfig !== "") effectivePromptConfig = interactiveConfig;
78
- else if (interactiveConfig === false) effectivePromptConfig = void 0;
79
- else effectivePromptConfig = schema.prompt;
80
- if (effectivePromptConfig !== void 0 && prompter !== void 0) {
81
- const promptResult = await resolvePromptValueWithConfig(name, schema, effectivePromptConfig, prompter);
82
- if (promptResult.ok) {
83
- if (schema.deprecated !== void 0) deprecations.push({
84
- kind: "flag",
85
- name,
86
- message: schema.deprecated
87
- });
88
- resolved[name] = promptResult.value;
89
- continue;
90
- }
91
- if (promptResult.error !== void 0) {
92
- errors.push(promptResult.error);
93
- continue;
94
- }
95
- }
96
- if (schema.defaultValue !== void 0) {
97
- resolved[name] = schema.defaultValue;
98
- continue;
99
- }
48
+ const bindings = withPromptBinding(schema, sourceBindings(schema), effectivePromptConfig(name, schema, interactiveConfigs));
49
+ record(name, schema, await runStages(bindingsFromPrompt(bindings), stageInput(name, schema, parsedFlags, bindings, options.prompter), state), resolved, errors, hardErrorFlags, options);
50
+ if (Object.hasOwn(resolved, name) || hardErrorFlags.has(name)) continue;
100
51
  if (schema.kind === "array" && schema.presence !== "required") {
101
52
  resolved[name] = [];
53
+ options.provenance[name] = { stage: "default" };
102
54
  continue;
103
55
  }
104
56
  if (schema.kind === "keyValue" && schema.presence !== "required") {
105
57
  resolved[name] = {};
58
+ options.provenance[name] = { stage: "default" };
106
59
  continue;
107
60
  }
108
61
  if (schema.presence === "required") {
@@ -122,61 +75,62 @@ async function resolveFlags(flagSchemas, parsedFlags, env, config, prompter, int
122
75
  resolved[name] = void 0;
123
76
  }
124
77
  for (const [name, schema] of Object.entries(flagSchemas)) {
125
- const value = resolved[name];
126
- if (schema.kind === "array" && schema.unique && Array.isArray(value)) resolved[name] = [...new Set(value)];
127
- if (schema.pathChecks !== void 0 && typeof value === "string" && stat !== void 0) {
128
- const violation = await validatePathChecks(name, value, schema.pathChecks, stat, mkdir);
78
+ const value = Object.hasOwn(resolved, name) ? resolved[name] : void 0;
79
+ const checks = flagValueSchema(schema).pathChecks;
80
+ if (schema.kind === "array" && schema.unique && Array.isArray(value)) resolved[name] = [...dedupe(value)];
81
+ if (checks === void 0 || options.stat === void 0) continue;
82
+ const echo = echoesValue(Object.hasOwn(options.provenance, name) ? options.provenance[name] : void 0);
83
+ for (const path of pathValuesOf(Object.hasOwn(resolved, name) ? resolved[name] : void 0)) {
84
+ const violation = await validatePathChecks({
85
+ kind: "flag",
86
+ name
87
+ }, path, checks, options.stat, options.mkdir, echo);
129
88
  if (violation !== void 0) errors.push(violation);
130
89
  }
131
90
  }
132
91
  if (isNonEmpty(errors)) throwAggregatedErrors(errors);
133
92
  return resolved;
134
93
  }
94
+ /** Assemble what one flag contributes to its own resolution. */
95
+ function stageInput(name, schema, parsedFlags, bindings, prompter) {
96
+ const present = Object.hasOwn(parsedFlags, name);
97
+ return {
98
+ cli: readCliValue(present, present ? parsedFlags[name] : void 0, bindings),
99
+ coerce: (binding, raw) => coerceValue(name, binding, raw, schema),
100
+ finishCli: (value, stdinData, stdin) => finishCliFlagValue(name, schema, value, stdinData, stdin),
101
+ runPrompt: async (binding) => prompter === void 0 ? {
102
+ ok: false,
103
+ error: void 0
104
+ } : resolvePromptValueWithConfig(name, schema, binding, prompter)
105
+ };
106
+ }
107
+ /** Apply one stage walk's outcome to the resolution state. */
108
+ function record(name, schema, outcome, resolved, errors, hardErrorFlags, options) {
109
+ if (outcome.kind === "error") {
110
+ errors.push(outcome.error);
111
+ hardErrorFlags.add(name);
112
+ return;
113
+ }
114
+ if (outcome.kind === "absent") return;
115
+ if (schema.deprecated !== void 0 && outcome.provenance.stage !== "default") options.deprecations.push({
116
+ kind: "flag",
117
+ name,
118
+ message: schema.deprecated
119
+ });
120
+ resolved[name] = outcome.value;
121
+ options.provenance[name] = outcome.provenance;
122
+ }
135
123
  /**
136
- * Check a resolved path value against its declared filesystem expectations.
124
+ * Pick the prompt config this invocation uses for a flag.
137
125
  *
138
- * @returns `undefined` when the path satisfies the checks, or a
139
- * {@link ValidationError} with code `'CONSTRAINT_VIOLATED'` otherwise.
140
- * @internal
126
+ * `.interactive()` returning `false` disables the prompt outright; any other
127
+ * falsy value means "no override" and leaves the schema's own config in place.
141
128
  */
142
- async function validatePathChecks(flagName, value, checks, stat, mkdir) {
143
- const found = await stat(value);
144
- if (found === null) {
145
- if (checks.create && mkdir !== void 0) try {
146
- await mkdir(value);
147
- return;
148
- } catch (error) {
149
- return new ValidationError(`Failed to create directory '${value}' for flag --${flagName}: ${error instanceof Error ? error.message : String(error)}`, {
150
- code: "CONSTRAINT_VIOLATED",
151
- details: {
152
- flag: flagName,
153
- value,
154
- constraint: "create"
155
- },
156
- suggest: `Provide a creatable or existing directory path for --${flagName}`
157
- });
158
- }
159
- if (!checks.mustExist) return void 0;
160
- return new ValidationError(`Path '${value}' for flag --${flagName} does not exist`, {
161
- code: "CONSTRAINT_VIOLATED",
162
- details: {
163
- flag: flagName,
164
- value,
165
- constraint: "mustExist"
166
- },
167
- suggest: `Provide an existing path for --${flagName}`
168
- });
169
- }
170
- if (checks.type !== void 0 && found !== checks.type) return new ValidationError(`Path '${value}' for flag --${flagName} is a ${found}, expected a ${checks.type}`, {
171
- code: "CONSTRAINT_VIOLATED",
172
- details: {
173
- flag: flagName,
174
- value,
175
- constraint: "pathType",
176
- expected: checks.type
177
- },
178
- suggest: `Provide a ${checks.type} path for --${flagName}`
179
- });
129
+ function effectivePromptConfig(name, schema, interactiveConfigs) {
130
+ const override = interactiveConfigs !== void 0 && Object.hasOwn(interactiveConfigs, name) ? interactiveConfigs[name] : void 0;
131
+ if (override === false) return void 0;
132
+ if (override === void 0 || override === null || override === 0 || override === "") return schema.prompt;
133
+ return override;
180
134
  }
181
135
  /** Maps each flag kind to the prompt kinds that produce compatible values. */
182
136
  const COMPATIBLE_PROMPT_KINDS = {
@@ -195,6 +149,39 @@ const COMPATIBLE_PROMPT_KINDS = {
195
149
  keyValue: []
196
150
  };
197
151
  /**
152
+ * Word an incompatible prompt config for the surface that declared it.
153
+ *
154
+ * A kind with no compatible prompt at all is a different diagnostic from one
155
+ * whose prompt is merely the wrong sort, so the empty list gets its own message
156
+ * on both surfaces.
157
+ *
158
+ * @param subject - How the surface spells the input.
159
+ * @param kind - The input's declared kind.
160
+ * @param promptKind - The prompt kind the config asked for.
161
+ * @param allowed - The prompt kinds that kind accepts.
162
+ * @returns The error to report.
163
+ * @internal
164
+ */
165
+ function promptCompatibilityError(subject, kind, promptKind, allowed) {
166
+ const details = {
167
+ ...subject.details,
168
+ promptKind,
169
+ allowed
170
+ };
171
+ const headline = `Prompt kind '${promptKind}' is not compatible with ${kind} ${subject.singular} ${subject.reference}.`;
172
+ const first = allowed[0];
173
+ if (first === void 0) return new ValidationError(`${headline} ${kind} ${subject.plural} are not promptable`, {
174
+ code: "CONSTRAINT_VIOLATED",
175
+ details,
176
+ suggest: `Remove the prompt config for ${subject.reference}`
177
+ });
178
+ return new ValidationError(`${headline} Use '${first}' instead`, {
179
+ code: "CONSTRAINT_VIOLATED",
180
+ details,
181
+ suggest: `Change the prompt to { kind: '${first}' } for ${subject.reference}`
182
+ });
183
+ }
184
+ /**
198
185
  * Check whether a prompt kind is compatible with the flag's declared kind.
199
186
  *
200
187
  * @returns `undefined` when compatible, or a {@link ValidationError} with
@@ -204,27 +191,15 @@ const COMPATIBLE_PROMPT_KINDS = {
204
191
  function validatePromptFlagCompatibility(flagName, flagKind, promptKind) {
205
192
  const allowed = COMPATIBLE_PROMPT_KINDS[flagKind];
206
193
  if (allowed.includes(promptKind)) return void 0;
207
- const first = allowed[0];
208
- if (first === void 0) return new ValidationError(`Prompt kind '${promptKind}' is not compatible with ${flagKind} flag --${flagName}. ${flagKind} flags are not promptable`, {
209
- code: "CONSTRAINT_VIOLATED",
194
+ return promptCompatibilityError({
195
+ reference: `--${flagName}`,
196
+ singular: "flag",
197
+ plural: "flags",
210
198
  details: {
211
199
  flag: flagName,
212
- flagKind,
213
- promptKind,
214
- allowed
215
- },
216
- suggest: `Remove the prompt config for --${flagName}`
217
- });
218
- return new ValidationError(`Prompt kind '${promptKind}' is not compatible with ${flagKind} flag --${flagName}. Use '${first}' instead`, {
219
- code: "CONSTRAINT_VIOLATED",
220
- details: {
221
- flag: flagName,
222
- flagKind,
223
- promptKind,
224
- allowed
225
- },
226
- suggest: `Change the prompt to { kind: '${first}' } for --${flagName}`
227
- });
200
+ flagKind
201
+ }
202
+ }, flagKind, promptKind, allowed);
228
203
  }
229
204
  /**
230
205
  * Validate prompt/flag compatibility, run the prompt engine, and coerce the result.
@@ -234,13 +209,14 @@ function validatePromptFlagCompatibility(flagName, flagKind, promptKind) {
234
209
  * before the prompter is invoked).
235
210
  * @internal
236
211
  */
237
- async function resolvePromptValueWithConfig(flagName, schema, promptConfig, prompter) {
212
+ async function resolvePromptValueWithConfig(flagName, schema, binding, prompter) {
213
+ const promptConfig = binding.prompt;
238
214
  const mismatch = validatePromptFlagCompatibility(flagName, schema.kind, promptConfig.kind);
239
215
  if (mismatch !== void 0) return {
240
216
  ok: false,
241
217
  error: mismatch
242
218
  };
243
- const resolvedConfig = resolvePromptConfig(promptConfig, schema.enumValues);
219
+ const resolvedConfig = resolvePromptConfig(promptConfig, valueEnumValues(flagValueSchema(schema)));
244
220
  const result = await prompter.promptOne(resolvedConfig);
245
221
  if (!result.answered) return {
246
222
  ok: false,
@@ -250,13 +226,15 @@ async function resolvePromptValueWithConfig(flagName, schema, promptConfig, prom
250
226
  ok: false,
251
227
  error: void 0
252
228
  };
253
- return coerceValue(flagName, { kind: "prompt" }, result.value, schema);
229
+ return coerceValue(flagName, binding, result.value, schema);
254
230
  }
255
231
  /** Build a human-readable suggestion listing all available sources for a required flag. @internal */
256
232
  function buildRequiredFlagSuggest(name, schema) {
257
233
  const sources = [];
258
234
  const takesValue = schema.kind !== "boolean" && schema.kind !== "count";
259
235
  sources.push(`Provide --${name}${takesValue ? " <value>" : ""}`);
236
+ const stdin = schema.stdin;
237
+ if (stdin !== void 0) sources.push(stdin.when === "dash" ? `pass --${name} - to read stdin` : stdin.when === "missing" ? `pipe a value to stdin` : `pipe a value to stdin or pass --${name} -`);
260
238
  if (schema.envVar !== void 0) sources.push(`set ${schema.envVar}`);
261
239
  if (schema.configPath !== void 0) sources.push(`add ${schema.configPath} to config`);
262
240
  if (sources.length <= 1) return sources.join("");
@@ -265,4 +243,4 @@ function buildRequiredFlagSuggest(name, schema) {
265
243
  return sources.length === 2 ? `${rest.join("")} or ${last}` : `${rest.join(", ")}, or ${last}`;
266
244
  }
267
245
  //#endregion
268
- export { COMPATIBLE_PROMPT_KINDS, resolveFlags };
246
+ export { COMPATIBLE_PROMPT_KINDS, promptCompatibilityError, resolveFlags };