@rockcarver/frodo-cli 5.0.0-6 → 5.0.0-7

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.
@@ -0,0 +1,1843 @@
1
+ const require_rolldown_runtime = require("./rolldown-runtime-Ctb5zv51.cjs");
2
+ const require_ColorTheme = require("./ColorTheme-DEHDqYXV.cjs");
3
+ const require_Console = require("./Console--leD9RdR.cjs");
4
+ const require_EscapableSelectPrompt = require("./EscapableSelectPrompt-Us2SkS12.cjs");
5
+ const require_AuthoringPrintState = require("./AuthoringPrintState-vyWOD1Wt.cjs");
6
+ const require_EntityPickers = require("./EntityPickers-szvN8rXt.cjs");
7
+ const require_DefaultsStore = require("./DefaultsStore-RlEkAWqT.cjs");
8
+ const require_RealmPickers = require("./RealmPickers-7b9g8ZTE.cjs");
9
+ let path = require("path");
10
+ path = require_rolldown_runtime.__toESM(path, 1);
11
+ let fs = require("fs");
12
+ fs = require_rolldown_runtime.__toESM(fs, 1);
13
+ let os = require("os");
14
+ os = require_rolldown_runtime.__toESM(os, 1);
15
+ /**
16
+ * Read a line of free-form text. Paste-safe and editable (the readline
17
+ * buffer does the editing; the prompt only reads it), unlike accumulating
18
+ * individual keypresses by hand.
19
+ */
20
+ async function promptInput(config) {
21
+ if (!require_EscapableSelectPrompt.canPrompt()) return void 0;
22
+ return runTextPrompt(config, { suppress: false });
23
+ }
24
+ /**
25
+ * Read a line of text without echoing it (passwords, passphrases, and
26
+ * similar secrets). Same result contract as `promptInput`.
27
+ */
28
+ async function promptPassword(config) {
29
+ if (!require_EscapableSelectPrompt.canPrompt()) return void 0;
30
+ return runTextPrompt(config, { suppress: true });
31
+ }
32
+ /**
33
+ * Terminal conditions outside the user's in-prompt choices: stdin EOF
34
+ * (Ctrl-D, e.g. the driver's shutdown write) and Ctrl-C both reject the
35
+ * prompt with @inquirer/core's ExitPromptError. For gap-fills both mean
36
+ * "no value supplied" and must degrade to the declined result (`''`) so
37
+ * the caller falls through to its pre-existing missing-input error --
38
+ * never a raw stack trace. (Escape is handled in-prompt, so it never
39
+ * reaches this wrapper.)
40
+ */
41
+ async function runTextPrompt(config, opts) {
42
+ require_EscapableSelectPrompt.notePromptRendered();
43
+ try {
44
+ return await textPrompt(config, opts);
45
+ } catch (error) {
46
+ if (error instanceof require_EscapableSelectPrompt.ExitPromptError) return "";
47
+ throw error;
48
+ }
49
+ }
50
+ function textPrompt(config, { suppress }) {
51
+ return require_EscapableSelectPrompt.createPrompt((cfg, done) => {
52
+ const [value, setValue] = require_EscapableSelectPrompt.useState("");
53
+ const [status, setStatus] = require_EscapableSelectPrompt.useState("idle");
54
+ const prefix = require_EscapableSelectPrompt.usePrefix({ status: status === "declined" ? "done" : status });
55
+ require_EscapableSelectPrompt.useKeypress((key, rl) => {
56
+ if (require_EscapableSelectPrompt.isEnterKey(key)) {
57
+ const line = value || rl.line || "";
58
+ if (line.length === 0 && cfg.default !== void 0) {
59
+ setValue(cfg.default);
60
+ setStatus("done");
61
+ done(cfg.default);
62
+ } else if (line.length === 0) {
63
+ setStatus("declined");
64
+ done("");
65
+ } else {
66
+ setValue(line);
67
+ setStatus("done");
68
+ done(line);
69
+ }
70
+ } else if (key.name === "escape") {
71
+ setStatus("declined");
72
+ done("");
73
+ } else setValue(rl.line);
74
+ });
75
+ const defaultHint = cfg.default !== void 0 && !suppress ? ` ${require_ColorTheme.theme.muted(`(${cfg.default})`)}` : "";
76
+ if (status === "declined") return `${prefix} ${config.message} ${require_ColorTheme.theme.muted("(no input)")}`;
77
+ if (status === "done") {
78
+ const shown = suppress ? "*".repeat(value.length) : value;
79
+ return `${prefix} ${config.message} ${require_ColorTheme.theme.positive(shown)}`;
80
+ }
81
+ const shown = suppress ? "*".repeat(value.length) : value;
82
+ return `${prefix} ${config.message}${defaultHint}${shown ? ` ${require_ColorTheme.theme.command(shown)}` : ""}`;
83
+ })(config, { clearPromptOnDone: true });
84
+ }
85
+ //#endregion
86
+ //#region src/utils/interactive/CommandPreview.ts
87
+ /**
88
+ * frodo-lib's sentinel default for "no realm chosen yet" and its
89
+ * per-deployment-type translations (the same mapping frodo-lib's
90
+ * determineDefaultRealm applies during auth). Zero-import constraint:
91
+ * the map is duplicated here rather than imported from frodo-lib --
92
+ * if the lib map ever changes, this copy MUST change with it (the test
93
+ * below pins the values).
94
+ */
95
+ const DEFAULT_REALM_KEY = "__default__realm__";
96
+ const DEPLOYMENT_TYPE_REALM_MAP = {
97
+ classic: "/",
98
+ cloud: "alpha",
99
+ forgeops: "/"
100
+ };
101
+ /**
102
+ * The deployment type the resolver knows for this process (set from the
103
+ * CLI side via setDeploymentTypeForPreview -- the resolution pass and
104
+ * profile loading may resolve it in either order relative to the first
105
+ * prompt render). Undefined = not yet known.
106
+ */
107
+ let previewDeploymentType;
108
+ /**
109
+ * Records the deployment type for sentinel translation in the preview.
110
+ * Called by the resolution pass when the deployment type is (or becomes)
111
+ * known: CLI-provided (-m/--type), connection-profile-carried, or
112
+ * persisted.
113
+ */
114
+ function setDeploymentTypeForPreview(type) {
115
+ previewDeploymentType = type;
116
+ }
117
+ /**
118
+ * Translates a positional value for serialization. The realm sentinel
119
+ * NEVER displays: with a known deployment type it becomes that type's
120
+ * default realm (alpha on cloud, / on classic/forgeops -- the SAME
121
+ * translation frodo-lib applies during auth, so the printed command is
122
+ * exactly what the run will execute; printing the TRANSLATED value is
123
+ * deliberate -- defaults can change between frodo versions, and a CI
124
+ * pipeline that copy-pasted the printed command must keep reading and
125
+ * writing the realm it was authored against, pinning the value now
126
+ * beats a silent realm change on upgrade). Before the type is known
127
+ * (e.g. the profile picker footer, where no host has been picked yet)
128
+ * the positional is OMITTED entirely -- the sentinel is an
129
+ * implementation detail no user ever typed or should ever see, and the
130
+ * live footer is a status display, not a copy-paste surface; by the
131
+ * final authoring print the type is always resolved, so the pipeline
132
+ * guarantee is unaffected.
133
+ */
134
+ function serializePositionalValue(argumentName, value) {
135
+ if (argumentName === "password") return "********";
136
+ if (argumentName === "realm" && value === DEFAULT_REALM_KEY) return (previewDeploymentType && DEPLOYMENT_TYPE_REALM_MAP[previewDeploymentType]) ?? "";
137
+ return value;
138
+ }
139
+ /** Options that are machinery, not configuration -- never serialized. */
140
+ const NON_SERIALIZABLE_OPTIONS = /* @__PURE__ */ new Set([
141
+ "help",
142
+ "help-more",
143
+ "help-all",
144
+ "version",
145
+ "prompt",
146
+ "no-prompt",
147
+ "edit",
148
+ "save-defaults"
149
+ ]);
150
+ /**
151
+ * Serializes the command as it would be typed on the command line today
152
+ * -- every valued option as its flag (value placeholder included),
153
+ * valued positional arguments in order. Secrets (the password
154
+ * positional) are masked; values are shell-safe by inspection but NOT
155
+ * shell-quoted -- this is a preview, not an eval string.
156
+ */
157
+ function serializeCommand(command) {
158
+ const parts = [commandPath(command)];
159
+ const args = [];
160
+ command.registeredArguments.forEach((argument, index) => {
161
+ const value = command.processedArgs?.[index];
162
+ if (typeof value !== "string" || value.length === 0) return;
163
+ const serialized = serializePositionalValue(argument.name(), value);
164
+ if (serialized.length === 0) return;
165
+ args.push(serialized);
166
+ });
167
+ parts.push(...args);
168
+ for (const option of command.options) {
169
+ if (NON_SERIALIZABLE_OPTIONS.has(option.name())) continue;
170
+ const value = command.getOptionValue(option.attributeName());
171
+ if (value === void 0 || value === "" || !option.negate && value === false) continue;
172
+ if (command.getOptionValueSource(option.attributeName()) === "default") continue;
173
+ if (value === true || option.negate) parts.push(option.flags.split(/[, ]+/)[0]);
174
+ else if (Array.isArray(value)) {
175
+ const longFlag = option.flags.split(/[, ]+/).find((token) => token.startsWith("--"));
176
+ for (const entry of value) parts.push(`${longFlag ?? option.flags} ${String(entry)}`);
177
+ } else {
178
+ const longFlag = option.flags.split(/[, ]+/).find((token) => token.startsWith("--"));
179
+ parts.push(`${longFlag ?? option.flags} ${String(value)}`);
180
+ }
181
+ }
182
+ return parts.join(" ");
183
+ }
184
+ /**
185
+ * The `frodo x y z` path of the command (root name + ancestors + this).
186
+ */
187
+ function commandPath(command) {
188
+ const names = [];
189
+ for (let cursor = command; cursor; cursor = cursor.parent) names.unshift(cursor.name());
190
+ return names.join(" ");
191
+ }
192
+ /**
193
+ * Whether the command still has mandatory input to collect (red+cursive
194
+ * in the preview) or is validated and ready (green/white): a deferred
195
+ * mandatory option, an unsatisfied one-of group, or -- per the resolver's
196
+ * readiness input -- an unresolved connection. Positional values are NOT
197
+ * sniffed here: host/username/password can legitimately resolve from
198
+ * env/profile without ever landing in the command object (the resolver's
199
+ * own fallbacks), so only the resolver can say whether the connection
200
+ * level is satisfied.
201
+ */
202
+ function isCommandReady(_command, readiness) {
203
+ if (readiness.missingMandatoryOptionLabels.length > 0) return false;
204
+ if (readiness.oneOfUnsatisfied) return false;
205
+ return readiness.connectionResolved !== false;
206
+ }
207
+ /**
208
+ * The preview footer line for the prompts: colored per readiness state
209
+ * (red + cursive = still missing mandatory input; green/white = ready).
210
+ */
211
+ function renderCommandPreview(command, readiness) {
212
+ const serialized = serializeCommand(command);
213
+ if (isCommandReady(command, readiness)) return require_ColorTheme.theme.positive(serialized);
214
+ return require_ColorTheme.theme.italic(require_ColorTheme.theme.negative(serialized));
215
+ }
216
+ /**
217
+ * The default highlighted-value→option-value mapping: pass-through for
218
+ * strings (value pickers), otherwise undefined (entity objects, the
219
+ * "enter manually" sentinel -- the callback renders the committed state).
220
+ */
221
+ function defaultToValue(highlighted) {
222
+ return typeof highlighted === "string" ? highlighted : void 0;
223
+ }
224
+ /**
225
+ * LIVE preview footer (the footer shows what the
226
+ * user is INFLUENCING, not what they last committed). Returns a callback
227
+ * for a prompt's `preview` config that re-renders on every highlight
228
+ * change: the highlighted value is serialized into a SHADOW copy of the
229
+ * command's positional (the real command object is untouched -- only
230
+ * <enter> commits), so arrowing through e.g. a realm list moves the
231
+ * footer's realm token in real time. When nothing is highlighted
232
+ * (filtered to no matches) the callback falls back to the command's
233
+ * committed state.
234
+ *
235
+ * Options picks pass `undefined` as the positional name and use the
236
+ * option-name variant below instead; this helper is for positionals
237
+ * (realm, host...).
238
+ */
239
+ function livePositionalPreview(command, positionalName, readiness) {
240
+ const index = command.registeredArguments.findIndex((argument) => argument.name() === positionalName);
241
+ return (highlighted) => {
242
+ const value = defaultToValue(highlighted);
243
+ if (index !== -1 && command.processedArgs && value) {
244
+ const committed = command.processedArgs[index];
245
+ command.processedArgs[index] = value;
246
+ try {
247
+ return renderCommandPreview(command, readiness);
248
+ } finally {
249
+ command.processedArgs[index] = committed;
250
+ }
251
+ }
252
+ return renderCommandPreview(command, readiness);
253
+ };
254
+ }
255
+ /**
256
+ * LIVE preview for an entity/option/value picker: the highlighted
257
+ * choice's value (after `toValue`) is serialized into a SHADOW copy of
258
+ * the named OPTION (source 'cli', the same source the real apply uses)
259
+ * for this render only. Restoring writes the previous value+source back
260
+ * verbatim: for a never-set option that is (undefined, undefined), which
261
+ * is exactly commander's pristine state (getOptionValue -> undefined,
262
+ * serializer skips it). `toValue` maps the highlighted choice to the
263
+ * option's value form -- identity for value pickers, the entity's label
264
+ * for entity pickers (whose choice values are the raw entities, exactly
265
+ * what the real apply writes); a mapping to undefined/empty renders the
266
+ * committed state.
267
+ */
268
+ function liveOptionPreview(command, optionName, readiness, toValue = defaultToValue) {
269
+ return (highlighted) => {
270
+ const value = toValue(highlighted);
271
+ if (value && value.length > 0) {
272
+ const committed = command.getOptionValue(optionName);
273
+ const committedSource = command.getOptionValueSource(optionName);
274
+ command.setOptionValueWithSource(optionName, value, "cli");
275
+ try {
276
+ return renderCommandPreview(command, readiness);
277
+ } finally {
278
+ command.setOptionValueWithSource(optionName, committed, committedSource);
279
+ }
280
+ }
281
+ return renderCommandPreview(command, readiness);
282
+ };
283
+ }
284
+ /**
285
+ * LIVE preview for the invocation editor (a MULTI-select): the callback
286
+ * receives the currently SELECTED attribute names (the space-toggled
287
+ * set), and the footer renders each as its flag -- booleans commit `true`
288
+ * on the editor's pick, valued options still need their value step, so
289
+ * they serialize as the flag with the value placeholder the user is
290
+ * about to fill ("--type <type>"). The real command object is never
291
+ * written here: every shadow is applied for THIS render and restored in
292
+ * the finally. An empty selection renders the committed state.
293
+ */
294
+ function liveMultiOptionPreview(command, readiness) {
295
+ return (selectedAttributeNames) => {
296
+ if (!Array.isArray(selectedAttributeNames)) return renderCommandPreview(command, readiness);
297
+ const shadows = [];
298
+ for (const attributeName of selectedAttributeNames) {
299
+ if (typeof attributeName !== "string") continue;
300
+ const option = command.options.find((candidate) => candidate.attributeName() === attributeName);
301
+ if (!option) continue;
302
+ const boolean = !/<[^>]+>|\[[^\]]+\]/.test(option.flags);
303
+ const committed = command.getOptionValue(attributeName);
304
+ const committedSource = command.getOptionValueSource(attributeName);
305
+ const hasUserValue = committedSource === "cli" && committed !== void 0 && (!Array.isArray(committed) || committed.length > 0);
306
+ shadows.push({
307
+ optionName: attributeName,
308
+ committed,
309
+ committedSource
310
+ });
311
+ if (!boolean && hasUserValue) continue;
312
+ const placeholder = option.flags.split(/[, ]+/).filter((token) => /^[<[].*>?\]?$/.test(token)).join(" ") || "value";
313
+ command.setOptionValueWithSource(attributeName, boolean ? true : placeholder, "cli");
314
+ }
315
+ try {
316
+ return renderCommandPreview(command, readiness);
317
+ } finally {
318
+ for (const shadow of shadows.reverse()) command.setOptionValueWithSource(shadow.optionName, shadow.committed, shadow.committedSource);
319
+ }
320
+ };
321
+ }
322
+ //#endregion
323
+ //#region src/utils/interactive/ConnectionPagePrompt.ts
324
+ /**
325
+ * Resolved by `connectionPage` when the user presses Escape on the page
326
+ * (not inside a row editor): "don't touch connection args". The caller
327
+ * falls back to its pre-existing behavior (today: the sequential
328
+ * prompts; for an already-resolved visit, just conclude).
329
+ */
330
+ const PAGE_ESCAPE = Symbol("connectionPage:escape");
331
+ /** The masked rendering of a password row's stored value. */
332
+ const PASSWORD_MASK = "••••••••";
333
+ const connectionPageImpl = require_EscapableSelectPrompt.createPrompt((config, done) => {
334
+ const [rows, setRows] = require_EscapableSelectPrompt.useState(config.rows);
335
+ const doneIndex = config.rows.length;
336
+ const [active, setActive] = require_EscapableSelectPrompt.useState(0);
337
+ const [status, setStatus] = require_EscapableSelectPrompt.useState("idle");
338
+ const [editing, setEditing] = require_EscapableSelectPrompt.useState(null);
339
+ const [draft, setDraft] = require_EscapableSelectPrompt.useState("");
340
+ const [resolving, setResolving] = require_EscapableSelectPrompt.useState(false);
341
+ const prefix = require_EscapableSelectPrompt.usePrefix({ status: status === "escaped" ? "done" : status });
342
+ const draftRef = require_EscapableSelectPrompt.useRef("");
343
+ const escapeGraceRef = require_EscapableSelectPrompt.useRef(void 0);
344
+ const [escapeGraceOpen, setEscapeGraceOpen] = require_EscapableSelectPrompt.useState(false);
345
+ const resolvingRef = require_EscapableSelectPrompt.useRef(false);
346
+ require_EscapableSelectPrompt.useEffect(() => () => escapeGraceRef.current?.dispose(), []);
347
+ require_EscapableSelectPrompt.useEffect(() => {
348
+ draftRef.current = draft;
349
+ }, [draft]);
350
+ const commitRow = async (key, value) => {
351
+ setEditing(null);
352
+ setDraft("");
353
+ if (key === "host" && config.onHostChange) {
354
+ setResolving(true);
355
+ resolvingRef.current = true;
356
+ try {
357
+ const updated = await config.onHostChange(value);
358
+ setRows(updated);
359
+ } catch {}
360
+ setResolving(false);
361
+ resolvingRef.current = false;
362
+ } else setRows((previous) => previous.map((row) => row.key === key ? {
363
+ ...row,
364
+ value
365
+ } : row));
366
+ };
367
+ const conclude = () => {
368
+ setStatus("done");
369
+ const result = {};
370
+ for (const row of rows) result[row.key] = row.value;
371
+ done(result);
372
+ };
373
+ require_EscapableSelectPrompt.useKeypress((key, rl) => {
374
+ if (resolvingRef.current) return;
375
+ if (editing !== null) {
376
+ if (require_EscapableSelectPrompt.isEnterKey(key)) {
377
+ escapeGraceRef.current?.otherKey();
378
+ escapeGraceRef.current = void 0;
379
+ const line = draft || rl.line || "";
380
+ if (editing === "password" && line.length === 0) commitRow(editing, rows.find((r) => r.key === "password")?.value ?? "");
381
+ else commitRow(editing, line);
382
+ } else if (key.name === "escape") {
383
+ if (escapeGraceRef.current) {
384
+ const grace = escapeGraceRef.current;
385
+ escapeGraceRef.current = void 0;
386
+ grace.secondEscape();
387
+ return;
388
+ }
389
+ setEscapeGraceOpen(true);
390
+ escapeGraceRef.current = require_EscapableSelectPrompt.armEscapeGrace({
391
+ onSecondEscape: () => {
392
+ setEditing(null);
393
+ setDraft("");
394
+ setStatus("escaped");
395
+ done(require_EscapableSelectPrompt.EXIT_ALL);
396
+ },
397
+ onGraceExpire: () => {
398
+ setEscapeGraceOpen(false);
399
+ setEditing(null);
400
+ setDraft("");
401
+ rl.clearLine(0);
402
+ }
403
+ });
404
+ return;
405
+ } else {
406
+ escapeGraceRef.current?.otherKey();
407
+ escapeGraceRef.current = void 0;
408
+ setDraft(rl.line);
409
+ }
410
+ return;
411
+ }
412
+ if (key.name === "escape") {
413
+ if (escapeGraceRef.current) {
414
+ const grace = escapeGraceRef.current;
415
+ escapeGraceRef.current = void 0;
416
+ grace.secondEscape();
417
+ return;
418
+ }
419
+ setEscapeGraceOpen(true);
420
+ escapeGraceRef.current = require_EscapableSelectPrompt.armEscapeGrace({
421
+ onSecondEscape: () => {
422
+ setEscapeGraceOpen(false);
423
+ setStatus("escaped");
424
+ done(require_EscapableSelectPrompt.EXIT_ALL);
425
+ },
426
+ onGraceExpire: () => {
427
+ setEscapeGraceOpen(false);
428
+ setStatus("escaped");
429
+ done(PAGE_ESCAPE);
430
+ }
431
+ });
432
+ return;
433
+ } else if (require_EscapableSelectPrompt.isEnterKey(key)) {
434
+ escapeGraceRef.current?.otherKey();
435
+ escapeGraceRef.current = void 0;
436
+ if (active === doneIndex) conclude();
437
+ else {
438
+ const row = rows[active];
439
+ setEditing(row.key);
440
+ setDraft("");
441
+ rl.clearLine(0);
442
+ }
443
+ } else if (require_EscapableSelectPrompt.isUpKey(key) || require_EscapableSelectPrompt.isDownKey(key)) {
444
+ escapeGraceRef.current?.otherKey();
445
+ escapeGraceRef.current = void 0;
446
+ const offset = require_EscapableSelectPrompt.isUpKey(key) ? -1 : 1;
447
+ setActive(active + offset < 0 ? doneIndex : (active + offset) % (doneIndex + 1));
448
+ }
449
+ });
450
+ const renderValue = (row, isEditing) => {
451
+ if (isEditing) return row.key === "password" ? "•".repeat(draft.length) : draft;
452
+ if (row.value === void 0 || row.value === "") return require_ColorTheme.theme.muted("(not set)");
453
+ return row.key === "password" ? require_ColorTheme.theme.muted(PASSWORD_MASK) : row.value;
454
+ };
455
+ if (status === "escaped") return `${prefix} ${config.message} ${require_ColorTheme.theme.muted("(cancelled)")}`;
456
+ if (status === "done") return `${prefix} ${config.message} ${require_ColorTheme.theme.positive("saved for this invocation")}`;
457
+ const resolvingNote = resolving ? require_ColorTheme.theme.muted(" (re-resolving credentials...)") : "";
458
+ const menu = require_EscapableSelectPrompt.renderNavigationMenu(require_EscapableSelectPrompt.navigationMenuItems({
459
+ enter: "edit / done",
460
+ escape: "cancel page"
461
+ }));
462
+ const rowLines = [...rows.map((row, index) => {
463
+ const isEditing = editing === row.key;
464
+ const cursor = isEditing ? "›" : index === active ? "›" : " ";
465
+ const note = !isEditing && row.note ? require_ColorTheme.theme.muted(` (${row.note})`) : "";
466
+ const line = `${cursor} ${row.label}: ${renderValue(row, isEditing)}${note}`;
467
+ return {
468
+ text: index === active || isEditing ? require_ColorTheme.theme.command(line) : line,
469
+ plain: `${cursor} ${row.label}: ${require_EscapableSelectPrompt.stripAnsi(renderValue(row, isEditing))}${row.note && !isEditing ? ` (${row.note})` : ""}`
470
+ };
471
+ }), (() => {
472
+ const line = `${active === doneIndex ? "›" : " "} Done — run with these values`;
473
+ return {
474
+ text: require_ColorTheme.theme.command(line),
475
+ plain: line
476
+ };
477
+ })()];
478
+ if (escapeGraceOpen) rowLines.push({
479
+ text: require_ColorTheme.theme.muted("esc again to exit all -- or wait to cancel the page"),
480
+ plain: "esc again to exit all -- or wait to cancel the page"
481
+ });
482
+ return [
483
+ menu,
484
+ require_EscapableSelectPrompt.renderFramedBox({
485
+ title: {
486
+ text: `${prefix} ${config.message}${resolvingNote}`,
487
+ plain: `? ${config.message}${resolvingNote}`
488
+ },
489
+ lines: rowLines
490
+ }),
491
+ config.preview
492
+ ].filter(Boolean).join("\n");
493
+ });
494
+ const connectionPage = ((config) => {
495
+ require_EscapableSelectPrompt.notePromptRendered();
496
+ return connectionPageImpl(config, { clearPromptOnDone: true });
497
+ });
498
+ //#endregion
499
+ //#region src/utils/interactive/ChoiceSections.ts
500
+ /**
501
+ * Builds the rows the prompt renders. With a query: the flat
502
+ * case-insensitive name matches across ALL choices, no headers,
503
+ * unindented (the pre-grouping behavior -- nothing hides from
504
+ * type-to-find). Without: own choices, then per group (config order)
505
+ * its header, and its choices -- indented -- only while expanded.
506
+ * Empty groups never render.
507
+ *
508
+ * `groups` omitted/empty keeps the exact pre-grouping behavior for
509
+ * every caller that has not adopted sections (choice `group` ids are
510
+ * then ignored): one flat list.
511
+ */
512
+ function buildSectionRows(options) {
513
+ const { choices, selected } = options;
514
+ const query = options.query ?? "";
515
+ if (query.length > 0) {
516
+ const needle = query.toLowerCase();
517
+ return choices.filter((choice) => choice.name.toLowerCase().includes(needle)).map((choice) => ({
518
+ kind: "choice",
519
+ choice,
520
+ indent: false
521
+ }));
522
+ }
523
+ const groups = options.groups ?? [];
524
+ if (groups.length === 0) return choices.map((choice) => ({
525
+ kind: "choice",
526
+ choice,
527
+ indent: false
528
+ }));
529
+ const known = new Set(groups.map((group) => group.id));
530
+ const extra = [...new Set(choices.map((choice) => choice.group).filter((group) => group !== void 0 && !known.has(group)))].sort((a, b) => a.localeCompare(b));
531
+ const ordered = [...groups, ...extra.map((id) => ({
532
+ id,
533
+ label: id
534
+ }))];
535
+ const byGroup = /* @__PURE__ */ new Map();
536
+ const own = [];
537
+ for (const choice of choices) if (choice.group === void 0) own.push(choice);
538
+ else {
539
+ const bucket = byGroup.get(choice.group);
540
+ if (bucket) bucket.push(choice);
541
+ else byGroup.set(choice.group, [choice]);
542
+ }
543
+ const rows = own.map((choice) => ({
544
+ kind: "choice",
545
+ choice,
546
+ indent: false
547
+ }));
548
+ for (const group of ordered) {
549
+ const members = byGroup.get(group.id);
550
+ if (!members || members.length === 0) continue;
551
+ const expanded = options.expanded.has(group.id);
552
+ rows.push({
553
+ kind: "header",
554
+ group,
555
+ count: members.length,
556
+ selectedCount: selected ? members.filter((choice) => selected.has(choice.value)).length : 0,
557
+ expanded
558
+ });
559
+ if (expanded) for (const choice of members) rows.push({
560
+ kind: "choice",
561
+ choice,
562
+ indent: true
563
+ });
564
+ }
565
+ return rows;
566
+ }
567
+ /**
568
+ * The groups that start EXPANDED: every group holding a choice the
569
+ * user has already set (the editor's `defaultValues` -- CLI/env/saved
570
+ * default/previous commit). State must never hide behind a collapsed
571
+ * header; own options need no expansion.
572
+ */
573
+ function initialExpanded(groups, choices, defaultValues) {
574
+ const valued = new Set(defaultValues);
575
+ const expanded = /* @__PURE__ */ new Set();
576
+ for (const choice of choices) if (choice.group !== void 0 && valued.has(choice.value)) expanded.add(choice.group);
577
+ const known = new Set(groups.map((group) => group.id));
578
+ return new Set([...expanded].filter((id) => known.has(id)));
579
+ }
580
+ /** The row index of the choice with this value (-1 when absent). */
581
+ function rowIndexOf(rows, value) {
582
+ return rows.findIndex((row) => row.kind === "choice" && row.choice.value === value);
583
+ }
584
+ //#endregion
585
+ //#region src/utils/interactive/EscapableMultiSelectPrompt.ts
586
+ /**
587
+ * Distinct return value `escapableMultiSelect` resolves with when the user
588
+ * presses Escape instead of committing -- callers branch on this to back
589
+ * out (skip the editor entirely) instead of treating it as a real
590
+ * selection. Nothing selected + Enter commits the empty set (a deliberate
591
+ * "run with defaults"), distinct from Escape's "don't touch this step".
592
+ * The ← key (query empty) is an alias for Escape -- the "return
593
+ * to the segment that invoked this editor" key; with text typed it stays
594
+ * readline cursor movement.
595
+ */
596
+ const MULTISEL_ESCAPE = Symbol("escapableMultiSelect:escape");
597
+ const escapableMultiSelectImpl = require_EscapableSelectPrompt.createPrompt((config, done) => {
598
+ const { pageSize = 20, choices } = config;
599
+ const [status, setStatus] = require_EscapableSelectPrompt.useState("idle");
600
+ const prefix = require_EscapableSelectPrompt.usePrefix({ status: status === "escaped" ? "done" : status });
601
+ const [query, setQuery] = require_EscapableSelectPrompt.useState("");
602
+ const [expandedState, setExpandedState] = require_EscapableSelectPrompt.useState(() => (config.groups?.length ?? 0) > 0 ? initialExpanded(config.groups ?? [], choices, config.defaultValues ?? []) : /* @__PURE__ */ new Set());
603
+ const [selected, setSelected] = require_EscapableSelectPrompt.useState(() => new Set(config.defaultValues ?? []));
604
+ const [editing, setEditing] = require_EscapableSelectPrompt.useState(null);
605
+ const [editingChoices, setEditingChoices] = require_EscapableSelectPrompt.useState([]);
606
+ const [draft, setDraft] = require_EscapableSelectPrompt.useState("");
607
+ const [pickerActive, setPickerActive] = require_EscapableSelectPrompt.useState(0);
608
+ const rows = require_EscapableSelectPrompt.useMemo(() => buildSectionRows({
609
+ choices,
610
+ groups: config.groups,
611
+ expanded: expandedState,
612
+ query,
613
+ selected
614
+ }), [
615
+ choices,
616
+ config.groups,
617
+ query,
618
+ selected,
619
+ expandedState
620
+ ]);
621
+ const lastQueryRef = require_EscapableSelectPrompt.useRef(query);
622
+ require_EscapableSelectPrompt.useEffect(() => {
623
+ if (lastQueryRef.current === query) return;
624
+ lastQueryRef.current = query;
625
+ setActive(0);
626
+ }, [query]);
627
+ const expandedRef2 = expandedState;
628
+ const [active, setActive] = require_EscapableSelectPrompt.useState(0);
629
+ const highlighted = rows[active];
630
+ const highlightedChoice = highlighted?.kind === "choice" ? highlighted.choice : void 0;
631
+ const escapeGraceRef = require_EscapableSelectPrompt.useRef(void 0);
632
+ const [escapeGraceOpen, setEscapeGraceOpen] = require_EscapableSelectPrompt.useState(false);
633
+ const [leftGuard, setLeftGuard] = require_EscapableSelectPrompt.useState("");
634
+ require_EscapableSelectPrompt.useEffect(() => () => escapeGraceRef.current?.dispose(), []);
635
+ const closeInlineEditor = (rl, returnTo) => {
636
+ setEditing(null);
637
+ setEditingChoices([]);
638
+ setDraft("");
639
+ setPickerActive(0);
640
+ lastQueryRef.current = "";
641
+ setQuery("");
642
+ if (returnTo !== void 0) {
643
+ const groupId = choices.find((choice) => choice.value === returnTo)?.group;
644
+ if (groupId !== void 0 && !expandedRef2.has(groupId)) setExpandedState((previous) => {
645
+ const next = new Set(previous);
646
+ next.add(groupId);
647
+ return next;
648
+ });
649
+ const index = rowIndexOf(buildSectionRows({
650
+ choices,
651
+ groups: config.groups,
652
+ expanded: groupId !== void 0 && !expandedRef2.has(groupId) ? /* @__PURE__ */ new Set([...expandedRef2, groupId]) : expandedRef2,
653
+ query: "",
654
+ selected
655
+ }), returnTo);
656
+ if (index >= 0) setActive(index);
657
+ }
658
+ rl.write(null, {
659
+ ctrl: true,
660
+ name: "u"
661
+ });
662
+ rl.clearLine(0);
663
+ };
664
+ require_EscapableSelectPrompt.useKeypress((key, rl) => {
665
+ if (editing !== null) {
666
+ if (editingChoices.length > 0) {
667
+ if (require_EscapableSelectPrompt.isEnterKey(key)) {
668
+ escapeGraceRef.current?.otherKey();
669
+ escapeGraceRef.current = void 0;
670
+ const value = editingChoices[pickerActive] ?? editingChoices[0];
671
+ config.onValue?.(editing, value);
672
+ setSelected((previous) => {
673
+ const next = new Set(previous);
674
+ next.add(editing);
675
+ return next;
676
+ });
677
+ closeInlineEditor(rl, editing);
678
+ return;
679
+ }
680
+ if (key.name === "escape") {
681
+ if (escapeGraceRef.current) {
682
+ const grace = escapeGraceRef.current;
683
+ escapeGraceRef.current = void 0;
684
+ grace.secondEscape();
685
+ return;
686
+ }
687
+ setEscapeGraceOpen(true);
688
+ escapeGraceRef.current = require_EscapableSelectPrompt.armEscapeGrace({
689
+ onSecondEscape: () => {
690
+ closeInlineEditor(rl, editing);
691
+ setStatus("escaped");
692
+ done(require_EscapableSelectPrompt.EXIT_ALL);
693
+ },
694
+ onGraceExpire: () => {
695
+ setEscapeGraceOpen(false);
696
+ closeInlineEditor(rl, editing);
697
+ }
698
+ });
699
+ return;
700
+ }
701
+ if (require_EscapableSelectPrompt.isUpKey(key) || require_EscapableSelectPrompt.isDownKey(key)) {
702
+ escapeGraceRef.current?.otherKey();
703
+ escapeGraceRef.current = void 0;
704
+ const offset = require_EscapableSelectPrompt.isUpKey(key) ? -1 : 1;
705
+ setPickerActive((previous) => Math.min(editingChoices.length - 1, Math.max(0, previous + offset)));
706
+ return;
707
+ }
708
+ return;
709
+ }
710
+ if (require_EscapableSelectPrompt.isEnterKey(key)) {
711
+ escapeGraceRef.current?.otherKey();
712
+ escapeGraceRef.current = void 0;
713
+ const line = draft || rl.line || "";
714
+ if (line.trim().length === 0) return;
715
+ config.onValue?.(editing, line);
716
+ setSelected((previous) => {
717
+ const next = new Set(previous);
718
+ next.add(editing);
719
+ return next;
720
+ });
721
+ closeInlineEditor(rl, editing);
722
+ return;
723
+ }
724
+ if (key.name === "escape") {
725
+ if (escapeGraceRef.current) {
726
+ const grace = escapeGraceRef.current;
727
+ escapeGraceRef.current = void 0;
728
+ grace.secondEscape();
729
+ return;
730
+ }
731
+ setEscapeGraceOpen(true);
732
+ escapeGraceRef.current = require_EscapableSelectPrompt.armEscapeGrace({
733
+ onSecondEscape: () => {
734
+ closeInlineEditor(rl, editing);
735
+ setStatus("escaped");
736
+ done(require_EscapableSelectPrompt.EXIT_ALL);
737
+ },
738
+ onGraceExpire: () => {
739
+ setEscapeGraceOpen(false);
740
+ closeInlineEditor(rl, editing);
741
+ }
742
+ });
743
+ return;
744
+ }
745
+ escapeGraceRef.current?.otherKey();
746
+ escapeGraceRef.current = void 0;
747
+ setDraft(rl.line);
748
+ return;
749
+ }
750
+ if (key.name === "escape" || key.name === "left" && rl.line.length === 0) {
751
+ if (rl.line.length > 0) {
752
+ rl.clearLine(0);
753
+ setQuery("");
754
+ escapeGraceRef.current?.otherKey();
755
+ escapeGraceRef.current = void 0;
756
+ return;
757
+ }
758
+ const uncommitted = [...selected].filter((value) => !config.defaultValues?.includes(value));
759
+ if (uncommitted.length > 0) {
760
+ if (key.name === "left") {
761
+ setLeftGuard(`select or reset first -- ${uncommitted.length} option${uncommitted.length === 1 ? "" : "s"} not committed ([ESC] resets, [ENTER] commits)`);
762
+ return;
763
+ }
764
+ const resetThenResolve = () => {
765
+ setSelected((previous) => {
766
+ const next = new Set(previous);
767
+ for (const value of uncommitted) next.delete(value);
768
+ return next;
769
+ });
770
+ setStatus("escaped");
771
+ done(MULTISEL_ESCAPE);
772
+ };
773
+ if (escapeGraceRef.current) {
774
+ const grace = escapeGraceRef.current;
775
+ escapeGraceRef.current = void 0;
776
+ grace.secondEscape();
777
+ return;
778
+ }
779
+ setEscapeGraceOpen(true);
780
+ escapeGraceRef.current = require_EscapableSelectPrompt.armEscapeGrace({
781
+ onSecondEscape: () => {
782
+ setEscapeGraceOpen(false);
783
+ setStatus("escaped");
784
+ done(require_EscapableSelectPrompt.EXIT_ALL);
785
+ },
786
+ onGraceExpire: resetThenResolve
787
+ });
788
+ return;
789
+ }
790
+ if (key.name === "escape") {
791
+ if (escapeGraceRef.current) {
792
+ const grace = escapeGraceRef.current;
793
+ escapeGraceRef.current = void 0;
794
+ grace.secondEscape();
795
+ return;
796
+ }
797
+ setEscapeGraceOpen(true);
798
+ escapeGraceRef.current = require_EscapableSelectPrompt.armEscapeGrace({
799
+ onSecondEscape: () => {
800
+ setEscapeGraceOpen(false);
801
+ setStatus("escaped");
802
+ done(require_EscapableSelectPrompt.EXIT_ALL);
803
+ },
804
+ onGraceExpire: () => {
805
+ setEscapeGraceOpen(false);
806
+ setStatus("escaped");
807
+ done(MULTISEL_ESCAPE);
808
+ }
809
+ });
810
+ return;
811
+ }
812
+ escapeGraceRef.current?.otherKey();
813
+ escapeGraceRef.current = void 0;
814
+ setStatus("escaped");
815
+ done(MULTISEL_ESCAPE);
816
+ } else if (require_EscapableSelectPrompt.isEnterKey(key)) {
817
+ escapeGraceRef.current?.otherKey();
818
+ escapeGraceRef.current = void 0;
819
+ setLeftGuard("");
820
+ setStatus("done");
821
+ done([...selected]);
822
+ } else if (require_EscapableSelectPrompt.isSpaceKey(key)) {
823
+ escapeGraceRef.current?.otherKey();
824
+ escapeGraceRef.current = void 0;
825
+ setLeftGuard("");
826
+ if (!highlighted) return;
827
+ rl.write(null, {
828
+ ctrl: true,
829
+ name: "u"
830
+ });
831
+ rl.clearLine(0);
832
+ if (highlighted.kind === "header") {
833
+ const id = highlighted.group.id;
834
+ setExpandedState((previous) => {
835
+ const next = new Set(previous);
836
+ if (next.has(id)) next.delete(id);
837
+ else next.add(id);
838
+ return next;
839
+ });
840
+ return;
841
+ }
842
+ if (!selected.has(highlighted.choice.value)) {
843
+ const groupId = highlighted.choice.group;
844
+ if (groupId !== void 0 && !expandedRef2.has(groupId)) setExpandedState((previous) => {
845
+ const next = new Set(previous);
846
+ next.add(groupId);
847
+ return next;
848
+ });
849
+ }
850
+ if (!selected.has(highlighted.choice.value) && config.needsValue?.(highlighted.choice.value)) {
851
+ const choicesFor = config.choicesFor?.(highlighted.choice.value) ?? void 0;
852
+ const current = config.currentValueFor?.(highlighted.choice.value) ?? "";
853
+ setEditing(highlighted.choice.value);
854
+ setEditingChoices(choicesFor ?? []);
855
+ setPickerActive(choicesFor ? Math.max(0, choicesFor.indexOf(current)) : 0);
856
+ setDraft(current);
857
+ rl.write(null, {
858
+ ctrl: true,
859
+ name: "u"
860
+ });
861
+ rl.clearLine(0);
862
+ return;
863
+ }
864
+ setSelected((previous) => {
865
+ const next = new Set(previous);
866
+ if (next.has(highlighted.choice.value)) next.delete(highlighted.choice.value);
867
+ else next.add(highlighted.choice.value);
868
+ return next;
869
+ });
870
+ } else if (require_EscapableSelectPrompt.isUpKey(key) || require_EscapableSelectPrompt.isDownKey(key)) {
871
+ escapeGraceRef.current?.otherKey();
872
+ escapeGraceRef.current = void 0;
873
+ setLeftGuard("");
874
+ if (rows.length === 0) return;
875
+ const offset = require_EscapableSelectPrompt.isUpKey(key) ? -1 : 1;
876
+ setActive((previous) => Math.min(rows.length - 1, Math.max(0, previous + offset)));
877
+ } else {
878
+ escapeGraceRef.current?.otherKey();
879
+ escapeGraceRef.current = void 0;
880
+ setLeftGuard("");
881
+ setQuery(rl.line);
882
+ }
883
+ });
884
+ if (status === "escaped") return `${prefix} ${config.message} ${require_ColorTheme.theme.muted("(cancelled)")}`;
885
+ if (status === "done") {
886
+ const picked = choices.filter((choice) => selected.has(choice.value));
887
+ const summary = picked.length === 0 ? require_ColorTheme.theme.muted("(none -- run with defaults)") : require_ColorTheme.theme.positive(picked.map((choice) => choice.name).join(", "));
888
+ return `${prefix} ${config.message} ${summary}`;
889
+ }
890
+ const page = require_EscapableSelectPrompt.usePagination({
891
+ items: rows,
892
+ active,
893
+ renderItem: ({ item, isActive }) => {
894
+ if (item.kind === "header") {
895
+ const twisty = item.expanded ? "▾" : "▸";
896
+ const badge = !item.expanded && item.selectedCount > 0 ? ` · ${item.selectedCount} selected` : "";
897
+ const line = `${twisty} ${item.group.label} (${item.count})${badge}`;
898
+ return isActive ? require_ColorTheme.theme.command(line) : line;
899
+ }
900
+ const line = `${selected.has(item.choice.value) ? "◉" : "○"} ${isActive ? "› " : " "}${item.indent ? " " : ""}${item.choice.name}`;
901
+ return isActive ? require_ColorTheme.theme.command(line) : line;
902
+ },
903
+ pageSize,
904
+ loop: false
905
+ });
906
+ const queryEcho = query.length > 0 ? require_ColorTheme.theme.command(` query: ${query}`) : "";
907
+ const editingName = editing !== null ? choices.find((choice) => choice.value === editing)?.name ?? String(editing) : "";
908
+ const menu = require_EscapableSelectPrompt.renderNavigationMenu(require_EscapableSelectPrompt.navigationMenuItems(editing !== null ? {
909
+ enter: editingChoices.length > 0 ? "pick" : "commit value",
910
+ escape: "rejects"
911
+ } : {
912
+ filter: true,
913
+ space: highlighted?.kind === "header" ? highlighted.expanded ? "collapse" : "expand" : "select",
914
+ enter: "commit",
915
+ left: true,
916
+ escape: "back · [ESC]×2 exit all"
917
+ }));
918
+ const panelLines = [];
919
+ if (leftGuard) panelLines.push({
920
+ text: require_ColorTheme.theme.negative(leftGuard),
921
+ plain: leftGuard
922
+ });
923
+ else if (escapeGraceOpen) panelLines.push({
924
+ text: require_ColorTheme.theme.muted("esc again to exit all -- or wait to go back one level"),
925
+ plain: "esc again to exit all -- or wait to go back one level"
926
+ });
927
+ if (rows.length > 0) for (const row of page.split("\n")) panelLines.push({
928
+ text: row,
929
+ plain: require_EscapableSelectPrompt.stripAnsi(row)
930
+ });
931
+ else panelLines.push({
932
+ text: require_ColorTheme.theme.muted("(no matches -- backspace to edit)"),
933
+ plain: "(no matches -- backspace to edit)"
934
+ });
935
+ if (highlighted?.kind === "header") {
936
+ const members = choices.filter((choice) => choice.group === highlighted.group.id);
937
+ panelLines.push({
938
+ text: "",
939
+ plain: ""
940
+ });
941
+ panelLines.push(...require_EscapableSelectPrompt.descriptionPanelLines(`${highlighted.group.label}: ${members.map((choice) => choice.name).join(", ")}`));
942
+ } else if (highlightedChoice?.description) {
943
+ panelLines.push({
944
+ text: "",
945
+ plain: ""
946
+ });
947
+ panelLines.push(...require_EscapableSelectPrompt.descriptionPanelLines(highlightedChoice.description));
948
+ }
949
+ const panel = require_EscapableSelectPrompt.renderFramedBox({
950
+ title: {
951
+ text: `${prefix} ${config.message}${queryEcho}`,
952
+ plain: `? ${config.message}${queryEcho}`
953
+ },
954
+ lines: panelLines
955
+ });
956
+ const valueBox = editing === null ? "" : editingChoices.length > 0 ? require_EscapableSelectPrompt.renderFramedBox({
957
+ title: `Value for ${editingName}`,
958
+ lines: editingChoices.map((choice, index) => {
959
+ const line = `${index === pickerActive ? "›" : " "} ${choice}`;
960
+ return {
961
+ text: index === pickerActive ? require_ColorTheme.theme.command(line) : line,
962
+ plain: line
963
+ };
964
+ })
965
+ }) : require_EscapableSelectPrompt.renderFramedBox({
966
+ title: `Value for ${editingName}`,
967
+ lines: [{
968
+ text: require_ColorTheme.theme.command(draft || "(type a value)"),
969
+ plain: draft || "(type a value)"
970
+ }]
971
+ });
972
+ return [
973
+ menu,
974
+ panel,
975
+ ...editing !== null ? [valueBox] : [],
976
+ typeof config.preview === "function" ? config.preview(choices.filter((choice) => selected.has(choice.value)).map((choice) => choice.value)) : config.preview
977
+ ].filter(Boolean).join("\n");
978
+ });
979
+ const escapableMultiSelect = ((config) => {
980
+ require_EscapableSelectPrompt.notePromptRendered();
981
+ return escapableMultiSelectImpl(config, { clearPromptOnDone: true });
982
+ });
983
+ //#endregion
984
+ //#region src/utils/interactive/PositionalArgs.ts
985
+ /**
986
+ * Index of the default positional argument of that name on this command
987
+ * (commands omit default args via the FrodoCommand omits list, so the
988
+ * index differs per command), or -1 when the command doesn't declare it.
989
+ */
990
+ function positionalIndex(command, name) {
991
+ return command.registeredArguments.findIndex((argument) => argument.name() === name);
992
+ }
993
+ function positionalValue(command, name) {
994
+ const index = positionalIndex(command, name);
995
+ if (index === -1) return void 0;
996
+ const value = command.processedArgs?.[index];
997
+ return typeof value === "string" && value.length > 0 ? value : void 0;
998
+ }
999
+ /**
1000
+ * Writes `value` into BOTH surfaces the CLI reads for a positional:
1001
+ *
1002
+ * - `processedArgs` is what the action handler's positional parameters
1003
+ * are sliced from (commander's action() wrapper slices
1004
+ * this.processedArgs).
1005
+ * - `args` (raw, options-removed user args) is what
1006
+ * handleDefaultArgsAndOpts iterates to copy default arguments into
1007
+ * frodo-lib state INSIDE the action body -- it does NOT read
1008
+ * processedArgs, so a processedArgs-only injection would be
1009
+ * overwritten with `undefined` the moment the action starts.
1010
+ * Verified against commander's _processArguments (fills processedArgs
1011
+ * from args, never writes back) and this repo's
1012
+ * handleDefaultArgsAndOpts (iterates command.args).
1013
+ *
1014
+ * `args` holds only user-supplied positional values; a gap-fill by
1015
+ * definition fills a position the user left empty, so extending/padding
1016
+ * with the injected value is safe. Pad with nulls for any inner
1017
+ * positions the user skipped (rare: inner default args are optional),
1018
+ * since args is positional.
1019
+ */
1020
+ function setPositionalValue(command, name, value) {
1021
+ const index = positionalIndex(command, name);
1022
+ if (index === -1) return;
1023
+ if (command.processedArgs) command.processedArgs[index] = value;
1024
+ if (Array.isArray(command.args)) {
1025
+ while (command.args.length < index) command.args.push(null);
1026
+ if (index === command.args.length) command.args.push(value);
1027
+ else if (command.args[index] == null) command.args[index] = value;
1028
+ }
1029
+ }
1030
+ //#endregion
1031
+ //#region src/utils/SettingsStore.ts
1032
+ const SETTINGS_FILENAME = "Settings.json";
1033
+ function getSettingsPath() {
1034
+ return path.default.join(os.default.homedir(), ".frodo", SETTINGS_FILENAME);
1035
+ }
1036
+ function readSettings() {
1037
+ try {
1038
+ const parsed = JSON.parse(fs.default.readFileSync(getSettingsPath(), "utf8"));
1039
+ return typeof parsed === "object" && parsed !== null ? parsed : {};
1040
+ } catch {
1041
+ return {};
1042
+ }
1043
+ }
1044
+ function writeSettings(settings) {
1045
+ const file = getSettingsPath();
1046
+ fs.default.mkdirSync(path.default.dirname(file), { recursive: true });
1047
+ fs.default.writeFileSync(file, JSON.stringify(settings, null, 2));
1048
+ }
1049
+ /**
1050
+ * Whether the invocation editor should run by default on this invocation:
1051
+ * the persisted guided-mode toggle, with --no-prompt / FRODO_NO_PROMPT /
1052
+ * FRODO_TEST still gating everything downstream (the editor itself runs
1053
+ * behind canPrompt, so those environments ignore guided mode exactly as
1054
+ * they ignore --edit).
1055
+ */
1056
+ function guidedModeEnabled() {
1057
+ return readSettings().guidedMode === true;
1058
+ }
1059
+ function setGuidedMode(enabled) {
1060
+ const settings = readSettings();
1061
+ settings.guidedMode = enabled;
1062
+ writeSettings(settings);
1063
+ }
1064
+ //#endregion
1065
+ //#region src/cli/ResolveInteractiveInputs.ts
1066
+ /**
1067
+ * The "zero-touch" resolution pass: fills missing command input
1068
+ * interactively before the action body runs (see
1069
+ * docs/INTERACTIVE-COMMANDS.md). Wired from FrodoCommand's preAction
1070
+ * hook; never modifies frodo-lib.
1071
+ *
1072
+ * Two resolver kinds run here, connection arguments first (the host gives
1073
+ * the later prompts their context), then deferred mandatory options:
1074
+ *
1075
+ * 1. Connection arguments. Missing `host` (dropdown of saved connection
1076
+ * profiles, single profile silently assumed, free-text entry when none
1077
+ * exist -- see runInteractivePreferredCredentialPicker for the
1078
+ * precedent), missing `username`/`password` -- but ONLY when no saved
1079
+ * profile can supply credentials for the resolved host, since frodo-lib
1080
+ * already falls back to profile-stored credentials on its own
1081
+ * (AuthenticateOps loadConnectionProfile); prompting when a profile
1082
+ * would answer anyway would be pure friction. `--browser`/`--device`
1083
+ * likewise suppress the username/password prompts (their flow is the
1084
+ * interactive part) but not the host prompt, which those flows still
1085
+ * need.
1086
+ *
1087
+ * 2. Deferred mandatory options. Commander's
1088
+ * `missingMandatoryOptionValue()` normally throws during parsing --
1089
+ * BEFORE the preAction hook chain runs. FrodoCommand overrides it to
1090
+ * record the violation instead, which makes all 57 existing
1091
+ * `makeOptionMandatory()` call sites prompt-capable with zero syntax
1092
+ * change. Options carrying commander `choices()` are offered as a
1093
+ * dropdown instead of free typing.
1094
+ *
1095
+ * Everything here is gap-filling, and every gap-fill writes into the
1096
+ * command's own `processedArgs`/option values -- NOT into frodo-lib state
1097
+ * -- because `handleDefaultArgsAndOpts` (which copies positional args into
1098
+ * state) runs INSIDE the action body, after this pass; writing state here
1099
+ * would be overwritten by `undefined` a moment later. A fully-specified
1100
+ * invocation reaches the action untouched, and outside the prompt gate
1101
+ * (see PromptGate) the pass degrades to exactly the old error behavior.
1102
+ */
1103
+ var ResolveInteractiveInputs_exports = /* @__PURE__ */ require_rolldown_runtime.__exportAll({
1104
+ MISSING_MANDATORY_OPTION_CODE: () => MISSING_MANDATORY_OPTION_CODE,
1105
+ ONE_OF_UNSATISFIED_CODE: () => ONE_OF_UNSATISFIED_CODE,
1106
+ commandPreviewFor: () => commandPreviewFor,
1107
+ commandReadinessFor: () => commandReadinessFor,
1108
+ deferMissingMandatoryOption: () => deferMissingMandatoryOption,
1109
+ deferOneOfGroups: () => deferOneOfGroups,
1110
+ getOneOfGroups: () => getOneOfGroups,
1111
+ liveOptionPreviewFor: () => liveOptionPreviewFor,
1112
+ livePositionalPreviewFor: () => livePositionalPreviewFor,
1113
+ resolveInteractiveInputs: () => resolveInteractiveInputs,
1114
+ runInvocationEditorForCommand: () => runInvocationEditorForCommand,
1115
+ setPositionalValueForCommand: () => setPositionalValue
1116
+ });
1117
+ const { getConnectionProfilesPath, getConnectionProfileByHost } = require_ColorTheme.frodo.conn;
1118
+ const { probeDeploymentType } = require_ColorTheme.frodo.login;
1119
+ const { isValidUrl } = require_ColorTheme.frodo.utils;
1120
+ /**
1121
+ * A mandatory-option violation that commander's parse recorded instead of
1122
+ * throwing on. Lives here rather than on the command instance so the
1123
+ * deferred state survives the parse->hook handoff regardless of how
1124
+ * commander clones or nests commands.
1125
+ */
1126
+ const pendingMandatoryViolations = /* @__PURE__ */ new WeakMap();
1127
+ /**
1128
+ * Whether the connection level (host/username/password) resolved for this
1129
+ * command this session -- set by resolveConnectionArgs, whether the values
1130
+ * came from argv, env fallbacks, saved profiles, or the prompts. The
1131
+ * preview's readiness keys on THIS, not on the positionals: env/profile
1132
+ * resolution leaves the command object's positionals empty while the
1133
+ * connection is fully resolved. Lives beside pendingMandatoryViolations
1134
+ * for the same parse->hook handoff reasons.
1135
+ */
1136
+ const connectionReadiness = /* @__PURE__ */ new WeakMap();
1137
+ const pendingOneOfGroups = /* @__PURE__ */ new WeakMap();
1138
+ /**
1139
+ * Registers option-requiredness groups on a command for resolution-pass
1140
+ * evaluation. Called from FrodoCommand.requireOneOf/requireAllOf.
1141
+ */
1142
+ function deferOneOfGroups(command, groups) {
1143
+ pendingOneOfGroups.set(command, [...pendingOneOfGroups.get(command) ?? [], ...groups]);
1144
+ }
1145
+ /**
1146
+ * The option-requiredness groups registered on a command (empty when
1147
+ * none). Read by FrodoStubHelp to render the rule in help output -- the
1148
+ * help annotation and the resolver consume the same metadata.
1149
+ */
1150
+ function getOneOfGroups(command) {
1151
+ return pendingOneOfGroups.get(command) ?? [];
1152
+ }
1153
+ /**
1154
+ * Records a mandatory option that was missing at parse time, instead of
1155
+ * throwing. Called from FrodoCommand's `missingMandatoryOptionValue`
1156
+ * override. `optionLabel` is the option's full flags string (e.g.
1157
+ * `-s, --schema <schema>`), matching what commander's own error message
1158
+ * embeds.
1159
+ */
1160
+ function deferMissingMandatoryOption(command, optionLabel) {
1161
+ const pending = pendingMandatoryViolations.get(command) ?? [];
1162
+ pending.push(optionLabel);
1163
+ pendingMandatoryViolations.set(command, pending);
1164
+ }
1165
+ /**
1166
+ * The CommanderError code commander itself uses for this failure; the
1167
+ * re-throw preserves it so scripts can match on it.
1168
+ */
1169
+ const MISSING_MANDATORY_OPTION_CODE = "commander.missingMandatoryOptionValue";
1170
+ /**
1171
+ * Rebuilds commander's exact error message for a deferred violation (see
1172
+ * missingMandatoryOptionValue in commander's lib/command.js).
1173
+ */
1174
+ function missingMandatoryOptionMessage(optionLabel) {
1175
+ return `error: required option '${optionLabel}' not specified`;
1176
+ }
1177
+ /**
1178
+ * Runs the interactive resolution pass for `command` (the leaf command
1179
+ * about to execute).
1180
+ *
1181
+ * When prompting is disallowed, any deferred mandatory violation is
1182
+ * re-thrown with commander's own message/code (identical to pre-Phase-1
1183
+ * behavior -- commander would have thrown during parsing) and everything
1184
+ * else is a no-op. When the user backs out of a prompt (Escape/empty
1185
+ * Enter), any deferred violations are re-thrown the same way (matching
1186
+ * the old parse order, where the mandatory check ran first) and missing
1187
+ * connection args are left for the action's getTokens() to fail on
1188
+ * exactly as before.
1189
+ */
1190
+ async function resolveInteractiveInputs(command) {
1191
+ const violations = pendingMandatoryViolations.get(command) ?? [];
1192
+ if (!require_EscapableSelectPrompt.canPrompt()) {
1193
+ if (violations.length > 0) throwMissingMandatory(command, violations[0]);
1194
+ const unsatisfiedGroups = findUnsatisfiedOneOfGroups(command);
1195
+ if (unsatisfiedGroups.length > 0) throwOneOfUnsatisfied(command, unsatisfiedGroups[0]);
1196
+ return;
1197
+ }
1198
+ applyPersistedDefaults(command);
1199
+ require_RealmPickers.noteRealmProvenance();
1200
+ setDeploymentTypeForPreview(require_ColorTheme.state.getDeploymentType());
1201
+ const explicitlyInteractive = command.getOptionValue("prompt") === true && command.getOptionValueSource("prompt") === "cli" || guidedModeEnabled();
1202
+ connectionReadiness.set(command, false);
1203
+ const connectionResolved = await resolveConnectionArgs(command);
1204
+ connectionReadiness.set(command, connectionResolved);
1205
+ const mandatoryResolved = connectionResolved ? await resolveMandatoryOptions(command) : false;
1206
+ if (!connectionResolved || !mandatoryResolved) {
1207
+ if (violations.length > 0) throwMissingMandatory(command, violations[0]);
1208
+ return;
1209
+ }
1210
+ if (!await resolveOneOfGroups(command)) {
1211
+ const unsatisfied = findUnsatisfiedOneOfGroups(command);
1212
+ if (unsatisfied.length > 0) throwOneOfUnsatisfied(command, unsatisfied[0]);
1213
+ }
1214
+ if (explicitlyInteractive) await runInvocationEditor(command);
1215
+ require_AuthoringPrintState.armAuthoringPrint();
1216
+ require_AuthoringPrintState.setAuthoringPrintFlush(() => {
1217
+ if (require_EscapableSelectPrompt.promptsRendered() === 0 && !explicitlyInteractive) return;
1218
+ require_Console.printMessage(renderCommandPreview(command, {
1219
+ missingMandatoryOptionLabels: [],
1220
+ oneOfUnsatisfied: false
1221
+ }), "text");
1222
+ });
1223
+ }
1224
+ /**
1225
+ * Emits commander's exact mandatory-option failure: same message, same
1226
+ * CommanderError code, same stderr output and exit path as pre-Phase-1.
1227
+ */
1228
+ function throwMissingMandatory(command, optionLabel) {
1229
+ command.error(missingMandatoryOptionMessage(optionLabel), { code: MISSING_MANDATORY_OPTION_CODE });
1230
+ }
1231
+ /**
1232
+ * Commander-style failure for an unsatisfied one-of group. The message
1233
+ * mirrors commander's own error shape (message + help + exit 1), which is
1234
+ * also the UX the replaced `Unrecognized combination` else-branches had
1235
+ * (they printed, showed help, and exited 1).
1236
+ */
1237
+ function throwOneOfUnsatisfied(command, group) {
1238
+ const members = group.options.map((name) => {
1239
+ const option = command.options.find((candidate) => candidate.attributeName() === name);
1240
+ return option ? option.flags : `--${name}`;
1241
+ }).join(group.all ? " + " : " | ");
1242
+ command.error(`error: ${group.all ? `all of '${members}' are required` : `one of '${members}' is required`}${group.purpose ? ` to choose ${group.purpose}` : ""}`, { code: ONE_OF_UNSATISFIED_CODE });
1243
+ }
1244
+ /**
1245
+ * The CommanderError code for an unsatisfied one-of group. Namespaced like
1246
+ * commander's own codes (`commander.missingArgument`,
1247
+ * `commander.missingMandatoryOptionValue`) so scripts can match on it, but
1248
+ * distinct from any commander code since this rule is frodo-specific.
1249
+ */
1250
+ const ONE_OF_UNSATISFIED_CODE = "frodo.oneOfUnsatisfied";
1251
+ /**
1252
+ * The `→` routing for pickers inside the resolution pass: runs
1253
+ * `escapableSelect` with the command's discoverability hint attached,
1254
+ * and when the user presses → (resolve `RIGHT`), opens the invocation
1255
+ * editor, then re-prompts -- so a user who landed in a mandatory/one-of/
1256
+ * profile picker can discover and edit everything else from there (the
1257
+ * segment navigation described in docs/INTERACTIVE-COMMANDS.md). Without
1258
+ * a hint (nothing to configure) this is exactly `escapableSelect`: the
1259
+ * → key stays readline's business and the loop never engages.
1260
+ *
1261
+ * Re-prompting after the editor keeps the picker's own contract intact
1262
+ * (the caller sees a plain value or ESCAPE); the editor's ←/Esc re-enter
1263
+ * this loop, where the user can still decline with Escape.
1264
+ */
1265
+ async function selectWithEditorRouting(command, config) {
1266
+ const hint = require_EscapableSelectPrompt.editableOptionsHint(command);
1267
+ const preview = config.preview ?? commandPreviewFor(command);
1268
+ for (;;) {
1269
+ const choice = await require_EscapableSelectPrompt.escapableSelect({
1270
+ ...config,
1271
+ hint,
1272
+ preview
1273
+ });
1274
+ if (choice === require_EscapableSelectPrompt.EXIT_ALL) throw require_EscapableSelectPrompt.EXIT_ALL_SIGNAL;
1275
+ if (choice === require_EscapableSelectPrompt.ESCAPE) return require_EscapableSelectPrompt.ESCAPE;
1276
+ if (choice !== require_EscapableSelectPrompt.RIGHT) return choice;
1277
+ await runInvocationEditor(command);
1278
+ }
1279
+ }
1280
+ /**
1281
+ * The command preview footer for `command`'s prompts: the
1282
+ * command-so-far, red + cursive while mandatory input is missing, green/
1283
+ * white when validated and ready. Readiness derives from this module's
1284
+ * registries (deferred mandatory violations, one-of groups, connection
1285
+ * resolution); undefined when prompting is disallowed (the preview is an
1286
+ * interactive affordance only).
1287
+ */
1288
+ function commandPreviewFor(command) {
1289
+ if (!require_EscapableSelectPrompt.canPrompt()) return void 0;
1290
+ const readiness = commandReadinessFor(command);
1291
+ return readiness ? renderCommandPreview(command, readiness) : void 0;
1292
+ }
1293
+ /**
1294
+ * The resolver's current readiness input for `command` (the data behind
1295
+ * commandPreviewFor's render), for callers building LIVE preview
1296
+ * callbacks (livePositionalPreview/liveOptionPreview need the readiness
1297
+ * at every re-render, not a one-shot string). Undefined when prompting
1298
+ * is disallowed -- same gate as commandPreviewFor.
1299
+ */
1300
+ function commandReadinessFor(command) {
1301
+ if (!require_EscapableSelectPrompt.canPrompt()) return void 0;
1302
+ const missingMandatoryOptionLabels = (pendingMandatoryViolations.get(command) ?? []).filter((label) => {
1303
+ const option = command.options.find((candidate) => candidate.flags === label);
1304
+ if (!option) return true;
1305
+ const value = command.getOptionValue(option.attributeName());
1306
+ return value === void 0 || value === false || value === "";
1307
+ });
1308
+ const oneOfUnsatisfied = findUnsatisfiedOneOfGroups(command).length > 0;
1309
+ const connectionResolved = connectionReadiness.get(command);
1310
+ return {
1311
+ missingMandatoryOptionLabels,
1312
+ oneOfUnsatisfied,
1313
+ ...connectionResolved !== void 0 ? { connectionResolved } : {}
1314
+ };
1315
+ }
1316
+ /**
1317
+ * LIVE preview callbacks for `command`'s pickers (the footer shows what
1318
+ * the user is INFLUENCING -- arrowing through a list re-renders the
1319
+ * command with the highlighted value shadowed in). Built fresh per
1320
+ * picker open so the readiness snapshot (mandatory/one-of state at that
1321
+ * moment) is current; the callbacks stay valid across the picker's
1322
+ * renders. Undefined when prompting is disallowed -- same gate as
1323
+ * commandPreviewFor.
1324
+ */
1325
+ function livePositionalPreviewFor(command, positionalName) {
1326
+ const readiness = commandReadinessFor(command);
1327
+ if (!readiness) return void 0;
1328
+ return livePositionalPreview(command, positionalName, readiness);
1329
+ }
1330
+ function liveOptionPreviewFor(command, optionName, toValue) {
1331
+ const readiness = commandReadinessFor(command);
1332
+ if (!readiness) return void 0;
1333
+ return liveOptionPreview(command, optionName, readiness, toValue);
1334
+ }
1335
+ /**
1336
+ * Prompts for a value from a closed choice set. A ONE-item set auto-commits
1337
+ * (a single choice is no choice; commander would accept only that value
1338
+ * anyway -- the plan's single-option refinement); otherwise a searchable
1339
+ * dropdown. Returns ESCAPE only from the interactive picker, so a
1340
+ * single-choice set can never decline. With `optionName`, the picker's
1341
+ * footer is LIVE: arrowing through the values re-renders the command with
1342
+ * the highlighted value shadowed into that option.
1343
+ */
1344
+ async function selectFromChoices(command, message, choices, optionName) {
1345
+ if (choices.length === 1) {
1346
+ require_Console.verboseMessage(`Only one value available: ${choices[0]}`);
1347
+ return choices[0];
1348
+ }
1349
+ return selectWithEditorRouting(command, {
1350
+ message,
1351
+ ...optionName ? { preview: liveOptionPreviewFor(command, optionName) } : {},
1352
+ choices: choices.map((choiceValue) => ({
1353
+ name: choiceValue,
1354
+ value: choiceValue
1355
+ }))
1356
+ });
1357
+ }
1358
+ /**
1359
+ * Prompts for each deferred mandatory option violation. Options with a
1360
+ * closed value set (commander `choices()`) get a dropdown; everything
1361
+ * else free text. Returns false as soon as the user declines one (Escape
1362
+ * or empty Enter) -- the caller then restores the old error semantics.
1363
+ */
1364
+ async function resolveMandatoryOptions(command) {
1365
+ const violations = pendingMandatoryViolations.get(command) ?? [];
1366
+ for (const violation of violations) {
1367
+ const option = command.options.find((candidate) => {
1368
+ return candidate.flags === violation;
1369
+ });
1370
+ if (!option) throwMissingMandatory(command, violation);
1371
+ const attributeName = option.attributeName();
1372
+ if (require_EntityPickers.hasEntityPick(command, attributeName)) {
1373
+ require_Console.verboseMessage(`${option.flags} will be offered from the target system after login.`);
1374
+ continue;
1375
+ }
1376
+ let value;
1377
+ if (option.argChoices && option.argChoices.length > 0) {
1378
+ const choice = await selectFromChoices(command, `Choose a value for ${option.flags}:`, option.argChoices, option.attributeName());
1379
+ if (choice === require_EscapableSelectPrompt.ESCAPE) return false;
1380
+ value = choice;
1381
+ } else {
1382
+ const answer = await promptInput({ message: `Enter a value for ${option.flags}:` });
1383
+ if (!answer) return false;
1384
+ value = answer;
1385
+ }
1386
+ command.setOptionValueWithSource(attributeName, value, "cli");
1387
+ require_Console.verboseMessage(`Using ${value} for ${option.flags}.`);
1388
+ }
1389
+ return true;
1390
+ }
1391
+ /**
1392
+ * Whether an option-requiredness group is satisfied by the current option
1393
+ * values: every member for requireAllOf groups, at least one for
1394
+ * requireOneOf groups. Values are read via getOptionValue so injected
1395
+ * gap-fills count.
1396
+ */
1397
+ function groupSatisfied(command, group) {
1398
+ const defined = (name) => {
1399
+ const value = command.getOptionValue(name);
1400
+ return value !== void 0 && value !== false && value !== "";
1401
+ };
1402
+ return group.all ? group.options.every(defined) : group.options.some(defined);
1403
+ }
1404
+ /**
1405
+ * All registered option-requiredness groups the current invocation does
1406
+ * not satisfy.
1407
+ */
1408
+ function findUnsatisfiedOneOfGroups(command) {
1409
+ return (pendingOneOfGroups.get(command) ?? []).filter((group) => !groupSatisfied(command, group));
1410
+ }
1411
+ /**
1412
+ * Interactive resolution of unsatisfied one-of groups: the user picks WHICH
1413
+ * member to supply (dropdown over the group's members, defaulting to the
1414
+ * first), then a value step matched to the member's type -- dropdown for
1415
+ * commander `choices()`, free text otherwise (booleans resolve by the pick
1416
+ * itself). Mirrors resolveMandatoryOptions' decline semantics: Escape or
1417
+ * empty Enter returns false and the caller restores the error.
1418
+ */
1419
+ async function resolveOneOfGroups(command) {
1420
+ const unsatisfied = findUnsatisfiedOneOfGroups(command);
1421
+ for (const group of unsatisfied) {
1422
+ const memberOptions = group.options.map((name) => {
1423
+ const option = command.options.find((candidate) => candidate.attributeName() === name);
1424
+ return option ? {
1425
+ name,
1426
+ option
1427
+ } : void 0;
1428
+ }).filter((member) => member !== void 0);
1429
+ if (memberOptions.length === 0) continue;
1430
+ const subject = group.purpose ?? "what to act on";
1431
+ const readiness = commandReadinessFor(command);
1432
+ const picked = await selectWithEditorRouting(command, {
1433
+ message: `Choose ${subject}:`,
1434
+ ...readiness ? { preview: (highlighted) => {
1435
+ const member = memberOptions.find((candidate) => candidate.name === highlighted);
1436
+ if (!member) return renderCommandPreview(command, readiness);
1437
+ const isBoolean = !/<[^>]+>|\[[^\]]+\]/.test(member.option.flags);
1438
+ return liveOptionPreview(command, member.name, readiness, isBoolean ? () => "true" : () => void 0)(highlighted);
1439
+ } } : {},
1440
+ choices: memberOptions.map((member) => ({
1441
+ value: member.name,
1442
+ name: `${member.option.flags}${member.option.description ? ` -- ${member.option.description}` : ""}`
1443
+ }))
1444
+ });
1445
+ if (picked === require_EscapableSelectPrompt.ESCAPE) return false;
1446
+ const chosen = memberOptions.find((member) => member.name === picked);
1447
+ if (require_EntityPickers.hasEntityPick(command, chosen.name)) {
1448
+ require_Console.verboseMessage(`${chosen.option.flags} will be offered from the target system after login.`);
1449
+ continue;
1450
+ }
1451
+ if (chosen.option.argChoices && chosen.option.argChoices.length > 0) {
1452
+ const value = await selectFromChoices(command, `Choose a value for ${chosen.option.flags}:`, chosen.option.argChoices, chosen.name);
1453
+ if (value === require_EscapableSelectPrompt.ESCAPE) return false;
1454
+ command.setOptionValueWithSource(chosen.name, value, "cli");
1455
+ } else if (!/<[^>]+>|\[[^\]]+\]/.test(chosen.option.flags)) command.setOptionValueWithSource(chosen.name, true, "cli");
1456
+ else {
1457
+ const answer = await promptInput({ message: `Enter a value for ${chosen.option.flags}:` });
1458
+ if (!answer) return false;
1459
+ command.setOptionValueWithSource(chosen.name, answer, "cli");
1460
+ }
1461
+ require_Console.verboseMessage(`Using ${chosen.option.flags}.`);
1462
+ }
1463
+ return true;
1464
+ }
1465
+ /**
1466
+ * Whether the invocation carries an explicit interactive-auth mode
1467
+ * (--browser/--device). Read from the parsed option values, NOT from
1468
+ * frodo-lib state: `handleDefaultArgsAndOpts` sets authMode from these
1469
+ * same options inside the action body, i.e. after this pass runs.
1470
+ */
1471
+ function isInteractiveAuthMode(command) {
1472
+ return !!command.getOptionValue("browser") || !!command.getOptionValue("device");
1473
+ }
1474
+ /**
1475
+ * Reads the saved connection profiles file directly (no auth, no network)
1476
+ * to enumerate candidates for the host dropdown. Returns a sorted list;
1477
+ * empty when the file is missing or unreadable.
1478
+ */
1479
+ function listSavedProfiles() {
1480
+ const filename = getConnectionProfilesPath();
1481
+ let connectionsData;
1482
+ try {
1483
+ connectionsData = JSON.parse(fs.default.readFileSync(filename, "utf8"));
1484
+ } catch {
1485
+ return [];
1486
+ }
1487
+ return Object.keys(connectionsData).sort().map((host) => ({
1488
+ host,
1489
+ alias: connectionsData[host].alias
1490
+ }));
1491
+ }
1492
+ const ENTER_MANUALLY = Symbol("resolveConnectionArgs:enterManually");
1493
+ /**
1494
+ * Prompts for the missing connection-level positional arguments: host,
1495
+ * then username/password -- the latter only when no saved profile can
1496
+ * supply credentials for the resolved host. Returns false when the user
1497
+ * declines a prompt (Escape or empty Enter); the caller then restores the
1498
+ * pre-Phase-1 error semantics.
1499
+ *
1500
+ * Skipped per-argument when: the command doesn't declare the argument,
1501
+ * the value is already present (positional arg, or env var via frodo-lib
1502
+ * state's own env fallback), or --browser/--device makes the
1503
+ * username/password prompts redundant.
1504
+ */
1505
+ async function resolveConnectionArgs(command) {
1506
+ if (positionalIndex(command, "host") !== -1 && !positionalValue(command, "host") && !require_ColorTheme.state.getHost()) {
1507
+ const profiles = listSavedProfiles();
1508
+ let picked;
1509
+ if (profiles.length === 1) {
1510
+ picked = profiles[0].host;
1511
+ require_Console.verboseMessage(`No host given; using the only saved connection profile: ${picked}`);
1512
+ } else if (profiles.length > 1) {
1513
+ const readiness = commandReadinessFor(command);
1514
+ const choice = await selectWithEditorRouting(command, {
1515
+ message: "Choose a connection profile:",
1516
+ ...readiness ? { preview: livePositionalPreview(command, "host", readiness) } : {},
1517
+ search: ({ value, name }, query) => {
1518
+ const needle = query.toLowerCase();
1519
+ if (value === ENTER_MANUALLY) return name.length === 0;
1520
+ return value.toLowerCase().includes(needle) || (profiles.find((p) => p.host === value)?.alias ?? "").toLowerCase().includes(needle);
1521
+ },
1522
+ choices: [{
1523
+ value: ENTER_MANUALLY,
1524
+ name: "Enter a host manually...",
1525
+ description: "Type an AM base URL (or a profile substring)."
1526
+ }, ...profiles.map((profile) => ({
1527
+ value: profile.host,
1528
+ name: profile.alias ? `${profile.host} (${profile.alias})` : profile.host
1529
+ }))]
1530
+ });
1531
+ if (choice === require_EscapableSelectPrompt.ESCAPE) return false;
1532
+ if (choice === ENTER_MANUALLY) {
1533
+ const answer = await promptInput({ message: "AM base URL (or profile alias/substring):" });
1534
+ if (!answer) return false;
1535
+ picked = answer;
1536
+ } else picked = choice;
1537
+ } else {
1538
+ const answer = await promptInput({ message: "AM base URL:" });
1539
+ if (!answer) return false;
1540
+ picked = answer;
1541
+ }
1542
+ setPositionalValue(command, "host", picked);
1543
+ }
1544
+ {
1545
+ const host = positionalValue(command, "host") ?? require_ColorTheme.state.getHost();
1546
+ if (!require_ColorTheme.state.getDeploymentType() && host) try {
1547
+ setDeploymentTypeForPreview((await getConnectionProfileByHost(host)).deploymentType);
1548
+ } catch {
1549
+ if (require_EscapableSelectPrompt.canPrompt() && isValidUrl(host)) try {
1550
+ const probe = await probeDeploymentType(host);
1551
+ require_ColorTheme.state.setDeploymentType(probe.deploymentType);
1552
+ setDeploymentTypeForPreview(probe.deploymentType);
1553
+ } catch {}
1554
+ }
1555
+ }
1556
+ const usernameNeeded = positionalIndex(command, "username") !== -1 && !positionalValue(command, "username") && !require_ColorTheme.state.getUsername() && !isInteractiveAuthMode(command);
1557
+ const passwordNeeded = positionalIndex(command, "password") !== -1 && !positionalValue(command, "password") && !require_ColorTheme.state.getPassword() && !isInteractiveAuthMode(command);
1558
+ if (!usernameNeeded && !passwordNeeded) return true;
1559
+ const host = positionalValue(command, "host") ?? require_ColorTheme.state.getHost();
1560
+ if (!host) return true;
1561
+ let savedUsername;
1562
+ let profileNote;
1563
+ try {
1564
+ const profile = await getConnectionProfileByHost(host);
1565
+ if (profile.username && profile.password || profile.svcacctId || profile.amsterPrivateKey) return true;
1566
+ savedUsername = profile.username ?? void 0;
1567
+ profileNote = profile.alias ? `from profile ${profile.alias}` : "from profile";
1568
+ } catch {}
1569
+ const result = await connectionPage({
1570
+ message: "Connection:",
1571
+ preview: commandPreviewFor(command),
1572
+ rows: [
1573
+ {
1574
+ key: "host",
1575
+ label: "host",
1576
+ value: host,
1577
+ note: profileNote ?? void 0
1578
+ },
1579
+ {
1580
+ key: "username",
1581
+ label: "username",
1582
+ value: positionalValue(command, "username") ?? require_ColorTheme.state.getUsername(),
1583
+ note: require_ColorTheme.state.getUsername() ? "from FRODO_USERNAME" : profileNote ?? void 0
1584
+ },
1585
+ {
1586
+ key: "password",
1587
+ label: "password",
1588
+ value: positionalValue(command, "password") ?? require_ColorTheme.state.getPassword(),
1589
+ note: require_ColorTheme.state.getPassword() ? "from FRODO_PASSWORD" : profileNote ?? void 0
1590
+ }
1591
+ ],
1592
+ onHostChange: async (newHost) => {
1593
+ setPositionalValue(command, "host", newHost);
1594
+ let note;
1595
+ let savedUser;
1596
+ try {
1597
+ const profile = await getConnectionProfileByHost(newHost);
1598
+ note = profile.alias ? `from profile ${profile.alias}` : "from profile";
1599
+ savedUser = profile.username ?? void 0;
1600
+ } catch {
1601
+ note = void 0;
1602
+ }
1603
+ return [
1604
+ {
1605
+ key: "host",
1606
+ label: "host",
1607
+ value: newHost,
1608
+ note
1609
+ },
1610
+ {
1611
+ key: "username",
1612
+ label: "username",
1613
+ value: positionalValue(command, "username") ?? savedUser,
1614
+ note
1615
+ },
1616
+ {
1617
+ key: "password",
1618
+ label: "password",
1619
+ value: void 0,
1620
+ note
1621
+ }
1622
+ ];
1623
+ }
1624
+ });
1625
+ if (result === require_EscapableSelectPrompt.EXIT_ALL) throw require_EscapableSelectPrompt.EXIT_ALL_SIGNAL;
1626
+ if (result === PAGE_ESCAPE) {
1627
+ if (usernameNeeded) {
1628
+ const answer = await promptInput({
1629
+ message: "Username:",
1630
+ default: savedUsername
1631
+ });
1632
+ if (!answer) return false;
1633
+ setPositionalValue(command, "username", answer);
1634
+ }
1635
+ if (passwordNeeded) {
1636
+ const answer = await promptPassword({ message: "Password:" });
1637
+ if (!answer) return false;
1638
+ setPositionalValue(command, "password", answer);
1639
+ }
1640
+ return true;
1641
+ }
1642
+ if (result.username) setPositionalValue(command, "username", result.username);
1643
+ if (result.password) setPositionalValue(command, "password", result.password);
1644
+ return true;
1645
+ }
1646
+ /**
1647
+ * Public entry for utils/interactive picker modules (EntityPickers,
1648
+ * RealmPickers): their `→` key opens this editor, then re-prompts. Kept
1649
+ * as a named export because those modules import this file lazily (the
1650
+ * cycle is otherwise static: this file imports their registries).
1651
+ */
1652
+ async function runInvocationEditorForCommand(command) {
1653
+ await runInvocationEditor(command);
1654
+ }
1655
+ /**
1656
+ * Applies the command's persisted defaults (~/.frodo/
1657
+ * Defaults.json) to every option the user did NOT provide this
1658
+ * invocation (flag or env -- the precedence gate is
1659
+ * optionMissingUserValue: source undefined or 'default'). Values land
1660
+ * with source 'cli': persisted defaults are user-authored
1661
+ * configuration, and everything downstream (editor display, preview
1662
+ * footer, the eventual-command serializer) must treat them as real
1663
+ * input. Interactive only -- non-interactive runs keep byte-identical
1664
+ * behavior (built-in defaults).
1665
+ */
1666
+ function applyPersistedDefaults(command) {
1667
+ if (!require_EscapableSelectPrompt.canPrompt()) return;
1668
+ const persisted = require_DefaultsStore.applicableCommandDefaults(command);
1669
+ for (const option of command.options) {
1670
+ const value = persisted[option.attributeName()];
1671
+ if (value === void 0) continue;
1672
+ if (!require_DefaultsStore.optionMissingUserValue(command, option)) continue;
1673
+ const collectsArrays = Array.isArray(command.getOptionValue(option.attributeName())) || Array.isArray(option.defaultValue);
1674
+ if (Array.isArray(value) !== collectsArrays) continue;
1675
+ command.setOptionValueWithSource(option.attributeName(), value, "cli");
1676
+ require_Console.verboseMessage(`Using saved default ${option.flags} ${String(value)} (frodo settings defaults to change).`);
1677
+ }
1678
+ }
1679
+ async function runInvocationEditor(command) {
1680
+ const candidates = require_EscapableSelectPrompt.editableOptionalOptions(command);
1681
+ if (candidates.length === 0) {
1682
+ require_Console.verboseMessage("No optional options left to edit.");
1683
+ return;
1684
+ }
1685
+ const preselected = candidates.filter((option) => command.getOptionValueSource(option.attributeName()) === "cli").map((option) => option.attributeName());
1686
+ const runValueStep = async (attributeName) => {
1687
+ const option = command.options.find((candidate) => candidate.attributeName() === attributeName);
1688
+ if (!option) return void 0;
1689
+ const current = command.getOptionValue(attributeName);
1690
+ const currentText = current === void 0 || current === false ? void 0 : String(current);
1691
+ if (option.argChoices && option.argChoices.length > 0) {
1692
+ const value = await require_EscapableSelectPrompt.escapableSelect({
1693
+ message: `Choose a value for ${option.flags}:`,
1694
+ preview: liveOptionPreviewFor(command, attributeName),
1695
+ choices: option.argChoices.map((choiceValue) => ({
1696
+ name: choiceValue,
1697
+ value: choiceValue
1698
+ })),
1699
+ default: currentText
1700
+ });
1701
+ if (value === require_EscapableSelectPrompt.EXIT_ALL) return require_EscapableSelectPrompt.EXIT_ALL;
1702
+ if (value === require_EscapableSelectPrompt.ESCAPE || value === require_EscapableSelectPrompt.RIGHT) return void 0;
1703
+ command.setOptionValueWithSource(attributeName, value, "cli");
1704
+ return value;
1705
+ }
1706
+ if (!/<[^>]+>|\[[^\]]+\]/.test(option.flags)) {
1707
+ command.setOptionValueWithSource(attributeName, true, "cli");
1708
+ return true;
1709
+ }
1710
+ const answer = await promptInput({
1711
+ message: `Enter a value for ${option.flags}:`,
1712
+ default: currentText
1713
+ });
1714
+ if (!answer) return void 0;
1715
+ command.setOptionValueWithSource(attributeName, answer, "cli");
1716
+ return answer;
1717
+ };
1718
+ const committed = {};
1719
+ const picked = await escapableMultiSelect({
1720
+ message: `Optional options for '${command.name()}' (space to select):`,
1721
+ defaultValues: preselected,
1722
+ preview: (() => {
1723
+ const readiness = commandReadinessFor(command);
1724
+ if (!readiness) return void 0;
1725
+ return liveMultiOptionPreview(command, readiness);
1726
+ })(),
1727
+ needsValue: (attributeName) => {
1728
+ const option = command.options.find((candidate) => candidate.attributeName() === attributeName);
1729
+ return !!option && /<[^>]+>|\[[^\]]+\]/.test(option.flags);
1730
+ },
1731
+ choicesFor: (attributeName) => {
1732
+ const option = command.options.find((candidate) => candidate.attributeName() === attributeName);
1733
+ return option?.argChoices && option.argChoices.length > 0 ? option.argChoices.map(String) : void 0;
1734
+ },
1735
+ currentValueFor: (attributeName) => {
1736
+ if (!command.options.find((candidate) => candidate.attributeName() === attributeName)) return void 0;
1737
+ const current = command.getOptionValue(attributeName);
1738
+ if (current === void 0 || current === false || Array.isArray(current)) return void 0;
1739
+ return String(current);
1740
+ },
1741
+ onValue: (attributeName, value) => {
1742
+ const option = command.options.find((candidate) => candidate.attributeName() === attributeName);
1743
+ if (!option) return;
1744
+ if (Array.isArray(option.defaultValue)) {
1745
+ const existing = command.getOptionValue(attributeName);
1746
+ command.setOptionValueWithSource(attributeName, [...Array.isArray(existing) ? existing : [], value], "cli");
1747
+ } else command.setOptionValueWithSource(attributeName, value, "cli");
1748
+ committed[attributeName] = command.getOptionValue(attributeName);
1749
+ require_Console.verboseMessage(`Using ${option.flags} ${value}.`);
1750
+ },
1751
+ groups: require_EscapableSelectPrompt.editableOptionGroups(candidates),
1752
+ choices: require_EscapableSelectPrompt.sortEditableOptions(candidates).map((option) => {
1753
+ const current = command.getOptionValue(option.attributeName());
1754
+ const sourced = current === void 0 || current === false ? void 0 : command.getOptionValueSource(option.attributeName()) === "default" ? ` (default: ${current})` : ` (current: ${current})`;
1755
+ return {
1756
+ value: option.attributeName(),
1757
+ name: option.flags,
1758
+ group: require_EscapableSelectPrompt.editableOptionGroupOf(option),
1759
+ description: option.description ? `${option.description}${sourced ?? ""}` : sourced?.trim()
1760
+ };
1761
+ })
1762
+ });
1763
+ if (picked === require_EscapableSelectPrompt.EXIT_ALL) throw require_EscapableSelectPrompt.EXIT_ALL_SIGNAL;
1764
+ if (picked === MULTISEL_ESCAPE) {
1765
+ require_Console.verboseMessage("Invocation editor dismissed; values unchanged.");
1766
+ return;
1767
+ }
1768
+ const savingDefaults = command.getOptionValue("saveDefaults") === true && command.getOptionValueSource("saveDefaults") === "cli";
1769
+ for (const attributeName of picked) {
1770
+ if (command.getOptionValueSource(attributeName) === "cli" && command.getOptionValue(attributeName) !== void 0) {
1771
+ const option = command.options.find((candidate) => candidate.attributeName() === attributeName);
1772
+ require_Console.verboseMessage(`Using ${option.flags}.`);
1773
+ continue;
1774
+ }
1775
+ const value = await runValueStep(attributeName);
1776
+ if (value === require_EscapableSelectPrompt.EXIT_ALL) throw require_EscapableSelectPrompt.EXIT_ALL_SIGNAL;
1777
+ if (value === void 0) continue;
1778
+ committed[attributeName] = value;
1779
+ const option = command.options.find((candidate) => candidate.attributeName() === attributeName);
1780
+ require_Console.verboseMessage(`Using ${option.flags}.`);
1781
+ }
1782
+ if (picked.length > 0) {
1783
+ const { replayEditorOptionStates } = await Promise.resolve().then(() => require("./FrodoCommand-gFM6WHXw.cjs")).then((n) => n.FrodoCommand_exports);
1784
+ replayEditorOptionStates(command);
1785
+ }
1786
+ if (savingDefaults && Object.keys(committed).length > 0) {
1787
+ const { saveCommandDefaults } = await Promise.resolve().then(() => require("./DefaultsStore-RlEkAWqT.cjs")).then((n) => n.DefaultsStore_exports);
1788
+ saveCommandDefaults(command, committed);
1789
+ require_Console.successMessage(`Saved ${Object.keys(committed).length} option${Object.keys(committed).length === 1 ? "" : "s"} as defaults for '${commandStorePath(command)}'.`);
1790
+ }
1791
+ }
1792
+ /** The `frodo x y z` path -- the store's key (DefaultsStore's own helper,
1793
+ * re-imported lazily beside its save call). */
1794
+ function commandStorePath(command) {
1795
+ const names = [];
1796
+ for (let cursor = command; cursor; cursor = cursor.parent) names.unshift(cursor.name());
1797
+ return names.join(" ");
1798
+ }
1799
+ //#endregion
1800
+ Object.defineProperty(exports, "ResolveInteractiveInputs_exports", {
1801
+ enumerable: true,
1802
+ get: function() {
1803
+ return ResolveInteractiveInputs_exports;
1804
+ }
1805
+ });
1806
+ Object.defineProperty(exports, "deferMissingMandatoryOption", {
1807
+ enumerable: true,
1808
+ get: function() {
1809
+ return deferMissingMandatoryOption;
1810
+ }
1811
+ });
1812
+ Object.defineProperty(exports, "deferOneOfGroups", {
1813
+ enumerable: true,
1814
+ get: function() {
1815
+ return deferOneOfGroups;
1816
+ }
1817
+ });
1818
+ Object.defineProperty(exports, "getOneOfGroups", {
1819
+ enumerable: true,
1820
+ get: function() {
1821
+ return getOneOfGroups;
1822
+ }
1823
+ });
1824
+ Object.defineProperty(exports, "readSettings", {
1825
+ enumerable: true,
1826
+ get: function() {
1827
+ return readSettings;
1828
+ }
1829
+ });
1830
+ Object.defineProperty(exports, "resolveInteractiveInputs", {
1831
+ enumerable: true,
1832
+ get: function() {
1833
+ return resolveInteractiveInputs;
1834
+ }
1835
+ });
1836
+ Object.defineProperty(exports, "setGuidedMode", {
1837
+ enumerable: true,
1838
+ get: function() {
1839
+ return setGuidedMode;
1840
+ }
1841
+ });
1842
+
1843
+ //# sourceMappingURL=ResolveInteractiveInputs-CQBVc_CT.cjs.map