@camunda8/cli 4.2.0 → 4.2.1-alpha.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 (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 +92 -86
  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
package/dist/index.js CHANGED
@@ -5,10 +5,9 @@
5
5
  */
6
6
  import { realpathSync } from "node:fs";
7
7
  import { fileURLToPath } from "node:url";
8
- import { parseArgs } from "node:util";
9
8
  import { COMMAND_DISPATCH } from "./command-dispatch.js";
10
9
  import { c8ctl, createClient, getLogger, getUserDataDir, loadSessionState, printUpdateNotification, resolveTenantId, SilentError, startUpdateCheck, } from "./core/index.js";
11
- import { commandRegistryEntries, createDryRun, deriveParseArgsOptions, detectUnknownFlags, executePluginCommand, GLOBAL_FLAGS, getCommandDef, getPluginCommands, getPluginVersionForCommand, isHostIncompatiblePluginCommand, isPassthroughPluginCommand, loadInstalledPlugins, confirm as promptConfirm, select as promptSelect, refreshCompletionsIfStale, resolveAlias, resolveVerbAlias, showCommandHelp, showHelp, showVerbResources, showVersion, validateFlags, } from "./framework/index.js";
10
+ import { analyzePluginFlags, commandRegistryEntries, createDryRun, describeMisplacedFlags, detectUnknownFlags, executePluginCommand, getCommandDef, getPluginCommands, getPluginVersionForCommand, globalOptions, isHostIncompatiblePluginCommand, isPassthroughPluginCommand, loadInstalledPlugins, parseFlags, parseVerbArgs, confirm as promptConfirm, select as promptSelect, refreshCompletionsIfStale, showCommandHelp, showHelp, showVerbResources, showVersion, splitGlobals, stripBlockedFlagTokens, stripGlobalFlags, typedReservedFlags, undeclaredFlags, validateFlags, } from "./framework/index.js";
12
11
  import { npm } from "./utils/index.js";
13
12
  /**
14
13
  * Type guard: extract a string value from parseArgs values, or undefined.
@@ -32,26 +31,6 @@ function parseVersionFlag(values) {
32
31
  ? parseInt(values.version, 10)
33
32
  : undefined;
34
33
  }
35
- /**
36
- * Parse command line arguments.
37
- * Options are derived from the command registry — no manual duplication.
38
- */
39
- function parseCliArgs() {
40
- try {
41
- const { values, positionals } = parseArgs({
42
- args: process.argv.slice(2),
43
- options: deriveParseArgsOptions(),
44
- allowPositionals: true,
45
- strict: false,
46
- });
47
- return { values, positionals };
48
- }
49
- catch (error) {
50
- const message = error instanceof Error ? error.message : String(error);
51
- console.error(`Error parsing arguments: ${message}`);
52
- process.exit(1);
53
- }
54
- }
55
34
  /**
56
35
  * Resolve process definition ID from --id, --processDefinitionId, or --bpmnProcessId flag
57
36
  */
@@ -61,188 +40,19 @@ export function resolveProcessDefinitionId(values) {
61
40
  str(values.bpmnProcessId));
62
41
  }
