@camunda8/cli 4.7.0-alpha.4 → 4.7.0-alpha.41

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 (122) hide show
  1. package/CONTEXT.md +12 -0
  2. package/PLUGIN-HELP.md +1 -1
  3. package/README.md +8 -1
  4. package/dist/commands/deploy.d.ts.map +1 -1
  5. package/dist/commands/deploy.js +2 -2
  6. package/dist/commands/deploy.js.map +1 -1
  7. package/dist/commands/helpers/deploy-helpers.d.ts +14 -1
  8. package/dist/commands/helpers/deploy-helpers.d.ts.map +1 -1
  9. package/dist/commands/helpers/deploy-helpers.js +69 -13
  10. package/dist/commands/helpers/deploy-helpers.js.map +1 -1
  11. package/dist/commands/mcp-proxy.d.ts.map +1 -1
  12. package/dist/commands/mcp-proxy.js +13 -8
  13. package/dist/commands/mcp-proxy.js.map +1 -1
  14. package/dist/commands/profiles.d.ts.map +1 -1
  15. package/dist/commands/profiles.js +13 -7
  16. package/dist/commands/profiles.js.map +1 -1
  17. package/dist/commands/run.d.ts.map +1 -1
  18. package/dist/commands/run.js +1 -8
  19. package/dist/commands/run.js.map +1 -1
  20. package/dist/commands/watch.d.ts.map +1 -1
  21. package/dist/commands/watch.js +10 -2
  22. package/dist/commands/watch.js.map +1 -1
  23. package/dist/core/client.d.ts +13 -0
  24. package/dist/core/client.d.ts.map +1 -1
  25. package/dist/core/client.js +48 -21
  26. package/dist/core/client.js.map +1 -1
  27. package/dist/core/config.d.ts +34 -3
  28. package/dist/core/config.d.ts.map +1 -1
  29. package/dist/core/config.js +91 -9
  30. package/dist/core/config.js.map +1 -1
  31. package/dist/core/env-address.d.ts +22 -0
  32. package/dist/core/env-address.d.ts.map +1 -0
  33. package/dist/core/env-address.js +30 -0
  34. package/dist/core/env-address.js.map +1 -0
  35. package/dist/core/errors.d.ts +17 -0
  36. package/dist/core/errors.d.ts.map +1 -1
  37. package/dist/core/errors.js +32 -0
  38. package/dist/core/errors.js.map +1 -1
  39. package/dist/core/index.d.ts +2 -0
  40. package/dist/core/index.d.ts.map +1 -1
  41. package/dist/core/index.js +2 -0
  42. package/dist/core/index.js.map +1 -1
  43. package/dist/core/logger.d.ts.map +1 -1
  44. package/dist/core/logger.js +2 -1
  45. package/dist/core/logger.js.map +1 -1
  46. package/dist/core/node-version.d.ts +18 -0
  47. package/dist/core/node-version.d.ts.map +1 -0
  48. package/dist/core/node-version.js +38 -0
  49. package/dist/core/node-version.js.map +1 -0
  50. package/dist/default-plugins/cluster/README.md +16 -1
  51. package/dist/default-plugins/cluster/c8ctl-plugin.js +745 -115
  52. package/dist/default-plugins/element-template/c8ctl-plugin.js +248 -7
  53. package/dist/default-plugins/mcp/README.md +37 -0
  54. package/dist/default-plugins/mcp/c8ctl-plugin.js +4973 -0
  55. package/dist/default-plugins/mcp/package.json +8 -0
  56. package/dist/default-plugins/modeler/README.md +23 -0
  57. package/dist/default-plugins/modeler/c8ctl-plugin.js +4314 -0
  58. package/dist/default-plugins/modeler/package.json +8 -0
  59. package/dist/default-plugins/setup/README.md +42 -0
  60. package/dist/default-plugins/setup/c8ctl-plugin.js +6845 -0
  61. package/dist/default-plugins/setup/package.json +8 -0
  62. package/dist/default-plugins/skills/README.md +35 -0
  63. package/dist/default-plugins/skills/c8ctl-plugin.js +3369 -0
  64. package/dist/default-plugins/skills/package.json +8 -0
  65. package/dist/framework/argv-parser.d.ts +14 -0
  66. package/dist/framework/argv-parser.d.ts.map +1 -1
  67. package/dist/framework/argv-parser.js +25 -0
  68. package/dist/framework/argv-parser.js.map +1 -1
  69. package/dist/framework/command-registry.d.ts +28 -2
  70. package/dist/framework/command-registry.d.ts.map +1 -1
  71. package/dist/framework/command-registry.js +47 -2
  72. package/dist/framework/command-registry.js.map +1 -1
  73. package/dist/framework/plugins/plugin-loader.d.ts +20 -2
  74. package/dist/framework/plugins/plugin-loader.d.ts.map +1 -1
  75. package/dist/framework/plugins/plugin-loader.js.map +1 -1
  76. package/dist/framework/ui/help.d.ts.map +1 -1
  77. package/dist/framework/ui/help.js +57 -14
  78. package/dist/framework/ui/help.js.map +1 -1
  79. package/dist/framework/ui/prompt.d.ts +88 -0
  80. package/dist/framework/ui/prompt.d.ts.map +1 -1
  81. package/dist/framework/ui/prompt.js +558 -20
  82. package/dist/framework/ui/prompt.js.map +1 -1
  83. package/dist/index.d.ts.map +1 -1
  84. package/dist/index.js +68 -12
  85. package/dist/index.js.map +1 -1
  86. package/dist/utils/command-local/mcp-install-helpers.d.ts +68 -0
  87. package/dist/utils/command-local/mcp-install-helpers.d.ts.map +1 -0
  88. package/dist/utils/command-local/mcp-install-helpers.js +485 -0
  89. package/dist/utils/command-local/mcp-install-helpers.js.map +1 -0
  90. package/dist/utils/command-local/process-instance-helpers.d.ts +6 -0
  91. package/dist/utils/command-local/process-instance-helpers.d.ts.map +1 -1
  92. package/dist/utils/command-local/process-instance-helpers.js +9 -0
  93. package/dist/utils/command-local/process-instance-helpers.js.map +1 -1
  94. package/dist/utils/command-local/skills-install-helpers.d.ts +49 -0
  95. package/dist/utils/command-local/skills-install-helpers.d.ts.map +1 -0
  96. package/dist/utils/command-local/skills-install-helpers.js +436 -0
  97. package/dist/utils/command-local/skills-install-helpers.js.map +1 -0
  98. package/dist/utils/index.d.ts +2 -2
  99. package/dist/utils/index.d.ts.map +1 -1
  100. package/dist/utils/index.js +2 -2
  101. package/dist/utils/index.js.map +1 -1
  102. package/dist/utils/shared/camunda-json.d.ts +16 -3
  103. package/dist/utils/shared/camunda-json.d.ts.map +1 -1
  104. package/dist/utils/shared/camunda-json.js +20 -5
  105. package/dist/utils/shared/camunda-json.js.map +1 -1
  106. package/dist/utils/shared/deploy-resource-selection.d.ts +7 -15
  107. package/dist/utils/shared/deploy-resource-selection.d.ts.map +1 -1
  108. package/dist/utils/shared/deploy-resource-selection.js +9 -19
  109. package/dist/utils/shared/deploy-resource-selection.js.map +1 -1
  110. package/dist/utils/shared/ignore.d.ts +6 -0
  111. package/dist/utils/shared/ignore.d.ts.map +1 -1
  112. package/dist/utils/shared/ignore.js +9 -1
  113. package/dist/utils/shared/ignore.js.map +1 -1
  114. package/package.json +3 -2
  115. package/dist/utils/command-local/setup-detectors.d.ts +0 -51
  116. package/dist/utils/command-local/setup-detectors.d.ts.map +0 -1
  117. package/dist/utils/command-local/setup-detectors.js +0 -115
  118. package/dist/utils/command-local/setup-detectors.js.map +0 -1
  119. package/dist/utils/command-local/setup-prerequisites.d.ts +0 -67
  120. package/dist/utils/command-local/setup-prerequisites.d.ts.map +0 -1
  121. package/dist/utils/command-local/setup-prerequisites.js +0 -238
  122. package/dist/utils/command-local/setup-prerequisites.js.map +0 -1
