@diafunc/cli 0.10.1 → 0.12.0

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.
@@ -1,10 +1,9 @@
1
1
  import {
2
2
  package_default
3
- } from "./chunk-4EDLP7DD.js";
3
+ } from "./chunk-A4VM56MK.js";
4
4
 
5
5
  // src/index.ts
6
- import { Command } from "commander";
7
- import chalk34 from "chalk";
6
+ import chalk37 from "chalk";
8
7
 
9
8
  // src/commands/auth/login.ts
10
9
  import chalk4 from "chalk";
@@ -108,8 +107,8 @@ var ApiError = class _ApiError extends Error {
108
107
  return withDetails;
109
108
  }
110
109
  };
111
- function looksLikeMarkup(text) {
112
- const head = text.trimStart().slice(0, 200).toLowerCase();
110
+ function looksLikeMarkup(text2) {
111
+ const head = text2.trimStart().slice(0, 200).toLowerCase();
113
112
  return head.startsWith("<") || head.includes("<html") || head.includes("<!doctype");
114
113
  }
115
114
  var NetworkError = class extends Error {
@@ -214,8 +213,8 @@ async function parseErrorBody(response) {
214
213
  const body = await response.json();
215
214
  return ApiError.fromBody(response.status, body);
216
215
  }
217
- const text = (await response.text()).trim();
218
- return new ApiError(response.status, text || response.statusText);
216
+ const text2 = (await response.text()).trim();
217
+ return new ApiError(response.status, text2 || response.statusText);
219
218
  } catch {
220
219
  return new ApiError(response.status, response.statusText);
221
220
  }
@@ -324,11 +323,11 @@ ${bodyPreview}`));
324
323
  return void 0;
325
324
  }
326
325
  const contentType = response.headers.get("content-type") ?? "";
327
- const text = await response.text();
326
+ const text2 = await response.text();
328
327
  if (contentType.includes("application/json")) {
329
- return text ? JSON.parse(text) : void 0;
328
+ return text2 ? JSON.parse(text2) : void 0;
330
329
  }
331
- return text;
330
+ return text2;
332
331
  },
333
332
  async requestRaw(opts) {
334
333
  const response = await doRequest(opts);
@@ -812,11 +811,16 @@ function empty(noun, options) {
812
811
  }
813
812
  console.log(chalk2.dim(`No ${noun}.`));
814
813
  }
814
+ function heading(text2) {
815
+ console.log();
816
+ console.log(chalk2.bold(text2));
817
+ }
815
818
 
816
819
  // src/util/errors.ts
817
820
  var EXIT_FAILURE = 1;
818
821
  var EXIT_USAGE = 2;
819
822
  var EXIT_AUTH = 3;
823
+ var EXIT_CANCELLED = 130;
820
824
  var CliError = class extends Error {
821
825
  exitCode;
822
826
  hint;
@@ -911,8 +915,8 @@ async function deviceCodeLogin(config, profile) {
911
915
  body: new URLSearchParams({ client_id: DEVICE_CLIENT_ID, scope: DEVICE_SCOPE }).toString()
912
916
  });
913
917
  if (!deviceResponse.ok) {
914
- const text = await deviceResponse.text();
915
- failure(`Failed to start device-code flow: ${text || deviceResponse.statusText}`);
918
+ const text2 = await deviceResponse.text();
919
+ failure(`Failed to start device-code flow: ${text2 || deviceResponse.statusText}`);
916
920
  process.exit(1);
917
921
  }
918
922
  const device = await deviceResponse.json();
@@ -1073,22 +1077,22 @@ function terminalWidth() {
1073
1077
  if (!columns || !Number.isFinite(columns)) return 80;
1074
1078
  return Math.max(40, columns - 1);
1075
1079
  }
1076
- function displayWidth(text) {
1077
- return stripAnsi(text).length;
1080
+ function displayWidth(text2) {
1081
+ return stripAnsi(text2).length;
1078
1082
  }
1079
1083
  var ANSI_PATTERN = new RegExp("\\u001B\\[[0-9;]*m", "g");
1080
- function stripAnsi(text) {
1081
- return text.replace(ANSI_PATTERN, "");
1084
+ function stripAnsi(text2) {
1085
+ return text2.replace(ANSI_PATTERN, "");
1082
1086
  }
1083
- function truncate(text, width) {
1084
- const plain = stripAnsi(text);
1085
- if (plain.length <= width) return text;
1087
+ function truncate(text2, width) {
1088
+ const plain = stripAnsi(text2);
1089
+ if (plain.length <= width) return text2;
1086
1090
  if (width <= 1) return plain.slice(0, Math.max(0, width));
1087
1091
  return plain.slice(0, width - 1) + "\u2026";
1088
1092
  }
1089
- function wrap(text, width) {
1093
+ function wrap(text2, width) {
1090
1094
  const out = [];
1091
- for (const paragraph of text.split("\n")) {
1095
+ for (const paragraph of text2.split("\n")) {
1092
1096
  if (paragraph.length <= width) {
1093
1097
  out.push(paragraph);
1094
1098
  continue;
@@ -1116,7 +1120,7 @@ function wrap(text, width) {
1116
1120
  import chalk5 from "chalk";
1117
1121
  var ABSENT = "\u2014";
1118
1122
  function renderValue(value, kind = "text", plain = false) {
1119
- const dim = (text) => plain ? text : chalk5.dim(text);
1123
+ const dim = (text2) => plain ? text2 : chalk5.dim(text2);
1120
1124
  if (value === null || value === void 0 || value === "") return dim(ABSENT);
1121
1125
  switch (kind) {
1122
1126
  case "id":
@@ -1139,8 +1143,8 @@ function renderValue(value, kind = "text", plain = false) {
1139
1143
  }
1140
1144
  }
1141
1145
  function renderNumber(value, plain) {
1142
- const text = typeof value === "number" && !plain ? formatNumber(value) : String(value);
1143
- return plain ? text : chalk5.cyan(text);
1146
+ const text2 = typeof value === "number" && !plain ? formatNumber(value) : String(value);
1147
+ return plain ? text2 : chalk5.cyan(text2);
1144
1148
  }
1145
1149
  function renderArray(value, plain, dim) {
1146
1150
  if (value.length === 0) return dim(ABSENT);
@@ -1356,9 +1360,9 @@ function budgetWidths(specs, cells) {
1356
1360
  }
1357
1361
  return widths;
1358
1362
  }
1359
- function pad(text, width) {
1360
- const deficit = width - displayWidth(text);
1361
- return deficit > 0 ? text + " ".repeat(deficit) : text;
1363
+ function pad(text2, width) {
1364
+ const deficit = width - displayWidth(text2);
1365
+ return deficit > 0 ? text2 + " ".repeat(deficit) : text2;
1362
1366
  }
1363
1367
  function forPipe(value, spec) {
1364
1368
  const rendered = stripAnsi(renderValue(value, spec.kind ?? inferKind(spec.key), true));
@@ -2946,15 +2950,15 @@ import chalk12 from "chalk";
2946
2950
  // src/util/references.ts
2947
2951
  function parseEntityReference(ref, overrides) {
2948
2952
  const config = loadConfig();
2949
- const defaultProject = overrides?.project ?? config.defaults.project;
2953
+ const defaultProject2 = overrides?.project ?? config.defaults.project;
2950
2954
  const defaultBranch = overrides?.branch ?? config.defaults.branch ?? "main";
2951
2955
  if (!ref.includes("/") && ref.includes(":")) {
2952
2956
  const [entityId, entityBranch] = ref.split(":");
2953
- if (!defaultProject) {
2957
+ if (!defaultProject2) {
2954
2958
  throw new Error("No default project configured. Set one with: diafunc config set defaults.project <id>");
2955
2959
  }
2956
2960
  return {
2957
- projectId: defaultProject,
2961
+ projectId: defaultProject2,
2958
2962
  projectBranch: defaultBranch,
2959
2963
  entityId,
2960
2964
  entityBranch: entityBranch || defaultBranch
@@ -2962,11 +2966,11 @@ function parseEntityReference(ref, overrides) {
2962
2966
  }
2963
2967
  const parts = ref.split("/");
2964
2968
  if (parts.length === 1) {
2965
- if (!defaultProject) {
2969
+ if (!defaultProject2) {
2966
2970
  throw new Error("No default project configured. Set one with: diafunc config set defaults.project <id>");
2967
2971
  }
2968
2972
  return {
2969
- projectId: defaultProject,
2973
+ projectId: defaultProject2,
2970
2974
  projectBranch: defaultBranch,
2971
2975
  entityId: parts[0],
2972
2976
  entityBranch: defaultBranch
@@ -3010,11 +3014,11 @@ function parseEntityReference(ref, overrides) {
3010
3014
  }
3011
3015
  function parseProjectReference(ref, overrides) {
3012
3016
  const config = loadConfig();
3013
- const defaultProject = overrides?.project ?? config.defaults.project;
3017
+ const defaultProject2 = overrides?.project ?? config.defaults.project;
3014
3018
  const defaultBranch = overrides?.branch ?? config.defaults.branch ?? "main";
3015
3019
  if (!ref.includes("/")) {
3016
3020
  return {
3017
- projectId: ref || defaultProject,
3021
+ projectId: ref || defaultProject2,
3018
3022
  projectBranch: defaultBranch
3019
3023
  };
3020
3024
  }
@@ -4061,8 +4065,8 @@ Examples:
4061
4065
  fs3.writeFileSync(options.out, buffer);
4062
4066
  success(`Content saved to ${options.out}`);
4063
4067
  } else {
4064
- const text = await response.text();
4065
- process.stdout.write(text);
4068
+ const text2 = await response.text();
4069
+ process.stdout.write(text2);
4066
4070
  }
4067
4071
  } catch (error) {
4068
4072
  handleError(error);
@@ -4262,8 +4266,8 @@ function registerEventCommands(program) {
4262
4266
  });
4263
4267
  event.command("create").description("Create one or more events (body from JSON file or stdin)").argument("[file]", "JSON file containing a BareEvent array; defaults to stdin").action(async (file) => {
4264
4268
  try {
4265
- const fs14 = await import("fs");
4266
- const body = file ? fs14.readFileSync(file, "utf-8") : await new Promise((resolve, reject) => {
4269
+ const fs15 = await import("fs");
4270
+ const body = file ? fs15.readFileSync(file, "utf-8") : await new Promise((resolve, reject) => {
4267
4271
  let data = "";
4268
4272
  process.stdin.setEncoding("utf-8");
4269
4273
  process.stdin.on("data", (chunk) => {
@@ -4394,12 +4398,12 @@ Examples:
4394
4398
  handleError(error);
4395
4399
  }
4396
4400
  });
4397
- branch.command("fork").description("Fork a project").argument("<projectId>", "Source project ID").argument("<forkProjectId>", "New forked project ID").option("--branch <branch>", "Source branch", "main").option("--name <name>", "Forked project name").option("--description <desc>", "Forked project description", "").action(async (projectId, forkProjectId, options) => {
4401
+ branch.command("fork").description("Fork a project (source branch: the global --branch, default main)").argument("<projectId>", "Source project ID").argument("<forkProjectId>", "New forked project ID").option("--name <name>", "Forked project name").option("--description <desc>", "Forked project description", "").action(async (projectId, forkProjectId, options, cmd) => {
4398
4402
  try {
4399
4403
  const api = createApiClient();
4400
4404
  await api.storage.fork({
4401
4405
  projectId,
4402
- projectBranch: options.branch,
4406
+ projectBranch: getOverrides5(cmd).branch ?? "main",
4403
4407
  forkProjectId,
4404
4408
  forkProjectName: options.name ?? forkProjectId,
4405
4409
  forkProjectDescription: options.description
@@ -5714,16 +5718,16 @@ var MarkdownRenderer = class {
5714
5718
  if (this.inFence) {
5715
5719
  return [chalk18.cyan(` ${line}`)];
5716
5720
  }
5717
- const heading = line.match(/^(#{1,6})\s+(.*)$/);
5718
- if (heading) {
5719
- const text = inline(heading[2]);
5720
- return ["", heading[1].length <= 2 ? chalk18.bold.underline(text) : chalk18.bold(text)];
5721
+ const heading2 = line.match(/^(#{1,6})\s+(.*)$/);
5722
+ if (heading2) {
5723
+ const text2 = inline(heading2[2]);
5724
+ return ["", heading2[1].length <= 2 ? chalk18.bold.underline(text2) : chalk18.bold(text2)];
5721
5725
  }
5722
5726
  if (/^\s*([-*_])\1{2,}\s*$/.test(line)) {
5723
5727
  return [chalk18.dim("\u2500".repeat(Math.min(this.width, 60)))];
5724
5728
  }
5725
- const quote = line.match(/^\s*>\s?(.*)$/);
5726
- if (quote) return [chalk18.dim(` \u2502 ${inline(quote[1])}`)];
5729
+ const quote2 = line.match(/^\s*>\s?(.*)$/);
5730
+ if (quote2) return [chalk18.dim(` \u2502 ${inline(quote2[1])}`)];
5727
5731
  const bullet = line.match(/^(\s*)[-*+]\s+(.*)$/);
5728
5732
  if (bullet) {
5729
5733
  return wrapWithIndent(
@@ -5749,12 +5753,12 @@ function renderMarkdown(source, width = terminalWidth()) {
5749
5753
  const renderer = new MarkdownRenderer(width);
5750
5754
  return [...renderer.push(source), ...renderer.flush()].join("\n");
5751
5755
  }
5752
- function wrapWithIndent(text, indent, width) {
5753
- return wrap(text, width).map((l, i) => i === 0 ? l : " ".repeat(indent) + l);
5756
+ function wrapWithIndent(text2, indent, width) {
5757
+ return wrap(text2, width).map((l, i) => i === 0 ? l : " ".repeat(indent) + l);
5754
5758
  }
5755
- function inline(text) {
5759
+ function inline(text2) {
5756
5760
  const codeSpans = [];
5757
- let working = text.replace(/`([^`]+)`/g, (_m, code) => {
5761
+ let working = text2.replace(/`([^`]+)`/g, (_m, code) => {
5758
5762
  codeSpans.push(code);
5759
5763
  return `${CODE_OPEN}${codeSpans.length - 1}${CODE_CLOSE}`;
5760
5764
  });
@@ -5851,7 +5855,7 @@ var HELP = [
5851
5855
  ];
5852
5856
  async function runChatRepl(options) {
5853
5857
  const { input: promptInput } = await import("@inquirer/prompts");
5854
- const { getUpdateNotice } = await import("./update-check-XRMWJ753.js");
5858
+ const { getUpdateNotice } = await import("./update-check-SNH7P32S.js");
5855
5859
  let sessionId = options.session;
5856
5860
  let lastReportedSession;
5857
5861
  console.log(chalk19.bold("Diafunc chat") + chalk19.dim(" \xB7 /help for commands, /quit to exit"));
@@ -5937,6 +5941,10 @@ async function runChatRepl(options) {
5937
5941
  }
5938
5942
  }
5939
5943
  }
5944
+ function chatContext(cmd) {
5945
+ const globals = cmd.optsWithGlobals();
5946
+ return { project: globals.project, branch: globals.branch ?? "main" };
5947
+ }
5940
5948
  function registerChatCommands(program) {
5941
5949
  const chat = program.command("chat").description("Ask the Diafunc assistant").addHelpText("after", `
5942
5950
  Examples:
@@ -5944,22 +5952,24 @@ Examples:
5944
5952
  $ diafunc chat --project <id> with a project in context
5945
5953
  $ diafunc chat send "how do I add a table?" one question, one answer
5946
5954
  `);
5947
- chat.option("--session <id>", "Continue an existing session").option("--project <id>", "Project context").option("--branch <branch>", "Project branch", "main").action(async (options) => {
5955
+ chat.command("repl", { isDefault: true }).description("Interactive chat session (the default: `diafunc chat`)").option("--session <id>", "Continue an existing session").action(async (options, cmd) => {
5948
5956
  try {
5949
- await runChatRepl(options);
5957
+ const context = chatContext(cmd);
5958
+ await runChatRepl({ session: options.session, project: context.project, branch: context.branch });
5950
5959
  } catch (error) {
5951
5960
  handleError(error);
5952
5961
  }
5953
5962
  });
5954
- chat.command("send").description("Send a chat message (blocking)").argument("<message>", "Message to send").option("--project <id>", "Project context").option("--branch <branch>", "Project branch", "main").option("--session <id>", "Session ID to continue").action(async (message, options, cmd) => {
5963
+ chat.command("send").description("Send a chat message (blocking). Project context: the global --project and --branch").argument("<message>", "Message to send").option("--session <id>", "Session ID to continue").action(async (message, options, cmd) => {
5955
5964
  try {
5956
5965
  const outputFormat = getOutputFormat12(cmd);
5957
5966
  const api = createApiClient();
5967
+ const context = chatContext(cmd);
5958
5968
  const response = await api.language.chat({
5959
5969
  message,
5960
5970
  sessionId: options.session,
5961
- projectId: options.project,
5962
- projectBranch: options.branch
5971
+ projectId: context.project,
5972
+ projectBranch: context.branch
5963
5973
  });
5964
5974
  if (outputFormat === "human") {
5965
5975
  console.log(renderMarkdown(response.content));
@@ -5974,15 +5984,16 @@ Examples:
5974
5984
  handleError(error);
5975
5985
  }
5976
5986
  });
5977
- chat.command("stream").description("Send a chat message (streaming)").argument("<message>", "Message to send").option("--project <id>", "Project context").option("--branch <branch>", "Project branch", "main").option("--session <id>", "Session ID to continue").action(async (message, options, cmd) => {
5987
+ chat.command("stream").description("Send a chat message (streaming). Project context: the global --project and --branch").argument("<message>", "Message to send").option("--session <id>", "Session ID to continue").action(async (message, options, cmd) => {
5978
5988
  try {
5979
5989
  const outputFormat = getOutputFormat12(cmd);
5980
5990
  const api = createApiClient();
5991
+ const context = chatContext(cmd);
5981
5992
  const response = await api.language.chatStream({
5982
5993
  message,
5983
5994
  sessionId: options.session,
5984
- projectId: options.project,
5985
- projectBranch: options.branch
5995
+ projectId: context.project,
5996
+ projectBranch: context.branch
5986
5997
  });
5987
5998
  if (outputFormat === "json") {
5988
5999
  const events = [];
@@ -6135,7 +6146,7 @@ function getOutputFormat13(cmd) {
6135
6146
  return globalOpts.output ?? config.defaults.output ?? "human";
6136
6147
  }
6137
6148
  function registerSearchCommands(program) {
6138
- program.command("search").description("Search across every project you can see").argument("<query>", "Search query").option("--project <id>", "Limit the search to one project").option("--branch <branch>", "Project branch, when --project is given").option("--type <contentType>", "Limit to one content type, e.g. project, notebook, table, function").option("--limit <n>", "Maximum results", "20").addHelpText("after", `
6149
+ program.command("search").description("Search across every project you can see").argument("<query>", "Search query").option("--type <contentType>", "Limit to one content type, e.g. project, notebook, table, function").option("--limit <n>", "Maximum results", "20").addHelpText("after", `
6139
6150
  Examples:
6140
6151
  $ diafunc search "housing" everything matching, across projects
6141
6152
  $ diafunc search "housing" --type project only projects
@@ -6147,14 +6158,14 @@ Examples:
6147
6158
  const overrides = cmd.optsWithGlobals();
6148
6159
  const config = loadConfig();
6149
6160
  const api = createApiClient();
6150
- const projectId = options.project ?? overrides.project ?? config.defaults.project ?? null;
6161
+ const projectId = overrides.project ?? config.defaults.project ?? null;
6151
6162
  const limit = Number.parseInt(options.limit, 10);
6152
6163
  const page = await api.index.searchPage({
6153
6164
  query,
6154
6165
  limit: Number.isFinite(limit) && limit > 0 ? limit : 20,
6155
6166
  contentType: options.type ?? null,
6156
6167
  projectId,
6157
- projectBranch: projectId ? options.branch ?? overrides.branch ?? config.defaults.branch ?? "main" : null
6168
+ projectBranch: projectId ? overrides.branch ?? config.defaults.branch ?? "main" : null
6158
6169
  });
6159
6170
  const items = dedupe(page.items);
6160
6171
  if (items.length === 0) {
@@ -6212,19 +6223,19 @@ function renderResults(items) {
6212
6223
  }
6213
6224
  var HIGHLIGHT_OPEN = /<mark>/g;
6214
6225
  var HIGHLIGHT_CLOSE = /<\/mark>/g;
6215
- function highlight(text) {
6216
- const parts = text.split(HIGHLIGHT_OPEN);
6226
+ function highlight(text2) {
6227
+ const parts = text2.split(HIGHLIGHT_OPEN);
6217
6228
  return parts.map((part, i) => {
6218
6229
  if (i === 0) return chalk20.dim(part);
6219
6230
  const [marked, ...rest] = part.split(HIGHLIGHT_CLOSE);
6220
6231
  return chalk20.bold.cyan(marked) + chalk20.dim(rest.join(""));
6221
6232
  }).join("");
6222
6233
  }
6223
- function stripHighlight(text) {
6224
- return text.replace(HIGHLIGHT_OPEN, "").replace(HIGHLIGHT_CLOSE, "");
6234
+ function stripHighlight(text2) {
6235
+ return text2.replace(HIGHLIGHT_OPEN, "").replace(HIGHLIGHT_CLOSE, "");
6225
6236
  }
6226
- function collapse(text) {
6227
- const flat = text.replace(/\s+/g, " ").trim();
6237
+ function collapse(text2) {
6238
+ const flat = text2.replace(/\s+/g, " ").trim();
6228
6239
  return flat.length > 160 ? `${flat.slice(0, 159)}\u2026` : flat;
6229
6240
  }
6230
6241
 
@@ -6359,12 +6370,13 @@ function registerAdminCommands(program) {
6359
6370
  handleError(error);
6360
6371
  }
6361
6372
  });
6362
- admin.command("index-rebuild").description("Rebuild all search indexes (or a specific project with --project)").option("--project <id>", "Project ID to rebuild").action(async (options) => {
6373
+ admin.command("index-rebuild").description("Rebuild all search indexes (or a specific project with the global --project)").action(async (_options, cmd) => {
6363
6374
  try {
6364
6375
  const api = createApiClient();
6365
- if (options.project) {
6366
- await api.index.rebuildProject(options.project);
6367
- success(`Index rebuild initiated for project "${options.project}".`);
6376
+ const { project } = cmd.optsWithGlobals();
6377
+ if (project) {
6378
+ await api.index.rebuildProject(project);
6379
+ success(`Index rebuild initiated for project "${project}".`);
6368
6380
  } else {
6369
6381
  await api.index.rebuildAll();
6370
6382
  success("Index rebuild initiated for all projects.");
@@ -6614,7 +6626,7 @@ Examples:
6614
6626
  }
6615
6627
 
6616
6628
  // src/commands/analyze/index.ts
6617
- import chalk25 from "chalk";
6629
+ import chalk26 from "chalk";
6618
6630
  import * as fs8 from "fs";
6619
6631
  import * as path7 from "path";
6620
6632
  import { spawn as spawn2 } from "child_process";
@@ -6705,8 +6717,293 @@ function estimateRemaining(fraction, elapsedMs) {
6705
6717
  return remaining > 0 ? remaining : null;
6706
6718
  }
6707
6719
 
6720
+ // src/commands/analyze/wizard.ts
6721
+ import chalk25 from "chalk";
6722
+ var DEPTH_PRESETS = [
6723
+ { name: "Express", hours: "1", budget: "500" },
6724
+ { name: "Quick", hours: "2", budget: "2000" },
6725
+ { name: "Standard", hours: "4", budget: "10000" },
6726
+ { name: "Thorough", hours: "8", budget: "40000" },
6727
+ { name: "Deep", hours: "24", budget: "150000" }
6728
+ ];
6729
+ var DEFAULT_HOURS = "4";
6730
+ var DEFAULT_BUDGET = "10000";
6731
+ async function promptCreationFields(prompter, supplied, fallbackName) {
6732
+ const name = supplied.name ?? await prompter.input({
6733
+ message: "Analysis name",
6734
+ default: fallbackName,
6735
+ validate: (value) => value.trim().length > 0 || "A name is required."
6736
+ });
6737
+ const description = supplied.description ?? await prompter.input({
6738
+ message: "Description (optional)"
6739
+ });
6740
+ const visibility = supplied.visibility ?? await prompter.select({
6741
+ message: "Visibility",
6742
+ default: "PRIVATE",
6743
+ choices: [
6744
+ { name: "Private", value: "PRIVATE", description: "Only you can open the analysis." },
6745
+ { name: "Public", value: "PUBLIC", description: "Anyone with the link can read the notebook." }
6746
+ ]
6747
+ });
6748
+ return { name: name.trim(), description: description.trim() || null, visibility };
6749
+ }
6750
+ function matchDepthPreset(hours, budget) {
6751
+ if (!hours || !budget) return null;
6752
+ return DEPTH_PRESETS.find((p) => p.hours === hours && p.budget === budget) ?? null;
6753
+ }
6754
+ function defaultTargets(columns) {
6755
+ const named = columns.filter((c) => c.name && c.name.length > 0);
6756
+ return named.length > 0 ? [named[named.length - 1].name] : [];
6757
+ }
6758
+ function positiveNumber(label) {
6759
+ return (value) => {
6760
+ const parsed = Number(value.trim());
6761
+ if (!Number.isFinite(parsed) || parsed <= 0) return `${label} must be a positive number.`;
6762
+ return true;
6763
+ };
6764
+ }
6765
+ async function promptRunFields(prompter, options) {
6766
+ const { columns } = options;
6767
+ const named = columns.filter((c) => c.name && c.name.length > 0);
6768
+ let supplied = { ...options.supplied };
6769
+ const nothingSupplied = supplied.targets === void 0 && supplied.segment === void 0 && supplied.questions === void 0 && supplied.hours === void 0 && supplied.budget === void 0;
6770
+ if (options.presets.length > 0 && nothingSupplied) {
6771
+ const preset = await prompter.select({
6772
+ message: "Start from a saved preset?",
6773
+ default: null,
6774
+ choices: [
6775
+ { name: "No, set it up now", value: null },
6776
+ ...options.presets.map((p) => ({
6777
+ name: p.name,
6778
+ value: p,
6779
+ description: describePreset(p)
6780
+ }))
6781
+ ]
6782
+ });
6783
+ if (preset) {
6784
+ supplied = {
6785
+ targets: preset.targetKeys.length > 0 ? preset.targetKeys : void 0,
6786
+ questions: preset.questions.length > 0 ? preset.questions : void 0,
6787
+ segment: preset.segmentKey ?? void 0,
6788
+ hours: preset.time || void 0,
6789
+ budget: preset.budget || void 0
6790
+ };
6791
+ }
6792
+ }
6793
+ let targets = supplied.targets ?? null;
6794
+ if (targets === null || targets.length === 0) {
6795
+ if (named.length > 0) {
6796
+ const preselected = new Set(defaultTargets(named));
6797
+ targets = await prompter.checkbox({
6798
+ message: "Target variables: what should the analysis predict?",
6799
+ choices: named.map((c) => ({
6800
+ name: c.valueType ? `${c.name} ${chalk25.dim(`(${c.valueType})`)}` : c.name,
6801
+ value: c.name,
6802
+ checked: preselected.has(c.name)
6803
+ })),
6804
+ validate: (chosen) => chosen.length > 0 || "Pick at least one target column."
6805
+ });
6806
+ } else {
6807
+ const typed2 = await prompter.input({
6808
+ message: "Target column names (comma-separated)",
6809
+ validate: (value) => splitCsv(value).length > 0 || "Name at least one target column."
6810
+ });
6811
+ targets = splitCsv(typed2);
6812
+ }
6813
+ }
6814
+ const remaining = named.filter((c) => !targets.includes(c.name));
6815
+ let segment = supplied.segment ?? null;
6816
+ if (supplied.segment === void 0 && remaining.length > 0) {
6817
+ segment = await prompter.select({
6818
+ message: "Segment the analysis by a column? (optional)",
6819
+ default: null,
6820
+ choices: [
6821
+ { name: "No segmentation", value: null },
6822
+ ...remaining.map((c) => ({
6823
+ name: c.valueType ? `${c.name} ${chalk25.dim(`(${c.valueType})`)}` : c.name,
6824
+ value: c.name
6825
+ }))
6826
+ ]
6827
+ });
6828
+ }
6829
+ let questions = supplied.questions ?? null;
6830
+ if (supplied.questions === void 0) {
6831
+ const wanted = await prompter.confirm({
6832
+ message: "Add questions for the analysis to answer? (optional)",
6833
+ default: false
6834
+ });
6835
+ if (wanted) {
6836
+ const collected = [];
6837
+ for (; ; ) {
6838
+ const question2 = await prompter.input({
6839
+ message: collected.length === 0 ? "Question" : "Another question (blank to finish)"
6840
+ });
6841
+ const trimmed = question2.trim();
6842
+ if (trimmed.length === 0) break;
6843
+ collected.push(trimmed);
6844
+ }
6845
+ questions = collected.length > 0 ? collected : null;
6846
+ }
6847
+ }
6848
+ let hours = supplied.hours;
6849
+ let budget = supplied.budget;
6850
+ if (hours === void 0 && budget === void 0) {
6851
+ const chosen = await prompter.select({
6852
+ message: "Depth: how long may the search run, and what may it spend?",
6853
+ default: DEPTH_PRESETS.find((p) => p.name === "Standard") ?? null,
6854
+ choices: [
6855
+ ...DEPTH_PRESETS.map((p) => ({
6856
+ name: p.name,
6857
+ value: p,
6858
+ description: `${p.hours}h \xB7 ${p.budget} credits`
6859
+ })),
6860
+ { name: "Set your own", value: null }
6861
+ ]
6862
+ });
6863
+ if (chosen) {
6864
+ hours = chosen.hours;
6865
+ budget = chosen.budget;
6866
+ }
6867
+ }
6868
+ if (hours === void 0) {
6869
+ hours = await prompter.input({
6870
+ message: "Computation time in hours",
6871
+ default: DEFAULT_HOURS,
6872
+ validate: positiveNumber("Computation time")
6873
+ });
6874
+ }
6875
+ if (budget === void 0) {
6876
+ budget = await prompter.input({
6877
+ message: "Credit budget",
6878
+ default: DEFAULT_BUDGET,
6879
+ validate: positiveNumber("Credit budget")
6880
+ });
6881
+ }
6882
+ return {
6883
+ targets: targets ?? [],
6884
+ segment,
6885
+ questions,
6886
+ hours: hours.trim(),
6887
+ budget: budget.trim()
6888
+ };
6889
+ }
6890
+ function describePreset(preset) {
6891
+ const parts = [`${preset.time || DEFAULT_HOURS}h`, `${preset.budget || DEFAULT_BUDGET} credits`];
6892
+ if (preset.targetKeys.length > 0) parts.push(`targets: ${preset.targetKeys.join(", ")}`);
6893
+ if (preset.segmentKey) parts.push(`segmented by ${preset.segmentKey}`);
6894
+ return parts.join(" \xB7 ");
6895
+ }
6896
+ function summaryLines(creation, run) {
6897
+ const lines = [
6898
+ `Name: ${creation.name}`,
6899
+ `Visibility: ${creation.visibility === "PUBLIC" ? "Public" : "Private"}`,
6900
+ `Targets: ${run.targets.join(", ")}`
6901
+ ];
6902
+ if (run.segment) lines.push(`Segment: ${run.segment}`);
6903
+ if (run.questions && run.questions.length > 0) {
6904
+ lines.push(`Questions: ${run.questions.length}`);
6905
+ }
6906
+ const depth = matchDepthPreset(run.hours, run.budget);
6907
+ const named = depth ? `${depth.name}, ` : "";
6908
+ lines.push(`Depth: ${named}${run.hours}h \xB7 ${run.budget} credits`);
6909
+ return lines;
6910
+ }
6911
+ function splitCsv(value) {
6912
+ return value.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
6913
+ }
6914
+ function missingRunFields(recipe) {
6915
+ const missing = [];
6916
+ if (!recipe.hours || recipe.hours.trim().length === 0) missing.push("hours");
6917
+ if (!recipe.budget || recipe.budget.trim().length === 0) missing.push("budget");
6918
+ if (!recipe.targets || recipe.targets.length === 0) missing.push("targets");
6919
+ return missing;
6920
+ }
6921
+ function suppliedFromAnalysis(analysis) {
6922
+ return {
6923
+ targets: analysis.targets && analysis.targets.length > 0 ? analysis.targets : void 0,
6924
+ hours: analysis.hours?.trim() ? analysis.hours : void 0,
6925
+ budget: analysis.budget?.trim() ? analysis.budget : void 0,
6926
+ segment: analysis.segment ?? null,
6927
+ questions: analysis.questions ?? null
6928
+ };
6929
+ }
6930
+ var FIELD_COMMANDS = {
6931
+ hours: "hours <id> <hours>",
6932
+ budget: "budget <id> <credits>",
6933
+ targets: "targets <id> <csv>"
6934
+ };
6935
+ function explainMissingRunFields(analysisId, missing, reason2) {
6936
+ const commands = missing.map((f) => `'diafunc analyze ${FIELD_COMMANDS[f].replace("<id>", analysisId)}'`);
6937
+ const columns = missing.includes("targets") ? ` Column names: 'diafunc analyze columns ${analysisId}'.` : "";
6938
+ return {
6939
+ message: `Analysis ${analysisId} cannot run yet: it has no ${joinList(missing)}, and ${reason2}.`,
6940
+ suggestion: `Set ${missing.length === 1 ? "it" : "them"} with ${commands.join(", ")}, then rerun.${columns}`
6941
+ };
6942
+ }
6943
+ function joinList(items) {
6944
+ if (items.length <= 1) return items.join("");
6945
+ return `${items.slice(0, -1).join(", ")} or ${items[items.length - 1]}`;
6946
+ }
6947
+
6948
+ // src/prompting/prompter.ts
6949
+ var PromptCancelled = class extends Error {
6950
+ constructor() {
6951
+ super("Cancelled.");
6952
+ this.name = "PromptCancelled";
6953
+ }
6954
+ };
6955
+ function createInquirerPrompter() {
6956
+ const load = () => import("@inquirer/prompts");
6957
+ const guard = async (work) => {
6958
+ try {
6959
+ return await work();
6960
+ } catch (error) {
6961
+ if (error instanceof Error && error.name === "ExitPromptError") throw new PromptCancelled();
6962
+ throw error;
6963
+ }
6964
+ };
6965
+ return {
6966
+ async input(options) {
6967
+ const { input } = await load();
6968
+ return guard(() => input(options));
6969
+ },
6970
+ async select(options) {
6971
+ const { select } = await load();
6972
+ return guard(() => select(options));
6973
+ },
6974
+ async checkbox(options) {
6975
+ const { checkbox } = await load();
6976
+ return guard(() => checkbox(options));
6977
+ },
6978
+ async confirm(options) {
6979
+ const { confirm } = await load();
6980
+ return guard(() => confirm(options));
6981
+ },
6982
+ async search(options) {
6983
+ const { search } = await load();
6984
+ return guard(() => search({
6985
+ message: options.message,
6986
+ pageSize: 12,
6987
+ source: async (term) => options.source(term ?? "")
6988
+ }));
6989
+ }
6990
+ };
6991
+ }
6992
+ function canPrompt(outputFormat, noInteractive) {
6993
+ if (noInteractive) return false;
6994
+ if (outputFormat !== "human") return false;
6995
+ return Boolean(process.stdin.isTTY) && isInteractive();
6996
+ }
6997
+ function whyNoPrompt(outputFormat, noInteractive) {
6998
+ if (noInteractive) return "--no-interactive is set";
6999
+ if (outputFormat !== "human") return `--output ${outputFormat} does not prompt`;
7000
+ return "there is no terminal to ask";
7001
+ }
7002
+
6708
7003
  // src/commands/analyze/index.ts
6709
7004
  var POLL_INTERVAL_MS = 2e3;
7005
+ var COLUMN_READ_ATTEMPTS = 3;
7006
+ var COLUMN_READ_INTERVAL_MS = 1e3;
6710
7007
  function openUrl(url) {
6711
7008
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
6712
7009
  const args = process.platform === "win32" ? ["/c", "start", '""', url] : [url];
@@ -6717,6 +7014,9 @@ function getOutputFormat15(cmd) {
6717
7014
  const globalOpts = cmd.optsWithGlobals();
6718
7015
  return globalOpts.output ?? config.defaults.output ?? "human";
6719
7016
  }
7017
+ function noInteractiveFlag(cmd) {
7018
+ return cmd.optsWithGlobals().interactive === false;
7019
+ }
6720
7020
  function parseCsv(value) {
6721
7021
  if (value === void 0) return null;
6722
7022
  return value.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
@@ -6738,17 +7038,24 @@ function multipartFromFile(file) {
6738
7038
  formData.append("content", blob, path7.basename(file));
6739
7039
  return formData;
6740
7040
  }
7041
+ function reportCommandError(error) {
7042
+ if (error instanceof PromptCancelled) throw error;
7043
+ handleError(error);
7044
+ }
6741
7045
  async function runAnalysis(file, options, cmd) {
6742
7046
  if (!fs8.existsSync(file)) {
6743
7047
  failure(`File not found: ${file}`);
6744
- process.exit(1);
7048
+ process.exit(EXIT_FAILURE);
6745
7049
  }
7050
+ const outputFormat = getOutputFormat15(cmd);
7051
+ const noInteractive = noInteractiveFlag(cmd);
7052
+ const interactive = canPrompt(outputFormat, noInteractive);
7053
+ const api = createApiClient();
6746
7054
  if (options.preset) {
6747
- const api2 = createApiClient();
6748
- const opt = await api2.analysis.getPreset(options.preset);
7055
+ const opt = await api.analysis.getPreset(options.preset);
6749
7056
  if (!opt.preset) {
6750
7057
  failure(`Preset not found: ${options.preset}`);
6751
- process.exit(1);
7058
+ process.exit(EXIT_FAILURE);
6752
7059
  }
6753
7060
  const p = opt.preset;
6754
7061
  if (options.targets === void 0 && p.targetKeys.length > 0) options.targets = p.targetKeys.join(",");
@@ -6757,33 +7064,105 @@ async function runAnalysis(file, options, cmd) {
6757
7064
  if (options.hours === void 0) options.hours = p.time;
6758
7065
  if (options.budget === void 0) options.budget = p.budget;
6759
7066
  }
6760
- const hours = options.hours ?? "4";
6761
- const budget = options.budget ?? "400";
6762
- const api = createApiClient();
6763
- const visibility = parseVisibility(options.visibility);
6764
- const name = options.name ?? path7.basename(file, path7.extname(file));
7067
+ const flagTargets = parseCsv(options.targets);
7068
+ if (!interactive && (flagTargets === null || flagTargets.length === 0)) {
7069
+ usageError(
7070
+ `Target columns are required, and ${whyNoPrompt(outputFormat, noInteractive)}.`,
7071
+ `Pass --targets <csv> or --preset <id>. The names are the column headers of ${path7.basename(file)}.`
7072
+ );
7073
+ }
7074
+ const prompter = createInquirerPrompter();
7075
+ const fallbackName = path7.basename(file, path7.extname(file));
7076
+ const creation = interactive ? await promptCreationFields(prompter, {
7077
+ name: options.name,
7078
+ description: options.description,
7079
+ visibility: options.visibility === void 0 ? void 0 : parseVisibility(options.visibility)
7080
+ }, fallbackName) : {
7081
+ name: options.name ?? fallbackName,
7082
+ description: options.description?.trim() || null,
7083
+ visibility: options.visibility === void 0 ? "PRIVATE" : parseVisibility(options.visibility)
7084
+ };
6765
7085
  const request = {
6766
- name,
6767
- description: options.description || null,
6768
- visibility,
7086
+ name: creation.name,
7087
+ description: creation.description,
7088
+ visibility: creation.visibility,
6769
7089
  introduction: options.introduction ?? null,
6770
- hours,
6771
- budget,
6772
- targets: parseCsv(options.targets),
7090
+ hours: options.hours ?? DEFAULT_HOURS,
7091
+ budget: options.budget ?? DEFAULT_BUDGET,
7092
+ targets: flagTargets,
6773
7093
  questions: parseCsv(options.questions),
6774
7094
  segment: options.segment ?? null
6775
7095
  };
6776
- const created = await withStatus(`Creating analysis "${name}"`, () => api.analysis.create(request));
6777
- console.log(chalk25.dim(` analysisId: ${created.analysisId}`));
7096
+ const created = await withStatus(`Creating analysis "${creation.name}"`, () => api.analysis.create(request));
7097
+ detail(`analysisId: ${created.analysisId}`);
6778
7098
  await withStatus(
6779
7099
  `Uploading ${path7.basename(file)}`,
6780
7100
  () => api.analysis.uploadDataMultipart(created.analysisId, multipartFromFile(file))
6781
7101
  );
7102
+ if (interactive) {
7103
+ const configured = await configureInteractively(api, prompter, created.analysisId, request, {
7104
+ targets: options.targets === void 0 ? void 0 : parseCsv(options.targets),
7105
+ segment: options.segment,
7106
+ questions: options.questions === void 0 ? void 0 : parseCsv(options.questions),
7107
+ hours: options.hours,
7108
+ budget: options.budget
7109
+ });
7110
+ if (!configured) return;
7111
+ }
6782
7112
  const run = await withStatus("Queuing analysis run", () => api.analysis.runAnalysis(created.analysisId));
6783
- console.log(chalk25.dim(` runId: ${run.runId}`));
7113
+ detail(`runId: ${run.runId}`);
6784
7114
  console.log();
6785
7115
  await monitorRun(api, created.analysisId, run.runId, cmd);
6786
7116
  }
7117
+ async function configureInteractively(api, prompter, analysisId, recipe, supplied) {
7118
+ const columns = await readColumns(api, analysisId);
7119
+ const presets = await readPresets(api);
7120
+ console.log();
7121
+ const answers = await promptRunFields(prompter, { columns, presets, supplied });
7122
+ console.log();
7123
+ await withStatus("Saving the analysis settings", () => api.analysis.update(analysisId, {
7124
+ ...recipe,
7125
+ targets: answers.targets,
7126
+ questions: answers.questions,
7127
+ segment: answers.segment,
7128
+ hours: answers.hours,
7129
+ budget: answers.budget
7130
+ }));
7131
+ console.log();
7132
+ heading("Ready to run");
7133
+ const identity = {
7134
+ name: recipe.name,
7135
+ description: recipe.description ?? null,
7136
+ visibility: recipe.visibility ?? "PRIVATE"
7137
+ };
7138
+ for (const line of summaryLines(identity, answers)) detail(line);
7139
+ console.log();
7140
+ if (!await prompter.confirm({ message: "Start the analysis?", default: true })) {
7141
+ warn("Not started. The analysis and these settings are saved.");
7142
+ hint(`Start it later with 'diafunc analyze rerun ${analysisId}'.`);
7143
+ return false;
7144
+ }
7145
+ return true;
7146
+ }
7147
+ async function readColumns(api, analysisId) {
7148
+ for (let attempt = 0; attempt < COLUMN_READ_ATTEMPTS; attempt++) {
7149
+ if (attempt > 0) await new Promise((resolve) => setTimeout(resolve, COLUMN_READ_INTERVAL_MS));
7150
+ try {
7151
+ const columns = await api.analysis.getColumns(analysisId);
7152
+ if (columns.length > 0) return columns;
7153
+ } catch {
7154
+ }
7155
+ }
7156
+ warn("Could not read the column names from the uploaded file.");
7157
+ return [];
7158
+ }
7159
+ async function readPresets(api) {
7160
+ try {
7161
+ return await api.analysis.getPresets();
7162
+ } catch {
7163
+ return [];
7164
+ }
7165
+ }
6787
7166
  async function monitorRun(api, analysisId, runId, cmd) {
6788
7167
  const config = loadConfig();
6789
7168
  const outputFormat = getOutputFormat15(cmd);
@@ -6845,12 +7224,12 @@ async function monitorRun(api, analysisId, runId, cmd) {
6845
7224
  status.stop();
6846
7225
  }
6847
7226
  }
6848
- function safeParse(text) {
7227
+ function safeParse(text2) {
6849
7228
  try {
6850
- const parsed = JSON.parse(text);
6851
- return parsed && typeof parsed === "object" ? parsed : { output: text };
7229
+ const parsed = JSON.parse(text2);
7230
+ return parsed && typeof parsed === "object" ? parsed : { output: text2 };
6852
7231
  } catch {
6853
- return { output: text };
7232
+ return { output: text2 };
6854
7233
  }
6855
7234
  }
6856
7235
  async function reportTerminalRun(api, config, run, analysisId, runId, outputFormat) {
@@ -6932,12 +7311,12 @@ async function getAnalysisDetails(analysisId, options, cmd) {
6932
7311
  }
6933
7312
  }
6934
7313
  var INTRODUCTION_PREVIEW_LINES = 3;
6935
- function isLong(text) {
6936
- return Boolean(text && text.split("\n").length > INTRODUCTION_PREVIEW_LINES);
7314
+ function isLong(text2) {
7315
+ return Boolean(text2 && text2.split("\n").length > INTRODUCTION_PREVIEW_LINES);
6937
7316
  }
6938
- function abbreviate(text) {
6939
- if (!isLong(text)) return text;
6940
- const lines = text.split("\n").filter((l) => l.trim().length > 0);
7317
+ function abbreviate(text2) {
7318
+ if (!isLong(text2)) return text2;
7319
+ const lines = text2.split("\n").filter((l) => l.trim().length > 0);
6941
7320
  return `${lines.slice(0, INTRODUCTION_PREVIEW_LINES).join("\n")}
6942
7321
  \u2026`;
6943
7322
  }
@@ -6974,13 +7353,51 @@ async function watchAnalysis(analysisId, cmd) {
6974
7353
  console.log(`Watching run ${latest.runId} for analysis ${recipe.analysisId} ...`);
6975
7354
  await monitorRun(api, recipe.analysisId, latest.runId, cmd);
6976
7355
  }
6977
- async function rerunAnalysis(analysisId) {
7356
+ async function rerunAnalysis(analysisId, cmd) {
6978
7357
  const api = createApiClient();
7358
+ const found = await api.analysis.get(analysisId);
7359
+ if (!found.analysis) {
7360
+ failure(`Analysis not found: ${analysisId}`);
7361
+ process.exit(EXIT_FAILURE);
7362
+ }
7363
+ const analysis = found.analysis;
7364
+ const missing = missingRunFields(analysis);
7365
+ if (missing.length > 0) {
7366
+ const outputFormat = getOutputFormat15(cmd);
7367
+ const noInteractive = noInteractiveFlag(cmd);
7368
+ if (!canPrompt(outputFormat, noInteractive)) {
7369
+ const { message, suggestion } = explainMissingRunFields(
7370
+ analysisId,
7371
+ missing,
7372
+ whyNoPrompt(outputFormat, noInteractive)
7373
+ );
7374
+ usageError(message, suggestion);
7375
+ }
7376
+ const recipe = {
7377
+ name: analysis.name,
7378
+ description: analysis.description,
7379
+ visibility: analysis.visibility,
7380
+ introduction: analysis.introduction,
7381
+ hours: analysis.hours,
7382
+ budget: analysis.budget,
7383
+ targets: analysis.targets,
7384
+ questions: analysis.questions,
7385
+ segment: analysis.segment
7386
+ };
7387
+ const configured = await configureInteractively(
7388
+ api,
7389
+ createInquirerPrompter(),
7390
+ analysisId,
7391
+ recipe,
7392
+ suppliedFromAnalysis(analysis)
7393
+ );
7394
+ if (!configured) return;
7395
+ }
6979
7396
  const run = await api.analysis.runAnalysis(analysisId);
6980
7397
  success(`Queued new run ${run.runId} for analysis ${analysisId}`);
6981
- console.log(chalk25.dim(` State: ${run.state}`));
7398
+ console.log(chalk26.dim(` State: ${run.state}`));
6982
7399
  console.log();
6983
- console.log(chalk25.dim("Track progress: diafunc analyze watch " + analysisId));
7400
+ console.log(chalk26.dim("Track progress: diafunc analyze watch " + analysisId));
6984
7401
  }
6985
7402
  async function openAnalysis(analysisId) {
6986
7403
  const api = createApiClient();
@@ -6997,7 +7414,7 @@ async function openAnalysis(analysisId) {
6997
7414
  console.log(`Opening ${url} ...`);
6998
7415
  openUrl(url);
6999
7416
  } catch {
7000
- console.log(chalk25.dim("Notebook not yet provisioned \u2014 run the analysis first."));
7417
+ console.log(chalk26.dim("Notebook not yet provisioned \u2014 run the analysis first."));
7001
7418
  }
7002
7419
  }
7003
7420
  async function createRecipe(options, cmd) {
@@ -7121,7 +7538,7 @@ async function getPreset(presetId, cmd) {
7121
7538
  const api = createApiClient();
7122
7539
  const opt = await api.analysis.getPreset(presetId);
7123
7540
  if (!opt.preset) {
7124
- console.log(chalk25.dim("Preset not found."));
7541
+ console.log(chalk26.dim("Preset not found."));
7125
7542
  return;
7126
7543
  }
7127
7544
  format(opt.preset, { format: outputFormat });
@@ -7204,7 +7621,7 @@ async function updateTriggerCmd(triggerId, options, cmd) {
7204
7621
  }
7205
7622
  function registerAnalyzeCommand(program) {
7206
7623
  const analyze = program.command("analyze").description("Run and manage automatic analyses");
7207
- analyze.argument("[file]", "CSV or Excel file to analyze").option("--name <name>", "Analysis name (derived from filename if omitted)").option("--description <text>", "Analysis description", "").option("--visibility <vis>", "PRIVATE or PUBLIC", "PRIVATE").option("--hours <hours>", "Computation time in hours (default: 4; preset value used when --preset set)").option("--budget <credits>", "Credit budget (default: 400; preset value used when --preset set)").option("--targets <csv>", "Comma-separated target column names").option("--questions <csv>", "Comma-separated questions to answer").option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction at notebook position 0").option("--preset <id>", "Apply a saved preset as defaults (explicit flags override preset values)").action(async (file, options, cmd) => {
7624
+ analyze.command("run", { isDefault: true }).description("Create an analysis from a data file, configure it and run it (the default: `analyze <file>`)").argument("[file]", "CSV or Excel file to analyze").option("--name <name>", "Analysis name (asked for, or derived from the filename)").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC (default: PRIVATE)").option("--hours <hours>", `Computation time in hours (default: ${DEFAULT_HOURS}; preset value used when --preset set)`).option("--budget <credits>", `Credit budget (default: ${DEFAULT_BUDGET}; preset value used when --preset set)`).option("--targets <csv>", "Comma-separated target column names (required when not interactive)").option("--questions <csv>", "Comma-separated questions to answer").option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction at notebook position 0").option("--preset <id>", "Apply a saved preset as defaults (explicit flags override preset values)").action(async (file, options, cmd) => {
7208
7625
  try {
7209
7626
  if (!file) {
7210
7627
  analyze.help();
@@ -7212,7 +7629,7 @@ function registerAnalyzeCommand(program) {
7212
7629
  }
7213
7630
  await runAnalysis(file, options, cmd);
7214
7631
  } catch (error) {
7215
- handleError(error);
7632
+ reportCommandError(error);
7216
7633
  }
7217
7634
  });
7218
7635
  analyze.command("list").description("List recent analyses").option("--limit <n>", "Number of analyses to list", "20").action(async (options, cmd) => {
@@ -7243,11 +7660,11 @@ function registerAnalyzeCommand(program) {
7243
7660
  handleError(error);
7244
7661
  }
7245
7662
  });
7246
- analyze.command("rerun").description("Queue a fresh run on an existing analysis").argument("<id>", "Analysis ID to rerun").action(async (id) => {
7663
+ analyze.command("rerun").description("Queue a fresh run on an existing analysis (asks for anything a run still needs)").argument("<id>", "Analysis ID to rerun").action(async (id, _options, cmd) => {
7247
7664
  try {
7248
- await rerunAnalysis(id);
7665
+ await rerunAnalysis(id, cmd);
7249
7666
  } catch (error) {
7250
- handleError(error);
7667
+ reportCommandError(error);
7251
7668
  }
7252
7669
  });
7253
7670
  analyze.command("create").description("Create an analysis recipe without uploading data or running").option("--name <name>", "Analysis name").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC", "PRIVATE").option("--hours <h>", "Computation hours").option("--budget <credits>", "Credit budget").option("--targets <csv>", "Comma-separated target column names").option("--questions <csv>", "Comma-separated questions").option("--segment <name>", "Segmentation column").option("--introduction <markdown>", "Markdown introduction").action(async (options, cmd) => {
@@ -7278,11 +7695,11 @@ function registerAnalyzeCommand(program) {
7278
7695
  handleError(error);
7279
7696
  }
7280
7697
  });
7281
- analyze.command("description").description("Set or clear the analysis description (empty string clears)").argument("<id>", "Analysis ID").argument("<text>", "New description (empty string to clear)").action(async (id, text, _options, cmd) => {
7698
+ analyze.command("description").description("Set or clear the analysis description (empty string clears)").argument("<id>", "Analysis ID").argument("<text>", "New description (empty string to clear)").action(async (id, text2, _options, cmd) => {
7282
7699
  try {
7283
7700
  await patchAndPrint(
7284
7701
  id,
7285
- text,
7702
+ text2,
7286
7703
  (api, aid, v) => api.analysis.patchDescription(aid, { description: v === "" ? null : v }),
7287
7704
  "Description",
7288
7705
  cmd
@@ -7476,7 +7893,7 @@ function registerAnalyzeCommand(program) {
7476
7893
  }
7477
7894
 
7478
7895
  // src/commands/data-sources/index.ts
7479
- import chalk26 from "chalk";
7896
+ import chalk27 from "chalk";
7480
7897
  function getOutputFormat16(cmd) {
7481
7898
  const config = loadConfig();
7482
7899
  const globalOpts = cmd.optsWithGlobals();
@@ -7565,9 +7982,9 @@ function runTableRow(run) {
7565
7982
  triggeredBy: run.triggeredBy ?? "\u2014"
7566
7983
  };
7567
7984
  }
7568
- function resolveProjectId(explicit, cmd) {
7985
+ function resolveProjectId(cmd) {
7569
7986
  const globals = cmd.optsWithGlobals();
7570
- const resolved = explicit ?? globals.project ?? loadConfig().defaults.project;
7987
+ const resolved = globals.project ?? loadConfig().defaults.project;
7571
7988
  if (!resolved) {
7572
7989
  usageError(
7573
7990
  "This command needs a project.",
@@ -7612,7 +8029,7 @@ async function showDashboard(projectId, cmd) {
7612
8029
  return;
7613
8030
  }
7614
8031
  const r = dashboard.rollup;
7615
- let line = chalk26.bold(`DataSources in ${projectId}: `) + `${r.totalSources} total, ${r.scheduledSources} scheduled, ${r.sourcesWithRecentFailure} failing recently`;
8032
+ let line = chalk27.bold(`DataSources in ${projectId}: `) + `${r.totalSources} total, ${r.scheduledSources} scheduled, ${r.sourcesWithRecentFailure} failing recently`;
7616
8033
  if (r.lastActivityAt) line += `, last activity ${r.lastActivityAt}`;
7617
8034
  console.log(line);
7618
8035
  if (dashboard.sources.length === 0) {
@@ -7650,8 +8067,8 @@ async function createDataSource(options, cmd) {
7650
8067
  const ds = await api.storage.createDataSource(request);
7651
8068
  if (outputFormat === "human") {
7652
8069
  success(`Created data source ${ds.id}`);
7653
- console.log(chalk26.dim(` Last run: ${ds.lastRunStatus ?? "\u2014"}`));
7654
- if (ds.lastRunError) console.log(chalk26.dim(` Error: ${ds.lastRunError}`));
8070
+ console.log(chalk27.dim(` Last run: ${ds.lastRunStatus ?? "\u2014"}`));
8071
+ if (ds.lastRunError) console.log(chalk27.dim(` Error: ${ds.lastRunError}`));
7655
8072
  } else {
7656
8073
  format(ds, { format: outputFormat });
7657
8074
  }
@@ -7697,7 +8114,7 @@ async function refreshDataSource(id, cmd) {
7697
8114
  const run = await api.storage.refreshDataSource(id);
7698
8115
  if (outputFormat === "human") {
7699
8116
  success(`Refresh queued \u2014 run ${run.runId}, status ${run.status}`);
7700
- if (run.errorMessage) console.log(chalk26.red(` Error: ${run.errorMessage}`));
8117
+ if (run.errorMessage) console.log(chalk27.red(` Error: ${run.errorMessage}`));
7701
8118
  } else {
7702
8119
  format(run, { format: outputFormat });
7703
8120
  }
@@ -7746,13 +8163,13 @@ async function listConnectorTypes(cmd) {
7746
8163
  }
7747
8164
  function registerDataSourcesCommands(program) {
7748
8165
  const dataSources = program.command("data-sources").description("Manage scheduled DataSource imports (Google Sheets, S3 URL, JDBC)");
7749
- dataSources.command("list").description("List the data sources of one project").option("--project <id>", "Project ID; defaults to defaults.project from the config").addHelpText("after", `
8166
+ dataSources.command("list").description("List the data sources of one project").addHelpText("after", `
7750
8167
  Examples:
7751
8168
  $ diafunc data-sources list --project <id>
7752
8169
  $ diafunc config set defaults.project <id> then --project can be omitted
7753
- `).action(async (options, cmd) => {
8170
+ `).action(async (_options, cmd) => {
7754
8171
  try {
7755
- await listDataSources(resolveProjectId(options.project, cmd), cmd);
8172
+ await listDataSources(resolveProjectId(cmd), cmd);
7756
8173
  } catch (error) {
7757
8174
  handleError(error);
7758
8175
  }
@@ -7824,7 +8241,7 @@ Examples:
7824
8241
  }
7825
8242
 
7826
8243
  // src/commands/table-exporters/index.ts
7827
- import chalk27 from "chalk";
8244
+ import chalk28 from "chalk";
7828
8245
  function getOutputFormat17(cmd) {
7829
8246
  const config = loadConfig();
7830
8247
  const globalOpts = cmd.optsWithGlobals();
@@ -7855,7 +8272,7 @@ function registerTableExportersCommands(program) {
7855
8272
  format: outputFormat,
7856
8273
  columns: ["id", "name", "format", "extension", "mimeType", "priority", "function", "createdBy"]
7857
8274
  });
7858
- console.log(chalk27.dim(`${list.length} exporter(s)`));
8275
+ console.log(chalk28.dim(`${list.length} exporter(s)`));
7859
8276
  } catch (error) {
7860
8277
  handleError(error);
7861
8278
  }
@@ -7913,15 +8330,14 @@ function registerTableExportersCommands(program) {
7913
8330
  }
7914
8331
 
7915
8332
  // src/commands/skeleton/index.ts
7916
- import chalk28 from "chalk";
8333
+ import chalk29 from "chalk";
7917
8334
  import * as fs9 from "fs";
7918
8335
  function getOutputFormat18(cmd) {
7919
8336
  const config = loadConfig();
7920
8337
  const globalOpts = cmd.optsWithGlobals();
7921
8338
  return globalOpts.output ?? config.defaults.output ?? "human";
7922
8339
  }
7923
- function resolveProjectId2(localOption, cmd) {
7924
- if (localOption) return localOption;
8340
+ function resolveProjectId2(cmd) {
7925
8341
  const globalOpts = cmd.optsWithGlobals();
7926
8342
  if (globalOpts.project) return globalOpts.project;
7927
8343
  const config = loadConfig();
@@ -7966,12 +8382,13 @@ function skeletonTableRow(s) {
7966
8382
  }
7967
8383
  async function createSkeleton(options, cmd) {
7968
8384
  const outputFormat = getOutputFormat18(cmd);
7969
- const projectId = resolveProjectId2(options.project, cmd);
8385
+ const projectId = resolveProjectId2(cmd);
7970
8386
  const template = resolveTemplate(options.template);
7971
8387
  const weight = parseWeight(options.weight);
8388
+ const globals = cmd.optsWithGlobals();
7972
8389
  const request = {
7973
8390
  projectId,
7974
- projectBranch: options.branch,
8391
+ projectBranch: globals.branch ?? loadConfig().defaults.branch ?? "main",
7975
8392
  name: options.name,
7976
8393
  template,
7977
8394
  weight
@@ -7980,17 +8397,17 @@ async function createSkeleton(options, cmd) {
7980
8397
  const skeleton = await api.storage.createSkeleton(request);
7981
8398
  if (outputFormat === "human") {
7982
8399
  success(`Created skeleton ${skeleton.id}`);
7983
- console.log(chalk28.dim(` name: ${skeleton.name}`));
7984
- console.log(chalk28.dim(` template: ${skeleton.template}`));
7985
- console.log(chalk28.dim(` paramCount: ${skeleton.paramCount}`));
7986
- console.log(chalk28.dim(` weight: ${skeleton.weight}`));
8400
+ console.log(chalk29.dim(` name: ${skeleton.name}`));
8401
+ console.log(chalk29.dim(` template: ${skeleton.template}`));
8402
+ console.log(chalk29.dim(` paramCount: ${skeleton.paramCount}`));
8403
+ console.log(chalk29.dim(` weight: ${skeleton.weight}`));
7987
8404
  } else {
7988
8405
  format(skeleton, { format: outputFormat });
7989
8406
  }
7990
8407
  }
7991
- async function listSkeletons(localProject, cmd) {
8408
+ async function listSkeletons(cmd) {
7992
8409
  const outputFormat = getOutputFormat18(cmd);
7993
- const projectId = resolveProjectId2(localProject, cmd);
8410
+ const projectId = resolveProjectId2(cmd);
7994
8411
  const api = createApiClient();
7995
8412
  const skeletons = await api.storage.listSkeletons(projectId);
7996
8413
  if (outputFormat === "human" && skeletons.length === 0) {
@@ -8022,10 +8439,10 @@ async function updateSkeleton(id, options, cmd) {
8022
8439
  const skeleton = await api.storage.updateSkeleton(id, request);
8023
8440
  if (outputFormat === "human") {
8024
8441
  success(`Updated skeleton ${skeleton.id}`);
8025
- console.log(chalk28.dim(` name: ${skeleton.name}`));
8026
- console.log(chalk28.dim(` template: ${skeleton.template}`));
8027
- console.log(chalk28.dim(` paramCount: ${skeleton.paramCount}`));
8028
- console.log(chalk28.dim(` weight: ${skeleton.weight}`));
8442
+ console.log(chalk29.dim(` name: ${skeleton.name}`));
8443
+ console.log(chalk29.dim(` template: ${skeleton.template}`));
8444
+ console.log(chalk29.dim(` paramCount: ${skeleton.paramCount}`));
8445
+ console.log(chalk29.dim(` weight: ${skeleton.weight}`));
8029
8446
  } else {
8030
8447
  format(skeleton, { format: outputFormat });
8031
8448
  }
@@ -8045,16 +8462,16 @@ Examples:
8045
8462
  skeleton.command("create").description("Create a skeleton. Parse errors from the engine are surfaced as stderr.").requiredOption("--name <name>", "Display name").requiredOption(
8046
8463
  "--template <expr>",
8047
8464
  'Skeleton template expression (e.g. "?*x+?"). Use "@file.txt" to read from a file; "@@\u2026" escapes a literal leading @.'
8048
- ).option("--project <id>", "Project ID (defaults to global --project / config defaults.project)").option("--branch <branch>", "Project branch", "main").option("--weight <number>", "Sampling weight (positive; server default applies if omitted)").action(async (options, cmd) => {
8465
+ ).option("--weight <number>", "Sampling weight (positive; server default applies if omitted)").action(async (options, cmd) => {
8049
8466
  try {
8050
8467
  await createSkeleton(options, cmd);
8051
8468
  } catch (error) {
8052
8469
  handleError(error);
8053
8470
  }
8054
8471
  });
8055
- skeleton.command("list").description("List skeletons in a project").option("--project <id>", "Project ID (defaults to global --project / config defaults.project)").action(async (options, cmd) => {
8472
+ skeleton.command("list").description("List skeletons in a project").action(async (_options, cmd) => {
8056
8473
  try {
8057
- await listSkeletons(options.project, cmd);
8474
+ await listSkeletons(cmd);
8058
8475
  } catch (error) {
8059
8476
  handleError(error);
8060
8477
  }
@@ -8153,7 +8570,7 @@ _diafunc_completions() {
8153
8570
  COMPREPLY=($(compgen -W "call" -- "\${cur}"))
8154
8571
  ;;
8155
8572
  chat)
8156
- subcommands="send stream upload session usage"
8573
+ subcommands="repl send stream upload session usage"
8157
8574
  if [[ "\${COMP_WORDS[2]}" == "session" ]]; then
8158
8575
  COMPREPLY=($(compgen -W "list delete" -- "\${cur}"))
8159
8576
  else
@@ -8250,7 +8667,7 @@ _diafunc_project() { _values 'subcommand' list get create delete lock unlock mem
8250
8667
  _diafunc_team() { _values 'subcommand' list get use usage create portal cancel leave members invitations seats packs transfer; }
8251
8668
  _diafunc_entity() { _values 'subcommand' list get delete history revert rename content; }
8252
8669
  _diafunc_table() { _values 'subcommand' view import export row column cell clear; }
8253
- _diafunc_chat() { _values 'subcommand' send stream upload session usage; }
8670
+ _diafunc_chat() { _values 'subcommand' repl send stream upload session usage; }
8254
8671
  _diafunc_admin() { _values 'subcommand' users subscription settings backup; }
8255
8672
 
8256
8673
  _diafunc "$@"`;
@@ -8309,7 +8726,7 @@ complete -c diafunc -n "__fish_seen_subcommand_from table; and not __fish_seen_s
8309
8726
  complete -c diafunc -n "__fish_seen_subcommand_from function; and not __fish_seen_subcommand_from call evaluations outputs logs stop engines" -a "call evaluations outputs logs stop engines"
8310
8727
 
8311
8728
  # chat
8312
- complete -c diafunc -n "__fish_seen_subcommand_from chat; and not __fish_seen_subcommand_from send stream upload session usage" -a "send stream upload session usage"
8729
+ complete -c diafunc -n "__fish_seen_subcommand_from chat; and not __fish_seen_subcommand_from repl send stream upload session usage" -a "repl send stream upload session usage"
8313
8730
 
8314
8731
  # team
8315
8732
  complete -c diafunc -n "__fish_seen_subcommand_from team; and not __fish_seen_subcommand_from list get use usage create portal cancel leave members invitations seats packs transfer" -a "list get use usage create portal cancel leave members invitations seats packs transfer"
@@ -8342,7 +8759,7 @@ function registerCompletionCommand(program) {
8342
8759
  }
8343
8760
 
8344
8761
  // src/commands/whoami/index.ts
8345
- import chalk29 from "chalk";
8762
+ import chalk30 from "chalk";
8346
8763
  function registerWhoamiCommand(program) {
8347
8764
  program.command("whoami").description("Show the currently authenticated user").action(async (_options, cmd) => {
8348
8765
  try {
@@ -8352,8 +8769,8 @@ function registerWhoamiCommand(program) {
8352
8769
  const api = createApiClient();
8353
8770
  const user = await api.admin.getMyUser();
8354
8771
  if (outputFormat === "human") {
8355
- console.log(chalk29.bold(user.name) + chalk29.dim(` <${user.email}>`));
8356
- console.log(chalk29.dim(` Role: ${user.role} \xB7 Remaining credits: ${user.remainingCredits} \xB7 Profile: ${config.currentProfile}`));
8772
+ console.log(chalk30.bold(user.name) + chalk30.dim(` <${user.email}>`));
8773
+ console.log(chalk30.dim(` Role: ${user.role} \xB7 Remaining credits: ${user.remainingCredits} \xB7 Profile: ${config.currentProfile}`));
8357
8774
  } else {
8358
8775
  format(user, { format: outputFormat });
8359
8776
  }
@@ -8364,7 +8781,7 @@ function registerWhoamiCommand(program) {
8364
8781
  }
8365
8782
 
8366
8783
  // src/commands/utilization/index.ts
8367
- import chalk30 from "chalk";
8784
+ import chalk31 from "chalk";
8368
8785
  function getOutputFormat19(cmd) {
8369
8786
  const config = loadConfig();
8370
8787
  const globalOpts = cmd.optsWithGlobals();
@@ -8380,20 +8797,20 @@ function windowLabel(u) {
8380
8797
  return `billing cycle ${u.year}-${String(u.month).padStart(2, "0")}`;
8381
8798
  }
8382
8799
  function printUtilizationHuman(u, label) {
8383
- const when = windowLabel(u);
8384
- console.log(label ? chalk30.bold(label) + " " + chalk30.dim(when) : chalk30.bold(when));
8800
+ const when2 = windowLabel(u);
8801
+ console.log(label ? chalk31.bold(label) + " " + chalk31.dim(when2) : chalk31.bold(when2));
8385
8802
  if (u.types.length === 0) {
8386
- console.log(chalk30.dim(" (no usage)"));
8803
+ console.log(chalk31.dim(" (no usage)"));
8387
8804
  return;
8388
8805
  }
8389
8806
  const types = [...u.types].sort((a, b) => b.credits - a.credits);
8390
8807
  const width = Math.max(...types.map((t) => t.type.length));
8391
8808
  for (const t of types) {
8392
- const line = ` ${t.type.padEnd(width)} ${formatNumber(t.quantity).padStart(12)} ${chalk30.dim("credits")} ${t.credits.toFixed(2).padStart(10)}`;
8393
- console.log(t.credits === 0 ? chalk30.dim(line) : line);
8809
+ const line = ` ${t.type.padEnd(width)} ${formatNumber(t.quantity).padStart(12)} ${chalk31.dim("credits")} ${t.credits.toFixed(2).padStart(10)}`;
8810
+ console.log(t.credits === 0 ? chalk31.dim(line) : line);
8394
8811
  }
8395
8812
  const total = u.totalCredits ?? u.types.reduce((s, t) => s + t.credits, 0);
8396
- console.log(chalk30.bold(` ${"Total".padEnd(width)} ${" ".repeat(12)} ${chalk30.dim("credits")} ${total.toFixed(2).padStart(10)}`));
8813
+ console.log(chalk31.bold(` ${"Total".padEnd(width)} ${" ".repeat(12)} ${chalk31.dim("credits")} ${total.toFixed(2).padStart(10)}`));
8397
8814
  }
8398
8815
  function registerUtilizationCommand(program) {
8399
8816
  const util = program.command("utilization").description("Show credit utilization for the current billing cycle").addHelpText("after", `
@@ -8596,7 +9013,7 @@ Examples:
8596
9013
  }
8597
9014
 
8598
9015
  // src/commands/shell/index.ts
8599
- import chalk31 from "chalk";
9016
+ import chalk32 from "chalk";
8600
9017
  import * as fs11 from "fs";
8601
9018
  import * as os3 from "os";
8602
9019
  import * as path8 from "path";
@@ -8662,21 +9079,21 @@ async function evaluate(api, fnRef, language, sourceCode) {
8662
9079
  }, false);
8663
9080
  if (result.outputs?.length) {
8664
9081
  for (const out of result.outputs) {
8665
- console.log(chalk31.dim(` [${out.type}]`) + " " + out.output);
9082
+ console.log(chalk32.dim(` [${out.type}]`) + " " + out.output);
8666
9083
  }
8667
9084
  }
8668
9085
  if (result.successful) {
8669
9086
  if (result.result) {
8670
- console.log(chalk31.green("=>") + " " + result.result);
9087
+ console.log(chalk32.green("=>") + " " + result.result);
8671
9088
  } else {
8672
- console.log(chalk31.dim("=> (no value)"));
9089
+ console.log(chalk32.dim("=> (no value)"));
8673
9090
  }
8674
9091
  const duration = result.completed - result.started;
8675
- console.log(chalk31.dim(` [${duration}ms \xB7 ${evaluationId}]`));
9092
+ console.log(chalk32.dim(` [${duration}ms \xB7 ${evaluationId}]`));
8676
9093
  } else {
8677
- console.log(chalk31.red("error: ") + result.error);
9094
+ console.log(chalk32.red("error: ") + result.error);
8678
9095
  if (result.lineNumber > 0) {
8679
- console.log(chalk31.dim(` at line ${result.lineNumber}, col ${result.columnNumber}`));
9096
+ console.log(chalk32.dim(` at line ${result.lineNumber}, col ${result.columnNumber}`));
8680
9097
  }
8681
9098
  }
8682
9099
  }
@@ -8697,19 +9114,19 @@ function registerShellCommand(program) {
8697
9114
  });
8698
9115
  const api = createApiClient();
8699
9116
  const { input: promptInput } = await import("@inquirer/prompts");
8700
- const { getUpdateNotice } = await import("./update-check-XRMWJ753.js");
9117
+ const { getUpdateNotice } = await import("./update-check-SNH7P32S.js");
8701
9118
  const resolvedLanguage = await resolveLanguage(api, fnRef.projectId, options.language);
8702
- console.log(chalk31.bold("Diafunc shell") + chalk31.dim(` \xB7 function ${fnRef.entityId} \xB7 ${resolvedLanguage}`));
8703
- console.log(chalk31.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
8704
- console.log(chalk31.dim("Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit"));
9119
+ console.log(chalk32.bold("Diafunc shell") + chalk32.dim(` \xB7 function ${fnRef.entityId} \xB7 ${resolvedLanguage}`));
9120
+ console.log(chalk32.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
9121
+ console.log(chalk32.dim("Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit"));
8705
9122
  const notice = await getUpdateNotice();
8706
- if (notice) console.log(chalk31.dim(notice));
9123
+ if (notice) console.log(chalk32.dim(notice));
8707
9124
  console.log();
8708
9125
  let language = resolvedLanguage;
8709
9126
  for (; ; ) {
8710
9127
  let line;
8711
9128
  try {
8712
- line = await promptInput({ message: chalk31.cyan.bold(`${language} >`) });
9129
+ line = await promptInput({ message: chalk32.cyan.bold(`${language} >`) });
8713
9130
  } catch {
8714
9131
  console.log();
8715
9132
  return;
@@ -8727,54 +9144,54 @@ function registerShellCommand(program) {
8727
9144
  case "help":
8728
9145
  case "h":
8729
9146
  case "?":
8730
- console.log(chalk31.dim(" /edit open $EDITOR for multi-line code"));
8731
- console.log(chalk31.dim(" /file <path> evaluate the contents of a file"));
8732
- console.log(chalk31.dim(" /lang <name> switch language (Java, JavaScript, Kotlin, Python, Scala)"));
8733
- console.log(chalk31.dim(" /quit exit the shell"));
9147
+ console.log(chalk32.dim(" /edit open $EDITOR for multi-line code"));
9148
+ console.log(chalk32.dim(" /file <path> evaluate the contents of a file"));
9149
+ console.log(chalk32.dim(" /lang <name> switch language (Java, JavaScript, Kotlin, Python, Scala)"));
9150
+ console.log(chalk32.dim(" /quit exit the shell"));
8734
9151
  continue;
8735
9152
  case "lang":
8736
9153
  if (arg) language = arg;
8737
- console.log(chalk31.dim(`Language: ${language}`));
9154
+ console.log(chalk32.dim(`Language: ${language}`));
8738
9155
  continue;
8739
9156
  case "edit": {
8740
9157
  const sourceCode = await openInEditor("", extensionFor2(language));
8741
9158
  if (!sourceCode.trim()) {
8742
- console.log(chalk31.dim("(empty \u2014 not evaluated)"));
9159
+ console.log(chalk32.dim("(empty \u2014 not evaluated)"));
8743
9160
  continue;
8744
9161
  }
8745
9162
  try {
8746
9163
  await evaluate(api, fnRef, language, sourceCode);
8747
9164
  } catch (e) {
8748
- console.error(chalk31.red(e.message));
9165
+ console.error(chalk32.red(e.message));
8749
9166
  }
8750
9167
  continue;
8751
9168
  }
8752
9169
  case "file": {
8753
9170
  if (!arg) {
8754
- console.log(chalk31.dim("usage: /file <path>"));
9171
+ console.log(chalk32.dim("usage: /file <path>"));
8755
9172
  continue;
8756
9173
  }
8757
9174
  if (!fs11.existsSync(arg)) {
8758
- console.log(chalk31.red(`file not found: ${arg}`));
9175
+ console.log(chalk32.red(`file not found: ${arg}`));
8759
9176
  continue;
8760
9177
  }
8761
9178
  const sourceCode = fs11.readFileSync(arg, "utf-8");
8762
9179
  try {
8763
9180
  await evaluate(api, fnRef, language, sourceCode);
8764
9181
  } catch (e) {
8765
- console.error(chalk31.red(e.message));
9182
+ console.error(chalk32.red(e.message));
8766
9183
  }
8767
9184
  continue;
8768
9185
  }
8769
9186
  default:
8770
- console.log(chalk31.dim(`Unknown command: /${cmd2}. Try /help.`));
9187
+ console.log(chalk32.dim(`Unknown command: /${cmd2}. Try /help.`));
8771
9188
  continue;
8772
9189
  }
8773
9190
  }
8774
9191
  try {
8775
9192
  await evaluate(api, fnRef, language, trimmed);
8776
9193
  } catch (e) {
8777
- console.error(chalk31.red(e.message));
9194
+ console.error(chalk32.red(e.message));
8778
9195
  }
8779
9196
  }
8780
9197
  } catch (error) {
@@ -8784,7 +9201,7 @@ function registerShellCommand(program) {
8784
9201
  }
8785
9202
 
8786
9203
  // src/commands/update/index.ts
8787
- import chalk32 from "chalk";
9204
+ import chalk33 from "chalk";
8788
9205
  import * as path9 from "path";
8789
9206
  import { spawn as spawn4 } from "child_process";
8790
9207
 
@@ -8830,14 +9247,14 @@ function registerUpdateCommand(program) {
8830
9247
  const install = detectInstall();
8831
9248
  const latest = await fetchLatestVersion();
8832
9249
  if (latest === package_default.version) {
8833
- console.log(chalk32.dim(`diafunc is already at the latest version (${package_default.version}).`));
9250
+ console.log(chalk33.dim(`diafunc is already at the latest version (${package_default.version}).`));
8834
9251
  return;
8835
9252
  }
8836
- console.log(chalk32.dim(`Current: ${package_default.version} \u2192 Available: ${latest}`));
9253
+ console.log(chalk33.dim(`Current: ${package_default.version} \u2192 Available: ${latest}`));
8837
9254
  if (install.method === "npm") {
8838
9255
  console.log();
8839
9256
  console.log("Installed via npm. Upgrade with:");
8840
- console.log(chalk32.bold(` npm install -g @diafunc/cli@${latest}`));
9257
+ console.log(chalk33.bold(` npm install -g @diafunc/cli@${latest}`));
8841
9258
  return;
8842
9259
  }
8843
9260
  const installDir = path9.dirname(install.binaryPath);
@@ -8851,7 +9268,7 @@ function registerUpdateCommand(program) {
8851
9268
  }
8852
9269
 
8853
9270
  // src/commands/uninstall/index.ts
8854
- import chalk33 from "chalk";
9271
+ import chalk34 from "chalk";
8855
9272
  import { spawn as spawn5 } from "child_process";
8856
9273
  import * as fs13 from "fs";
8857
9274
  import * as os4 from "os";
@@ -8863,11 +9280,11 @@ function registerUninstallCommand(program) {
8863
9280
  const configDir = path10.join(os4.homedir(), ".diafunc");
8864
9281
  if (install.method === "npm") {
8865
9282
  console.log("Installed via npm. Remove with:");
8866
- console.log(chalk33.bold(" npm uninstall -g @diafunc/cli"));
9283
+ console.log(chalk34.bold(" npm uninstall -g @diafunc/cli"));
8867
9284
  if (fs13.existsSync(configDir)) {
8868
9285
  console.log();
8869
9286
  console.log(`Config + credentials live at ${configDir} \u2014 remove manually with:`);
8870
- console.log(chalk33.bold(` rm -rf ${configDir}`));
9287
+ console.log(chalk34.bold(` rm -rf ${configDir}`));
8871
9288
  }
8872
9289
  return;
8873
9290
  }
@@ -8877,7 +9294,7 @@ function registerUninstallCommand(program) {
8877
9294
  default: false
8878
9295
  });
8879
9296
  if (!removeBinary) {
8880
- console.log(chalk33.dim("Aborted."));
9297
+ console.log(chalk34.dim("Aborted."));
8881
9298
  return;
8882
9299
  }
8883
9300
  let removeConfig = options.purge ?? false;
@@ -8889,7 +9306,7 @@ function registerUninstallCommand(program) {
8889
9306
  }
8890
9307
  if (removeConfig && fs13.existsSync(configDir)) {
8891
9308
  fs13.rmSync(configDir, { recursive: true, force: true });
8892
- console.log(chalk33.dim(`Removed ${configDir}`));
9309
+ console.log(chalk34.dim(`Removed ${configDir}`));
8893
9310
  }
8894
9311
  if (process.platform === "win32") {
8895
9312
  const cmd = `timeout /t 2 /nobreak >nul & del /f /q "${install.binaryPath}"`;
@@ -8899,13 +9316,13 @@ function registerUninstallCommand(program) {
8899
9316
  windowsHide: true
8900
9317
  });
8901
9318
  child.unref();
8902
- console.log(chalk33.dim(`Removing ${install.binaryPath} on exit...`));
9319
+ console.log(chalk34.dim(`Removing ${install.binaryPath} on exit...`));
8903
9320
  console.log();
8904
9321
  console.log("diafunc uninstalled.");
8905
9322
  return;
8906
9323
  }
8907
9324
  fs13.rmSync(install.binaryPath, { force: true });
8908
- console.log(chalk33.dim(`Removed ${install.binaryPath}`));
9325
+ console.log(chalk34.dim(`Removed ${install.binaryPath}`));
8909
9326
  console.log();
8910
9327
  console.log("diafunc uninstalled.");
8911
9328
  } catch (error) {
@@ -8914,6 +9331,757 @@ function registerUninstallCommand(program) {
8914
9331
  });
8915
9332
  }
8916
9333
 
9334
+ // src/prompting/command.ts
9335
+ import { Command } from "commander";
9336
+ var commanderOriginal = Command.prototype;
9337
+ var DiafuncCommand = class _DiafuncCommand extends Command {
9338
+ /** Gaps recorded during the current parse, in the order commander found them. */
9339
+ pendingInputs = [];
9340
+ /** Set on the program only; every command reads it from there. */
9341
+ promptEnvironment = {};
9342
+ createCommand(name) {
9343
+ return new _DiafuncCommand(name);
9344
+ }
9345
+ missingArgument(name) {
9346
+ if (!this.mayPrompt()) {
9347
+ commanderOriginal.missingArgument.call(this, name);
9348
+ return;
9349
+ }
9350
+ const index = this.registeredArguments.findIndex((a) => a.name() === name);
9351
+ const argument = this.registeredArguments[index];
9352
+ this.pendingInputs.push({
9353
+ kind: "argument",
9354
+ name,
9355
+ index,
9356
+ description: argument?.description ?? "",
9357
+ variadic: Boolean(argument?.variadic)
9358
+ });
9359
+ }
9360
+ missingMandatoryOptionValue(option) {
9361
+ if (!this.mayPrompt()) {
9362
+ commanderOriginal.missingMandatoryOptionValue.call(this, option);
9363
+ return;
9364
+ }
9365
+ this.pendingInputs.push({
9366
+ kind: "option",
9367
+ name: option.attributeName(),
9368
+ flag: option.long ?? option.flags,
9369
+ description: option.description ?? "",
9370
+ variadic: Boolean(option.variadic)
9371
+ });
9372
+ }
9373
+ /** The environment set on the program. */
9374
+ environment() {
9375
+ let root = this;
9376
+ while (root.parent) root = root.parent;
9377
+ return root instanceof _DiafuncCommand ? root.promptEnvironment : {};
9378
+ }
9379
+ mayPrompt() {
9380
+ const forced = this.environment().interactive;
9381
+ if (forced !== void 0) return forced;
9382
+ const globals = this.optsWithGlobals();
9383
+ const output = globals.output ?? loadConfig().defaults.output ?? "human";
9384
+ return canPrompt(output, globals.interactive === false);
9385
+ }
9386
+ };
9387
+
9388
+ // src/prompting/fill.ts
9389
+ import chalk36 from "chalk";
9390
+
9391
+ // src/prompting/resolvers.ts
9392
+ var PROJECT_ROLES = ["OWNER", "ADMIN", "DEVELOPER", "GUEST"];
9393
+ var TRIGGER_TYPES = ["SCHEDULE", "EVENT", "LINK", "MANUAL"];
9394
+ var ANALYSIS_TRIGGER_KINDS = ["ONCE", "CRON"];
9395
+ var VISIBILITIES = ["PRIVATE", "PUBLIC"];
9396
+ var SHELLS = ["bash", "zsh", "fish"];
9397
+ var CONFIG_KEYS = ["defaults.project", "defaults.branch", "defaults.output"];
9398
+ var ENTITY_TYPE_BY_GROUP = {
9399
+ table: "table",
9400
+ function: "function",
9401
+ trigger: "function",
9402
+ schedule: "function"
9403
+ };
9404
+ var TEXT = { kind: "text" };
9405
+ var TEXT_OR_EMPTY = { kind: "text", allowEmpty: true };
9406
+ var POSITIVE = { kind: "number", min: 0, integer: false, exclusive: true };
9407
+ var INDEX = { kind: "number", min: 0, integer: true };
9408
+ var BY_COMMAND = {
9409
+ "analyze segment": { "<name>": { kind: "analysisColumns", multiple: false, allowEmpty: true } },
9410
+ "analyze targets": { "<csv>": { kind: "analysisColumns", multiple: true, allowEmpty: false } },
9411
+ "analyze questions": { "<csv>": TEXT_OR_EMPTY },
9412
+ "analyze description": { "<text>": TEXT_OR_EMPTY },
9413
+ "analyze introduction": { "<markdown>": TEXT_OR_EMPTY },
9414
+ "analyze presets save": { "--targets": TEXT, "--hours": POSITIVE, "--budget": POSITIVE },
9415
+ "branch merge": {
9416
+ "--source": { kind: "entity", form: "ref" },
9417
+ "--target": { kind: "project", withBranch: true }
9418
+ },
9419
+ "branch create": { "<branchName>": TEXT },
9420
+ "branch delete": { "<branchName>": { kind: "projectBranch", projectFrom: "projectId" } },
9421
+ "admin backup restore-project": { "<projectBranch>": { kind: "projectBranch", projectFrom: "projectId" } },
9422
+ "data-sources create": {
9423
+ "--project-id": { kind: "project", withBranch: false },
9424
+ "--project-branch": { kind: "projectBranch", projectFrom: "projectId" },
9425
+ "--target-entity-id": { kind: "entity", form: "id", contentType: "table", projectFrom: "projectId" },
9426
+ "--target-entity-branch": { kind: "text", defaultValue: "main" },
9427
+ "--type": { kind: "connectorType" }
9428
+ },
9429
+ "table-exporters create": {
9430
+ "--function-project": { kind: "project", withBranch: false },
9431
+ "--function-entity": { kind: "entity", form: "id", contentType: "function", projectFrom: "functionProject" },
9432
+ "--format": TEXT
9433
+ },
9434
+ "table exports get": { "--ref": { kind: "entity", form: "ref", contentType: "table" } },
9435
+ "table export": { "<format>": { kind: "exportFormat" } },
9436
+ "entity export": { "<entityIds>": { kind: "entity", form: "id", projectFrom: "project", multiple: true } },
9437
+ "notebook export": {
9438
+ "<notebookIds>": { kind: "entity", form: "id", contentType: "notebook", projectFrom: "project", multiple: true }
9439
+ },
9440
+ "link delete": { "<linkId>": { kind: "link" } },
9441
+ "link create": { "<linkId>": TEXT },
9442
+ "config profile use": { "<name>": { kind: "profile" } },
9443
+ "config profile remove": { "<name>": { kind: "profile" } },
9444
+ "config get": { "<key>": { kind: "choice", choices: CONFIG_KEYS } },
9445
+ "config set": { "<key>": { kind: "choice", choices: CONFIG_KEYS } },
9446
+ "project members invite": { "<userId>": TEXT, "<role>": { kind: "choice", choices: PROJECT_ROLES } },
9447
+ "project members join": { "<userId>": TEXT },
9448
+ "trigger create": { "--type": { kind: "choice", choices: TRIGGER_TYPES } },
9449
+ "analyze triggers create": { "--kind": { kind: "choice", choices: ANALYSIS_TRIGGER_KINDS } },
9450
+ "function outputs": { "<evaluationId>": TEXT },
9451
+ "team create": { "--seats": { kind: "number", min: 1, integer: true } },
9452
+ "team seats preview": { "<count>": { kind: "number", min: 1, integer: true } },
9453
+ "team seats set": { "<count>": { kind: "number", min: 1, integer: true } }
9454
+ };
9455
+ var BY_NAME = {
9456
+ projectId: { kind: "project", withBranch: false },
9457
+ projectRef: { kind: "project", withBranch: true },
9458
+ project: { kind: "project", withBranch: true },
9459
+ teamId: { kind: "team" },
9460
+ invitationId: { kind: "teamInvitation" },
9461
+ analysisId: { kind: "analysis" },
9462
+ sessionId: { kind: "chatSession" },
9463
+ tokenId: { kind: "apiToken" },
9464
+ resource: { kind: "tokenResource" },
9465
+ scopes: { kind: "choices", choices: VALID_SCOPES },
9466
+ evaluationId: { kind: "evaluation" },
9467
+ eventId: { kind: "event" },
9468
+ occurrenceId: { kind: "occurrence" },
9469
+ exportId: { kind: "tableExport" },
9470
+ invoiceNumber: { kind: "invoice" },
9471
+ fileName: { kind: "invoiceDocument" },
9472
+ shell: { kind: "choice", choices: SHELLS },
9473
+ vis: { kind: "choice", choices: VISIBILITIES },
9474
+ kind: { kind: "choice", choices: ANALYSIS_TRIGGER_KINDS },
9475
+ date: { kind: "date" },
9476
+ file: { kind: "file" },
9477
+ email: { kind: "text", email: true },
9478
+ index: INDEX,
9479
+ row: INDEX,
9480
+ col: INDEX,
9481
+ count: INDEX,
9482
+ version: { kind: "number", min: 1, integer: true },
9483
+ hours: POSITIVE,
9484
+ credits: POSITIVE,
9485
+ seats: { kind: "number", min: 1, integer: true },
9486
+ value: TEXT_OR_EMPTY,
9487
+ // Free text: names, messages and ids the reader is creating rather than choosing.
9488
+ name: TEXT,
9489
+ newId: TEXT,
9490
+ message: TEXT,
9491
+ query: TEXT,
9492
+ title: TEXT,
9493
+ token: TEXT,
9494
+ subscriptionToken: TEXT,
9495
+ forkProjectId: TEXT,
9496
+ targetBranch: TEXT,
9497
+ bucketName: TEXT,
9498
+ objectName: TEXT,
9499
+ template: TEXT,
9500
+ plan: TEXT,
9501
+ schedule: TEXT,
9502
+ consumerType: TEXT,
9503
+ consumerId: TEXT,
9504
+ format: TEXT,
9505
+ key: TEXT
9506
+ };
9507
+ function tokenOf(input) {
9508
+ return input.kind === "option" ? input.flag ?? `--${input.name}` : `<${input.name}>`;
9509
+ }
9510
+ function specFor(path11, input) {
9511
+ const exact = BY_COMMAND[path11]?.[tokenOf(input)];
9512
+ if (exact) return exact;
9513
+ const group = path11.split(" ")[0];
9514
+ const sub = path11.split(" ").slice(0, 2).join(" ");
9515
+ switch (input.name) {
9516
+ case "ref":
9517
+ case "sourceRef":
9518
+ case "targetRef":
9519
+ return { kind: "entity", form: "ref", contentType: ENTITY_TYPE_BY_GROUP[group] };
9520
+ case "userId":
9521
+ return group === "team" ? { kind: "teamMember" } : { kind: "projectMember" };
9522
+ case "id":
9523
+ if (sub === "analyze presets") return { kind: "preset" };
9524
+ if (group === "analyze") return { kind: "analysis" };
9525
+ if (group === "data-sources") return { kind: "dataSource" };
9526
+ if (group === "skeleton") return { kind: "skeleton" };
9527
+ if (group === "table-exporters") return { kind: "tableExporter" };
9528
+ if (group === "status") return { kind: "statusComponent" };
9529
+ return null;
9530
+ case "runId":
9531
+ if (group === "analyze") return { kind: "analysisRun" };
9532
+ if (group === "data-sources") return { kind: "dataSourceRun" };
9533
+ return null;
9534
+ case "triggerId":
9535
+ if (group === "analyze") return { kind: "analysisTrigger" };
9536
+ if (group === "trigger") return { kind: "functionTrigger" };
9537
+ return null;
9538
+ case "role":
9539
+ return { kind: "choice", choices: PROJECT_ROLES };
9540
+ case "type":
9541
+ return null;
9542
+ default:
9543
+ return BY_NAME[input.name] ?? null;
9544
+ }
9545
+ }
9546
+ function dependencies(spec) {
9547
+ switch (spec.kind) {
9548
+ case "teamMember":
9549
+ case "teamInvitation":
9550
+ return ["teamId"];
9551
+ case "projectMember":
9552
+ return ["projectId"];
9553
+ case "analysisColumns":
9554
+ return ["id"];
9555
+ case "evaluation":
9556
+ return ["ref", "date"];
9557
+ case "functionTrigger":
9558
+ case "event":
9559
+ case "tableExport":
9560
+ return ["ref"];
9561
+ case "occurrence":
9562
+ return ["ref", "eventId"];
9563
+ case "link":
9564
+ return ["sourceRef"];
9565
+ case "tokenResource":
9566
+ return ["resourceType"];
9567
+ case "dataSourceRun":
9568
+ return ["id"];
9569
+ case "invoiceDocument":
9570
+ return ["invoiceNumber"];
9571
+ case "projectBranch":
9572
+ return [spec.projectFrom];
9573
+ case "entity":
9574
+ return spec.projectFrom ? [spec.projectFrom] : [];
9575
+ default:
9576
+ return [];
9577
+ }
9578
+ }
9579
+
9580
+ // src/prompting/pickers.ts
9581
+ import * as fs14 from "fs";
9582
+ import chalk35 from "chalk";
9583
+ var SEARCH_THRESHOLD = 10;
9584
+ var TYPE_IT = "\0type-it";
9585
+ async function askFor(spec, input, ctx) {
9586
+ const prefilled = ctx.prefill.get(input.name);
9587
+ if (prefilled !== void 0) return prefilled;
9588
+ switch (spec.kind) {
9589
+ case "project":
9590
+ return askProject(ctx, spec.withBranch, messageFor(input, "Project"));
9591
+ case "entity":
9592
+ return askEntity(ctx, spec, input);
9593
+ case "team":
9594
+ return listed(ctx, "teams", messageFor(input, "Team"), async () => (await ctx.api().admin.listMyTeams()).map((t) => ({ label: t.name, value: t.id, hint: t.id })));
9595
+ case "teamMember": {
9596
+ const teamId = text(ctx, "teamId");
9597
+ return listed(ctx, "team members", messageFor(input, "Team member"), async () => teamId ? (await ctx.api().admin.listTeamMembers(teamId)).filter((m) => !m.removedAt).map((m) => ({ label: m.name ?? m.email ?? m.userId, value: m.userId, hint: `${m.role} \xB7 ${m.userId}` })) : []);
9598
+ }
9599
+ case "projectMember": {
9600
+ const projectId = text(ctx, "projectId")?.split("/")[0];
9601
+ return listed(ctx, "project members", messageFor(input, "Project member"), async () => projectId ? (await ctx.api().admin.getProjectMembers(projectId)).map((m) => ({ label: m.userId, value: m.userId, hint: m.role })) : []);
9602
+ }
9603
+ case "teamInvitation": {
9604
+ const teamId = text(ctx, "teamId");
9605
+ return listed(ctx, "invitations", messageFor(input, "Invitation"), async () => teamId ? (await ctx.api().admin.listTeamInvitations(teamId)).map((i) => ({ label: i.email, value: i.invitationId, hint: `${i.role} \xB7 ${i.invitationId}` })) : []);
9606
+ }
9607
+ case "analysis":
9608
+ return askAnalysis(ctx, messageFor(input, "Analysis"));
9609
+ case "analysisRun": {
9610
+ const analysisId = text(ctx, "id") ?? await askAnalysis(ctx, "Analysis");
9611
+ return listed(ctx, "runs", messageFor(input, "Run"), async () => {
9612
+ const runs = await ctx.api().analysis.getRunsForAnalysis(analysisId, 20);
9613
+ const unfinished = (s) => !["COMPLETED", "FAILED", "CANCELLED"].includes(s);
9614
+ return [...runs].sort((a, b) => Number(unfinished(b.state)) - Number(unfinished(a.state))).map((r) => ({ label: r.state, value: r.runId, hint: `${when(r.submittedAt)} \xB7 ${r.runId}` }));
9615
+ });
9616
+ }
9617
+ case "preset":
9618
+ return listed(ctx, "presets", messageFor(input, "Preset"), async () => (await ctx.api().analysis.getPresets()).filter((p) => p.presetId).map((p) => ({ label: p.name, value: p.presetId, hint: p.presetId })));
9619
+ case "analysisTrigger": {
9620
+ const analysisId = text(ctx, "analysisId") ?? await askAnalysis(ctx, "Analysis");
9621
+ return listed(ctx, "triggers", messageFor(input, "Trigger"), async () => (await ctx.api().analysis.listTriggers(analysisId)).map((t) => ({
9622
+ label: `${t.kind} ${t.scheduleSpec}`,
9623
+ value: t.triggerId,
9624
+ hint: `${t.active ? "active" : "paused"} \xB7 ${t.triggerId}`
9625
+ })));
9626
+ }
9627
+ case "analysisColumns":
9628
+ return askColumns(ctx, spec, input);
9629
+ case "evaluation":
9630
+ return askEvaluation(ctx, input);
9631
+ case "functionTrigger": {
9632
+ const ref = entityRef(ctx, "ref");
9633
+ return listed(ctx, "triggers", messageFor(input, "Trigger"), async () => ref ? (await ctx.api().evaluation.getTriggers(ref.projectId, ref.projectBranch, ref.entityId, ref.entityBranch)).filter((t) => t.triggerId).map((t) => ({ label: `${t.type}${t.expression ? ` ${t.expression}` : ""}`, value: t.triggerId, hint: t.triggerId })) : []);
9634
+ }
9635
+ case "chatSession":
9636
+ return listed(ctx, "chat sessions", messageFor(input, "Chat session"), async () => (await ctx.api().language.getSessions()).map((s) => ({ label: s.title || "(untitled)", value: s.sessionId, hint: `${s.modified} \xB7 ${s.sessionId}` })));
9637
+ case "apiToken":
9638
+ return listed(ctx, "API tokens", messageFor(input, "API token"), async () => (await ctx.api().admin.getApiTokens()).map((t) => ({
9639
+ label: t.name,
9640
+ value: t.tokenId,
9641
+ hint: `${t.resourceType} ${t.resourceId} \xB7 ${t.scopes.join(",")}`
9642
+ })));
9643
+ case "tokenResource":
9644
+ return text(ctx, "resourceType")?.toLowerCase() === "team" ? listed(ctx, "teams", "Team", async () => (await ctx.api().admin.listMyTeams()).map((t) => ({ label: t.name, value: t.id, hint: t.id }))) : askProject(ctx, false, "Project");
9645
+ case "dataSource":
9646
+ return listed(ctx, "data sources", messageFor(input, "Data source"), async () => (await ctx.api().storage.listDataSources(defaultProject(ctx))).map((d) => ({ label: d.name, value: d.id, hint: `${d.type} \xB7 ${d.id}` })));
9647
+ case "dataSourceRun": {
9648
+ const id = text(ctx, "id");
9649
+ return listed(ctx, "runs", messageFor(input, "Run"), async () => id ? (await ctx.api().storage.listDataSourceRuns(id, 20)).map((r) => ({ label: r.status, value: r.runId, hint: `${r.startedAt ?? ""} \xB7 ${r.runId}` })) : []);
9650
+ }
9651
+ case "skeleton": {
9652
+ const projectId = defaultProject(ctx) ?? await askProject(ctx, false, "Project");
9653
+ return listed(ctx, "skeletons", messageFor(input, "Skeleton"), async () => (await ctx.api().storage.listSkeletons(projectId)).map((s) => ({ label: s.name, value: s.id, hint: `${s.template} \xB7 ${s.id}` })));
9654
+ }
9655
+ case "tableExporter":
9656
+ return listed(ctx, "exporters", messageFor(input, "Exporter"), async () => (await ctx.api().storage.listUserDefinedExporters()).filter((e) => e.id).map((e) => ({ label: e.name, value: e.id, hint: `${e.format} \xB7 ${e.id}` })));
9657
+ case "tableExport": {
9658
+ const ref = entityRef(ctx, "ref");
9659
+ return listed(ctx, "exports", messageFor(input, "Export"), async () => ref ? (await ctx.api().storage.listExports(ref)).map((e) => ({
9660
+ label: e.filename,
9661
+ value: e.exportId,
9662
+ hint: `${e.finished ? e.succeeded ? "done" : "failed" : `${Math.round(e.progress * 100)}%`} \xB7 ${e.exportId}`
9663
+ })) : []);
9664
+ }
9665
+ case "invoice":
9666
+ return listed(ctx, "invoices", messageFor(input, "Invoice"), async () => {
9667
+ const invoices = await ctx.api().admin.getInvoices();
9668
+ for (const i of invoices) ctx.prefill.set(`invoiceKind:${i.invoiceNumber}`, i.kind ?? "INVOICE");
9669
+ return invoices.map((i) => ({
9670
+ label: `#${i.invoiceNumber} ${i.periodFrom ?? ""}\u2013${i.periodTo ?? ""}`,
9671
+ value: String(i.invoiceNumber),
9672
+ hint: `${i.status ?? ""} \xB7 ${i.total ?? ""} ${i.currency ?? ""}`.trim()
9673
+ }));
9674
+ });
9675
+ case "invoiceDocument": {
9676
+ const number = text(ctx, "invoiceNumber");
9677
+ const kind = number ? ctx.prefill.get(`invoiceKind:${number}`) : void 0;
9678
+ const slug = kind && /credit/i.test(kind) ? "credit-note" : "invoice";
9679
+ return typed(ctx, messageFor(input, "Document file name"), { defaultValue: number ? `diafunc-${slug}-${number}.pdf` : void 0 });
9680
+ }
9681
+ case "projectBranch": {
9682
+ const projectId = text(ctx, spec.projectFrom)?.split("/")[0];
9683
+ return listed(ctx, "branches", messageFor(input, "Branch"), async () => projectId ? (await ctx.api().storage.getProjectBranches(projectId)).map((b) => ({ label: b, value: b })) : []);
9684
+ }
9685
+ case "event":
9686
+ return askEvent(ctx, input);
9687
+ case "occurrence": {
9688
+ const ref = entityRef(ctx, "ref");
9689
+ const eventId = text(ctx, "eventId");
9690
+ return listed(ctx, "occurrences", messageFor(input, "Occurrence"), async () => ref ? (await ctx.api().storage.getEvents(ref)).filter((e) => !eventId || e.eventId === eventId).map((e) => ({ label: e.occurrenceId, value: e.occurrenceId, hint: e.type })) : []);
9691
+ }
9692
+ case "link": {
9693
+ const ref = entityRef(ctx, "sourceRef");
9694
+ return listed(ctx, "links", messageFor(input, "Link"), async () => ref ? (await ctx.api().storage.getLinkIds("FORWARD", ref)).map((id) => ({ label: id, value: id })) : []);
9695
+ }
9696
+ case "exportFormat":
9697
+ return listed(ctx, "export formats", messageFor(input, "Export format"), async () => (await ctx.api().storage.getSupportedExportFormats()).formats.map((f) => ({ label: f.displayName, value: f.id, hint: `${f.id} \xB7 ${f.category}` })));
9698
+ case "connectorType":
9699
+ return listed(ctx, "connector types", messageFor(input, "Connector type"), async () => (await ctx.api().storage.listDataSourceConnectorTypes()).map((t) => ({ label: t, value: t })));
9700
+ case "profile":
9701
+ return listed(ctx, "profiles", messageFor(input, "Profile"), async () => Object.keys(loadConfig().profiles).map((p) => ({ label: p, value: p })));
9702
+ case "statusComponent":
9703
+ return listed(ctx, "components", messageFor(input, "Component"), async () => (await createStatusService().getComponents()).map((c) => ({ label: c.id, value: c.id, hint: `${c.state} \xB7 ${c.domainId}` })));
9704
+ case "choice":
9705
+ return choose(ctx, question(input), spec.choices.map((c) => ({ label: c, value: c })));
9706
+ case "choices": {
9707
+ const chosen = await ctx.prompter.checkbox({
9708
+ message: question(input),
9709
+ choices: spec.choices.map((c) => ({ name: c, value: c })),
9710
+ validate: (picked) => picked.length > 0 || "Pick at least one."
9711
+ });
9712
+ return chosen.join(",");
9713
+ }
9714
+ case "file":
9715
+ return typed(ctx, question(input), {
9716
+ validate: (value) => fs14.existsSync(value.trim()) || `No file at ${value.trim()}.`
9717
+ });
9718
+ case "number":
9719
+ return typed(ctx, question(input), { validate: numberRule(spec) });
9720
+ case "date":
9721
+ return typed(ctx, question(input), {
9722
+ defaultValue: currentUtcHour(),
9723
+ validate: (value) => /^\d{4}-\d{2}-\d{2}-\d{2}$/.test(value.trim()) || "Use YYYY-MM-DD-HH, in UTC."
9724
+ });
9725
+ case "text":
9726
+ return typed(ctx, question(input), {
9727
+ allowEmpty: spec.allowEmpty,
9728
+ defaultValue: spec.defaultValue,
9729
+ validate: spec.email ? (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim()) || "That is not an email address." : void 0
9730
+ });
9731
+ }
9732
+ }
9733
+ async function askProject(ctx, withBranch, message) {
9734
+ const projectId = await fromIndex(ctx, message, { contentType: "project" }, (item) => item.projectId);
9735
+ if (!withBranch) return projectId;
9736
+ let branches = [];
9737
+ try {
9738
+ branches = await ctx.api().storage.getProjectBranches(projectId);
9739
+ } catch {
9740
+ }
9741
+ if (branches.length <= 1) return projectId;
9742
+ const branch = await choose(ctx, "Branch", branches.map((b) => ({ label: b, value: b })), "main");
9743
+ return branch === "main" ? projectId : `${projectId}/${branch}`;
9744
+ }
9745
+ async function askEntity(ctx, spec, input) {
9746
+ const { projectId, projectBranch } = await projectContext(ctx, spec.projectFrom);
9747
+ const noun = spec.contentType ? capitalize(spec.contentType) : "Entity";
9748
+ const query = { contentType: spec.contentType, projectId, projectBranch };
9749
+ const answer = (item) => spec.form === "id" ? item.entityId : [item.projectId, item.projectBranch, item.entityId, ...item.entityBranch && item.entityBranch !== "main" ? [item.entityBranch] : []].join("/");
9750
+ if (spec.multiple) {
9751
+ let items = [];
9752
+ try {
9753
+ items = await indexItems(ctx, "*", query, 200);
9754
+ } catch (error) {
9755
+ ctx.note(`Could not list them (${reason(error)}).`);
9756
+ }
9757
+ if (items.length === 0) {
9758
+ const typed2 = await typedValue(ctx, `${question(input)} (space-separated)`);
9759
+ return typed2.split(/[\s,]+/).filter(Boolean);
9760
+ }
9761
+ return ctx.prompter.checkbox({
9762
+ message: messageFor(input, `${noun}s`),
9763
+ choices: items.map((item) => ({ name: labelled(item.name || item.entityId, item.entityId), value: answer(item) })),
9764
+ validate: (picked) => picked.length > 0 || "Pick at least one."
9765
+ });
9766
+ }
9767
+ return fromIndex(ctx, messageFor(input, noun), query, answer);
9768
+ }
9769
+ async function projectContext(ctx, projectFrom) {
9770
+ const config = loadConfig();
9771
+ const raw = (projectFrom ? text(ctx, projectFrom) : void 0) ?? ctx.globals.project ?? config.defaults.project ?? await askProject(ctx, true, "Project");
9772
+ const [projectId, branch] = raw.split("/");
9773
+ return { projectId, projectBranch: branch || ctx.globals.branch || config.defaults.branch || "main" };
9774
+ }
9775
+ var FIRST_PAGE = 100;
9776
+ async function fromIndex(ctx, message, query, answer) {
9777
+ let firstPage = null;
9778
+ let warned = false;
9779
+ const toChoice = (item) => ({
9780
+ name: labelled(item.name || item.entityId || item.projectId, item.entityId ?? item.projectId),
9781
+ value: answer(item)
9782
+ });
9783
+ const picked = await ctx.prompter.search({
9784
+ message,
9785
+ source: async (term) => {
9786
+ try {
9787
+ firstPage ??= await indexItems(ctx, "*", query, FIRST_PAGE);
9788
+ const needle = term.trim().toLowerCase();
9789
+ let items = needle ? firstPage.filter((item) => `${item.name ?? ""} ${item.entityId ?? item.projectId}`.toLowerCase().includes(needle)) : firstPage;
9790
+ if (needle && items.length === 0) items = await indexItems(ctx, term.trim(), query, 30);
9791
+ return [...items.map(toChoice), typeItChoice()];
9792
+ } catch (error) {
9793
+ if (!warned) ctx.note(`Could not search (${reason(error)}).`);
9794
+ warned = true;
9795
+ return [typeItChoice()];
9796
+ }
9797
+ }
9798
+ });
9799
+ return picked === TYPE_IT ? typedValue(ctx, message) : picked;
9800
+ }
9801
+ async function indexItems(ctx, term, query, limit) {
9802
+ const page = await ctx.api().index.searchPage({
9803
+ query: term,
9804
+ limit,
9805
+ contentType: query.contentType ?? null,
9806
+ projectId: query.projectId ?? null,
9807
+ projectBranch: query.projectId ? query.projectBranch ?? "main" : null
9808
+ });
9809
+ const seen = /* @__PURE__ */ new Set();
9810
+ return page.items.filter((item) => {
9811
+ if (query.contentType !== "project" && !item.entityId) return false;
9812
+ const key = [item.contentType, item.projectId, item.projectBranch, item.entityId, item.entityBranch].join("|");
9813
+ if (seen.has(key)) return false;
9814
+ seen.add(key);
9815
+ return true;
9816
+ });
9817
+ }
9818
+ async function askAnalysis(ctx, message) {
9819
+ return listed(ctx, "analyses", message, async () => (await ctx.api().analysis.getRecent(50)).map((a) => ({
9820
+ label: a.name,
9821
+ value: a.analysisId,
9822
+ hint: `${a.latestRunState ?? "never run"} \xB7 ${a.analysisId}`
9823
+ })));
9824
+ }
9825
+ async function askColumns(ctx, spec, input) {
9826
+ const analysisId = text(ctx, "id");
9827
+ let columns = [];
9828
+ try {
9829
+ if (analysisId) columns = (await ctx.api().analysis.getColumns(analysisId)).map((c) => c.name).filter(Boolean);
9830
+ } catch (error) {
9831
+ ctx.note(`Could not read the columns (${reason(error)}).`);
9832
+ }
9833
+ if (columns.length === 0) return typed(ctx, question(input), { allowEmpty: spec.allowEmpty });
9834
+ if (spec.multiple) {
9835
+ const chosen = await ctx.prompter.checkbox({
9836
+ message: messageFor(input, "Columns"),
9837
+ choices: columns.map((c) => ({ name: c, value: c })),
9838
+ validate: (picked) => picked.length > 0 || "Pick at least one column."
9839
+ });
9840
+ return chosen.join(",");
9841
+ }
9842
+ const items = columns.map((c) => ({ label: c, value: c }));
9843
+ if (spec.allowEmpty) items.unshift({ label: "None (clear it)", value: "" });
9844
+ return choose(ctx, messageFor(input, "Column"), items);
9845
+ }
9846
+ async function askEvaluation(ctx, input) {
9847
+ const ref = entityRef(ctx, "ref");
9848
+ const hour = parseHour(text(ctx, "date") ?? currentUtcHour());
9849
+ return listed(ctx, "evaluations in that hour", messageFor(input, "Evaluation"), async () => ref && hour ? (await ctx.api().evaluation.getEvaluations(
9850
+ ref.projectId,
9851
+ ref.projectBranch,
9852
+ ref.entityId,
9853
+ ref.entityBranch,
9854
+ hour.year,
9855
+ hour.month,
9856
+ hour.day,
9857
+ hour.hour
9858
+ )).map((e) => ({ label: e.evaluationId, value: e.evaluationId, hint: e.active ? "running" : "finished" })) : []);
9859
+ }
9860
+ async function askEvent(ctx, input) {
9861
+ const ref = entityRef(ctx, "ref");
9862
+ let events = [];
9863
+ try {
9864
+ if (ref) events = await ctx.api().storage.getEvents(ref);
9865
+ } catch (error) {
9866
+ ctx.note(`Could not list the events (${reason(error)}).`);
9867
+ }
9868
+ if (events.length === 0) return typedValue(ctx, question(input));
9869
+ const key = await choose(ctx, messageFor(input, "Event"), events.map((e) => ({
9870
+ label: `${e.type} ${e.eventId}`,
9871
+ value: `${e.eventId}\0${e.occurrenceId}`,
9872
+ hint: e.occurrenceId
9873
+ })));
9874
+ if (key === TYPE_IT || !key.includes("\0")) return key === TYPE_IT ? typedValue(ctx, question(input)) : key;
9875
+ const [eventId, occurrenceId] = key.split("\0");
9876
+ ctx.prefill.set("occurrenceId", occurrenceId);
9877
+ return eventId;
9878
+ }
9879
+ async function listed(ctx, noun, message, load) {
9880
+ let items;
9881
+ try {
9882
+ items = await load();
9883
+ } catch (error) {
9884
+ ctx.note(`Could not list ${noun} (${reason(error)}); type it instead.`);
9885
+ return typedValue(ctx, message);
9886
+ }
9887
+ if (items.length === 0) {
9888
+ ctx.note(`No ${noun} to choose from; type it instead.`);
9889
+ return typedValue(ctx, message);
9890
+ }
9891
+ const picked = await choose(ctx, message, items);
9892
+ return picked === TYPE_IT ? typedValue(ctx, message) : picked;
9893
+ }
9894
+ async function choose(ctx, message, items, defaultValue) {
9895
+ const choices = [
9896
+ ...items.map((i) => ({ name: labelled(i.label, i.hint), value: i.value })),
9897
+ typeItChoice()
9898
+ ];
9899
+ if (items.length > SEARCH_THRESHOLD) {
9900
+ return ctx.prompter.search({
9901
+ message,
9902
+ source: (term) => {
9903
+ const needle = term.trim().toLowerCase();
9904
+ if (!needle) return choices;
9905
+ return [
9906
+ ...choices.filter((c) => c.value !== TYPE_IT && `${c.name} ${c.value}`.toLowerCase().includes(needle)),
9907
+ typeItChoice()
9908
+ ];
9909
+ }
9910
+ });
9911
+ }
9912
+ return ctx.prompter.select({ message, choices, default: defaultValue });
9913
+ }
9914
+ async function typed(ctx, message, options = {}) {
9915
+ const value = await ctx.prompter.input({
9916
+ message,
9917
+ default: options.defaultValue,
9918
+ validate: (raw) => {
9919
+ if (!options.allowEmpty && raw.trim().length === 0) return "A value is required.";
9920
+ if (options.allowEmpty && raw.trim().length === 0) return true;
9921
+ return options.validate ? options.validate(raw) : true;
9922
+ }
9923
+ });
9924
+ return value.trim();
9925
+ }
9926
+ function typedValue(ctx, message) {
9927
+ return typed(ctx, message);
9928
+ }
9929
+ function typeItChoice() {
9930
+ return { name: chalk35.dim("Type it instead"), value: TYPE_IT };
9931
+ }
9932
+ function text(ctx, name) {
9933
+ const value = ctx.known.get(name);
9934
+ return typeof value === "string" && value.length > 0 ? value : void 0;
9935
+ }
9936
+ function entityRef(ctx, name) {
9937
+ const ref = text(ctx, name);
9938
+ if (!ref) return void 0;
9939
+ try {
9940
+ return parseEntityReference(ref, ctx.globals);
9941
+ } catch {
9942
+ return void 0;
9943
+ }
9944
+ }
9945
+ function defaultProject(ctx) {
9946
+ return (ctx.globals.project ?? loadConfig().defaults.project)?.split("/")[0];
9947
+ }
9948
+ function messageFor(input, noun) {
9949
+ const lead = /^(Source|Target)\b/.exec(input.description)?.[1];
9950
+ return lead ? `${lead} ${noun.toLowerCase()}` : noun;
9951
+ }
9952
+ function question(input) {
9953
+ const text2 = input.description.trim() || input.name;
9954
+ return capitalize(text2);
9955
+ }
9956
+ function capitalize(value) {
9957
+ return value.charAt(0).toUpperCase() + value.slice(1);
9958
+ }
9959
+ function labelled(label, hint2) {
9960
+ return hint2 && hint2 !== label ? `${label} ${chalk35.dim(hint2)}` : label;
9961
+ }
9962
+ function numberRule(spec) {
9963
+ return (raw) => {
9964
+ const value = Number(raw.trim());
9965
+ if (raw.trim() === "" || !Number.isFinite(value)) return "Enter a number.";
9966
+ if (spec.integer && !Number.isInteger(value)) return "Enter a whole number.";
9967
+ if (spec.exclusive ? value <= spec.min : value < spec.min) {
9968
+ return spec.exclusive ? `Enter a number above ${spec.min}.` : `Enter ${spec.min} or more.`;
9969
+ }
9970
+ return true;
9971
+ };
9972
+ }
9973
+ function currentUtcHour(now = /* @__PURE__ */ new Date()) {
9974
+ const iso = now.toISOString();
9975
+ return `${iso.slice(0, 10)}-${iso.slice(11, 13)}`;
9976
+ }
9977
+ function parseHour(value) {
9978
+ const match = /^(\d{4})-(\d{2})-(\d{2})-(\d{2})$/.exec(value.trim());
9979
+ if (!match) return null;
9980
+ return { year: Number(match[1]), month: Number(match[2]), day: Number(match[3]), hour: Number(match[4]) };
9981
+ }
9982
+ function when(epochMs) {
9983
+ return epochMs ? new Date(epochMs).toISOString().slice(0, 16).replace("T", " ") : "";
9984
+ }
9985
+ function reason(error) {
9986
+ return error instanceof Error ? error.message : String(error);
9987
+ }
9988
+
9989
+ // src/prompting/fill.ts
9990
+ async function fillPendingInputs(actionCommand) {
9991
+ const chain = commandChain(actionCommand);
9992
+ const owners = chain.filter((c) => c instanceof DiafuncCommand && c.pendingInputs.length > 0);
9993
+ if (owners.length === 0) return;
9994
+ const env = actionCommand.environment();
9995
+ const pending = owners.flatMap((owner) => owner.pendingInputs.splice(0).map((input) => ({
9996
+ owner,
9997
+ input,
9998
+ spec: specFor(pathOf(owner), input) ?? { kind: "text" }
9999
+ })));
10000
+ const ctx = {
10001
+ prompter: env.prompter ?? createInquirerPrompter(),
10002
+ api: memoize(env.api ?? (() => createApiClient())),
10003
+ known: knownValues(actionCommand),
10004
+ globals: actionCommand.optsWithGlobals(),
10005
+ prefill: /* @__PURE__ */ new Map(),
10006
+ note: (line) => process.stderr.write(chalk36.dim(` ${line}
10007
+ `))
10008
+ };
10009
+ for (const item of orderByDependencies(pending)) {
10010
+ const value = await askFor(item.spec, item.input, ctx);
10011
+ write(item.owner, item.input, value);
10012
+ ctx.known.set(item.input.name, value);
10013
+ }
10014
+ const log = env.log ?? ((line) => console.log(line));
10015
+ log(chalk36.dim(` Equivalent: ${equivalentCommand(actionCommand)}`));
10016
+ }
10017
+ function commandChain(cmd) {
10018
+ const chain = [];
10019
+ for (let c = cmd; c; c = c.parent) chain.unshift(c);
10020
+ return chain;
10021
+ }
10022
+ function pathOf(cmd) {
10023
+ return commandChain(cmd).slice(1).map((c) => c.name()).join(" ");
10024
+ }
10025
+ function knownValues(cmd) {
10026
+ const known = /* @__PURE__ */ new Map();
10027
+ for (const [key, value] of Object.entries(cmd.optsWithGlobals())) {
10028
+ if (value !== void 0) known.set(key, value);
10029
+ }
10030
+ cmd.registeredArguments.forEach((argument, i) => {
10031
+ const value = cmd.processedArgs[i];
10032
+ if (value !== void 0) known.set(argument.name(), value);
10033
+ });
10034
+ return known;
10035
+ }
10036
+ function orderByDependencies(pending) {
10037
+ const remaining = [...pending];
10038
+ const ordered = [];
10039
+ while (remaining.length > 0) {
10040
+ const waiting = new Set(remaining.map((p) => p.input.name));
10041
+ const index = remaining.findIndex((p) => dependencies(p.spec).every((name) => !waiting.has(name) || name === p.input.name));
10042
+ ordered.push(...remaining.splice(index === -1 ? 0 : index, 1));
10043
+ }
10044
+ return ordered;
10045
+ }
10046
+ function write(owner, input, value) {
10047
+ if (input.kind === "argument" && input.index !== void 0 && input.index >= 0) {
10048
+ owner.processedArgs[input.index] = value;
10049
+ } else {
10050
+ owner.setOptionValueWithSource(input.name, value, "cli");
10051
+ }
10052
+ }
10053
+ function memoize(make) {
10054
+ let made;
10055
+ return () => made ??= make();
10056
+ }
10057
+ function equivalentCommand(cmd) {
10058
+ const chain = commandChain(cmd);
10059
+ const tokens = [chain[0].name(), ...chain.slice(1).map((c) => c.name())];
10060
+ for (const value of cmd.processedArgs) {
10061
+ if (value === void 0) continue;
10062
+ for (const v of Array.isArray(value) ? value : [value]) tokens.push(quote(String(v)));
10063
+ }
10064
+ for (const c of chain) {
10065
+ for (const option of c.options) {
10066
+ const key = option.attributeName();
10067
+ if (c.getOptionValueSource(key) !== "cli" || !option.long) continue;
10068
+ const value = c.getOptionValue(key);
10069
+ if (typeof value === "boolean") {
10070
+ if (value === !option.negate) tokens.push(option.long);
10071
+ } else if (Array.isArray(value)) {
10072
+ for (const v of value) tokens.push(option.long, quote(String(v)));
10073
+ } else if (value !== void 0) {
10074
+ tokens.push(option.long, quote(String(value)));
10075
+ }
10076
+ }
10077
+ }
10078
+ return tokens.join(" ");
10079
+ }
10080
+ function quote(value) {
10081
+ if (/^[\w@%+=:,./-]+$/.test(value)) return value;
10082
+ return `'${value.replace(/'/g, `'\\''`)}'`;
10083
+ }
10084
+
8917
10085
  // src/index.ts
8918
10086
  var HELP_EPILOGUE = `
8919
10087
  Getting started:
@@ -8932,11 +10100,16 @@ Output:
8932
10100
  Add --output json for scripting, or pipe any command to get tab-separated fields.
8933
10101
  Add --verbose to see the requests, --dry-run to preview a mutation.
8934
10102
 
10103
+ Missing input:
10104
+ In a terminal, leave out a required argument and the command asks for it, offering
10105
+ your projects, tables, teams and the like to choose from. --no-interactive never asks.
10106
+
8935
10107
  Docs: https://diafunc.com/documentation
8936
10108
  `;
8937
- function createProgram() {
8938
- const program = new Command();
8939
- program.name("diafunc").description("Diafunc CLI \u2014 command-line interface for the Diafunc platform").version(package_default.version).option("-p, --profile <name>", "Profile to use").option("-o, --output <format>", "Output format: human, json, table (default: human)").option("--project <id>", "Default project ID override").option("--branch <name>", "Default branch override").option("--dry-run", "Preview mutating operations without executing them").option("--verbose", "Echo every HTTP request to stderr").option("--no-color", "Disable coloured output").showSuggestionAfterError().showHelpAfterError(`(run 'diafunc --help' to see the available commands)`).configureOutput({
10109
+ function createProgram(environment = {}) {
10110
+ const program = new DiafuncCommand();
10111
+ program.promptEnvironment = environment;
10112
+ program.name("diafunc").description("Diafunc CLI \u2014 command-line interface for the Diafunc platform").version(package_default.version).option("-p, --profile <name>", "Profile to use").option("-o, --output <format>", "Output format: human, json, table (default: human)").option("--project <id>", "Project to work in (overrides defaults.project)").option("--branch <name>", "Project branch (overrides defaults.branch)").option("--dry-run", "Preview mutating operations without executing them").option("--verbose", "Echo every HTTP request to stderr").option("--no-color", "Disable coloured output").option("--no-interactive", "Never prompt: a missing required input fails as it would in a script").showSuggestionAfterError().showHelpAfterError(`(run 'diafunc --help' to see the available commands)`).configureHelp({ showGlobalOptions: true }).configureOutput({
8940
10113
  // Commander writes usage errors to stdout by default, which puts a complaint in the middle
8941
10114
  // of whatever a caller was capturing.
8942
10115
  writeErr: (str) => process.stderr.write(str)
@@ -8944,8 +10117,8 @@ function createProgram() {
8944
10117
  const opts = thisCommand.optsWithGlobals();
8945
10118
  if (opts.dryRun) setDryRun(true);
8946
10119
  if (opts.verbose) setVerbose(true);
8947
- if (opts.color === false) chalk34.level = 0;
8948
- });
10120
+ if (opts.color === false) chalk37.level = 0;
10121
+ }).hook("preAction", (_thisCommand, actionCommand) => fillPendingInputs(actionCommand));
8949
10122
  program.addHelpText("after", HELP_EPILOGUE);
8950
10123
  registerAuthCommands(program);
8951
10124
  registerConfigCommands(program);
@@ -8981,6 +10154,9 @@ function createProgram() {
8981
10154
  }
8982
10155
 
8983
10156
  export {
10157
+ EXIT_CANCELLED,
10158
+ handleError,
10159
+ PromptCancelled,
8984
10160
  createProgram
8985
10161
  };
8986
- //# sourceMappingURL=chunk-XRUDG6ZY.js.map
10162
+ //# sourceMappingURL=chunk-4NQYIRPF.js.map