@kjanat/dreamcli 2.5.0 → 3.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.
- package/CHANGELOG.md +153 -1
- package/README.md +9 -2
- package/dist/core/cli/dispatch.mjs +214 -1
- package/dist/core/cli/help-links.mjs +41 -1
- package/dist/core/cli/index.d.mts +109 -16
- package/dist/core/cli/index.mjs +901 -1
- package/dist/core/cli/planner.d.mts +27 -5
- package/dist/core/cli/planner.mjs +300 -1
- package/dist/core/cli/plugin.mjs +41 -1
- package/dist/core/cli/propagate.mjs +57 -1
- package/dist/core/cli/root-help.d.mts +16 -2
- package/dist/core/cli/root-help.mjs +208 -6
- package/dist/core/cli/root-surface.d.mts +18 -3
- package/dist/core/cli/root-surface.mjs +27 -1
- package/dist/core/cli/runtime-preflight.d.mts +16 -1
- package/dist/core/cli/runtime-preflight.mjs +168 -1
- package/dist/core/completion/index.d.mts +32 -1
- package/dist/core/completion/index.mjs +90 -1
- package/dist/core/completion/shells/bash.mjs +304 -3
- package/dist/core/completion/shells/fish.mjs +159 -2
- package/dist/core/completion/shells/powershell.mjs +353 -2
- package/dist/core/completion/shells/shared.d.mts +10 -0
- package/dist/core/completion/shells/shared.mjs +154 -1
- package/dist/core/completion/shells/zsh.mjs +244 -2
- package/dist/core/config/index.mjs +246 -1
- package/dist/core/config/package-json.mjs +385 -3
- package/dist/core/errors/index.mjs +87 -1
- package/dist/core/execution/index.mjs +189 -1
- package/dist/core/help/ansi.mjs +122 -2
- package/dist/core/help/index.d.mts +45 -1
- package/dist/core/help/index.mjs +329 -7
- package/dist/core/json-schema/index.mjs +487 -9
- package/dist/core/json-schema/meta-descriptions.generated.d.mts +38 -38
- package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
- package/dist/core/output/activity.mjs +452 -1
- package/dist/core/output/bind.mjs +56 -1
- package/dist/core/output/contracts.mjs +57 -1
- package/dist/core/output/display-value.mjs +32 -1
- package/dist/core/output/index.d.mts +21 -0
- package/dist/core/output/index.mjs +442 -2
- package/dist/core/output/renderers.mjs +46 -1
- package/dist/core/output/writer.mjs +12 -1
- package/dist/core/parse/index.d.mts +15 -1
- package/dist/core/parse/index.mjs +555 -1
- package/dist/core/prompt/index.d.mts +11 -4
- package/dist/core/prompt/index.mjs +348 -6
- package/dist/core/resolve/args.mjs +105 -1
- package/dist/core/resolve/coerce.mjs +279 -1
- package/dist/core/resolve/config.mjs +19 -1
- package/dist/core/resolve/errors.mjs +140 -2
- package/dist/core/resolve/flags.mjs +196 -1
- package/dist/core/resolve/index.mjs +85 -1
- package/dist/core/resolve/property.d.mts +2 -1
- package/dist/core/resolve/property.mjs +45 -1
- package/dist/core/schema/arg.d.mts +90 -10
- package/dist/core/schema/arg.mjs +463 -1
- package/dist/core/schema/command.d.mts +21 -1
- package/dist/core/schema/command.mjs +712 -1
- package/dist/core/schema/flag.d.mts +92 -2
- package/dist/core/schema/flag.mjs +453 -1
- package/dist/core/schema/index.d.mts +2 -1
- package/dist/core/schema/middleware.mjs +41 -1
- package/dist/core/schema/number-constraints.d.mts +96 -0
- package/dist/core/schema/number-constraints.mjs +60 -0
- package/dist/core/schema/prompt.d.mts +15 -0
- package/dist/core/schema/run.d.mts +4 -4
- package/dist/core/schema-dsl/runtime.mjs +271 -2
- package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
- package/dist/core/testkit/index.d.mts +9 -5
- package/dist/core/testkit/index.mjs +83 -1
- package/dist/index.d.mts +3 -1
- package/dist/index.mjs +22 -1
- package/dist/runtime/adapter.mjs +82 -1
- package/dist/runtime/auto.mjs +46 -1
- package/dist/runtime/bun.mjs +28 -1
- package/dist/runtime/deno.mjs +217 -2
- package/dist/runtime/detect.mjs +45 -1
- package/dist/runtime/node.mjs +169 -2
- package/dist/runtime/paths.mjs +48 -1
- package/dist/runtime.mjs +7 -1
- package/dist/strings.mjs +22 -1
- package/dist/testkit.mjs +5 -1
- package/dist/version.mjs +7 -1
- package/examples/basic.ts +5 -1
- package/examples/gh/package.json +2 -7
- package/examples/pwsh-demo/package.json +1 -7
- package/examples/pwsh-demo/src/main.test.ts +1 -4
- package/examples/pwsh-demo/src/main.ts +14 -4
- package/examples/transport-launcher.ts +85 -0
- package/package.json +23 -41
- package/dist/runtime/support.d.mts +0 -42
- package/dist/runtime/support.mjs +0 -1
- package/src/core/cli/dispatch.ts +0 -349
- package/src/core/cli/help-links.ts +0 -82
- package/src/core/cli/index.ts +0 -1413
- package/src/core/cli/planner.ts +0 -487
- package/src/core/cli/plugin.ts +0 -117
- package/src/core/cli/propagate.ts +0 -97
- package/src/core/cli/root-help.ts +0 -252
- package/src/core/cli/root-surface.ts +0 -74
- package/src/core/cli/runtime-preflight.ts +0 -438
- package/src/core/completion/index.ts +0 -88
- package/src/core/completion/shells/bash.ts +0 -459
- package/src/core/completion/shells/fish.ts +0 -259
- package/src/core/completion/shells/powershell.ts +0 -439
- package/src/core/completion/shells/shared.ts +0 -283
- package/src/core/completion/shells/zsh.ts +0 -381
- package/src/core/config/index.ts +0 -417
- package/src/core/config/package-json.ts +0 -560
- package/src/core/errors/index.ts +0 -193
- package/src/core/execution/index.ts +0 -268
- package/src/core/help/ansi.ts +0 -144
- package/src/core/help/index.ts +0 -516
- package/src/core/json-schema/index.ts +0 -891
- package/src/core/json-schema/meta-descriptions.generated.ts +0 -185
- package/src/core/output/activity.ts +0 -575
- package/src/core/output/bind.ts +0 -59
- package/src/core/output/contracts.ts +0 -194
- package/src/core/output/display-value.ts +0 -48
- package/src/core/output/index.ts +0 -704
- package/src/core/output/renderers.ts +0 -125
- package/src/core/output/writer.ts +0 -46
- package/src/core/parse/index.ts +0 -681
- package/src/core/prompt/index.ts +0 -583
- package/src/core/resolve/args.ts +0 -144
- package/src/core/resolve/coerce.ts +0 -432
- package/src/core/resolve/config.ts +0 -26
- package/src/core/resolve/contracts.ts +0 -135
- package/src/core/resolve/errors.ts +0 -227
- package/src/core/resolve/flags.ts +0 -255
- package/src/core/resolve/index.ts +0 -108
- package/src/core/resolve/property.ts +0 -99
- package/src/core/schema/activity.ts +0 -240
- package/src/core/schema/arg.ts +0 -719
- package/src/core/schema/command.ts +0 -1498
- package/src/core/schema/flag.ts +0 -801
- package/src/core/schema/index.ts +0 -91
- package/src/core/schema/middleware.ts +0 -171
- package/src/core/schema/prompt.ts +0 -156
- package/src/core/schema/run.ts +0 -198
- package/src/core/schema-dsl/index.ts +0 -109
- package/src/core/schema-dsl/parse.ts +0 -262
- package/src/core/schema-dsl/runtime.ts +0 -609
- package/src/core/schema-dsl/to-json-schema.ts +0 -102
- package/src/core/testkit/index.ts +0 -123
- package/src/index.ts +0 -179
- package/src/runtime/adapter.ts +0 -303
- package/src/runtime/auto.ts +0 -110
- package/src/runtime/bun.ts +0 -55
- package/src/runtime/deno.ts +0 -369
- package/src/runtime/detect.ts +0 -105
- package/src/runtime/index.ts +0 -21
- package/src/runtime/node-builtins.d.ts +0 -27
- package/src/runtime/node.ts +0 -300
- package/src/runtime/paths.ts +0 -64
- package/src/runtime/support.ts +0 -135
- package/src/runtime.ts +0 -31
- package/src/strings.ts +0 -34
- package/src/testkit.ts +0 -25
- package/src/version.ts +0 -20
package/dist/core/cli/index.mjs
CHANGED
|
@@ -1 +1,901 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { getFlagAliasNames } from "../schema/flag.mjs";
|
|
2
|
+
import { CLIError } from "../errors/index.mjs";
|
|
3
|
+
import { SHELLS, detectShell, generateCompletion, normalizeShell } from "../completion/index.mjs";
|
|
4
|
+
import { formatHelp } from "../help/index.mjs";
|
|
5
|
+
import { clearRequestedExitCode, createCaptureOutput, createOutput } from "../output/index.mjs";
|
|
6
|
+
import { arg } from "../schema/arg.mjs";
|
|
7
|
+
import { command } from "../schema/command.mjs";
|
|
8
|
+
import { includesBeforeSeparator } from "../parse/index.mjs";
|
|
9
|
+
import { buildRunResult, executeCommand } from "../execution/index.mjs";
|
|
10
|
+
import { runCommand } from "../testkit/index.mjs";
|
|
11
|
+
import { stripTrailing } from "../../strings.mjs";
|
|
12
|
+
import { createAdapter } from "../../runtime/auto.mjs";
|
|
13
|
+
import { deriveHelpLinks } from "./help-links.mjs";
|
|
14
|
+
import { planInvocation } from "./planner.mjs";
|
|
15
|
+
import "./plugin.mjs";
|
|
16
|
+
import { formatRootHelp } from "./root-help.mjs";
|
|
17
|
+
import { prepareRuntimePreflight } from "./runtime-preflight.mjs";
|
|
18
|
+
//#region src/core/cli/index.ts
|
|
19
|
+
/** Long-flag name reserved by `.completions({ as: 'flag' })`; the planner intercepts it before dispatch. */
|
|
20
|
+
const COMPLETIONS_FLAG_NAME = "completions";
|
|
21
|
+
/**
|
|
22
|
+
* Whether a command — or any of its nested subcommands — declares a flag that
|
|
23
|
+
* collides with the eager `--completions` flag, by canonical name or long alias.
|
|
24
|
+
*
|
|
25
|
+
* @internal
|
|
26
|
+
*/
|
|
27
|
+
function commandReservesCompletionsFlag(schema) {
|
|
28
|
+
if (Object.hasOwn(schema.flags, COMPLETIONS_FLAG_NAME)) return true;
|
|
29
|
+
for (const flagSchema of Object.values(schema.flags)) if (getFlagAliasNames(flagSchema, {
|
|
30
|
+
kind: "long",
|
|
31
|
+
includeHidden: true
|
|
32
|
+
}).includes(COMPLETIONS_FLAG_NAME)) return true;
|
|
33
|
+
return schema.commands.some(commandReservesCompletionsFlag);
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Reject a command whose flags would be shadowed by the eager `--completions`
|
|
37
|
+
* flag once `.completions({ as: 'flag' })` is active. Because the planner
|
|
38
|
+
* intercepts `--completions` before dispatch, such a flag could never be reached.
|
|
39
|
+
*
|
|
40
|
+
* @internal
|
|
41
|
+
*/
|
|
42
|
+
function assertNoCompletionsFlagCollision(schema) {
|
|
43
|
+
if (commandReservesCompletionsFlag(schema)) throw new CLIError(`Command '${schema.name}' defines a '--${COMPLETIONS_FLAG_NAME}' flag, which is reserved by .completions({ as: 'flag' })`, {
|
|
44
|
+
code: "RESERVED_FLAG",
|
|
45
|
+
suggest: `Rename the flag, or register completions as a subcommand with .completions() instead of { as: 'flag' }`
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
function commandRoutes(schema) {
|
|
49
|
+
return [schema.name, ...schema.aliases];
|
|
50
|
+
}
|
|
51
|
+
function assertNoSiblingRouteConflict(parentCommandName, routeOwners, route, commandName) {
|
|
52
|
+
const owner = routeOwners.get(route);
|
|
53
|
+
if (owner !== void 0) throw new CLIError(`Duplicate command route '${route}' under '${parentCommandName}' (${owner} and ${commandName})`, {
|
|
54
|
+
code: "DUPLICATE_COMMAND",
|
|
55
|
+
suggest: "Ensure sibling command names and aliases are unique"
|
|
56
|
+
});
|
|
57
|
+
routeOwners.set(route, commandName);
|
|
58
|
+
}
|
|
59
|
+
function assertNoTopLevelRouteConflict(commands, incoming, defaultCommand) {
|
|
60
|
+
const routeOwners = /* @__PURE__ */ new Map();
|
|
61
|
+
const existing = defaultCommand !== void 0 ? [...commands, defaultCommand] : commands;
|
|
62
|
+
for (const command of existing) for (const route of commandRoutes(command.schema)) assertNoSiblingRouteConflict("root", routeOwners, route, command.schema.name);
|
|
63
|
+
for (const route of commandRoutes(incoming)) {
|
|
64
|
+
const owner = routeOwners.get(route);
|
|
65
|
+
if (owner !== void 0) throw new CLIError(`Command route '${route}' is already registered by '${owner}'`, {
|
|
66
|
+
code: "DUPLICATE_COMMAND",
|
|
67
|
+
suggest: owner === incoming.name ? `Ensure command '${incoming.name}' does not reuse route '${route}'` : `Rename '${incoming.name}' or remove route '${route}' from '${owner}'`
|
|
68
|
+
});
|
|
69
|
+
routeOwners.set(route, incoming.name);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Erase a typed {@linkcode CommandBuilder} into an {@linkcode ErasedCommand}, recursively
|
|
74
|
+
* building the subcommand tree.
|
|
75
|
+
*
|
|
76
|
+
* The closure captures the fully-typed builder, so {@linkcode runCommand()} receives
|
|
77
|
+
* the original `CommandBuilder<F, A>` — no type assertions needed.\
|
|
78
|
+
* Subcommands are recursively erased and indexed by name and alias for
|
|
79
|
+
* O(1) lookup during dispatch.
|
|
80
|
+
*
|
|
81
|
+
* @internal
|
|
82
|
+
*/
|
|
83
|
+
function eraseCommand(cmd) {
|
|
84
|
+
const subcommands = /* @__PURE__ */ new Map();
|
|
85
|
+
const routeOwners = /* @__PURE__ */ new Map();
|
|
86
|
+
for (const sub of cmd._subcommands) {
|
|
87
|
+
const routes = commandRoutes(sub.schema);
|
|
88
|
+
for (const route of routes) assertNoSiblingRouteConflict(cmd.schema.name, routeOwners, route, sub.schema.name);
|
|
89
|
+
const erased = eraseCommand(sub);
|
|
90
|
+
for (const route of routes) subcommands.set(route, erased);
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
schema: cmd.schema,
|
|
94
|
+
subcommands,
|
|
95
|
+
_command: cmd,
|
|
96
|
+
_execute(argv, options) {
|
|
97
|
+
return runCommand(cmd, argv, options);
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Build {@linkcode RunOptions} from {@linkcode CLIRunOptions}, conditionally spreading each
|
|
103
|
+
* field to satisfy `exactOptionalPropertyTypes`.
|
|
104
|
+
*
|
|
105
|
+
* @param options - CLI-level run options (may be `undefined` for defaults).
|
|
106
|
+
* @param helpOptions - Help formatting options forwarded to commands.
|
|
107
|
+
* @param meta - Optional command metadata (omitted for root-level dispatch).
|
|
108
|
+
* @returns Options record ready for {@linkcode ErasedCommand._execute | ErasedCommand._execute()}.
|
|
109
|
+
*
|
|
110
|
+
* @internal
|
|
111
|
+
*/
|
|
112
|
+
function buildCommandRunOptions(options, helpOptions, meta) {
|
|
113
|
+
return {
|
|
114
|
+
help: helpOptions,
|
|
115
|
+
...meta !== void 0 ? { meta } : {},
|
|
116
|
+
...options?.plugins !== void 0 ? { plugins: options.plugins } : {},
|
|
117
|
+
...options?.env !== void 0 ? { env: options.env } : {},
|
|
118
|
+
...options?.config !== void 0 ? { config: options.config } : {},
|
|
119
|
+
...options?.stdinData !== void 0 ? { stdinData: options.stdinData } : {},
|
|
120
|
+
...options?.prompter !== void 0 ? { prompter: options.prompter } : {},
|
|
121
|
+
...options?.answers !== void 0 ? { answers: options.answers } : {},
|
|
122
|
+
...options?.verbosity !== void 0 ? { verbosity: options.verbosity } : {},
|
|
123
|
+
...options?.jsonMode !== void 0 ? { jsonMode: options.jsonMode } : {},
|
|
124
|
+
...options?.isTTY !== void 0 ? { isTTY: options.isTTY } : {},
|
|
125
|
+
...options?.out !== void 0 ? { out: options.out } : {},
|
|
126
|
+
...options?.captured !== void 0 ? { captured: options.captured } : {}
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Immutable CLI program builder.
|
|
131
|
+
*
|
|
132
|
+
* Registers commands, handles root-level `--help`/`--version`, and
|
|
133
|
+
* dispatches to the matched command based on argv.
|
|
134
|
+
*
|
|
135
|
+
* Two execution paths:
|
|
136
|
+
* - `.execute(argv, options?)` — testable, returns {@linkcode RunResult}
|
|
137
|
+
* - `.run(options?)` — production entry, reads `process.argv`, exits process
|
|
138
|
+
*
|
|
139
|
+
* @example
|
|
140
|
+
* ```ts
|
|
141
|
+
* import { cli, command, flag, arg } from '@kjanat/dreamcli';
|
|
142
|
+
*
|
|
143
|
+
* const deploy = command('deploy')
|
|
144
|
+
* .arg('target', arg.string())
|
|
145
|
+
* .flag('force', flag.boolean().alias('f'))
|
|
146
|
+
* .action(({ args, flags, out }) => {
|
|
147
|
+
* out.log(`Deploying ${args.target}...`);
|
|
148
|
+
* });
|
|
149
|
+
*
|
|
150
|
+
* cli('mycli')
|
|
151
|
+
* .version('1.0.0')
|
|
152
|
+
* .command(deploy)
|
|
153
|
+
* .run();
|
|
154
|
+
* ```
|
|
155
|
+
*/
|
|
156
|
+
var CLIBuilder = class CLIBuilder {
|
|
157
|
+
/** @internal Runtime schema descriptor. */
|
|
158
|
+
schema;
|
|
159
|
+
/** Build a CLIBuilder from a pre-constructed schema descriptor. */
|
|
160
|
+
constructor(schema) {
|
|
161
|
+
this.schema = schema;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Set the program version (shown by `--version`).
|
|
165
|
+
*
|
|
166
|
+
* @param v - Semantic version string.
|
|
167
|
+
* @returns The builder (for chaining).
|
|
168
|
+
*/
|
|
169
|
+
version(v) {
|
|
170
|
+
return new CLIBuilder({
|
|
171
|
+
...this.schema,
|
|
172
|
+
version: v
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Set the program description (shown in root help).
|
|
177
|
+
*
|
|
178
|
+
* @param text - Short description displayed in root help output.
|
|
179
|
+
* @returns The builder (for chaining).
|
|
180
|
+
*/
|
|
181
|
+
description(text) {
|
|
182
|
+
return new CLIBuilder({
|
|
183
|
+
...this.schema,
|
|
184
|
+
description: text
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* Make the root-help header clickable with OSC 8 hyperlinks.
|
|
189
|
+
*
|
|
190
|
+
* Links the program name and version on the first line of root `--help`
|
|
191
|
+
* output in terminals that support
|
|
192
|
+
* [OSC 8 hyperlinks](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda).
|
|
193
|
+
* The escapes are only emitted when stdout is a TTY (overridable via
|
|
194
|
+
* `options.help.hyperlinks`), and only in the header — usage lines, the
|
|
195
|
+
* `--help` hint, the commands table, and completion scripts stay plain.
|
|
196
|
+
*
|
|
197
|
+
* URLs not provided here are derived from manifest metadata when
|
|
198
|
+
* `.manifest()` is active (works with both filesystem discovery and
|
|
199
|
+
* pre-loaded data):
|
|
200
|
+
* - **name** → normalized `repository` URL, falling back to `homepage`
|
|
201
|
+
* - **version** → forge release tag (`{repo}/releases/tag/v{version}` on
|
|
202
|
+
* GitHub, `{repo}/-/releases/v{version}` on GitLab)
|
|
203
|
+
*
|
|
204
|
+
* @param links - Explicit URLs; omit to derive everything from the manifest.
|
|
205
|
+
* @returns The builder (for chaining).
|
|
206
|
+
*
|
|
207
|
+
* @example
|
|
208
|
+
* ```ts
|
|
209
|
+
* // Derive both links from the manifest repository/homepage:
|
|
210
|
+
* cli('mycli')
|
|
211
|
+
* .manifest()
|
|
212
|
+
* .links()
|
|
213
|
+
* .run();
|
|
214
|
+
*
|
|
215
|
+
* // Explicit URLs (no package.json required):
|
|
216
|
+
* cli('mycli')
|
|
217
|
+
* .version('1.0.0')
|
|
218
|
+
* .links({
|
|
219
|
+
* name: 'https://github.com/me/mycli',
|
|
220
|
+
* version: 'https://github.com/me/mycli/releases/tag/v1.0.0',
|
|
221
|
+
* })
|
|
222
|
+
* .run();
|
|
223
|
+
* ```
|
|
224
|
+
*/
|
|
225
|
+
links(links) {
|
|
226
|
+
return new CLIBuilder({
|
|
227
|
+
...this.schema,
|
|
228
|
+
helpLinks: {
|
|
229
|
+
name: toUrlString(links?.name),
|
|
230
|
+
version: toUrlString(links?.version)
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Configure root-help rendering defaults.
|
|
236
|
+
*
|
|
237
|
+
* Stored on the schema and merged **under** any runtime `options.help`
|
|
238
|
+
* (runtime wins). Call multiple times to set fields incrementally.
|
|
239
|
+
*
|
|
240
|
+
* @param config - Help rendering options (see {@link HelpConfig}).
|
|
241
|
+
* @returns The builder (for chaining).
|
|
242
|
+
*
|
|
243
|
+
* @example
|
|
244
|
+
* ```ts
|
|
245
|
+
* // Echo the default command under Commands and never show the footer:
|
|
246
|
+
* cli('mycli')
|
|
247
|
+
* .help({ showDefaultInCommands: true, footer: false })
|
|
248
|
+
* .default(serve)
|
|
249
|
+
* .run();
|
|
250
|
+
* ```
|
|
251
|
+
*/
|
|
252
|
+
help(config) {
|
|
253
|
+
return new CLIBuilder({
|
|
254
|
+
...this.schema,
|
|
255
|
+
helpConfig: {
|
|
256
|
+
...this.schema.helpConfig,
|
|
257
|
+
...config
|
|
258
|
+
}
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Enable automatic config file discovery.
|
|
263
|
+
*
|
|
264
|
+
* When enabled, `.run()` probes standard paths before dispatching:
|
|
265
|
+
* 1. `$CWD/.{appName}.json`
|
|
266
|
+
* 2. `$CWD/{appName}.config.json`
|
|
267
|
+
* 3. `$CONFIG_DIR/{appName}/config.json`
|
|
268
|
+
* (`$XDG_CONFIG_HOME` / `~/.config` on Unix,
|
|
269
|
+
* `%APPDATA%` / `%USERPROFILE%\\AppData\\Roaming` on Windows)
|
|
270
|
+
*
|
|
271
|
+
* The user can override the path via `--config <path>` or `--config=<path>`.
|
|
272
|
+
*
|
|
273
|
+
* Loaded config feeds into the resolution chain
|
|
274
|
+
* (CLI → env → **config** → prompt → default) for flags that
|
|
275
|
+
* declare `.config('dotted.path')`.
|
|
276
|
+
*
|
|
277
|
+
* Has no effect in `.execute()` (which receives config via
|
|
278
|
+
* `options.config` directly).
|
|
279
|
+
*
|
|
280
|
+
* @param appName - Name used to build search paths.
|
|
281
|
+
* @param loaders - Additional {@link FormatLoader}s (JSON is built-in).
|
|
282
|
+
* @returns The builder (for chaining).
|
|
283
|
+
*/
|
|
284
|
+
config(appName, loaders) {
|
|
285
|
+
return new CLIBuilder({
|
|
286
|
+
...this.schema,
|
|
287
|
+
configSettings: {
|
|
288
|
+
appName,
|
|
289
|
+
loaders
|
|
290
|
+
}
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* Register a custom config format loader.
|
|
295
|
+
*
|
|
296
|
+
* Adds a {@link FormatLoader} incrementally — call multiple times to
|
|
297
|
+
* register multiple formats. Loaders registered later for the same
|
|
298
|
+
* extension override earlier ones.
|
|
299
|
+
*
|
|
300
|
+
* Requires `.config()` to have been called first (sets the app name).
|
|
301
|
+
*
|
|
302
|
+
* @param loader - Format loader (or extensions + parse function).
|
|
303
|
+
* @returns The builder (for chaining).
|
|
304
|
+
*
|
|
305
|
+
* @example Bun built-in parsers
|
|
306
|
+
* ```ts
|
|
307
|
+
* import { configFormat } from '@kjanat/dreamcli';
|
|
308
|
+
*
|
|
309
|
+
* cli('myapp')
|
|
310
|
+
* .config('myapp')
|
|
311
|
+
* .configLoader(configFormat(['yaml', 'yml'], Bun.YAML.parse))
|
|
312
|
+
* .configLoader(configFormat(['toml'], Bun.TOML.parse))
|
|
313
|
+
* .run();
|
|
314
|
+
* ```
|
|
315
|
+
*
|
|
316
|
+
* @example npm package parsers
|
|
317
|
+
* ```ts
|
|
318
|
+
* import { configFormat } from '@kjanat/dreamcli';
|
|
319
|
+
* import { parse as parseYaml } from 'yaml';
|
|
320
|
+
* import { parse as parseTOML } from '@iarna/toml';
|
|
321
|
+
*
|
|
322
|
+
* cli('myapp')
|
|
323
|
+
* .config('myapp')
|
|
324
|
+
* .configLoader(configFormat(['yaml', 'yml'], parseYaml))
|
|
325
|
+
* .configLoader(configFormat(['toml'], parseTOML))
|
|
326
|
+
* .run();
|
|
327
|
+
* ```
|
|
328
|
+
*/
|
|
329
|
+
configLoader(loader) {
|
|
330
|
+
if (this.schema.configSettings === void 0) throw new CLIError(".configLoader() requires .config() to be called first", {
|
|
331
|
+
code: "INVALID_BUILDER_STATE",
|
|
332
|
+
suggest: "Call .config(appName) before .configLoader()"
|
|
333
|
+
});
|
|
334
|
+
const existing = this.schema.configSettings.loaders ?? [];
|
|
335
|
+
return new CLIBuilder({
|
|
336
|
+
...this.schema,
|
|
337
|
+
configSettings: {
|
|
338
|
+
...this.schema.configSettings,
|
|
339
|
+
loaders: [...existing, loader]
|
|
340
|
+
}
|
|
341
|
+
});
|
|
342
|
+
}
|
|
343
|
+
manifest(input) {
|
|
344
|
+
return new CLIBuilder(buildManifestSchema(this.schema, input, DEFAULT_MANIFEST_FILES, false));
|
|
345
|
+
}
|
|
346
|
+
packageJson(input) {
|
|
347
|
+
return new CLIBuilder(buildManifestSchema(this.schema, input, DEFAULT_MANIFEST_FILES, true));
|
|
348
|
+
}
|
|
349
|
+
denoJson(input) {
|
|
350
|
+
return new CLIBuilder(buildManifestSchema(this.schema, input, DENO_MANIFEST_FILES, true));
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Register a command with the CLI program.
|
|
354
|
+
*
|
|
355
|
+
* The command's type parameters are erased for heterogeneous storage.
|
|
356
|
+
* Type safety is preserved inside the closure that delegates to
|
|
357
|
+
* {@linkcode runCommand | runCommand()}.
|
|
358
|
+
*
|
|
359
|
+
* @param cmd - {@link CommandBuilder} to register.
|
|
360
|
+
* @returns The builder (for chaining).
|
|
361
|
+
*/
|
|
362
|
+
command(cmd) {
|
|
363
|
+
assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema, this.schema.defaultCommand);
|
|
364
|
+
if (this.schema.completionsFlag !== void 0) assertNoCompletionsFlagCollision(cmd.schema);
|
|
365
|
+
return new CLIBuilder({
|
|
366
|
+
...this.schema,
|
|
367
|
+
commands: [...this.schema.commands, eraseCommand(cmd)]
|
|
368
|
+
});
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Register a command as the default — dispatched when no subcommand is given.
|
|
372
|
+
*
|
|
373
|
+
* The CLI root behaves like a hybrid command group: named subcommands
|
|
374
|
+
* dispatch normally, but empty argv or flags-only argv falls through to
|
|
375
|
+
* this command instead of showing root help.
|
|
376
|
+
*
|
|
377
|
+
* The default command is the CLI's root *surface*: its flags and arguments
|
|
378
|
+
* are rendered inline in root help. It is **not** a named subcommand — it
|
|
379
|
+
* cannot be invoked by its own name (`mycli mycmd` does not route to it) and
|
|
380
|
+
* it is omitted from the root `Commands:` list by default (re-enable with
|
|
381
|
+
* `.help({ showDefaultInCommands: true })`). Only one default is allowed.
|
|
382
|
+
*
|
|
383
|
+
* @example
|
|
384
|
+
* ```ts
|
|
385
|
+
* // Single-command CLI — no subcommand name needed:
|
|
386
|
+
* // mytool --force production
|
|
387
|
+
* cli('mytool')
|
|
388
|
+
* .default(deploy)
|
|
389
|
+
* .run();
|
|
390
|
+
*
|
|
391
|
+
* // Multi-command CLI with a default:
|
|
392
|
+
* // mytool production → runs deploy
|
|
393
|
+
* // mytool status → runs status
|
|
394
|
+
* cli('mytool')
|
|
395
|
+
* .default(deploy)
|
|
396
|
+
* .command(status)
|
|
397
|
+
* .run();
|
|
398
|
+
* ```
|
|
399
|
+
*
|
|
400
|
+
* @param cmd - {@link CommandBuilder} to register as the default.
|
|
401
|
+
* @returns The builder (for chaining).
|
|
402
|
+
*/
|
|
403
|
+
default(cmd) {
|
|
404
|
+
if (this.schema.defaultCommand !== void 0) throw new CLIError("Only one default command is allowed", {
|
|
405
|
+
code: "DUPLICATE_DEFAULT",
|
|
406
|
+
suggest: "Call .default() only once when building the CLI"
|
|
407
|
+
});
|
|
408
|
+
assertNoTopLevelRouteConflict(this.schema.commands, cmd.schema);
|
|
409
|
+
if (this.schema.completionsFlag !== void 0) assertNoCompletionsFlagCollision(cmd.schema);
|
|
410
|
+
const erased = eraseCommand(cmd);
|
|
411
|
+
return new CLIBuilder({
|
|
412
|
+
...this.schema,
|
|
413
|
+
defaultCommand: erased
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* Register a CLI plugin.
|
|
418
|
+
*
|
|
419
|
+
* Plugins run in registration order. At each lifecycle stage, all hooks for
|
|
420
|
+
* the first plugin run before hooks for the second plugin, and so on.
|
|
421
|
+
*
|
|
422
|
+
* @param definition - A frozen {@link CLIPlugin} created by {@link plugin}.
|
|
423
|
+
* @returns The builder (for chaining).
|
|
424
|
+
* @see {@link plugin} to construct plugin definitions.
|
|
425
|
+
*/
|
|
426
|
+
plugin(definition) {
|
|
427
|
+
return new CLIBuilder({
|
|
428
|
+
...this.schema,
|
|
429
|
+
plugins: [...this.schema.plugins, definition]
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Register built-in shell completion.
|
|
434
|
+
*
|
|
435
|
+
* By default (`{ as: 'command' }`) this registers a `completions` subcommand
|
|
436
|
+
* that accepts a `shell` argument and writes the script to stdout. With
|
|
437
|
+
* `{ as: 'flag' }` it instead exposes an eager `--completions <shell>` flag on
|
|
438
|
+
* the CLI root — no subcommand is registered, so a default command stays the
|
|
439
|
+
* lone root surface. The flag may be given without a value to auto-detect the
|
|
440
|
+
* shell from `$SHELL` / `$PSModulePath`.
|
|
441
|
+
*
|
|
442
|
+
* In subcommand mode, call this **after** registering all other commands so
|
|
443
|
+
* the completion script includes the full command set: that path snapshots the
|
|
444
|
+
* schema (and completion options) at call time, so commands registered
|
|
445
|
+
* afterwards will not appear in that subcommand's generated script. In flag
|
|
446
|
+
* mode, generation runs at execution time from the final builder schema, so
|
|
447
|
+
* registration order does not matter.
|
|
448
|
+
*
|
|
449
|
+
* @example
|
|
450
|
+
* ```ts
|
|
451
|
+
* // Subcommand form (default):
|
|
452
|
+
* cli('mycli')
|
|
453
|
+
* .version('1.0.0')
|
|
454
|
+
* .command(deploy)
|
|
455
|
+
* .completions({ rootMode: 'surface' })
|
|
456
|
+
* .run();
|
|
457
|
+
*
|
|
458
|
+
* // Eager-flag form, ideal for single-command CLIs:
|
|
459
|
+
* cli('mycli')
|
|
460
|
+
* .completions({ as: 'flag' })
|
|
461
|
+
* .default(serve)
|
|
462
|
+
* .run();
|
|
463
|
+
* ```
|
|
464
|
+
*/
|
|
465
|
+
completions(options) {
|
|
466
|
+
if (this.schema.hasBuiltInCompletions) throw new CLIError(".completions() has already been called", {
|
|
467
|
+
code: "DUPLICATE_COMMAND",
|
|
468
|
+
suggest: "Call .completions() only once when building the CLI"
|
|
469
|
+
});
|
|
470
|
+
if (options?.as === "flag") {
|
|
471
|
+
if (this.schema.defaultCommand !== void 0) assertNoCompletionsFlagCollision(this.schema.defaultCommand.schema);
|
|
472
|
+
for (const registered of this.schema.commands) assertNoCompletionsFlagCollision(registered.schema);
|
|
473
|
+
return new CLIBuilder({
|
|
474
|
+
...this.schema,
|
|
475
|
+
hasBuiltInCompletions: true,
|
|
476
|
+
completionsFlag: {
|
|
477
|
+
shells: SHELLS,
|
|
478
|
+
options
|
|
479
|
+
}
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
const cliSchema = this.schema;
|
|
483
|
+
const completionOptions = options;
|
|
484
|
+
const cmd = command("completions").alias("completion").description("Generate shell completion script").arg("shell", arg.custom((raw) => {
|
|
485
|
+
const shell = normalizeShell(raw);
|
|
486
|
+
if (shell === void 0) throw new Error(`Unknown shell '${raw}'. Valid shells: ${SHELLS.join(", ")}`);
|
|
487
|
+
return shell;
|
|
488
|
+
}).env("SHELL").describe(`Target shell (${SHELLS.join(", ")})`)).action(({ args, meta, out }) => {
|
|
489
|
+
const script = generateCompletion(meta.bin === cliSchema.name ? cliSchema : {
|
|
490
|
+
...cliSchema,
|
|
491
|
+
name: meta.bin
|
|
492
|
+
}, args.shell, completionOptions);
|
|
493
|
+
if (out.jsonMode) out.json({
|
|
494
|
+
shell: args.shell,
|
|
495
|
+
script
|
|
496
|
+
});
|
|
497
|
+
else out.log(script);
|
|
498
|
+
});
|
|
499
|
+
return new CLIBuilder({
|
|
500
|
+
...this.command(cmd).schema,
|
|
501
|
+
hasBuiltInCompletions: true
|
|
502
|
+
});
|
|
503
|
+
}
|
|
504
|
+
/**
|
|
505
|
+
* Execute the CLI program against explicit argv.
|
|
506
|
+
*
|
|
507
|
+
* This is the testable execution path — no process state is touched.
|
|
508
|
+
* Returns a structured {@linkcode RunResult} with exit code and captured output.
|
|
509
|
+
*
|
|
510
|
+
* @param argv - Raw argv tokens (NOT including the binary/script path,
|
|
511
|
+
* i.e. equivalent to `process.argv.slice(2)`).
|
|
512
|
+
* @param options - Injectable runtime state.
|
|
513
|
+
* @returns Structured result with exit code and captured output.
|
|
514
|
+
*/
|
|
515
|
+
async execute(argv, options) {
|
|
516
|
+
const jsonMode = includesBeforeSeparator(argv, "--json") || options?.jsonMode === true;
|
|
517
|
+
const captureOptions = {
|
|
518
|
+
...options?.verbosity !== void 0 ? { verbosity: options.verbosity } : {},
|
|
519
|
+
...jsonMode ? { jsonMode } : {},
|
|
520
|
+
...options?.isTTY !== void 0 ? { isTTY: options.isTTY } : {}
|
|
521
|
+
};
|
|
522
|
+
let out;
|
|
523
|
+
let captured;
|
|
524
|
+
if (options?.out !== void 0) {
|
|
525
|
+
out = options.out;
|
|
526
|
+
captured = options.captured ?? {
|
|
527
|
+
stdout: [],
|
|
528
|
+
stderr: [],
|
|
529
|
+
activity: []
|
|
530
|
+
};
|
|
531
|
+
} else [out, captured] = createCaptureOutput(Object.keys(captureOptions).length > 0 ? captureOptions : void 0);
|
|
532
|
+
clearRequestedExitCode(out);
|
|
533
|
+
const helpOptions = {
|
|
534
|
+
...this.schema.helpConfig,
|
|
535
|
+
...options?.help,
|
|
536
|
+
binName: options?.help?.binName ?? this.schema.name,
|
|
537
|
+
hyperlinks: options?.help?.hyperlinks ?? this.schema.helpConfig?.hyperlinks ?? out.isTTY
|
|
538
|
+
};
|
|
539
|
+
const effectiveOptions = {
|
|
540
|
+
...options,
|
|
541
|
+
plugins: this.schema.plugins,
|
|
542
|
+
...jsonMode ? { jsonMode } : {}
|
|
543
|
+
};
|
|
544
|
+
const output = {
|
|
545
|
+
jsonMode,
|
|
546
|
+
isTTY: out.isTTY,
|
|
547
|
+
verbosity: options?.verbosity ?? "normal"
|
|
548
|
+
};
|
|
549
|
+
const planned = planInvocation({
|
|
550
|
+
schema: this.schema,
|
|
551
|
+
argv,
|
|
552
|
+
help: helpOptions,
|
|
553
|
+
output
|
|
554
|
+
});
|
|
555
|
+
switch (planned.kind) {
|
|
556
|
+
case "root-version":
|
|
557
|
+
out.log(planned.version);
|
|
558
|
+
return buildRunResult({
|
|
559
|
+
exitCode: 0,
|
|
560
|
+
error: void 0
|
|
561
|
+
}, captured);
|
|
562
|
+
case "root-completions": {
|
|
563
|
+
const shell = planned.shell ?? detectShell(options?.env ?? {});
|
|
564
|
+
if (shell === void 0) {
|
|
565
|
+
const error = new CLIError("Could not detect shell", {
|
|
566
|
+
code: "MISSING_VALUE",
|
|
567
|
+
suggest: `Pass one explicitly, e.g. '${helpOptions.binName} --completions zsh'`
|
|
568
|
+
});
|
|
569
|
+
if (jsonMode) out.json({ error: error.toJSON() });
|
|
570
|
+
else {
|
|
571
|
+
out.error(error.message);
|
|
572
|
+
out.error(`Suggestion: ${error.suggest}`);
|
|
573
|
+
}
|
|
574
|
+
return buildRunResult({
|
|
575
|
+
exitCode: error.exitCode,
|
|
576
|
+
error
|
|
577
|
+
}, captured);
|
|
578
|
+
}
|
|
579
|
+
const script = generateCompletion(helpOptions.binName === void 0 || helpOptions.binName === this.schema.name ? this.schema : {
|
|
580
|
+
...this.schema,
|
|
581
|
+
name: helpOptions.binName
|
|
582
|
+
}, shell, planned.options);
|
|
583
|
+
if (jsonMode) out.json({
|
|
584
|
+
shell,
|
|
585
|
+
script
|
|
586
|
+
});
|
|
587
|
+
else out.log(script);
|
|
588
|
+
return buildRunResult({
|
|
589
|
+
exitCode: 0,
|
|
590
|
+
error: void 0
|
|
591
|
+
}, captured);
|
|
592
|
+
}
|
|
593
|
+
case "root-help": {
|
|
594
|
+
const helpText = formatRootHelp(resolveHelpLinksSchema(this.schema), planned.help);
|
|
595
|
+
out.log(helpText);
|
|
596
|
+
return buildRunResult({
|
|
597
|
+
exitCode: 0,
|
|
598
|
+
error: void 0
|
|
599
|
+
}, captured);
|
|
600
|
+
}
|
|
601
|
+
case "dispatch-error":
|
|
602
|
+
if (jsonMode) out.json({ error: planned.error.toJSON() });
|
|
603
|
+
else {
|
|
604
|
+
out.error(planned.error.message);
|
|
605
|
+
if (planned.error.suggest !== void 0 && planned.error.code !== "NO_ACTION") out.error(`Suggestion: ${planned.error.suggest}`);
|
|
606
|
+
}
|
|
607
|
+
return buildRunResult({
|
|
608
|
+
exitCode: planned.error.exitCode,
|
|
609
|
+
error: planned.error
|
|
610
|
+
}, captured);
|
|
611
|
+
case "needs-subcommand": {
|
|
612
|
+
const helpText = formatHelp(planned.command.schema, planned.help);
|
|
613
|
+
out.log(helpText);
|
|
614
|
+
return buildRunResult({
|
|
615
|
+
exitCode: 0,
|
|
616
|
+
error: void 0
|
|
617
|
+
}, captured);
|
|
618
|
+
}
|
|
619
|
+
case "match": {
|
|
620
|
+
const commandRunOptions = buildCommandRunOptions(effectiveOptions, planned.plan.help ?? helpOptions, planned.plan.meta);
|
|
621
|
+
if (planned.plan.command._command === void 0) return planned.plan.command._execute(planned.plan.argv, {
|
|
622
|
+
...commandRunOptions,
|
|
623
|
+
mergedSchema: planned.plan.mergedSchema
|
|
624
|
+
});
|
|
625
|
+
return buildRunResult(await executeCommand({
|
|
626
|
+
command: planned.plan.command._command,
|
|
627
|
+
argv: planned.plan.argv,
|
|
628
|
+
out,
|
|
629
|
+
schema: planned.plan.mergedSchema,
|
|
630
|
+
meta: planned.plan.meta,
|
|
631
|
+
options: commandRunOptions
|
|
632
|
+
}), captured);
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* Run the CLI program as a production entry point.
|
|
638
|
+
*
|
|
639
|
+
* Reads argv from the runtime adapter, dispatches to the matched
|
|
640
|
+
* command, writes output to real streams, and exits the process.
|
|
641
|
+
*
|
|
642
|
+
* This is the **only** place that touches process state (via the
|
|
643
|
+
* adapter). For testing, use `.execute()` instead — or provide a
|
|
644
|
+
* test adapter via `options.adapter`.
|
|
645
|
+
*
|
|
646
|
+
* Defaults to {@linkcode createAdapter | createAdapter()} when no adapter is provided,
|
|
647
|
+
* which auto-detects the runtime (Node.js, Bun) and creates
|
|
648
|
+
* the appropriate adapter.
|
|
649
|
+
*
|
|
650
|
+
* @param options - Optional runtime configuration including adapter.
|
|
651
|
+
*/
|
|
652
|
+
async run(options) {
|
|
653
|
+
const adapter = options?.adapter ?? createAdapter();
|
|
654
|
+
const inheritedName = this.schema.inheritName ? inferInvocationName(adapter.argv) : void 0;
|
|
655
|
+
const preflight = await prepareRuntimePreflight({
|
|
656
|
+
schema: this.schema,
|
|
657
|
+
adapter,
|
|
658
|
+
options,
|
|
659
|
+
inheritedName
|
|
660
|
+
});
|
|
661
|
+
if (preflight.kind === "config-error") {
|
|
662
|
+
if (preflight.jsonMode) adapter.stdout(`${JSON.stringify({ error: preflight.error.toJSON() })}\n`);
|
|
663
|
+
else {
|
|
664
|
+
adapter.stderr(`Error: ${preflight.error.message}\n`);
|
|
665
|
+
if (preflight.error.suggest !== void 0) adapter.stderr(`Suggestion: ${preflight.error.suggest}\n`);
|
|
666
|
+
}
|
|
667
|
+
return adapter.exit(preflight.error.exitCode);
|
|
668
|
+
}
|
|
669
|
+
const effectiveBuilder = preflight.schema === this.schema ? this : new CLIBuilder(preflight.schema);
|
|
670
|
+
const executeOptions = {
|
|
671
|
+
...options,
|
|
672
|
+
...preflight.inputs,
|
|
673
|
+
out: createOutput({
|
|
674
|
+
stdout: adapter.stdout,
|
|
675
|
+
stderr: adapter.stderr,
|
|
676
|
+
jsonMode: preflight.inputs.jsonMode,
|
|
677
|
+
isTTY: preflight.inputs.isTTY,
|
|
678
|
+
...preflight.inputs.verbosity !== "normal" ? { verbosity: preflight.inputs.verbosity } : {}
|
|
679
|
+
})
|
|
680
|
+
};
|
|
681
|
+
const result = await effectiveBuilder.execute(preflight.filteredArgv, executeOptions);
|
|
682
|
+
for (const line of result.stdout) adapter.stdout(line);
|
|
683
|
+
for (const line of result.stderr) adapter.stderr(line);
|
|
684
|
+
return adapter.exit(result.exitCode);
|
|
685
|
+
}
|
|
686
|
+
};
|
|
687
|
+
const RUNTIME_BINARIES = /* @__PURE__ */ new Set([
|
|
688
|
+
"bun",
|
|
689
|
+
"deno",
|
|
690
|
+
"node",
|
|
691
|
+
"tsx"
|
|
692
|
+
]);
|
|
693
|
+
/**
|
|
694
|
+
* Extract the final path segment from a path-like or URL-like string.
|
|
695
|
+
*
|
|
696
|
+
* @param input - Forward- or backslash-delimited path.
|
|
697
|
+
* @returns Trailing segment, or `undefined` when the input is empty or slash-only.
|
|
698
|
+
*
|
|
699
|
+
* @internal
|
|
700
|
+
*/
|
|
701
|
+
function basename(input) {
|
|
702
|
+
const trimmed = stripTrailing(input, [47, 92]);
|
|
703
|
+
if (trimmed.length === 0) return void 0;
|
|
704
|
+
const slashIdx = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));
|
|
705
|
+
const name = slashIdx >= 0 ? trimmed.slice(slashIdx + 1) : trimmed;
|
|
706
|
+
return name.length > 0 ? name : void 0;
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Detect known interpreter/runtime binary names (node, bun, deno, tsx).
|
|
710
|
+
*
|
|
711
|
+
* @param input - Candidate binary name, with or without `.exe` suffix.
|
|
712
|
+
* @returns `true` when `input` matches a known runtime after normalization.
|
|
713
|
+
*
|
|
714
|
+
* @internal
|
|
715
|
+
*/
|
|
716
|
+
function isRuntimeBinaryName(input) {
|
|
717
|
+
const normalized = input.toLowerCase().replace(/\.exe$/i, "");
|
|
718
|
+
return RUNTIME_BINARIES.has(normalized);
|
|
719
|
+
}
|
|
720
|
+
/**
|
|
721
|
+
* Infer the displayed CLI name from the current runtime invocation.
|
|
722
|
+
*
|
|
723
|
+
* Resolution order:
|
|
724
|
+
* 1. Node/Bun/tsx-style interpreters → script/entry argument basename
|
|
725
|
+
* 2. Standalone executable invocations → argv[0] basename
|
|
726
|
+
* 3. `undefined` when no stable entrypoint can be inferred (e.g. Deno synthetic argv)
|
|
727
|
+
*
|
|
728
|
+
* @param argv - Full process argv (typically `process.argv` or adapter equivalent).
|
|
729
|
+
* @returns Inferred program name, or `undefined` when inference is ambiguous.
|
|
730
|
+
*
|
|
731
|
+
* @internal
|
|
732
|
+
*/
|
|
733
|
+
function inferInvocationName(argv) {
|
|
734
|
+
const argv0 = argv[0];
|
|
735
|
+
const argv1 = argv[1];
|
|
736
|
+
const runtimeName = argv0 !== void 0 ? basename(argv0) : void 0;
|
|
737
|
+
if (runtimeName !== void 0 && isRuntimeBinaryName(runtimeName)) {
|
|
738
|
+
if (runtimeName === "bun" && argv1 === "run") {
|
|
739
|
+
const entryArg = argv[2];
|
|
740
|
+
if (entryArg === void 0 || entryArg.startsWith("-")) return void 0;
|
|
741
|
+
return basename(entryArg);
|
|
742
|
+
}
|
|
743
|
+
if (runtimeName === "deno" && argv1 === "run") return void 0;
|
|
744
|
+
if (argv1 === void 0 || argv1.startsWith("-")) return void 0;
|
|
745
|
+
return basename(argv1);
|
|
746
|
+
}
|
|
747
|
+
return argv0 !== void 0 ? basename(argv0) : void 0;
|
|
748
|
+
}
|
|
749
|
+
/** Coerce a `string | URL` link input to its string form. @internal */
|
|
750
|
+
function toUrlString(value) {
|
|
751
|
+
if (value === void 0) return void 0;
|
|
752
|
+
return value instanceof URL ? value.href : value;
|
|
753
|
+
}
|
|
754
|
+
/**
|
|
755
|
+
* Resolve derived help links against pre-loaded package.json data.
|
|
756
|
+
*
|
|
757
|
+
* `.run()` resolves links during runtime preflight (where discovered
|
|
758
|
+
* package.json metadata lives); this covers the filesystem-free
|
|
759
|
+
* `.execute()` path, where only the `.packageJson(data)` overload can
|
|
760
|
+
* contribute. Idempotent — already-resolved fields pass through unchanged.
|
|
761
|
+
*
|
|
762
|
+
* @internal
|
|
763
|
+
*/
|
|
764
|
+
function resolveHelpLinksSchema(schema) {
|
|
765
|
+
if (schema.helpLinks === void 0) return schema;
|
|
766
|
+
return {
|
|
767
|
+
...schema,
|
|
768
|
+
helpLinks: deriveHelpLinks(schema.helpLinks, schema.packageJsonSettings?.data, schema.version)
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
/** Default manifest filenames for `.manifest()` / `.packageJson()`. @internal */
|
|
772
|
+
const DEFAULT_MANIFEST_FILES = ["package.json"];
|
|
773
|
+
/** Manifest filenames for the `.denoJson()` preset, in priority order. @internal */
|
|
774
|
+
const DENO_MANIFEST_FILES = [
|
|
775
|
+
"deno.json",
|
|
776
|
+
"deno.jsonc",
|
|
777
|
+
"jsr.json"
|
|
778
|
+
];
|
|
779
|
+
/**
|
|
780
|
+
* Normalise an {@link InferNameOption} into the flat `{ inferName, stripScope }`
|
|
781
|
+
* pair stored in {@link ResolvedManifestSettings}.
|
|
782
|
+
*
|
|
783
|
+
* @internal
|
|
784
|
+
*/
|
|
785
|
+
function normalizeInferName(option) {
|
|
786
|
+
if (option === void 0 || option === false) return {
|
|
787
|
+
inferName: false,
|
|
788
|
+
stripScope: true
|
|
789
|
+
};
|
|
790
|
+
if (option === true) return {
|
|
791
|
+
inferName: true,
|
|
792
|
+
stripScope: true
|
|
793
|
+
};
|
|
794
|
+
return {
|
|
795
|
+
inferName: true,
|
|
796
|
+
stripScope: option.scope !== "keep"
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Build the next {@link CLISchema} for a manifest builder method.
|
|
801
|
+
*
|
|
802
|
+
* Shared by {@link CLIBuilder.manifest}, {@link CLIBuilder.packageJson}, and
|
|
803
|
+
* {@link CLIBuilder.denoJson}. The data overload (detected via field shape)
|
|
804
|
+
* merges `version`/`description` immediately so `.execute()` sees them; the
|
|
805
|
+
* settings overload stores discovery config for runtime preflight.
|
|
806
|
+
*
|
|
807
|
+
* @internal
|
|
808
|
+
*/
|
|
809
|
+
function buildManifestSchema(schema, input, defaultFiles, pinFiles) {
|
|
810
|
+
if (isPackageJsonData(input)) return {
|
|
811
|
+
...schema,
|
|
812
|
+
...schema.version === void 0 && input.version !== void 0 ? { version: input.version } : {},
|
|
813
|
+
...schema.description === void 0 && input.description !== void 0 ? { description: input.description } : {},
|
|
814
|
+
packageJsonSettings: {
|
|
815
|
+
inferName: false,
|
|
816
|
+
stripScope: true,
|
|
817
|
+
from: void 0,
|
|
818
|
+
files: defaultFiles,
|
|
819
|
+
data: input
|
|
820
|
+
}
|
|
821
|
+
};
|
|
822
|
+
const { inferName, stripScope } = normalizeInferName(input?.inferName);
|
|
823
|
+
const files = pinFiles ? defaultFiles : input?.files ?? defaultFiles;
|
|
824
|
+
return {
|
|
825
|
+
...schema,
|
|
826
|
+
packageJsonSettings: {
|
|
827
|
+
inferName,
|
|
828
|
+
stripScope,
|
|
829
|
+
from: normalizeFromSetting(input?.from),
|
|
830
|
+
files,
|
|
831
|
+
data: void 0
|
|
832
|
+
}
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
/**
|
|
836
|
+
* Coerce a {@link ResolvedManifestSettings.from | `manifest.from`} input
|
|
837
|
+
* (string path, `file:` URL string, or {@link URL} instance) to a plain
|
|
838
|
+
* filesystem path string. `undefined` passes through unchanged.
|
|
839
|
+
*
|
|
840
|
+
* Runtime-agnostic by design — relies only on the `URL` global (available in
|
|
841
|
+
* every JS runtime) rather than `node:url`, keeping core free of Node
|
|
842
|
+
* built-ins. Non-`file:` inputs are returned unchanged as paths.
|
|
843
|
+
*
|
|
844
|
+
* @internal
|
|
845
|
+
*/
|
|
846
|
+
function normalizeFromSetting(from) {
|
|
847
|
+
if (from === void 0) return void 0;
|
|
848
|
+
if (from instanceof URL) {
|
|
849
|
+
if (from.protocol !== "file:") return from.href;
|
|
850
|
+
} else if (!from.startsWith("file:")) return from;
|
|
851
|
+
const decoded = decodeURIComponent(new URL(from).pathname);
|
|
852
|
+
if (/^\/[A-Za-z]:/.test(decoded)) return decoded.slice(1).replace(/\//g, "\\");
|
|
853
|
+
return decoded;
|
|
854
|
+
}
|
|
855
|
+
/**
|
|
856
|
+
* Predicate distinguishing the {@link PackageJsonData | data} overload of
|
|
857
|
+
* `.packageJson()` from the settings overload at runtime.
|
|
858
|
+
*
|
|
859
|
+
* A value is treated as `PackageJsonData` when it's a plain object that
|
|
860
|
+
* carries at least one recognised field (`name`, `version`, `description`,
|
|
861
|
+
* `bin`, `homepage`, or `repository`). An empty `{}` or a settings-shaped
|
|
862
|
+
* object (`inferName` / `from`) falls through to the settings overload.
|
|
863
|
+
*
|
|
864
|
+
* npm's `files` field (publish globs) is intentionally NOT recognised here, so
|
|
865
|
+
* an object whose only key is `files` routes to the settings overload — where
|
|
866
|
+
* `files` means candidate manifest filenames, never publish globs. Manifests
|
|
867
|
+
* that publish a CLI carry `name`/`version`, so those route to the data overload
|
|
868
|
+
* as expected.
|
|
869
|
+
*
|
|
870
|
+
* Edge case: a metadata-less manifest (e.g. a versionless private-root
|
|
871
|
+
* `package.json` carrying only `files`/`private`) routes to settings, so its
|
|
872
|
+
* `files` would be read as candidate filenames and the object is not stored as
|
|
873
|
+
* data. This is harmless in practice — a metadata-less manifest contributes no
|
|
874
|
+
* `version`/`description` either way — but it means a pre-loaded object must
|
|
875
|
+
* carry real metadata to be honoured as data.
|
|
876
|
+
*
|
|
877
|
+
* @internal
|
|
878
|
+
*/
|
|
879
|
+
function isPackageJsonData(value) {
|
|
880
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
|
|
881
|
+
return "name" in value || "version" in value || "description" in value || "bin" in value || "homepage" in value || "repository" in value;
|
|
882
|
+
}
|
|
883
|
+
function cli(nameOrOptions) {
|
|
884
|
+
return new CLIBuilder({
|
|
885
|
+
name: typeof nameOrOptions === "string" ? nameOrOptions : nameOrOptions.name ?? "cli",
|
|
886
|
+
inheritName: typeof nameOrOptions === "string" ? false : nameOrOptions.inherit ?? false,
|
|
887
|
+
version: void 0,
|
|
888
|
+
description: void 0,
|
|
889
|
+
commands: [],
|
|
890
|
+
defaultCommand: void 0,
|
|
891
|
+
configSettings: void 0,
|
|
892
|
+
packageJsonSettings: void 0,
|
|
893
|
+
helpLinks: void 0,
|
|
894
|
+
hasBuiltInCompletions: false,
|
|
895
|
+
completionsFlag: void 0,
|
|
896
|
+
helpConfig: void 0,
|
|
897
|
+
plugins: []
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
//#endregion
|
|
901
|
+
export { CLIBuilder, cli };
|