@@ -66,6 +66,15 @@ import { createInterface, emitKeypressEvents } from "node:readline";
66
66
  // ── ANSI helpers ──────────────────────────────────────────────────
67
67
  const ESC = "\x1b[";
68
68
  const CLEAR_LINE = `${ESC}2K`;
69
+ /** Erase from the cursor to end of line: clears the stale tail of a
70
+ * wrapped row whose new content is shorter than the previous render's. */
71
+ const CLEAR_TO_EOL = `${ESC}0K`;
72
+ /** Erase from the cursor to the end of the screen: the recovery wipe
73
+ * when a terminal resize invalidates the cursor anchor — the previous
74
+ * render's physical line count no longer matches what the terminal
75
+ * painted, so everything from the (best-effort) rewind point down is
76
+ * cleared and the menu repaints from a fresh anchor. */
77
+ const ERASE_TO_END_OF_SCREEN = `${ESC}0J`;
69
78
  const CURSOR_UP = (n) => `${ESC}${n}A`;
70
79
  const CURSOR_TO_COL = (n) => `${ESC}${n}G`;
71
80
  const HIDE_CURSOR = `${ESC}?25l`;
@@ -73,6 +82,8 @@ const SHOW_CURSOR = `${ESC}?25h`;
73
82
  const DIM = `${ESC}2m`;
74
83
  const BOLD = `${ESC}1m`;
75
84
  const CYAN = `${ESC}36m`;
85
+ const YELLOW = `${ESC}33m`;
86
+ const INVERSE = `${ESC}7m`;
76
87
  const RESET = `${ESC}0m`;