63
42
  /**
64
- * Return the raw argv tokens that follow the verb position, where the
65
- * verb position is found by walking from the start and skipping leading
66
- * GLOBAL_FLAGS only (consuming the value of string-typed global flags).
67
- * The first non-flag token — or any unknown `--*`/`-*` token — is
68
- * treated as the verb candidate.
69
- *
70
- * This avoids `argv.indexOf(verb)`, which is unsafe because the verb
71
- * string may also appear as the value of a global string flag (e.g.
72
- * `--profile <verb>`). Returns `[]` if no verb token is found at or
73
- * after the scan position.
74
- */
75
- export function sliceArgvAfterVerb(argv, verb) {
76
- const stringGlobalNames = new Set();
77
- const stringGlobalShorts = new Set();
78
- const booleanGlobalNames = new Set();
79
- const booleanGlobalShorts = new Set();
80
- for (const [name, def] of Object.entries(GLOBAL_FLAGS)) {
81
- const short = "short" in def ? def.short : undefined;
82
- if (def.type === "string") {
83
- stringGlobalNames.add(name);
84
- if (short)
85
- stringGlobalShorts.add(short);
86
- }
87
- else {
88
- booleanGlobalNames.add(name);
89
- if (short)
90
- booleanGlobalShorts.add(short);
91
- }
92
- }
93
- let i = 0;
94
- while (i < argv.length) {
95
- const tok = argv[i];
96
- if (tok === "--") {
97
- // GNU `--` convention: end of options. The next token is the
98
- // verb candidate. Skip the separator and continue scanning so
99
- // `c8ctl -- <verb> <args...>` dispatches correctly with the
100
- // full post-verb argv (rather than bailing and forwarding []).
101
- i++;
102
- continue;
103
- }
104
- if (tok.startsWith("--")) {
105
- const eq = tok.indexOf("=");
106
- const name = eq >= 0 ? tok.slice(2, eq) : tok.slice(2);
107
- if (booleanGlobalNames.has(name)) {
108
- i++;
109
- continue;
110
- }
111
- if (stringGlobalNames.has(name)) {
112
- i += eq < 0 ? 2 : 1;
113
- continue;
114
- }
115
- // Unknown long flag — do not silently consume a value. Fall through
116
- // to the verb match below (and bail if it doesn't match).
117
- }
118
- else if (tok.startsWith("-") && tok.length === 2) {
119
- const short = tok.slice(1);
120
- if (booleanGlobalShorts.has(short)) {
121
- i++;
122
- continue;
123
- }
124
- if (stringGlobalShorts.has(short)) {
125
- i += 2;
126
- continue;
127
- }
128
- }
129
- // First token that is not a leading GLOBAL_FLAG must be the verb.
130
- if (tok === verb)
131
- return argv.slice(i + 1);
132
- return [];
133
- }
134
- return [];
135
- }
136
- /**
137
- * Strip GLOBAL_FLAGS (and the value of any string-typed global flag) from
138
- * a raw argv slice before forwarding to a passthrough plugin handler
139
- * (#366). GLOBAL_FLAGS already affect the c8ctl runtime via their
140
- * regular handling in `main()`; the plugin must not see them again.
141
- *
142
- * Conservative behaviour: an isolated `--` terminator is preserved and
143
- * everything after it is forwarded verbatim, matching POSIX convention.
144
- */
145
- export function stripGlobalFlags(argv) {
146
- const booleanFlags = new Set();
147
- const stringFlags = new Set();
148
- const booleanShorts = new Set();
149
- const stringShorts = new Set();
150
- for (const [name, def] of Object.entries(GLOBAL_FLAGS)) {
151
- const short = "short" in def ? def.short : undefined;
152
- if (def.type === "boolean") {
153
- booleanFlags.add(name);
154
- if (short)
155
- booleanShorts.add(short);
156
- }
157
- else {
158
- stringFlags.add(name);
159
- if (short)
160
- stringShorts.add(short);
161
- }
162
- }
163
- const out = [];
164
- let i = 0;
165
- let sawTerminator = false;
166
- while (i < argv.length) {
167
- const tok = argv[i];
168
- if (sawTerminator) {
169
- out.push(tok);
170
- i++;
171
- continue;
172
- }
173
- if (tok === "--") {
174
- sawTerminator = true;
175
- out.push(tok);
176
- i++;
177
- continue;
178
- }
179
- if (tok.startsWith("--")) {
180
- const eq = tok.indexOf("=");
181
- const name = eq >= 0 ? tok.slice(2, eq) : tok.slice(2);
182
- if (booleanFlags.has(name) || stringFlags.has(name)) {
183
- if (eq < 0 && stringFlags.has(name))
184
- i++; // consume value
185
- i++;
186
- continue;
187
- }
188
- }
189
- else if (tok.startsWith("-") && tok.length === 2) {
190
- const short = tok.slice(1);
191
- if (booleanShorts.has(short)) {
192
- i++;
193
- continue;
194
- }
195
- if (stringShorts.has(short)) {
196
- i += 2; // consume short flag and its value
197
- continue;
198
- }
199
- }
200
- out.push(tok);
201
- i++;
202
- }
203
- return out;
204
- }
205
- /**
206
- * Remove tokens for blocked plugin flags from an argv slice so they cannot
207
- * shift positionals during the plugin-flag re-parse.
208
- *
209
- * Post-#373, "blocked" exclusively means "collides with a GLOBAL flag".
210
- * The user may have supplied a value token (`--name value`) intending
211
- * either:
212
- * - the GLOBAL's interpretation (global type === "string"), or
213
- * - the PLUGIN's interpretation (plugin type === "string", e.g. global
214
- * is boolean but the plugin declared the same name as string).
215
- *
216
- * Either way the value is meaningless to both sides (plugin's flag is
217
- * blocked; global is consumed by the host elsewhere) and must not leak
218
- * into the plugin's positional args. Strip the following non-flag token
219
- * if either side typed the flag as string.
43
+ * Warn about flags a user typed on a plugin verb that the plugin never
44
+ * declared. The host drops them before the handler runs, so without this they
45
+ * would vanish silently. A warning, not an error (matching built-in verbs).
220
46
  */
