@camunda8/cli 4.2.0 → 4.2.1-alpha.1

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 (39) hide show
  1. package/PLUGIN-HELP.md +93 -7
  2. package/dist/commands/plugins.d.ts.map +1 -1
  3. package/dist/commands/plugins.js +22 -3
  4. package/dist/commands/plugins.js.map +1 -1
  5. package/dist/commands/process-instances.d.ts.map +1 -1
  6. package/dist/commands/process-instances.js +9 -17
  7. package/dist/commands/process-instances.js.map +1 -1
  8. package/dist/default-plugins/cluster/c8ctl-plugin.js +59 -82
  9. package/dist/framework/argv-parser.d.ts +182 -0
  10. package/dist/framework/argv-parser.d.ts.map +1 -0
  11. package/dist/framework/argv-parser.js +488 -0
  12. package/dist/framework/argv-parser.js.map +1 -0
  13. package/dist/framework/command-registry.d.ts +14 -8
  14. package/dist/framework/command-registry.d.ts.map +1 -1
  15. package/dist/framework/command-registry.js +18 -13
  16. package/dist/framework/command-registry.js.map +1 -1
  17. package/dist/framework/index.d.ts +2 -0
  18. package/dist/framework/index.d.ts.map +1 -1
  19. package/dist/framework/index.js +2 -0
  20. package/dist/framework/index.js.map +1 -1
  21. package/dist/framework/plugins/plugin-flags.d.ts +46 -0
  22. package/dist/framework/plugins/plugin-flags.d.ts.map +1 -0
  23. package/dist/framework/plugins/plugin-flags.js +80 -0
  24. package/dist/framework/plugins/plugin-flags.js.map +1 -0
  25. package/dist/framework/plugins/plugin-loader.d.ts +17 -0
  26. package/dist/framework/plugins/plugin-loader.d.ts.map +1 -1
  27. package/dist/framework/plugins/plugin-loader.js +32 -1
  28. package/dist/framework/plugins/plugin-loader.js.map +1 -1
  29. package/dist/framework/ui/completion.d.ts.map +1 -1
  30. package/dist/framework/ui/completion.js +12 -3
  31. package/dist/framework/ui/completion.js.map +1 -1
  32. package/dist/framework/ui/help.d.ts.map +1 -1
  33. package/dist/framework/ui/help.js +8 -0
  34. package/dist/framework/ui/help.js.map +1 -1
  35. package/dist/index.d.ts +0 -23
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +186 -310
  38. package/dist/index.js.map +1 -1
  39. package/package.json +1 -1
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Two-stage command-line parser.
3
+ *
4
+ * ```
5
+ * c8ctl [global flags] <verb> [<resource>] [verb flags + post-verb globals] [args]
6
+ * ```
7
+ *
8
+ * - **Stage 1** ({@link splitGlobals}) parses `GLOBAL_FLAGS` only, walking the
9
+ * argv from the start, and stops at the first positional — the verb. Every
10
+ * token after the verb is returned untouched (`rest`) so stage 2 can parse
11
+ * it against the flag table of *that* command.
12
+ * - **Stage 2** ({@link parseBuiltinVerbArgs} for built-in verbs, or
13
+ * {@link parseFlags} with a caller-built table for plugin verbs) parses
14
+ * `rest` against `GLOBAL_FLAGS ∪ effectiveFlags(verb, resource)`. Globals
15
+ * stay accepted after the verb (the lenient variant), so
16
+ * `c8ctl list pi --json` keeps working.
17
+ *
18
+ * Because each command is parsed against its own table, a flag name can mean
19
+ * different things on different commands without any handler re-reading
20
+ * `process.argv`: `--variables` is boolean for `get pi` and a string for
21
+ * `create pi`; `--version` is a boolean global before the verb (show the CLI
22
+ * version) and the string definition-version filter after `list pi`.
23
+ *
24
+ * This module also owns the raw-argv helpers the host needs for plugin
25
+ * commands (global-flag stripping for passthrough plugins, blocked-flag
26
+ * stripping for the plugin flag re-parse), so there is one place that knows
27
+ * how to walk flag tokens.
28
+ */
29
+ import { parseArgs } from "node:util";
30
+ /** One entry of a `node:util` `parseArgs` options table. */
31
+ export interface ParseOption {
32
+ type: "string" | "boolean";
33
+ short?: string;
34
+ multiple?: boolean;
35
+ }
36
+ /** A `parseArgs` options table. Null-prototype so flag names like `__proto__` are inert. */
37
+ export type ParseOptions = Record<string, ParseOption>;
38
+ /** Values produced by `parseArgs` with `strict: false`. */
39
+ export type ParsedValues = Record<string, string | boolean | (string | boolean)[] | undefined>;
40
+ /** A token as reported by `parseArgs({ tokens: true })`. */
41
+ export type ArgToken = NonNullable<ReturnType<typeof parseArgs>["tokens"]>[number];
42
+ /** `GLOBAL_FLAGS` exactly as declared (`--version` is a string: the post-verb definition-version filter). */
43
+ export declare function globalOptions(): ParseOptions;
44
+ /**
45
+ * The one place `parseArgs` is called for command-line parsing. Lenient
46
+ * (`strict: false`): unknown flags never throw — they are reported later as
47
+ * warnings by the unknown-flag detector.
48
+ */
49
+ export declare function parseFlags({ args, options, }: {
50
+ args: readonly string[];
51
+ options: ParseOptions;
52
+ }): {
53
+ values: ParsedValues;
54
+ positionals: string[];
55
+ tokens: ArgToken[];
56
+ };
57
+ /** A flag found before the verb that is not a global flag. */
58
+ export interface MisplacedFlag {
59
+ /** The token exactly as typed, e.g. `--limit` or `--limit=5`. */
60
+ token: string;
61
+ /** Flag name without dashes (`limit`, or `x` for `-x`). */
62
+ name: string;
63
+ /** True for the `--name=value` form (the value is part of the token). */
64
+ inlineValue: boolean;
65
+ /** Index of the token in argv. */
66
+ index: number;
67
+ }
68
+ export interface Stage1Result {
69
+ /** Global flags that appeared before the verb. `version` is `true` when `--version` / `-v` was given. */
70
+ globals: ParsedValues;
71
+ /** The raw verb token (may be an alias or a plugin verb), or `undefined` when there is none. */
72
+ verb: string | undefined;
73
+ /** Every argv token after the verb, verbatim. */
74
+ rest: string[];
75
+ /**
76
+ * Non-global flags that appeared before the verb. Only globals are valid
77
+ * there, so the host reports these instead of dispatching: the "verb"
78
+ * stage 1 stopped at may really be such a flag's value.
79
+ */
80
+ misplaced: MisplacedFlag[];
81
+ }
82
+ /**
83
+ * Stage 1: parse `GLOBAL_FLAGS` from the front of `argv` and stop at the
84
+ * verb. A `--` terminator is skipped, so `c8ctl -- list pi` still dispatches
85
+ * `list`; a `--` after the verb is left in `rest` for stage 2.
86
+ */
87
+ export declare function splitGlobals(argv: readonly string[]): Stage1Result;
88
+ /**
89
+ * `effectiveFlags(verb, resource)` as stage 2 parses it: the globals, the
90
+ * verb-level flags, and the flag bucket of `resource` only — never the
91
+ * buckets of sibling resources.
92
+ */
93
+ export declare function stage2Options({ verb, resource, }: {
94
+ verb: string;
95
+ resource: string;
96
+ }): ParseOptions;
97
+ export interface VerbArgs {
98
+ /** Canonical verb (aliases resolved). */
99
+ verb: string;
100
+ /** The resource as typed (alias/plural form), or `""`. */
101
+ resource: string;
102
+ /** The canonical resource name, or `""`. */
103
+ normalizedResource: string;
104
+ /** Positionals after the resource. */
105
+ args: string[];
106
+ /** Post-verb flag values (globals included). */
107
+ values: ParsedValues;
108
+ /** The parse tokens of the post-verb argv (spelling as typed). */
109
+ tokens: ArgToken[];
110
+ }
111
+ /**
112
+ * Stage 2: find the resource, pick `effectiveFlags(verb, resource)`, and
113
+ * parse `rest` against exactly that table.
114
+ *
115
+ * A verb that is not in the registry (a plugin verb, the reserved `help` /
116
+ * `menu` verbs, or a typo) is parsed against `GLOBAL_FLAGS` alone: a plugin's
117
+ * own flags are re-parsed from `rest` by the host once it has loaded the
118
+ * plugin's flag declarations.
119
+ */
120
+ export declare function parseVerbArgs({ rawVerb, rest, }: {
121
+ rawVerb: string;
122
+ rest: readonly string[];
123
+ }): VerbArgs;
124
+ /**
125
+ * Strip GLOBAL_FLAGS (and the value of any string-typed global flag) from
126
+ * the argv tail forwarded to a passthrough plugin handler.
127
+ * GLOBAL_FLAGS already affect the c8ctl runtime via their regular handling in
128
+ * `main()`; the plugin must not see them again.
129
+ *
130
+ * Conservative behaviour: an isolated `--` terminator is preserved and
131
+ * everything after it is forwarded verbatim, matching POSIX convention.
132
+ */
133
+ export declare function stripGlobalFlags(argv: readonly string[]): string[];
134
+ /**
135
+ * Remove tokens for blocked plugin flags from an argv slice so they cannot
136
+ * shift positionals during the plugin-flag re-parse.
137
+ *
138
+ * "Blocked" exclusively means "collides with a GLOBAL flag".
139
+ * The user may have supplied a value token (`--name value`) intending
140
+ * either:
141
+ * - the GLOBAL's interpretation (global type === "string"), or
142
+ * - the PLUGIN's interpretation (plugin type === "string", e.g. global
143
+ * is boolean but the plugin declared the same name as string).
144
+ *
145
+ * Either way the value is meaningless to both sides (plugin's flag is
146
+ * blocked; global is consumed by the host elsewhere) and must not leak
147
+ * into the plugin's positional args. Strip the following non-flag token
148
+ * if either side typed the flag as string. A reserved short alias
149
+ * (`reservedShorts`, e.g. a plugin's `-y` that is also c8ctl's `-y`) is
150
+ * stripped the same way.
151
+ */
152
+ export declare function stripBlockedFlagTokens({ argv, blocked, reservedShorts, pluginFlagDefs, globalFlagDefs, }: {
153
+ argv: readonly string[];
154
+ blocked: ReadonlySet<string>;
155
+ reservedShorts?: readonly {
156
+ name: string;
157
+ short: string;
158
+ }[];
159
+ pluginFlagDefs: Record<string, {
160
+ type: string;
161
+ }>;
162
+ globalFlagDefs: Record<string, {
163
+ type: string;
164
+ short?: string;
165
+ }>;
166
+ }): string[];
167
+ type TypedFlagDefs = Record<string, {
168
+ type: string;
169
+ short?: string;
170
+ } | undefined>;
171
+ /**
172
+ * Error text for non-global flags placed before the command. Names the
173
+ * surface (globals before the command, command flags after it) and, when it
174
+ * can be verified, shows the corrected order.
175
+ */
176
+ export declare function describeMisplacedFlags({ argv, misplaced, pluginFlags, }: {
177
+ argv: readonly string[];
178
+ misplaced: readonly MisplacedFlag[];
179
+ pluginFlags: Record<string, TypedFlagDefs>;
180
+ }): string;
181
+ export {};
182
+ //# sourceMappingURL=argv-parser.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"argv-parser.d.ts","sourceRoot":"","sources":["../../src/framework/argv-parser.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAatC,4DAA4D;AAC5D,MAAM,WAAW,WAAW;IAC3B,IAAI,EAAE,QAAQ,GAAG,SAAS,CAAC;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,OAAO,CAAC;CACnB;AAED,4FAA4F;AAC5F,MAAM,MAAM,YAAY,GAAG,MAAM,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KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;CACjE,GAAG,MAAM,EAAE,CAqDX;AAID,KAAK,aAAa,GAAG,MAAM,CAC1B,MAAM,EACN;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,SAAS,CAC5C,CAAC;AA+GF;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,EACtC,IAAI,EACJ,SAAS,EACT,WAAW,GACX,EAAE;IACF,IAAI,EAAE,SAAS,MAAM,EAAE,CAAC;IACxB,SAAS,EAAE,SAAS,aAAa,EAAE,CAAC;IACpC,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,aAAa,CAAC,CAAC;CAC3C,GAAG,MAAM,CAmBT"}
@@ -0,0 +1,488 @@
1
+ /**
2
+ * Two-stage command-line parser.
3
+ *
4
+ * ```
5
+ * c8ctl [global flags] <verb> [<resource>] [verb flags + post-verb globals] [args]
6
+ * ```
7
+ *
8
+ * - **Stage 1** ({@link splitGlobals}) parses `GLOBAL_FLAGS` only, walking the
9
+ * argv from the start, and stops at the first positional — the verb. Every
10
+ * token after the verb is returned untouched (`rest`) so stage 2 can parse
11
+ * it against the flag table of *that* command.
12
+ * - **Stage 2** ({@link parseBuiltinVerbArgs} for built-in verbs, or
13
+ * {@link parseFlags} with a caller-built table for plugin verbs) parses
14
+ * `rest` against `GLOBAL_FLAGS ∪ effectiveFlags(verb, resource)`. Globals
15
+ * stay accepted after the verb (the lenient variant), so
16
+ * `c8ctl list pi --json` keeps working.
17
+ *
18
+ * Because each command is parsed against its own table, a flag name can mean
19
+ * different things on different commands without any handler re-reading
20
+ * `process.argv`: `--variables` is boolean for `get pi` and a string for
21
+ * `create pi`; `--version` is a boolean global before the verb (show the CLI
22
+ * version) and the string definition-version filter after `list pi`.
23
+ *
24
+ * This module also owns the raw-argv helpers the host needs for plugin
25
+ * commands (global-flag stripping for passthrough plugins, blocked-flag
26
+ * stripping for the plugin flag re-parse), so there is one place that knows
27
+ * how to walk flag tokens.
28
+ */
29
+ import { parseArgs } from "node:util";
30
+ import { COMMAND_REGISTRY_BY_VERB, GLOBAL_FLAGS, getCommandDef, resolveAlias, resolveVerbAlias, VERB_ALIASES, } from "./command-registry.js";
31
+ function emptyOptions() {
32
+ return Object.create(null);
33
+ }
34
+ /** Add `defs` to `target`. On a name clash `string` wins and `multiple` sticks. */
35
+ function addOptions({ target, defs, }) {
36
+ for (const [name, def] of Object.entries(defs)) {
37
+ if (!def)
38
+ continue;
39
+ const existing = target[name];
40
+ if (!existing) {
41
+ target[name] = {
42
+ type: def.type,
43
+ ...(def.short && { short: def.short }),
44
+ ...(def.multiple && { multiple: true }),
45
+ };
46
+ continue;
47
+ }
48
+ if (def.type === "string")
49
+ existing.type = "string";
50
+ if (def.short && !existing.short)
51
+ existing.short = def.short;
52
+ if (def.multiple)
53
+ existing.multiple = true;
54
+ }
55
+ return target;
56
+ }
57
+ /** `GLOBAL_FLAGS` exactly as declared (`--version` is a string: the post-verb definition-version filter). */
58
+ export function globalOptions() {
59
+ return addOptions({ target: emptyOptions(), defs: GLOBAL_FLAGS });
60
+ }
61
+ /**
62
+ * The stage-1 table: `GLOBAL_FLAGS`, except that `--version` / `-v` is a
63
+ * plain boolean. Before the verb it can only mean "show the CLI version", and
64
+ * a boolean cannot swallow the verb that follows it (`c8ctl --version list pi`).
65
+ */
66
+ function stage1Options() {
67
+ const options = globalOptions();
68
+ options.version = { type: "boolean", short: GLOBAL_FLAGS.version.short };
69
+ return options;
70
+ }
71
+ // ─── Core tokenising parse ───────────────────────────────────────────────────
72
+ /** True when `token` is a flag in `options` (or the `--` terminator) and so cannot be a flag's value. */
73
+ function isKnownFlagToken({ token, options, }) {
74
+ if (token === "--")
75
+ return true;
76
+ if (token.startsWith("--")) {
77
+ const eq = token.indexOf("=");
78
+ return Object.hasOwn(options, eq < 0 ? token.slice(2) : token.slice(2, eq));
79
+ }
80
+ return (token.length === 2 &&
81
+ token.startsWith("-") &&
82
+ Object.values(options).some((o) => o.short === token[1]));
83
+ }
84
+ /**
85
+ * Stand-in value for "a string flag that was given no value because the next
86
+ * token is another flag". NUL cannot occur in an argv entry, so it cannot
87
+ * collide with real input. {@link parseFlags} turns it into `true` — the same
88
+ * thing `parseArgs` reports for a string flag at the very end of the line.
89
+ */
90
+ const NO_VALUE = "\u0000no-value";
91
+ /**
92
+ * `parseArgs` hands the next token to a string flag as its value even when
93
+ * that token is itself a flag (`--fields --dry-run` yields
94
+ * `fields: "--dry-run"` and silently drops `--dry-run`). Rewrite such a
95
+ * string flag to `--name=<NO_VALUE>` so the following known flag is parsed as
96
+ * a flag and the string flag reads as `true` (given, no value). Token
97
+ * positions are preserved. Only *known* flags are treated this way, so
98
+ * values that merely start with a dash (`--limit -5`) are untouched.
99
+ */
100
+ function protectFlagLikeValues({ args, options, }) {
101
+ const out = [...args];
102
+ const nameForShort = (char) => Object.entries(options).find(([, o]) => o.short === char)?.[0];
103
+ for (let i = 0; i < out.length - 1; i++) {
104
+ const token = out[i];
105
+ if (token === "--")
106
+ break;
107
+ let name;
108
+ if (token.startsWith("--") && !token.includes("=")) {
109
+ name = token.slice(2);
110
+ }
111
+ else if (token.length === 2 &&
112
+ token.startsWith("-") &&
113
+ token[1] !== "-") {
114
+ name = nameForShort(token[1]);
115
+ }
116
+ if (name === undefined || options[name]?.type !== "string")
117
+ continue;
118
+ if (isKnownFlagToken({ token: out[i + 1], options })) {
119
+ out[i] = `--${name}=${NO_VALUE}`;
120
+ }
121
+ }
122
+ return out;
123
+ }
124
+ /**
125
+ * The one place `parseArgs` is called for command-line parsing. Lenient
126
+ * (`strict: false`): unknown flags never throw — they are reported later as
127
+ * warnings by the unknown-flag detector.
128
+ */
129
+ export function parseFlags({ args, options, }) {
130
+ const { values, positionals, tokens } = parseArgs({
131
+ args: protectFlagLikeValues({ args, options }),
132
+ options,
133
+ allowPositionals: true,
134
+ strict: false,
135
+ tokens: true,
136
+ });
137
+ const resolved = Object.create(null);
138
+ for (const [name, value] of Object.entries(values)) {
139
+ resolved[name] = Array.isArray(value)
140
+ ? value.map((v) => (v === NO_VALUE ? true : v))
141
+ : value === NO_VALUE
142
+ ? true
143
+ : value;
144
+ }
145
+ return { values: resolved, positionals, tokens: tokens ?? [] };
146
+ }
147
+ /**
148
+ * Stage 1: parse `GLOBAL_FLAGS` from the front of `argv` and stop at the
149
+ * verb. A `--` terminator is skipped, so `c8ctl -- list pi` still dispatches
150
+ * `list`; a `--` after the verb is left in `rest` for stage 2.
151
+ */
152
+ export function splitGlobals(argv) {
153
+ const options = stage1Options();
154
+ const { tokens, values } = parseFlags({ args: argv, options });
155
+ const verbToken = tokens.find((t) => t.kind === "positional");
156
+ const end = verbToken ? verbToken.index : argv.length;
157
+ const misplaced = [];
158
+ for (const token of tokens) {
159
+ if (token.kind !== "option" || token.index >= end)
160
+ continue;
161
+ if (Object.hasOwn(options, token.name))
162
+ continue;
163
+ misplaced.push({
164
+ token: argv[token.index],
165
+ name: token.name,
166
+ inlineValue: token.inlineValue === true,
167
+ index: token.index,
168
+ });
169
+ }
170
+ if (!verbToken)
171
+ return { globals: values, verb: undefined, rest: [], misplaced };
172
+ return {
173
+ globals: parseFlags({ args: argv.slice(0, verbToken.index), options })
174
+ .values,
175
+ verb: verbToken.value,
176
+ rest: argv.slice(verbToken.index + 1),
177
+ misplaced,
178
+ };
179
+ }
180
+ // ─── Stage 2 (built-in verbs) ────────────────────────────────────────────────
181
+ /** Canonical verb names an input verb (canonical or alias) can refer to. */
182
+ function verbTargets(rawVerb) {
183
+ if (Object.hasOwn(COMMAND_REGISTRY_BY_VERB, rawVerb))
184
+ return [rawVerb];
185
+ return Object.hasOwn(VERB_ALIASES, rawVerb) ? VERB_ALIASES[rawVerb] : [];
186
+ }
187
+ /**
188
+ * Every flag any resource of `rawVerb` declares, plus globals. Used only to
189
+ * *find* the resource token — which flag values to skip while looking — never
190
+ * to parse the command. Names clash only across different verbs, so within
191
+ * one verb this is unambiguous.
192
+ */
193
+ function verbLocatorOptions(rawVerb) {
194
+ const options = globalOptions();
195
+ for (const target of verbTargets(rawVerb)) {
196
+ const def = COMMAND_REGISTRY_BY_VERB[target];
197
+ if (!def)
198
+ continue;
199
+ addOptions({ target: options, defs: def.flags });
200
+ for (const bucket of Object.values(def.resourceFlags ?? {})) {
201
+ addOptions({ target: options, defs: bucket });
202
+ }
203
+ }
204
+ return options;
205
+ }
206
+ /**
207
+ * `effectiveFlags(verb, resource)` as stage 2 parses it: the globals, the
208
+ * verb-level flags, and the flag bucket of `resource` only — never the
209
+ * buckets of sibling resources.
210
+ */
211
+ export function stage2Options({ verb, resource, }) {
212
+ const options = globalOptions();
213
+ const def = getCommandDef(verb);
214
+ if (!def)
215
+ return options;
216
+ addOptions({ target: options, defs: def.flags });
217
+ // Same plural fallback `detectUnknownFlags` applies, so a flag accepted
218
+ // there without a warning is also parsed here.
219
+ const bucket = def.resourceFlags?.[resource] ??
220
+ def.resourceFlags?.[resource.replace(/s$/, "")];
221
+ if (bucket)
222
+ addOptions({ target: options, defs: bucket });
223
+ return options;
224
+ }
225
+ /**
226
+ * Stage 2: find the resource, pick `effectiveFlags(verb, resource)`, and
227
+ * parse `rest` against exactly that table.
228
+ *
229
+ * A verb that is not in the registry (a plugin verb, the reserved `help` /
230
+ * `menu` verbs, or a typo) is parsed against `GLOBAL_FLAGS` alone: a plugin's
231
+ * own flags are re-parsed from `rest` by the host once it has loaded the
232
+ * plugin's flag declarations.
233
+ */
234
+ export function parseVerbArgs({ rawVerb, rest, }) {
235
+ const [located] = parseFlags({
236
+ args: rest,
237
+ options: verbLocatorOptions(rawVerb),
238
+ }).positionals;
239
+ const verb = resolveVerbAlias(rawVerb, located);
240
+ const normalizedResource = located ? resolveAlias(located) : "";
241
+ const { values, positionals, tokens } = parseFlags({
242
+ args: rest,
243
+ options: stage2Options({ verb, resource: normalizedResource }),
244
+ });
245
+ const [resource = "", ...args] = positionals;
246
+ return {
247
+ verb,
248
+ resource,
249
+ normalizedResource: resource ? resolveAlias(resource) : "",
250
+ args,
251
+ values,
252
+ tokens,
253
+ };
254
+ }
255
+ // ─── Raw-argv helpers for plugin commands ────────────────────────────────────
256
+ /**
257
+ * Strip GLOBAL_FLAGS (and the value of any string-typed global flag) from
258
+ * the argv tail forwarded to a passthrough plugin handler.
259
+ * GLOBAL_FLAGS already affect the c8ctl runtime via their regular handling in
260
+ * `main()`; the plugin must not see them again.
261
+ *
262
+ * Conservative behaviour: an isolated `--` terminator is preserved and
263
+ * everything after it is forwarded verbatim, matching POSIX convention.
264
+ */
265
+ export function stripGlobalFlags(argv) {
266
+ const booleanFlags = new Set();
267
+ const stringFlags = new Set();
268
+ const booleanShorts = new Set();
269
+ const stringShorts = new Set();
270
+ for (const [name, def] of Object.entries(GLOBAL_FLAGS)) {
271
+ const short = "short" in def ? def.short : undefined;
272
+ if (def.type === "boolean") {
273
+ booleanFlags.add(name);
274
+ if (short)
275
+ booleanShorts.add(short);
276
+ }
277
+ else {
278
+ stringFlags.add(name);
279
+ if (short)
280
+ stringShorts.add(short);
281
+ }
282
+ }
283
+ const out = [];
284
+ let i = 0;
285
+ let sawTerminator = false;
286
+ while (i < argv.length) {
287
+ const tok = argv[i];
288
+ if (sawTerminator) {
289
+ out.push(tok);
290
+ i++;
291
+ continue;
292
+ }
293
+ if (tok === "--") {
294
+ sawTerminator = true;
295
+ out.push(tok);
296
+ i++;
297
+ continue;
298
+ }
299
+ if (tok.startsWith("--")) {
300
+ const eq = tok.indexOf("=");
301
+ const name = eq >= 0 ? tok.slice(2, eq) : tok.slice(2);
302
+ if (booleanFlags.has(name) || stringFlags.has(name)) {
303
+ if (eq < 0 && stringFlags.has(name) && argv[i + 1] !== "--")
304
+ i++; // consume value, never the terminator
305
+ i++;
306
+ continue;
307
+ }
308
+ }
309
+ else if (tok.startsWith("-") && tok.length === 2) {
310
+ const short = tok.slice(1);
311
+ if (booleanShorts.has(short)) {
312
+ i++;
313
+ continue;
314
+ }
315
+ if (stringShorts.has(short)) {
316
+ i += argv[i + 1] === "--" ? 1 : 2; // consume short flag and its value, never the terminator
317
+ continue;
318
+ }
319
+ }
320
+ out.push(tok);
321
+ i++;
322
+ }
323
+ return out;
324
+ }
325
+ /**
326
+ * Remove tokens for blocked plugin flags from an argv slice so they cannot
327
+ * shift positionals during the plugin-flag re-parse.
328
+ *
329
+ * "Blocked" exclusively means "collides with a GLOBAL flag".
330
+ * The user may have supplied a value token (`--name value`) intending
331
+ * either:
332
+ * - the GLOBAL's interpretation (global type === "string"), or
333
+ * - the PLUGIN's interpretation (plugin type === "string", e.g. global
334
+ * is boolean but the plugin declared the same name as string).
335
+ *
336
+ * Either way the value is meaningless to both sides (plugin's flag is
337
+ * blocked; global is consumed by the host elsewhere) and must not leak
338
+ * into the plugin's positional args. Strip the following non-flag token
339
+ * if either side typed the flag as string. A reserved short alias
340
+ * (`reservedShorts`, e.g. a plugin's `-y` that is also c8ctl's `-y`) is
341
+ * stripped the same way.
342
+ */
343
+ export function stripBlockedFlagTokens({ argv, blocked, reservedShorts = [], pluginFlagDefs, globalFlagDefs, }) {
344
+ const out = [];
345
+ let i = 0;
346
+ while (i < argv.length) {
347
+ const arg = argv[i];
348
+ if (arg === "--") {
349
+ // Terminator: it and everything after it are literal positionals.
350
+ out.push(...argv.slice(i));
351
+ break;
352
+ }
353
+ if (arg.startsWith("--")) {
354
+ const eqIdx = arg.indexOf("=");
355
+ const name = eqIdx >= 0 ? arg.slice(2, eqIdx) : arg.slice(2);
356
+ if (blocked.has(name)) {
357
+ const eitherIsString = pluginFlagDefs[name]?.type === "string" ||
358
+ globalFlagDefs[name]?.type === "string";
359
+ if (eqIdx < 0 &&
360
+ eitherIsString &&
361
+ i + 1 < argv.length &&
362
+ !argv[i + 1].startsWith("-")) {
363
+ i++;
364
+ }
365
+ i++;
366
+ continue;
367
+ }
368
+ }
369
+ const shortOwner = arg.length === 2 && arg[0] === "-" && arg[1] !== "-"
370
+ ? reservedShorts.find((r) => r.short === arg[1])?.name
371
+ : undefined;
372
+ if (shortOwner !== undefined) {
373
+ const eitherIsString = pluginFlagDefs[shortOwner]?.type === "string" ||
374
+ Object.values(globalFlagDefs).some((g) => g.short === arg[1] && g.type === "string");
375
+ if (eitherIsString &&
376
+ i + 1 < argv.length &&
377
+ !argv[i + 1].startsWith("-")) {
378
+ i++;
379
+ }
380
+ i++;
381
+ continue;
382
+ }
383
+ out.push(arg);
384
+ i++;
385
+ }
386
+ return out;
387
+ }
388
+ function findFlagType({ defs, name, }) {
389
+ if (Object.hasOwn(defs, name))
390
+ return defs[name]?.type;
391
+ return Object.values(defs).find((d) => d?.short === name)?.type;
392
+ }
393
+ /** Quote a token for display only when it needs it. */
394
+ function display(token) {
395
+ return /\s/.test(token) ? JSON.stringify(token) : token;
396
+ }
397
+ /** `--help/-h, --version/-v, --profile, ...` for one-line reference. */
398
+ function globalFlagSummary() {
399
+ return Object.entries(GLOBAL_FLAGS)
400
+ .map(([name, def]) => {
401
+ const short = "short" in def ? def.short : undefined;
402
+ return short ? `--${name}/-${short}` : `--${name}`;
403
+ })
404
+ .join(", ");
405
+ }
406
+ /**
407
+ * Does the command that `argv` (minus the misplaced flag) dispatches to
408
+ * declare `flag` with `type`? Verifies a correction instead of guessing one.
409
+ */
410
+ function commandDeclares({ argv, pluginFlags, name, type, }) {
411
+ const { verb, rest } = splitGlobals(argv);
412
+ if (!verb)
413
+ return false;
414
+ if (getCommandDef(verb)) {
415
+ const parsed = parseVerbArgs({ rawVerb: verb, rest });
416
+ const defs = stage2Options({
417
+ verb: parsed.verb,
418
+ resource: parsed.normalizedResource,
419
+ });
420
+ return findFlagType({ defs, name }) === type;
421
+ }
422
+ const defs = Object.hasOwn(pluginFlags, verb) ? pluginFlags[verb] : undefined;
423
+ return defs !== undefined && findFlagType({ defs, name }) === type;
424
+ }
425
+ /**
426
+ * The corrected command line for a single misplaced flag, or `undefined`
427
+ * when it cannot be verified. The flag may be boolean (only its token
428
+ * moves) or take a value (the next token moves with it); a hypothesis is
429
+ * accepted only when the command it leaves behind declares the flag with
430
+ * that type.
431
+ */
432
+ function suggestOrder({ argv, flag, pluginFlags, }) {
433
+ const hypotheses = [
434
+ { type: "boolean", width: 1 },
435
+ ...(flag.inlineValue || flag.index + 1 >= argv.length
436
+ ? []
437
+ : [{ type: "string", width: 2 }]),
438
+ ];
439
+ for (const { type, width } of hypotheses) {
440
+ const moved = argv.slice(flag.index, flag.index + width);
441
+ const remaining = [
442
+ ...argv.slice(0, flag.index),
443
+ ...argv.slice(flag.index + width),
444
+ ];
445
+ // `--name=value` is a string flag spelled in one token.
446
+ const effectiveType = flag.inlineValue ? "string" : type;
447
+ if (commandDeclares({
448
+ argv: remaining,
449
+ pluginFlags,
450
+ name: flag.name,
451
+ type: effectiveType,
452
+ })) {
453
+ // Before a `--` after the verb, past which it would be a positional.
454
+ const { rest } = splitGlobals(remaining);
455
+ const cut = rest.includes("--")
456
+ ? remaining.length - rest.length + rest.indexOf("--")
457
+ : remaining.length;
458
+ const corrected = [
459
+ ...remaining.slice(0, cut),
460
+ ...moved,
461
+ ...remaining.slice(cut),
462
+ ];
463
+ return `c8ctl ${corrected.map(display).join(" ")}`;
464
+ }
465
+ }
466
+ return undefined;
467
+ }
468
+ /**
469
+ * Error text for non-global flags placed before the command. Names the
470
+ * surface (globals before the command, command flags after it) and, when it
471
+ * can be verified, shows the corrected order.
472
+ */
473
+ export function describeMisplacedFlags({ argv, misplaced, pluginFlags, }) {
474
+ const names = misplaced.map((m) => m.token.startsWith("--") ? `--${m.name}` : `-${m.name}`);
475
+ const list = names.join(", ");
476
+ const head = misplaced.length === 1
477
+ ? `Flag ${list} is not a global flag; command-specific flags go after the command`
478
+ : `Flags ${list} are not global flags; command-specific flags go after the command`;
479
+ const suggestion = misplaced.length === 1
480
+ ? suggestOrder({ argv, flag: misplaced[0], pluginFlags })
481
+ : undefined;
482
+ if (suggestion)
483
+ return `${head}. Did you mean: ${suggestion}`;
484
+ return (`${head}: c8ctl <command> [args] ${names[0]}. ` +
485
+ `Only global flags may come before the command (${globalFlagSummary()}). ` +
486
+ `Run "c8ctl help <command>" to see a command's flags.`);
487
+ }
488
+ //# sourceMappingURL=argv-parser.js.map