77
88
  const defaultIO = () => ({
78
89
  input: process.stdin,
@@ -147,26 +158,44 @@ export async function select(config) {
147
158
  // ── Interactive mode ────────────────────────────────────────
148
159
  return new Promise((resolve) => {
149
160
  let cursor = initialIndex;
150
- // Pre-compute the number of physical terminal lines the menu
151
- // occupies. When an option line is wider than the terminal, it
152
- // wraps to multiple physical lines. CURSOR_UP must move by
153
- // physical lines, not logical option count, or previous
154
- // renders bleed through.
155
- const cols = out.columns || 80;
156
- const headerLines = Math.max(1, Math.ceil((2 + message.length) / cols));
157
- const physicalLines = options.reduce((sum, opt, i) => {
161
+ // Count the physical terminal lines the menu occupies. When an
162
+ // option line is wider than the terminal, it wraps to multiple
163
+ // physical lines. CURSOR_UP must move by physical lines, not
164
+ // logical option count, or previous renders bleed through.
165
+ let cols = out.columns || 80;
166
+ const headerLineCount = (width) => Math.max(1, Math.ceil((2 + message.length) / width));
167
+ const physicalLineCount = (width) => options.reduce((sum, opt, i) => {
158
168
  // Visible width: " ❯ " (4 chars) + "N. " + label + optional " " + description
159
169
  const visible = 4 +
160
170
  numberPrefix(i).length +
161
171
  opt.label.length +
162
172
  (opt.description ? 1 + opt.description.length : 0);
163
- return sum + Math.max(1, Math.ceil(visible / cols));
173
+ return sum + Math.max(1, Math.ceil(visible / width));
164
174
  }, 0);
175
+ /** Physical lines the last render occupies on screen right now,
176
+ * recomputed at the live width: after a resize with no repaint
177
+ * since, the terminal has rewrapped the menu. */
178
+ const menuLinesOnScreen = () => physicalLineCount(out.columns || 80);
179
+ // Cursor rewinds must traverse the *previous* render's line count.
180
+ let renderedLines = 0;
165
181
  // Render the menu
166
182
  function render(firstRender) {
167
183
  if (!firstRender) {
168
- // Move cursor back up to overwrite previous render
169
- out.write(CURSOR_UP(physicalLines));
184
+ const width = out.columns || 80;
185
+ if (width !== cols) {
186
+ // The terminal was resized while the menu was open and
187
+ // rewrapped the previous render: its on-screen height is
188
+ // now the line count at the NEW width. Rewind by that to
189
+ // the menu's top, wipe everything below, and repaint from
190
+ // the fresh anchor.
191
+ cols = width;
192
+ out.write(CURSOR_UP(physicalLineCount(width)));
193
+ out.write(ERASE_TO_END_OF_SCREEN);
194
+ }
195
+ else {
196
+ // Move cursor back up to overwrite previous render
197
+ out.write(CURSOR_UP(renderedLines));
198
+ }
170
199
  }
171
200
  for (let i = 0; i < options.length; i++) {
172
201
  const opt = options[i];
@@ -179,6 +208,7 @@ export async function select(config) {
179
208
  : "";
180
209
  out.write(`${CLEAR_LINE}${CURSOR_TO_COL(1)} ${pointer} ${number}${label}${desc}\n`);
181
210
  }
211
+ renderedLines = physicalLineCount(cols);
182
212
  }
183
213
  // Print the message header
184
214
  out.write(`${BOLD}${CYAN}?${RESET} ${BOLD}${message}${RESET}\n`);
@@ -194,11 +224,12 @@ export async function select(config) {
194
224
  cleanup();
195
225
  const chosen = options[index];
196
226
  // Replace the menu with the final selection line
197
- out.write(CURSOR_UP(physicalLines));
198
- for (let i = 0; i < physicalLines; i++) {
227
+ const menuLines = menuLinesOnScreen();
228
+ out.write(CURSOR_UP(menuLines));
229
+ for (let i = 0; i < menuLines; i++) {
199
230
  out.write(`${CLEAR_LINE}\n`);
200
231
  }
201
- out.write(CURSOR_UP(physicalLines));
232
+ out.write(CURSOR_UP(menuLines));
202
233
  out.write(`${CLEAR_LINE}${CURSOR_TO_COL(1)} ${CYAN}${chosen.label}${RESET}`);
203
234
  if (chosen.description) {
204
235
  out.write(` ${DIM}${chosen.description}${RESET}`);
@@ -235,16 +266,21 @@ export async function select(config) {
235
266
  }
236
267
  else if (key.name === "escape" || (key.ctrl && key.name === "c")) {
237
268
  cleanup();
238
- // Clear the menu and header
239
- out.write(CURSOR_UP(physicalLines));
240
- for (let i = 0; i < physicalLines; i++) {
269
+ // Clear the menu and header. Both counts are measured at the
270
+ // live width — after a resize the terminal has rewrapped the
271
+ // prompt, so the counts from render time no longer match
272
+ // what is on screen.
273
+ const menuLines = menuLinesOnScreen();
274
+ const header = headerLineCount(out.columns || 80);
275
+ out.write(CURSOR_UP(menuLines));
276
+ for (let i = 0; i < menuLines; i++) {
241
277
  out.write(`${CLEAR_LINE}\n`);
242
278
  }
243
- out.write(CURSOR_UP(physicalLines + headerLines));
244
- for (let i = 0; i < headerLines; i++) {
279
+ out.write(CURSOR_UP(menuLines + header));
280
+ for (let i = 0; i < header; i++) {
245
281
  out.write(`${CLEAR_LINE}\n`);
246
282
  }
247
- out.write(CURSOR_UP(headerLines));
283
+ out.write(CURSOR_UP(header));
248
284
  // Ctrl+C: re-raise so the process exits naturally
249
285
  if (key.ctrl && key.name === "c") {
250
286
  process.kill(process.pid, "SIGINT");
@@ -264,6 +300,508 @@ export async function select(config) {
264
300
  }
265
301
  });
266
302
  }
303
+ const defaultMultiSelectKeyHint = (submitLabel) => `↑/↓ move · space/enter toggle · a all · tab to ${submitLabel} · esc cancel`;
304
+ /** Grapheme segmentation: composed emoji (ZWJ joins, skin-tone
305
+ * modifiers, flag pairs, VS16 forms) are one glyph, not a sum of
306
+ * code-point widths. */
307
+ const graphemeSegmenter = new Intl.Segmenter(undefined, {
308
+ granularity: "grapheme",
309
+ });
310
+ /**
311
+ * Terminal display width of a string in cells. Sizes and truncates
312
+ * the submit button's box so its borders stay aligned for non-ASCII
313
+ * labels.
314
+ */
315
+ function displayWidth(text) {
316
+ let width = 0;
317
+ for (const { segment } of graphemeSegmenter.segment(text)) {
318
+ width += graphemeWidth(segment);
319
+ }
320
+ return width;
321
+ }
322
+ /** Terminal cells occupied by one grapheme cluster. */
323
+ function graphemeWidth(cluster) {
324
+ // ZWJ-joined emoji (👩‍💻), skin-tone-modified emoji (👍🏽), flag pairs
325
+ // (🇬🇧) and VS16 emoji forms (❤️, keycaps) render as a single
326
+ // two-cell glyph. The ZWJ and VS16 shortcuts require an
327
+ // emoji in the cluster: Extended_Pictographic excludes the keycap
328
+ // bases (digits, #, *), so a bare ZWJ in ordinary text (e\u200d,
329
+ // 1\u200d) stays on the zero-width format-control path below.
330
+ // The VS16 branch keeps \p{Emoji} so keycap sequences (1️⃣) still
331
+ // measure as two cells.
332
+ if ((cluster.includes("\u200d") &&
333
+ /\p{Extended_Pictographic}/u.test(cluster)) ||
334
+ /\p{Emoji_Modifier}/u.test(cluster) ||
335
+ /\p{Regional_Indicator}/u.test(cluster) ||
336
+ (cluster.includes("\ufe0f") && /\p{Emoji}/u.test(cluster))) {
337
+ return 2;
338
+ }
339
+ let width = 0;
340
+ for (const char of cluster) {
341
+ const code = char.codePointAt(0) ?? 0;
342
+ if (
343
+ // combining marks, format controls (incl. ZWJ), variation selectors
344
+ /^[\p{Mn}\p{Me}\p{Cf}]$/u.test(char) ||
345
+ (code >= 0xfe00 && code <= 0xfe0f) ||
346
+ (code >= 0xe0100 && code <= 0xe01ef)) {
347
+ continue;
348
+ }
349
+ width += isWideCodePoint(code) || isEmojiPresentation(char) ? 2 : 1;
350
+ }
351
+ return width;
352
+ }
353
+ /**
354
+ * The longest prefix of `text` that fits `maxCells` terminal cells,
355
+ * marked with an ellipsis when truncated. Cuts at grapheme
356
+ * boundaries, so a composed emoji is never split.
357
+ */
358
+ function truncateToWidth(text, maxCells) {
359
+ if (displayWidth(text) <= maxCells)
360
+ return text;
361
+ let out = "";
362
+ let width = 1; // one cell reserved for the ellipsis
363
+ for (const { segment } of graphemeSegmenter.segment(text)) {
364
+ const segmentWidth = graphemeWidth(segment);
365
+ if (width + segmentWidth > maxCells)
366
+ break;
367
+ out += segment;
368
+ width += segmentWidth;
369
+ }
370
+ return `${out}…`;
371
+ }
372
+ /**
373
+ * Code points terminals render two cells wide by default emoji
374
+ * presentation (🚀, ✅, …). The Unicode property covers what the
375
+ * hand-maintained wide table cannot: emoji are added every release.
376
+ */
377
+ function isEmojiPresentation(char) {
378
+ return /^\p{Emoji_Presentation}$/u.test(char);
379
+ }
380
+ /** East-Asian wide/fullwidth ranges that occupy two terminal cells. */
381
+ function isWideCodePoint(code) {
382
+ return ((code >= 0x1100 && code <= 0x115f) || // Hangul Jamo
383
+ (code >= 0x2e80 && code <= 0x303e) || // CJK radicals, Kangxi, symbols
384
+ (code >= 0x3041 && code <= 0x33ff) || // Hiragana … CJK compatibility
385
+ (code >= 0x3400 && code <= 0x4dbf) || // CJK Unified Ext A
386
+ (code >= 0x4e00 && code <= 0x9fff) || // CJK Unified
387
+ (code >= 0xa000 && code <= 0xa4cf) || // Yi syllables and radicals
388
+ (code >= 0xac00 && code <= 0xd7a3) || // Hangul syllables
389
+ (code >= 0xf900 && code <= 0xfaff) || // CJK compatibility ideographs
390
+ (code >= 0xfe30 && code <= 0xfe6f) || // CJK compatibility forms
391
+ (code >= 0xff00 && code <= 0xff60) || // fullwidth forms
392
+ (code >= 0xffe0 && code <= 0xffe6) || // fullwidth signs
393
+ (code >= 0x1f300 && code <= 0x1f64f) || // emoji
394
+ (code >= 0x1f900 && code <= 0x1f9ff) || // supplemental emoji
395
+ (code >= 0x20000 && code <= 0x3fffd) // CJK Unified Ext B and beyond
396
+ );
397
+ }
398
+ /**
399
+ * Evaluate a checkbox list with dependencies: an option counts as
400
+ * checked only when every option it requires is itself effectively
401
+ * checked. Passes only ever uncheck options, so the fixpoint settles
402
+ * within options.length iterations even for chains (a needs b, b
403
+ * needs c).
404
+ */
405
+ function evaluateChecked(options, checked) {
406
+ let effective = [...checked];
407
+ let reasons = options.map(() => undefined);
408
+ for (let pass = 0; pass < options.length; pass++) {
409
+ reasons = options.map((opt) => {
410
+ const unmet = opt.requires?.find((req) => {
411
+ const reqIndex = options.findIndex((o) => Object.is(o.value, req.value));
412
+ return reqIndex === -1 || !effective[reqIndex];
413
+ });
414
+ return unmet?.reason;
415
+ });
416
+ const next = options.map((_, i) => checked[i] === true && reasons[i] === undefined);
417
+ if (next.every((v, i) => v === effective[i])) {
418
+ effective = next;
419
+ break;
420
+ }
421
+ effective = next;
422
+ }
423
+ return { effective, reasons };
424
+ }
425
+ /**
426
+ * Interleave group headers between options. A header is emitted when an
427
+ * option's group differs from the previous option's, so groups are
428
+ * contiguous runs — same-named sections are not merged.
429
+ */
430
+ function buildRows(options) {
431
+ const rows = [];
432
+ let lastGroup;
433
+ for (const [index, opt] of options.entries()) {
434
+ if (opt.group !== undefined && opt.group !== lastGroup) {
435
+ rows.push({ kind: "header", label: opt.group });
436
+ }
437
+ lastGroup = opt.group;
438
+ rows.push({ kind: "option", index });
439
+ }
440
+ return rows;
441
+ }
442
+ /**
443
+ * Present an interactive checkbox list.
444
+ *
445
+ * - **Interactive**: renders one row per option on stderr, grouped
446
+ * under non-interactive header rows when options carry a `group`,
447
+ * with a bordered submit button pinned below the list. Arrow keys move the
448
+ * highlight through the options and the button, Space (or the row's
449
+ * number) toggles an option, Enter toggles the focused option, `a`
450
+ * toggles all, Tab jumps to the button — and only Enter on the
451
+ * button confirms, possibly with nothing checked. Escape cancels.
452
+ * Options blocked by `requires` are dimmed with their reason
453
+ * highlighted, and the line under the list explains the focused
454
+ * blocked row. Returns the checked values in option order.
455
+ * - **Non-interactive**: returns the values of options marked
456
+ * `checked` with `interactive: false` and a `hint` string the caller
457
+ * can log.
458
+ */
459
+ export async function multiSelect(config) {
460
+ const { message, options, nonInteractiveHint } = config;
461
+ const { input, output: out } = config.io ?? defaultIO();
462
+ const submitLabel = config.submitLabel ?? "Submit";
463
+ const keyHint = config.keyHint ?? defaultMultiSelectKeyHint(submitLabel);
464
+ if (options.length === 0) {
465
+ throw new Error("multiSelect() requires at least one option");
466
+ }
467
+ // ── Non-interactive fallback ────────────────────────────────
468
+ if (!isInteractive({ input, output: out })) {
469
+ const initial = options.map((opt) => opt.checked === true);
470
+ const { effective, reasons } = evaluateChecked(options, initial);
471
+ const values = options
472
+ .filter((_opt, i) => effective[i])
473
+ .map((opt) => opt.value);
474
+ const lines = [`${message} (non-interactive, using defaults)`];
475
+ for (const row of buildRows(options)) {
476
+ if (row.kind === "header") {
477
+ lines.push(` ${row.label}`);
478
+ continue;
479
+ }
480
+ const opt = options[row.index];
481
+ const indent = opt.group === undefined ? " " : " ";
482
+ const desc = opt.description ? ` — ${opt.description}` : "";
483
+ const reason = reasons[row.index] !== undefined ? ` — ⚠ ${reasons[row.index]}` : "";
484
+ lines.push(`${indent}${effective[row.index] ? "[x]" : "[ ]"} ${opt.label}${desc}${reason}`);
485
+ }
486
+ lines.push("");
487
+ lines.push(nonInteractiveHint ?? "Hint: run interactively to choose.");
488
+ return {
489
+ interactive: false,
490
+ cancelled: false,
491
+ values,
492
+ hint: lines.join("\n"),
493
+ };
494
+ }
495
+ // ── Interactive mode ────────────────────────────────────────
496
+ return new Promise((resolve) => {
497
+ /** Cursor value when the submit button (not an option) is focused. */
498
+ const SUBMIT = options.length;
499
+ let cursor = 0;
500
+ const checked = options.map((opt) => opt.checked === true);
501
+ let state = evaluateChecked(options, checked);
502
+ /**
503
+ * Re-evaluate dependencies and persist the result: a disabled row is
504
+ * actually cleared, so re-enabling it later does not silently bring
505
+ * back a hidden checkmark — not for the initial state, not after a
506
+ * toggle, not after select-all.
507
+ */
508
+ function reevaluate() {
509
+ state = evaluateChecked(options, checked);
510
+ for (let i = 0; i < options.length; i++) {
511
+ checked[i] = state.effective[i];
512
+ }
513
+ }
514
+ reevaluate();
515
+ // Display rows interleave group headers with options. Group
516
+ // membership is fixed for the lifetime of the prompt, so the row
517
+ // list is built once; only the per-row state changes.
518
+ const rows = buildRows(options);
519
+ // Same wrap accounting as select(): rows wider than the terminal
520
+ // occupy extra physical lines that CURSOR_UP must traverse. `cols`
521
+ // is re-read on every repaint: a terminal resize while the menu is
522
+ // open changes how rows wrap, and trusting the stale width makes
523
+ // the rewind miss the previous render's anchor.
524
+ let cols = out.columns || 80;
525
+ const headerLineCount = (width) => Math.max(1, Math.ceil((2 + message.length) / width)) +
526
+ Math.max(1, Math.ceil((2 + keyHint.length) / width));
527
+ const rowVisibleLength = (row) => {
528
+ if (row.kind === "header")
529
+ return 2 + row.label.length;
530
+ const opt = options[row.index];
531
+ const reason = state.reasons[row.index];
532
+ // " ❯ " (4) + "[x] " (4) + group indent (2 when grouped) + label
533
+ // + optional " " + description + optional " ⚠ " + reason
534
+ return (8 +
535
+ (opt.group === undefined ? 0 : 2) +
536
+ opt.label.length +
537
+ (opt.description ? 1 + opt.description.length : 0) +
538
+ (reason !== undefined ? 3 + reason.length : 0));
539
+ };
540
+ /**
541
+ * The line under the list names the focused row's unmet
542
+ * requirement — the prominent explanation for a greyed-out
543
+ * option. Blank when the focused row is not blocked. Always
544
+ * rendered so the physical line count stays stable.
545
+ */
546
+ const footerText = () => {
547
+ const reason = state.reasons[cursor];
548
+ if (reason === undefined)
549
+ return undefined;
550
+ return `⚠ ${options[cursor].label} ${reason} — enable it to unlock this option`;
551
+ };
552
+ const footerVisibleLength = () => {
553
+ const text = footerText();
554
+ return text === undefined ? 0 : 2 + text.length;
555
+ };
556
+ // The submit button sits below the footer line, drawn as a
557
+ // bordered box (top border, label, bottom border) so it reads as
558
+ // a clickable button rather than another list row. The box is
559
+ // truncated to the terminal width instead of wrapping: a wrapped
560
+ // box looks broken, and a constant one-physical-row-per-line
561
+ // layout keeps rewind and tail-erasure accounting exact even
562
+ // when wide characters would otherwise straddle the last column.
563
+ /** `${submitLabel} — ${n} of ${total} selected ➜` — the trailing
564
+ * arrow is the wizard affordance: this button advances to the
565
+ * next step. */
566
+ const buttonText = () => {
567
+ const selected = state.effective.filter(Boolean).length;
568
+ return `${submitLabel} — ${selected} of ${options.length} selected ➜`;
569
+ };
570
+ /** Button label with two spaces of padding on each side,
571
+ * truncated so " " (2) + borders (2) + inner stay within the
572
+ * terminal with two cells of slack. */
573
+ const buttonInner = () => truncateToWidth(` ${buttonText()} `, Math.max(4, cols - 6));
574
+ // " " (2) + "│" (1) + inner + "│" (1); inner is measured in
575
+ // terminal cells, not code units, so CJK labels keep the box
576
+ // borders aligned.
577
+ const buttonVisibleLength = () => 4 + displayWidth(buttonInner());
578
+ // Recomputed per render: dependency reasons appear and disappear
579
+ // as options are toggled, changing how rows wrap.
580
+ const physicalLineCount = () => rows.reduce((sum, row) => sum + Math.max(1, Math.ceil(rowVisibleLength(row) / cols)), 0) +
581
+ Math.max(1, Math.ceil(footerVisibleLength() / cols)) +
582
+ 3 * Math.max(1, Math.ceil(buttonVisibleLength() / cols));
583
+ // Cursor rewinds must traverse the *previous* render's line count.
584
+ let lastRenderedLines = 0;
585
+ /** Visible length of each line the previous render painted, in
586
+ * order. Width-independent: the resize recovery re-wraps these at
587
+ * the new width to find the previous render's on-screen height —
588
+ * the current state may already differ from what was painted. */
589
+ let lastPaintedLengths = [];
590
+ /** Physical lines the previous render occupies on screen right
591
+ * now, at the live width: after a resize with no repaint since,
592
+ * the terminal has rewrapped the menu. */
593
+ const menuLinesOnScreen = () => {
594
+ const width = out.columns || 80;
595
+ return lastPaintedLengths.reduce((sum, len) => sum + Math.max(1, Math.ceil(len / width)), 0);
596
+ };
597
+ /**
598
+ * Erase the stale tail of a wrapped row whose new content is
599
+ * shorter than the previous render's — but only when the
600
+ * content does not exactly fill its last physical line: under
601
+ * delayed autowrap the cursor then sits on the final character,
602
+ * and erase-to-EOL would delete it. An exactly-full line was
603
+ * fully overwritten, so no stale tail can remain.
604
+ */
605
+ const eraseTail = (visibleLength) => visibleLength % cols === 0 ? "" : CLEAR_TO_EOL;
606
+ function render(firstRender) {
607
+ let resized = false;
608
+ if (!firstRender) {
609
+ const width = out.columns || 80;
610
+ if (width !== cols) {
611
+ // The terminal was resized while the menu was open and
612
+ // rewrapped the previous render: its on-screen height is
613
+ // the previous render's own line lengths wrapped at the
614
+ // NEW width (the current state may already differ from
615
+ // what was painted). Rewind by that to the menu's top,
616
+ // wipe everything below, and repaint from the fresh anchor.
617
+ cols = width;
618
+ const rewind = lastPaintedLengths.reduce((sum, len) => sum + Math.max(1, Math.ceil(len / cols)), 0);
619
+ out.write(CURSOR_UP(rewind));
620
+ out.write(ERASE_TO_END_OF_SCREEN);
621
+ resized = true;
622
+ }
623
+ else {
624
+ out.write(CURSOR_UP(lastRenderedLines));
625
+ }
626
+ }
627
+ const paintedLengths = [];
628
+ for (const row of rows) {
629
+ if (row.kind === "header") {
630
+ paintedLengths.push(2 + row.label.length);
631
+ out.write(`${CLEAR_LINE}${CURSOR_TO_COL(1)} ${BOLD}${row.label}${RESET}${eraseTail(2 + row.label.length)}\n`);
632
+ continue;
633
+ }
634
+ const i = row.index;
635
+ const opt = options[i];
636
+ const highlighted = i === cursor;
637
+ const reason = state.reasons[i];
638
+ const indent = opt.group === undefined ? " " : " ";
639
+ const pointer = highlighted ? `${CYAN}❯${RESET}` : " ";
640
+ const box = state.effective[i] && reason === undefined
641
+ ? `${INVERSE}[x]${RESET}`
642
+ : "[ ]";
643
+ // A blocked row dims label and description, and the reason
644
+ // stands out in warning yellow instead of blending into the
645
+ // dimmed row.
646
+ let label = opt.label;
647
+ if (reason !== undefined)
648
+ label = `${DIM}${opt.label}${RESET}`;
649
+ else if (highlighted)
650
+ label = `${BOLD}${opt.label}${RESET}`;
651
+ const desc = opt.description ? ` ${DIM}${opt.description}${RESET}` : "";
652
+ const why = reason !== undefined ? ` ${YELLOW}⚠ ${reason}${RESET}` : "";
653
+ out.write(`${CLEAR_LINE}${CURSOR_TO_COL(1)}${indent}${pointer} ${box} ${label}${desc}${why}${eraseTail(rowVisibleLength(row))}\n`);
654
+ paintedLengths.push(rowVisibleLength(row));
655
+ }
656
+ const footer = footerText();
657
+ paintedLengths.push(footerVisibleLength());
658
+ out.write(`${CLEAR_LINE}${CURSOR_TO_COL(1)}${footer === undefined ? "" : ` ${YELLOW}${footer}${RESET}`}${eraseTail(footerVisibleLength())}\n`);
659
+ // Bordered-box submit button: while focused, the button's
660
+ // content inverts (the pre-box affordance) with a bold
661
+ // label; the border itself always renders in solid terminal
662
+ // white — the button is active, and a dim border would
663
+ // suggest it is disabled.
664
+ const inner = buttonInner();
665
+ const innerWidth = displayWidth(inner);
666
+ const focused = cursor === SUBMIT;
667
+ const label = focused ? `${INVERSE}${BOLD}${inner}${RESET}` : inner;
668
+ const tail = eraseTail(buttonVisibleLength());
669
+ paintedLengths.push(buttonVisibleLength());
670
+ out.write(`${CLEAR_LINE}${CURSOR_TO_COL(1)} ╭${"─".repeat(innerWidth)}╮${tail}\n`);
671
+ paintedLengths.push(buttonVisibleLength());
672
+ out.write(`${CLEAR_LINE}${CURSOR_TO_COL(1)} │${label}│${tail}\n`);
673
+ paintedLengths.push(buttonVisibleLength());
674
+ out.write(`${CLEAR_LINE}${CURSOR_TO_COL(1)} ╰${"─".repeat(innerWidth)}╯${tail}\n`);
675
+ // A repaint can be shorter than the previous render (a reason
676
+ // or the footer collapsed to fewer wrapped lines). Erase the
677
+ // leftover lines — otherwise their stale text survives below
678
+ // the menu, out of reach of the final clearMenu(). Skip this
679
+ // after a resize recovery: the erase-to-end-of-screen already
680
+ // cleared everything below the fresh anchor, and each erased
681
+ // "leftover" would be a stray newline scrolling the freshly
682
+ // painted prompt upward.
683
+ const painted = physicalLineCount();
684
+ if (!resized) {
685
+ for (let i = painted; i < lastRenderedLines; i++) {
686
+ out.write(`${CLEAR_LINE}\n`);
687
+ }
688
+ if (painted < lastRenderedLines) {
689
+ out.write(CURSOR_UP(lastRenderedLines - painted));
690
+ }
691
+ }
692
+ lastRenderedLines = painted;
693
+ lastPaintedLengths = paintedLengths;
694
+ }
695
+ /** Re-evaluate dependencies after a toggle, then repaint. */
696
+ function retoggle(index, value) {
697
+ if (state.reasons[index] !== undefined)
698
+ return;
699
+ checked[index] = value ?? !checked[index];
700
+ reevaluate();
701
+ render(false);
702
+ }
703
+ function clearMenu() {
704
+ // Measured at the live width: a resize since the last repaint
705
+ // means the terminal rewrapped the menu.
706
+ const lines = menuLinesOnScreen();
707
+ out.write(CURSOR_UP(lines));
708
+ for (let i = 0; i < lines; i++) {
709
+ out.write(`${CLEAR_LINE}\n`);
710
+ }
711
+ out.write(CURSOR_UP(lines));
712
+ }
713
+ // Print the message header and key hint
714
+ out.write(`${BOLD}${CYAN}?${RESET} ${BOLD}${message}${RESET}\n`);
715
+ out.write(` ${DIM}${keyHint}${RESET}\n`);
716
+ out.write(HIDE_CURSOR);
717
+ render(true);
718
+ // Enable keypress events BEFORE raw mode so the first
719
+ // keystroke is captured (order matters).
720
+ emitKeypressEvents(input);
721
+ input.on("keypress", onKeypress);
722
+ input.setRawMode?.(true);
723
+ input.resume();
724
+ function confirmSelection() {
725
+ cleanup();
726
+ clearMenu();
727
+ const chosen = options.filter((_opt, i) => state.effective[i]);
728
+ const summary = chosen.length > 0
729
+ ? `${CYAN}${chosen.map((opt) => opt.label).join(", ")}${RESET}`
730
+ : `${DIM}(none selected)${RESET}`;
731
+ out.write(`${CLEAR_LINE}${CURSOR_TO_COL(1)} ${summary}\n`);
732
+ resolve({
733
+ interactive: true,
734
+ cancelled: false,
735
+ values: chosen.map((opt) => opt.value),
736
+ });
737
+ }
738
+ function onKeypress(_chunk, key) {
739
+ if (!key)
740
+ return;
741
+ const digit = Number(key.sequence);
742
+ if (key.sequence?.length === 1 &&
743
+ Number.isInteger(digit) &&
744
+ digit >= 1 &&
745
+ digit <= Math.min(options.length, MAX_NUMBERED_OPTIONS)) {
746
+ retoggle(digit - 1);
747
+ }
748
+ else if (key.name === "up" || (key.ctrl && key.name === "p")) {
749
+ cursor = cursor <= 0 ? SUBMIT : cursor - 1;
750
+ render(false);
751
+ }
752
+ else if (key.name === "down" || (key.ctrl && key.name === "n")) {
753
+ cursor = cursor >= SUBMIT ? 0 : cursor + 1;
754
+ render(false);
755
+ }
756
+ else if (key.name === "tab") {
757
+ cursor = cursor === SUBMIT ? 0 : SUBMIT;
758
+ render(false);
759
+ }
760
+ else if (key.name === "space") {
761
+ if (cursor !== SUBMIT)
762
+ retoggle(cursor);
763
+ }
764
+ else if (key.sequence === "a") {
765
+ // Set every option together so dependencies enabled by this
766
+ // selection are included in the same all-toggle.
767
+ const checkAll = state.effective.some((isChecked) => !isChecked);
768
+ checked.fill(checkAll);
769
+ reevaluate();
770
+ render(false);
771
+ }
772
+ else if (key.name === "return") {
773
+ if (cursor === SUBMIT)
774
+ confirmSelection();
775
+ else
776
+ retoggle(cursor);
777
+ }
778
+ else if (key.name === "escape" || (key.ctrl && key.name === "c")) {
779
+ cleanup();
780
+ clearMenu();
781
+ // The header count is measured at the live width too — the
782
+ // terminal rewrapped it on a resize.
783
+ const header = headerLineCount(out.columns || 80);
784
+ out.write(CURSOR_UP(header));
785
+ for (let i = 0; i < header; i++) {
786
+ out.write(`${CLEAR_LINE}\n`);
787
+ }
788
+ out.write(CURSOR_UP(header));
789
+ // Ctrl+C: re-raise so the process exits naturally
790
+ if (key.ctrl && key.name === "c") {
791
+ process.kill(process.pid, "SIGINT");
792
+ }
793
+ // Escape: resolve as cancelled
794
+ resolve({ interactive: true, cancelled: true });
795
+ }
796
+ }
797
+ function cleanup() {
798
+ input.removeListener("keypress", onKeypress);
799
+ input.setRawMode?.(false);
800
+ input.pause();
801
+ out.write(SHOW_CURSOR);
802
+ }
803
+ });
804
+ }
267
805
  // ── confirm() ─────────────────────────────────────────────────────
268
806
  /** Parse a yes/no answer; `undefined` means the answer was not recognised. */
269
807
  function parseYesNo(answer, defaultValue) {