221
- function stripBlockedFlagTokens(argv, blocked, pluginFlagDefs, globalFlagDefs) {
222
- const out = [];
223
- let i = 0;
224
- while (i < argv.length) {
225
- const arg = argv[i];
226
- if (arg.startsWith("--")) {
227
- const eqIdx = arg.indexOf("=");
228
- const name = eqIdx >= 0 ? arg.slice(2, eqIdx) : arg.slice(2);
229
- if (blocked.has(name)) {
230
- const eitherIsString = pluginFlagDefs[name]?.type === "string" ||
231
- globalFlagDefs[name]?.type === "string";
232
- if (eqIdx < 0 &&
233
- eitherIsString &&
234
- i + 1 < argv.length &&
235
- !argv[i + 1].startsWith("-")) {
236
- i++;
237
- }
238
- i++;
239
- continue;
240
- }
241
- }
242
- out.push(arg);
243
- i++;
244
- }
245
- return out;
47
+ function warnUndeclaredPluginFlags({ logger, verb, names, declared, }) {
48
+ if (names.length === 0)
49
+ return;
50
+ const list = names.join(", ");
51
+ const declaredText = declared.length > 0
52
+ ? `declared flags: ${declared.map((f) => `--${f}`).join(", ")}`
53
+ : "this command declares no flags";
54
+ logger.warn(`Unknown flag${names.length === 1 ? "" : "s"} ${list} for '${verb}'; ${declaredText}. ` +
55
+ `${names.length === 1 ? "It" : "They"} will be ignored.`);
246
56
  }
247
57
  /**
248
58
  * Warn about unrecognized flags for a verb × resource combination.
@@ -259,14 +69,12 @@ const VERB_REQUIRES_RESOURCE = new Set(commandRegistryEntries()
259
69
  .filter(([, def]) => def.requiresResource)
260
70
  .flatMap(([verb, def]) => [verb, ...(def.aliases ?? [])]));
261
71
  /**
262
- * Main CLI handler
72
+ * Apply GLOBAL_FLAGS to the process-wide runtime: per-invocation output mode,
73
+ * `--fields`, `--dry-run` and `--verbose`. Idempotent — `main()`
74
+ * calls it once for the flags before the verb and again with the merged set
75
+ * once the flags after the verb have been parsed.
263
76
  */
264
- async function main() {
265
- // Load session state from disk at startup
266
- loadSessionState();
267
- // Fire-and-forget: check for CLI updates in the background
268
- startUpdateCheck(c8ctl.version);
269
- const { values, positionals } = parseCliArgs();
77
+ function applyGlobalFlags(values) {
270
78
  // Apply per-invocation output mode override (#356).
271
79
  // Precedence: --json flag > C8CTL_OUTPUT_MODE env var > persisted session.
272
80
  // Setting `c8ctl.outputMode` directly is in-memory only; saveSessionState
@@ -283,21 +91,6 @@ async function main() {
283
91
  }
284
92
  // Any other C8CTL_OUTPUT_MODE value (including unset, empty, or
285
93
  // "yaml"/typo) falls through to the persisted mode loaded above.
286
- // Initialize logger with current output mode from c8ctl runtime
287
- const logger = getLogger(c8ctl.outputMode);
288
- // Resolve sort order from --asc / --desc flags (default: asc)
289
- const sortOrder = values.desc ? "desc" : "asc";
290
- if (values.asc && values.desc) {
291
- logger.error("Cannot specify both --asc and --desc. Use one or the other.");
292
- process.exit(1);
293
- }
294
- // Resolve --limit flag (max items to fetch)
295
- const limitStr = str(values.limit);
296
- const limit = limitStr ? parseInt(limitStr, 10) : undefined;
297
- if (limit !== undefined && (Number.isNaN(limit) || limit < 1)) {
298
- logger.error("--limit must be a positive integer.");
299
- process.exit(1);
300
- }
301
94
  // Resolve --fields flag (agent feature: filter output keys)
302
95
  if (values.fields && typeof values.fields === "string") {
303
96
  c8ctl.fields = values.fields
@@ -313,6 +106,36 @@ async function main() {
313
106
  if (values.verbose) {
314
107
  c8ctl.verbose = true;
315
108
  }
109
+ }
110
+ /**
111
+ * Main CLI handler
112
+ */
113
+ async function main() {
114
+ // Load session state from disk at startup
115
+ loadSessionState();
116
+ // Fire-and-forget: check for CLI updates in the background
117
+ startUpdateCheck(c8ctl.version);
118
+ // Stage 1: parse GLOBAL_FLAGS from the front of argv and stop at
119
+ // the verb. Everything after the verb stays raw for stage 2, which parses
120
+ // it against that command's own flag table.
121
+ const stage1 = splitGlobals(process.argv.slice(2));
122
+ // Global flags given before the verb take effect now so plugin loading
123
+ // (which logs) sees the right output mode; flags after the verb are
124
+ // applied again below once stage 2 has parsed them.
125
+ applyGlobalFlags(stage1.globals);
126
+ // The same three boolean globals may also follow the verb
127
+ // (`c8ctl list pi --json`), and plugin loading renders diagnostics in the
128
+ // output mode, so honour them now too. Only booleans: a global flag is
129
+ // never a plugin flag, and they cannot be mistaken for a flag's value.
130
+ // String globals (`--fields`, `--profile`) wait for the command's own
131
+ // flag table, below.
132
+ {
133
+ const { json, verbose, "dry-run": dryRun, } = parseFlags({
134
+ args: stage1.rest,
135
+ options: globalOptions(),
136
+ }).values;
137
+ applyGlobalFlags({ json, verbose, "dry-run": dryRun });
138
+ }
316
139
  // Inject dependencies into the runtime (breaks circular imports)
317
140
  // `npm` is the cross-platform runner from utils/. Assigning it here is also
318
141
  // the compile-time check that it still satisfies the `NpmRunner` contract
@@ -326,23 +149,65 @@ async function main() {
326
149
  });
327
150
  // Load installed plugins
328
151
  await loadInstalledPlugins();
329
- // Auto-refresh installed completions if CLI version changed
330
- refreshCompletionsIfStale(c8ctl.dryRun ?? false);
331
- // Extract command and resource
332
- const [rawVerb, resource, ...args] = positionals;
333
- // Handle global --version flag (only when no verb/command is provided)
334
- if (values.version && !rawVerb) {
335
- showVersion();
336
- return;
152
+ // Only global flags may precede the command. A command-specific flag
153
+ // there would also make stage 1 mistake the flag's value for the verb
154
+ // ("Unknown command: 5"), so name the real problem instead.
155
+ if (stage1.misplaced.length > 0) {
156
+ const pluginFlags = {};
157
+ for (const [name, cmd] of Object.entries(getPluginCommands())) {
158
+ if (typeof cmd !== "function")
159
+ pluginFlags[name] = cmd.flags;
160
+ }
161
+ getLogger(c8ctl.outputMode).error(describeMisplacedFlags({
162
+ argv: process.argv.slice(2),
163
+ misplaced: stage1.misplaced,
164
+ pluginFlags,
165
+ }));
166
+ process.exit(1);
337
167
  }
338
- if (values.help && positionals.length === 0) {
339
- showHelp();
168
+ const rawVerb = stage1.verb;
169
+ // A global --version before the verb is the CLI version. After the verb
170
+ // it is command-scoped (definition-version filter on built-ins, plugin
171
+ // version on plugin verbs) and is parsed by stage 2 below.
172
+ // Any value counts: lenient parsing yields a string for `--version=3`.
173
+ if (stage1.globals.version !== undefined) {
174
+ showVersion();
340
175
  return;
341
176
  }
342
177
  if (!rawVerb) {
343
178
  showHelp();
344
179
  return;
345
180
  }
181
+ // Stage 2: parse everything after the verb against
182
+ // GLOBAL_FLAGS ∪ effectiveFlags(verb, resource). Globals stay accepted
183
+ // after the verb (lenient variant).
184
+ const parsed = parseVerbArgs({ rawVerb, rest: stage1.rest });
185
+ const { resource, args } = parsed;
186
+ // A plugin verb that declares flags owns its own flag table: parse the
187
+ // tail against it so a string global (`--profile`) cannot swallow the
188
+ // plugin's flag that follows it (`--profile --flag1 x`).
189
+ let postVerbValues = parsed.values;
190
+ const declaringPlugin = Object.hasOwn(getPluginCommands(), parsed.verb)
191
+ ? getPluginCommands()[parsed.verb]
192
+ : undefined;
193
+ if (!getCommandDef(parsed.verb) &&
194
+ declaringPlugin !== undefined &&
195
+ typeof declaringPlugin !== "function" &&
196
+ !isPassthroughPluginCommand(parsed.verb)) {
197
+ postVerbValues = parseFlags({
198
+ args: stage1.rest,
199
+ options: analyzePluginFlags(declaringPlugin.flags).options,
200
+ }).values;
201
+ }
202
+ const values = { ...stage1.globals, ...postVerbValues };
203
+ // `--version` before the verb was handled above; only the post-verb
204
+ // (string) meaning reaches handlers.
205
+ values.version = postVerbValues.version;
206
+ applyGlobalFlags(values);
207
+ // Initialize logger with current output mode from c8ctl runtime
208
+ const logger = getLogger(c8ctl.outputMode);
209
+ // Auto-refresh installed completions if CLI version changed
210
+ refreshCompletionsIfStale(c8ctl.dryRun ?? false);
346
211
  // Handle help command
347
212
  if (rawVerb === "help" ||
348
213
  rawVerb === "menu" ||
@@ -359,10 +224,26 @@ async function main() {
359
224
  }
360
225
  // Resolve verb aliases to canonical verb name (e.g. "w" → "watch",
361
226
  // "rm" → "remove" or "unload" depending on the resource argument).
362
- // Must happen before --help and dispatch so the dispatch key uses the
363
- // canonical verb (not the raw alias) and `c8ctl rm plugin --help`
364
- // shows unload help (not remove help).
365
- const verb = resolveVerbAlias(rawVerb, resource);
227
+ // Stage 2 already resolved it so the dispatch key uses the canonical verb
228
+ // (not the raw alias) and `c8ctl rm plugin --help` shows unload help
229
+ // (not remove help).
230
+ const verb = parsed.verb;
231
+ // Sort order and --limit only apply to built-in commands; a plugin verb
232
+ // owns its own flag namespace.
233
+ const isPluginVerb = Object.hasOwn(getPluginCommands(), verb) && !getCommandDef(verb);
234
+ // Resolve sort order from --asc / --desc flags (default: asc)
235
+ const sortOrder = values.desc ? "desc" : "asc";
236
+ if (!isPluginVerb && values.asc && values.desc) {
237
+ logger.error("Cannot specify both --asc and --desc. Use one or the other.");
238
+ process.exit(1);
239
+ }
240
+ // Resolve --limit flag (max items to fetch)
241
+ const limitStr = isPluginVerb ? undefined : str(values.limit);
242
+ const limit = limitStr ? parseInt(limitStr, 10) : undefined;
243
+ if (limit !== undefined && (Number.isNaN(limit) || limit < 1)) {
244
+ logger.error("--limit must be a positive integer.");
245
+ process.exit(1);
246
+ }
366
247
  // `c8ctl <verb> [<resource>] [args] --help` — uniformly route to the help
367
248
  // renderer. Placed AFTER the `help`/`menu` reserved-verb handler and
368
249
  // BEFORE plugin pre-parse so that every verb (built-in or plugin,
@@ -376,9 +257,8 @@ async function main() {
376
257
  }
377
258
  // Check if this is a plugin command — only for verbs not claimed by a built-in.
378
259
  // Placed after help/menu handling so those reserved verbs can never be shadowed.
379
- const pluginCommands = getPluginCommands();
380
- if (verb && Object.hasOwn(pluginCommands, verb) && !getCommandDef(verb)) {
381
- const cmd = pluginCommands[verb];
260
+ if (isPluginVerb) {
261
+ const cmd = getPluginCommands()[verb];
382
262
  const cmdFlagDefs = typeof cmd !== "function" ? cmd.flags : undefined;
383
263
  // Plugin --version (#377): when a plugin verb is invoked with
384
264
  // --version, print the plugin's package version and identifying
@@ -432,14 +312,12 @@ async function main() {
432
312
  // Validation at load time guarantees passthrough commands are the
433
313
  // bare-function form and never carry a `flags` declaration.
434
314
  if (isPassthroughPluginCommand(verb)) {
435
- // Locate the verb token by walking process.argv from the start and
436
- // skipping leading GLOBAL_FLAGS (consuming string-flag values).
437
- // A naive `indexOf(verb)` is unsafe because `verb` may also appear
438
- // as the value of a global string flag (e.g. `--profile <verb>`).
439
- // Use rawVerb here because process.argv contains the original input.
440
- const rawAfterVerb = sliceArgvAfterVerb(process.argv.slice(2), rawVerb);
441
- const forwarded = stripGlobalFlags(rawAfterVerb);
442
- await executePluginCommand(verb, forwarded);
315
+ // Stage 1 already located the verb token (skipping leading
316
+ // GLOBAL_FLAGS, so a verb name that is also the value of a string
317
+ // global like `--profile <verb>` is never mistaken for the verb);
318
+ // `rest` is everything after it, verbatim.
319
+ const forwarded = stripGlobalFlags(stage1.rest);
320
+ await executePluginCommand(verb, forwarded, undefined, pluginCtx);
443
321
  return;
444
322
  }
445
323
  if (cmdFlagDefs) {
@@ -455,51 +333,34 @@ async function main() {
455
333
  // host strips them from argv before the plugin parser sees
456
334
  // them, so a plugin's same-named flag would never receive a
457
335
  // value (#364).
458
- const builtinOptions = {};
459
- for (const [name, def] of Object.entries(GLOBAL_FLAGS)) {
460
- const short = "short" in def ? def.short : undefined;
461
- builtinOptions[name] = {
462
- type: def.type,
463
- ...(short && { short }),
464
- };
465
- }
466
- const builtinShorts = new Set(Object.values(builtinOptions)
467
- .map((o) => o.short)
468
- .filter((s) => s !== undefined));
469
- // Use a null-prototype object so plugin-supplied flag names like
470
- // `__proto__`, `constructor`, or `prototype` cannot pollute the
471
- // prototype chain when later assigned (paired with the
472
- // `Object.hasOwn` collision check below).
473
- const mergedOptions = Object.assign(Object.create(null), builtinOptions);
474
- const blockedFlags = new Set();
475
- for (const [name, def] of Object.entries(cmdFlagDefs)) {
476
- if (Object.hasOwn(builtinOptions, name)) {
477
- // A required plugin flag whose name collides with a global
478
- // flag is unsatisfiable: the token is always stripped from
479
- // argv before the plugin parser sees it, so the required
480
- // check downstream would always fire with the misleading
481
- // "--<name> is required" message even when the user did
482
- // pass a value (#364). Fail fast here with a single
483
- // actionable error instead.
484
- if (def.required === true) {
485
- logger.error(`Plugin flag --${name} is declared required but conflicts with a global c8ctl flag of the same name; ` +
486
- `it can never be satisfied. The plugin must rename this flag.`);
487
- process.exit(1);
488
- }
489
- logger.warn(`Plugin flag --${name} conflicts with a global c8ctl flag and will not be parsed`);
490
- blockedFlags.add(name);
491
- continue;
492
- }
493
- const short = def.short && builtinShorts.has(def.short) ? undefined : def.short;
494
- if (def.short && !short) {
495
- logger.warn(`Plugin flag --${name} short alias -${def.short} conflicts with a global c8ctl alias and will be ignored`);
336
+ const analysis = analyzePluginFlags(cmdFlagDefs);
337
+ const blockedFlags = new Set(analysis.reservedNames);
338
+ for (const name of analysis.reservedNames) {
339
+ // A required plugin flag whose name collides with a global
340
+ // flag is unsatisfiable: the token is always consumed as the
341
+ // global before the plugin parser sees it, so the required
342
+ // check downstream would always fire with the misleading
343
+ // "--<name> is required" message even when the user did pass
344
+ // a value. The command can never succeed, so fail fast
345
+ // with a single actionable error on every invocation.
346
+ if (cmdFlagDefs[name].required === true) {
347
+ logger.error(`Plugin flag --${name} is declared required but conflicts with a global c8ctl flag of the same name; ` +
348
+ `it can never be satisfied. The plugin must rename this flag.`);
349
+ process.exit(1);
496
350
  }
497
- mergedOptions[name] = {
498
- type: def.type,
499
- ...(short && { short }),
500
- ...(def.multiple && { multiple: true }),
501
- };
502
351
  }
352
+ // A collision only matters to a user who typed the flag, so warn
353
+ // then — not on every invocation. The plugin author sees every
354
+ // collision up front in `c8ctl doctor plugin`.
355
+ for (const flag of typedReservedFlags({
356
+ argv: stage1.rest,
357
+ analysis,
358
+ })) {
359
+ logger.warn(`${flag} is reserved by c8ctl and is not passed to '${verb}' as a plugin flag. ` +
360
+ `Its value is available to the plugin through the context argument (ctx) where c8ctl exposes it.`);
361
+ }
362
+ const builtinOptions = globalOptions();
363
+ const mergedOptions = analysis.options;
503
364
  // Strip blocked-flag tokens from argv before re-parse. Blocked
504
365
  // names exclusively collide with GLOBAL_FLAGS (post-#373), but
505
366
  // `mergedOptions` carries the global type for those names, so
@@ -508,21 +369,28 @@ async function main() {
508
369
  // drift into positionals when the plugin typed the same name
509
370
  // as string. The helper consults both type tables and strips
510
371
  // the following non-flag token when either side is string.
511
- const filteredArgv = stripBlockedFlagTokens(process.argv.slice(2), blockedFlags, cmdFlagDefs, builtinOptions);
512
- let pluginParsed;
513
- try {
514
- pluginParsed = parseArgs({
515
- args: filteredArgv,
372
+ // Stage 2 for a plugin verb: re-parse the raw tokens after the verb
373
+ // against `GLOBAL_FLAGS ∪ plugin.flags`.
374
+ const filteredArgv = stripBlockedFlagTokens({
375
+ argv: stage1.rest,
376
+ blocked: blockedFlags,
377
+ reservedShorts: analysis.reservedShorts,
378
+ pluginFlagDefs: cmdFlagDefs,
379
+ globalFlagDefs: builtinOptions,
380
+ });
381
+ const pluginParsed = parseFlags({
382
+ args: filteredArgv,
383
+ options: mergedOptions,
384
+ });
385
+ warnUndeclaredPluginFlags({
386
+ logger,
387
+ verb,
388
+ names: undeclaredFlags({
389
+ tokens: pluginParsed.tokens,
516
390
  options: mergedOptions,
517
- allowPositionals: true,
518
- strict: false,
519
- });
520
- }
521
- catch (error) {
522
- const message = error instanceof Error ? error.message : String(error);
523
- console.error(`Error parsing arguments: ${message}`);
524
- process.exit(1);
525
- }
391
+ }),
392
+ declared: Object.keys(analysis.usable),
393
+ });
526
394
  const extractedFlags = {};
527
395
  for (const [flagName, def] of Object.entries(cmdFlagDefs)) {
528
396
  if (blockedFlags.has(flagName))
@@ -550,16 +418,24 @@ async function main() {
550
418
  process.exit(1);
551
419
  }
552
420
  }
553
- const [_verb, _resource, ...pluginArgs] = pluginParsed.positionals;
554
- await executePluginCommand(verb, _resource ? [_resource, ...pluginArgs] : pluginArgs, extractedFlags, pluginCtx);
421
+ await executePluginCommand(verb, pluginParsed.positionals, extractedFlags, pluginCtx);
555
422
  }
556
423
  else {
424
+ warnUndeclaredPluginFlags({
425
+ logger,
426
+ verb,
427
+ names: undeclaredFlags({
428
+ tokens: parsed.tokens,
429
+ options: globalOptions(),
430
+ }),
431
+ declared: [],
432
+ });
557
433
  await executePluginCommand(verb, resource ? [resource, ...args] : args, undefined, pluginCtx);
558
434
  }
559
435
  return;
560
436
  }
561
437
  // Normalize resource
562
- const normalizedResource = resource ? resolveAlias(resource) : "";
438
+ const normalizedResource = parsed.normalizedResource;
563
439
  // Resource validation guard — single chokepoint for all verbs that require a resource.
564
440
  // Derived from COMMAND_REGISTRY.requiresResource.
565
441
  // help/completion are dispatched before this point.