@diafunc/cli 0.18.0 → 0.20.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,9 +1,9 @@
1
1
  import {
2
2
  package_default
3
- } from "./chunk-JG3FMXGU.js";
3
+ } from "./chunk-V2VLVFWP.js";
4
4
 
5
5
  // src/index.ts
6
- import chalk36 from "chalk";
6
+ import chalk37 from "chalk";
7
7
 
8
8
  // src/commands/auth/login.ts
9
9
  import chalk4 from "chalk";
@@ -124,8 +124,8 @@ var REQUEST_TIMEOUT_MS = 6e4;
124
124
  var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
125
125
  var MAX_ATTEMPTS = 3;
126
126
  var RETRYABLE_METHODS = /* @__PURE__ */ new Set(["GET"]);
127
- function buildUrl(endpoint, service, path11, query) {
128
- const base = `${endpoint}/api/v1/${service}${path11}`;
127
+ function buildUrl(endpoint, service, path12, query) {
128
+ const base = `${endpoint}/api/v1/${service}${path12}`;
129
129
  const params = new URLSearchParams();
130
130
  if (query) {
131
131
  for (const [key, value] of Object.entries(query)) {
@@ -1510,6 +1510,7 @@ var SERVICE2 = "analyses";
1510
1510
  var RUNS_SERVICE = "runs";
1511
1511
  var PRESETS_SERVICE = "analysis-presets";
1512
1512
  var TRIGGERS_SERVICE = "triggers";
1513
+ var PUBLIC_SERVICE = "public-analyses";
1513
1514
  function createAnalysisService(client) {
1514
1515
  return {
1515
1516
  // ----- Lifecycle: create / read / replace / delete --------------------------------
@@ -1558,6 +1559,16 @@ function createAnalysisService(client) {
1558
1559
  path: `/${encodeURIComponent(analysisId)}`
1559
1560
  });
1560
1561
  },
1562
+ // ----- Public analyses: readable without signing in --------------------------------
1563
+ /** One page of the public analyses. `cursor` is the `nextCursor` of the page before. */
1564
+ async listPublic(page = {}) {
1565
+ return client.request({
1566
+ method: "GET",
1567
+ service: PUBLIC_SERVICE,
1568
+ path: "",
1569
+ query: { cursor: page.cursor, limit: page.limit }
1570
+ });
1571
+ },
1561
1572
  // ----- Typed PATCH per editable field --------------------------------------------
1562
1573
  async patchName(analysisId, request) {
1563
1574
  return client.request({
@@ -1656,6 +1667,46 @@ function createAnalysisService(client) {
1656
1667
  rawBody: formData
1657
1668
  });
1658
1669
  },
1670
+ // ----- Several files: sources ------------------------------------------------------
1671
+ async addSource(analysisId, formData) {
1672
+ return client.request({
1673
+ method: "POST",
1674
+ service: SERVICE2,
1675
+ path: `/${encodeURIComponent(analysisId)}/sources`,
1676
+ rawBody: formData
1677
+ });
1678
+ },
1679
+ async listSources(analysisId) {
1680
+ return client.request({
1681
+ method: "GET",
1682
+ service: SERVICE2,
1683
+ path: `/${encodeURIComponent(analysisId)}/sources`
1684
+ });
1685
+ },
1686
+ async removeSource(analysisId, sourceId) {
1687
+ return client.request({
1688
+ method: "DELETE",
1689
+ service: SERVICE2,
1690
+ path: `/${encodeURIComponent(analysisId)}/sources/${encodeURIComponent(sourceId)}`
1691
+ });
1692
+ },
1693
+ /** What building from the sources would yield: for `recipe`, or for the platform's proposal when it is null. */
1694
+ async planSources(analysisId, recipe) {
1695
+ return client.request({
1696
+ method: "POST",
1697
+ service: SERVICE2,
1698
+ path: `/${encodeURIComponent(analysisId)}/sources/plan`,
1699
+ body: recipe
1700
+ });
1701
+ },
1702
+ async buildSources(analysisId, recipe) {
1703
+ return client.request({
1704
+ method: "POST",
1705
+ service: SERVICE2,
1706
+ path: `/${encodeURIComponent(analysisId)}/sources/build`,
1707
+ body: recipe
1708
+ });
1709
+ },
1659
1710
  async uploadDataUrl(analysisId, request) {
1660
1711
  return client.request({
1661
1712
  method: "POST",
@@ -1672,6 +1723,22 @@ function createAnalysisService(client) {
1672
1723
  body: request
1673
1724
  });
1674
1725
  },
1726
+ /** How the import of the analysis's data stands. `dataImport` null means it finished and the counts are final. */
1727
+ async getDataImport(analysisId) {
1728
+ return client.request({
1729
+ method: "GET",
1730
+ service: SERVICE2,
1731
+ path: `/${encodeURIComponent(analysisId)}/data/import`
1732
+ });
1733
+ },
1734
+ /** Stops the running import. The platform waits a while for it to end and answers `STOPPING` when it has not yet. */
1735
+ async stopDataImport(analysisId) {
1736
+ return client.request({
1737
+ method: "DELETE",
1738
+ service: SERVICE2,
1739
+ path: `/${encodeURIComponent(analysisId)}/data/import`
1740
+ });
1741
+ },
1675
1742
  async getColumns(analysisId) {
1676
1743
  return client.request({
1677
1744
  method: "GET",
@@ -1951,14 +2018,14 @@ function createStorageService(client) {
1951
2018
  });
1952
2019
  },
1953
2020
  async deleteLink(projectId, projectBranch, sourceEntityId, sourceEntityBranch, linkId, targetEntityId, targetEntityBranch) {
1954
- let path11 = `/links/actual/${enc(projectId)}/${enc(projectBranch)}/${enc(sourceEntityId)}/${enc(sourceEntityBranch)}/${enc(linkId)}`;
2021
+ let path12 = `/links/actual/${enc(projectId)}/${enc(projectBranch)}/${enc(sourceEntityId)}/${enc(sourceEntityBranch)}/${enc(linkId)}`;
1955
2022
  if (targetEntityId && targetEntityBranch) {
1956
- path11 += `/${enc(targetEntityId)}/${enc(targetEntityBranch)}`;
2023
+ path12 += `/${enc(targetEntityId)}/${enc(targetEntityBranch)}`;
1957
2024
  }
1958
2025
  return client.request({
1959
2026
  method: "DELETE",
1960
2027
  service: SERVICE3,
1961
- path: path11
2028
+ path: path12
1962
2029
  });
1963
2030
  },
1964
2031
  // --- Events ---
@@ -2750,7 +2817,8 @@ function createIndexService(client) {
2750
2817
  cursor: query.cursor ?? void 0,
2751
2818
  contentType: query.contentType ?? void 0,
2752
2819
  projectId: query.projectId ?? void 0,
2753
- projectBranch: query.projectBranch ?? void 0
2820
+ projectBranch: query.projectBranch ?? void 0,
2821
+ sort: query.sort && query.sort !== "best" ? query.sort : void 0
2754
2822
  }
2755
2823
  });
2756
2824
  },
@@ -2994,8 +3062,8 @@ Examples:
2994
3062
  success(`Profile "${name}" removed.`);
2995
3063
  });
2996
3064
  }
2997
- function setNestedValue(obj, path11, value) {
2998
- const keys = path11.split(".");
3065
+ function setNestedValue(obj, path12, value) {
3066
+ const keys = path12.split(".");
2999
3067
  let current = obj;
3000
3068
  for (let i = 0; i < keys.length - 1; i++) {
3001
3069
  const key = keys[i];
@@ -3006,8 +3074,8 @@ function setNestedValue(obj, path11, value) {
3006
3074
  }
3007
3075
  current[keys[keys.length - 1]] = value;
3008
3076
  }
3009
- function getNestedValue(obj, path11) {
3010
- const keys = path11.split(".");
3077
+ function getNestedValue(obj, path12) {
3078
+ const keys = path12.split(".");
3011
3079
  let current = obj;
3012
3080
  for (const key of keys) {
3013
3081
  if (current === null || current === void 0 || typeof current !== "object") {
@@ -3365,17 +3433,17 @@ async function projectNames(api, projectIds) {
3365
3433
  const wanted = new Set(projectIds);
3366
3434
  const names = /* @__PURE__ */ new Map();
3367
3435
  if (wanted.size === 0) return names;
3368
- const take = (items) => {
3436
+ const take2 = (items) => {
3369
3437
  for (const item of items) {
3370
3438
  if (item.contentType !== "project" || !item.name || !wanted.has(item.projectId)) continue;
3371
3439
  if (!names.has(item.projectId)) names.set(item.projectId, item.name);
3372
3440
  }
3373
3441
  };
3374
- take((await api.index.searchPage({ query: "*", contentType: "project", limit: FIRST_PAGE })).items);
3442
+ take2((await api.index.searchPage({ query: "*", contentType: "project", limit: FIRST_PAGE })).items);
3375
3443
  const missing = [...wanted].filter((id) => !names.has(id));
3376
3444
  for (let i = 0; i < missing.length; i += CONCURRENCY) {
3377
3445
  const pages = await Promise.all(missing.slice(i, i + CONCURRENCY).map((projectId) => api.index.searchPage({ query: "*", contentType: "project", projectId, projectBranch: "main", limit: 5 }).catch(() => null)));
3378
- for (const page of pages) if (page) take(page.items);
3446
+ for (const page of pages) if (page) take2(page.items);
3379
3447
  }
3380
3448
  return names;
3381
3449
  }
@@ -4391,8 +4459,8 @@ function registerEventCommands(program) {
4391
4459
  });
4392
4460
  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) => {
4393
4461
  try {
4394
- const fs15 = await import("fs");
4395
- const body = file ? fs15.readFileSync(file, "utf-8") : await new Promise((resolve, reject) => {
4462
+ const fs16 = await import("fs");
4463
+ const body = file ? fs16.readFileSync(file, "utf-8") : await new Promise((resolve, reject) => {
4396
4464
  let data = "";
4397
4465
  process.stdin.setEncoding("utf-8");
4398
4466
  process.stdin.on("data", (chunk) => {
@@ -6219,7 +6287,7 @@ var HELP = [
6219
6287
  ];
6220
6288
  async function runChatRepl(options) {
6221
6289
  const { input: promptInput } = await import("@inquirer/prompts");
6222
- const { getUpdateNotice } = await import("./update-check-HMBNFIA5.js");
6290
+ const { getUpdateNotice } = await import("./update-check-7F4ABBDC.js");
6223
6291
  let sessionId = options.session;
6224
6292
  let lastReportedSession;
6225
6293
  console.log(chalk19.bold("Diafunc chat") + chalk19.dim(" \xB7 /help for commands, /quit to exit"));
@@ -6509,14 +6577,23 @@ function getOutputFormat13(cmd) {
6509
6577
  const globalOpts = cmd.optsWithGlobals();
6510
6578
  return globalOpts.output ?? config.defaults.output ?? "human";
6511
6579
  }
6580
+ function parseSort(raw) {
6581
+ if (raw === "best" || raw === "newest") return raw;
6582
+ return usageError(`Unknown sort "${raw}".`, "Use --sort best or --sort newest.");
6583
+ }
6512
6584
  function registerSearchCommands(program) {
6513
- 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", `
6585
+ 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").option("--sort <order>", "Order of equally relevant results: best (model quality) or newest", "best").addHelpText("after", `
6514
6586
  Examples:
6515
6587
  $ diafunc search "housing" everything matching, across projects
6516
6588
  $ diafunc search "housing" --type project only projects
6517
6589
  $ diafunc search "medv" --project <id> only inside one project
6590
+ $ diafunc search "housing" --sort newest most recently changed first among equal matches
6518
6591
  $ diafunc search "housing" --output json for scripting
6592
+
6593
+ Results are ordered by how well they match. Among results that match equally well, the project
6594
+ whose discovered model has the better quality comes first; inside one project the newer one does.
6519
6595
  `).action(async (query, options, cmd) => {
6596
+ const sort = parseSort(options.sort);
6520
6597
  try {
6521
6598
  const outputFormat = getOutputFormat13(cmd);
6522
6599
  const overrides = cmd.optsWithGlobals();
@@ -6529,7 +6606,8 @@ Examples:
6529
6606
  limit: Number.isFinite(limit) && limit > 0 ? limit : 20,
6530
6607
  contentType: options.type ?? null,
6531
6608
  projectId,
6532
- projectBranch: projectId ? overrides.branch ?? config.defaults.branch ?? "main" : null
6609
+ projectBranch: projectId ? overrides.branch ?? config.defaults.branch ?? "main" : null,
6610
+ sort
6533
6611
  });
6534
6612
  const items = dedupe(page.items);
6535
6613
  if (outputFormat === "json") {
@@ -6548,6 +6626,7 @@ Examples:
6548
6626
  columns: [
6549
6627
  { key: "contentType", header: "type" },
6550
6628
  { key: "name" },
6629
+ { key: "quality" },
6551
6630
  { key: "projectId", kind: "id" },
6552
6631
  { key: "entityId", kind: "id" }
6553
6632
  ]
@@ -6576,7 +6655,7 @@ function renderResults(items) {
6576
6655
  for (const item of items) {
6577
6656
  const name = item.name || "(unnamed)";
6578
6657
  console.log();
6579
- console.log(`${chalk20.dim(`[${item.contentType}]`)} ${chalk20.bold(name)}`);
6658
+ console.log(`${chalk20.dim(`[${item.contentType}]`)} ${chalk20.bold(name)}${qualityNote(item)}`);
6580
6659
  const raw = item.snippetField === "name" ? item.description : item.snippet ?? item.description;
6581
6660
  const line = raw ? collapse(raw) : null;
6582
6661
  if (line && stripHighlight(line) !== name) console.log(` ${highlight(line)}`);
@@ -6585,6 +6664,12 @@ function renderResults(items) {
6585
6664
  }
6586
6665
  console.log();
6587
6666
  }
6667
+ function qualityNote(item) {
6668
+ if (item.contentType !== "project" || typeof item.quality !== "number" || !Number.isFinite(item.quality)) {
6669
+ return "";
6670
+ }
6671
+ return chalk20.dim(` quality ${percent(item.quality).trim()}`);
6672
+ }
6588
6673
  var HIGHLIGHT_OPEN = /<mark>/g;
6589
6674
  var HIGHLIGHT_CLOSE = /<\/mark>/g;
6590
6675
  function highlight(text2) {
@@ -6811,8 +6896,8 @@ import chalk21 from "chalk";
6811
6896
  function createStatusService() {
6812
6897
  const config = loadConfig();
6813
6898
  const endpoint = resolveEndpoint(config);
6814
- async function fetchJson(path11) {
6815
- const url = `${endpoint}/status/v1${path11}`;
6899
+ async function fetchJson(path12) {
6900
+ const url = `${endpoint}/status/v1${path12}`;
6816
6901
  const response = await fetch(url, {
6817
6902
  headers: { "Accept": "application/json" }
6818
6903
  });
@@ -7010,8 +7095,8 @@ Examples:
7010
7095
  }
7011
7096
 
7012
7097
  // src/commands/analyze/index.ts
7013
- import * as fs8 from "fs";
7014
- import * as path7 from "path";
7098
+ import * as fs9 from "fs";
7099
+ import * as path8 from "path";
7015
7100
  import { spawn as spawn2 } from "child_process";
7016
7101
 
7017
7102
  // src/commands/analyze/watch-view.ts
@@ -7031,12 +7116,25 @@ var RUN_PHASE_LABELS = {
7031
7116
  var RUN_STEPS = ["PREPARING", "PROFILING", "DISCOVERING", "EXPLAINING", "WRITING"];
7032
7117
  var STARTING = "Starting";
7033
7118
  function phaseLabel(run) {
7034
- if (run.state === "QUEUED") return RUN_PHASE_LABELS.QUEUED;
7119
+ if (run.state === "QUEUED") return waitLabel(run);
7035
7120
  if (run.state === "DISPATCHING") return STARTING;
7036
7121
  if (run.phase && RUN_PHASE_LABELS[run.phase]) return RUN_PHASE_LABELS[run.phase];
7037
7122
  if (run.state === "RUNNING" && !((run.progressTotal ?? 0) > 0)) return RUN_PHASE_LABELS.PREPARING;
7038
7123
  return run.state.charAt(0) + run.state.slice(1).toLowerCase();
7039
7124
  }
7125
+ function waitLabel(run) {
7126
+ switch (run.waitReason) {
7127
+ case "OWN_RUNS":
7128
+ return "Waiting for one of your analyses to finish";
7129
+ case "PLATFORM_BUSY":
7130
+ return "Waiting for a free slot";
7131
+ default:
7132
+ return RUN_PHASE_LABELS.QUEUED;
7133
+ }
7134
+ }
7135
+ function waitCell(run) {
7136
+ return run.waitReason === "OWN_RUNS" ? "Waiting for your runs" : RUN_PHASE_LABELS.QUEUED;
7137
+ }
7040
7138
  function stepCounter(run) {
7041
7139
  if (!run.phase) return null;
7042
7140
  const index = RUN_STEPS.indexOf(run.phase);
@@ -7045,7 +7143,8 @@ function stepCounter(run) {
7045
7143
  }
7046
7144
  function runPhaseCell(run) {
7047
7145
  if (run.state === "COMPLETED") return null;
7048
- if (run.state === "QUEUED" || run.state === "DISPATCHING") return phaseLabel(run);
7146
+ if (run.state === "QUEUED") return waitCell(run);
7147
+ if (run.state === "DISPATCHING") return phaseLabel(run);
7049
7148
  if (run.phase && RUN_PHASE_LABELS[run.phase]) return RUN_PHASE_LABELS[run.phase];
7050
7149
  return null;
7051
7150
  }
@@ -7091,6 +7190,14 @@ function terminalSentence(state, duration, credits = null) {
7091
7190
  return `Analysis failed after ${duration}${cost}.`;
7092
7191
  }
7093
7192
  }
7193
+ function isImporting(dataImport) {
7194
+ return dataImport?.state === "IMPORTING" || dataImport?.state === "STOPPING";
7195
+ }
7196
+ function importingLabel(dataImport) {
7197
+ const progress = dataImport.progress;
7198
+ if (progress === null || progress === void 0 || !Number.isFinite(progress)) return "Importing data";
7199
+ return `Importing data, ${Math.floor(Math.max(0, Math.min(progress, 1)) * 100)} %`;
7200
+ }
7094
7201
 
7095
7202
  // src/commands/analyze/watch-view.ts
7096
7203
  function overallProgress(run) {
@@ -7157,6 +7264,178 @@ function renderWatchBlock(input) {
7157
7264
 
7158
7265
  // src/commands/analyze/wizard.ts
7159
7266
  import chalk25 from "chalk";
7267
+
7268
+ // src/commands/analyze/columns.ts
7269
+ var MAX_COLUMNS_LISTED = 30;
7270
+ var MAX_NEAR_MATCHES = 3;
7271
+ function parseColumnList(text2) {
7272
+ const names = [];
7273
+ let i = 0;
7274
+ while (i < text2.length) {
7275
+ while (i < text2.length && isSpace(text2[i])) i++;
7276
+ if (i >= text2.length) break;
7277
+ if (text2[i] === '"') {
7278
+ let name = "";
7279
+ let closed = false;
7280
+ i++;
7281
+ while (i < text2.length) {
7282
+ if (text2[i] === '"' && text2[i + 1] === '"') {
7283
+ name += '"';
7284
+ i += 2;
7285
+ } else if (text2[i] === '"') {
7286
+ closed = true;
7287
+ i++;
7288
+ break;
7289
+ } else {
7290
+ name += text2[i++];
7291
+ }
7292
+ }
7293
+ if (!closed) {
7294
+ throw new CliError(`A double quote is opened and never closed in: ${text2}`, {
7295
+ exitCode: EXIT_USAGE,
7296
+ hint: QUOTING_HINT
7297
+ });
7298
+ }
7299
+ while (i < text2.length && isSpace(text2[i])) i++;
7300
+ if (i < text2.length && text2[i] !== ",") {
7301
+ throw new CliError(`Text follows a closing double quote without a comma in: ${text2}`, {
7302
+ exitCode: EXIT_USAGE,
7303
+ hint: QUOTING_HINT
7304
+ });
7305
+ }
7306
+ i++;
7307
+ if (name.length > 0) names.push(name);
7308
+ } else {
7309
+ const end = text2.indexOf(",", i);
7310
+ const name = text2.slice(i, end === -1 ? text2.length : end).trim();
7311
+ i = end === -1 ? text2.length : end + 1;
7312
+ if (name.length > 0) names.push(name);
7313
+ }
7314
+ }
7315
+ return names;
7316
+ }
7317
+ var QUOTING_HINT = `Inside a list, put a name that contains a comma in double quotes and write a quote in it twice: '"a, b",c'.`;
7318
+ function isSpace(char) {
7319
+ return char === " " || char === " ";
7320
+ }
7321
+ function quoteColumn(name) {
7322
+ return `"${name.replace(/"/g, '""')}"`;
7323
+ }
7324
+ function loose(name) {
7325
+ return name.trim().toLowerCase();
7326
+ }
7327
+ function matchColumn(name, columns) {
7328
+ if (columns.includes(name)) return { kind: "column", column: name };
7329
+ const wanted = loose(name);
7330
+ const candidates = columns.filter((column) => loose(column) === wanted);
7331
+ if (candidates.length === 1) return { kind: "column", column: candidates[0] };
7332
+ return candidates.length > 1 ? { kind: "ambiguous", candidates } : { kind: "unknown" };
7333
+ }
7334
+ function nearMatches(name, columns) {
7335
+ const wanted = loose(name);
7336
+ if (wanted.length === 0) return [];
7337
+ return columns.map((column) => ({ column, distance: distanceTo(wanted, loose(column)) })).filter((scored) => scored.distance !== null).sort((a, b) => a.distance - b.distance).slice(0, MAX_NEAR_MATCHES).map((scored) => scored.column);
7338
+ }
7339
+ function distanceTo(wanted, column) {
7340
+ const edits = editDistance(wanted, column);
7341
+ if (edits <= Math.max(1, Math.floor(Math.min(wanted.length, column.length) / 4))) return edits;
7342
+ if (wanted.length >= 3 && (column.includes(wanted) || wanted.includes(column)) && column.length > 0) {
7343
+ return 100 + Math.abs(column.length - wanted.length);
7344
+ }
7345
+ return null;
7346
+ }
7347
+ function editDistance(a, b) {
7348
+ let previous = Array.from({ length: b.length + 1 }, (_, j) => j);
7349
+ for (let i = 1; i <= a.length; i++) {
7350
+ const current = [i];
7351
+ for (let j = 1; j <= b.length; j++) {
7352
+ current[j] = Math.min(
7353
+ previous[j] + 1,
7354
+ current[j - 1] + 1,
7355
+ previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
7356
+ );
7357
+ }
7358
+ previous = current;
7359
+ }
7360
+ return previous[b.length];
7361
+ }
7362
+ function take(name, columns, into, problems) {
7363
+ const match = matchColumn(name, columns);
7364
+ if (match.kind === "column") {
7365
+ if (!into.includes(match.column)) into.push(match.column);
7366
+ return true;
7367
+ }
7368
+ if (match.kind === "ambiguous") problems.ambiguous.push({ name, candidates: match.candidates });
7369
+ else problems.unknown.push(name);
7370
+ return false;
7371
+ }
7372
+ function refuse(problems, columns, analysisId) {
7373
+ const sentences = [];
7374
+ if (problems.unknown.length === 1) {
7375
+ sentences.push(`${quoteColumn(problems.unknown[0])} is not a column of the analysis data.`);
7376
+ } else if (problems.unknown.length > 1) {
7377
+ sentences.push(`These are not columns of the analysis data: ${problems.unknown.map(quoteColumn).join(", ")}.`);
7378
+ }
7379
+ for (const { name, candidates } of problems.ambiguous) {
7380
+ sentences.push(`${quoteColumn(name)} matches more than one column: ${candidates.map(quoteColumn).join(", ")}. Type the one you mean exactly.`);
7381
+ }
7382
+ const hints = [];
7383
+ const near = [...new Set(problems.unknown.flatMap((name) => nearMatches(name, columns)))];
7384
+ if (near.length > 0) hints.push(`Did you mean ${near.map(quoteColumn).join(" or ")}?`);
7385
+ const listed2 = columns.slice(0, MAX_COLUMNS_LISTED).map(quoteColumn).join(", ");
7386
+ const more = columns.length > MAX_COLUMNS_LISTED ? ` and ${columns.length - MAX_COLUMNS_LISTED} more${analysisId ? ` ('diafunc analyze columns ${analysisId}' lists them all)` : ""}` : "";
7387
+ hints.push(`The columns are: ${listed2}${more}.`);
7388
+ if (problems.fromList) {
7389
+ hints.push(`A name that contains a comma is an argument of its own, or goes in double quotes inside a list: '"a, b",c'.`);
7390
+ }
7391
+ throw new CliError(sentences.join(" "), { exitCode: EXIT_USAGE, hint: hints.join("\n ") });
7392
+ }
7393
+ function resolveColumnArguments(given, columns, analysisId) {
7394
+ const resolved = [];
7395
+ if (columns.length === 0) {
7396
+ for (const name of given.flatMap(parseColumnList)) {
7397
+ if (!resolved.includes(name)) resolved.push(name);
7398
+ }
7399
+ return resolved;
7400
+ }
7401
+ const problems = { unknown: [], ambiguous: [], fromList: false };
7402
+ for (const argument of given) {
7403
+ if (argument.trim().length === 0) continue;
7404
+ const whole = matchColumn(argument, columns);
7405
+ if (whole.kind === "column") {
7406
+ if (!resolved.includes(whole.column)) resolved.push(whole.column);
7407
+ continue;
7408
+ }
7409
+ const names = parseColumnList(argument);
7410
+ const single = names.length === 1 && names[0] === argument.trim();
7411
+ for (const name of names) {
7412
+ if (!take(name, columns, resolved, problems) && !single) problems.fromList = true;
7413
+ }
7414
+ }
7415
+ if (problems.unknown.length > 0 || problems.ambiguous.length > 0) refuse(problems, columns, analysisId);
7416
+ return resolved;
7417
+ }
7418
+ function resolveColumnNames(names, columns, analysisId) {
7419
+ if (columns.length === 0) return [...names];
7420
+ const resolved = [];
7421
+ const problems = { unknown: [], ambiguous: [], fromList: false };
7422
+ for (const name of names) take(name, columns, resolved, problems);
7423
+ if (problems.unknown.length > 0 || problems.ambiguous.length > 0) refuse(problems, columns, analysisId);
7424
+ return resolved;
7425
+ }
7426
+ function resolveColumnArgument(given, columns, analysisId) {
7427
+ if (columns.length === 0) return given;
7428
+ return resolveColumnNames([given], columns, analysisId)[0];
7429
+ }
7430
+ function occurrences(value) {
7431
+ if (value === void 0) return void 0;
7432
+ return Array.isArray(value) ? value : [value];
7433
+ }
7434
+ function collectColumns(value, previous = []) {
7435
+ return previous.concat([value]);
7436
+ }
7437
+
7438
+ // src/commands/analyze/wizard.ts
7160
7439
  var DEPTH_PRESETS = [
7161
7440
  { name: "Express", hours: "1", budget: "500" },
7162
7441
  { name: "Quick", hours: "2", budget: "2000" },
@@ -7243,10 +7522,16 @@ async function promptRunFields(prompter, options) {
7243
7522
  });
7244
7523
  } else {
7245
7524
  const typed2 = await prompter.input({
7246
- message: "Target column names (comma-separated)",
7247
- validate: (value) => splitCsv(value).length > 0 || "Name at least one target column."
7525
+ message: "Target column names (comma-separated; a name that contains a comma goes in double quotes)",
7526
+ validate: (value) => {
7527
+ try {
7528
+ return parseColumnList(value).length > 0 || "Name at least one target column.";
7529
+ } catch (error) {
7530
+ return error instanceof Error ? error.message : String(error);
7531
+ }
7532
+ }
7248
7533
  });
7249
- targets = splitCsv(typed2);
7534
+ targets = parseColumnList(typed2);
7250
7535
  }
7251
7536
  }
7252
7537
  const remaining = named.filter((c) => !targets.includes(c.name));
@@ -7305,9 +7590,9 @@ async function promptRunFields(prompter, options) {
7305
7590
  }
7306
7591
  if (hours === void 0) {
7307
7592
  hours = await prompter.input({
7308
- message: "Computation time (hours)",
7593
+ message: "Time budget (hours)",
7309
7594
  default: DEFAULT_HOURS,
7310
- validate: positiveNumber("Computation time")
7595
+ validate: positiveNumber("Time budget")
7311
7596
  });
7312
7597
  }
7313
7598
  if (budget === void 0) {
@@ -7346,9 +7631,6 @@ function summaryLines(creation, run) {
7346
7631
  lines.push(`Depth: ${named}${run.hours}h \xB7 ${run.budget} credits`);
7347
7632
  return lines;
7348
7633
  }
7349
- function splitCsv(value) {
7350
- return value.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
7351
- }
7352
7634
  function missingRunFields(recipe) {
7353
7635
  const missing = [];
7354
7636
  if (!recipe.hours || recipe.hours.trim().length === 0) missing.push("hours");
@@ -7368,7 +7650,7 @@ function suppliedFromAnalysis(analysis) {
7368
7650
  var FIELD_COMMANDS = {
7369
7651
  hours: "hours <id> <hours>",
7370
7652
  budget: "budget <id> <credits>",
7371
- targets: "targets <id> <csv>"
7653
+ targets: "targets <id> <column...>"
7372
7654
  };
7373
7655
  function explainMissingRunFields(analysisId, missing, reason2) {
7374
7656
  const commands = missing.map((f) => `'diafunc analyze ${FIELD_COMMANDS[f].replace("<id>", analysisId)}'`);
@@ -7438,6 +7720,9 @@ function whyNoPrompt(outputFormat, noInteractive) {
7438
7720
  return "there is no terminal to ask";
7439
7721
  }
7440
7722
 
7723
+ // src/commands/analyze/data-import.ts
7724
+ import chalk26 from "chalk";
7725
+
7441
7726
  // src/commands/analyze/details.ts
7442
7727
  function analysisDetails(analysis, endpoint) {
7443
7728
  const data = {
@@ -7447,6 +7732,7 @@ function analysisDetails(analysis, endpoint) {
7447
7732
  visibility: sentenceCase(analysis.visibility),
7448
7733
  introduction: analysis.introduction,
7449
7734
  data: dataShape(analysis.rowCount, analysis.columnCount),
7735
+ dataImport: analysis.dataImport?.message ?? null,
7450
7736
  targets: analysis.targets,
7451
7737
  targetKinds: analysis.targetKinds && Object.keys(analysis.targetKinds).length > 0 ? analysis.targetKinds : "detected from the data",
7452
7738
  featureExclusions: analysis.featureExclusions,
@@ -7457,7 +7743,8 @@ function analysisDetails(analysis, endpoint) {
7457
7743
  budget: creditsText(analysis.budget),
7458
7744
  constraints: constraintsText(analysis),
7459
7745
  notifyByEmail: analysis.notifyByEmail == null ? "account default" : analysis.notifyByEmail ? "yes" : "no",
7460
- latestRunState: analysis.latestRunState ? sentenceCase(analysis.latestRunState) : null,
7746
+ // While the data is still arriving no run can start, so the import is what the analysis is doing.
7747
+ latestRunState: isImporting(analysis.dataImport) ? importingLabel(analysis.dataImport) : analysis.latestRunState ? sentenceCase(analysis.latestRunState) : null,
7461
7748
  latestRunId: analysis.latestRunId,
7462
7749
  quality: qualityText(analysis),
7463
7750
  outputs: outputsText(analysis),
@@ -7476,13 +7763,14 @@ function analysisDetails(analysis, endpoint) {
7476
7763
  { key: "visibility", header: "Visibility" },
7477
7764
  { key: "introduction", header: "Introduction" },
7478
7765
  { key: "data", header: "Data" },
7766
+ { key: "dataImport", header: "Data import" },
7479
7767
  { key: "targets", header: "Targets" },
7480
7768
  { key: "targetKinds", header: "Target kinds" },
7481
7769
  { key: "featureExclusions", header: "Excluded columns" },
7482
7770
  { key: "confirmedInputs", header: "Known before the outcome" },
7483
7771
  { key: "questions", header: "Questions" },
7484
7772
  { key: "segment", header: "Segment" },
7485
- { key: "hours", header: "Computation time" },
7773
+ { key: "hours", header: "Time budget" },
7486
7774
  { key: "budget", header: "Credit budget" },
7487
7775
  { key: "constraints", header: "Constraints" },
7488
7776
  { key: "notifyByEmail", header: "Email when done" },
@@ -7550,6 +7838,280 @@ function constraintsText(analysis) {
7550
7838
  return parts.length > 0 ? parts.join(", ") : "none";
7551
7839
  }
7552
7840
 
7841
+ // src/commands/analyze/data-import.ts
7842
+ var IMPORT_POLL_INTERVAL_MS = 2e3;
7843
+ function renderImportBlock(dataImport, elapsedMs) {
7844
+ const title = dataImport.state === "STOPPING" ? "Stopping the data import" : "Importing data";
7845
+ const lines = [` ${chalk26.cyan(SPINNER)} ${chalk26.bold(title)}`];
7846
+ const elapsed = chalk26.dim(formatDurationPrecise(elapsedMs));
7847
+ if (dataImport.state === "IMPORTING" && dataImport.progress !== null && dataImport.progress !== void 0) {
7848
+ lines.push(` ${bar(dataImport.progress)} ${percent(dataImport.progress)} ${elapsed}`);
7849
+ } else {
7850
+ lines.push(` ${chalk26.dim(dataImport.message)} ${elapsed}`);
7851
+ }
7852
+ return lines;
7853
+ }
7854
+ function sleep3(ms) {
7855
+ let timer;
7856
+ const done = new Promise((resolve) => {
7857
+ timer = setTimeout(() => resolve("elapsed"), ms);
7858
+ });
7859
+ return { done, cancel: () => clearTimeout(timer) };
7860
+ }
7861
+ async function followImport(ctx, first) {
7862
+ const { api, analysisId } = ctx;
7863
+ const human = ctx.outputFormat === "human";
7864
+ const startedAt = Date.parse(first.startedAt);
7865
+ const since = Number.isFinite(startedAt) ? startedAt : Date.now();
7866
+ const status = new Status();
7867
+ let interrupt = () => {
7868
+ };
7869
+ const interrupted = new Promise((resolve) => {
7870
+ interrupt = () => resolve("interrupted");
7871
+ });
7872
+ process.once("SIGINT", interrupt);
7873
+ if (ctx.live) {
7874
+ status.start();
7875
+ } else {
7876
+ console.error("The import is still running on the platform. Waiting for it to finish.");
7877
+ }
7878
+ let current = first;
7879
+ try {
7880
+ for (; ; ) {
7881
+ if (ctx.live) status.set(renderImportBlock(current, Date.now() - since));
7882
+ const pause = sleep3(IMPORT_POLL_INTERVAL_MS);
7883
+ const woke = await Promise.race([pause.done, interrupted]);
7884
+ if (woke === "interrupted") {
7885
+ pause.cancel();
7886
+ status.stop();
7887
+ warn("Stopped waiting. The import keeps running on the platform.");
7888
+ hint(`See how far it is with 'diafunc analyze get ${analysisId}'.`);
7889
+ hint(`Start the run once it has finished with 'diafunc analyze rerun ${analysisId}'.`);
7890
+ process.exit(EXIT_CANCELLED);
7891
+ }
7892
+ let answer;
7893
+ try {
7894
+ answer = await api.analysis.getDataImport(analysisId);
7895
+ } catch (error) {
7896
+ if (error instanceof ApiError && error.status < 500) throw error;
7897
+ continue;
7898
+ }
7899
+ if (isImporting(answer.dataImport)) {
7900
+ current = answer.dataImport;
7901
+ continue;
7902
+ }
7903
+ status.stop();
7904
+ if (!answer.dataImport) {
7905
+ const shape = dataShape(answer.rowCount, answer.columnCount);
7906
+ if (human) {
7907
+ success(shape ? `Data imported: ${shape}.` : "Data imported.");
7908
+ } else if (ctx.machineReport === "stream") {
7909
+ process.stdout.write(JSON.stringify({
7910
+ type: "import",
7911
+ state: "IMPORTED",
7912
+ rowCount: answer.rowCount ?? null,
7913
+ columnCount: answer.columnCount ?? null
7914
+ }) + "\n");
7915
+ } else {
7916
+ console.error("The import has finished.");
7917
+ }
7918
+ }
7919
+ return { dataImport: answer.dataImport ?? null, rowCount: answer.rowCount ?? null, columnCount: answer.columnCount ?? null };
7920
+ }
7921
+ } finally {
7922
+ status.stop();
7923
+ process.off("SIGINT", interrupt);
7924
+ }
7925
+ }
7926
+ async function stopImport(api, analysisId) {
7927
+ let answer = await api.analysis.stopDataImport(analysisId);
7928
+ while (answer.dataImport?.state === "STOPPING") {
7929
+ await sleep3(IMPORT_POLL_INTERVAL_MS).done;
7930
+ answer = await api.analysis.getDataImport(analysisId);
7931
+ }
7932
+ return { dataImport: answer.dataImport ?? null, rowCount: answer.rowCount ?? null, columnCount: answer.columnCount ?? null };
7933
+ }
7934
+ async function importInFlight(api, analysisId) {
7935
+ try {
7936
+ const { dataImport } = await api.analysis.getDataImport(analysisId);
7937
+ return isImporting(dataImport) ? dataImport : null;
7938
+ } catch {
7939
+ return null;
7940
+ }
7941
+ }
7942
+ async function importBlockingRun(api, analysisId) {
7943
+ try {
7944
+ const { dataImport } = await api.analysis.getDataImport(analysisId);
7945
+ return dataImport?.blocksRun ? dataImport : null;
7946
+ } catch {
7947
+ return null;
7948
+ }
7949
+ }
7950
+ function uploadAgainHint(analysisId) {
7951
+ return `Upload the data with 'diafunc analyze upload ${analysisId} <file>'.`;
7952
+ }
7953
+ async function settle(ctx, answer, data) {
7954
+ let status = {
7955
+ dataImport: data.dataImport ?? null,
7956
+ rowCount: data.rowCount ?? null,
7957
+ columnCount: data.columnCount ?? null
7958
+ };
7959
+ if (isImporting(status.dataImport)) {
7960
+ status = await followImport(ctx, status.dataImport);
7961
+ }
7962
+ const ended = status.dataImport;
7963
+ if (ended) {
7964
+ if (ended.blocksRun) {
7965
+ throw new CliError(ended.message, { hint: uploadAgainHint(ctx.analysisId) });
7966
+ }
7967
+ warn(ended.message);
7968
+ }
7969
+ return { ...status, answer };
7970
+ }
7971
+ async function sendData(ctx, send) {
7972
+ let answer;
7973
+ try {
7974
+ answer = await send();
7975
+ } catch (error) {
7976
+ if (!(error instanceof ApiError) || error.status !== 409) throw error;
7977
+ const running = await importInFlight(ctx.api, ctx.analysisId);
7978
+ if (!running) throw error;
7979
+ if (!ctx.prompter) {
7980
+ throw new CliError(error.message, {
7981
+ hint: `Stop the running import with 'diafunc analyze stop-import ${ctx.analysisId}' and upload again, or wait for it: 'diafunc analyze get ${ctx.analysisId}' shows how far it is.`
7982
+ });
7983
+ }
7984
+ warn(error.message);
7985
+ const stopping = running.state === "STOPPING";
7986
+ const choice = await ctx.prompter.select({
7987
+ message: "What should happen?",
7988
+ choices: stopping ? [
7989
+ { name: "Upload as soon as the stopped import has ended", value: "replace" },
7990
+ { name: "Wait for the stopped import to end and upload nothing", value: "wait" }
7991
+ ] : [
7992
+ { name: "Wait for the running import to finish and keep its data", value: "wait" },
7993
+ { name: "Stop the running import and upload again", value: "replace" }
7994
+ ]
7995
+ });
7996
+ if (choice === "wait") {
7997
+ return settle(ctx, null, { dataImport: running });
7998
+ }
7999
+ await withStatus("Stopping the running import", () => stopImport(ctx.api, ctx.analysisId));
8000
+ answer = await send();
8001
+ }
8002
+ return settle(ctx, answer, answer);
8003
+ }
8004
+ async function queueRun(api, analysisId) {
8005
+ try {
8006
+ return await api.analysis.runAnalysis(analysisId);
8007
+ } catch (error) {
8008
+ if (!(error instanceof ApiError) || error.status !== 409) throw error;
8009
+ const blocking = await importBlockingRun(api, analysisId);
8010
+ if (!blocking) throw error;
8011
+ throw new CliError(error.message, {
8012
+ hint: isImporting(blocking) ? `Wait for the import to finish: 'diafunc analyze get ${analysisId}' shows how far it is. Then start the run with 'diafunc analyze rerun ${analysisId}'.` : uploadAgainHint(analysisId)
8013
+ });
8014
+ }
8015
+ }
8016
+
8017
+ // src/commands/analyze/sources.ts
8018
+ import * as fs8 from "fs";
8019
+ import * as path7 from "path";
8020
+ var CAUTIONS = /* @__PURE__ */ new Set([
8021
+ "UNEVEN_COLUMNS",
8022
+ "TYPE_CONFLICT",
8023
+ "SOURCE_WARNING",
8024
+ "LEFT_OUT",
8025
+ "POSSIBLE_KEY",
8026
+ "MANY_TO_MANY",
8027
+ "NO_KEY",
8028
+ "TOO_LARGE",
8029
+ "HINT_REJECTED"
8030
+ ]);
8031
+ function recipeWithChoices(proposal, choices) {
8032
+ if (proposal.parts.length < 2) return null;
8033
+ const originColumn = choices.fileColumn ? proposal.originColumn : null;
8034
+ const dropDuplicates = !choices.keepDuplicates;
8035
+ if (originColumn === proposal.originColumn && dropDuplicates === proposal.dropDuplicates) return null;
8036
+ return { parts: proposal.parts, originColumn, dropDuplicates, lookups: proposal.lookups ?? [] };
8037
+ }
8038
+ function labelOf(file) {
8039
+ return path7.basename(file, path7.extname(file)).trim().toLowerCase();
8040
+ }
8041
+ function otherRowsLabel(proposal) {
8042
+ const alternative = (proposal.lookups ?? []).find((lookup) => lookup.alternative)?.alternative;
8043
+ return alternative && alternative.parts.length > 0 ? alternative.parts[0].label : null;
8044
+ }
8045
+ function recipeWithRowsOf(proposal, rowsOf) {
8046
+ const wanted = labelOf(rowsOf);
8047
+ if (proposal.recipe.parts.some((part) => part.label.trim().toLowerCase() === wanted)) return null;
8048
+ const alternative = (proposal.lookups ?? []).find((lookup) => lookup.alternative)?.alternative;
8049
+ if (alternative && alternative.parts.some((part) => part.label.trim().toLowerCase() === wanted)) return alternative;
8050
+ const rows = proposal.recipe.parts.map((part) => part.label).join(", ");
8051
+ throw new CliError(`${rowsOf} cannot carry the rows of this table.`, {
8052
+ exitCode: EXIT_USAGE,
8053
+ hint: alternative ? `The rows can come from ${rows} or from ${alternative.parts.map((part) => part.label).join(", ")}.` : `These files have one reading: the rows come from ${rows}.`
8054
+ });
8055
+ }
8056
+ function planLines(plan) {
8057
+ const lines = [{
8058
+ text: `One table of ${plan.rows.toLocaleString("en-US")} rows and ${plan.columns.toLocaleString("en-US")} columns.`,
8059
+ caution: false
8060
+ }];
8061
+ for (const finding of plan.findings) {
8062
+ lines.push({ text: finding.message, caution: CAUTIONS.has(finding.kind) });
8063
+ }
8064
+ return lines;
8065
+ }
8066
+ function multipart(file) {
8067
+ const formData = new FormData();
8068
+ formData.append("content", new Blob([fs8.readFileSync(file)]), path7.basename(file));
8069
+ return formData;
8070
+ }
8071
+ async function uploadSeveral(api, analysisId, files, choices, human) {
8072
+ for (const file of files) {
8073
+ if (!fs8.existsSync(file)) {
8074
+ throw new CliError(`File not found: ${file}`, { exitCode: EXIT_USAGE });
8075
+ }
8076
+ }
8077
+ for (const earlier of await api.analysis.listSources(analysisId)) {
8078
+ await api.analysis.removeSource(analysisId, earlier.sourceId);
8079
+ }
8080
+ for (const file of files) {
8081
+ await withStatus(`Uploading ${path7.basename(file)}`, () => api.analysis.addSource(analysisId, multipart(file)));
8082
+ }
8083
+ let other = null;
8084
+ const plan = await withStatus("Reading the files together", async () => {
8085
+ const proposal = await api.analysis.planSources(analysisId, null);
8086
+ const exchanged = choices.rowsOf ? recipeWithRowsOf(proposal, choices.rowsOf) : null;
8087
+ if (exchanged) {
8088
+ other = proposal.recipe.parts[0]?.label ?? null;
8089
+ return api.analysis.planSources(analysisId, exchanged);
8090
+ }
8091
+ other = otherRowsLabel(proposal);
8092
+ const chosen = recipeWithChoices(proposal.recipe, choices);
8093
+ return chosen ? api.analysis.planSources(analysisId, chosen) : proposal;
8094
+ });
8095
+ if (human) {
8096
+ for (const line of planLines(plan)) {
8097
+ if (line.caution) warn(line.text);
8098
+ else detail(line.text);
8099
+ }
8100
+ if (other) {
8101
+ hint(`These files can be read two ways. For one row per row of ${other}, add --rows-of ${other}.`);
8102
+ }
8103
+ }
8104
+ if (choices.planOnly) {
8105
+ if (human) hint("Plan only: the files are stored with the analysis and nothing was built.");
8106
+ return { plan, rowCount: null, columnCount: null };
8107
+ }
8108
+ const tables = plan.recipe.parts.length + (plan.recipe.lookups ?? []).reduce((sum, lookup) => sum + lookup.parts.length, 0);
8109
+ return withStatus(
8110
+ `Building one table from ${tables} file${tables === 1 ? "" : "s"}`,
8111
+ () => api.analysis.buildSources(analysisId, plan.recipe)
8112
+ );
8113
+ }
8114
+
7553
8115
  // src/commands/analyze/index.ts
7554
8116
  var POLL_INTERVAL_MS = 2e3;
7555
8117
  var MISSING_RUN_POLLS = 5;
@@ -7568,9 +8130,17 @@ function getOutputFormat15(cmd) {
7568
8130
  function noInteractiveFlag(cmd) {
7569
8131
  return cmd.optsWithGlobals().interactive === false;
7570
8132
  }
7571
- function parseCsv(value) {
7572
- if (value === void 0) return null;
7573
- return value.split(",").map((s) => s.trim()).filter((s) => s.length > 0);
8133
+ function importContext(api, analysisId, cmd, machineReport) {
8134
+ const outputFormat = getOutputFormat15(cmd);
8135
+ const noInteractive = noInteractiveFlag(cmd);
8136
+ return {
8137
+ api,
8138
+ analysisId,
8139
+ outputFormat,
8140
+ live: outputFormat === "human" && !noInteractive && isInteractive(),
8141
+ prompter: canPrompt(outputFormat, noInteractive) ? createInquirerPrompter() : null,
8142
+ machineReport
8143
+ };
7574
8144
  }
7575
8145
  function collectQuestion(value, previous = []) {
7576
8146
  return previous.concat([value]);
@@ -7595,25 +8165,29 @@ function budgetHoursOf(hours) {
7595
8165
  return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
7596
8166
  }
7597
8167
  function multipartFromFile(file) {
7598
- const buffer = fs8.readFileSync(file);
8168
+ const buffer = fs9.readFileSync(file);
7599
8169
  const blob = new Blob([buffer]);
7600
8170
  const formData = new FormData();
7601
- formData.append("content", blob, path7.basename(file));
8171
+ formData.append("content", blob, path8.basename(file));
7602
8172
  return formData;
7603
8173
  }
7604
8174
  function reportCommandError(error) {
7605
8175
  if (error instanceof PromptCancelled) throw error;
7606
8176
  handleError(error);
7607
8177
  }
7608
- async function runAnalysis(file, options, cmd) {
7609
- if (!fs8.existsSync(file)) {
7610
- failure(`File not found: ${file}`);
7611
- process.exit(EXIT_FAILURE);
8178
+ async function runAnalysis(files, options, cmd) {
8179
+ for (const candidate of files) {
8180
+ if (!fs9.existsSync(candidate)) {
8181
+ failure(`File not found: ${candidate}`);
8182
+ process.exit(EXIT_FAILURE);
8183
+ }
7612
8184
  }
8185
+ const file = files[0];
7613
8186
  const outputFormat = getOutputFormat15(cmd);
7614
8187
  const noInteractive = noInteractiveFlag(cmd);
7615
8188
  const interactive = canPrompt(outputFormat, noInteractive);
7616
8189
  const api = createApiClient();
8190
+ let presetTargets;
7617
8191
  if (options.preset) {
7618
8192
  const opt = await api.analysis.getPreset(options.preset);
7619
8193
  if (!opt.preset) {
@@ -7622,21 +8196,22 @@ async function runAnalysis(file, options, cmd) {
7622
8196
  process.exit(EXIT_FAILURE);
7623
8197
  }
7624
8198
  const p = opt.preset;
7625
- if (options.targets === void 0 && p.targetKeys.length > 0) options.targets = p.targetKeys.join(",");
8199
+ if (options.targets === void 0 && p.targetKeys.length > 0) presetTargets = p.targetKeys;
7626
8200
  if (options.question === void 0 && p.questions.length > 0) options.question = [...p.questions];
7627
8201
  if (options.segment === void 0 && p.segmentKey) options.segment = p.segmentKey;
7628
8202
  if (options.hours === void 0) options.hours = p.time;
7629
8203
  if (options.budget === void 0) options.budget = p.budget;
7630
8204
  }
7631
- const flagTargets = parseCsv(options.targets);
7632
- if (!interactive && (flagTargets === null || flagTargets.length === 0)) {
8205
+ const typedTargets = occurrences(options.targets)?.filter((entry) => entry.trim().length > 0);
8206
+ const targetsGiven = (typedTargets?.length ?? 0) > 0 || (presetTargets?.length ?? 0) > 0;
8207
+ if (!interactive && !targetsGiven) {
7633
8208
  usageError(
7634
8209
  `Target columns are required, and ${whyNoPrompt(outputFormat, noInteractive)}.`,
7635
- `Pass --targets <csv> or --preset <id>. The names are the column headers of ${path7.basename(file)}.`
8210
+ `Pass --targets <columns> or --preset <id>. The names are the column headers of ${files.length > 1 ? "the files" : path8.basename(file)}.`
7636
8211
  );
7637
8212
  }
7638
8213
  const prompter = createInquirerPrompter();
7639
- const fallbackName = path7.basename(file, path7.extname(file));
8214
+ const fallbackName = path8.basename(file, path8.extname(file));
7640
8215
  const creation = interactive ? await promptCreationFields(prompter, {
7641
8216
  name: options.name,
7642
8217
  description: options.description,
@@ -7653,39 +8228,78 @@ async function runAnalysis(file, options, cmd) {
7653
8228
  introduction: options.introduction ?? null,
7654
8229
  hours: options.hours ?? DEFAULT_HOURS,
7655
8230
  budget: options.budget ?? DEFAULT_BUDGET,
7656
- targets: flagTargets,
8231
+ // The targets and the segment are column names, and the columns exist only once the file is
8232
+ // uploaded. They are set below, read against the real header.
8233
+ targets: null,
7657
8234
  questions: questionsOf(options.question),
7658
- segment: options.segment ?? null
8235
+ segment: null
7659
8236
  };
7660
8237
  const created = await withStatus(`Creating analysis "${creation.name}"`, () => api.analysis.create(request));
7661
8238
  if (isDryRun()) {
7662
- hint(`Dry run: nothing was created. A real run would upload ${path7.basename(file)}, queue the analysis and follow it.`);
8239
+ hint(`Dry run: nothing was created. A real run would upload ${path8.basename(file)}, queue the analysis and follow it.`);
7663
8240
  return;
7664
8241
  }
7665
8242
  detail(`analysisId: ${created.analysisId}`);
7666
- await withStatus(
7667
- `Uploading ${path7.basename(file)}`,
8243
+ await sendData(importContext(api, created.analysisId, cmd, "stream"), () => files.length > 1 ? uploadSeveral(api, created.analysisId, files, stackChoices(options), outputFormat === "human") : withStatus(
8244
+ `Uploading ${path8.basename(file)}`,
7668
8245
  () => api.analysis.uploadDataMultipart(created.analysisId, multipartFromFile(file))
8246
+ ));
8247
+ const columns = await readColumns(api, created.analysisId);
8248
+ const named = namedColumns(
8249
+ created.analysisId,
8250
+ columns,
8251
+ interactive,
8252
+ { typedTargets, presetTargets, segment: options.segment }
7669
8253
  );
7670
8254
  let runHours = request.hours;
7671
8255
  if (interactive) {
7672
8256
  const configuredHours = await configureInteractively(api, prompter, created.analysisId, request, {
7673
- targets: options.targets === void 0 ? void 0 : parseCsv(options.targets),
7674
- segment: options.segment,
8257
+ targets: named.targets,
8258
+ segment: named.segment,
7675
8259
  questions: options.question === void 0 ? void 0 : questionsOf(options.question),
7676
8260
  hours: options.hours,
7677
8261
  budget: options.budget
7678
- });
8262
+ }, columns);
7679
8263
  if (configuredHours === null) return;
7680
8264
  runHours = configuredHours;
8265
+ } else {
8266
+ await withStatus("Saving the analysis settings", () => api.analysis.update(created.analysisId, {
8267
+ ...request,
8268
+ targets: named.targets ?? null,
8269
+ segment: named.segment ?? null
8270
+ }));
7681
8271
  }
7682
- const run = await withStatus("Queuing analysis run", () => api.analysis.runAnalysis(created.analysisId));
8272
+ const run = await withStatus("Queuing analysis run", () => queueRun(api, created.analysisId));
7683
8273
  detail(`runId: ${run.runId}`);
7684
8274
  console.log();
7685
8275
  await monitorRun(api, created.analysisId, run.runId, budgetHoursOf(runHours), cmd);
7686
8276
  }
7687
- async function configureInteractively(api, prompter, analysisId, recipe, supplied) {
7688
- const columns = await readColumns(api, analysisId);
8277
+ function namedColumns(analysisId, columns, interactive, given) {
8278
+ const names = columns.map((c) => c.name).filter((name) => name && name.length > 0);
8279
+ const read = (resolve) => {
8280
+ try {
8281
+ return resolve();
8282
+ } catch (error) {
8283
+ if (!(error instanceof CliError)) throw error;
8284
+ if (!interactive) {
8285
+ throw new CliError(error.message, {
8286
+ exitCode: error.exitCode,
8287
+ hint: [
8288
+ error.hint,
8289
+ `Analysis ${analysisId} is created and holds the data. Name the columns with 'diafunc analyze targets ${analysisId} <column...>' and start it with 'diafunc analyze rerun ${analysisId}'.`
8290
+ ].filter(Boolean).join("\n ")
8291
+ });
8292
+ }
8293
+ warn(error.message);
8294
+ return void 0;
8295
+ }
8296
+ };
8297
+ const targets = given.typedTargets && given.typedTargets.length > 0 ? read(() => resolveColumnArguments(given.typedTargets, names, analysisId)) : given.presetTargets && given.presetTargets.length > 0 ? read(() => resolveColumnNames(given.presetTargets, names, analysisId)) : void 0;
8298
+ const segment = given.segment === void 0 || given.segment === "" ? void 0 : read(() => resolveColumnArgument(given.segment, names, analysisId));
8299
+ return { targets, segment };
8300
+ }
8301
+ async function configureInteractively(api, prompter, analysisId, recipe, supplied, knownColumns) {
8302
+ const columns = knownColumns ?? await readColumns(api, analysisId);
7689
8303
  const presets = await readPresets(api);
7690
8304
  console.log();
7691
8305
  const answers = await promptRunFields(prompter, { columns, presets, supplied });
@@ -7867,8 +8481,11 @@ async function listAnalyses(limit, cmd) {
7867
8481
  hours: a.hours,
7868
8482
  budget: a.budget,
7869
8483
  targets: a.targets,
7870
- latestRunState: a.latestRunState,
7871
- createdAt: a.createdAt
8484
+ // A reader sees the import where the run state would be: no run can start before the data is
8485
+ // in place. JSON keeps the state as it is and carries the import beside it.
8486
+ latestRunState: outputFormat !== "json" && isImporting(a.dataImport) ? importingLabel(a.dataImport) : a.latestRunState,
8487
+ createdAt: a.createdAt,
8488
+ ...outputFormat === "json" && a.dataImport !== void 0 ? { dataImport: a.dataImport } : {}
7872
8489
  })), {
7873
8490
  format: outputFormat,
7874
8491
  columns: [
@@ -7982,7 +8599,7 @@ async function rerunAnalysis(analysisId, cmd) {
7982
8599
  );
7983
8600
  if (configuredHours === null) return;
7984
8601
  }
7985
- const run = await api.analysis.runAnalysis(analysisId);
8602
+ const run = await queueRun(api, analysisId);
7986
8603
  if (isDryRun()) {
7987
8604
  hint("Dry run: no run was queued.");
7988
8605
  return;
@@ -8008,6 +8625,10 @@ async function openAnalysis(analysisId) {
8008
8625
  hint("The notebook is not available yet. Run the analysis first.");
8009
8626
  }
8010
8627
  }
8628
+ function typedColumns(given) {
8629
+ const entries = occurrences(given);
8630
+ return entries === void 0 ? null : resolveColumnArguments(entries, []);
8631
+ }
8011
8632
  async function createAnalysis(options, cmd) {
8012
8633
  const outputFormat = getOutputFormat15(cmd);
8013
8634
  const api = createApiClient();
@@ -8019,7 +8640,7 @@ async function createAnalysis(options, cmd) {
8019
8640
  introduction: options.introduction ?? null,
8020
8641
  hours: options.hours ?? null,
8021
8642
  budget: options.budget ?? null,
8022
- targets: parseCsv(options.targets),
8643
+ targets: typedColumns(options.targets),
8023
8644
  questions: questionsOf(options.question),
8024
8645
  segment: options.segment ?? null
8025
8646
  };
@@ -8053,29 +8674,98 @@ async function patchAndPrint(analysisId, value, handler, successLabel, cmd) {
8053
8674
  format(updated, { format: outputFormat });
8054
8675
  }
8055
8676
  }
8056
- async function uploadData(analysisId, file, options) {
8677
+ async function columnNames(api, analysisId) {
8678
+ return (await api.analysis.getColumns(analysisId)).map((c) => c.name).filter((name) => name && name.length > 0);
8679
+ }
8680
+ async function patchColumns(analysisId, given, send, successLabel, cmd) {
8057
8681
  const api = createApiClient();
8058
- const dataUrl = options.url;
8059
- if (dataUrl) {
8060
- if (file) {
8061
- usageError("Provide either a file or --url, not both.", "Drop one of the two and run it again.");
8682
+ const columns = resolveColumnArguments(occurrences(given) ?? [], await columnNames(api, analysisId), analysisId);
8683
+ await patchAndPrint(analysisId, "", () => send(api, columns), successLabel, cmd);
8684
+ }
8685
+ function stackChoices(options) {
8686
+ return {
8687
+ fileColumn: options.fileColumn !== false,
8688
+ keepDuplicates: options.keepDuplicates === true,
8689
+ rowsOf: options.rowsOf,
8690
+ planOnly: options.planOnly === true
8691
+ };
8692
+ }
8693
+ async function uploadData(analysisId, files, options, cmd) {
8694
+ const api = createApiClient();
8695
+ const outputFormat = getOutputFormat15(cmd);
8696
+ const ctx = importContext(api, analysisId, cmd, "none");
8697
+ const file = files[0];
8698
+ if (files.length > 1) {
8699
+ if (options.url) {
8700
+ usageError("Provide either files or --url, not both.", "Drop one of the two and run it again.");
8701
+ }
8702
+ const built = await sendData(
8703
+ ctx,
8704
+ () => uploadSeveral(api, analysisId, files, stackChoices(options), outputFormat === "human")
8705
+ );
8706
+ if (outputFormat !== "human") {
8707
+ format({
8708
+ ...built.answer,
8709
+ rowCount: built.rowCount,
8710
+ columnCount: built.columnCount,
8711
+ dataImport: built.dataImport
8712
+ }, { format: outputFormat });
8062
8713
  }
8063
- await withStatus(`Uploading from ${dataUrl}`, () => api.analysis.uploadDataUrl(analysisId, { dataUrl }));
8064
8714
  return;
8065
8715
  }
8066
- if (!file) {
8067
- usageError(
8068
- "Provide a file path or --url <URL>.",
8069
- `For example: diafunc analyze upload ${analysisId} data.csv`
8070
- );
8716
+ const dataUrl = options.url;
8717
+ if (dataUrl && file) {
8718
+ usageError("Provide either a file or --url, not both.", "Drop one of the two and run it again.");
8071
8719
  }
8072
- if (!fs8.existsSync(file)) {
8073
- throw new CliError(`File not found: ${file}`, { exitCode: EXIT_USAGE });
8720
+ if (!dataUrl) {
8721
+ if (!file) {
8722
+ usageError(
8723
+ "Provide a file path or --url <URL>.",
8724
+ `For example: diafunc analyze upload ${analysisId} data.csv`
8725
+ );
8726
+ }
8727
+ if (!fs9.existsSync(file)) {
8728
+ throw new CliError(`File not found: ${file}`, { exitCode: EXIT_USAGE });
8729
+ }
8074
8730
  }
8075
- await withStatus(
8076
- `Uploading ${path7.basename(file)}`,
8731
+ const uploaded = await sendData(ctx, () => dataUrl ? withStatus(`Uploading from ${dataUrl}`, () => api.analysis.uploadDataUrl(analysisId, { dataUrl })) : withStatus(
8732
+ `Uploading ${path8.basename(file)}`,
8077
8733
  () => api.analysis.uploadDataMultipart(analysisId, multipartFromFile(file))
8078
- );
8734
+ ));
8735
+ if (isDryRun()) {
8736
+ hint("Dry run: nothing was uploaded.");
8737
+ return;
8738
+ }
8739
+ if (outputFormat !== "human") {
8740
+ format({
8741
+ dataImport: uploaded.dataImport,
8742
+ rowCount: uploaded.rowCount,
8743
+ columnCount: uploaded.columnCount
8744
+ }, { format: outputFormat });
8745
+ }
8746
+ }
8747
+ async function stopDataImport(analysisId, cmd) {
8748
+ const outputFormat = getOutputFormat15(cmd);
8749
+ const api = createApiClient();
8750
+ const stopped = await withStatus("Stopping the data import", () => stopImport(api, analysisId));
8751
+ if (isDryRun()) {
8752
+ hint("Dry run: nothing was stopped.");
8753
+ return;
8754
+ }
8755
+ if (outputFormat !== "human") {
8756
+ format(stopped, { format: outputFormat });
8757
+ return;
8758
+ }
8759
+ if (!stopped.dataImport) {
8760
+ success(`No data import is running for analysis ${analysisId}.`);
8761
+ return;
8762
+ }
8763
+ if (stopped.dataImport.state === "STOPPED") {
8764
+ success(`Stopped the data import of analysis ${analysisId}.`);
8765
+ hint(stopped.dataImport.message);
8766
+ return;
8767
+ }
8768
+ warn(stopped.dataImport.message);
8079
8769
  }
8080
8770
  async function listColumns(analysisId, cmd) {
8081
8771
  const outputFormat = getOutputFormat15(cmd);
@@ -8166,7 +8856,7 @@ async function savePreset(options, cmd) {
8166
8856
  const preset = {
8167
8857
  presetId: options.id ?? null,
8168
8858
  name: options.name,
8169
- targetKeys: parseCsv(options.targets) ?? [],
8859
+ targetKeys: typedColumns(options.targets) ?? [],
8170
8860
  questions: questionsOf(options.question) ?? [],
8171
8861
  segmentKey: options.segment ?? null,
8172
8862
  time: options.hours,
@@ -8246,15 +8936,17 @@ async function updateTriggerCmd(triggerId, options, cmd) {
8246
8936
  });
8247
8937
  format(trigger, { format: outputFormat });
8248
8938
  }
8939
+ var COLUMN_LIST_HELP = "one argument each or comma-separated; a name that contains a comma is an argument of its own, or goes in double quotes inside a list";
8940
+ var TARGETS_HELP = `Target column names: repeat the flag or separate them with commas; a name that contains a comma is one flag of its own, or goes in double quotes inside a list`;
8249
8941
  function registerAnalyzeCommand(program) {
8250
8942
  const analyze = program.command("analyze").description("Run and manage automatic analyses");
8251
- analyze.command("run", { isDefault: true }).description("Create an analysis from a data file, configure it and run it (the default: `analyze <file>`)").argument("[file]", "Data file to analyze (CSV, Excel and more than 45 file formats; see `table import-formats`)").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 (hours). Default ${DEFAULT_HOURS}, the Standard preset; a saved preset applies when omitted`).option("--budget <credits>", `Credit budget. Default ${Number(DEFAULT_BUDGET).toLocaleString("en-US")}, the Standard preset; a saved preset applies when omitted`).option("--targets <csv>", "Comma-separated target column names (required when not interactive)").option("--question <text>", "A question for the analysis to answer; repeat the flag for several", collectQuestion).option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction shown at the top of the notebook").option("--preset <id>", "Apply a saved preset as defaults (explicit flags override it)").action(async (file, options, cmd) => {
8943
+ analyze.command("run", { isDefault: true }).description("Create an analysis from a data file, configure it and run it (the default: `analyze <file>`)").argument("[files...]", "Data file to analyze (CSV, Excel and more than 45 file formats; see `table import-formats`). Several files are combined into one table: files with the same columns are stacked, a file that shares a key adds its columns").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>", `Time budget (hours). Default ${DEFAULT_HOURS}, the Standard preset; a saved preset applies when omitted`).option("--budget <credits>", `Credit budget. Default ${Number(DEFAULT_BUDGET).toLocaleString("en-US")}, the Standard preset; a saved preset applies when omitted`).option("--targets <columns>", `${TARGETS_HELP} (required when not interactive)`, collectColumns).option("--question <text>", "A question for the analysis to answer; repeat the flag for several", collectQuestion).option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction shown at the top of the notebook").option("--preset <id>", "Apply a saved preset as defaults (explicit flags override it)").option("--no-file-column", "With several files: do not add the column that records the file each row came from").option("--keep-duplicates", "With several files: keep rows that occur in more than one file").option("--rows-of <file>", "With several files that can be read two ways: the file in which one row is one observation").action(async (files, options, cmd) => {
8252
8944
  try {
8253
- if (!file) {
8945
+ if (files.length === 0) {
8254
8946
  analyze.help();
8255
8947
  return;
8256
8948
  }
8257
- await runAnalysis(file, options, cmd);
8949
+ await runAnalysis(files, options, cmd);
8258
8950
  } catch (error) {
8259
8951
  reportCommandError(error);
8260
8952
  }
@@ -8287,14 +8979,14 @@ function registerAnalyzeCommand(program) {
8287
8979
  handleError(error);
8288
8980
  }
8289
8981
  });
8290
- 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) => {
8982
+ analyze.command("rerun").description("Queue a fresh run on an existing analysis (asks for anything a run still needs). A run cannot start while the data is still being imported").argument("<id>", "Analysis ID to rerun").action(async (id, _options, cmd) => {
8291
8983
  try {
8292
8984
  await rerunAnalysis(id, cmd);
8293
8985
  } catch (error) {
8294
8986
  reportCommandError(error);
8295
8987
  }
8296
8988
  });
8297
- analyze.command("create").description("Create an analysis without uploading data or running it").option("--name <name>", "Analysis name").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC", "PRIVATE").option("--hours <hours>", "Computation time (hours)").option("--budget <credits>", "Credit budget").option("--targets <csv>", "Comma-separated target column names").option("--question <text>", "A question for the analysis to answer; repeat the flag for several", collectQuestion).option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction shown at the top of the notebook").action(async (options, cmd) => {
8989
+ analyze.command("create").description("Create an analysis without uploading data or running it").option("--name <name>", "Analysis name").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC", "PRIVATE").option("--hours <hours>", "Time budget (hours)").option("--budget <credits>", "Credit budget").option("--targets <columns>", TARGETS_HELP, collectColumns).option("--question <text>", "A question for the analysis to answer; repeat the flag for several", collectQuestion).option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction shown at the top of the notebook").action(async (options, cmd) => {
8298
8990
  try {
8299
8991
  await createAnalysis(options, cmd);
8300
8992
  } catch (error) {
@@ -8362,7 +9054,7 @@ function registerAnalyzeCommand(program) {
8362
9054
  handleError(error);
8363
9055
  }
8364
9056
  });
8365
- analyze.command("hours").description("Set the computation time (hours) for the next run").argument("<id>", "Analysis ID").argument("<hours>", "Computation time (hours), e.g. 4").action(async (id, hours, _options, cmd) => {
9057
+ analyze.command("hours").description("Set the time budget (hours) for the next run").argument("<id>", "Analysis ID").argument("<hours>", "Time budget (hours), e.g. 4").action(async (id, hours, _options, cmd) => {
8366
9058
  try {
8367
9059
  await patchAndPrint(
8368
9060
  id,
@@ -8388,13 +9080,12 @@ function registerAnalyzeCommand(program) {
8388
9080
  handleError(error);
8389
9081
  }
8390
9082
  });
8391
- analyze.command("targets").description("Set the target column names (comma-separated)").argument("<id>", "Analysis ID").argument("<csv>", "Comma-separated target column names").action(async (id, csv, _options, cmd) => {
9083
+ analyze.command("targets").description("Set the target columns, matched against the columns of the analysis data").argument("<id>", "Analysis ID").argument("<column...>", `Target column names, ${COLUMN_LIST_HELP}`).action(async (id, given, _options, cmd) => {
8392
9084
  try {
8393
- const targets = parseCsv(csv) ?? [];
8394
- await patchAndPrint(
9085
+ await patchColumns(
8395
9086
  id,
8396
- csv,
8397
- (api, aid) => api.analysis.patchTargets(aid, { targets }),
9087
+ given,
9088
+ (api, targets) => api.analysis.patchTargets(id, { targets }),
8398
9089
  "Targets",
8399
9090
  cmd
8400
9091
  );
@@ -8402,13 +9093,12 @@ function registerAnalyzeCommand(program) {
8402
9093
  handleError(error);
8403
9094
  }
8404
9095
  });
8405
- analyze.command("feature-exclusions").description("Set the columns every fit leaves out as an input (comma-separated; empty string leaves nothing out)").argument("<id>", "Analysis ID").argument("<csv>", "Comma-separated column names").action(async (id, csv, _options, cmd) => {
9096
+ analyze.command("feature-exclusions").description("Set the columns every fit leaves out as an input (a single empty string leaves nothing out)").argument("<id>", "Analysis ID").argument("<column...>", `Column names, ${COLUMN_LIST_HELP}`).action(async (id, given, _options, cmd) => {
8406
9097
  try {
8407
- const columns = parseCsv(csv) ?? [];
8408
- await patchAndPrint(
9098
+ await patchColumns(
8409
9099
  id,
8410
- csv,
8411
- (api, aid) => api.analysis.patchFeatureExclusions(aid, { columns }),
9100
+ given,
9101
+ (api, columns) => api.analysis.patchFeatureExclusions(id, { columns }),
8412
9102
  "Columns left out of the fit",
8413
9103
  cmd
8414
9104
  );
@@ -8416,13 +9106,12 @@ function registerAnalyzeCommand(program) {
8416
9106
  handleError(error);
8417
9107
  }
8418
9108
  });
8419
- analyze.command("confirmed-inputs").description("Set the columns the owner confirms as known before the outcome (comma-separated; empty string confirms nothing). A confirmed column raises no leakage concern.").argument("<id>", "Analysis ID").argument("<csv>", "Comma-separated column names").action(async (id, csv, _options, cmd) => {
9109
+ analyze.command("confirmed-inputs").description("Set the columns the owner confirms as known before the outcome (a single empty string confirms nothing). A confirmed column raises no leakage concern.").argument("<id>", "Analysis ID").argument("<column...>", `Column names, ${COLUMN_LIST_HELP}`).action(async (id, given, _options, cmd) => {
8420
9110
  try {
8421
- const columns = parseCsv(csv) ?? [];
8422
- await patchAndPrint(
9111
+ await patchColumns(
8423
9112
  id,
8424
- csv,
8425
- (api, aid) => api.analysis.patchConfirmedInputs(aid, { columns }),
9113
+ given,
9114
+ (api, columns) => api.analysis.patchConfirmedInputs(id, { columns }),
8426
9115
  "Columns known before the outcome",
8427
9116
  cmd
8428
9117
  );
@@ -8444,12 +9133,14 @@ function registerAnalyzeCommand(program) {
8444
9133
  handleError(error);
8445
9134
  }
8446
9135
  });
8447
- analyze.command("segment").description("Set or clear the segmentation column (empty string clears)").argument("<id>", "Analysis ID").argument("<name>", "Column name (empty string to clear)").action(async (id, name, _options, cmd) => {
9136
+ analyze.command("segment").description("Set or clear the segmentation column (empty string clears)").argument("<id>", "Analysis ID").argument("<name>", "Column name, matched against the columns of the analysis data (empty string to clear)").action(async (id, name, _options, cmd) => {
8448
9137
  try {
9138
+ const api = createApiClient();
9139
+ const segment = name === "" ? null : resolveColumnArgument(name, await columnNames(api, id), id);
8449
9140
  await patchAndPrint(
8450
9141
  id,
8451
9142
  name,
8452
- (api, aid, v) => api.analysis.patchSegment(aid, { segment: v === "" ? null : v }),
9143
+ () => api.analysis.patchSegment(id, { segment }),
8453
9144
  "Segment",
8454
9145
  cmd
8455
9146
  );
@@ -8457,9 +9148,16 @@ function registerAnalyzeCommand(program) {
8457
9148
  handleError(error);
8458
9149
  }
8459
9150
  });
8460
- analyze.command("upload").description("Replace the analysis data with a new file (any supported format; see `table import-formats`)").argument("<id>", "Analysis ID").argument("[file]", "Data file to upload (CSV, Excel and more than 45 file formats; see `table import-formats`)").option("--url <url>", "HTTPS URL to fetch the data file from, instead of a file path").action(async (id, file, options) => {
9151
+ analyze.command("upload").description("Replace the analysis data with a new file (any supported format; see `table import-formats`). An import that takes long is followed until it has finished").argument("<id>", "Analysis ID").argument("[files...]", "Data file to upload (CSV, Excel and more than 45 file formats; see `table import-formats`). Several files are combined into one table: files with the same columns are stacked, a file that shares a key adds its columns").option("--url <url>", "HTTPS URL to fetch the data file from, instead of a file path").option("--no-file-column", "With several files: do not add the column that records the file each row came from").option("--keep-duplicates", "With several files: keep rows that occur in more than one file").option("--rows-of <file>", "With several files that can be read two ways: the file in which one row is one observation").option("--plan-only", "With several files: store them and print how they fit together, without building the table").action(async (id, files, options, cmd) => {
8461
9152
  try {
8462
- await uploadData(id, file, options);
9153
+ await uploadData(id, files, options, cmd);
9154
+ } catch (error) {
9155
+ reportCommandError(error);
9156
+ }
9157
+ });
9158
+ analyze.command("stop-import").description("Stop the data import that is running for an analysis, so the data can be uploaded again").argument("<id>", "Analysis ID").action(async (id, _options, cmd) => {
9159
+ try {
9160
+ await stopDataImport(id, cmd);
8463
9161
  } catch (error) {
8464
9162
  handleError(error);
8465
9163
  }
@@ -8500,7 +9198,7 @@ function registerAnalyzeCommand(program) {
8500
9198
  handleError(error);
8501
9199
  }
8502
9200
  });
8503
- presets.command("save").description("Create a new preset (omit --id) or update an existing one (with --id)").requiredOption("--name <name>", "Preset name").requiredOption("--targets <csv>", "Comma-separated target column names").requiredOption("--hours <hours>", "Computation time (hours)").requiredOption("--budget <credits>", "Credit budget").option("--question <text>", "A question for the analysis to answer; repeat the flag for several", collectQuestion).option("--segment <name>", "Column to segment the analysis by").option("--id <id>", "Existing preset ID (update mode)").action(async (options, cmd) => {
9201
+ presets.command("save").description("Create a new preset (omit --id) or update an existing one (with --id)").requiredOption("--name <name>", "Preset name").requiredOption("--targets <columns>", TARGETS_HELP, collectColumns).requiredOption("--hours <hours>", "Time budget (hours)").requiredOption("--budget <credits>", "Credit budget").option("--question <text>", "A question for the analysis to answer; repeat the flag for several", collectQuestion).option("--segment <name>", "Column to segment the analysis by").option("--id <id>", "Existing preset ID (update mode)").action(async (options, cmd) => {
8504
9202
  try {
8505
9203
  await savePreset(options, cmd);
8506
9204
  } catch (error) {
@@ -8547,13 +9245,178 @@ function registerAnalyzeCommand(program) {
8547
9245
  });
8548
9246
  }
8549
9247
 
8550
- // src/commands/data-sources/index.ts
8551
- import chalk26 from "chalk";
9248
+ // src/commands/public/index.ts
9249
+ var MIN_LIMIT = 1;
9250
+ var MAX_LIMIT = 500;
8552
9251
  function getOutputFormat16(cmd) {
8553
9252
  const config = loadConfig();
8554
9253
  const globalOpts = cmd.optsWithGlobals();
8555
9254
  return globalOpts.output ?? config.defaults.output ?? "human";
8556
9255
  }
9256
+ function parseLimit(value) {
9257
+ const limit = Number(value);
9258
+ if (!Number.isInteger(limit) || limit < MIN_LIMIT || limit > MAX_LIMIT) {
9259
+ throw new CliError(
9260
+ `Invalid limit "${value}". Expected a whole number from ${MIN_LIMIT} to ${MAX_LIMIT}.`,
9261
+ { exitCode: EXIT_USAGE }
9262
+ );
9263
+ }
9264
+ return limit;
9265
+ }
9266
+ var ISO_INSTANT = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2}))?$/;
9267
+ function parseChangedSince(value) {
9268
+ const text2 = value.trim();
9269
+ const instant = ISO_INSTANT.test(text2) ? Date.parse(text2) : Number.NaN;
9270
+ if (!Number.isFinite(instant)) {
9271
+ throw new CliError(
9272
+ `Invalid timestamp "${value}". Expected ISO-8601, such as 2026-10-01 or 2026-10-01T08:30:00Z.`,
9273
+ { exitCode: EXIT_USAGE }
9274
+ );
9275
+ }
9276
+ return instant;
9277
+ }
9278
+ function instantMillis(value) {
9279
+ if (typeof value === "number") return value;
9280
+ return typeof value === "string" ? Date.parse(value) : Number.NaN;
9281
+ }
9282
+ async function readPublicAnalyses(analysis, options) {
9283
+ const analyses = [];
9284
+ const seen = /* @__PURE__ */ new Set();
9285
+ let cursor = options.cursor;
9286
+ for (; ; ) {
9287
+ const page = await analysis.listPublic({ cursor, limit: options.limit });
9288
+ for (const entry of page.analyses ?? []) {
9289
+ if (options.changedSince === void 0 || instantMillis(entry.changedAt) >= options.changedSince) {
9290
+ analyses.push(entry);
9291
+ }
9292
+ }
9293
+ const next = page.nextCursor ?? null;
9294
+ if (!options.all || next === null) return { analyses, nextCursor: next };
9295
+ if (seen.has(next)) {
9296
+ throw new CliError(`The platform returned the cursor "${next}" twice; stopped after ${analyses.length} analyses.`);
9297
+ }
9298
+ seen.add(next);
9299
+ cursor = next;
9300
+ }
9301
+ }
9302
+ async function listPublicAnalyses(options, cmd) {
9303
+ const outputFormat = getOutputFormat16(cmd);
9304
+ const limit = parseLimit(options.limit);
9305
+ const changedSince = options.changedSince === void 0 ? void 0 : parseChangedSince(options.changedSince);
9306
+ const api = createApiClient();
9307
+ const listing = await readPublicAnalyses(api.analysis, {
9308
+ limit,
9309
+ cursor: options.cursor,
9310
+ all: options.all,
9311
+ changedSince
9312
+ });
9313
+ if (outputFormat === "json") {
9314
+ format(listing, { format: outputFormat });
9315
+ return;
9316
+ }
9317
+ if (listing.analyses.length === 0 && outputFormat === "human") {
9318
+ empty("public analyses");
9319
+ } else {
9320
+ format(listing.analyses, {
9321
+ format: outputFormat,
9322
+ columns: [
9323
+ { key: "analysisId", kind: "id" },
9324
+ { key: "projectId", kind: "id" },
9325
+ { key: "publishedAt", header: "published", kind: "date" },
9326
+ { key: "changedAt", header: "changed", kind: "date" }
9327
+ ]
9328
+ });
9329
+ }
9330
+ if (listing.nextCursor !== null) {
9331
+ hint(`More public analyses follow. Continue with --cursor ${listing.nextCursor}, or pass --all.`);
9332
+ }
9333
+ }
9334
+ function newestRunRecord(run) {
9335
+ return {
9336
+ runId: run.runId,
9337
+ state: run.state,
9338
+ phase: runPhaseCell(run),
9339
+ submittedAt: run.submittedAt,
9340
+ startedAt: run.startedAt,
9341
+ endedAt: run.endedAt
9342
+ };
9343
+ }
9344
+ async function showPublicAnalysis(analysisId, cmd) {
9345
+ const outputFormat = getOutputFormat16(cmd);
9346
+ const api = createApiClient();
9347
+ const result = await api.analysis.get(analysisId);
9348
+ if (!result?.analysis) {
9349
+ throw new CliError(`No public analysis "${analysisId}".`, {
9350
+ hint: `List the public analyses with 'diafunc public list'.`
9351
+ });
9352
+ }
9353
+ const runs = await api.analysis.getRunsForAnalysis(analysisId, 1);
9354
+ const newestRun = runs?.[0] ?? null;
9355
+ if (outputFormat === "json") {
9356
+ format({ analysis: result.analysis, newestRun }, { format: outputFormat });
9357
+ return;
9358
+ }
9359
+ if (outputFormat === "table") {
9360
+ format({
9361
+ ...result.analysis,
9362
+ newestRunId: newestRun?.runId ?? null,
9363
+ newestRunState: newestRun?.state ?? null,
9364
+ newestRunSubmittedAt: newestRun?.submittedAt ?? null,
9365
+ newestRunStartedAt: newestRun?.startedAt ?? null,
9366
+ newestRunEndedAt: newestRun?.endedAt ?? null
9367
+ }, { format: outputFormat });
9368
+ return;
9369
+ }
9370
+ const details = analysisDetails(result.analysis, resolveEndpoint(loadConfig()));
9371
+ format(details.data, { format: outputFormat, columns: details.columns });
9372
+ heading("Newest run");
9373
+ if (!newestRun) {
9374
+ empty("runs");
9375
+ return;
9376
+ }
9377
+ format(newestRunRecord(newestRun), {
9378
+ format: outputFormat,
9379
+ columns: [
9380
+ { key: "runId", header: "Run ID", kind: "id" },
9381
+ { key: "state", header: "State", kind: "state" },
9382
+ { key: "phase", header: "Phase" },
9383
+ { key: "submittedAt", header: "Submitted", kind: "date" },
9384
+ { key: "startedAt", header: "Started", kind: "date" },
9385
+ { key: "endedAt", header: "Ended", kind: "date" }
9386
+ ]
9387
+ });
9388
+ }
9389
+ function registerPublicCommands(program) {
9390
+ const pub = program.command("public").description("Read the analyses their owners made public (no sign-in needed)").addHelpText("after", `
9391
+ Examples:
9392
+ $ diafunc public list the first 100 public analyses
9393
+ $ diafunc public list --all --output json every one of them, for a script
9394
+ $ diafunc public list --all --changed-since 2026-10-01 only those changed since that day
9395
+ $ diafunc public show <analysisId> one analysis and its newest run
9396
+ `);
9397
+ pub.command("list").description("List public analyses").option("--limit <n>", `Analyses per page (${MIN_LIMIT} to ${MAX_LIMIT})`, "100").option("--cursor <c>", "Continue from the cursor an earlier call ended with").option("--all", "Follow the pages to the end of the listing").option("--changed-since <ISO-8601>", "Only analyses changed at or after this date or instant").action(async (options, cmd) => {
9398
+ try {
9399
+ await listPublicAnalyses(options, cmd);
9400
+ } catch (error) {
9401
+ handleError(error);
9402
+ }
9403
+ });
9404
+ pub.command("show").description("Show a public analysis and its newest run").argument("<analysisId>", "Analysis ID").action(async (analysisId, _options, cmd) => {
9405
+ try {
9406
+ await showPublicAnalysis(analysisId, cmd);
9407
+ } catch (error) {
9408
+ handleError(error);
9409
+ }
9410
+ });
9411
+ }
9412
+
9413
+ // src/commands/data-sources/index.ts
9414
+ import chalk27 from "chalk";
9415
+ function getOutputFormat17(cmd) {
9416
+ const config = loadConfig();
9417
+ const globalOpts = cmd.optsWithGlobals();
9418
+ return globalOpts.output ?? config.defaults.output ?? "human";
9419
+ }
8557
9420
  function parseConfigPairs(pairs) {
8558
9421
  const out = {};
8559
9422
  if (!pairs) return out;
@@ -8649,7 +9512,7 @@ function resolveProjectId(cmd) {
8649
9512
  return resolved;
8650
9513
  }
8651
9514
  async function listDataSources(projectId, cmd) {
8652
- const outputFormat = getOutputFormat16(cmd);
9515
+ const outputFormat = getOutputFormat17(cmd);
8653
9516
  const api = createApiClient();
8654
9517
  const sources = await api.storage.listDataSources(projectId);
8655
9518
  if (outputFormat === "human" && sources.length === 0) {
@@ -8670,13 +9533,13 @@ async function listDataSources(projectId, cmd) {
8670
9533
  });
8671
9534
  }
8672
9535
  async function getDataSource(id, cmd) {
8673
- const outputFormat = getOutputFormat16(cmd);
9536
+ const outputFormat = getOutputFormat17(cmd);
8674
9537
  const api = createApiClient();
8675
9538
  const ds = await api.storage.getDataSource(id);
8676
9539
  format(ds, { format: outputFormat });
8677
9540
  }
8678
9541
  async function showDashboard(projectId, cmd) {
8679
- const outputFormat = getOutputFormat16(cmd);
9542
+ const outputFormat = getOutputFormat17(cmd);
8680
9543
  const api = createApiClient();
8681
9544
  const dashboard = await api.storage.getDataSourceDashboard(projectId);
8682
9545
  if (outputFormat !== "human") {
@@ -8684,7 +9547,7 @@ async function showDashboard(projectId, cmd) {
8684
9547
  return;
8685
9548
  }
8686
9549
  const r = dashboard.rollup;
8687
- let line = chalk26.bold(`DataSources in ${projectId}: `) + `${r.totalSources} total, ${r.scheduledSources} scheduled, ${r.sourcesWithRecentFailure} failing recently`;
9550
+ let line = chalk27.bold(`DataSources in ${projectId}: `) + `${r.totalSources} total, ${r.scheduledSources} scheduled, ${r.sourcesWithRecentFailure} failing recently`;
8688
9551
  if (r.lastActivityAt) line += `, last activity ${r.lastActivityAt}`;
8689
9552
  console.log(line);
8690
9553
  if (dashboard.sources.length === 0) {
@@ -8707,7 +9570,7 @@ async function showDashboard(projectId, cmd) {
8707
9570
  });
8708
9571
  }
8709
9572
  async function createDataSource(options, cmd) {
8710
- const outputFormat = getOutputFormat16(cmd);
9573
+ const outputFormat = getOutputFormat17(cmd);
8711
9574
  const api = createApiClient();
8712
9575
  const request = {
8713
9576
  projectId: options.projectId,
@@ -8722,14 +9585,14 @@ async function createDataSource(options, cmd) {
8722
9585
  const ds = await api.storage.createDataSource(request);
8723
9586
  if (outputFormat === "human") {
8724
9587
  success(`Created data source ${ds.id}`);
8725
- console.log(chalk26.dim(` Last run: ${ds.lastRunStatus ?? "\u2014"}`));
8726
- if (ds.lastRunError) console.log(chalk26.dim(` Error: ${ds.lastRunError}`));
9588
+ console.log(chalk27.dim(` Last run: ${ds.lastRunStatus ?? "\u2014"}`));
9589
+ if (ds.lastRunError) console.log(chalk27.dim(` Error: ${ds.lastRunError}`));
8727
9590
  } else {
8728
9591
  format(ds, { format: outputFormat });
8729
9592
  }
8730
9593
  }
8731
9594
  async function updateDataSource(id, options, cmd) {
8732
- const outputFormat = getOutputFormat16(cmd);
9595
+ const outputFormat = getOutputFormat17(cmd);
8733
9596
  if (options.name === void 0 && options.type === void 0 && (!options.config || options.config.length === 0) && options.scheduleCron === void 0 && !options.clearSchedule) {
8734
9597
  throw new Error("Provide at least one of --name, --type, --config, --schedule-cron, or --clear-schedule.");
8735
9598
  }
@@ -8764,18 +9627,18 @@ async function deleteDataSource(id) {
8764
9627
  success(`Deleted data source ${id}`);
8765
9628
  }
8766
9629
  async function refreshDataSource(id, cmd) {
8767
- const outputFormat = getOutputFormat16(cmd);
9630
+ const outputFormat = getOutputFormat17(cmd);
8768
9631
  const api = createApiClient();
8769
9632
  const run = await api.storage.refreshDataSource(id);
8770
9633
  if (outputFormat === "human") {
8771
9634
  success(`Refresh queued: run ${run.runId}, status ${run.status}.`);
8772
- if (run.errorMessage) console.log(chalk26.red(` Error: ${run.errorMessage}`));
9635
+ if (run.errorMessage) console.log(chalk27.red(` Error: ${run.errorMessage}`));
8773
9636
  } else {
8774
9637
  format(run, { format: outputFormat });
8775
9638
  }
8776
9639
  }
8777
9640
  async function listRuns2(id, limit, cmd) {
8778
- const outputFormat = getOutputFormat16(cmd);
9641
+ const outputFormat = getOutputFormat17(cmd);
8779
9642
  const api = createApiClient();
8780
9643
  const runs = await api.storage.listDataSourceRuns(id, limit);
8781
9644
  if (outputFormat === "human" && runs.length === 0) {
@@ -8797,13 +9660,13 @@ async function listRuns2(id, limit, cmd) {
8797
9660
  });
8798
9661
  }
8799
9662
  async function getRun(id, runId, cmd) {
8800
- const outputFormat = getOutputFormat16(cmd);
9663
+ const outputFormat = getOutputFormat17(cmd);
8801
9664
  const api = createApiClient();
8802
9665
  const run = await api.storage.getDataSourceRun(id, runId);
8803
9666
  format(run, { format: outputFormat });
8804
9667
  }
8805
9668
  async function listConnectorTypes(cmd) {
8806
- const outputFormat = getOutputFormat16(cmd);
9669
+ const outputFormat = getOutputFormat17(cmd);
8807
9670
  const api = createApiClient();
8808
9671
  const types = await api.storage.listDataSourceConnectorTypes();
8809
9672
  if (outputFormat === "human") {
@@ -8896,8 +9759,8 @@ Examples:
8896
9759
  }
8897
9760
 
8898
9761
  // src/commands/table-exporters/index.ts
8899
- import chalk27 from "chalk";
8900
- function getOutputFormat17(cmd) {
9762
+ import chalk28 from "chalk";
9763
+ function getOutputFormat18(cmd) {
8901
9764
  const config = loadConfig();
8902
9765
  const globalOpts = cmd.optsWithGlobals();
8903
9766
  return globalOpts.output ?? config.defaults.output ?? "human";
@@ -8906,7 +9769,7 @@ function registerTableExportersCommands(program) {
8906
9769
  const exporters = program.command("table-exporters").description("Manage user-defined exporters (UDE); admin only");
8907
9770
  exporters.command("list").description("List all registered user-defined exporters").action(async (_options, cmd) => {
8908
9771
  try {
8909
- const outputFormat = getOutputFormat17(cmd);
9772
+ const outputFormat = getOutputFormat18(cmd);
8910
9773
  const api = createApiClient();
8911
9774
  const list = await api.storage.listUserDefinedExporters();
8912
9775
  if (outputFormat === "json") {
@@ -8927,14 +9790,14 @@ function registerTableExportersCommands(program) {
8927
9790
  format: outputFormat,
8928
9791
  columns: ["id", "name", "format", "extension", "mimeType", "priority", "function", "createdBy"]
8929
9792
  });
8930
- console.log(chalk27.dim(`${list.length} exporter(s)`));
9793
+ console.log(chalk28.dim(`${list.length} exporter(s)`));
8931
9794
  } catch (error) {
8932
9795
  handleError(error);
8933
9796
  }
8934
9797
  });
8935
9798
  exporters.command("get").description("Show a single user-defined exporter by id").argument("<id>", "Exporter id").action(async (id, _options, cmd) => {
8936
9799
  try {
8937
- const outputFormat = getOutputFormat17(cmd);
9800
+ const outputFormat = getOutputFormat18(cmd);
8938
9801
  const api = createApiClient();
8939
9802
  const list = await api.storage.listUserDefinedExporters();
8940
9803
  const exporter = list.find((e) => e.id === id);
@@ -8949,7 +9812,7 @@ function registerTableExportersCommands(program) {
8949
9812
  });
8950
9813
  exporters.command("create").description("Register a new user-defined exporter").requiredOption("--name <name>", 'Display name (e.g. "Acme machine instrument export")').requiredOption("--format <token>", 'Format token used in the dispatch URL (e.g. "acme")').requiredOption("--function-project <id>", "Function entity's project id").requiredOption("--function-entity <id>", "Function entity id").option("--description <text>", "Free-form description").option("--extension <ext>", 'Filename extension (must start with ".")').option("--mime-type <mime>", "MIME type the function produces").option("--function-project-branch <branch>", "Function project branch", "main").option("--function-entity-branch <branch>", "Function entity branch", "main").option("--priority <n>", "Dispatch priority (default 50; > 200 overrides built-ins)", "50").action(async (options, cmd) => {
8951
9814
  try {
8952
- const outputFormat = getOutputFormat17(cmd);
9815
+ const outputFormat = getOutputFormat18(cmd);
8953
9816
  const api = createApiClient();
8954
9817
  const payload = {
8955
9818
  name: options.name,
@@ -8985,9 +9848,9 @@ function registerTableExportersCommands(program) {
8985
9848
  }
8986
9849
 
8987
9850
  // src/commands/skeleton/index.ts
8988
- import chalk28 from "chalk";
8989
- import * as fs9 from "fs";
8990
- function getOutputFormat18(cmd) {
9851
+ import chalk29 from "chalk";
9852
+ import * as fs10 from "fs";
9853
+ function getOutputFormat19(cmd) {
8991
9854
  const config = loadConfig();
8992
9855
  const globalOpts = cmd.optsWithGlobals();
8993
9856
  return globalOpts.output ?? config.defaults.output ?? "human";
@@ -9010,10 +9873,10 @@ function resolveTemplate(raw) {
9010
9873
  if (!file) {
9011
9874
  throw new Error("--template @ requires a filename after the @, e.g. --template @template.txt");
9012
9875
  }
9013
- if (!fs9.existsSync(file)) {
9876
+ if (!fs10.existsSync(file)) {
9014
9877
  throw new Error(`Template file not found: ${file}`);
9015
9878
  }
9016
- return fs9.readFileSync(file, "utf-8").trim();
9879
+ return fs10.readFileSync(file, "utf-8").trim();
9017
9880
  }
9018
9881
  return raw;
9019
9882
  }
@@ -9036,7 +9899,7 @@ function skeletonTableRow(s) {
9036
9899
  };
9037
9900
  }
9038
9901
  async function createSkeleton(options, cmd) {
9039
- const outputFormat = getOutputFormat18(cmd);
9902
+ const outputFormat = getOutputFormat19(cmd);
9040
9903
  const projectId = resolveProjectId2(cmd);
9041
9904
  const template = resolveTemplate(options.template);
9042
9905
  const weight = parseWeight(options.weight);
@@ -9052,16 +9915,16 @@ async function createSkeleton(options, cmd) {
9052
9915
  const skeleton = await api.storage.createSkeleton(request);
9053
9916
  if (outputFormat === "human") {
9054
9917
  success(`Created skeleton ${skeleton.id}`);
9055
- console.log(chalk28.dim(` name: ${skeleton.name}`));
9056
- console.log(chalk28.dim(` template: ${skeleton.template}`));
9057
- console.log(chalk28.dim(` paramCount: ${skeleton.paramCount}`));
9058
- console.log(chalk28.dim(` weight: ${skeleton.weight}`));
9918
+ console.log(chalk29.dim(` name: ${skeleton.name}`));
9919
+ console.log(chalk29.dim(` template: ${skeleton.template}`));
9920
+ console.log(chalk29.dim(` paramCount: ${skeleton.paramCount}`));
9921
+ console.log(chalk29.dim(` weight: ${skeleton.weight}`));
9059
9922
  } else {
9060
9923
  format(skeleton, { format: outputFormat });
9061
9924
  }
9062
9925
  }
9063
9926
  async function listSkeletons(cmd) {
9064
- const outputFormat = getOutputFormat18(cmd);
9927
+ const outputFormat = getOutputFormat19(cmd);
9065
9928
  const projectId = resolveProjectId2(cmd);
9066
9929
  const api = createApiClient();
9067
9930
  const skeletons = await api.storage.listSkeletons(projectId);
@@ -9075,13 +9938,13 @@ async function listSkeletons(cmd) {
9075
9938
  });
9076
9939
  }
9077
9940
  async function getSkeleton(id, cmd) {
9078
- const outputFormat = getOutputFormat18(cmd);
9941
+ const outputFormat = getOutputFormat19(cmd);
9079
9942
  const api = createApiClient();
9080
9943
  const skeleton = await api.storage.getSkeleton(id);
9081
9944
  format(skeleton, { format: outputFormat });
9082
9945
  }
9083
9946
  async function updateSkeleton(id, options, cmd) {
9084
- const outputFormat = getOutputFormat18(cmd);
9947
+ const outputFormat = getOutputFormat19(cmd);
9085
9948
  if (options.name === void 0 && options.template === void 0 && options.weight === void 0) {
9086
9949
  throw new Error("Provide at least one of --name, --template, --weight.");
9087
9950
  }
@@ -9094,10 +9957,10 @@ async function updateSkeleton(id, options, cmd) {
9094
9957
  const skeleton = await api.storage.updateSkeleton(id, request);
9095
9958
  if (outputFormat === "human") {
9096
9959
  success(`Updated skeleton ${skeleton.id}`);
9097
- console.log(chalk28.dim(` name: ${skeleton.name}`));
9098
- console.log(chalk28.dim(` template: ${skeleton.template}`));
9099
- console.log(chalk28.dim(` paramCount: ${skeleton.paramCount}`));
9100
- console.log(chalk28.dim(` weight: ${skeleton.weight}`));
9960
+ console.log(chalk29.dim(` name: ${skeleton.name}`));
9961
+ console.log(chalk29.dim(` template: ${skeleton.template}`));
9962
+ console.log(chalk29.dim(` paramCount: ${skeleton.paramCount}`));
9963
+ console.log(chalk29.dim(` weight: ${skeleton.weight}`));
9101
9964
  } else {
9102
9965
  format(skeleton, { format: outputFormat });
9103
9966
  }
@@ -9417,7 +10280,7 @@ function registerCompletionCommand(program) {
9417
10280
  }
9418
10281
 
9419
10282
  // src/commands/whoami/index.ts
9420
- import chalk29 from "chalk";
10283
+ import chalk30 from "chalk";
9421
10284
  function registerWhoamiCommand(program) {
9422
10285
  program.command("whoami").description("Show the currently authenticated user").action(async (_options, cmd) => {
9423
10286
  try {
@@ -9427,8 +10290,8 @@ function registerWhoamiCommand(program) {
9427
10290
  const api = createApiClient();
9428
10291
  const user = await api.admin.getMyUser();
9429
10292
  if (outputFormat === "human") {
9430
- console.log(chalk29.bold(user.name) + chalk29.dim(` <${user.email}>`));
9431
- console.log(chalk29.dim(` Role: ${user.role} \xB7 Remaining credits: ${user.remainingCredits} \xB7 Profile: ${config.currentProfile}`));
10293
+ console.log(chalk30.bold(user.name) + chalk30.dim(` <${user.email}>`));
10294
+ console.log(chalk30.dim(` Role: ${user.role} \xB7 Remaining credits: ${user.remainingCredits} \xB7 Profile: ${config.currentProfile}`));
9432
10295
  } else {
9433
10296
  format(user, { format: outputFormat });
9434
10297
  }
@@ -9439,8 +10302,8 @@ function registerWhoamiCommand(program) {
9439
10302
  }
9440
10303
 
9441
10304
  // src/commands/utilization/index.ts
9442
- import chalk30 from "chalk";
9443
- function getOutputFormat19(cmd) {
10305
+ import chalk31 from "chalk";
10306
+ function getOutputFormat20(cmd) {
9444
10307
  const config = loadConfig();
9445
10308
  const globalOpts = cmd.optsWithGlobals();
9446
10309
  return globalOpts.output ?? config.defaults.output ?? "human";
@@ -9456,19 +10319,19 @@ function windowLabel(u) {
9456
10319
  }
9457
10320
  function printUtilizationHuman(u, label) {
9458
10321
  const when2 = windowLabel(u);
9459
- console.log(label ? chalk30.bold(label) + " " + chalk30.dim(when2) : chalk30.bold(when2));
10322
+ console.log(label ? chalk31.bold(label) + " " + chalk31.dim(when2) : chalk31.bold(when2));
9460
10323
  if (u.types.length === 0) {
9461
- console.log(chalk30.dim(" (no usage)"));
10324
+ console.log(chalk31.dim(" (no usage)"));
9462
10325
  return;
9463
10326
  }
9464
10327
  const types = [...u.types].sort((a, b) => b.credits - a.credits);
9465
10328
  const width = Math.max(...types.map((t) => t.type.length));
9466
10329
  for (const t of types) {
9467
- const line = ` ${t.type.padEnd(width)} ${formatNumber(t.quantity).padStart(12)} ${chalk30.dim("credits")} ${t.credits.toFixed(2).padStart(10)}`;
9468
- console.log(t.credits === 0 ? chalk30.dim(line) : line);
10330
+ const line = ` ${t.type.padEnd(width)} ${formatNumber(t.quantity).padStart(12)} ${chalk31.dim("credits")} ${t.credits.toFixed(2).padStart(10)}`;
10331
+ console.log(t.credits === 0 ? chalk31.dim(line) : line);
9469
10332
  }
9470
10333
  const total = u.totalCredits ?? u.types.reduce((s, t) => s + t.credits, 0);
9471
- console.log(chalk30.bold(` ${"Total".padEnd(width)} ${" ".repeat(12)} ${chalk30.dim("credits")} ${total.toFixed(2).padStart(10)}`));
10334
+ console.log(chalk31.bold(` ${"Total".padEnd(width)} ${" ".repeat(12)} ${chalk31.dim("credits")} ${total.toFixed(2).padStart(10)}`));
9472
10335
  }
9473
10336
  function formatDailyHistory(history) {
9474
10337
  const spentOn = (u) => u.dailyCredits ?? u.types.reduce((sum, t) => sum + (t.dailyCredits ?? 0), 0);
@@ -9485,14 +10348,14 @@ function formatDailyHistory(history) {
9485
10348
  for (const u of history) {
9486
10349
  const spent = spentOn(u);
9487
10350
  total += spent;
9488
- const line = `${windowLabel(u).padEnd(width)} ${amount(spent)} ${chalk30.dim("credits")}`;
9489
- lines.push(spent > 0 ? chalk30.bold(line) : chalk30.dim(line));
10351
+ const line = `${windowLabel(u).padEnd(width)} ${amount(spent)} ${chalk31.dim("credits")}`;
10352
+ lines.push(spent > 0 ? chalk31.bold(line) : chalk31.dim(line));
9490
10353
  for (const t of costly(u)) {
9491
10354
  lines.push(` ${t.type.padEnd(width - 2)} ${amount(t.dailyCredits ?? 0)}`);
9492
10355
  }
9493
10356
  }
9494
10357
  lines.push("");
9495
- lines.push(chalk30.bold(`${totalLabel.padEnd(width)} ${amount(total)} ${chalk30.dim("credits")}`));
10358
+ lines.push(chalk31.bold(`${totalLabel.padEnd(width)} ${amount(total)} ${chalk31.dim("credits")}`));
9496
10359
  return lines;
9497
10360
  }
9498
10361
  function registerUtilizationCommand(program) {
@@ -9505,7 +10368,7 @@ Examples:
9505
10368
  `);
9506
10369
  util.command("actual", { isDefault: true }).description("Show current utilization (default subcommand)").action(async (_options, cmd) => {
9507
10370
  try {
9508
- const outputFormat = getOutputFormat19(cmd);
10371
+ const outputFormat = getOutputFormat20(cmd);
9509
10372
  const api = createApiClient();
9510
10373
  const utilization = await api.admin.getActualUtilization();
9511
10374
  if (outputFormat === "human") {
@@ -9519,7 +10382,7 @@ Examples:
9519
10382
  });
9520
10383
  util.command("history").description("Show what each day of the billing cycle cost").action(async (_options, cmd) => {
9521
10384
  try {
9522
- const outputFormat = getOutputFormat19(cmd);
10385
+ const outputFormat = getOutputFormat20(cmd);
9523
10386
  const api = createApiClient();
9524
10387
  const history = await api.admin.getUtilizationHistory();
9525
10388
  if (outputFormat === "human") {
@@ -9540,7 +10403,7 @@ Examples:
9540
10403
  }
9541
10404
 
9542
10405
  // src/commands/entity-branch/index.ts
9543
- function getOutputFormat20(cmd) {
10406
+ function getOutputFormat21(cmd) {
9544
10407
  const config = loadConfig();
9545
10408
  const globalOpts = cmd.optsWithGlobals();
9546
10409
  return globalOpts.output ?? config.defaults.output ?? "human";
@@ -9553,7 +10416,7 @@ function registerEntityBranchCommands(program) {
9553
10416
  const eb = program.command("entity-branch").description("Manage entity branches (parallel versions of a single entity)");
9554
10417
  eb.command("list").description("List branches of an entity").argument("<ref>", "Entity reference (projectId/branch/entityId)").action(async (ref, _options, cmd) => {
9555
10418
  try {
9556
- const outputFormat = getOutputFormat20(cmd);
10419
+ const outputFormat = getOutputFormat21(cmd);
9557
10420
  const overrides = getOverrides11(cmd);
9558
10421
  const resolved = parseEntityReference(ref, overrides);
9559
10422
  const api = createApiClient();
@@ -9605,7 +10468,7 @@ function forReader(subscription) {
9605
10468
  Object.entries(subscription).filter(([key]) => !BILLING_INTERNALS.has(key))
9606
10469
  );
9607
10470
  }
9608
- function getOutputFormat21(cmd) {
10471
+ function getOutputFormat22(cmd) {
9609
10472
  const config = loadConfig();
9610
10473
  const globalOpts = cmd.optsWithGlobals();
9611
10474
  return globalOpts.output ?? config.defaults.output ?? "human";
@@ -9619,7 +10482,7 @@ Examples:
9619
10482
  sub.command("current", { isDefault: true }).description("Show the current subscription").action(async (_options, cmd) => {
9620
10483
  try {
9621
10484
  const api = createApiClient();
9622
- const outputFormat = getOutputFormat21(cmd);
10485
+ const outputFormat = getOutputFormat22(cmd);
9623
10486
  const s = await api.admin.getCurrentSubscription();
9624
10487
  format(outputFormat === "human" ? forReader(s) : s, { format: outputFormat });
9625
10488
  } catch (error) {
@@ -9629,7 +10492,7 @@ Examples:
9629
10492
  sub.command("next").description("Show the next (upcoming) subscription").action(async (_options, cmd) => {
9630
10493
  try {
9631
10494
  const api = createApiClient();
9632
- const outputFormat = getOutputFormat21(cmd);
10495
+ const outputFormat = getOutputFormat22(cmd);
9633
10496
  const s = await api.admin.getNextSubscription();
9634
10497
  format(outputFormat === "human" ? forReader(s) : s, { format: outputFormat });
9635
10498
  } catch (error) {
@@ -9640,7 +10503,7 @@ Examples:
9640
10503
  try {
9641
10504
  const api = createApiClient();
9642
10505
  const plans = await api.admin.getSubscriptionPlans(subscriptionToken);
9643
- format(plans, { format: getOutputFormat21(cmd) });
10506
+ format(plans, { format: getOutputFormat22(cmd) });
9644
10507
  } catch (error) {
9645
10508
  handleError(error);
9646
10509
  }
@@ -9648,8 +10511,8 @@ Examples:
9648
10511
  }
9649
10512
 
9650
10513
  // src/commands/invoice/index.ts
9651
- import * as fs10 from "fs";
9652
- function getOutputFormat22(cmd) {
10514
+ import * as fs11 from "fs";
10515
+ function getOutputFormat23(cmd) {
9653
10516
  const config = loadConfig();
9654
10517
  const globalOpts = cmd.optsWithGlobals();
9655
10518
  return globalOpts.output ?? config.defaults.output ?? "human";
@@ -9666,7 +10529,7 @@ Examples:
9666
10529
  const api = createApiClient();
9667
10530
  const invoices = await api.admin.getInvoices();
9668
10531
  format(invoices, {
9669
- format: getOutputFormat22(cmd),
10532
+ format: getOutputFormat23(cmd),
9670
10533
  columns: [
9671
10534
  { key: "invoiceNumber", header: "number" },
9672
10535
  { key: "issued", kind: "date" },
@@ -9686,7 +10549,7 @@ Examples:
9686
10549
  const response = await api.admin.downloadInvoice(invoiceNumber, fileName);
9687
10550
  const buffer = Buffer.from(await response.arrayBuffer());
9688
10551
  const outPath = options.out ?? fileName;
9689
- fs10.writeFileSync(outPath, buffer);
10552
+ fs11.writeFileSync(outPath, buffer);
9690
10553
  success(`Invoice saved to ${outPath}`);
9691
10554
  } catch (error) {
9692
10555
  handleError(error);
@@ -9695,10 +10558,10 @@ Examples:
9695
10558
  }
9696
10559
 
9697
10560
  // src/commands/shell/index.ts
9698
- import chalk31 from "chalk";
9699
- import * as fs11 from "fs";
10561
+ import chalk32 from "chalk";
10562
+ import * as fs12 from "fs";
9700
10563
  import * as os3 from "os";
9701
- import * as path8 from "path";
10564
+ import * as path9 from "path";
9702
10565
  import { spawn as spawn3 } from "child_process";
9703
10566
  import { randomUUID as randomUUID3 } from "crypto";
9704
10567
  function extensionFor2(language) {
@@ -9711,16 +10574,16 @@ function extensionFor2(language) {
9711
10574
  return "txt";
9712
10575
  }
9713
10576
  async function openInEditor(initial, ext) {
9714
- const tmpFile = path8.join(os3.tmpdir(), `diafunc-shell-${randomUUID3()}.${ext}`);
9715
- fs11.writeFileSync(tmpFile, initial);
10577
+ const tmpFile = path9.join(os3.tmpdir(), `diafunc-shell-${randomUUID3()}.${ext}`);
10578
+ fs12.writeFileSync(tmpFile, initial);
9716
10579
  const editor = process.env.VISUAL ?? process.env.EDITOR ?? "vi";
9717
10580
  await new Promise((resolve, reject) => {
9718
10581
  const child = spawn3(editor, [tmpFile], { stdio: "inherit" });
9719
10582
  child.on("exit", (code) => code === 0 ? resolve() : reject(new Error(`Editor exited with ${code}`)));
9720
10583
  child.on("error", reject);
9721
10584
  });
9722
- const content = fs11.readFileSync(tmpFile, "utf-8");
9723
- fs11.unlinkSync(tmpFile);
10585
+ const content = fs12.readFileSync(tmpFile, "utf-8");
10586
+ fs12.unlinkSync(tmpFile);
9724
10587
  return content;
9725
10588
  }
9726
10589
  function utcNowParts() {
@@ -9761,21 +10624,21 @@ async function evaluate(api, fnRef, language, sourceCode) {
9761
10624
  }, false);
9762
10625
  if (result.outputs?.length) {
9763
10626
  for (const out of result.outputs) {
9764
- console.log(chalk31.dim(` [${out.type}]`) + " " + out.output);
10627
+ console.log(chalk32.dim(` [${out.type}]`) + " " + out.output);
9765
10628
  }
9766
10629
  }
9767
10630
  if (result.successful) {
9768
10631
  if (result.result) {
9769
- console.log(chalk31.green("=>") + " " + result.result);
10632
+ console.log(chalk32.green("=>") + " " + result.result);
9770
10633
  } else {
9771
- console.log(chalk31.dim("=> (no value)"));
10634
+ console.log(chalk32.dim("=> (no value)"));
9772
10635
  }
9773
10636
  const duration = result.completed - result.started;
9774
- console.log(chalk31.dim(` [${duration}ms \xB7 ${evaluationId}]`));
10637
+ console.log(chalk32.dim(` [${duration}ms \xB7 ${evaluationId}]`));
9775
10638
  } else {
9776
- console.log(chalk31.red("error: ") + result.error);
10639
+ console.log(chalk32.red("error: ") + result.error);
9777
10640
  if (result.lineNumber > 0) {
9778
- console.log(chalk31.dim(` at line ${result.lineNumber}, col ${result.columnNumber}`));
10641
+ console.log(chalk32.dim(` at line ${result.lineNumber}, col ${result.columnNumber}`));
9779
10642
  }
9780
10643
  }
9781
10644
  }
@@ -9796,19 +10659,19 @@ function registerShellCommand(program) {
9796
10659
  });
9797
10660
  const api = createApiClient();
9798
10661
  const { input: promptInput } = await import("@inquirer/prompts");
9799
- const { getUpdateNotice } = await import("./update-check-HMBNFIA5.js");
10662
+ const { getUpdateNotice } = await import("./update-check-7F4ABBDC.js");
9800
10663
  const resolvedLanguage = await resolveLanguage(api, fnRef.projectId, options.language);
9801
- console.log(chalk31.bold("Diafunc shell") + chalk31.dim(` \xB7 function ${fnRef.entityId} \xB7 ${resolvedLanguage}`));
9802
- console.log(chalk31.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
9803
- console.log(chalk31.dim("Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit"));
10664
+ console.log(chalk32.bold("Diafunc shell") + chalk32.dim(` \xB7 function ${fnRef.entityId} \xB7 ${resolvedLanguage}`));
10665
+ console.log(chalk32.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
10666
+ console.log(chalk32.dim("Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit"));
9804
10667
  const notice = await getUpdateNotice();
9805
- if (notice) console.log(chalk31.dim(notice));
10668
+ if (notice) console.log(chalk32.dim(notice));
9806
10669
  console.log();
9807
10670
  let language = resolvedLanguage;
9808
10671
  for (; ; ) {
9809
10672
  let line;
9810
10673
  try {
9811
- line = await promptInput({ message: chalk31.cyan.bold(`${language} >`) });
10674
+ line = await promptInput({ message: chalk32.cyan.bold(`${language} >`) });
9812
10675
  } catch {
9813
10676
  console.log();
9814
10677
  return;
@@ -9826,54 +10689,54 @@ function registerShellCommand(program) {
9826
10689
  case "help":
9827
10690
  case "h":
9828
10691
  case "?":
9829
- console.log(chalk31.dim(" /edit open $EDITOR for multi-line code"));
9830
- console.log(chalk31.dim(" /file <path> evaluate the contents of a file"));
9831
- console.log(chalk31.dim(" /lang <name> switch language (Java, JavaScript, Kotlin, Python, Scala)"));
9832
- console.log(chalk31.dim(" /quit exit the shell"));
10692
+ console.log(chalk32.dim(" /edit open $EDITOR for multi-line code"));
10693
+ console.log(chalk32.dim(" /file <path> evaluate the contents of a file"));
10694
+ console.log(chalk32.dim(" /lang <name> switch language (Java, JavaScript, Kotlin, Python, Scala)"));
10695
+ console.log(chalk32.dim(" /quit exit the shell"));
9833
10696
  continue;
9834
10697
  case "lang":
9835
10698
  if (arg) language = arg;
9836
- console.log(chalk31.dim(`Language: ${language}`));
10699
+ console.log(chalk32.dim(`Language: ${language}`));
9837
10700
  continue;
9838
10701
  case "edit": {
9839
10702
  const sourceCode = await openInEditor("", extensionFor2(language));
9840
10703
  if (!sourceCode.trim()) {
9841
- console.log(chalk31.dim("(empty; not evaluated)"));
10704
+ console.log(chalk32.dim("(empty; not evaluated)"));
9842
10705
  continue;
9843
10706
  }
9844
10707
  try {
9845
10708
  await evaluate(api, fnRef, language, sourceCode);
9846
10709
  } catch (e) {
9847
- console.error(chalk31.red(e.message));
10710
+ console.error(chalk32.red(e.message));
9848
10711
  }
9849
10712
  continue;
9850
10713
  }
9851
10714
  case "file": {
9852
10715
  if (!arg) {
9853
- console.log(chalk31.dim("usage: /file <path>"));
10716
+ console.log(chalk32.dim("usage: /file <path>"));
9854
10717
  continue;
9855
10718
  }
9856
- if (!fs11.existsSync(arg)) {
9857
- console.log(chalk31.red(`file not found: ${arg}`));
10719
+ if (!fs12.existsSync(arg)) {
10720
+ console.log(chalk32.red(`file not found: ${arg}`));
9858
10721
  continue;
9859
10722
  }
9860
- const sourceCode = fs11.readFileSync(arg, "utf-8");
10723
+ const sourceCode = fs12.readFileSync(arg, "utf-8");
9861
10724
  try {
9862
10725
  await evaluate(api, fnRef, language, sourceCode);
9863
10726
  } catch (e) {
9864
- console.error(chalk31.red(e.message));
10727
+ console.error(chalk32.red(e.message));
9865
10728
  }
9866
10729
  continue;
9867
10730
  }
9868
10731
  default:
9869
- console.log(chalk31.dim(`Unknown command: /${cmd2}. Try /help.`));
10732
+ console.log(chalk32.dim(`Unknown command: /${cmd2}. Try /help.`));
9870
10733
  continue;
9871
10734
  }
9872
10735
  }
9873
10736
  try {
9874
10737
  await evaluate(api, fnRef, language, trimmed);
9875
10738
  } catch (e) {
9876
- console.error(chalk31.red(e.message));
10739
+ console.error(chalk32.red(e.message));
9877
10740
  }
9878
10741
  }
9879
10742
  } catch (error) {
@@ -9883,19 +10746,19 @@ function registerShellCommand(program) {
9883
10746
  }
9884
10747
 
9885
10748
  // src/commands/update/index.ts
9886
- import chalk32 from "chalk";
9887
- import * as path9 from "path";
10749
+ import chalk33 from "chalk";
10750
+ import * as path10 from "path";
9888
10751
  import { spawn as spawn4 } from "child_process";
9889
10752
 
9890
10753
  // src/util/install-method.ts
9891
- import * as fs12 from "fs";
10754
+ import * as fs13 from "fs";
9892
10755
  function detectInstall() {
9893
10756
  const exec = process.execPath;
9894
10757
  const exe = exec.replace(/\\/g, "/").toLowerCase();
9895
10758
  const isNode = exe.endsWith("/node") || exe.endsWith("/node.exe");
9896
10759
  return {
9897
10760
  method: isNode ? "npm" : "binary",
9898
- binaryPath: isNode ? exec : fs12.realpathSync(exec)
10761
+ binaryPath: isNode ? exec : fs13.realpathSync(exec)
9899
10762
  };
9900
10763
  }
9901
10764
 
@@ -9929,17 +10792,17 @@ function registerUpdateCommand(program) {
9929
10792
  const install = detectInstall();
9930
10793
  const latest = await fetchLatestVersion();
9931
10794
  if (latest === package_default.version) {
9932
- console.log(chalk32.dim(`diafunc is already at the latest version (${package_default.version}).`));
10795
+ console.log(chalk33.dim(`diafunc is already at the latest version (${package_default.version}).`));
9933
10796
  return;
9934
10797
  }
9935
- console.log(chalk32.dim(`Current: ${package_default.version} \u2192 Available: ${latest}`));
10798
+ console.log(chalk33.dim(`Current: ${package_default.version} \u2192 Available: ${latest}`));
9936
10799
  if (install.method === "npm") {
9937
10800
  console.log();
9938
10801
  console.log("Installed via npm. Upgrade with:");
9939
- console.log(chalk32.bold(` npm install -g @diafunc/cli@${latest}`));
10802
+ console.log(chalk33.bold(` npm install -g @diafunc/cli@${latest}`));
9940
10803
  return;
9941
10804
  }
9942
- const installDir = path9.dirname(install.binaryPath);
10805
+ const installDir = path10.dirname(install.binaryPath);
9943
10806
  console.log(`Installing diafunc ${latest} to ${installDir}...`);
9944
10807
  console.log();
9945
10808
  await runInstaller(installDir);
@@ -9950,23 +10813,23 @@ function registerUpdateCommand(program) {
9950
10813
  }
9951
10814
 
9952
10815
  // src/commands/uninstall/index.ts
9953
- import chalk33 from "chalk";
10816
+ import chalk34 from "chalk";
9954
10817
  import { spawn as spawn5 } from "child_process";
9955
- import * as fs13 from "fs";
10818
+ import * as fs14 from "fs";
9956
10819
  import * as os4 from "os";
9957
- import * as path10 from "path";
10820
+ import * as path11 from "path";
9958
10821
  function registerUninstallCommand(program) {
9959
10822
  program.command("uninstall").description("Remove the CLI binary and (optionally) its config from this machine").option("-y, --yes", "Skip confirmation prompts").option("--purge", "Also remove ~/.diafunc/ (config + credentials) without prompting").action(async (options) => {
9960
10823
  try {
9961
10824
  const install = detectInstall();
9962
- const configDir = path10.join(os4.homedir(), ".diafunc");
10825
+ const configDir = path11.join(os4.homedir(), ".diafunc");
9963
10826
  if (install.method === "npm") {
9964
10827
  console.log("Installed via npm. Remove with:");
9965
- console.log(chalk33.bold(" npm uninstall -g @diafunc/cli"));
9966
- if (fs13.existsSync(configDir)) {
10828
+ console.log(chalk34.bold(" npm uninstall -g @diafunc/cli"));
10829
+ if (fs14.existsSync(configDir)) {
9967
10830
  console.log();
9968
10831
  console.log(`Config and credentials live at ${configDir}. Remove them manually with:`);
9969
- console.log(chalk33.bold(` rm -rf ${configDir}`));
10832
+ console.log(chalk34.bold(` rm -rf ${configDir}`));
9970
10833
  }
9971
10834
  return;
9972
10835
  }
@@ -9976,19 +10839,19 @@ function registerUninstallCommand(program) {
9976
10839
  default: false
9977
10840
  });
9978
10841
  if (!removeBinary) {
9979
- console.log(chalk33.dim("Aborted."));
10842
+ console.log(chalk34.dim("Aborted."));
9980
10843
  return;
9981
10844
  }
9982
10845
  let removeConfig = options.purge ?? false;
9983
- if (!options.purge && !options.yes && fs13.existsSync(configDir)) {
10846
+ if (!options.purge && !options.yes && fs14.existsSync(configDir)) {
9984
10847
  removeConfig = await confirm({
9985
10848
  message: `Also remove ${configDir} (config + credentials)?`,
9986
10849
  default: false
9987
10850
  });
9988
10851
  }
9989
- if (removeConfig && fs13.existsSync(configDir)) {
9990
- fs13.rmSync(configDir, { recursive: true, force: true });
9991
- console.log(chalk33.dim(`Removed ${configDir}`));
10852
+ if (removeConfig && fs14.existsSync(configDir)) {
10853
+ fs14.rmSync(configDir, { recursive: true, force: true });
10854
+ console.log(chalk34.dim(`Removed ${configDir}`));
9992
10855
  }
9993
10856
  if (process.platform === "win32") {
9994
10857
  const cmd = `timeout /t 2 /nobreak >nul & del /f /q "${install.binaryPath}"`;
@@ -9998,13 +10861,13 @@ function registerUninstallCommand(program) {
9998
10861
  windowsHide: true
9999
10862
  });
10000
10863
  child.unref();
10001
- console.log(chalk33.dim(`Removing ${install.binaryPath} on exit...`));
10864
+ console.log(chalk34.dim(`Removing ${install.binaryPath} on exit...`));
10002
10865
  console.log();
10003
10866
  console.log("diafunc uninstalled.");
10004
10867
  return;
10005
10868
  }
10006
- fs13.rmSync(install.binaryPath, { force: true });
10007
- console.log(chalk33.dim(`Removed ${install.binaryPath}`));
10869
+ fs14.rmSync(install.binaryPath, { force: true });
10870
+ console.log(chalk34.dim(`Removed ${install.binaryPath}`));
10008
10871
  console.log();
10009
10872
  console.log("diafunc uninstalled.");
10010
10873
  } catch (error) {
@@ -10068,7 +10931,7 @@ var DiafuncCommand = class _DiafuncCommand extends Command {
10068
10931
  };
10069
10932
 
10070
10933
  // src/prompting/fill.ts
10071
- import chalk35 from "chalk";
10934
+ import chalk36 from "chalk";
10072
10935
 
10073
10936
  // src/prompting/resolvers.ts
10074
10937
  var PROJECT_ROLES = ["OWNER", "ADMIN", "DEVELOPER", "GUEST"];
@@ -10089,12 +10952,14 @@ var POSITIVE = { kind: "number", min: 0, integer: false, exclusive: true };
10089
10952
  var INDEX = { kind: "number", min: 0, integer: true };
10090
10953
  var BY_COMMAND = {
10091
10954
  "analyze segment": { "<name>": { kind: "analysisColumns", multiple: false, allowEmpty: true } },
10092
- "analyze targets": { "<csv>": { kind: "analysisColumns", multiple: true, allowEmpty: false } },
10093
- "analyze feature-exclusions": { "<csv>": { kind: "analysisColumns", multiple: true, allowEmpty: true } },
10094
- "analyze confirmed-inputs": { "<csv>": { kind: "analysisColumns", multiple: true, allowEmpty: true } },
10955
+ "analyze targets": { "<column>": { kind: "analysisColumns", multiple: true, allowEmpty: false } },
10956
+ "analyze feature-exclusions": { "<column>": { kind: "analysisColumns", multiple: true, allowEmpty: true } },
10957
+ "analyze confirmed-inputs": { "<column>": { kind: "analysisColumns", multiple: true, allowEmpty: true } },
10095
10958
  "analyze questions": { "<question>": TEXT_OR_EMPTY },
10096
10959
  "analyze description": { "<text>": TEXT_OR_EMPTY },
10097
10960
  "analyze introduction": { "<markdown>": TEXT_OR_EMPTY },
10961
+ // Not the analysis picker: that one offers the reader's own analyses, and this command needs no account.
10962
+ "public show": { "<analysisId>": TEXT },
10098
10963
  "analyze presets save": { "--targets": TEXT, "--hours": POSITIVE, "--budget": POSITIVE },
10099
10964
  "branch merge": {
10100
10965
  "--source": { kind: "entity", form: "ref" },
@@ -10191,11 +11056,11 @@ var BY_NAME = {
10191
11056
  function tokenOf(input) {
10192
11057
  return input.kind === "option" ? input.flag ?? `--${input.name}` : `<${input.name}>`;
10193
11058
  }
10194
- function specFor(path11, input) {
10195
- const exact = BY_COMMAND[path11]?.[tokenOf(input)];
11059
+ function specFor(path12, input) {
11060
+ const exact = BY_COMMAND[path12]?.[tokenOf(input)];
10196
11061
  if (exact) return exact;
10197
- const group = path11.split(" ")[0];
10198
- const sub = path11.split(" ").slice(0, 2).join(" ");
11062
+ const group = path12.split(" ")[0];
11063
+ const sub = path12.split(" ").slice(0, 2).join(" ");
10199
11064
  switch (input.name) {
10200
11065
  case "ref":
10201
11066
  case "sourceRef":
@@ -10262,8 +11127,8 @@ function dependencies(spec) {
10262
11127
  }
10263
11128
 
10264
11129
  // src/prompting/pickers.ts
10265
- import * as fs14 from "fs";
10266
- import chalk34 from "chalk";
11130
+ import * as fs15 from "fs";
11131
+ import chalk35 from "chalk";
10267
11132
  var SEARCH_THRESHOLD = 10;
10268
11133
  var TYPE_IT = "\0type-it";
10269
11134
  async function askFor(spec, input, ctx) {
@@ -10397,7 +11262,7 @@ async function askFor(spec, input, ctx) {
10397
11262
  }
10398
11263
  case "file":
10399
11264
  return typed(ctx, question(input), {
10400
- validate: (value) => fs14.existsSync(value.trim()) || `No file at ${value.trim()}.`
11265
+ validate: (value) => fs15.existsSync(value.trim()) || `No file at ${value.trim()}.`
10401
11266
  });
10402
11267
  case "number":
10403
11268
  return typed(ctx, question(input), { validate: numberRule(spec) });
@@ -10521,7 +11386,7 @@ async function askColumns(ctx, spec, input) {
10521
11386
  choices: columns.map((c) => ({ name: c, value: c })),
10522
11387
  validate: (picked) => picked.length > 0 || "Pick at least one column."
10523
11388
  });
10524
- return chosen.join(",");
11389
+ return chosen;
10525
11390
  }
10526
11391
  const items = columns.map((c) => ({ label: c, value: c }));
10527
11392
  if (spec.allowEmpty) items.unshift({ label: "None (clear it)", value: "" });
@@ -10611,7 +11476,7 @@ function typedValue(ctx, message) {
10611
11476
  return typed(ctx, message);
10612
11477
  }
10613
11478
  function typeItChoice() {
10614
- return { name: chalk34.dim("Type it instead"), value: TYPE_IT };
11479
+ return { name: chalk35.dim("Type it instead"), value: TYPE_IT };
10615
11480
  }
10616
11481
  function text(ctx, name) {
10617
11482
  const value = ctx.known.get(name);
@@ -10641,7 +11506,7 @@ function capitalize(value) {
10641
11506
  return value.charAt(0).toUpperCase() + value.slice(1);
10642
11507
  }
10643
11508
  function labelled(label, hint2) {
10644
- return hint2 && hint2 !== label ? `${label} ${chalk34.dim(hint2)}` : label;
11509
+ return hint2 && hint2 !== label ? `${label} ${chalk35.dim(hint2)}` : label;
10645
11510
  }
10646
11511
  function numberRule(spec) {
10647
11512
  return (raw) => {
@@ -10687,7 +11552,7 @@ async function fillPendingInputs(actionCommand) {
10687
11552
  known: knownValues(actionCommand),
10688
11553
  globals: actionCommand.optsWithGlobals(),
10689
11554
  prefill: /* @__PURE__ */ new Map(),
10690
- note: (line) => process.stderr.write(chalk35.dim(` ${line}
11555
+ note: (line) => process.stderr.write(chalk36.dim(` ${line}
10691
11556
  `))
10692
11557
  };
10693
11558
  for (const item of orderByDependencies(pending)) {
@@ -10696,7 +11561,7 @@ async function fillPendingInputs(actionCommand) {
10696
11561
  ctx.known.set(item.input.name, value);
10697
11562
  }
10698
11563
  const log = env.log ?? ((line) => console.log(line));
10699
- log(chalk35.dim(` Equivalent: ${equivalentCommand(actionCommand)}`));
11564
+ log(chalk36.dim(` Equivalent: ${equivalentCommand(actionCommand)}`));
10700
11565
  }
10701
11566
  function commandChain(cmd) {
10702
11567
  const chain = [];
@@ -10801,7 +11666,7 @@ function createProgram(environment = {}) {
10801
11666
  const opts = thisCommand.optsWithGlobals();
10802
11667
  if (opts.dryRun) setDryRun(true);
10803
11668
  if (opts.verbose) setVerbose(true);
10804
- if (opts.color === false) chalk36.level = 0;
11669
+ if (opts.color === false) chalk37.level = 0;
10805
11670
  }).hook("preAction", (_thisCommand, actionCommand) => fillPendingInputs(actionCommand));
10806
11671
  program.addHelpText("after", HELP_EPILOGUE);
10807
11672
  registerAuthCommands(program);
@@ -10822,6 +11687,7 @@ function createProgram(environment = {}) {
10822
11687
  registerAdminCommands(program);
10823
11688
  registerStatusCommands(program);
10824
11689
  registerAnalyzeCommand(program);
11690
+ registerPublicCommands(program);
10825
11691
  registerDataSourcesCommands(program);
10826
11692
  registerTableExportersCommands(program);
10827
11693
  registerSkeletonCommands(program);
@@ -10843,4 +11709,4 @@ export {
10843
11709
  PromptCancelled,
10844
11710
  createProgram
10845
11711
  };
10846
- //# sourceMappingURL=chunk-ZVC7B6VZ.js.map
11712
+ //# sourceMappingURL=chunk-D7AJH4Y3.js.map