@diafunc/cli 0.9.1 → 0.10.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,12 +1,13 @@
1
1
  import {
2
2
  package_default
3
- } from "./chunk-VKUAIYZZ.js";
3
+ } from "./chunk-B3VUD7NV.js";
4
4
 
5
5
  // src/index.ts
6
6
  import { Command } from "commander";
7
+ import chalk34 from "chalk";
7
8
 
8
9
  // src/commands/auth/login.ts
9
- import chalk2 from "chalk";
10
+ import chalk4 from "chalk";
10
11
 
11
12
  // src/config/store.ts
12
13
  import * as fs from "fs";
@@ -53,6 +54,9 @@ function resolveEndpoint(config, profileOverride) {
53
54
  return profile.endpoint.replace(/\/+$/, "");
54
55
  }
55
56
 
57
+ // src/client/http.ts
58
+ import chalk from "chalk";
59
+
56
60
  // src/client/errors.ts
57
61
  var ApiError = class _ApiError extends Error {
58
62
  status;
@@ -67,22 +71,47 @@ var ApiError = class _ApiError extends Error {
67
71
  return new _ApiError(status, body.message, body.details);
68
72
  }
69
73
  toUserMessage() {
74
+ const detail2 = this.readableMessage();
70
75
  switch (this.status) {
71
76
  case 401:
72
- return `Authentication failed. Run 'diafunc auth login' to configure your credentials.`;
77
+ return `Authentication failed. Run 'diafunc auth login' to sign in again.`;
73
78
  case 403:
74
- return this.message ? `Permission denied: ${this.message}${this.details ? ` (${this.details})` : ""}` : `Permission denied. Your token may not have the required scope.`;
79
+ return detail2 ? `Permission denied: ${detail2}` : `Permission denied. Your account or token lacks the required access.`;
75
80
  case 404:
76
- return `Not found: ${this.message}`;
81
+ return detail2 ? `Not found: ${detail2}` : `Not found: the server has no such resource.`;
77
82
  case 409:
78
- return `Conflict: ${this.message}`;
83
+ return detail2 ? `Conflict: ${detail2}` : `Conflict: the resource changed under this request.`;
79
84
  case 429:
80
- return `Rate limited. Please wait before retrying.`;
85
+ return `Rate limited. Wait a moment and try again.`;
86
+ case 500:
87
+ case 502:
88
+ case 503:
89
+ case 504:
90
+ return detail2 ? `The Diafunc platform returned ${this.status}: ${detail2}` : `The Diafunc platform returned ${this.status}. Check 'diafunc status summary'.`;
81
91
  default:
82
- return this.details ? `${this.message} (${this.details})` : this.message;
92
+ return detail2 || `The request failed with status ${this.status}.`;
83
93
  }
84
94
  }
95
+ /**
96
+ * The server's message, or nothing when what came back was not meant for a person.
97
+ *
98
+ * A gateway answering with its own HTML error page used to be surfaced verbatim, so a missing
99
+ * endpoint read as
100
+ * `Error: Not found: <html><head><title>Error</title></head><body>Not Found</body></html>`.
101
+ * Markup is never the explanation the reader needs, so it is dropped in favour of the
102
+ * status-derived sentence above.
103
+ */
104
+ readableMessage() {
105
+ const message = (this.message ?? "").trim();
106
+ if (!message || looksLikeMarkup(message)) return "";
107
+ const withDetails = this.details && !looksLikeMarkup(this.details) ? `${message} (${this.details})` : message;
108
+ return withDetails;
109
+ }
85
110
  };
111
+ function looksLikeMarkup(text) {
112
+ const head = text.trimStart().slice(0, 200).toLowerCase();
113
+ return head.startsWith("<") || head.includes("<html") || head.includes("<!doctype");
114
+ }
86
115
  var NetworkError = class extends Error {
87
116
  constructor(message, cause) {
88
117
  super(message);
@@ -92,6 +121,10 @@ var NetworkError = class extends Error {
92
121
  };
93
122
 
94
123
  // src/client/http.ts
124
+ var REQUEST_TIMEOUT_MS = 6e4;
125
+ var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
126
+ var MAX_ATTEMPTS = 3;
127
+ var RETRYABLE_METHODS = /* @__PURE__ */ new Set(["GET"]);
95
128
  function buildUrl(endpoint, service, path11, query) {
96
129
  const base = `${endpoint}/api/v1/${service}${path11}`;
97
130
  const params = new URLSearchParams();
@@ -181,16 +214,29 @@ async function parseErrorBody(response) {
181
214
  const body = await response.json();
182
215
  return ApiError.fromBody(response.status, body);
183
216
  }
184
- const text = await response.text();
217
+ const text = (await response.text()).trim();
185
218
  return new ApiError(response.status, text || response.statusText);
186
219
  } catch {
187
220
  return new ApiError(response.status, response.statusText);
188
221
  }
189
222
  }
190
223
  var _dryRun = false;
224
+ var _verbose = false;
191
225
  function setDryRun(enabled) {
192
226
  _dryRun = enabled;
193
227
  }
228
+ function setVerbose(enabled) {
229
+ _verbose = enabled;
230
+ }
231
+ function trace(line) {
232
+ if (_verbose) console.error(chalk.dim(` [http] ${line}`));
233
+ }
234
+ function isTransient(error) {
235
+ if (error.name === "TimeoutError" || error.name === "AbortError") return false;
236
+ const cause = error.cause;
237
+ const code = cause?.code ?? "";
238
+ return ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT", "ENOTFOUND", "EAI_AGAIN"].includes(code);
239
+ }
194
240
  function createHttpClient(options = {}) {
195
241
  const config = loadConfig();
196
242
  const endpoint = resolveEndpoint(config, options.profileOverride);
@@ -198,10 +244,10 @@ function createHttpClient(options = {}) {
198
244
  if (_dryRun && opts.method !== "GET") {
199
245
  const url2 = buildUrl(endpoint, opts.service, opts.path, opts.query);
200
246
  const bodyPreview = opts.body ? JSON.stringify(opts.body, null, 2) : opts.rawBody ? "(binary)" : "(none)";
201
- console.log(`[dry-run] ${opts.method} ${url2}`);
247
+ console.error(chalk.yellow(`[dry-run] ${opts.method} ${url2}`));
202
248
  if (opts.body) {
203
- console.log(`[dry-run] Body:
204
- ${bodyPreview}`);
249
+ console.error(chalk.dim(`[dry-run] Body:
250
+ ${bodyPreview}`));
205
251
  }
206
252
  return new Response("{}", { status: 200, headers: { "content-type": "application/json" } });
207
253
  }
@@ -224,18 +270,49 @@ ${bodyPreview}`);
224
270
  headers["Content-Type"] = "application/json";
225
271
  body = JSON.stringify(opts.body);
226
272
  }
227
- try {
228
- return await fetch(url, {
229
- method: opts.method,
230
- headers,
231
- body
232
- });
233
- } catch (err) {
273
+ headers["User-Agent"] = `diafunc-cli/${package_default.version} (${process.platform}; node ${process.versions.node})`;
274
+ const retryable = RETRYABLE_METHODS.has(opts.method);
275
+ const maxAttempts = retryable ? MAX_ATTEMPTS : 1;
276
+ let lastError;
277
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
278
+ const startedAt = Date.now();
279
+ try {
280
+ const response = await fetch(url, {
281
+ method: opts.method,
282
+ headers,
283
+ body,
284
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
285
+ });
286
+ trace(`${opts.method} ${url} -> ${response.status} (${Date.now() - startedAt}ms)`);
287
+ if (RETRYABLE_STATUSES.has(response.status) && attempt < maxAttempts) {
288
+ trace(`retrying after ${response.status} (attempt ${attempt} of ${maxAttempts})`);
289
+ await delay(attempt * 500);
290
+ continue;
291
+ }
292
+ return response;
293
+ } catch (err) {
294
+ lastError = err instanceof Error ? err : new Error(String(err));
295
+ trace(`${opts.method} ${url} -> ${lastError.name}: ${lastError.message}`);
296
+ if (attempt < maxAttempts && isTransient(lastError)) {
297
+ await delay(attempt * 500);
298
+ continue;
299
+ }
300
+ break;
301
+ }
302
+ }
303
+ if (lastError?.name === "TimeoutError") {
234
304
  throw new NetworkError(
235
- `Failed to connect to ${endpoint}. Check your network and endpoint configuration.`,
236
- err instanceof Error ? err : void 0
305
+ `No response from ${endpoint} within ${REQUEST_TIMEOUT_MS / 1e3}s.`,
306
+ lastError
237
307
  );
238
308
  }
309
+ throw new NetworkError(
310
+ `Failed to connect to ${endpoint}${lastError ? ` (${lastError.message})` : ""}. Check your network, or the endpoint set by 'diafunc config list'.`,
311
+ lastError
312
+ );
313
+ }
314
+ function delay(ms) {
315
+ return new Promise((resolve) => setTimeout(resolve, ms));
239
316
  }
240
317
  return {
241
318
  async request(opts) {
@@ -695,22 +772,90 @@ function createAdminService(client) {
695
772
  }
696
773
 
697
774
  // src/util/errors.ts
698
- import chalk from "chalk";
775
+ import chalk3 from "chalk";
776
+
777
+ // src/output/messages.ts
778
+ import chalk2 from "chalk";
779
+
780
+ // src/output/json.ts
781
+ function formatJson(data) {
782
+ console.log(JSON.stringify(data, null, 2));
783
+ }
784
+
785
+ // src/output/messages.ts
786
+ var MARK_OK = "\u2713";
787
+ var MARK_WARN = "!";
788
+ var MARK_FAIL = "\u2717";
789
+ function success(message, options) {
790
+ if (options?.format === "json") {
791
+ formatJson({ ok: true, message });
792
+ return;
793
+ }
794
+ console.log(`${chalk2.green(MARK_OK)} ${message}`);
795
+ }
796
+ function warn(message) {
797
+ console.error(`${chalk2.yellow(MARK_WARN)} ${message}`);
798
+ }
799
+ function failure(message) {
800
+ console.error(`${chalk2.red(MARK_FAIL)} ${message}`);
801
+ }
802
+ function detail(message) {
803
+ console.log(chalk2.dim(` ${message}`));
804
+ }
805
+ function hint(message) {
806
+ console.error(chalk2.dim(` ${message}`));
807
+ }
808
+ function empty(noun, options) {
809
+ if (options?.format === "json") {
810
+ formatJson([]);
811
+ return;
812
+ }
813
+ console.log(chalk2.dim(`No ${noun}.`));
814
+ }
815
+
816
+ // src/util/errors.ts
817
+ var EXIT_FAILURE = 1;
818
+ var EXIT_USAGE = 2;
819
+ var EXIT_AUTH = 3;
820
+ var CliError = class extends Error {
821
+ exitCode;
822
+ hint;
823
+ constructor(message, options = {}) {
824
+ super(message);
825
+ this.name = "CliError";
826
+ this.exitCode = options.exitCode ?? EXIT_FAILURE;
827
+ this.hint = options.hint;
828
+ }
829
+ };
830
+ function usageError(message, suggestion) {
831
+ failure(message);
832
+ if (suggestion) hint(suggestion);
833
+ process.exit(EXIT_USAGE);
834
+ }
699
835
  function handleError(error) {
836
+ if (error instanceof CliError) {
837
+ failure(error.message);
838
+ if (error.hint) hint(error.hint);
839
+ process.exit(error.exitCode);
840
+ }
700
841
  if (error instanceof ApiError) {
701
- console.error(chalk.red("Error:"), error.toUserMessage());
702
- process.exit(1);
842
+ failure(error.toUserMessage());
843
+ if (error.status === 401) hint(`Run 'diafunc auth login' to sign in.`);
844
+ if (error.status === 404) hint(`Check the id, or list what exists with the matching 'list' command.`);
845
+ process.exit(error.status === 401 || error.status === 403 ? EXIT_AUTH : EXIT_FAILURE);
703
846
  }
704
847
  if (error instanceof NetworkError) {
705
- console.error(chalk.red("Network error:"), error.message);
706
- process.exit(1);
848
+ failure(error.message);
849
+ hint(`Run 'diafunc status summary' to check the platform, or 'diafunc config list' for the endpoint in use.`);
850
+ process.exit(EXIT_FAILURE);
707
851
  }
708
852
  if (error instanceof Error) {
709
- console.error(chalk.red("Error:"), error.message);
710
- process.exit(1);
853
+ failure(error.message);
854
+ if (process.env.DIAFUNC_DEBUG && error.stack) console.error(chalk3.dim(error.stack));
855
+ process.exit(EXIT_FAILURE);
711
856
  }
712
- console.error(chalk.red("Error:"), String(error));
713
- process.exit(1);
857
+ failure(String(error));
858
+ process.exit(EXIT_FAILURE);
714
859
  }
715
860
 
716
861
  // src/commands/auth/login.ts
@@ -733,7 +878,7 @@ function registerLoginCommand(parent) {
733
878
  const config = loadConfig();
734
879
  const profile = config.profiles[config.currentProfile];
735
880
  if (!profile) {
736
- console.error(chalk2.red(`Profile "${config.currentProfile}" not found. Run 'diafunc config profile add' first.`));
881
+ failure(`Profile "${config.currentProfile}" not found. Run 'diafunc config profile add' first.`);
737
882
  process.exit(1);
738
883
  }
739
884
  if (options.endpoint) {
@@ -745,8 +890,8 @@ function registerLoginCommand(parent) {
745
890
  const client = createHttpClient();
746
891
  const admin = createAdminService(client);
747
892
  const user = await admin.getMyUser();
748
- console.log(chalk2.green("Authenticated successfully."));
749
- console.log(` User: ${chalk2.bold(user.name)}`);
893
+ success("Authenticated successfully.");
894
+ console.log(` User: ${chalk4.bold(user.name)}`);
750
895
  console.log(` Email: ${user.email}`);
751
896
  console.log(` Profile: ${config.currentProfile}`);
752
897
  console.log(` Endpoint: ${profile.endpoint}`);
@@ -767,18 +912,18 @@ async function deviceCodeLogin(config, profile) {
767
912
  });
768
913
  if (!deviceResponse.ok) {
769
914
  const text = await deviceResponse.text();
770
- console.error(chalk2.red("Failed to start device-code flow:"), text || deviceResponse.statusText);
915
+ failure(`Failed to start device-code flow: ${text || deviceResponse.statusText}`);
771
916
  process.exit(1);
772
917
  }
773
918
  const device = await deviceResponse.json();
774
919
  console.log("");
775
- console.log(`Open this URL in a browser: ${chalk2.cyan(device.verification_uri)}`);
776
- console.log(`Enter the code: ${chalk2.bold.yellow(device.user_code)}`);
920
+ console.log(`Open this URL in a browser: ${chalk4.cyan(device.verification_uri)}`);
921
+ console.log(`Enter the code: ${chalk4.bold.yellow(device.user_code)}`);
777
922
  console.log("");
778
- console.log(chalk2.dim("Or open the full URL to pre-fill:"));
779
- console.log(chalk2.dim(` ${device.verification_uri_complete}`));
923
+ console.log(chalk4.dim("Or open the full URL to pre-fill:"));
924
+ console.log(chalk4.dim(` ${device.verification_uri_complete}`));
780
925
  console.log("");
781
- console.log(chalk2.dim(`Waiting for approval (expires in ${Math.floor(device.expires_in / 60)} min)...`));
926
+ console.log(chalk4.dim(`Waiting for approval (expires in ${Math.floor(device.expires_in / 60)} min)...`));
782
927
  const deadline = Date.now() + device.expires_in * 1e3;
783
928
  let interval = Math.max(1, device.interval || 5);
784
929
  while (Date.now() < deadline) {
@@ -805,8 +950,8 @@ async function deviceCodeLogin(config, profile) {
805
950
  const client = createHttpClient();
806
951
  const admin = createAdminService(client);
807
952
  const user = await admin.getMyUser();
808
- console.log(chalk2.green("\nLogged in successfully."));
809
- console.log(` User: ${chalk2.bold(user.name)}`);
953
+ success("Logged in successfully.");
954
+ console.log(` User: ${chalk4.bold(user.name)}`);
810
955
  console.log(` Email: ${user.email}`);
811
956
  console.log(` Profile: ${config.currentProfile}`);
812
957
  console.log(` Endpoint: ${profile.endpoint}`);
@@ -821,14 +966,13 @@ async function deviceCodeLogin(config, profile) {
821
966
  continue;
822
967
  }
823
968
  if (errorBody.error === "expired_token") {
824
- console.error(chalk2.red("\nCode expired before approval. Run `diafunc auth login` again."));
969
+ failure("Code expired before approval. Run `diafunc auth login` again.");
825
970
  process.exit(1);
826
971
  }
827
- console.error(chalk2.red(`
828
- Device-code flow failed: ${errorBody.error}${errorBody.error_description ? " \u2014 " + errorBody.error_description : ""}`));
972
+ failure(`Device-code flow failed: ${errorBody.error}${errorBody.error_description ? " \u2014 " + errorBody.error_description : ""}`);
829
973
  process.exit(1);
830
974
  }
831
- console.error(chalk2.red("\nTimed out waiting for approval."));
975
+ failure("Timed out waiting for approval.");
832
976
  process.exit(1);
833
977
  }
834
978
  function sleep(ms) {
@@ -836,7 +980,6 @@ function sleep(ms) {
836
980
  }
837
981
 
838
982
  // src/commands/auth/logout.ts
839
- import chalk3 from "chalk";
840
983
  function deriveAuthUrl3(endpoint) {
841
984
  const trimmed = endpoint.replace(/\/+$/, "");
842
985
  if (trimmed.includes("://auth.")) {
@@ -852,11 +995,11 @@ function registerLogoutCommand(parent) {
852
995
  const config = loadConfig();
853
996
  const profile = config.profiles[config.currentProfile];
854
997
  if (!profile) {
855
- console.error(chalk3.red(`Profile "${config.currentProfile}" not found.`));
998
+ failure(`Profile "${config.currentProfile}" not found.`);
856
999
  process.exit(1);
857
1000
  }
858
1001
  if (!profile.auth) {
859
- console.log(chalk3.dim("No credentials stored for this profile."));
1002
+ empty("credentials stored for this profile");
860
1003
  return;
861
1004
  }
862
1005
  if (profile.auth.type === "device-code") {
@@ -876,94 +1019,371 @@ function registerLogoutCommand(parent) {
876
1019
  }
877
1020
  delete profile.auth;
878
1021
  saveConfig(config);
879
- console.log(chalk3.green(`Logged out from profile "${config.currentProfile}".`));
1022
+ success(`Logged out from profile "${config.currentProfile}".`);
880
1023
  });
881
1024
  }
882
1025
 
883
1026
  // src/commands/auth/status.ts
1027
+ import chalk7 from "chalk";
1028
+
1029
+ // src/output/human.ts
884
1030
  import chalk6 from "chalk";
885
1031
 
886
- // src/output/formatter.ts
887
- import chalk5 from "chalk";
1032
+ // src/output/columns.ts
1033
+ function normalizeColumns(columns) {
1034
+ return columns.map((c) => typeof c === "string" ? { key: c } : c);
1035
+ }
1036
+ function humanizeKey(key) {
1037
+ return key.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/[_-]+/g, " ").toLowerCase();
1038
+ }
1039
+ function headerOf(spec) {
1040
+ return spec.header ?? humanizeKey(spec.key);
1041
+ }
1042
+ function inferKind(key) {
1043
+ const k = key.toLowerCase();
1044
+ if (/[a-z](At|Date|Time|Timestamp)$/.test(key) || DATE_KEYS.has(k)) return "date";
1045
+ if (/[a-z](State|Status)$/.test(key) || k === "state" || k === "status") return "state";
1046
+ if (/[a-z]Ids?$/.test(key) || k === "id") return "id";
1047
+ return "text";
1048
+ }
1049
+ var DATE_KEYS = /* @__PURE__ */ new Set([
1050
+ "created",
1051
+ "modified",
1052
+ "started",
1053
+ "ended",
1054
+ "issued",
1055
+ "requested",
1056
+ "finished",
1057
+ "submitted",
1058
+ "renewal",
1059
+ "expires",
1060
+ "joined",
1061
+ "invited",
1062
+ "removed",
1063
+ "lastaccessed",
1064
+ "lastcheck"
1065
+ ]);
888
1066
 
889
- // src/output/human.ts
890
- import chalk4 from "chalk";
891
- import Table from "cli-table3";
892
- function formatHuman(data, columns, dateColumns) {
893
- const isDate = (key) => dateColumns?.includes(key) ?? false;
894
- if (Array.isArray(data)) {
895
- if (data.length === 0) {
896
- console.log(chalk4.dim("No results."));
897
- return;
898
- }
899
- const cols = columns ?? Object.keys(data[0]);
900
- const table = new Table({
901
- head: cols.map((c) => chalk4.bold(c)),
902
- style: { head: [], border: [] }
903
- });
904
- for (const row of data) {
905
- const r = row;
906
- table.push(cols.map((c) => formatValue(r[c], isDate(c))));
1067
+ // src/output/terminal.ts
1068
+ function isInteractive() {
1069
+ return Boolean(process.stdout.isTTY) && process.env.TERM !== "dumb";
1070
+ }
1071
+ function terminalWidth() {
1072
+ const columns = process.stdout.columns;
1073
+ if (!columns || !Number.isFinite(columns)) return 80;
1074
+ return Math.max(40, columns - 1);
1075
+ }
1076
+ function displayWidth(text) {
1077
+ return stripAnsi(text).length;
1078
+ }
1079
+ var ANSI_PATTERN = new RegExp("\\u001B\\[[0-9;]*m", "g");
1080
+ function stripAnsi(text) {
1081
+ return text.replace(ANSI_PATTERN, "");
1082
+ }
1083
+ function truncate(text, width) {
1084
+ const plain = stripAnsi(text);
1085
+ if (plain.length <= width) return text;
1086
+ if (width <= 1) return plain.slice(0, Math.max(0, width));
1087
+ return plain.slice(0, width - 1) + "\u2026";
1088
+ }
1089
+ function wrap(text, width) {
1090
+ const out = [];
1091
+ for (const paragraph of text.split("\n")) {
1092
+ if (paragraph.length <= width) {
1093
+ out.push(paragraph);
1094
+ continue;
907
1095
  }
908
- console.log(table.toString());
909
- } else if (data && typeof data === "object") {
910
- const obj = data;
911
- const table = new Table({
912
- style: { head: [], border: [] }
913
- });
914
- for (const [key, value] of Object.entries(obj)) {
915
- table.push({ [chalk4.bold(key)]: formatValue(value, isDate(key)) });
1096
+ let line = "";
1097
+ for (const word of paragraph.split(/(\s+)/)) {
1098
+ if (line.length + word.length <= width) {
1099
+ line += word;
1100
+ continue;
1101
+ }
1102
+ if (line.trim()) out.push(line.trimEnd());
1103
+ let rest = word.trimStart();
1104
+ while (rest.length > width) {
1105
+ out.push(rest.slice(0, width));
1106
+ rest = rest.slice(width);
1107
+ }
1108
+ line = rest;
916
1109
  }
917
- console.log(table.toString());
918
- } else {
919
- console.log(String(data));
1110
+ if (line.trim() || out.length === 0) out.push(line.trimEnd());
1111
+ }
1112
+ return out;
1113
+ }
1114
+
1115
+ // src/output/values.ts
1116
+ import chalk5 from "chalk";
1117
+ var ABSENT = "\u2014";
1118
+ function renderValue(value, kind = "text", plain = false) {
1119
+ const dim = (text) => plain ? text : chalk5.dim(text);
1120
+ if (value === null || value === void 0 || value === "") return dim(ABSENT);
1121
+ switch (kind) {
1122
+ case "id":
1123
+ return dim(String(value));
1124
+ case "date":
1125
+ return plain ? formatInstantAbsolute(value) : formatInstant(value);
1126
+ case "number":
1127
+ return renderNumber(value, plain);
1128
+ case "state":
1129
+ return plain ? String(value) : renderState(String(value));
1130
+ case "boolean":
1131
+ return renderBoolean(value, plain);
1132
+ case "text":
1133
+ default:
1134
+ if (typeof value === "boolean") return renderBoolean(value, plain);
1135
+ if (typeof value === "number") return renderNumber(value, plain);
1136
+ if (Array.isArray(value)) return renderArray(value, plain, dim);
1137
+ if (typeof value === "object") return JSON.stringify(value);
1138
+ return String(value);
920
1139
  }
921
1140
  }
922
- function formatValue(value, asDate = false) {
923
- if (value === null || value === void 0) return chalk4.dim("\u2014");
924
- if (asDate) return formatInstant(value);
925
- if (typeof value === "boolean") return value ? chalk4.green("true") : chalk4.red("false");
926
- if (typeof value === "number") return chalk4.cyan(String(value));
927
- if (typeof value === "object") return JSON.stringify(value);
928
- return String(value);
1141
+ function renderNumber(value, plain) {
1142
+ const text = typeof value === "number" && !plain ? formatNumber(value) : String(value);
1143
+ return plain ? text : chalk5.cyan(text);
1144
+ }
1145
+ function renderArray(value, plain, dim) {
1146
+ if (value.length === 0) return dim(ABSENT);
1147
+ const allScalar = value.every((v) => v === null || typeof v !== "object");
1148
+ return allScalar ? value.map(String).join(", ") : JSON.stringify(value);
1149
+ }
1150
+ function renderBoolean(value, plain) {
1151
+ const truthy = value === true || value === "true";
1152
+ if (plain) return truthy ? "yes" : "no";
1153
+ return truthy ? chalk5.green("yes") : chalk5.dim("no");
1154
+ }
1155
+ function formatNumber(value) {
1156
+ if (!Number.isFinite(value)) return String(value);
1157
+ if (!Number.isInteger(value)) return String(value);
1158
+ return value.toLocaleString("en-US");
929
1159
  }
930
1160
  function formatInstant(value) {
931
- if (value === null || value === void 0) return chalk4.dim("\u2014");
1161
+ const date = toDate(value);
1162
+ if (!date) return String(value);
1163
+ const absolute = formatLocal(date);
1164
+ const relative = formatRelative(date.getTime());
1165
+ return relative ? `${absolute} ${chalk5.dim(`(${relative})`)}` : absolute;
1166
+ }
1167
+ function formatInstantAbsolute(value) {
1168
+ const date = toDate(value);
1169
+ return date ? formatLocal(date) : String(value);
1170
+ }
1171
+ function toDate(value) {
1172
+ if (value === null || value === void 0 || value === "") return null;
1173
+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;
932
1174
  if (typeof value === "number") {
1175
+ const millis = value < 1e11 && value > 0 ? value * 1e3 : value;
1176
+ const d = new Date(millis);
1177
+ return Number.isNaN(d.getTime()) ? null : d;
1178
+ }
1179
+ if (typeof value === "string") {
1180
+ if (/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;
1181
+ if (/^\d+$/.test(value)) return toDate(Number(value));
933
1182
  const d = new Date(value);
934
- return Number.isNaN(d.getTime()) ? String(value) : d.toISOString().replace("T", " ").slice(0, 19);
1183
+ return Number.isNaN(d.getTime()) ? null : d;
935
1184
  }
936
- return String(value);
1185
+ return null;
1186
+ }
1187
+ function formatLocal(date) {
1188
+ const pad2 = (n) => String(n).padStart(2, "0");
1189
+ return `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}`;
1190
+ }
1191
+ function formatRelative(millis, now = Date.now()) {
1192
+ const delta = now - millis;
1193
+ const abs = Math.abs(delta);
1194
+ if (abs < 3e4) return "just now";
1195
+ if (abs > 180 * 24 * 60 * 60 * 1e3) return null;
1196
+ const span = formatDuration(abs);
1197
+ return delta >= 0 ? `${span} ago` : `in ${span}`;
1198
+ }
1199
+ function formatDuration(millis) {
1200
+ const seconds = Math.floor(millis / 1e3);
1201
+ if (seconds < 60) return `${seconds}s`;
1202
+ const minutes = Math.floor(seconds / 60);
1203
+ if (minutes < 60) return `${minutes}m ${String(seconds % 60).padStart(2, "0")}s`;
1204
+ const hours = Math.floor(minutes / 60);
1205
+ if (hours < 24) return `${hours}h ${String(minutes % 60).padStart(2, "0")}m`;
1206
+ const days = Math.floor(hours / 24);
1207
+ return `${days}d ${hours % 24}h`;
1208
+ }
1209
+ var GOOD_STATES = /* @__PURE__ */ new Set([
1210
+ "COMPLETED",
1211
+ "SUCCEEDED",
1212
+ "SUCCESS",
1213
+ "ACTIVE",
1214
+ "UP",
1215
+ "OPERATIONAL",
1216
+ "PAID",
1217
+ "RESOLVED",
1218
+ "OK"
1219
+ ]);
1220
+ var BAD_STATES = /* @__PURE__ */ new Set([
1221
+ "FAILED",
1222
+ "FAILURE",
1223
+ "ERROR",
1224
+ "DOWN",
1225
+ "CANCELLED",
1226
+ "CANCELED",
1227
+ "EXPIRED",
1228
+ "REVOKED",
1229
+ "UNPAID"
1230
+ ]);
1231
+ var BUSY_STATES = /* @__PURE__ */ new Set([
1232
+ "RUNNING",
1233
+ "QUEUED",
1234
+ "DISPATCHING",
1235
+ "PENDING",
1236
+ "IN_PROGRESS",
1237
+ "DEGRADED",
1238
+ "OPEN",
1239
+ "PROCESSING"
1240
+ ]);
1241
+ function renderState(state) {
1242
+ const key = state.toUpperCase();
1243
+ if (GOOD_STATES.has(key)) return chalk5.green(state);
1244
+ if (BAD_STATES.has(key)) return chalk5.red(state);
1245
+ if (BUSY_STATES.has(key)) return chalk5.yellow(state);
1246
+ return state;
937
1247
  }
938
1248
 
939
- // src/output/json.ts
940
- function formatJson(data) {
941
- console.log(JSON.stringify(data, null, 2));
1249
+ // src/output/human.ts
1250
+ var GAP = " ";
1251
+ var MIN_COLUMN_WIDTH = 6;
1252
+ function formatHuman(data, columns) {
1253
+ if (Array.isArray(data)) {
1254
+ renderRows(data, columns);
1255
+ } else if (data && typeof data === "object") {
1256
+ renderRecord(data);
1257
+ } else {
1258
+ console.log(String(data));
1259
+ }
1260
+ }
1261
+ function renderRows(rows, columns) {
1262
+ if (rows.length === 0) {
1263
+ console.log(chalk6.dim("No results."));
1264
+ return;
1265
+ }
1266
+ const specs = resolveSpecs(rows[0], columns);
1267
+ if (!isInteractive()) {
1268
+ console.log(specs.map((s) => headerOf(s)).join(" "));
1269
+ for (const row of rows) {
1270
+ console.log(specs.map((spec) => forPipe(row[spec.key], spec)).join(" "));
1271
+ }
1272
+ return;
1273
+ }
1274
+ let cells = rows.map((row) => specs.map((spec) => renderCell(row, spec)));
1275
+ if (naturalWidth(specs, cells) > terminalWidth()) {
1276
+ cells = rows.map((row) => specs.map((spec) => renderCell(row, spec, true)));
1277
+ }
1278
+ const widths = budgetWidths(specs, cells);
1279
+ console.log(
1280
+ specs.map((s, i) => chalk6.bold(pad(headerOf(s).toUpperCase(), widths[i]))).join(GAP).trimEnd()
1281
+ );
1282
+ for (const row of cells) {
1283
+ console.log(row.map((c, i) => pad(truncate(c, widths[i]), widths[i])).join(GAP).trimEnd());
1284
+ }
1285
+ }
1286
+ function renderRecord(obj) {
1287
+ const entries = Object.entries(obj);
1288
+ if (entries.length === 0) {
1289
+ console.log(chalk6.dim("No fields."));
1290
+ return;
1291
+ }
1292
+ if (!isInteractive()) {
1293
+ for (const [key, value] of entries) {
1294
+ console.log(`${key} ${forPipe(value, { key })}`);
1295
+ }
1296
+ return;
1297
+ }
1298
+ const labelWidth = Math.min(
1299
+ 24,
1300
+ entries.reduce((max, [key]) => Math.max(max, key.length), 0)
1301
+ );
1302
+ const valueWidth = Math.max(MIN_COLUMN_WIDTH, terminalWidth() - labelWidth - GAP.length);
1303
+ for (const [key, value] of entries) {
1304
+ const rendered = renderValue(value, inferKind(key));
1305
+ const label = chalk6.bold(pad(truncate(key, labelWidth), labelWidth));
1306
+ if (displayWidth(rendered) <= valueWidth) {
1307
+ console.log(label + GAP + rendered);
1308
+ continue;
1309
+ }
1310
+ const lines = wrap(stripAnsi(rendered), valueWidth);
1311
+ console.log(label + GAP + (lines[0] ?? ""));
1312
+ for (const line of lines.slice(1)) {
1313
+ console.log(" ".repeat(labelWidth + GAP.length) + line);
1314
+ }
1315
+ }
1316
+ }
1317
+ function resolveSpecs(sample, columns) {
1318
+ const specs = columns ? normalizeColumns(columns) : Object.keys(sample).map((key) => ({ key }));
1319
+ return specs.map((spec) => ({ ...spec, kind: spec.kind ?? inferKind(spec.key) }));
1320
+ }
1321
+ function renderCell(row, spec, compactDates = false) {
1322
+ const value = row[spec.key];
1323
+ const rendered = compactDates && spec.kind === "date" ? renderCompactDate(value) : renderValue(value, spec.kind);
1324
+ return spec.maxWidth ? truncate(rendered, spec.maxWidth) : rendered;
1325
+ }
1326
+ function renderCompactDate(value) {
1327
+ if (value === null || value === void 0 || value === "") return chalk6.dim(ABSENT);
1328
+ return formatInstantAbsolute(value);
1329
+ }
1330
+ function naturalWidth(specs, cells) {
1331
+ const widths = specs.map(
1332
+ (spec, i) => Math.max(displayWidth(headerOf(spec)), ...cells.map((row) => displayWidth(row[i])))
1333
+ );
1334
+ return widths.reduce((a, b) => a + b, 0) + GAP.length * (specs.length - 1);
1335
+ }
1336
+ var SHRINK_ORDER = ["text", "date", "state", "number", "boolean", "id"];
1337
+ function budgetWidths(specs, cells) {
1338
+ const widths = specs.map(
1339
+ (spec, i) => Math.max(displayWidth(headerOf(spec)), ...cells.map((row) => displayWidth(row[i])))
1340
+ );
1341
+ const budget = terminalWidth() - GAP.length * (specs.length - 1);
1342
+ let total = widths.reduce((a, b) => a + b, 0);
1343
+ if (total <= budget) return widths;
1344
+ for (const kind of SHRINK_ORDER) {
1345
+ const candidates = specs.map((spec, i) => ({ i, kind: spec.kind ?? "text" })).filter((c) => c.kind === kind).map((c) => c.i);
1346
+ while (total > budget) {
1347
+ let widest = -1;
1348
+ for (const i of candidates) {
1349
+ if (widths[i] > MIN_COLUMN_WIDTH && (widest < 0 || widths[i] > widths[widest])) widest = i;
1350
+ }
1351
+ if (widest < 0) break;
1352
+ widths[widest] -= 1;
1353
+ total -= 1;
1354
+ }
1355
+ if (total <= budget) break;
1356
+ }
1357
+ return widths;
1358
+ }
1359
+ function pad(text, width) {
1360
+ const deficit = width - displayWidth(text);
1361
+ return deficit > 0 ? text + " ".repeat(deficit) : text;
1362
+ }
1363
+ function forPipe(value, spec) {
1364
+ const rendered = stripAnsi(renderValue(value, spec.kind ?? inferKind(spec.key), true));
1365
+ return rendered === ABSENT ? "" : rendered;
942
1366
  }
943
1367
 
944
1368
  // src/output/table.ts
945
1369
  function formatTable(data, columns) {
946
1370
  if (Array.isArray(data)) {
947
- if (data.length === 0) return;
948
- const cols = columns ?? Object.keys(data[0]);
949
- console.log(cols.join(" "));
1371
+ const specs = columns ? normalizeColumns(columns) : Object.keys(data[0] ?? {}).map((key) => ({ key }));
1372
+ if (specs.length > 0) console.log(specs.map((s) => headerOf(s)).join(" "));
950
1373
  for (const row of data) {
951
- const r = row;
952
- console.log(cols.map((c) => cell(r[c])).join(" "));
1374
+ console.log(specs.map((s) => cell(row[s.key], s.kind ?? inferKind(s.key))).join(" "));
953
1375
  }
954
1376
  } else if (data && typeof data === "object") {
955
- const obj = data;
956
- for (const [key, value] of Object.entries(obj)) {
957
- console.log(`${key} ${cell(value)}`);
1377
+ for (const [key, value] of Object.entries(data)) {
1378
+ console.log(`${key} ${cell(value, inferKind(key))}`);
958
1379
  }
959
1380
  } else {
960
1381
  console.log(String(data));
961
1382
  }
962
1383
  }
963
- function cell(value) {
1384
+ function cell(value, kind) {
964
1385
  if (value === null || value === void 0) return "";
965
- if (typeof value === "object") return JSON.stringify(value);
966
- return String(value);
1386
+ return renderValue(value, kind, true);
967
1387
  }
968
1388
 
969
1389
  // src/output/formatter.ts
@@ -977,17 +1397,10 @@ function format(data, options) {
977
1397
  break;
978
1398
  case "human":
979
1399
  default:
980
- formatHuman(data, options.columns, options.dateColumns);
1400
+ formatHuman(data, options.columns);
981
1401
  break;
982
1402
  }
983
1403
  }
984
- function formatMessage(message, options) {
985
- if (options.format === "json") {
986
- formatJson({ message });
987
- } else {
988
- console.log(chalk5.green(message));
989
- }
990
- }
991
1404
 
992
1405
  // src/commands/auth/status.ts
993
1406
  function registerStatusCommand(parent) {
@@ -1001,7 +1414,7 @@ function registerStatusCommand(parent) {
1001
1414
  if (outputFormat === "json") {
1002
1415
  console.log(JSON.stringify({ authenticated: false, profile: config.currentProfile }));
1003
1416
  } else {
1004
- console.log(chalk6.yellow("Not authenticated."), `Run 'diafunc auth login' to configure credentials.`);
1417
+ console.log(chalk7.yellow("Not authenticated."), `Run 'diafunc auth login' to configure credentials.`);
1005
1418
  console.log(` Profile: ${config.currentProfile}`);
1006
1419
  console.log(` Endpoint: ${profile?.endpoint ?? "not configured"}`);
1007
1420
  }
@@ -1029,7 +1442,7 @@ function registerStatusCommand(parent) {
1029
1442
  }
1030
1443
 
1031
1444
  // src/commands/auth/token.ts
1032
- import chalk7 from "chalk";
1445
+ import chalk8 from "chalk";
1033
1446
 
1034
1447
  // src/client/services/analysis.ts
1035
1448
  var SERVICE2 = "analyses";
@@ -2125,14 +2538,6 @@ function createEvaluationService(client) {
2125
2538
  service: SERVICE4,
2126
2539
  path: `/triggers/${enc2(projectId)}/${enc2(projectBranch)}/${enc2(functionId)}/${enc2(functionBranch)}/${enc2(triggerId)}`
2127
2540
  });
2128
- },
2129
- // Engines
2130
- async getEngines() {
2131
- return client.request({
2132
- method: "GET",
2133
- service: SERVICE4,
2134
- path: "/engines/"
2135
- });
2136
2541
  }
2137
2542
  };
2138
2543
  }
@@ -2252,6 +2657,25 @@ function enc5(s) {
2252
2657
  }
2253
2658
  function createIndexService(client) {
2254
2659
  return {
2660
+ /**
2661
+ * Cross-project search. Scoped to one project by passing `projectId`; unscoped it searches
2662
+ * everything the caller can see, which is what the command's description has always promised.
2663
+ */
2664
+ async searchPage(query) {
2665
+ return client.request({
2666
+ method: "GET",
2667
+ service: SERVICE7,
2668
+ path: "/search/page",
2669
+ query: {
2670
+ query: query.query,
2671
+ limit: query.limit ?? 20,
2672
+ cursor: query.cursor ?? void 0,
2673
+ contentType: query.contentType ?? void 0,
2674
+ projectId: query.projectId ?? void 0,
2675
+ projectBranch: query.projectBranch ?? void 0
2676
+ }
2677
+ });
2678
+ },
2255
2679
  async rebuildAll() {
2256
2680
  return client.request({
2257
2681
  method: "POST",
@@ -2304,7 +2728,7 @@ function registerTokenCommands(parent) {
2304
2728
  const resourceType = options.resourceType.trim().toLowerCase();
2305
2729
  if (!VALID_RESOURCE_TYPES.includes(resourceType)) {
2306
2730
  console.error(
2307
- chalk7.red(`Invalid resource type: "${options.resourceType}".`),
2731
+ chalk8.red(`Invalid resource type: "${options.resourceType}".`),
2308
2732
  `Valid resource types: ${VALID_RESOURCE_TYPES.join(", ")}`
2309
2733
  );
2310
2734
  process.exit(1);
@@ -2312,7 +2736,7 @@ function registerTokenCommands(parent) {
2312
2736
  const scopes = options.scopes.split(",").map((s) => s.trim());
2313
2737
  for (const scope of scopes) {
2314
2738
  if (!VALID_SCOPES.includes(scope)) {
2315
- console.error(chalk7.red(`Invalid scope: "${scope}".`), `Valid scopes: ${VALID_SCOPES.join(", ")}`);
2739
+ console.error(chalk8.red(`Invalid scope: "${scope}".`), `Valid scopes: ${VALID_SCOPES.join(", ")}`);
2316
2740
  process.exit(1);
2317
2741
  }
2318
2742
  }
@@ -2325,14 +2749,14 @@ function registerTokenCommands(parent) {
2325
2749
  validityDays: parseInt(options.days, 10)
2326
2750
  });
2327
2751
  if (outputFormat === "human") {
2328
- console.log(chalk7.green("API token created successfully."));
2752
+ success("API token created successfully.");
2329
2753
  console.log();
2330
- console.log(` Token: ${chalk7.bold(result.token)}`);
2754
+ console.log(` Token: ${chalk8.bold(result.token)}`);
2331
2755
  console.log(` Token ID: ${result.tokenId}`);
2332
2756
  console.log(` Name: ${result.name}`);
2333
2757
  console.log(` Expires: ${result.expiresAt}`);
2334
2758
  console.log();
2335
- console.log(chalk7.yellow("Save this token \u2014 it will not be shown again."));
2759
+ console.log(chalk8.yellow("Save this token \u2014 it will not be shown again."));
2336
2760
  } else {
2337
2761
  format(result, { format: outputFormat });
2338
2762
  }
@@ -2359,7 +2783,7 @@ function registerTokenCommands(parent) {
2359
2783
  try {
2360
2784
  const api = createApiClient();
2361
2785
  await api.admin.revokeApiToken(tokenId);
2362
- console.log(chalk7.green(`Token ${tokenId} revoked.`));
2786
+ success(`Token ${tokenId} revoked.`);
2363
2787
  } catch (error) {
2364
2788
  handleError(error);
2365
2789
  }
@@ -2368,7 +2792,14 @@ function registerTokenCommands(parent) {
2368
2792
 
2369
2793
  // src/commands/auth/index.ts
2370
2794
  function registerAuthCommands(program) {
2371
- const auth = program.command("auth").description("Authentication and credential management");
2795
+ const auth = program.command("auth").description("Authentication and credential management").addHelpText("after", `
2796
+ Examples:
2797
+ $ diafunc auth login sign in with a browser
2798
+ $ diafunc auth status who you are signed in as
2799
+ $ diafunc auth token create a token for scripts and CI
2800
+ $ diafunc auth logout
2801
+ `);
2802
+ ;
2372
2803
  registerLoginCommand(auth);
2373
2804
  registerLogoutCommand(auth);
2374
2805
  registerStatusCommand(auth);
@@ -2376,20 +2807,29 @@ function registerAuthCommands(program) {
2376
2807
  }
2377
2808
 
2378
2809
  // src/commands/config/index.ts
2379
- import chalk8 from "chalk";
2810
+ import chalk9 from "chalk";
2380
2811
  function registerConfigCommands(program) {
2381
- const config = program.command("config").description("Manage CLI configuration");
2812
+ const config = program.command("config").description("Manage CLI configuration").addHelpText("after", `
2813
+ Setting a default project lets every command that takes one omit it.
2814
+
2815
+ Examples:
2816
+ $ diafunc config list
2817
+ $ diafunc config set defaults.project <id>
2818
+ $ diafunc config set defaults.output json
2819
+ $ diafunc config profile add staging --endpoint https://staging.diafunc.com
2820
+ `);
2821
+ ;
2382
2822
  config.command("set").description("Set a configuration value").argument("<key>", "Config key (e.g., defaults.project, defaults.branch, defaults.output)").argument("<value>", "Config value").action((key, value) => {
2383
2823
  const cfg = loadConfig();
2384
2824
  setNestedValue(cfg, key, value);
2385
2825
  saveConfig(cfg);
2386
- console.log(chalk8.green(`Set ${key} = ${value}`));
2826
+ success(`Set ${key} = ${value}`);
2387
2827
  });
2388
2828
  config.command("get").description("Get a configuration value").argument("<key>", "Config key").action((key) => {
2389
2829
  const cfg = loadConfig();
2390
2830
  const value = getNestedValue(cfg, key);
2391
2831
  if (value === void 0) {
2392
- console.log(chalk8.dim("(not set)"));
2832
+ console.log(chalk9.dim("(not set)"));
2393
2833
  } else {
2394
2834
  console.log(String(value));
2395
2835
  }
@@ -2399,20 +2839,20 @@ function registerConfigCommands(program) {
2399
2839
  const globalOpts = cmd.optsWithGlobals();
2400
2840
  const outputFormat = globalOpts.output ?? "human";
2401
2841
  if (outputFormat === "human") {
2402
- console.log(chalk8.bold("Config file:"), CONFIG_FILE);
2403
- console.log(chalk8.bold("Active profile:"), cfg.currentProfile);
2842
+ console.log(chalk9.bold("Config file:"), CONFIG_FILE);
2843
+ console.log(chalk9.bold("Active profile:"), cfg.currentProfile);
2404
2844
  console.log();
2405
- console.log(chalk8.bold("Profiles:"));
2845
+ console.log(chalk9.bold("Profiles:"));
2406
2846
  for (const [name, profile2] of Object.entries(cfg.profiles)) {
2407
- const active = name === cfg.currentProfile ? chalk8.green(" (active)") : "";
2847
+ const active = name === cfg.currentProfile ? chalk9.green(" (active)") : "";
2408
2848
  const authType = profile2.auth?.type ?? "none";
2409
- console.log(` ${chalk8.bold(name)}${active}`);
2849
+ console.log(` ${chalk9.bold(name)}${active}`);
2410
2850
  console.log(` Endpoint: ${profile2.endpoint}`);
2411
2851
  console.log(` Auth: ${authType}`);
2412
2852
  }
2413
2853
  if (Object.keys(cfg.defaults).length > 0) {
2414
2854
  console.log();
2415
- console.log(chalk8.bold("Defaults:"));
2855
+ console.log(chalk9.bold("Defaults:"));
2416
2856
  for (const [key, value] of Object.entries(cfg.defaults)) {
2417
2857
  console.log(` ${key}: ${value}`);
2418
2858
  }
@@ -2425,7 +2865,7 @@ function registerConfigCommands(program) {
2425
2865
  profile.command("add").description("Add a new profile").argument("<name>", "Profile name").option("--endpoint <url>", "API endpoint URL", "https://diafunc.com").option("--token <token>", "API token to store").action((name, options) => {
2426
2866
  const cfg = loadConfig();
2427
2867
  if (cfg.profiles[name]) {
2428
- console.error(chalk8.red(`Profile "${name}" already exists. Use 'diafunc config profile use' to switch to it.`));
2868
+ failure(`Profile "${name}" already exists. Use 'diafunc config profile use' to switch to it.`);
2429
2869
  process.exit(1);
2430
2870
  }
2431
2871
  cfg.profiles[name] = {
@@ -2433,18 +2873,18 @@ function registerConfigCommands(program) {
2433
2873
  ...options.token ? { auth: { type: "api-token", token: options.token } } : {}
2434
2874
  };
2435
2875
  saveConfig(cfg);
2436
- console.log(chalk8.green(`Profile "${name}" added.`));
2876
+ success(`Profile "${name}" added.`);
2437
2877
  });
2438
2878
  profile.command("use").description("Switch to a profile").argument("<name>", "Profile name").action((name) => {
2439
2879
  const cfg = loadConfig();
2440
2880
  if (!cfg.profiles[name]) {
2441
- console.error(chalk8.red(`Profile "${name}" not found.`));
2881
+ failure(`Profile "${name}" not found.`);
2442
2882
  console.log(`Available profiles: ${Object.keys(cfg.profiles).join(", ")}`);
2443
2883
  process.exit(1);
2444
2884
  }
2445
2885
  cfg.currentProfile = name;
2446
2886
  saveConfig(cfg);
2447
- console.log(chalk8.green(`Switched to profile "${name}".`));
2887
+ success(`Switched to profile "${name}".`);
2448
2888
  });
2449
2889
  profile.command("list").description("List all profiles").action((_options, cmd) => {
2450
2890
  const cfg = loadConfig();
@@ -2464,16 +2904,16 @@ function registerConfigCommands(program) {
2464
2904
  profile.command("remove").description("Remove a profile").argument("<name>", "Profile name").action((name) => {
2465
2905
  const cfg = loadConfig();
2466
2906
  if (!cfg.profiles[name]) {
2467
- console.error(chalk8.red(`Profile "${name}" not found.`));
2907
+ failure(`Profile "${name}" not found.`);
2468
2908
  process.exit(1);
2469
2909
  }
2470
2910
  if (name === cfg.currentProfile) {
2471
- console.error(chalk8.red(`Cannot remove the active profile. Switch to another profile first.`));
2911
+ failure(`Cannot remove the active profile. Switch to another profile first.`);
2472
2912
  process.exit(1);
2473
2913
  }
2474
2914
  delete cfg.profiles[name];
2475
2915
  saveConfig(cfg);
2476
- console.log(chalk8.green(`Profile "${name}" removed.`));
2916
+ success(`Profile "${name}" removed.`);
2477
2917
  });
2478
2918
  }
2479
2919
  function setNestedValue(obj, path11, value) {
@@ -2501,7 +2941,7 @@ function getNestedValue(obj, path11) {
2501
2941
  }
2502
2942
 
2503
2943
  // src/commands/project/index.ts
2504
- import chalk10 from "chalk";
2944
+ import chalk12 from "chalk";
2505
2945
 
2506
2946
  // src/util/references.ts
2507
2947
  function parseEntityReference(ref, overrides) {
@@ -2586,29 +3026,134 @@ function parseProjectReference(ref, overrides) {
2586
3026
  }
2587
3027
 
2588
3028
  // src/commands/bundle-helpers.ts
2589
- import chalk9 from "chalk";
3029
+ import chalk11 from "chalk";
2590
3030
  import * as fs2 from "fs";
2591
3031
  import * as path2 from "path";
3032
+
3033
+ // src/output/progress.ts
3034
+ import chalk10 from "chalk";
3035
+ var ESC = "\x1B[";
3036
+ var CURSOR_UP = (n) => `${ESC}${n}A`;
3037
+ var CLEAR_BELOW = `${ESC}0J`;
3038
+ var SPINNER = "\0spinner\0";
3039
+ var Status = class _Status {
3040
+ lines = [];
3041
+ painted = 0;
3042
+ lastLogged = "";
3043
+ spinnerIndex = 0;
3044
+ timer = null;
3045
+ static FRAMES = ["\u280B", "\u2819", "\u2839", "\u2838", "\u283C", "\u2834", "\u2826", "\u2827", "\u2807", "\u280F"];
3046
+ /** Replaces the transient block. Repaints only when the content actually changed. */
3047
+ set(lines) {
3048
+ const next = lines.filter((l) => l !== void 0);
3049
+ if (!isInteractive()) {
3050
+ const joined = next.map((l) => l.split(SPINNER).join("").trim()).filter(Boolean).join(" \xB7 ");
3051
+ if (joined && joined !== this.lastLogged) {
3052
+ this.lastLogged = joined;
3053
+ console.log(joined);
3054
+ }
3055
+ this.lines = next;
3056
+ return;
3057
+ }
3058
+ this.lines = next;
3059
+ this.repaint();
3060
+ }
3061
+ /** Prints a durable line above the transient block. */
3062
+ log(line) {
3063
+ if (!isInteractive()) {
3064
+ console.log(line);
3065
+ return;
3066
+ }
3067
+ this.erase();
3068
+ console.log(line);
3069
+ this.repaint();
3070
+ }
3071
+ /**
3072
+ * Starts the spinner animation. The caller still drives content through {@link set}; this only
3073
+ * advances the frame so a long wait does not look like a hung process.
3074
+ */
3075
+ start() {
3076
+ if (this.timer || !isInteractive()) return;
3077
+ this.timer = setInterval(() => {
3078
+ this.spinnerIndex = (this.spinnerIndex + 1) % _Status.FRAMES.length;
3079
+ this.repaint();
3080
+ }, 80);
3081
+ this.timer.unref?.();
3082
+ }
3083
+ /** Stops the animation and clears the transient block for good. */
3084
+ stop() {
3085
+ if (this.timer) {
3086
+ clearInterval(this.timer);
3087
+ this.timer = null;
3088
+ }
3089
+ this.erase();
3090
+ this.lines = [];
3091
+ }
3092
+ /** The current spinner glyph, for a caller that wants one frame rather than an animation. */
3093
+ spinner() {
3094
+ return isInteractive() ? _Status.FRAMES[this.spinnerIndex] : "\xB7";
3095
+ }
3096
+ frame(line) {
3097
+ return line.includes(SPINNER) ? line.split(SPINNER).join(this.spinner()) : line;
3098
+ }
3099
+ repaint() {
3100
+ this.erase();
3101
+ const width = terminalWidth();
3102
+ for (const line of this.lines) {
3103
+ process.stdout.write(truncate(this.frame(line), width) + "\n");
3104
+ }
3105
+ this.painted = this.lines.length;
3106
+ }
3107
+ erase() {
3108
+ if (this.painted === 0) return;
3109
+ process.stdout.write(CURSOR_UP(this.painted) + CLEAR_BELOW);
3110
+ this.painted = 0;
3111
+ }
3112
+ };
3113
+ async function withStatus(label, work) {
3114
+ const status = new Status();
3115
+ status.set([`${chalk10.cyan(SPINNER)} ${label}`]);
3116
+ status.start();
3117
+ const startedAt = Date.now();
3118
+ try {
3119
+ const result = await work();
3120
+ status.stop();
3121
+ console.log(`${chalk10.green("\u2713")} ${label} ${chalk10.dim(`(${Date.now() - startedAt}ms)`)}`);
3122
+ return result;
3123
+ } catch (error) {
3124
+ status.stop();
3125
+ console.error(`${chalk10.red("\u2717")} ${label}`);
3126
+ throw error;
3127
+ }
3128
+ }
3129
+ function bar(fraction, width = 28) {
3130
+ const clamped = Math.max(0, Math.min(1, Number.isFinite(fraction) ? fraction : 0));
3131
+ const filled = Math.round(clamped * width);
3132
+ return chalk10.cyan("\u2588".repeat(filled)) + chalk10.dim("\u2591".repeat(width - filled));
3133
+ }
3134
+ function percent(fraction) {
3135
+ const clamped = Math.max(0, Math.min(1, Number.isFinite(fraction) ? fraction : 0));
3136
+ return `${Math.round(clamped * 100)}%`.padStart(4);
3137
+ }
3138
+
3139
+ // src/commands/bundle-helpers.ts
2592
3140
  async function streamResponseToFile(response, outFile) {
2593
3141
  const buffer = Buffer.from(await response.arrayBuffer());
2594
3142
  fs2.writeFileSync(outFile, buffer);
2595
3143
  return buffer.length;
2596
3144
  }
2597
3145
  function printLossiness(notes) {
2598
- if (notes && notes.length > 0) {
2599
- console.log(chalk9.yellow("Lossiness:"));
2600
- for (const note of notes) {
2601
- console.log(chalk9.yellow(` - ${note}`));
2602
- }
2603
- }
3146
+ if (!notes || notes.length === 0) return;
3147
+ warn(notes.length === 1 ? "One detail could not be carried in the bundle:" : "Some details could not be carried in the bundle:");
3148
+ for (const note of notes) hint(`- ${note}`);
2604
3149
  }
2605
3150
  function printImportPreview(preview) {
2606
- console.log(chalk9.bold(`${preview.kind} bundle \xB7 ${preview.entityCount} entities`));
3151
+ console.log(chalk11.bold(`${preview.kind} bundle \xB7 ${preview.entityCount} entities`));
2607
3152
  if (preview.projectName) {
2608
- console.log(chalk9.dim(preview.projectName));
3153
+ console.log(chalk11.dim(preview.projectName));
2609
3154
  }
2610
3155
  if (preview.sourceProjectId) {
2611
- console.log(chalk9.dim(`from ${preview.sourceProjectId}/${preview.sourceProjectBranch}` + (preview.createdBy ? ` \xB7 by ${preview.createdBy}` : "")));
3156
+ console.log(chalk11.dim(`from ${preview.sourceProjectId}/${preview.sourceProjectBranch}` + (preview.createdBy ? ` \xB7 by ${preview.createdBy}` : "")));
2612
3157
  }
2613
3158
  const counts = /* @__PURE__ */ new Map();
2614
3159
  for (const e of preview.entities ?? []) {
@@ -2629,7 +3174,7 @@ function printImportPreview(preview) {
2629
3174
  printLossiness(preview.lossinessNotes);
2630
3175
  }
2631
3176
  function printImportResult(result) {
2632
- console.log(chalk9.green(`Imported ${result.entityCount} entities, ${result.linkCount} links.`));
3177
+ success(`Imported ${result.entityCount} entities, ${result.linkCount} links.`);
2633
3178
  if (result.skeletonCount) {
2634
3179
  console.log(`Skeletons: ${result.skeletonCount}`);
2635
3180
  }
@@ -2667,18 +3212,53 @@ async function runBundleImport(storage, projectId, projectBranch, file, options,
2667
3212
  }
2668
3213
  var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2669
3214
  async function pollUntilFinished(storage, projectId, projectBranch, bundleId, intervalMs = 2e3, maxAttempts = 150) {
2670
- for (let attempt = 0; attempt < maxAttempts; attempt++) {
2671
- const bundles = await storage.getBundles(projectId, projectBranch);
2672
- const job = bundles.find((b) => b.bundleId === bundleId);
2673
- if (job && job.finished) {
2674
- if (job.succeeded === false) {
2675
- throw new Error(`Export failed: ${job.error || "unknown error"}`);
3215
+ const status = new Status();
3216
+ status.start();
3217
+ const startedAt = Date.now();
3218
+ try {
3219
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
3220
+ const bundles = await storage.getBundles(projectId, projectBranch);
3221
+ const job = bundles.find((b) => b.bundleId === bundleId);
3222
+ if (job && job.finished) {
3223
+ if (job.succeeded === false) {
3224
+ throw new Error(`Export failed: ${job.error || "unknown error"}`);
3225
+ }
3226
+ return job;
2676
3227
  }
2677
- return job;
3228
+ status.set([progressLine("Exporting", job?.progress, Date.now() - startedAt)]);
3229
+ await sleep2(intervalMs);
3230
+ }
3231
+ } finally {
3232
+ status.stop();
3233
+ }
3234
+ throw new Error(
3235
+ `Export ${bundleId} is still running after ${formatDuration(intervalMs * maxAttempts)} \u2014 check it with 'diafunc notebook bundles ${projectId}'`
3236
+ );
3237
+ }
3238
+ function progressLine(label, progress, elapsedMs) {
3239
+ const elapsed = chalk11.dim(formatDuration(elapsedMs));
3240
+ if (progress === null || progress === void 0) {
3241
+ return ` ${chalk11.cyan(SPINNER)} ${label} ${elapsed}`;
3242
+ }
3243
+ const fraction = progress > 1 ? progress / 100 : progress;
3244
+ return ` ${chalk11.cyan(SPINNER)} ${label} ${bar(fraction, 20)} ${percent(fraction)} ${elapsed}`;
3245
+ }
3246
+
3247
+ // src/util/function-language.ts
3248
+ var FUNCTION_LANGUAGES = ["Java", "Kotlin", "Python", "JavaScript", "Scala"];
3249
+ var DEFAULT_FUNCTION_LANGUAGE = "Java";
3250
+ async function resolveLanguage(api, projectId, explicit) {
3251
+ if (explicit) {
3252
+ return explicit;
3253
+ }
3254
+ try {
3255
+ const project = await api.admin.getProject(projectId);
3256
+ if (project?.language) {
3257
+ return project.language;
2678
3258
  }
2679
- await sleep2(intervalMs);
3259
+ } catch {
2680
3260
  }
2681
- throw new Error(`Export ${bundleId} did not finish within the timeout \u2014 poll it with 'diafunc notebook bundles'`);
3261
+ return DEFAULT_FUNCTION_LANGUAGE;
2682
3262
  }
2683
3263
 
2684
3264
  // src/commands/project/index.ts
@@ -2693,15 +3273,39 @@ function getOverrides(cmd) {
2693
3273
  }
2694
3274
  function registerProjectCommands(program) {
2695
3275
  const project = program.command("project").description("Manage projects");
2696
- project.command("list").description("List projects").option("--all", "List all projects (admin)").action(async (options, cmd) => {
3276
+ project.command("list").description("List projects").option("--all", "List every project on the platform (admin)").option("--limit <n>", "Maximum projects to show; 0 for all", "20").addHelpText("after", `
3277
+ Examples:
3278
+ $ diafunc project list the twenty most recent
3279
+ $ diafunc project list --limit 0 every one of them
3280
+ $ diafunc search "housing" --type project find a project by name
3281
+
3282
+ A project's name lives on its main entity rather than on the project row, so this listing shows
3283
+ ids. Use 'diafunc search --type project' when you know the name but not the id.
3284
+ `).action(async (options, cmd) => {
2697
3285
  try {
2698
3286
  const outputFormat = getOutputFormat(cmd);
2699
3287
  const api = createApiClient();
2700
3288
  const projects = options.all ? await api.admin.getAllProjects() : await api.admin.getProjects();
2701
- format(projects, {
3289
+ const limit = Number.parseInt(options.limit, 10);
3290
+ const capped = Number.isFinite(limit) && limit > 0 ? projects.slice(0, limit) : projects;
3291
+ format(capped, {
2702
3292
  format: outputFormat,
2703
- columns: ["projectId", "teamName", "visibility", "language", "active", "locked"]
2704
- });
3293
+ columns: [
3294
+ { key: "projectId", kind: "id" },
3295
+ { key: "teamName", header: "team" },
3296
+ { key: "visibility" },
3297
+ { key: "language" },
3298
+ { key: "active", kind: "boolean" },
3299
+ { key: "locked", kind: "boolean" },
3300
+ { key: "created", kind: "date" }
3301
+ ]
3302
+ });
3303
+ if (capped.length < projects.length) {
3304
+ console.log(chalk12.dim(
3305
+ `
3306
+ Showing ${capped.length} of ${projects.length}. Pass --limit 0 to see them all.`
3307
+ ));
3308
+ }
2705
3309
  } catch (error) {
2706
3310
  handleError(error);
2707
3311
  }
@@ -2716,7 +3320,7 @@ function registerProjectCommands(program) {
2716
3320
  handleError(error);
2717
3321
  }
2718
3322
  });
2719
- project.command("create").description("Create a new project").option("--visibility <visibility>", "Project visibility (PRIVATE or PUBLIC)", "PRIVATE").option("--language <language>", "Project language", "Java").action(async (options, cmd) => {
3323
+ project.command("create").description("Create a new project").option("--visibility <visibility>", "Project visibility (PRIVATE or PUBLIC)", "PRIVATE").option("--language <language>", "The project's default language for functions (Java, Kotlin, Python, JavaScript, Scala)", DEFAULT_FUNCTION_LANGUAGE).action(async (options, cmd) => {
2720
3324
  try {
2721
3325
  const outputFormat = getOutputFormat(cmd);
2722
3326
  const api = createApiClient();
@@ -2726,8 +3330,8 @@ function registerProjectCommands(program) {
2726
3330
  active: true
2727
3331
  });
2728
3332
  if (outputFormat === "human") {
2729
- console.log(chalk10.green("Project created."));
2730
- console.log(` Project ID: ${chalk10.bold(p.projectId)}`);
3333
+ success("Project created.");
3334
+ console.log(` Project ID: ${chalk12.bold(p.projectId)}`);
2731
3335
  console.log(` Visibility: ${p.visibility}`);
2732
3336
  console.log(` Language: ${p.language}`);
2733
3337
  } else {
@@ -2748,7 +3352,7 @@ function registerProjectCommands(program) {
2748
3352
  ...options.active !== void 0 ? { active: options.active === "true" } : {}
2749
3353
  };
2750
3354
  await api.admin.updateProject(updated);
2751
- console.log(chalk10.green(`Project "${projectId}" updated.`));
3355
+ success(`Project "${projectId}" updated.`);
2752
3356
  } catch (error) {
2753
3357
  handleError(error);
2754
3358
  }
@@ -2760,7 +3364,11 @@ function registerProjectCommands(program) {
2760
3364
  const recent = await api.admin.getRecentProjects();
2761
3365
  format(recent, {
2762
3366
  format: outputFormat,
2763
- columns: ["projectId", "projectBranch", "lastAccessed"]
3367
+ columns: [
3368
+ { key: "projectId", kind: "id" },
3369
+ { key: "projectBranch", header: "branch" },
3370
+ { key: "lastAccessed", kind: "date" }
3371
+ ]
2764
3372
  });
2765
3373
  } catch (error) {
2766
3374
  handleError(error);
@@ -2770,7 +3378,7 @@ function registerProjectCommands(program) {
2770
3378
  try {
2771
3379
  const api = createApiClient();
2772
3380
  await api.admin.deleteProject(projectId);
2773
- console.log(chalk10.green(`Project "${projectId}" deleted.`));
3381
+ success(`Project "${projectId}" deleted.`);
2774
3382
  } catch (error) {
2775
3383
  handleError(error);
2776
3384
  }
@@ -2779,7 +3387,7 @@ function registerProjectCommands(program) {
2779
3387
  try {
2780
3388
  const api = createApiClient();
2781
3389
  await api.admin.lockProject(projectId);
2782
- console.log(chalk10.green(`Project "${projectId}" locked.`));
3390
+ success(`Project "${projectId}" locked.`);
2783
3391
  } catch (error) {
2784
3392
  handleError(error);
2785
3393
  }
@@ -2788,7 +3396,7 @@ function registerProjectCommands(program) {
2788
3396
  try {
2789
3397
  const api = createApiClient();
2790
3398
  await api.admin.unlockProject(projectId);
2791
- console.log(chalk10.green(`Project "${projectId}" unlocked.`));
3399
+ success(`Project "${projectId}" unlocked.`);
2792
3400
  } catch (error) {
2793
3401
  handleError(error);
2794
3402
  }
@@ -2811,7 +3419,7 @@ function registerProjectCommands(program) {
2811
3419
  try {
2812
3420
  const api = createApiClient();
2813
3421
  await api.admin.inviteProjectMember(projectId, userId, role.toUpperCase());
2814
- console.log(chalk10.green(`Invited ${userId} to "${projectId}" as ${role.toUpperCase()}.`));
3422
+ success(`Invited ${userId} to "${projectId}" as ${role.toUpperCase()}.`);
2815
3423
  } catch (error) {
2816
3424
  handleError(error);
2817
3425
  }
@@ -2820,7 +3428,7 @@ function registerProjectCommands(program) {
2820
3428
  try {
2821
3429
  const api = createApiClient();
2822
3430
  await api.admin.joinProject(projectId, userId);
2823
- console.log(chalk10.green(`Joined project "${projectId}".`));
3431
+ success(`Joined project "${projectId}".`);
2824
3432
  } catch (error) {
2825
3433
  handleError(error);
2826
3434
  }
@@ -2829,7 +3437,7 @@ function registerProjectCommands(program) {
2829
3437
  try {
2830
3438
  const api = createApiClient();
2831
3439
  await api.admin.removeProjectMember(projectId, userId);
2832
- console.log(chalk10.green(`Removed ${userId} from "${projectId}".`));
3440
+ success(`Removed ${userId} from "${projectId}".`);
2833
3441
  } catch (error) {
2834
3442
  handleError(error);
2835
3443
  }
@@ -2841,16 +3449,16 @@ function registerProjectCommands(program) {
2841
3449
  const api = createApiClient();
2842
3450
  const bundleId = await api.storage.exportProjectBundle(ref.projectId, ref.projectBranch);
2843
3451
  if (options.async) {
2844
- console.log(chalk10.green(`Project export queued (bundle ID: ${bundleId}).`));
3452
+ success(`Project export queued (bundle ID: ${bundleId}).`);
2845
3453
  console.log(`Poll progress: diafunc notebook bundles ${project2}`);
2846
3454
  return;
2847
3455
  }
2848
- console.log(chalk10.dim(`Project export queued (bundle ID: ${bundleId}); waiting for it to finish\u2026`));
3456
+ console.log(chalk12.dim(`Project export queued (bundle ID: ${bundleId}); waiting for it to finish\u2026`));
2849
3457
  const job = await pollUntilFinished(api.storage, ref.projectId, ref.projectBranch, bundleId);
2850
3458
  const response = await api.storage.getBundleContent(ref.projectId, ref.projectBranch, bundleId, job.filename);
2851
3459
  const outFile = options.out ?? "project.dfproj";
2852
3460
  const bytes = await streamResponseToFile(response, outFile);
2853
- console.log(chalk10.green(`Bundle written to ${outFile} (${bytes} bytes, ${job.entityCount ?? "?"} entities).`));
3461
+ success(`Bundle written to ${outFile} (${bytes} bytes, ${job.entityCount ?? "?"} entities).`);
2854
3462
  } catch (error) {
2855
3463
  handleError(error);
2856
3464
  }
@@ -2869,25 +3477,25 @@ function registerProjectCommands(program) {
2869
3477
  }
2870
3478
 
2871
3479
  // src/commands/team/index.ts
2872
- import chalk12 from "chalk";
3480
+ import chalk14 from "chalk";
2873
3481
 
2874
3482
  // src/util/confirm.ts
2875
3483
  import * as readline from "readline";
2876
- import chalk11 from "chalk";
3484
+ import chalk13 from "chalk";
2877
3485
  async function confirmDestructive(message, opts = {}) {
2878
3486
  if (!process.stdin.isTTY || opts.yes) return;
2879
3487
  const expected = opts.resourceId ?? "yes";
2880
- const hint = opts.resourceId ? `"${opts.resourceId}"` : '"yes"';
2881
- console.log(chalk11.yellow(`! ${message}`));
3488
+ const hint2 = opts.resourceId ? `"${opts.resourceId}"` : '"yes"';
3489
+ console.log(chalk13.yellow(`! ${message}`));
2882
3490
  const answer = await new Promise((resolve) => {
2883
3491
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
2884
- rl.question(` Type ${hint} to confirm: `, (ans) => {
3492
+ rl.question(` Type ${hint2} to confirm: `, (ans) => {
2885
3493
  rl.close();
2886
3494
  resolve(ans);
2887
3495
  });
2888
3496
  });
2889
3497
  if (answer.trim() !== expected) {
2890
- console.log(chalk11.dim("Aborted."));
3498
+ console.log(chalk13.dim("Aborted."));
2891
3499
  process.exit(1);
2892
3500
  }
2893
3501
  }
@@ -2947,15 +3555,21 @@ function printInvoicePreview(preview, outputFormat) {
2947
3555
  }
2948
3556
  }
2949
3557
  function registerTeamCommands(program) {
2950
- const team = program.command("team").description("Manage teams: membership, invitations, seats, billing, and ownership");
3558
+ const team = program.command("team").description("Manage teams: membership, invitations, seats, billing, and ownership").addHelpText("after", `
3559
+ Examples:
3560
+ $ diafunc team list the teams you belong to
3561
+ $ diafunc team use <teamId> work under one
3562
+ $ diafunc team usage <teamId> credits, by member
3563
+ $ diafunc team members invite <teamId> <email> MEMBER
3564
+ `);
3565
+ ;
2951
3566
  team.command("list", { isDefault: true }).description("List the teams you belong to").action(async (_options, cmd) => {
2952
3567
  try {
2953
3568
  const api = createApiClient();
2954
3569
  const teams = await api.admin.listMyTeams();
2955
3570
  format(teams, {
2956
3571
  format: getOutputFormat2(cmd),
2957
- columns: ["id", "name", "planId", "seatCount", "packCount", "renewal"],
2958
- dateColumns: ["createdAt", "dunningStartedAt"]
3572
+ columns: ["id", "name", "planId", "seatCount", "packCount", "renewal"]
2959
3573
  });
2960
3574
  } catch (error) {
2961
3575
  handleError(error);
@@ -2965,8 +3579,7 @@ function registerTeamCommands(program) {
2965
3579
  try {
2966
3580
  const api = createApiClient();
2967
3581
  format(await api.admin.getTeam(teamId), {
2968
- format: getOutputFormat2(cmd),
2969
- dateColumns: ["createdAt", "dunningStartedAt"]
3582
+ format: getOutputFormat2(cmd)
2970
3583
  });
2971
3584
  } catch (error) {
2972
3585
  handleError(error);
@@ -2976,7 +3589,7 @@ function registerTeamCommands(program) {
2976
3589
  try {
2977
3590
  const api = createApiClient();
2978
3591
  await api.admin.setActiveTeam(teamId);
2979
- formatMessage(`Active team set to "${teamId}".`, { format: getOutputFormat2(cmd) });
3592
+ success(`Active team set to "${teamId}".`, { format: getOutputFormat2(cmd) });
2980
3593
  } catch (error) {
2981
3594
  handleError(error);
2982
3595
  }
@@ -3018,7 +3631,7 @@ function registerTeamCommands(program) {
3018
3631
  return;
3019
3632
  }
3020
3633
  console.log("Open this URL to complete checkout:");
3021
- console.log(chalk12.cyan(session.url));
3634
+ console.log(chalk14.cyan(session.url));
3022
3635
  } catch (error) {
3023
3636
  handleError(error);
3024
3637
  }
@@ -3033,7 +3646,7 @@ function registerTeamCommands(program) {
3033
3646
  return;
3034
3647
  }
3035
3648
  console.log("Open this URL to manage billing:");
3036
- console.log(chalk12.cyan(session.url));
3649
+ console.log(chalk14.cyan(session.url));
3037
3650
  } catch (error) {
3038
3651
  handleError(error);
3039
3652
  }
@@ -3046,7 +3659,7 @@ function registerTeamCommands(program) {
3046
3659
  );
3047
3660
  const api = createApiClient();
3048
3661
  const response = await api.admin.cancelTeam(teamId);
3049
- formatMessage(
3662
+ success(
3050
3663
  `Team "${teamId}" cancelled. Access ends ${response.endsAt ?? "at the end of the period"}.`,
3051
3664
  { format: getOutputFormat2(cmd) }
3052
3665
  );
@@ -3062,7 +3675,7 @@ function registerTeamCommands(program) {
3062
3675
  });
3063
3676
  const api = createApiClient();
3064
3677
  await api.admin.leaveTeam(teamId);
3065
- formatMessage(`Left team "${teamId}".`, { format: getOutputFormat2(cmd) });
3678
+ success(`Left team "${teamId}".`, { format: getOutputFormat2(cmd) });
3066
3679
  } catch (error) {
3067
3680
  handleError(error);
3068
3681
  }
@@ -3082,8 +3695,7 @@ function registerMemberCommands(team) {
3082
3695
  const shown = options.all ? all : all.filter((m) => !m.removedAt);
3083
3696
  format(shown, {
3084
3697
  format: getOutputFormat2(cmd),
3085
- columns: options.all ? ["userId", "name", "email", "role", "joinedAt", "removedAt"] : ["userId", "name", "email", "role", "joinedAt"],
3086
- dateColumns: ["joinedAt", "invitedAt", "removedAt"]
3698
+ columns: options.all ? ["userId", "name", "email", "role", "joinedAt", "removedAt"] : ["userId", "name", "email", "role", "joinedAt"]
3087
3699
  });
3088
3700
  } catch (error) {
3089
3701
  handleError(error);
@@ -3094,7 +3706,7 @@ function registerMemberCommands(team) {
3094
3706
  const role = parseRole(options.role);
3095
3707
  const api = createApiClient();
3096
3708
  await api.admin.inviteTeamMember(teamId, email, role);
3097
- formatMessage(`Invited ${email} to team "${teamId}" as ${role}.`, {
3709
+ success(`Invited ${email} to team "${teamId}" as ${role}.`, {
3098
3710
  format: getOutputFormat2(cmd)
3099
3711
  });
3100
3712
  } catch (error) {
@@ -3109,7 +3721,7 @@ function registerMemberCommands(team) {
3109
3721
  });
3110
3722
  const api = createApiClient();
3111
3723
  await api.admin.removeTeamMember(teamId, userId);
3112
- formatMessage(`Removed ${userId} from team "${teamId}".`, {
3724
+ success(`Removed ${userId} from team "${teamId}".`, {
3113
3725
  format: getOutputFormat2(cmd)
3114
3726
  });
3115
3727
  } catch (error) {
@@ -3124,8 +3736,7 @@ function registerInvitationCommands(team) {
3124
3736
  const api = createApiClient();
3125
3737
  format(await api.admin.listTeamInvitations(teamId), {
3126
3738
  format: getOutputFormat2(cmd),
3127
- columns: ["invitationId", "email", "role", "invitedBy", "expiresAt"],
3128
- dateColumns: ["createdAt", "expiresAt"]
3739
+ columns: ["invitationId", "email", "role", "invitedBy", "expiresAt"]
3129
3740
  });
3130
3741
  } catch (error) {
3131
3742
  handleError(error);
@@ -3139,7 +3750,7 @@ function registerInvitationCommands(team) {
3139
3750
  });
3140
3751
  const api = createApiClient();
3141
3752
  await api.admin.revokeTeamInvitation(teamId, invitationId);
3142
- formatMessage(`Revoked invitation "${invitationId}".`, {
3753
+ success(`Revoked invitation "${invitationId}".`, {
3143
3754
  format: getOutputFormat2(cmd)
3144
3755
  });
3145
3756
  } catch (error) {
@@ -3150,7 +3761,7 @@ function registerInvitationCommands(team) {
3150
3761
  try {
3151
3762
  const api = createApiClient();
3152
3763
  await api.admin.resendTeamInvitation(teamId, invitationId);
3153
- formatMessage(`Resent invitation "${invitationId}".`, {
3764
+ success(`Resent invitation "${invitationId}".`, {
3154
3765
  format: getOutputFormat2(cmd)
3155
3766
  });
3156
3767
  } catch (error) {
@@ -3161,7 +3772,7 @@ function registerInvitationCommands(team) {
3161
3772
  try {
3162
3773
  const api = createApiClient();
3163
3774
  const member = await api.admin.acceptTeamInvitation(token);
3164
- formatMessage(`Joined the team as ${member.role}.`, {
3775
+ success(`Joined the team as ${member.role}.`, {
3165
3776
  format: getOutputFormat2(cmd)
3166
3777
  });
3167
3778
  } catch (error) {
@@ -3191,7 +3802,7 @@ function registerSeatCommands(team) {
3191
3802
  );
3192
3803
  const api = createApiClient();
3193
3804
  const change = await api.admin.updateTeamSeatCount(teamId, seatCount);
3194
- formatMessage(`Seats changed from ${change.oldSeatCount} to ${change.newSeatCount}.`, {
3805
+ success(`Seats changed from ${change.oldSeatCount} to ${change.newSeatCount}.`, {
3195
3806
  format: getOutputFormat2(cmd)
3196
3807
  });
3197
3808
  } catch (error) {
@@ -3221,7 +3832,7 @@ function registerPackCommands(team) {
3221
3832
  );
3222
3833
  const api = createApiClient();
3223
3834
  const change = await api.admin.updateTeamPackCount(teamId, packCount);
3224
- formatMessage(`Packs changed from ${change.oldPackCount} to ${change.newPackCount}.`, {
3835
+ success(`Packs changed from ${change.oldPackCount} to ${change.newPackCount}.`, {
3225
3836
  format: getOutputFormat2(cmd)
3226
3837
  });
3227
3838
  } catch (error) {
@@ -3258,7 +3869,7 @@ function registerOwnershipCommands(team) {
3258
3869
  }
3259
3870
  return;
3260
3871
  }
3261
- format(pending, { format: outputFormat, dateColumns: ["createdAt"] });
3872
+ format(pending, { format: outputFormat });
3262
3873
  } catch (error) {
3263
3874
  handleError(error);
3264
3875
  }
@@ -3272,10 +3883,10 @@ function registerOwnershipCommands(team) {
3272
3883
  format(response, { format: outputFormat });
3273
3884
  return;
3274
3885
  }
3275
- console.log(chalk12.green(`Ownership transfer ${response.status}.`));
3886
+ success(`Ownership transfer ${response.status}.`);
3276
3887
  if (response.checkoutUrl) {
3277
3888
  console.log("Open this URL to complete the billing handover:");
3278
- console.log(chalk12.cyan(response.checkoutUrl));
3889
+ console.log(chalk14.cyan(response.checkoutUrl));
3279
3890
  }
3280
3891
  } catch (error) {
3281
3892
  handleError(error);
@@ -3285,7 +3896,7 @@ function registerOwnershipCommands(team) {
3285
3896
  try {
3286
3897
  const api = createApiClient();
3287
3898
  await api.admin.cancelOwnershipTransfer(teamId);
3288
- formatMessage(`Cancelled the ownership transfer for team "${teamId}".`, {
3899
+ success(`Cancelled the ownership transfer for team "${teamId}".`, {
3289
3900
  format: getOutputFormat2(cmd)
3290
3901
  });
3291
3902
  } catch (error) {
@@ -3295,7 +3906,6 @@ function registerOwnershipCommands(team) {
3295
3906
  }
3296
3907
 
3297
3908
  // src/commands/entity/index.ts
3298
- import chalk13 from "chalk";
3299
3909
  import * as fs3 from "fs";
3300
3910
  function getOutputFormat3(cmd) {
3301
3911
  const config = loadConfig();
@@ -3307,7 +3917,16 @@ function getOverrides2(cmd) {
3307
3917
  return { project: opts.project, branch: opts.branch };
3308
3918
  }
3309
3919
  function registerEntityCommands(program) {
3310
- const entity = program.command("entity").description("Manage entities");
3920
+ const entity = program.command("entity").description("Manage entities").addHelpText("after", `
3921
+ An entity reference is <project>/<branch>/<entity>/<entityBranch>. With
3922
+ 'diafunc config set defaults.project <id>' the leading parts can be omitted.
3923
+
3924
+ Examples:
3925
+ $ diafunc entity list <projectId>
3926
+ $ diafunc entity get <project>/main/<entity>/main
3927
+ $ diafunc entity history <project>/main/<entity>/main
3928
+ `);
3929
+ ;
3311
3930
  entity.command("list").description("List entities in a project (via linked entities from project root)").argument("<projectRef>", "Project reference (projectId or projectId/branch)").action(async (projectRef, _options, cmd) => {
3312
3931
  try {
3313
3932
  const outputFormat = getOutputFormat3(cmd);
@@ -3373,7 +3992,7 @@ function registerEntityCommands(program) {
3373
3992
  const resolved = parseEntityReference(ref, overrides);
3374
3993
  const api = createApiClient();
3375
3994
  await api.storage.deleteEntity(resolved);
3376
- console.log(chalk13.green(`Entity "${resolved.entityId}" deleted.`));
3995
+ success(`Entity "${resolved.entityId}" deleted.`);
3377
3996
  } catch (error) {
3378
3997
  handleError(error);
3379
3998
  }
@@ -3414,7 +4033,7 @@ function registerEntityCommands(program) {
3414
4033
  const resolved = parseEntityReference(ref, overrides);
3415
4034
  const api = createApiClient();
3416
4035
  await api.storage.revertEntity(resolved, parseInt(version, 10));
3417
- console.log(chalk13.green(`Entity "${resolved.entityId}" reverted to version ${version}.`));
4036
+ success(`Entity "${resolved.entityId}" reverted to version ${version}.`);
3418
4037
  } catch (error) {
3419
4038
  handleError(error);
3420
4039
  }
@@ -3425,7 +4044,7 @@ function registerEntityCommands(program) {
3425
4044
  const resolved = parseEntityReference(ref, overrides);
3426
4045
  const api = createApiClient();
3427
4046
  await api.storage.renameEntity(resolved, newId);
3428
- console.log(chalk13.green(`Entity renamed from "${resolved.entityId}" to "${newId}".`));
4047
+ success(`Entity renamed from "${resolved.entityId}" to "${newId}".`);
3429
4048
  } catch (error) {
3430
4049
  handleError(error);
3431
4050
  }
@@ -3440,7 +4059,7 @@ function registerEntityCommands(program) {
3440
4059
  if (options.out) {
3441
4060
  const buffer = Buffer.from(await response.arrayBuffer());
3442
4061
  fs3.writeFileSync(options.out, buffer);
3443
- console.log(chalk13.green(`Content saved to ${options.out}`));
4062
+ success(`Content saved to ${options.out}`);
3444
4063
  } else {
3445
4064
  const text = await response.text();
3446
4065
  process.stdout.write(text);
@@ -3457,7 +4076,7 @@ function registerEntityCommands(program) {
3457
4076
  const fileBuffer = fs3.readFileSync(file);
3458
4077
  const base64 = fileBuffer.toString("base64");
3459
4078
  await api.storage.saveEntityContentBase64(resolved, base64);
3460
- console.log(chalk13.green(`Content uploaded from "${file}" to entity "${resolved.entityId}".`));
4079
+ success(`Content uploaded from "${file}" to entity "${resolved.entityId}".`);
3461
4080
  } catch (error) {
3462
4081
  handleError(error);
3463
4082
  }
@@ -3469,7 +4088,7 @@ function registerEntityCommands(program) {
3469
4088
  const resolved = parseEntityReference(ref, overrides);
3470
4089
  const api = createApiClient();
3471
4090
  await api.storage.deleteEntityContent(resolved);
3472
- console.log(chalk13.green(`Content deleted from entity "${resolved.entityId}".`));
4091
+ success(`Content deleted from entity "${resolved.entityId}".`);
3473
4092
  } catch (error) {
3474
4093
  handleError(error);
3475
4094
  }
@@ -3482,14 +4101,14 @@ function registerEntityCommands(program) {
3482
4101
  const request = { rootEntityIds: entityIds, dataFormat: options.data };
3483
4102
  if (options.async) {
3484
4103
  const bundleId = await api.storage.exportEntitySubset(ref.projectId, ref.projectBranch, request);
3485
- console.log(chalk13.green(`Export queued (bundle ID: ${bundleId}).`));
4104
+ success(`Export queued (bundle ID: ${bundleId}).`);
3486
4105
  console.log(`Poll progress: diafunc notebook bundles ${project}`);
3487
4106
  return;
3488
4107
  }
3489
4108
  const response = await api.storage.streamEntitySubset(ref.projectId, ref.projectBranch, request);
3490
4109
  const outFile = options.out ?? "entities.dfset";
3491
4110
  const bytes = await streamResponseToFile(response, outFile);
3492
- console.log(chalk13.green(`Bundle written to ${outFile} (${bytes} bytes, ${entityIds.length} entity(ies)).`));
4111
+ success(`Bundle written to ${outFile} (${bytes} bytes, ${entityIds.length} entity(ies)).`);
3493
4112
  } catch (error) {
3494
4113
  handleError(error);
3495
4114
  }
@@ -3508,7 +4127,6 @@ function registerEntityCommands(program) {
3508
4127
  }
3509
4128
 
3510
4129
  // src/commands/link/index.ts
3511
- import chalk14 from "chalk";
3512
4130
  function getOutputFormat4(cmd) {
3513
4131
  const config = loadConfig();
3514
4132
  const globalOpts = cmd.optsWithGlobals();
@@ -3558,7 +4176,7 @@ function registerLinkCommands(program) {
3558
4176
  target.entityId,
3559
4177
  target.entityBranch
3560
4178
  );
3561
- console.log(chalk14.green(`Link "${linkId}" created: ${source.entityId} \u2192 ${target.entityId}`));
4179
+ success(`Link "${linkId}" created: ${source.entityId} \u2192 ${target.entityId}`);
3562
4180
  } catch (error) {
3563
4181
  handleError(error);
3564
4182
  }
@@ -3579,7 +4197,7 @@ function registerLinkCommands(program) {
3579
4197
  target.entityId,
3580
4198
  target.entityBranch
3581
4199
  );
3582
- console.log(chalk14.green(`Link "${linkId}" deleted: ${source.entityId} \u2192 ${target.entityId}`));
4200
+ success(`Link "${linkId}" deleted: ${source.entityId} \u2192 ${target.entityId}`);
3583
4201
  } else {
3584
4202
  await api.storage.deleteLink(
3585
4203
  source.projectId,
@@ -3588,7 +4206,7 @@ function registerLinkCommands(program) {
3588
4206
  source.entityBranch,
3589
4207
  linkId
3590
4208
  );
3591
- console.log(chalk14.green(`All links with ID "${linkId}" from "${source.entityId}" deleted.`));
4209
+ success(`All links with ID "${linkId}" from "${source.entityId}" deleted.`);
3592
4210
  }
3593
4211
  } catch (error) {
3594
4212
  handleError(error);
@@ -3597,7 +4215,6 @@ function registerLinkCommands(program) {
3597
4215
  }
3598
4216
 
3599
4217
  // src/commands/event/index.ts
3600
- import chalk15 from "chalk";
3601
4218
  function getOutputFormat5(cmd) {
3602
4219
  const config = loadConfig();
3603
4220
  const globalOpts = cmd.optsWithGlobals();
@@ -3659,7 +4276,7 @@ function registerEventCommands(program) {
3659
4276
  const api = createApiClient();
3660
4277
  const arr = Array.isArray(events) ? events : [events];
3661
4278
  await api.storage.createEvents(arr);
3662
- console.log(chalk15.green(`${arr.length} event(s) created.`));
4279
+ success(`${arr.length} event(s) created.`);
3663
4280
  } catch (error) {
3664
4281
  handleError(error);
3665
4282
  }
@@ -3686,7 +4303,7 @@ function registerEventCommands(program) {
3686
4303
  const resolved = parseEntityReference(ref, overrides);
3687
4304
  const api = createApiClient();
3688
4305
  await api.storage.deleteEvent(resolved, eventId, occurrenceId);
3689
- console.log(chalk15.green(`Event "${eventId}/${occurrenceId}" deleted.`));
4306
+ success(`Event "${eventId}/${occurrenceId}" deleted.`);
3690
4307
  } catch (error) {
3691
4308
  handleError(error);
3692
4309
  }
@@ -3694,7 +4311,6 @@ function registerEventCommands(program) {
3694
4311
  }
3695
4312
 
3696
4313
  // src/commands/branch/index.ts
3697
- import chalk16 from "chalk";
3698
4314
  function getOutputFormat6(cmd) {
3699
4315
  const config = loadConfig();
3700
4316
  const globalOpts = cmd.optsWithGlobals();
@@ -3705,7 +4321,13 @@ function getOverrides5(cmd) {
3705
4321
  return { project: opts.project, branch: opts.branch };
3706
4322
  }
3707
4323
  function registerBranchCommands(program) {
3708
- const branch = program.command("branch").description("Manage branches");
4324
+ const branch = program.command("branch").description("Manage branches").addHelpText("after", `
4325
+ Examples:
4326
+ $ diafunc branch list <projectId>
4327
+ $ diafunc branch create <projectId> experiment
4328
+ $ diafunc branch merge --from experiment --to main --entity <id>
4329
+ `);
4330
+ ;
3709
4331
  branch.command("list").description("List branches for a project").argument("[projectId]", "Project ID (uses default if omitted)").action(async (projectId, _options, cmd) => {
3710
4332
  try {
3711
4333
  const outputFormat = getOutputFormat6(cmd);
@@ -3713,7 +4335,7 @@ function registerBranchCommands(program) {
3713
4335
  const config = loadConfig();
3714
4336
  const pid = projectId ?? overrides.project ?? config.defaults.project;
3715
4337
  if (!pid) {
3716
- console.error(chalk16.red("No project specified. Pass a project ID or set defaults.project."));
4338
+ failure("No project specified. Pass a project ID or set defaults.project.");
3717
4339
  process.exit(1);
3718
4340
  }
3719
4341
  const api = createApiClient();
@@ -3737,7 +4359,7 @@ function registerBranchCommands(program) {
3737
4359
  sourceProjectBranch: options.source,
3738
4360
  targetProjectBranch: branchName
3739
4361
  });
3740
- console.log(chalk16.green(`Branch "${branchName}" created in project "${projectId}" from "${options.source}".`));
4362
+ success(`Branch "${branchName}" created in project "${projectId}" from "${options.source}".`);
3741
4363
  } catch (error) {
3742
4364
  handleError(error);
3743
4365
  }
@@ -3746,7 +4368,7 @@ function registerBranchCommands(program) {
3746
4368
  try {
3747
4369
  const api = createApiClient();
3748
4370
  await api.storage.deleteProjectBranch(projectId, branchName);
3749
- console.log(chalk16.green(`Branch "${branchName}" deleted from project "${projectId}".`));
4371
+ success(`Branch "${branchName}" deleted from project "${projectId}".`);
3750
4372
  } catch (error) {
3751
4373
  handleError(error);
3752
4374
  }
@@ -3767,7 +4389,7 @@ function registerBranchCommands(program) {
3767
4389
  linkId: options.linkId,
3768
4390
  deepMerge: options.deep
3769
4391
  });
3770
- console.log(chalk16.green("Merge completed."));
4392
+ success("Merge completed.");
3771
4393
  } catch (error) {
3772
4394
  handleError(error);
3773
4395
  }
@@ -3782,7 +4404,7 @@ function registerBranchCommands(program) {
3782
4404
  forkProjectName: options.name ?? forkProjectId,
3783
4405
  forkProjectDescription: options.description
3784
4406
  });
3785
- console.log(chalk16.green(`Project "${projectId}" forked to "${forkProjectId}".`));
4407
+ success(`Project "${projectId}" forked to "${forkProjectId}".`);
3786
4408
  } catch (error) {
3787
4409
  handleError(error);
3788
4410
  }
@@ -3790,7 +4412,7 @@ function registerBranchCommands(program) {
3790
4412
  }
3791
4413
 
3792
4414
  // src/commands/table/index.ts
3793
- import chalk17 from "chalk";
4415
+ import chalk15 from "chalk";
3794
4416
  import * as fs4 from "fs";
3795
4417
  import * as path3 from "path";
3796
4418
  function getOutputFormat7(cmd) {
@@ -3816,7 +4438,14 @@ function deriveOutFile(entityId, extension, archive, compression) {
3816
4438
  return name;
3817
4439
  }
3818
4440
  function registerTableCommands(program) {
3819
- const table = program.command("table").description("Manage tables");
4441
+ const table = program.command("table").description("Manage tables").addHelpText("after", `
4442
+ Examples:
4443
+ $ diafunc table view <ref> --rows 0:20 the first twenty rows
4444
+ $ diafunc table import <ref> data.csv load a file
4445
+ $ diafunc table export <ref> parquet write one out
4446
+ $ diafunc table import-formats what can be loaded
4447
+ `);
4448
+ ;
3820
4449
  table.command("view").description("View table data").argument("<ref>", "Table entity reference").option("--rows <range>", "Row range (e.g., 0:10)").option("--cols <range>", "Column range (e.g., 0:5)").action(async (ref, options, cmd) => {
3821
4450
  try {
3822
4451
  const outputFormat = getOutputFormat7(cmd);
@@ -3860,7 +4489,7 @@ function registerTableCommands(program) {
3860
4489
  console.log(colNames.map((c) => row2[c] ?? "").join(" "));
3861
4490
  }
3862
4491
  } else {
3863
- console.log(chalk17.dim(`${snapshot.rows.length} rows \xD7 ${snapshot.columns.length} columns`));
4492
+ console.log(chalk15.dim(`${snapshot.rows.length} rows \xD7 ${snapshot.columns.length} columns`));
3864
4493
  format(tableData, { format: outputFormat, columns: colNames });
3865
4494
  }
3866
4495
  } catch (error) {
@@ -3872,33 +4501,44 @@ function registerTableCommands(program) {
3872
4501
  const overrides = getOverrides6(cmd);
3873
4502
  const resolved = parseEntityReference(ref, overrides);
3874
4503
  if (!fs4.existsSync(file)) {
3875
- console.error(chalk17.red(`File not found: ${file}`));
3876
- process.exit(1);
4504
+ failure(`File not found: ${file}`);
4505
+ process.exit(EXIT_USAGE);
3877
4506
  }
3878
4507
  const api = createApiClient();
3879
4508
  const fileBuffer = fs4.readFileSync(file);
3880
4509
  const blob = new Blob([fileBuffer]);
3881
4510
  const formData = new FormData();
3882
4511
  formData.append("content", blob, path3.basename(file));
3883
- console.log(`Importing ${path3.basename(file)} ...`);
3884
- const importId = await api.storage.importTable(resolved, formData, options.selection);
3885
- console.log(`Import started (ID: ${importId}). Waiting for completion ...`);
4512
+ const importId = await withStatus(
4513
+ `Uploading ${path3.basename(file)}`,
4514
+ () => api.storage.importTable(resolved, formData, options.selection)
4515
+ );
3886
4516
  const pollInterval = 1e3;
3887
4517
  const maxAttempts = 300;
3888
- for (let i = 0; i < maxAttempts; i++) {
3889
- await new Promise((resolve) => setTimeout(resolve, pollInterval));
3890
- const imp = await api.storage.getImport(resolved, importId);
3891
- if (imp.finished !== null) {
3892
- if (imp.succeeded) {
3893
- console.log(chalk17.green(`Import completed successfully (${imp.duration}ms).`));
3894
- } else {
3895
- console.error(chalk17.red(`Import failed: ${imp.error}`));
3896
- process.exit(1);
4518
+ const status = new Status();
4519
+ status.start();
4520
+ const startedAt = Date.now();
4521
+ try {
4522
+ for (let i = 0; i < maxAttempts; i++) {
4523
+ await new Promise((resolve) => setTimeout(resolve, pollInterval));
4524
+ const imp = await api.storage.getImport(resolved, importId);
4525
+ if (imp.finished !== null) {
4526
+ status.stop();
4527
+ if (imp.succeeded) {
4528
+ success(`Imported in ${formatDuration(imp.duration)}.`);
4529
+ return;
4530
+ }
4531
+ failure(`Import failed: ${imp.error}`);
4532
+ process.exit(EXIT_FAILURE);
3897
4533
  }
3898
- return;
4534
+ status.set([progressLine("Importing", imp.progress, Date.now() - startedAt)]);
3899
4535
  }
4536
+ } finally {
4537
+ status.stop();
3900
4538
  }
3901
- console.error(chalk17.yellow("Import still in progress. Check status later."));
4539
+ failure(`Import ${importId} is still running after ${formatDuration(pollInterval * maxAttempts)}.`);
4540
+ hint(`It continues on the server \u2014 re-check with 'diafunc table view ${ref}'.`);
4541
+ process.exit(EXIT_FAILURE);
3902
4542
  } catch (error) {
3903
4543
  handleError(error);
3904
4544
  }
@@ -3918,10 +4558,22 @@ function registerTableCommands(program) {
3918
4558
  category: f.category,
3919
4559
  extensions: f.extensions.join(", "),
3920
4560
  mimeTypes: f.mimeTypes.join(", "),
3921
- multiTable: f.multiTable ? "yes" : "no",
3922
- userDefined: f.userDefined ? "yes" : "no"
4561
+ multiTable: f.multiTable,
4562
+ userDefined: f.userDefined
3923
4563
  }));
3924
- format(rows, { format: outputFormat, columns: ["id", "displayName", "category", "extensions", "mimeTypes", "multiTable", "userDefined"] });
4564
+ format(rows, {
4565
+ format: outputFormat,
4566
+ columns: [
4567
+ { key: "id" },
4568
+ { key: "displayName", header: "name" },
4569
+ { key: "category" },
4570
+ { key: "extensions" },
4571
+ // The longest of these runs to 93 characters and would otherwise set the table width.
4572
+ { key: "mimeTypes", header: "mime types", maxWidth: 40 },
4573
+ { key: "multiTable", header: "multi-table", kind: "boolean" },
4574
+ { key: "userDefined", header: "user-defined", kind: "boolean" }
4575
+ ]
4576
+ });
3925
4577
  } catch (error) {
3926
4578
  handleError(error);
3927
4579
  }
@@ -3934,15 +4586,15 @@ function registerTableCommands(program) {
3934
4586
  const formats = await api.storage.getSupportedExportFormats();
3935
4587
  const format2 = formats.formats.find((f) => f.id.toLowerCase() === fmt.toLowerCase());
3936
4588
  if (!format2) {
3937
- console.error(chalk17.red(`Unknown format: "${fmt}". Run \`diafunc table export-formats\` to see the catalogue.`));
4589
+ failure(`Unknown format: "${fmt}". Run \`diafunc table export-formats\` to see the catalogue.`);
3938
4590
  process.exit(1);
3939
4591
  }
3940
4592
  if (options.compression && !formats.compressionAlgorithms.includes(options.compression)) {
3941
- console.error(chalk17.red(`Unknown compression: "${options.compression}". Use one of ${formats.compressionAlgorithms.join(", ")}.`));
4593
+ failure(`Unknown compression: "${options.compression}". Use one of ${formats.compressionAlgorithms.join(", ")}.`);
3942
4594
  process.exit(1);
3943
4595
  }
3944
4596
  if (options.archive && !formats.archiveAlgorithms.includes(options.archive)) {
3945
- console.error(chalk17.red(`Unknown archive: "${options.archive}". Use one of ${formats.archiveAlgorithms.join(", ")}.`));
4597
+ failure(`Unknown archive: "${options.archive}". Use one of ${formats.archiveAlgorithms.join(", ")}.`);
3946
4598
  process.exit(1);
3947
4599
  }
3948
4600
  const exportOptions = {
@@ -3972,10 +4624,10 @@ function registerTableCommands(program) {
3972
4624
  const outFile = options.out ?? deriveOutFile(resolved.entityId, format2.extension, options.archive, options.compression);
3973
4625
  const buffer = Buffer.from(await response.arrayBuffer());
3974
4626
  fs4.writeFileSync(outFile, buffer);
3975
- console.log(chalk17.green(`Table streamed to ${outFile}`));
4627
+ success(`Table streamed to ${outFile}`);
3976
4628
  } else {
3977
4629
  const exportId = await api.storage.exportTable(resolved, format2.id, exportOptions);
3978
- console.log(chalk17.green(`Export queued (ID: ${exportId}).`));
4630
+ success(`Export queued (ID: ${exportId}).`);
3979
4631
  console.log(`Poll progress: diafunc table exports get ${exportId} --ref ${ref}`);
3980
4632
  }
3981
4633
  } catch (error) {
@@ -4000,8 +4652,8 @@ function registerTableCommands(program) {
4000
4652
  knownLimitations: f.knownLimitations.join(" / ")
4001
4653
  }));
4002
4654
  format(rows, { format: outputFormat, columns: ["id", "displayName", "category", "extension", "mimeType", "knownLimitations"] });
4003
- console.log(chalk17.dim(`Compression: ${response.compressionAlgorithms.join(", ")}`));
4004
- console.log(chalk17.dim(`Archive: ${response.archiveAlgorithms.join(", ")}`));
4655
+ console.log(chalk15.dim(`Compression: ${response.compressionAlgorithms.join(", ")}`));
4656
+ console.log(chalk15.dim(`Archive: ${response.archiveAlgorithms.join(", ")}`));
4005
4657
  } catch (error) {
4006
4658
  handleError(error);
4007
4659
  }
@@ -4019,7 +4671,7 @@ function registerTableCommands(program) {
4019
4671
  return;
4020
4672
  }
4021
4673
  if (exports.length === 0) {
4022
- console.log(chalk17.dim("No exports found."));
4674
+ empty("exports found");
4023
4675
  return;
4024
4676
  }
4025
4677
  const rows = exports.map((e) => ({
@@ -4044,7 +4696,7 @@ function registerTableCommands(program) {
4044
4696
  const exports = await api.storage.listExports(resolved);
4045
4697
  const exp = exports.find((e) => e.exportId === exportId);
4046
4698
  if (!exp) {
4047
- console.error(chalk17.red(`Export ${exportId} not found for ref ${options.ref}.`));
4699
+ failure(`Export ${exportId} not found for ref ${options.ref}.`);
4048
4700
  process.exit(1);
4049
4701
  }
4050
4702
  if (outputFormat === "json") {
@@ -4053,11 +4705,11 @@ function registerTableCommands(program) {
4053
4705
  }
4054
4706
  if (exp.finished === null) {
4055
4707
  const pct = Math.round((exp.progress ?? 0) * 100);
4056
- console.log(chalk17.dim(`Export in progress: ${pct}% \u2014 check again later.`));
4708
+ console.log(chalk15.dim(`Export in progress: ${pct}% \u2014 check again later.`));
4057
4709
  return;
4058
4710
  }
4059
4711
  if (!exp.succeeded) {
4060
- console.error(chalk17.red(`Export failed: ${exp.error}`));
4712
+ failure(`Export failed: ${exp.error}`);
4061
4713
  process.exit(1);
4062
4714
  }
4063
4715
  const outFile = options.out ?? exp.filename;
@@ -4065,7 +4717,7 @@ function registerTableCommands(program) {
4065
4717
  const response = await api.storage.downloadExport(resolved, exportId, exp.filename);
4066
4718
  const buffer = Buffer.from(await response.arrayBuffer());
4067
4719
  fs4.writeFileSync(outFile, buffer);
4068
- console.log(chalk17.green(`Export saved to ${outFile}`));
4720
+ success(`Export saved to ${outFile}`);
4069
4721
  } catch (error) {
4070
4722
  handleError(error);
4071
4723
  }
@@ -4077,7 +4729,7 @@ function registerTableCommands(program) {
4077
4729
  const resolved = parseEntityReference(ref, overrides);
4078
4730
  const api = createApiClient();
4079
4731
  await api.storage.appendRow(resolved);
4080
- console.log(chalk17.green("Row appended."));
4732
+ success("Row appended.");
4081
4733
  } catch (error) {
4082
4734
  handleError(error);
4083
4735
  }
@@ -4088,7 +4740,7 @@ function registerTableCommands(program) {
4088
4740
  const resolved = parseEntityReference(ref, overrides);
4089
4741
  const api = createApiClient();
4090
4742
  await api.storage.insertRow(resolved, parseInt(index, 10));
4091
- console.log(chalk17.green(`Row inserted at index ${index}.`));
4743
+ success(`Row inserted at index ${index}.`);
4092
4744
  } catch (error) {
4093
4745
  handleError(error);
4094
4746
  }
@@ -4099,7 +4751,7 @@ function registerTableCommands(program) {
4099
4751
  const resolved = parseEntityReference(ref, overrides);
4100
4752
  const api = createApiClient();
4101
4753
  await api.storage.removeRow(resolved, parseInt(index, 10));
4102
- console.log(chalk17.green(`Row ${index} removed.`));
4754
+ success(`Row ${index} removed.`);
4103
4755
  } catch (error) {
4104
4756
  handleError(error);
4105
4757
  }
@@ -4110,7 +4762,7 @@ function registerTableCommands(program) {
4110
4762
  const resolved = parseEntityReference(ref, overrides);
4111
4763
  const api = createApiClient();
4112
4764
  await api.storage.deleteRow(resolved, parseInt(index, 10));
4113
- console.log(chalk17.green(`Row ${index} deleted.`));
4765
+ success(`Row ${index} deleted.`);
4114
4766
  } catch (error) {
4115
4767
  handleError(error);
4116
4768
  }
@@ -4122,7 +4774,7 @@ function registerTableCommands(program) {
4122
4774
  const resolved = parseEntityReference(ref, overrides);
4123
4775
  const api = createApiClient();
4124
4776
  await api.storage.appendColumn(resolved);
4125
- console.log(chalk17.green("Column appended."));
4777
+ success("Column appended.");
4126
4778
  } catch (error) {
4127
4779
  handleError(error);
4128
4780
  }
@@ -4133,7 +4785,7 @@ function registerTableCommands(program) {
4133
4785
  const resolved = parseEntityReference(ref, overrides);
4134
4786
  const api = createApiClient();
4135
4787
  await api.storage.insertColumn(resolved, parseInt(index, 10));
4136
- console.log(chalk17.green(`Column inserted at index ${index}.`));
4788
+ success(`Column inserted at index ${index}.`);
4137
4789
  } catch (error) {
4138
4790
  handleError(error);
4139
4791
  }
@@ -4144,7 +4796,7 @@ function registerTableCommands(program) {
4144
4796
  const resolved = parseEntityReference(ref, overrides);
4145
4797
  const api = createApiClient();
4146
4798
  await api.storage.removeColumn(resolved, parseInt(index, 10));
4147
- console.log(chalk17.green(`Column ${index} removed.`));
4799
+ success(`Column ${index} removed.`);
4148
4800
  } catch (error) {
4149
4801
  handleError(error);
4150
4802
  }
@@ -4155,7 +4807,7 @@ function registerTableCommands(program) {
4155
4807
  const resolved = parseEntityReference(ref, overrides);
4156
4808
  const api = createApiClient();
4157
4809
  await api.storage.deleteColumn(resolved, parseInt(index, 10));
4158
- console.log(chalk17.green(`Column ${index} deleted.`));
4810
+ success(`Column ${index} deleted.`);
4159
4811
  } catch (error) {
4160
4812
  handleError(error);
4161
4813
  }
@@ -4172,7 +4824,7 @@ function registerTableCommands(program) {
4172
4824
  value,
4173
4825
  type: "text"
4174
4826
  }]);
4175
- console.log(chalk17.green(`Cell [${row2}, ${col}] set to "${value}".`));
4827
+ success(`Cell [${row2}, ${col}] set to "${value}".`);
4176
4828
  } catch (error) {
4177
4829
  handleError(error);
4178
4830
  }
@@ -4183,7 +4835,7 @@ function registerTableCommands(program) {
4183
4835
  const resolved = parseEntityReference(ref, overrides);
4184
4836
  const api = createApiClient();
4185
4837
  await api.storage.removeCell(resolved, parseInt(row2, 10), parseInt(col, 10));
4186
- console.log(chalk17.green(`Cell [${row2}, ${col}] deleted.`));
4838
+ success(`Cell [${row2}, ${col}] deleted.`);
4187
4839
  } catch (error) {
4188
4840
  handleError(error);
4189
4841
  }
@@ -4195,7 +4847,7 @@ function registerTableCommands(program) {
4195
4847
  const resolved = parseEntityReference(ref, overrides);
4196
4848
  const api = createApiClient();
4197
4849
  await api.storage.clearTable(resolved);
4198
- console.log(chalk17.green("Table cleared."));
4850
+ success("Table cleared.");
4199
4851
  } catch (error) {
4200
4852
  handleError(error);
4201
4853
  }
@@ -4203,7 +4855,7 @@ function registerTableCommands(program) {
4203
4855
  }
4204
4856
 
4205
4857
  // src/commands/notebook/index.ts
4206
- import chalk18 from "chalk";
4858
+ import chalk16 from "chalk";
4207
4859
  import * as fs5 from "fs";
4208
4860
  import * as path4 from "path";
4209
4861
  function getOutputFormat8(cmd) {
@@ -4216,7 +4868,13 @@ function getOverrides7(cmd) {
4216
4868
  return { project: opts.project, branch: opts.branch };
4217
4869
  }
4218
4870
  function registerNotebookCommands(program) {
4219
- const notebook = program.command("notebook").description("Export and import notebook bundles");
4871
+ const notebook = program.command("notebook").description("Export and import notebook bundles").addHelpText("after", `
4872
+ Examples:
4873
+ $ diafunc notebook export <project> <notebookId> -o notebook.dfnb
4874
+ $ diafunc notebook import <project> notebook.dfnb --preview
4875
+ $ diafunc notebook import <project> notebook.dfnb
4876
+ `);
4877
+ ;
4220
4878
  notebook.command("export").description("Export one or more notebooks (plus their closure) to a .dfnb bundle").argument("<project>", "Project reference (projectId or projectId/branch)").argument("<notebookIds...>", "Entity id(s) of the notebook(s) to export").option("--out <file>", "Output file (defaults to notebooks.dfnb)").option("--data <encoding>", "Embedded table-data encoding: csv (default) or parquet", "csv").option("--async", "Queue a background job instead of streaming the download now").action(async (project, notebookIds, options, cmd) => {
4221
4879
  try {
4222
4880
  const overrides = getOverrides7(cmd);
@@ -4225,7 +4883,7 @@ function registerNotebookCommands(program) {
4225
4883
  const request = { rootEntityIds: notebookIds, dataFormat: options.data };
4226
4884
  if (options.async) {
4227
4885
  const bundleId = await api.storage.exportBundle(ref.projectId, ref.projectBranch, request);
4228
- console.log(chalk18.green(`Export queued (bundle ID: ${bundleId}).`));
4886
+ success(`Export queued (bundle ID: ${bundleId}).`);
4229
4887
  console.log(`Poll progress: diafunc notebook bundles ${project}`);
4230
4888
  return;
4231
4889
  }
@@ -4233,7 +4891,7 @@ function registerNotebookCommands(program) {
4233
4891
  const outFile = options.out ?? "notebooks.dfnb";
4234
4892
  const buffer = Buffer.from(await response.arrayBuffer());
4235
4893
  fs5.writeFileSync(outFile, buffer);
4236
- console.log(chalk18.green(`Bundle written to ${outFile} (${buffer.length} bytes, ${notebookIds.length} notebook(s)).`));
4894
+ success(`Bundle written to ${outFile} (${buffer.length} bytes, ${notebookIds.length} notebook(s)).`);
4237
4895
  } catch (error) {
4238
4896
  handleError(error);
4239
4897
  }
@@ -4254,9 +4912,9 @@ function registerNotebookCommands(program) {
4254
4912
  format(preview, { format: outputFormat });
4255
4913
  return;
4256
4914
  }
4257
- console.log(chalk18.bold(`${preview.kind} bundle \xB7 ${preview.entityCount} entities`));
4915
+ console.log(chalk16.bold(`${preview.kind} bundle \xB7 ${preview.entityCount} entities`));
4258
4916
  if (preview.sourceProjectId) {
4259
- console.log(chalk18.dim(`from ${preview.sourceProjectId}/${preview.sourceProjectBranch}` + (preview.createdBy ? ` \xB7 by ${preview.createdBy}` : "")));
4917
+ console.log(chalk16.dim(`from ${preview.sourceProjectId}/${preview.sourceProjectBranch}` + (preview.createdBy ? ` \xB7 by ${preview.createdBy}` : "")));
4260
4918
  }
4261
4919
  const counts = /* @__PURE__ */ new Map();
4262
4920
  for (const e of preview.entities ?? []) {
@@ -4266,9 +4924,9 @@ function registerNotebookCommands(program) {
4266
4924
  console.log(` ${type}: ${count}`);
4267
4925
  }
4268
4926
  if (preview.lossinessNotes && preview.lossinessNotes.length > 0) {
4269
- console.log(chalk18.yellow("Lossiness:"));
4927
+ console.log(chalk16.yellow("Lossiness:"));
4270
4928
  for (const note of preview.lossinessNotes) {
4271
- console.log(chalk18.yellow(` - ${note}`));
4929
+ console.log(chalk16.yellow(` - ${note}`));
4272
4930
  }
4273
4931
  }
4274
4932
  return;
@@ -4278,7 +4936,7 @@ function registerNotebookCommands(program) {
4278
4936
  format(result, { format: outputFormat });
4279
4937
  return;
4280
4938
  }
4281
- console.log(chalk18.green(`Imported ${result.entityCount} entities, ${result.linkCount} links.`));
4939
+ success(`Imported ${result.entityCount} entities, ${result.linkCount} links.`);
4282
4940
  console.log(`Notebook id(s): ${result.rootEntityIds.join(", ")}`);
4283
4941
  } catch (error) {
4284
4942
  handleError(error);
@@ -4315,13 +4973,56 @@ function registerNotebookCommands(program) {
4315
4973
  }
4316
4974
 
4317
4975
  // src/commands/function/index.ts
4318
- import chalk19 from "chalk";
4976
+ import chalk17 from "chalk";
4319
4977
  import * as fs6 from "fs";
4320
4978
  import * as os2 from "os";
4321
4979
  import * as path5 from "path";
4322
4980
  import { spawn } from "child_process";
4323
4981
  import { randomUUID } from "crypto";
4324
4982
 
4983
+ // src/util/time-uuid.ts
4984
+ import { randomBytes } from "crypto";
4985
+ var GREGORIAN_OFFSET = 122192928000000000n;
4986
+ var INTERVALS_PER_MILLI = 10000n;
4987
+ function createTimeUuidGenerator() {
4988
+ const node = randomBytes(6);
4989
+ node[0] |= 1;
4990
+ const nodeHex = node.toString("hex");
4991
+ let clockSequence = randomBytes(2).readUInt16BE(0) & 16383;
4992
+ let lastTimestamp = 0n;
4993
+ let intervalsWithinMilli = 0n;
4994
+ return function generate(now = Date.now()) {
4995
+ let timestamp = BigInt(now) * 10000n + GREGORIAN_OFFSET;
4996
+ if (timestamp !== lastTimestamp) {
4997
+ lastTimestamp = timestamp;
4998
+ intervalsWithinMilli = 0n;
4999
+ } else {
5000
+ intervalsWithinMilli += 1n;
5001
+ if (intervalsWithinMilli >= INTERVALS_PER_MILLI) {
5002
+ clockSequence = clockSequence + 1 & 16383;
5003
+ intervalsWithinMilli = 0n;
5004
+ }
5005
+ timestamp = lastTimestamp + intervalsWithinMilli;
5006
+ }
5007
+ const timeLow = Number(timestamp & 0xffffffffn);
5008
+ const timeMid = Number(timestamp >> 32n & 0xffffn);
5009
+ const timeHiAndVersion = Number(timestamp >> 48n & 0x0fffn) | 4096;
5010
+ const clockSeqHi = clockSequence >> 8 & 63 | 128;
5011
+ const clockSeqLow = clockSequence & 255;
5012
+ return [
5013
+ hex(timeLow, 8),
5014
+ hex(timeMid, 4),
5015
+ hex(timeHiAndVersion, 4),
5016
+ hex(clockSeqHi, 2) + hex(clockSeqLow, 2),
5017
+ nodeHex
5018
+ ].join("-");
5019
+ };
5020
+ }
5021
+ var timeUuid = createTimeUuidGenerator();
5022
+ function hex(value, width) {
5023
+ return value.toString(16).padStart(width, "0");
5024
+ }
5025
+
4325
5026
  // src/util/function-content.ts
4326
5027
  function decodeFunctionSource(entity) {
4327
5028
  if (!entity.content) return "";
@@ -4338,8 +5039,12 @@ function encodeFunctionSource(sourceCode) {
4338
5039
  }
4339
5040
  function buildFunctionEntity(args) {
4340
5041
  const now = Date.now();
4341
- const attributes = { language: args.language };
4342
- const attributeTypes = { language: "text" };
5042
+ const attributes = {};
5043
+ const attributeTypes = {};
5044
+ if (args.language !== null && args.language !== void 0) {
5045
+ attributes.language = args.language;
5046
+ attributeTypes.language = "text";
5047
+ }
4343
5048
  if (args.name !== null && args.name !== void 0) {
4344
5049
  attributes.name = args.name;
4345
5050
  attributeTypes.name = "text";
@@ -4383,7 +5088,7 @@ function getOverrides8(cmd) {
4383
5088
  function createTimeUuid() {
4384
5089
  const now = /* @__PURE__ */ new Date();
4385
5090
  return {
4386
- evaluationId: randomUUID(),
5091
+ evaluationId: timeUuid(now.getTime()),
4387
5092
  year: now.getUTCFullYear(),
4388
5093
  month: now.getUTCMonth() + 1,
4389
5094
  day: now.getUTCDate(),
@@ -4391,7 +5096,14 @@ function createTimeUuid() {
4391
5096
  };
4392
5097
  }
4393
5098
  function registerFunctionCommands(program) {
4394
- const fn = program.command("function").description("Execute and manage functions");
5099
+ const fn = program.command("function").description("Execute and manage functions").addHelpText("after", `
5100
+ Examples:
5101
+ $ diafunc function call <ref> --args '{"x": 1}' run one
5102
+ $ diafunc function edit <ref> edit the source in $EDITOR
5103
+ $ diafunc function logs <ref> what the last run printed
5104
+ $ diafunc function languages what it can be written in
5105
+ `);
5106
+ ;
4395
5107
  fn.command("call").description("Execute a function").argument("<ref>", "Function entity reference").option("--async", "Execute asynchronously").option("--args <json>", "Arguments as JSON object").option("--target <ref>", "Target entity reference").action(async (ref, options, cmd) => {
4396
5108
  try {
4397
5109
  const outputFormat = getOutputFormat9(cmd);
@@ -4437,7 +5149,7 @@ function registerFunctionCommands(program) {
4437
5149
  }, isAsync);
4438
5150
  if (isAsync) {
4439
5151
  if (outputFormat === "human") {
4440
- console.log(chalk19.green("Function launched."));
5152
+ success("Function launched.");
4441
5153
  console.log(` Evaluation ID: ${result.evaluationId}`);
4442
5154
  } else {
4443
5155
  format({ evaluationId: result.evaluationId }, { format: outputFormat });
@@ -4445,14 +5157,14 @@ function registerFunctionCommands(program) {
4445
5157
  } else {
4446
5158
  if (outputFormat === "human") {
4447
5159
  if (result.successful) {
4448
- console.log(chalk19.green("Function completed successfully."));
5160
+ success("Function completed successfully.");
4449
5161
  if (result.result) {
4450
5162
  console.log(` Result: ${result.result}`);
4451
5163
  }
4452
5164
  const duration = result.completed - result.started;
4453
5165
  console.log(` Duration: ${duration}ms`);
4454
5166
  } else {
4455
- console.log(chalk19.red("Function failed."));
5167
+ console.log(chalk17.red("Function failed."));
4456
5168
  console.log(` Error: ${result.error}`);
4457
5169
  if (result.lineNumber > 0) {
4458
5170
  console.log(` Line: ${result.lineNumber}, Column: ${result.columnNumber}`);
@@ -4460,7 +5172,7 @@ function registerFunctionCommands(program) {
4460
5172
  }
4461
5173
  if (result.outputs?.length) {
4462
5174
  console.log();
4463
- console.log(chalk19.bold("Outputs:"));
5175
+ console.log(chalk17.bold("Outputs:"));
4464
5176
  for (const out of result.outputs) {
4465
5177
  console.log(` [${out.type}] ${out.output}`);
4466
5178
  }
@@ -4501,7 +5213,14 @@ function registerFunctionCommands(program) {
4501
5213
  }));
4502
5214
  format(summary, {
4503
5215
  format: outputFormat,
4504
- columns: ["evaluationId", "active", "successful", "language", "started", "duration"]
5216
+ columns: [
5217
+ { key: "evaluationId", kind: "id" },
5218
+ { key: "active", kind: "boolean" },
5219
+ { key: "successful", kind: "boolean" },
5220
+ { key: "language" },
5221
+ { key: "started", kind: "date" },
5222
+ { key: "duration", kind: "number" }
5223
+ ]
4505
5224
  });
4506
5225
  } catch (error) {
4507
5226
  handleError(error);
@@ -4514,11 +5233,11 @@ function registerFunctionCommands(program) {
4514
5233
  const outputs = await api.evaluation.getOutputs(projectId, evaluationId);
4515
5234
  if (outputFormat === "human") {
4516
5235
  if (outputs.length === 0) {
4517
- console.log(chalk19.dim("No outputs."));
5236
+ empty("outputs");
4518
5237
  }
4519
5238
  for (const out of outputs) {
4520
5239
  const time = new Date(out.timestamp).toISOString();
4521
- console.log(`${chalk19.dim(time)} [${out.type}] ${out.output}`);
5240
+ console.log(`${chalk17.dim(time)} [${out.type}] ${out.output}`);
4522
5241
  }
4523
5242
  } else {
4524
5243
  format(outputs, { format: outputFormat });
@@ -4568,17 +5287,21 @@ function registerFunctionCommands(program) {
4568
5287
  hour,
4569
5288
  evaluationId
4570
5289
  );
4571
- console.log(chalk19.green(`Evaluation ${evaluationId} stopped.`));
5290
+ success(`Evaluation ${evaluationId} stopped.`);
4572
5291
  } catch (error) {
4573
5292
  handleError(error);
4574
5293
  }
4575
5294
  });
4576
- fn.command("engines").description("List available engines").action(async (_options, cmd) => {
5295
+ fn.command("languages").description("List the languages a function can be written in").action(async (_options, cmd) => {
4577
5296
  try {
4578
5297
  const outputFormat = getOutputFormat9(cmd);
4579
- const api = createApiClient();
4580
- const engines = await api.evaluation.getEngines();
4581
- format(engines, { format: outputFormat });
5298
+ format(
5299
+ FUNCTION_LANGUAGES.map((language) => ({
5300
+ language,
5301
+ default: language === DEFAULT_FUNCTION_LANGUAGE
5302
+ })),
5303
+ { format: outputFormat, columns: [{ key: "language" }, { key: "default", kind: "boolean" }] }
5304
+ );
4582
5305
  } catch (error) {
4583
5306
  handleError(error);
4584
5307
  }
@@ -4600,7 +5323,7 @@ function registerFunctionCommands(program) {
4600
5323
  handleError(error);
4601
5324
  }
4602
5325
  });
4603
- fn.command("create").description("Create a new function entity").argument("<ref>", "Function entity reference").option("--language <lang>", "Function language (Java, JavaScript, Kotlin, Python, Scala)", "Java").option("--source <file>", "Initial source code file").option("--name <name>", "Display name (defaults to entityId)").action(async (ref, options, cmd) => {
5326
+ fn.command("create").description("Create a new function entity").argument("<ref>", "Function entity reference").option("--language <lang>", "Function language (Java, Kotlin, Python, JavaScript, Scala); defaults to the project's language").option("--source <file>", "Initial source code file").option("--name <name>", "Display name (defaults to entityId)").action(async (ref, options, cmd) => {
4604
5327
  try {
4605
5328
  const overrides = getOverrides8(cmd);
4606
5329
  const resolved = parseEntityReference(ref, overrides);
@@ -4612,11 +5335,12 @@ function registerFunctionCommands(program) {
4612
5335
  entityId: resolved.entityId,
4613
5336
  entityBranch: resolved.entityBranch,
4614
5337
  name: options.name ?? resolved.entityId,
4615
- language: options.language,
5338
+ language: options.language ?? null,
4616
5339
  sourceCode
4617
5340
  });
4618
5341
  await api.storage.saveEntities([entity]);
4619
- console.log(chalk19.green(`Function "${resolved.entityId}" created (${options.language}).`));
5342
+ const effective = options.language ? options.language : `${await resolveLanguage(api, resolved.projectId)}, the project's language`;
5343
+ success(`Function "${resolved.entityId}" created (${effective}).`);
4620
5344
  } catch (error) {
4621
5345
  handleError(error);
4622
5346
  }
@@ -4631,7 +5355,7 @@ function registerFunctionCommands(program) {
4631
5355
  const sourceCode = decodeFunctionSource(entity);
4632
5356
  if (options.out) {
4633
5357
  fs6.writeFileSync(options.out, sourceCode);
4634
- console.log(chalk19.green(`Source written to ${options.out}`));
5358
+ success(`Source written to ${options.out}`);
4635
5359
  } else {
4636
5360
  process.stdout.write(sourceCode);
4637
5361
  if (!sourceCode.endsWith("\n")) process.stdout.write("\n");
@@ -4655,7 +5379,7 @@ function registerFunctionCommands(program) {
4655
5379
  process.stdin.on("error", reject);
4656
5380
  });
4657
5381
  await api.storage.saveEntityContentBase64(resolved, encodeFunctionSource(sourceCode));
4658
- console.log(chalk19.green(`Source updated for "${resolved.entityId}".`));
5382
+ success(`Source updated for "${resolved.entityId}".`);
4659
5383
  } catch (error) {
4660
5384
  handleError(error);
4661
5385
  }
@@ -4680,11 +5404,11 @@ function registerFunctionCommands(program) {
4680
5404
  const newSource = fs6.readFileSync(tmpFile, "utf-8");
4681
5405
  fs6.unlinkSync(tmpFile);
4682
5406
  if (newSource === currentSource) {
4683
- console.log(chalk19.dim("No changes."));
5407
+ empty("changes");
4684
5408
  return;
4685
5409
  }
4686
5410
  await api.storage.saveEntityContentBase64(resolved, encodeFunctionSource(newSource));
4687
- console.log(chalk19.green(`Source updated for "${resolved.entityId}".`));
5411
+ success(`Source updated for "${resolved.entityId}".`);
4688
5412
  } catch (error) {
4689
5413
  handleError(error);
4690
5414
  }
@@ -4701,7 +5425,6 @@ function extensionFor(language) {
4701
5425
  }
4702
5426
 
4703
5427
  // src/commands/trigger/index.ts
4704
- import chalk20 from "chalk";
4705
5428
  function getOutputFormat10(cmd) {
4706
5429
  const config = loadConfig();
4707
5430
  const globalOpts = cmd.optsWithGlobals();
@@ -4712,7 +5435,13 @@ function getOverrides9(cmd) {
4712
5435
  return { project: opts.project, branch: opts.branch };
4713
5436
  }
4714
5437
  function registerTriggerCommands(program) {
4715
- const trigger = program.command("trigger").description("Manage function triggers");
5438
+ const trigger = program.command("trigger").description("Manage function triggers").addHelpText("after", `
5439
+ Examples:
5440
+ $ diafunc trigger list <ref>
5441
+ $ diafunc trigger create <ref> --expression '0 0 * * *'
5442
+ $ diafunc trigger delete <ref> <triggerId>
5443
+ `);
5444
+ ;
4716
5445
  trigger.command("list").description("List triggers for a function").argument("<ref>", "Function entity reference").action(async (ref, _options, cmd) => {
4717
5446
  try {
4718
5447
  const outputFormat = getOutputFormat10(cmd);
@@ -4771,7 +5500,7 @@ function registerTriggerCommands(program) {
4771
5500
  resolved.entityBranch,
4772
5501
  triggerId
4773
5502
  );
4774
- console.log(chalk20.green(`Trigger "${triggerId}" deleted.`));
5503
+ success(`Trigger "${triggerId}" deleted.`);
4775
5504
  } catch (error) {
4776
5505
  handleError(error);
4777
5506
  }
@@ -4819,7 +5548,7 @@ function registerTriggerCommands(program) {
4819
5548
  scheduler: null,
4820
5549
  heartbeat: null
4821
5550
  });
4822
- console.log(chalk20.green("Trigger saved."));
5551
+ success("Trigger saved.");
4823
5552
  } catch (error) {
4824
5553
  handleError(error);
4825
5554
  }
@@ -4827,8 +5556,6 @@ function registerTriggerCommands(program) {
4827
5556
  }
4828
5557
 
4829
5558
  // src/commands/schedule/index.ts
4830
- import chalk21 from "chalk";
4831
- import { randomUUID as randomUUID2 } from "crypto";
4832
5559
  function getOutputFormat11(cmd) {
4833
5560
  const config = loadConfig();
4834
5561
  const globalOpts = cmd.optsWithGlobals();
@@ -4865,7 +5592,7 @@ function registerScheduleCommands(program) {
4865
5592
  targetEntityBranch = targetRef.entityBranch;
4866
5593
  }
4867
5594
  const result = await api.scheduler.scheduleCall({
4868
- evaluationId: randomUUID2(),
5595
+ evaluationId: timeUuid(),
4869
5596
  projectId: resolved.projectId,
4870
5597
  projectBranch: resolved.projectBranch,
4871
5598
  functionId: resolved.entityId,
@@ -4879,7 +5606,7 @@ function registerScheduleCommands(program) {
4879
5606
  removeFunction: false
4880
5607
  });
4881
5608
  if (outputFormat === "human") {
4882
- console.log(chalk21.green("Function scheduled."));
5609
+ success("Function scheduled.");
4883
5610
  } else {
4884
5611
  format(result, { format: outputFormat });
4885
5612
  }
@@ -4904,7 +5631,7 @@ function registerScheduleCommands(program) {
4904
5631
  hour,
4905
5632
  evaluationId
4906
5633
  );
4907
- console.log(chalk21.green(`Scheduled evaluation ${evaluationId} stopped.`));
5634
+ success(`Scheduled evaluation ${evaluationId} stopped.`);
4908
5635
  } catch (error) {
4909
5636
  handleError(error);
4910
5637
  }
@@ -4941,71 +5668,202 @@ function registerScheduleCommands(program) {
4941
5668
  }
4942
5669
 
4943
5670
  // src/commands/chat/index.ts
4944
- import chalk22 from "chalk";
5671
+ import chalk19 from "chalk";
4945
5672
  import * as fs7 from "fs";
4946
5673
  import * as path6 from "path";
5674
+
5675
+ // src/output/markdown.ts
5676
+ import chalk18 from "chalk";
5677
+ var CODE_OPEN = "\0c";
5678
+ var CODE_CLOSE = "\0";
5679
+ var MarkdownRenderer = class {
5680
+ constructor(width = terminalWidth()) {
5681
+ this.width = width;
5682
+ }
5683
+ width;
5684
+ inFence = false;
5685
+ pending = "";
5686
+ /** Renders whatever complete lines `chunk` completes. The remainder is held for the next call. */
5687
+ push(chunk) {
5688
+ if (!isInteractive()) return this.pushPlain(chunk);
5689
+ this.pending += chunk;
5690
+ const parts = this.pending.split("\n");
5691
+ this.pending = parts.pop() ?? "";
5692
+ return parts.flatMap((line) => this.line(line));
5693
+ }
5694
+ /** Renders the held remainder, if any. Call once the stream has ended. */
5695
+ flush() {
5696
+ if (this.pending === "") return [];
5697
+ const rest = this.pending;
5698
+ this.pending = "";
5699
+ return isInteractive() ? this.line(rest) : [rest];
5700
+ }
5701
+ pushPlain(chunk) {
5702
+ this.pending += chunk;
5703
+ const parts = this.pending.split("\n");
5704
+ this.pending = parts.pop() ?? "";
5705
+ return parts;
5706
+ }
5707
+ line(line) {
5708
+ const fence = line.match(/^\s*```(\w*)\s*$/);
5709
+ if (fence) {
5710
+ const opening = !this.inFence;
5711
+ this.inFence = !this.inFence;
5712
+ return opening && fence[1] ? [chalk18.dim(` ${fence[1]}`)] : [];
5713
+ }
5714
+ if (this.inFence) {
5715
+ return [chalk18.cyan(` ${line}`)];
5716
+ }
5717
+ const heading = line.match(/^(#{1,6})\s+(.*)$/);
5718
+ if (heading) {
5719
+ const text = inline(heading[2]);
5720
+ return ["", heading[1].length <= 2 ? chalk18.bold.underline(text) : chalk18.bold(text)];
5721
+ }
5722
+ if (/^\s*([-*_])\1{2,}\s*$/.test(line)) {
5723
+ return [chalk18.dim("\u2500".repeat(Math.min(this.width, 60)))];
5724
+ }
5725
+ const quote = line.match(/^\s*>\s?(.*)$/);
5726
+ if (quote) return [chalk18.dim(` \u2502 ${inline(quote[1])}`)];
5727
+ const bullet = line.match(/^(\s*)[-*+]\s+(.*)$/);
5728
+ if (bullet) {
5729
+ return wrapWithIndent(
5730
+ `${bullet[1]}${chalk18.cyan("\u2022")} ${inline(bullet[2])}`,
5731
+ bullet[1].length + 2,
5732
+ this.width
5733
+ );
5734
+ }
5735
+ const numbered = line.match(/^(\s*)(\d+)\.\s+(.*)$/);
5736
+ if (numbered) {
5737
+ return wrapWithIndent(
5738
+ `${numbered[1]}${chalk18.cyan(`${numbered[2]}.`)} ${inline(numbered[3])}`,
5739
+ numbered[1].length + numbered[2].length + 2,
5740
+ this.width
5741
+ );
5742
+ }
5743
+ if (line.trim() === "") return [""];
5744
+ return wrapWithIndent(inline(line), 0, this.width);
5745
+ }
5746
+ };
5747
+ function renderMarkdown(source, width = terminalWidth()) {
5748
+ if (!isInteractive()) return source;
5749
+ const renderer = new MarkdownRenderer(width);
5750
+ return [...renderer.push(source), ...renderer.flush()].join("\n");
5751
+ }
5752
+ function wrapWithIndent(text, indent, width) {
5753
+ return wrap(text, width).map((l, i) => i === 0 ? l : " ".repeat(indent) + l);
5754
+ }
5755
+ function inline(text) {
5756
+ const codeSpans = [];
5757
+ let working = text.replace(/`([^`]+)`/g, (_m, code) => {
5758
+ codeSpans.push(code);
5759
+ return `${CODE_OPEN}${codeSpans.length - 1}${CODE_CLOSE}`;
5760
+ });
5761
+ working = working.replace(/\*\*([^*]+)\*\*/g, (_m, t) => chalk18.bold(t)).replace(/__([^_]+)__/g, (_m, t) => chalk18.bold(t)).replace(/(^|[^*])\*([^*\n]+)\*/g, (_m, lead, t) => lead + chalk18.italic(t)).replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, label, url) => `${chalk18.underline(label)} ${chalk18.dim(`(${url})`)}`);
5762
+ return working.replace(
5763
+ new RegExp(`${CODE_OPEN}(\\d+)${CODE_CLOSE}`, "g"),
5764
+ (_m, i) => chalk18.yellow(codeSpans[Number(i)])
5765
+ );
5766
+ }
5767
+
5768
+ // src/commands/chat/index.ts
4947
5769
  function getOutputFormat12(cmd) {
4948
5770
  const config = loadConfig();
4949
5771
  const globalOpts = cmd.optsWithGlobals();
4950
5772
  return globalOpts.output ?? config.defaults.output ?? "human";
4951
5773
  }
4952
- async function streamOneTurn(message, sessionId, projectId, branch) {
5774
+ async function streamOneTurn(message, sessionId, projectId, branch, signal) {
4953
5775
  const api = createApiClient();
4954
- const response = await api.language.chatStream({
4955
- message,
4956
- sessionId,
4957
- projectId,
4958
- projectBranch: projectId ? branch : void 0
4959
- });
5776
+ const status = new Status();
5777
+ status.set([` ${chalk19.magenta(SPINNER)} ${chalk19.dim("thinking")}`]);
5778
+ status.start();
5779
+ let response;
5780
+ try {
5781
+ response = await api.language.chatStream({
5782
+ message,
5783
+ sessionId,
5784
+ projectId,
5785
+ projectBranch: projectId ? branch : void 0
5786
+ });
5787
+ } catch (error) {
5788
+ status.stop();
5789
+ throw error;
5790
+ }
4960
5791
  const reader = response.body.getReader();
4961
5792
  const decoder = new TextDecoder();
5793
+ const markdown = new MarkdownRenderer();
4962
5794
  let buffer = "";
4963
5795
  let finalSession = sessionId ?? "";
4964
5796
  let input = 0;
4965
5797
  let output = 0;
4966
- while (true) {
4967
- const { done, value } = await reader.read();
4968
- if (done) break;
4969
- buffer += decoder.decode(value, { stream: true });
4970
- const lines = buffer.split("\n");
4971
- buffer = lines.pop() ?? "";
4972
- for (const line of lines) {
4973
- if (!line.startsWith("data:")) continue;
4974
- const data = line.slice(5).trim();
4975
- if (!data) continue;
4976
- try {
4977
- const event = JSON.parse(data);
4978
- if (event.type === "token" && event.content) {
4979
- process.stdout.write(event.content);
4980
- } else if (event.type === "done") {
4981
- finalSession = event.sessionId ?? finalSession;
4982
- input = event.inputTokens;
4983
- output = event.outputTokens;
4984
- } else if (event.type === "error") {
4985
- console.error(chalk22.red(`
4986
- Error: ${event.content}`));
5798
+ let started = false;
5799
+ const emit = (lines) => {
5800
+ if (lines.length === 0) return;
5801
+ if (!started) {
5802
+ started = true;
5803
+ status.stop();
5804
+ }
5805
+ for (const line of lines) console.log(line);
5806
+ };
5807
+ const onAbort = () => {
5808
+ void reader.cancel();
5809
+ };
5810
+ signal?.addEventListener("abort", onAbort, { once: true });
5811
+ try {
5812
+ for (; ; ) {
5813
+ const { done, value } = await reader.read();
5814
+ if (done) break;
5815
+ buffer += decoder.decode(value, { stream: true });
5816
+ const lines = buffer.split("\n");
5817
+ buffer = lines.pop() ?? "";
5818
+ for (const line of lines) {
5819
+ if (!line.startsWith("data:")) continue;
5820
+ const data = line.slice(5).trim();
5821
+ if (!data) continue;
5822
+ try {
5823
+ const event = JSON.parse(data);
5824
+ if (event.type === "token" && event.content) {
5825
+ emit(markdown.push(event.content));
5826
+ } else if (event.type === "done") {
5827
+ finalSession = event.sessionId ?? finalSession;
5828
+ input = event.inputTokens;
5829
+ output = event.outputTokens;
5830
+ } else if (event.type === "error") {
5831
+ emit(markdown.flush());
5832
+ failure(event.content ?? "The assistant reported an error.");
5833
+ }
5834
+ } catch {
4987
5835
  }
4988
- } catch {
4989
5836
  }
4990
5837
  }
5838
+ emit(markdown.flush());
5839
+ } finally {
5840
+ signal?.removeEventListener("abort", onAbort);
5841
+ status.stop();
4991
5842
  }
4992
5843
  return { sessionId: finalSession, input, output };
4993
5844
  }
5845
+ var HELP = [
5846
+ " /new start a fresh session",
5847
+ " /session [id] show the current session, or switch to another",
5848
+ " /clear clear the screen",
5849
+ " /help this list",
5850
+ " /quit leave (Ctrl-D also works)"
5851
+ ];
4994
5852
  async function runChatRepl(options) {
4995
5853
  const { input: promptInput } = await import("@inquirer/prompts");
4996
- const { getUpdateNotice } = await import("./update-check-L55QNPYQ.js");
5854
+ const { getUpdateNotice } = await import("./update-check-4RHYIJHZ.js");
4997
5855
  let sessionId = options.session;
4998
- console.log(chalk22.bold("Diafunc chat") + chalk22.dim(" \xB7 /help for commands, /quit to exit"));
4999
- if (sessionId) {
5000
- console.log(chalk22.dim(`Continuing session ${sessionId}`));
5001
- }
5856
+ let lastReportedSession;
5857
+ console.log(chalk19.bold("Diafunc chat") + chalk19.dim(" \xB7 /help for commands, /quit to exit"));
5858
+ if (options.project) console.log(chalk19.dim(`Project context: ${options.project}`));
5859
+ if (sessionId) console.log(chalk19.dim(`Continuing session ${sessionId}`));
5002
5860
  const notice = await getUpdateNotice();
5003
- if (notice) console.log(chalk22.dim(notice));
5861
+ if (notice) console.log(chalk19.dim(notice));
5004
5862
  console.log();
5005
5863
  for (; ; ) {
5006
5864
  let line;
5007
5865
  try {
5008
- line = await promptInput({ message: chalk22.cyan.bold("you >") });
5866
+ line = await promptInput({ message: chalk19.cyan.bold("you >") });
5009
5867
  } catch {
5010
5868
  console.log();
5011
5869
  return;
@@ -5022,43 +5880,70 @@ async function runChatRepl(options) {
5022
5880
  return;
5023
5881
  case "new":
5024
5882
  sessionId = void 0;
5025
- console.log(chalk22.dim("Started a new session."));
5883
+ lastReportedSession = void 0;
5884
+ console.log(chalk19.dim("Started a new session."));
5885
+ continue;
5886
+ case "clear":
5887
+ console.clear();
5026
5888
  continue;
5027
5889
  case "session":
5028
5890
  if (!arg) {
5029
- console.log(chalk22.dim(`Current session: ${sessionId ?? "(new)"}`));
5891
+ console.log(chalk19.dim(`Current session: ${sessionId ?? "(new)"}`));
5030
5892
  } else {
5031
5893
  sessionId = arg;
5032
- console.log(chalk22.dim(`Switched to session ${sessionId}`));
5894
+ lastReportedSession = void 0;
5895
+ console.log(chalk19.dim(`Switched to session ${sessionId}`));
5033
5896
  }
5034
5897
  continue;
5035
5898
  case "help":
5036
5899
  case "h":
5037
5900
  case "?":
5038
- console.log(chalk22.dim(" /new start a new session"));
5039
- console.log(chalk22.dim(" /session [id] switch to a session (no id = show current)"));
5040
- console.log(chalk22.dim(" /quit exit the REPL"));
5901
+ for (const l of HELP) console.log(chalk19.dim(l));
5041
5902
  continue;
5042
5903
  default:
5043
- console.log(chalk22.dim(`Unknown command: /${cmd}. Try /help.`));
5904
+ console.log(chalk19.dim(`Unknown command: /${cmd}. Try /help.`));
5044
5905
  continue;
5045
5906
  }
5046
5907
  }
5047
- process.stdout.write(chalk22.magenta.bold("diafunc > "));
5908
+ const controller = new AbortController();
5909
+ const onSigint = () => controller.abort();
5910
+ process.on("SIGINT", onSigint);
5911
+ console.log();
5048
5912
  try {
5049
- const result = await streamOneTurn(trimmed, sessionId, options.project, options.branch);
5913
+ const result = await streamOneTurn(trimmed, sessionId, options.project, options.branch, controller.signal);
5050
5914
  sessionId = result.sessionId || sessionId;
5051
5915
  console.log();
5052
- console.log(chalk22.dim(`[session ${sessionId} \xB7 ${result.input} in / ${result.output} out]`));
5916
+ if (controller.signal.aborted) {
5917
+ console.log(chalk19.dim(" (cancelled)"));
5918
+ } else {
5919
+ const parts = [`${result.input} in / ${result.output} out`];
5920
+ if (sessionId && sessionId !== lastReportedSession) {
5921
+ parts.push(`session ${sessionId}`);
5922
+ lastReportedSession = sessionId;
5923
+ }
5924
+ console.log(chalk19.dim(` ${parts.join(" \xB7 ")}`));
5925
+ }
5053
5926
  console.log();
5054
5927
  } catch (error) {
5055
- console.error(chalk22.red(`
5056
- Request failed: ${error.message}`));
5928
+ if (controller.signal.aborted) {
5929
+ console.log(chalk19.dim(" (cancelled)"));
5930
+ console.log();
5931
+ } else {
5932
+ failure(`Request failed: ${error.message}`);
5933
+ hint(`Check 'diafunc status summary' if this keeps happening.`);
5934
+ }
5935
+ } finally {
5936
+ process.off("SIGINT", onSigint);
5057
5937
  }
5058
5938
  }
5059
5939
  }
5060
5940
  function registerChatCommands(program) {
5061
- const chat = program.command("chat").description("AI chat");
5941
+ const chat = program.command("chat").description("Ask the Diafunc assistant").addHelpText("after", `
5942
+ Examples:
5943
+ $ diafunc chat interactive session
5944
+ $ diafunc chat --project <id> with a project in context
5945
+ $ diafunc chat send "how do I add a table?" one question, one answer
5946
+ `);
5062
5947
  chat.option("--session <id>", "Continue an existing session").option("--project <id>", "Project context").option("--branch <branch>", "Project branch", "main").action(async (options) => {
5063
5948
  try {
5064
5949
  await runChatRepl(options);
@@ -5077,9 +5962,11 @@ function registerChatCommands(program) {
5077
5962
  projectBranch: options.branch
5078
5963
  });
5079
5964
  if (outputFormat === "human") {
5080
- console.log(response.content);
5965
+ console.log(renderMarkdown(response.content));
5081
5966
  console.log();
5082
- console.log(chalk22.dim(`Session: ${response.sessionId} | Tokens: ${response.inputTokens} in, ${response.outputTokens} out`));
5967
+ console.log(chalk19.dim(
5968
+ ` session ${response.sessionId} \xB7 ${response.inputTokens} in / ${response.outputTokens} out`
5969
+ ));
5083
5970
  } else {
5084
5971
  format(response, { format: outputFormat });
5085
5972
  }
@@ -5144,10 +6031,9 @@ function registerChatCommands(program) {
5144
6031
  sessionId = event.sessionId ?? "";
5145
6032
  console.log();
5146
6033
  console.log();
5147
- console.log(chalk22.dim(`Session: ${sessionId} | Tokens: ${event.inputTokens} in, ${event.outputTokens} out`));
6034
+ console.log(chalk19.dim(`Session: ${sessionId} | Tokens: ${event.inputTokens} in, ${event.outputTokens} out`));
5148
6035
  } else if (event.type === "error") {
5149
- console.error(chalk22.red(`
5150
- Error: ${event.content}`));
6036
+ failure(`Error: ${event.content}`);
5151
6037
  }
5152
6038
  } catch {
5153
6039
  }
@@ -5162,7 +6048,7 @@ Error: ${event.content}`));
5162
6048
  chat.command("upload").description("Upload a file for chat context").argument("<file>", "File to upload").action(async (file) => {
5163
6049
  try {
5164
6050
  if (!fs7.existsSync(file)) {
5165
- console.error(chalk22.red(`File not found: ${file}`));
6051
+ failure(`File not found: ${file}`);
5166
6052
  process.exit(1);
5167
6053
  }
5168
6054
  const api = createApiClient();
@@ -5171,7 +6057,7 @@ Error: ${event.content}`));
5171
6057
  const formData = new FormData();
5172
6058
  formData.append("file", blob, path6.basename(file));
5173
6059
  const result = await api.language.upload(formData);
5174
- console.log(chalk22.green(`File uploaded: ${result}`));
6060
+ success(`File uploaded: ${result}`);
5175
6061
  } catch (error) {
5176
6062
  handleError(error);
5177
6063
  }
@@ -5194,7 +6080,7 @@ Error: ${event.content}`));
5194
6080
  try {
5195
6081
  const api = createApiClient();
5196
6082
  await api.language.deleteSession(sessionId);
5197
- console.log(chalk22.green(`Session "${sessionId}" deleted.`));
6083
+ success(`Session "${sessionId}" deleted.`);
5198
6084
  } catch (error) {
5199
6085
  handleError(error);
5200
6086
  }
@@ -5203,18 +6089,18 @@ Error: ${event.content}`));
5203
6089
  try {
5204
6090
  const outputFormat = getOutputFormat12(cmd);
5205
6091
  const api = createApiClient();
5206
- const detail = await api.language.getSession(sessionId);
6092
+ const detail2 = await api.language.getSession(sessionId);
5207
6093
  if (outputFormat === "human") {
5208
- console.log(chalk22.bold(detail.title) + chalk22.dim(` (${detail.sessionId})`));
6094
+ console.log(chalk19.bold(detail2.title) + chalk19.dim(` (${detail2.sessionId})`));
5209
6095
  console.log();
5210
- for (const msg of detail.messages) {
5211
- const role = msg.role === "user" ? chalk22.cyan.bold("You") : chalk22.magenta.bold("Diafunc");
5212
- console.log(`${role} ${chalk22.dim(msg.created)}`);
6096
+ for (const msg of detail2.messages) {
6097
+ const role = msg.role === "user" ? chalk19.cyan.bold("You") : chalk19.magenta.bold("Diafunc");
6098
+ console.log(`${role} ${chalk19.dim(msg.created)}`);
5213
6099
  console.log(msg.content);
5214
6100
  console.log();
5215
6101
  }
5216
6102
  } else {
5217
- format(detail, { format: outputFormat });
6103
+ format(detail2, { format: outputFormat });
5218
6104
  }
5219
6105
  } catch (error) {
5220
6106
  handleError(error);
@@ -5224,7 +6110,7 @@ Error: ${event.content}`));
5224
6110
  try {
5225
6111
  const api = createApiClient();
5226
6112
  await api.language.renameSession(sessionId, title);
5227
- console.log(chalk22.green(`Session "${sessionId}" renamed to "${title}".`));
6113
+ success(`Session "${sessionId}" renamed to "${title}".`);
5228
6114
  } catch (error) {
5229
6115
  handleError(error);
5230
6116
  }
@@ -5242,47 +6128,108 @@ Error: ${event.content}`));
5242
6128
  }
5243
6129
 
5244
6130
  // src/commands/search/index.ts
6131
+ import chalk20 from "chalk";
5245
6132
  function getOutputFormat13(cmd) {
5246
6133
  const config = loadConfig();
5247
6134
  const globalOpts = cmd.optsWithGlobals();
5248
6135
  return globalOpts.output ?? config.defaults.output ?? "human";
5249
6136
  }
5250
6137
  function registerSearchCommands(program) {
5251
- program.command("search").description("Search entities across projects").argument("<query>", "Search query").option("--project <id>", "Limit search to a project").option("--branch <branch>", "Project branch", "main").action(async (query, options, cmd) => {
6138
+ program.command("search").description("Search across every project you can see").argument("<query>", "Search query").option("--project <id>", "Limit the search to one project").option("--branch <branch>", "Project branch, when --project is given").option("--type <contentType>", "Limit to one content type, e.g. project, notebook, table, function").option("--limit <n>", "Maximum results", "20").addHelpText("after", `
6139
+ Examples:
6140
+ $ diafunc search "housing" everything matching, across projects
6141
+ $ diafunc search "housing" --type project only projects
6142
+ $ diafunc search "medv" --project <id> only inside one project
6143
+ $ diafunc search "housing" --output json for scripting
6144
+ `).action(async (query, options, cmd) => {
5252
6145
  try {
5253
6146
  const outputFormat = getOutputFormat13(cmd);
6147
+ const overrides = cmd.optsWithGlobals();
6148
+ const config = loadConfig();
5254
6149
  const api = createApiClient();
5255
- if (options.project) {
5256
- const results = await api.storage.searchProject(
5257
- options.project,
5258
- options.branch,
5259
- { query }
5260
- );
5261
- format(results, { format: outputFormat });
6150
+ const projectId = options.project ?? overrides.project ?? config.defaults.project ?? null;
6151
+ const limit = Number.parseInt(options.limit, 10);
6152
+ const page = await api.index.searchPage({
6153
+ query,
6154
+ limit: Number.isFinite(limit) && limit > 0 ? limit : 20,
6155
+ contentType: options.type ?? null,
6156
+ projectId,
6157
+ projectBranch: projectId ? options.branch ?? overrides.branch ?? config.defaults.branch ?? "main" : null
6158
+ });
6159
+ const items = dedupe(page.items);
6160
+ if (items.length === 0) {
6161
+ empty("matches", { format: outputFormat });
6162
+ return;
6163
+ }
6164
+ if (outputFormat === "json") {
6165
+ format({ ...page, items }, { format: outputFormat });
6166
+ return;
6167
+ }
6168
+ if (isInteractive()) {
6169
+ renderResults(items);
5262
6170
  } else {
5263
- const config = loadConfig();
5264
- const overrides = cmd.optsWithGlobals();
5265
- const projectId = overrides.project ?? config.defaults.project;
5266
- if (projectId) {
5267
- const results = await api.storage.searchProject(
5268
- projectId,
5269
- options.branch,
5270
- { query }
5271
- );
5272
- format(results, { format: outputFormat });
5273
- } else {
5274
- console.log("Specify --project or set defaults.project for project-scoped search.");
5275
- }
6171
+ format(items, {
6172
+ format: outputFormat,
6173
+ columns: [
6174
+ { key: "contentType", header: "type" },
6175
+ { key: "name" },
6176
+ { key: "projectId", kind: "id" },
6177
+ { key: "entityId", kind: "id" }
6178
+ ]
6179
+ });
6180
+ }
6181
+ if (page.nextCursor && isInteractive()) {
6182
+ console.log(chalk20.dim(`More results available \u2014 raise --limit to see them.`));
5276
6183
  }
5277
6184
  } catch (error) {
5278
6185
  handleError(error);
5279
6186
  }
5280
6187
  });
5281
6188
  }
6189
+ function dedupe(items) {
6190
+ const seen = /* @__PURE__ */ new Set();
6191
+ const out = [];
6192
+ for (const item of items) {
6193
+ const key = [item.contentType, item.projectId, item.projectBranch, item.entityId, item.entityBranch].join("|");
6194
+ if (seen.has(key)) continue;
6195
+ seen.add(key);
6196
+ out.push(item);
6197
+ }
6198
+ return out;
6199
+ }
6200
+ function renderResults(items) {
6201
+ for (const item of items) {
6202
+ const name = item.name || "(unnamed)";
6203
+ console.log();
6204
+ console.log(`${chalk20.dim(`[${item.contentType}]`)} ${chalk20.bold(name)}`);
6205
+ const raw = item.snippetField === "name" ? item.description : item.snippet ?? item.description;
6206
+ const line = raw ? collapse(raw) : null;
6207
+ if (line && stripHighlight(line) !== name) console.log(` ${highlight(line)}`);
6208
+ const ref = item.entityId ? `${item.projectId}/${item.projectBranch}/${item.entityId}/${item.entityBranch ?? "main"}` : item.projectId;
6209
+ console.log(` ${chalk20.dim(ref)}`);
6210
+ }
6211
+ console.log();
6212
+ }
6213
+ var HIGHLIGHT_OPEN = /<mark>/g;
6214
+ var HIGHLIGHT_CLOSE = /<\/mark>/g;
6215
+ function highlight(text) {
6216
+ const parts = text.split(HIGHLIGHT_OPEN);
6217
+ return parts.map((part, i) => {
6218
+ if (i === 0) return chalk20.dim(part);
6219
+ const [marked, ...rest] = part.split(HIGHLIGHT_CLOSE);
6220
+ return chalk20.bold.cyan(marked) + chalk20.dim(rest.join(""));
6221
+ }).join("");
6222
+ }
6223
+ function stripHighlight(text) {
6224
+ return text.replace(HIGHLIGHT_OPEN, "").replace(HIGHLIGHT_CLOSE, "");
6225
+ }
6226
+ function collapse(text) {
6227
+ const flat = text.replace(/\s+/g, " ").trim();
6228
+ return flat.length > 160 ? `${flat.slice(0, 159)}\u2026` : flat;
6229
+ }
5282
6230
 
5283
6231
  // src/commands/admin/index.ts
5284
6232
  import { readFile } from "fs/promises";
5285
- import chalk23 from "chalk";
5286
6233
  function getOutputFormat14(cmd) {
5287
6234
  const config = loadConfig();
5288
6235
  const globalOpts = cmd.optsWithGlobals();
@@ -5305,7 +6252,13 @@ function registerAdminCommands(program) {
5305
6252
  }));
5306
6253
  format(summary, {
5307
6254
  format: outputFormat,
5308
- columns: ["id", "name", "email", "role", "remainingCredits"]
6255
+ columns: [
6256
+ { key: "id", kind: "id" },
6257
+ { key: "name" },
6258
+ { key: "email" },
6259
+ { key: "role" },
6260
+ { key: "remainingCredits", header: "credits", kind: "number" }
6261
+ ]
5309
6262
  });
5310
6263
  } catch (error) {
5311
6264
  handleError(error);
@@ -5346,7 +6299,7 @@ function registerAdminCommands(program) {
5346
6299
  try {
5347
6300
  const api = createApiClient();
5348
6301
  await api.admin.mergeSetting({ [key]: value });
5349
- console.log(chalk23.green(`Setting "${key}" updated.`));
6302
+ success(`Setting "${key}" updated.`);
5350
6303
  } catch (error) {
5351
6304
  handleError(error);
5352
6305
  }
@@ -5357,10 +6310,10 @@ function registerAdminCommands(program) {
5357
6310
  const api = createApiClient();
5358
6311
  if (options.longTerm) {
5359
6312
  await api.storage.createLongTermFullBackup();
5360
- console.log(chalk23.green("Full long-term backup initiated."));
6313
+ success("Full long-term backup initiated.");
5361
6314
  } else {
5362
6315
  await api.storage.createShortTermFullBackup();
5363
- console.log(chalk23.green("Full short-term backup initiated."));
6316
+ success("Full short-term backup initiated.");
5364
6317
  }
5365
6318
  } catch (error) {
5366
6319
  handleError(error);
@@ -5371,10 +6324,10 @@ function registerAdminCommands(program) {
5371
6324
  const api = createApiClient();
5372
6325
  if (options.longTerm) {
5373
6326
  await api.storage.createLongTermProjectBackup();
5374
- console.log(chalk23.green("Project long-term backup initiated."));
6327
+ success("Project long-term backup initiated.");
5375
6328
  } else {
5376
6329
  await api.storage.createShortTermProjectBackup();
5377
- console.log(chalk23.green("Project short-term backup initiated."));
6330
+ success("Project short-term backup initiated.");
5378
6331
  }
5379
6332
  } catch (error) {
5380
6333
  handleError(error);
@@ -5388,7 +6341,7 @@ function registerAdminCommands(program) {
5388
6341
  );
5389
6342
  const api = createApiClient();
5390
6343
  await api.storage.restoreProjectBackup({ projectId, projectBranch, bucketName, objectName });
5391
- console.log(chalk23.green(`Restore initiated for ${projectId}/${projectBranch} from ${bucketName}/${objectName}.`));
6344
+ success(`Restore initiated for ${projectId}/${projectBranch} from ${bucketName}/${objectName}.`);
5392
6345
  } catch (error) {
5393
6346
  handleError(error);
5394
6347
  }
@@ -5401,7 +6354,7 @@ function registerAdminCommands(program) {
5401
6354
  );
5402
6355
  const api = createApiClient();
5403
6356
  await api.storage.restoreFullBackup({ bucketName, objectName });
5404
- console.log(chalk23.green(`Full restore initiated from ${bucketName}/${objectName}.`));
6357
+ success(`Full restore initiated from ${bucketName}/${objectName}.`);
5405
6358
  } catch (error) {
5406
6359
  handleError(error);
5407
6360
  }
@@ -5411,10 +6364,10 @@ function registerAdminCommands(program) {
5411
6364
  const api = createApiClient();
5412
6365
  if (options.project) {
5413
6366
  await api.index.rebuildProject(options.project);
5414
- console.log(chalk23.green(`Index rebuild initiated for project "${options.project}".`));
6367
+ success(`Index rebuild initiated for project "${options.project}".`);
5415
6368
  } else {
5416
6369
  await api.index.rebuildAll();
5417
- console.log(chalk23.green("Index rebuild initiated for all projects."));
6370
+ success("Index rebuild initiated for all projects.");
5418
6371
  }
5419
6372
  } catch (error) {
5420
6373
  handleError(error);
@@ -5425,7 +6378,7 @@ function registerAdminCommands(program) {
5425
6378
  const outputFormat = getOutputFormat14(cmd);
5426
6379
  const api = createApiClient();
5427
6380
  const perm = await api.admin.getPermissions(projectId);
5428
- format(perm, { format: outputFormat });
6381
+ format({ projectId, permission: perm }, { format: outputFormat });
5429
6382
  } catch (error) {
5430
6383
  handleError(error);
5431
6384
  }
@@ -5456,7 +6409,7 @@ function registerAdminCommands(program) {
5456
6409
  }
5457
6410
 
5458
6411
  // src/commands/status/summary.ts
5459
- import chalk24 from "chalk";
6412
+ import chalk21 from "chalk";
5460
6413
 
5461
6414
  // src/client/services/status.ts
5462
6415
  function createStatusService() {
@@ -5482,24 +6435,24 @@ function createStatusService() {
5482
6435
 
5483
6436
  // src/commands/status/summary.ts
5484
6437
  var STATE_COLORS = {
5485
- UP: chalk24.green,
5486
- DEGRADED: chalk24.yellow,
5487
- DOWN: chalk24.red,
5488
- UNKNOWN: chalk24.gray
6438
+ UP: chalk21.green,
6439
+ DEGRADED: chalk21.yellow,
6440
+ DOWN: chalk21.red,
6441
+ UNKNOWN: chalk21.gray
5489
6442
  };
5490
6443
  function stateColor(state) {
5491
- return STATE_COLORS[state] ?? chalk24.gray;
6444
+ return STATE_COLORS[state] ?? chalk21.gray;
5492
6445
  }
5493
6446
  function stateSymbol(state) {
5494
6447
  switch (state) {
5495
6448
  case "UP":
5496
- return chalk24.green("\u25CF");
6449
+ return chalk21.green("\u25CF");
5497
6450
  case "DEGRADED":
5498
- return chalk24.yellow("\u25CF");
6451
+ return chalk21.yellow("\u25CF");
5499
6452
  case "DOWN":
5500
- return chalk24.red("\u25CF");
6453
+ return chalk21.red("\u25CF");
5501
6454
  default:
5502
- return chalk24.gray("\u25CB");
6455
+ return chalk21.gray("\u25CB");
5503
6456
  }
5504
6457
  }
5505
6458
  function registerSummaryCommand(parent) {
@@ -5523,15 +6476,21 @@ function registerSummaryCommand(parent) {
5523
6476
  for (const domain of summary.domains) {
5524
6477
  const label = stateColor(domain.state)(domain.state.padEnd(10));
5525
6478
  console.log(` ${stateSymbol(domain.state)} ${label} ${domain.name}`);
6479
+ if (domain.componentIds.length > 0) {
6480
+ console.log(` ${chalk21.dim(domain.componentIds.join(", "))}`);
6481
+ }
5526
6482
  }
5527
6483
  console.log();
5528
6484
  if (summary.openIncidents > 0) {
5529
- console.log(chalk24.yellow(` ${summary.openIncidents} active incident(s)`));
6485
+ console.log(chalk21.yellow(` ${summary.openIncidents} active incident(s)`));
5530
6486
  } else {
5531
- console.log(chalk24.dim(" No active incidents"));
6487
+ console.log(chalk21.dim(" No active incidents"));
5532
6488
  }
5533
- console.log(chalk24.dim(`
5534
- Platform v${version.platformVersion} \u2022 ${new Date(summary.timestamp).toLocaleString()}`));
6489
+ console.log(chalk21.dim(
6490
+ `
6491
+ Platform v${version.platformVersion} \xB7 checked ${formatInstant(summary.timestamp)}`
6492
+ ));
6493
+ console.log(chalk21.dim(` Drill into one with 'diafunc status component <id>'.`));
5535
6494
  console.log();
5536
6495
  } catch (error) {
5537
6496
  handleError(error);
@@ -5540,17 +6499,17 @@ function registerSummaryCommand(parent) {
5540
6499
  }
5541
6500
 
5542
6501
  // src/commands/status/component.ts
5543
- import chalk25 from "chalk";
6502
+ import chalk22 from "chalk";
5544
6503
  function stateSymbol2(state) {
5545
6504
  switch (state) {
5546
6505
  case "UP":
5547
- return chalk25.green("\u25CF");
6506
+ return chalk22.green("\u25CF");
5548
6507
  case "DEGRADED":
5549
- return chalk25.yellow("\u25CF");
6508
+ return chalk22.yellow("\u25CF");
5550
6509
  case "DOWN":
5551
- return chalk25.red("\u25CF");
6510
+ return chalk22.red("\u25CF");
5552
6511
  default:
5553
- return chalk25.gray("\u25CB");
6512
+ return chalk22.gray("\u25CB");
5554
6513
  }
5555
6514
  }
5556
6515
  function registerComponentCommand(parent) {
@@ -5560,27 +6519,31 @@ function registerComponentCommand(parent) {
5560
6519
  const outputFormat = globalOpts.output ?? "human";
5561
6520
  const status = createStatusService();
5562
6521
  const components = await status.getComponents();
5563
- const match = components.find((c) => c.id === id || c.id === id + "-service");
6522
+ const wanted = id.toLowerCase();
6523
+ const match = components.find((c) => {
6524
+ const cid = c.id.toLowerCase();
6525
+ return cid === wanted || cid === `${wanted}-service` || cid.replace(/-service$/, "") === wanted.replace(/[\s-]*service$/, "").replace(/\s+/g, "-");
6526
+ });
5564
6527
  if (!match) {
5565
- const available = components.map((c) => c.id).join(", ");
5566
- console.error(chalk25.red(`Component "${id}" not found. Available: ${available}`));
5567
- process.exit(1);
6528
+ failure(`No component called "${id}".`);
6529
+ hint(`Available: ${components.map((c) => c.id).join(", ")}`);
6530
+ process.exit(EXIT_USAGE);
5568
6531
  }
5569
6532
  if (outputFormat !== "human") {
5570
6533
  format(match, { format: outputFormat });
5571
6534
  return;
5572
6535
  }
5573
6536
  console.log();
5574
- console.log(` ${stateSymbol2(match.state)} ${chalk25.bold(match.id)} ${match.version ? chalk25.dim("v" + match.version) : ""}`);
5575
- console.log(` State: ${match.state}`);
6537
+ console.log(` ${stateSymbol2(match.state)} ${chalk22.bold(match.id)} ${match.version ? chalk22.dim("v" + match.version) : ""}`);
6538
+ console.log(` State: ${renderState(match.state)}`);
5576
6539
  if (match.lastCheckAt) {
5577
- console.log(` Last check: ${new Date(match.lastCheckAt).toLocaleString()}`);
6540
+ console.log(` Last check: ${formatInstant(match.lastCheckAt)}`);
5578
6541
  }
5579
6542
  if (match.checks.length > 0) {
5580
6543
  console.log();
5581
6544
  console.log(" Checks:");
5582
6545
  for (const check of match.checks) {
5583
- const cat = check.category ? chalk25.dim(` (${check.category})`) : "";
6546
+ const cat = check.category ? chalk22.dim(` (${check.category})`) : "";
5584
6547
  console.log(` ${stateSymbol2(check.state)} ${check.name}${cat}`);
5585
6548
  }
5586
6549
  }
@@ -5592,12 +6555,12 @@ function registerComponentCommand(parent) {
5592
6555
  }
5593
6556
 
5594
6557
  // src/commands/status/incidents.ts
5595
- import chalk26 from "chalk";
6558
+ import chalk23 from "chalk";
5596
6559
  var SEVERITY_COLORS = {
5597
- ERROR: chalk26.red,
5598
- WARNING: chalk26.yellow,
5599
- INFO: chalk26.blue,
5600
- MAINTENANCE: chalk26.cyan
6560
+ ERROR: chalk23.red,
6561
+ WARNING: chalk23.yellow,
6562
+ INFO: chalk23.blue,
6563
+ MAINTENANCE: chalk23.cyan
5601
6564
  };
5602
6565
  function registerIncidentsCommand(parent) {
5603
6566
  parent.command("incidents").description("List recent incidents").option("-w, --window <window>", "Time window (e.g. 24h, 48h)", "24h").action(async (options, cmd) => {
@@ -5611,22 +6574,22 @@ function registerIncidentsCommand(parent) {
5611
6574
  return;
5612
6575
  }
5613
6576
  if (incidents.length === 0) {
5614
- console.log(chalk26.dim(`
6577
+ console.log(chalk23.dim(`
5615
6578
  No incidents in the last ${options.window}.
5616
6579
  `));
5617
6580
  return;
5618
6581
  }
5619
6582
  console.log();
5620
6583
  for (const incident of incidents) {
5621
- const color = SEVERITY_COLORS[incident.severity] ?? chalk26.gray;
6584
+ const color = SEVERITY_COLORS[incident.severity] ?? chalk23.gray;
5622
6585
  const severity = color(incident.severity.padEnd(8));
5623
6586
  const time = incident.startedAt ? new Date(incident.startedAt).toLocaleString() : "";
5624
- const resolved = incident.resolvedAt ? chalk26.green(" [resolved]") : chalk26.yellow(" [open]");
6587
+ const resolved = incident.resolvedAt ? chalk23.green(" [resolved]") : chalk23.yellow(" [open]");
5625
6588
  console.log(` ${severity} ${incident.summary}${resolved}`);
5626
- console.log(chalk26.dim(` ${time}`));
6589
+ console.log(chalk23.dim(` ${time}`));
5627
6590
  for (const update of incident.updates) {
5628
6591
  const updateTime = new Date(update.at).toLocaleTimeString();
5629
- console.log(chalk26.dim(` ${updateTime} ${update.status} ${update.message}`));
6592
+ console.log(chalk23.dim(` ${updateTime} ${update.status} ${update.message}`));
5630
6593
  }
5631
6594
  console.log();
5632
6595
  }
@@ -5638,25 +6601,112 @@ function registerIncidentsCommand(parent) {
5638
6601
 
5639
6602
  // src/commands/status/index.ts
5640
6603
  function registerStatusCommands(program) {
5641
- const status = program.command("status").description("Platform health and status");
6604
+ const status = program.command("status").description("Platform health and status").addHelpText("after", `
6605
+ Examples:
6606
+ $ diafunc status summary everything, at a glance
6607
+ $ diafunc status component storage one service in detail
6608
+ $ diafunc status incidents --days 7
6609
+ `);
6610
+ ;
5642
6611
  registerSummaryCommand(status);
5643
6612
  registerComponentCommand(status);
5644
6613
  registerIncidentsCommand(status);
5645
6614
  }
5646
6615
 
5647
6616
  // src/commands/analyze/index.ts
5648
- import chalk27 from "chalk";
6617
+ import chalk25 from "chalk";
5649
6618
  import * as fs8 from "fs";
5650
6619
  import * as path7 from "path";
5651
6620
  import { spawn as spawn2 } from "child_process";
5652
- function formatDuration(ms) {
5653
- const seconds = Math.floor(ms / 1e3);
5654
- const minutes = Math.floor(seconds / 60);
5655
- const hours = Math.floor(minutes / 60);
5656
- if (hours > 0) return `${hours}h ${minutes % 60}m`;
5657
- if (minutes > 0) return `${minutes}m ${seconds % 60}s`;
5658
- return `${seconds}s`;
6621
+
6622
+ // src/commands/analyze/watch-view.ts
6623
+ import chalk24 from "chalk";
6624
+
6625
+ // src/client/types/analysis.ts
6626
+ var RUN_PHASE_LABELS = {
6627
+ QUEUED: "Waiting for a slot",
6628
+ PREPARING: "Preparing",
6629
+ PROFILING: "Profiling your data",
6630
+ DISCOVERING: "Discovering formulas",
6631
+ EXPLAINING: "Building charts and diagnostics",
6632
+ WRITING: "Writing the report"
6633
+ };
6634
+
6635
+ // src/commands/analyze/watch-view.ts
6636
+ var PHASE_ORDER = ["QUEUED", "PREPARING", "PROFILING", "DISCOVERING", "EXPLAINING", "WRITING"];
6637
+ function overallProgress(run) {
6638
+ if (run.overallFraction !== null && run.overallFraction !== void 0) return run.overallFraction;
6639
+ if (run.progressTotal && run.progressTotal > 0) return (run.progressDone ?? 0) / run.progressTotal;
6640
+ return null;
6641
+ }
6642
+ function phaseLabel(run) {
6643
+ if (run.phase && RUN_PHASE_LABELS[run.phase]) return RUN_PHASE_LABELS[run.phase];
6644
+ return run.state.charAt(0) + run.state.slice(1).toLowerCase();
6645
+ }
6646
+ function stepCounter(run) {
6647
+ if (!run.phase) return null;
6648
+ const index = PHASE_ORDER.indexOf(run.phase);
6649
+ if (index < 0) return null;
6650
+ return `step ${index + 1} of ${PHASE_ORDER.length}`;
6651
+ }
6652
+ function phaseDetail(run) {
6653
+ const parts = [];
6654
+ if (run.phase === "DISCOVERING") {
6655
+ if (run.fitGeneration !== null && run.fitGeneration !== void 0) {
6656
+ parts.push(`generation ${formatNumber(run.fitGeneration)}`);
6657
+ }
6658
+ if (run.fitQuality !== null && run.fitQuality !== void 0) {
6659
+ parts.push(`quality ${run.fitQuality.toPrecision(4)}`);
6660
+ }
6661
+ if (run.fitBudgetFraction !== null && run.fitBudgetFraction !== void 0) {
6662
+ parts.push(`${Math.round(run.fitBudgetFraction * 100)}% of budget used`);
6663
+ }
6664
+ }
6665
+ if (parts.length === 0 && run.progressTotal && run.progressTotal > 0) {
6666
+ parts.push(`${formatNumber(run.progressDone ?? 0)} of ${formatNumber(run.progressTotal)} tasks`);
6667
+ } else if (parts.length === 0 && run.phaseFraction !== null && run.phaseFraction !== void 0) {
6668
+ parts.push(`${Math.round(run.phaseFraction * 100)}% of this step`);
6669
+ }
6670
+ return parts.length > 0 ? parts.join(" \xB7 ") : null;
6671
+ }
6672
+ function renderWatchBlock(input) {
6673
+ const { run, elapsedMs, caption } = input;
6674
+ const lines = [];
6675
+ const step = stepCounter(run);
6676
+ const headline = [
6677
+ chalk24.cyan(SPINNER),
6678
+ chalk24.bold(phaseLabel(run)),
6679
+ step ? chalk24.dim(step) : null
6680
+ ].filter(Boolean).join(" ");
6681
+ lines.push(` ${headline}`);
6682
+ const fraction = overallProgress(run);
6683
+ const elapsed = chalk24.dim(formatDuration(elapsedMs));
6684
+ if (fraction === null) {
6685
+ lines.push(` ${chalk24.dim("working")} ${elapsed}`);
6686
+ } else {
6687
+ const eta = estimateRemaining(fraction, elapsedMs);
6688
+ lines.push(
6689
+ ` ${bar(fraction)} ${percent(fraction)} ${elapsed}` + (eta ? chalk24.dim(` \xB7 ~${formatDuration(eta)} left`) : "")
6690
+ );
6691
+ }
6692
+ const detail2 = caption ?? phaseDetail(run);
6693
+ if (detail2) lines.push(` ${chalk24.dim(detail2)}`);
6694
+ if (run.retryAttempts && run.retryAttempts > 0) {
6695
+ lines.push(` ${chalk24.yellow("!")} ${chalk24.dim(
6696
+ `restarted ${run.retryAttempts === 1 ? "once" : `${run.retryAttempts} times`} after an interruption \u2014 progress restarts from the beginning`
6697
+ )}`);
6698
+ }
6699
+ return lines;
6700
+ }
6701
+ function estimateRemaining(fraction, elapsedMs) {
6702
+ if (fraction <= 0.02 || fraction >= 1 || elapsedMs < 3e4) return null;
6703
+ const total = elapsedMs / fraction;
6704
+ const remaining = total - elapsedMs;
6705
+ return remaining > 0 ? remaining : null;
5659
6706
  }
6707
+
6708
+ // src/commands/analyze/index.ts
6709
+ var POLL_INTERVAL_MS = 2e3;
5660
6710
  function openUrl(url) {
5661
6711
  const cmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
5662
6712
  const args = process.platform === "win32" ? ["/c", "start", '""', url] : [url];
@@ -5690,14 +6740,14 @@ function multipartFromFile(file) {
5690
6740
  }
5691
6741
  async function runAnalysis(file, options, cmd) {
5692
6742
  if (!fs8.existsSync(file)) {
5693
- console.error(chalk27.red(`File not found: ${file}`));
6743
+ failure(`File not found: ${file}`);
5694
6744
  process.exit(1);
5695
6745
  }
5696
6746
  if (options.preset) {
5697
6747
  const api2 = createApiClient();
5698
6748
  const opt = await api2.analysis.getPreset(options.preset);
5699
6749
  if (!opt.preset) {
5700
- console.error(chalk27.red(`Preset not found: ${options.preset}`));
6750
+ failure(`Preset not found: ${options.preset}`);
5701
6751
  process.exit(1);
5702
6752
  }
5703
6753
  const p = opt.preset;
@@ -5723,93 +6773,121 @@ async function runAnalysis(file, options, cmd) {
5723
6773
  questions: parseCsv(options.questions),
5724
6774
  segment: options.segment ?? null
5725
6775
  };
5726
- process.stdout.write(`Creating analysis "${name}" ...`);
5727
- const created = await api.analysis.create(request);
5728
- console.log(chalk27.green(" done"));
5729
- console.log(chalk27.dim(` analysisId: ${created.analysisId}`));
5730
- process.stdout.write(`Uploading ${path7.basename(file)} ...`);
5731
- await api.analysis.uploadDataMultipart(created.analysisId, multipartFromFile(file));
5732
- console.log(chalk27.green(" done"));
5733
- process.stdout.write("Queuing analysis run ...");
5734
- const run = await api.analysis.runAnalysis(created.analysisId);
5735
- console.log(chalk27.green(" done"));
5736
- console.log(chalk27.dim(` runId: ${run.runId}`));
6776
+ const created = await withStatus(`Creating analysis "${name}"`, () => api.analysis.create(request));
6777
+ console.log(chalk25.dim(` analysisId: ${created.analysisId}`));
6778
+ await withStatus(
6779
+ `Uploading ${path7.basename(file)}`,
6780
+ () => api.analysis.uploadDataMultipart(created.analysisId, multipartFromFile(file))
6781
+ );
6782
+ const run = await withStatus("Queuing analysis run", () => api.analysis.runAnalysis(created.analysisId));
6783
+ console.log(chalk25.dim(` runId: ${run.runId}`));
5737
6784
  console.log();
5738
- await monitorRun(api, created.analysisId, run.runId, parseFloat(hours), cmd);
6785
+ await monitorRun(api, created.analysisId, run.runId, cmd);
5739
6786
  }
5740
- async function monitorRun(api, analysisId, runId, hoursForProgress, cmd) {
6787
+ async function monitorRun(api, analysisId, runId, cmd) {
5741
6788
  const config = loadConfig();
5742
6789
  const outputFormat = getOutputFormat15(cmd);
5743
- const computationMs = hoursForProgress * 60 * 60 * 1e3;
5744
- const startMs = Date.now();
5745
- const seenOutputIds = /* @__PURE__ */ new Set();
5746
- for (let i = 0; ; i++) {
5747
- await new Promise((resolve) => setTimeout(resolve, 2e3));
5748
- let run = null;
5749
- try {
5750
- const opt = await api.analysis.getRun(runId);
5751
- run = opt.run;
5752
- } catch {
5753
- }
5754
- if (!run) continue;
5755
- try {
5756
- const outputs = await api.analysis.getRunOutputs(analysisId, runId);
5757
- for (const out of outputs) {
5758
- if (!seenOutputIds.has(out.outputId)) {
5759
- seenOutputIds.add(out.outputId);
5760
- if (outputFormat === "human") {
5761
- console.log(` ${chalk27.dim("Output:")} ${out.output}`);
6790
+ const human = outputFormat === "human";
6791
+ const status = new Status();
6792
+ const seenOutputs = /* @__PURE__ */ new Set();
6793
+ let caption = null;
6794
+ let lastReported = "";
6795
+ if (human) status.start();
6796
+ try {
6797
+ for (; ; ) {
6798
+ await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));
6799
+ let run = null;
6800
+ try {
6801
+ run = (await api.analysis.getRun(runId)).run;
6802
+ } catch {
6803
+ }
6804
+ if (!run) continue;
6805
+ try {
6806
+ for (const out of await api.analysis.getRunOutputs(analysisId, runId)) {
6807
+ const key = `${out.outputId}:${out.output}`;
6808
+ if (seenOutputs.has(key)) continue;
6809
+ seenOutputs.add(key);
6810
+ if (out.type === "event") {
6811
+ if (!human) process.stdout.write(JSON.stringify({ type: "event", ...safeParse(out.output) }) + "\n");
5762
6812
  } else {
5763
- process.stdout.write(
5764
- JSON.stringify({ type: "output", outputId: out.outputId, output: out.output }) + "\n"
5765
- );
6813
+ caption = out.output;
6814
+ if (!human) {
6815
+ process.stdout.write(JSON.stringify({ type: "info", message: out.output }) + "\n");
6816
+ }
5766
6817
  }
5767
6818
  }
6819
+ } catch {
5768
6820
  }
5769
- } catch {
5770
- }
5771
- if (isTerminalState(run.state)) {
5772
- console.log();
5773
- const baseStart = run.startedAt ?? run.submittedAt ?? startMs;
5774
- const duration = (run.endedAt ?? Date.now()) - baseStart;
5775
- const durationStr = formatDuration(duration);
5776
- if (run.state === "COMPLETED") {
5777
- if (outputFormat === "human") {
5778
- console.log(chalk27.green(`Analysis complete! (${durationStr})`));
5779
- try {
5780
- const nav = await api.analysis.getNavigation(analysisId);
5781
- const endpoint = config.profiles[config.currentProfile]?.endpoint ?? "https://diafunc.com";
5782
- console.log(` Project: ${endpoint}${nav.labUrl}`);
5783
- } catch {
5784
- }
5785
- } else {
5786
- format({ status: "completed", runId, analysisId, duration }, { format: outputFormat });
5787
- }
5788
- } else if (run.state === "CANCELLED") {
5789
- if (outputFormat === "human") {
5790
- console.log(chalk27.yellow("Analysis cancelled."));
5791
- } else {
5792
- format({ status: "cancelled", runId, analysisId }, { format: outputFormat });
5793
- }
6821
+ if (isTerminalState(run.state)) {
6822
+ status.stop();
6823
+ await reportTerminalRun(api, config, run, analysisId, runId, outputFormat);
6824
+ return;
6825
+ }
6826
+ const startedAt = run.startedAt ?? run.submittedAt ?? Date.now();
6827
+ if (human) {
6828
+ status.set(renderWatchBlock({ run, elapsedMs: Date.now() - startedAt, caption }));
5794
6829
  } else {
5795
- if (outputFormat === "human") {
5796
- console.log(chalk27.red("Analysis failed."));
5797
- if (run.errorMessage) console.log(` Error: ${run.errorMessage}`);
5798
- } else {
5799
- format({ status: "failed", runId, analysisId, error: run.errorMessage }, { format: outputFormat });
6830
+ const snapshot = JSON.stringify({
6831
+ type: "progress",
6832
+ state: run.state,
6833
+ phase: run.phase,
6834
+ overallFraction: run.overallFraction,
6835
+ progressDone: run.progressDone,
6836
+ progressTotal: run.progressTotal
6837
+ });
6838
+ if (snapshot !== lastReported) {
6839
+ lastReported = snapshot;
6840
+ process.stdout.write(snapshot + "\n");
5800
6841
  }
5801
6842
  }
5802
- return;
5803
- }
5804
- if (outputFormat === "human" && i % 5 === 0) {
5805
- const elapsed = Date.now() - startMs;
5806
- const progress = run.progressTotal && run.progressTotal > 0 ? (run.progressDone ?? 0) / run.progressTotal : Math.min(elapsed / computationMs, 1);
5807
- const pct = Math.round(progress * 100);
5808
- const filled = Math.round(progress * 30);
5809
- const bar = "\u2588".repeat(filled) + "\u2591".repeat(30 - filled);
5810
- const stateLabel = run.state.toLowerCase().padEnd(11);
5811
- process.stdout.write(`\r ${stateLabel} [${bar}] ${pct}% `);
5812
6843
  }
6844
+ } finally {
6845
+ status.stop();
6846
+ }
6847
+ }
6848
+ function safeParse(text) {
6849
+ try {
6850
+ const parsed = JSON.parse(text);
6851
+ return parsed && typeof parsed === "object" ? parsed : { output: text };
6852
+ } catch {
6853
+ return { output: text };
6854
+ }
6855
+ }
6856
+ async function reportTerminalRun(api, config, run, analysisId, runId, outputFormat) {
6857
+ const baseStart = run.startedAt ?? run.submittedAt ?? Date.now();
6858
+ const durationMs = (run.endedAt ?? Date.now()) - baseStart;
6859
+ if (outputFormat !== "human") {
6860
+ format({
6861
+ status: run.state.toLowerCase(),
6862
+ runId,
6863
+ analysisId,
6864
+ durationMs,
6865
+ error: run.errorMessage
6866
+ }, { format: outputFormat });
6867
+ if (run.state !== "COMPLETED") process.exit(EXIT_FAILURE);
6868
+ return;
6869
+ }
6870
+ console.log();
6871
+ if (run.state === "COMPLETED") {
6872
+ success(`Analysis complete in ${formatDuration(durationMs)}.`);
6873
+ await printNotebookLink(api, config, analysisId);
6874
+ return;
6875
+ }
6876
+ if (run.state === "CANCELLED") {
6877
+ warn(`Analysis cancelled after ${formatDuration(durationMs)}.`);
6878
+ process.exit(EXIT_FAILURE);
6879
+ }
6880
+ failure(`Analysis failed after ${formatDuration(durationMs)}.`);
6881
+ if (run.errorMessage) hint(run.errorMessage);
6882
+ hint(`Queue a fresh run with 'diafunc analyze rerun ${analysisId}'.`);
6883
+ process.exit(EXIT_FAILURE);
6884
+ }
6885
+ async function printNotebookLink(api, config, analysisId) {
6886
+ try {
6887
+ const nav = await api.analysis.getNavigation(analysisId);
6888
+ const endpoint = config.profiles[config.currentProfile]?.endpoint ?? "https://diafunc.com";
6889
+ detail(`${endpoint}${nav.labUrl}`);
6890
+ } catch {
5813
6891
  }
5814
6892
  }
5815
6893
  async function listAnalyses(limit, cmd) {
@@ -5822,40 +6900,68 @@ async function listAnalyses(limit, cmd) {
5822
6900
  visibility: a.visibility,
5823
6901
  hours: a.hours,
5824
6902
  budget: a.budget,
5825
- targets: (a.targets ?? []).join(", "),
5826
- latestRunState: a.latestRunState ?? "\u2014",
5827
- createdAt: a.createdAt ?? "\u2014"
6903
+ targets: a.targets,
6904
+ latestRunState: a.latestRunState,
6905
+ createdAt: a.createdAt
5828
6906
  })), {
5829
6907
  format: outputFormat,
5830
- columns: ["analysisId", "name", "visibility", "hours", "budget", "targets", "latestRunState", "createdAt"]
5831
- });
5832
- }
5833
- async function getAnalysisDetails(analysisId, cmd) {
6908
+ columns: [
6909
+ { key: "analysisId", kind: "id" },
6910
+ { key: "name", maxWidth: 40 },
6911
+ { key: "visibility" },
6912
+ { key: "hours" },
6913
+ { key: "budget" },
6914
+ { key: "targets" },
6915
+ { key: "latestRunState", header: "last run", kind: "state" },
6916
+ { key: "createdAt", header: "created", kind: "date" }
6917
+ ]
6918
+ });
6919
+ }
6920
+ async function getAnalysisDetails(analysisId, options, cmd) {
5834
6921
  const outputFormat = getOutputFormat15(cmd);
5835
6922
  const api = createApiClient();
5836
6923
  const result = analysisId ? await api.analysis.get(analysisId) : await api.analysis.getLast();
5837
6924
  if (!result.analysis) {
5838
- console.log(chalk27.dim("No analysis found."));
6925
+ empty("analysis found");
5839
6926
  return;
5840
6927
  }
5841
- format(result.analysis, { format: outputFormat });
6928
+ const analysis = outputFormat === "human" && !options.full ? { ...result.analysis, introduction: abbreviate(result.analysis.introduction) } : result.analysis;
6929
+ format(analysis, { format: outputFormat });
6930
+ if (outputFormat === "human" && !options.full && isLong(result.analysis.introduction)) {
6931
+ hint(`Introduction abbreviated \u2014 pass --full to print it whole.`);
6932
+ }
6933
+ }
6934
+ var INTRODUCTION_PREVIEW_LINES = 3;
6935
+ function isLong(text) {
6936
+ return Boolean(text && text.split("\n").length > INTRODUCTION_PREVIEW_LINES);
6937
+ }
6938
+ function abbreviate(text) {
6939
+ if (!isLong(text)) return text;
6940
+ const lines = text.split("\n").filter((l) => l.trim().length > 0);
6941
+ return `${lines.slice(0, INTRODUCTION_PREVIEW_LINES).join("\n")}
6942
+ \u2026`;
5842
6943
  }
5843
6944
  async function watchAnalysis(analysisId, cmd) {
5844
6945
  const api = createApiClient();
5845
6946
  const result = analysisId ? await api.analysis.get(analysisId) : await api.analysis.getLast();
5846
6947
  if (!result.analysis) {
5847
- console.log(chalk27.dim("No analysis found."));
6948
+ empty("analysis found");
5848
6949
  return;
5849
6950
  }
5850
6951
  const recipe = result.analysis;
5851
6952
  const runs = await api.analysis.getRunsForAnalysis(recipe.analysisId, 1);
5852
6953
  if (runs.length === 0) {
5853
- console.log(chalk27.dim("No runs for this analysis."));
6954
+ empty("runs for this analysis");
5854
6955
  return;
5855
6956
  }
5856
6957
  const latest = runs[0];
5857
6958
  if (isTerminalState(latest.state)) {
5858
- console.log(chalk27.green(`Latest run already in terminal state: ${latest.state}`));
6959
+ if (latest.state === "COMPLETED") {
6960
+ success("The latest run has already completed.");
6961
+ } else {
6962
+ warn(`The latest run ended as ${latest.state}.`);
6963
+ if (latest.errorMessage) hint(latest.errorMessage);
6964
+ }
5859
6965
  try {
5860
6966
  const nav = await api.analysis.getNavigation(recipe.analysisId);
5861
6967
  const config = loadConfig();
@@ -5866,21 +6972,21 @@ async function watchAnalysis(analysisId, cmd) {
5866
6972
  return;
5867
6973
  }
5868
6974
  console.log(`Watching run ${latest.runId} for analysis ${recipe.analysisId} ...`);
5869
- await monitorRun(api, recipe.analysisId, latest.runId, parseFloat(recipe.hours), cmd);
6975
+ await monitorRun(api, recipe.analysisId, latest.runId, cmd);
5870
6976
  }
5871
6977
  async function rerunAnalysis(analysisId) {
5872
6978
  const api = createApiClient();
5873
6979
  const run = await api.analysis.runAnalysis(analysisId);
5874
- console.log(chalk27.green(`\u2713 Queued new run ${run.runId} for analysis ${analysisId}`));
5875
- console.log(chalk27.dim(` State: ${run.state}`));
6980
+ success(`Queued new run ${run.runId} for analysis ${analysisId}`);
6981
+ console.log(chalk25.dim(` State: ${run.state}`));
5876
6982
  console.log();
5877
- console.log(chalk27.dim("Track progress: diafunc analyze watch " + analysisId));
6983
+ console.log(chalk25.dim("Track progress: diafunc analyze watch " + analysisId));
5878
6984
  }
5879
6985
  async function openAnalysis(analysisId) {
5880
6986
  const api = createApiClient();
5881
6987
  const result = analysisId ? await api.analysis.get(analysisId) : await api.analysis.getLast();
5882
6988
  if (!result.analysis) {
5883
- console.log(chalk27.dim("No analysis found."));
6989
+ empty("analysis found");
5884
6990
  return;
5885
6991
  }
5886
6992
  const config = loadConfig();
@@ -5891,7 +6997,7 @@ async function openAnalysis(analysisId) {
5891
6997
  console.log(`Opening ${url} ...`);
5892
6998
  openUrl(url);
5893
6999
  } catch {
5894
- console.log(chalk27.dim("Notebook not yet provisioned \u2014 run the analysis first."));
7000
+ console.log(chalk25.dim("Notebook not yet provisioned \u2014 run the analysis first."));
5895
7001
  }
5896
7002
  }
5897
7003
  async function createRecipe(options, cmd) {
@@ -5915,48 +7021,48 @@ async function createRecipe(options, cmd) {
5915
7021
  async function deleteAnalysis(analysisId) {
5916
7022
  const api = createApiClient();
5917
7023
  await api.analysis.delete(analysisId);
5918
- console.log(chalk27.green(`\u2713 Deleted analysis ${analysisId}`));
7024
+ success(`Deleted analysis ${analysisId}`);
5919
7025
  }
5920
7026
  async function patchAndPrint(analysisId, value, handler, successLabel, cmd) {
5921
7027
  const outputFormat = getOutputFormat15(cmd);
5922
7028
  const api = createApiClient();
5923
7029
  const updated = await handler(api, analysisId, value);
5924
7030
  if (outputFormat === "human") {
5925
- console.log(chalk27.green(`\u2713 ${successLabel} updated for analysis ${analysisId}`));
7031
+ success(`${successLabel} updated for analysis ${analysisId}`);
5926
7032
  } else {
5927
7033
  format(updated, { format: outputFormat });
5928
7034
  }
5929
7035
  }
5930
7036
  async function uploadData(analysisId, file, options) {
5931
7037
  const api = createApiClient();
5932
- if (options.url) {
7038
+ const dataUrl = options.url;
7039
+ if (dataUrl) {
5933
7040
  if (file) {
5934
- console.error(chalk27.red("Provide either a file or --url, not both."));
5935
- process.exit(1);
7041
+ usageError("Provide either a file or --url, not both.", "Drop one of the two and run it again.");
5936
7042
  }
5937
- process.stdout.write(`Uploading from ${options.url} ...`);
5938
- await api.analysis.uploadDataUrl(analysisId, { dataUrl: options.url });
5939
- console.log(chalk27.green(" done"));
7043
+ await withStatus(`Uploading from ${dataUrl}`, () => api.analysis.uploadDataUrl(analysisId, { dataUrl }));
5940
7044
  return;
5941
7045
  }
5942
7046
  if (!file) {
5943
- console.error(chalk27.red("Provide a file path or --url <URL>."));
5944
- process.exit(1);
7047
+ usageError(
7048
+ "Provide a file path or --url <URL>.",
7049
+ `For example: diafunc analyze upload ${analysisId} data.csv`
7050
+ );
5945
7051
  }
5946
7052
  if (!fs8.existsSync(file)) {
5947
- console.error(chalk27.red(`File not found: ${file}`));
5948
- process.exit(1);
7053
+ throw new CliError(`File not found: ${file}`, { exitCode: EXIT_USAGE });
5949
7054
  }
5950
- process.stdout.write(`Uploading ${path7.basename(file)} ...`);
5951
- await api.analysis.uploadDataMultipart(analysisId, multipartFromFile(file));
5952
- console.log(chalk27.green(" done"));
7055
+ await withStatus(
7056
+ `Uploading ${path7.basename(file)}`,
7057
+ () => api.analysis.uploadDataMultipart(analysisId, multipartFromFile(file))
7058
+ );
5953
7059
  }
5954
7060
  async function listColumns(analysisId, cmd) {
5955
7061
  const outputFormat = getOutputFormat15(cmd);
5956
7062
  const api = createApiClient();
5957
7063
  const columns = await api.analysis.getColumns(analysisId);
5958
7064
  if (columns.length === 0) {
5959
- console.log(chalk27.dim("No columns yet \u2014 upload data first."));
7065
+ empty("columns yet \u2014 upload data first");
5960
7066
  return;
5961
7067
  }
5962
7068
  format(columns, { format: outputFormat, columns: ["name", "valueType"] });
@@ -5974,7 +7080,13 @@ async function listRuns(analysisId, count, cmd) {
5974
7080
  evaluationId: r.evaluationId ?? "\u2014"
5975
7081
  })), {
5976
7082
  format: outputFormat,
5977
- columns: ["runId", "state", "submittedAt", "endedAt", "evaluationId"]
7083
+ columns: [
7084
+ { key: "runId", kind: "id" },
7085
+ { key: "state", kind: "state" },
7086
+ { key: "phase" },
7087
+ { key: "submittedAt", header: "submitted", kind: "date" },
7088
+ { key: "endedAt", header: "ended", kind: "date" }
7089
+ ]
5978
7090
  });
5979
7091
  }
5980
7092
  async function cancelRun(runId, cmd) {
@@ -5982,7 +7094,7 @@ async function cancelRun(runId, cmd) {
5982
7094
  const api = createApiClient();
5983
7095
  const run = await api.analysis.cancelRun(runId);
5984
7096
  if (outputFormat === "human") {
5985
- console.log(chalk27.green(`\u2713 Run ${run.runId} state: ${run.state}`));
7097
+ success(`Run ${run.runId} state: ${run.state}`);
5986
7098
  } else {
5987
7099
  format(run, { format: outputFormat });
5988
7100
  }
@@ -6009,7 +7121,7 @@ async function getPreset(presetId, cmd) {
6009
7121
  const api = createApiClient();
6010
7122
  const opt = await api.analysis.getPreset(presetId);
6011
7123
  if (!opt.preset) {
6012
- console.log(chalk27.dim("Preset not found."));
7124
+ console.log(chalk25.dim("Preset not found."));
6013
7125
  return;
6014
7126
  }
6015
7127
  format(opt.preset, { format: outputFormat });
@@ -6032,7 +7144,7 @@ async function savePreset(options, cmd) {
6032
7144
  async function deletePreset(presetId) {
6033
7145
  const api = createApiClient();
6034
7146
  await api.analysis.deletePreset(presetId);
6035
- console.log(chalk27.green(`\u2713 Deleted preset ${presetId}`));
7147
+ success(`Deleted preset ${presetId}`);
6036
7148
  }
6037
7149
  async function listTriggers(analysisId, cmd) {
6038
7150
  const outputFormat = getOutputFormat15(cmd);
@@ -6053,7 +7165,7 @@ async function createTrigger(analysisId, kind, schedule, cmd) {
6053
7165
  const outputFormat = getOutputFormat15(cmd);
6054
7166
  const upper = kind.toUpperCase();
6055
7167
  if (upper !== "ONCE" && upper !== "CRON") {
6056
- console.error(chalk27.red(`Invalid kind "${kind}" \u2014 must be ONCE or CRON.`));
7168
+ failure(`Invalid kind "${kind}" \u2014 must be ONCE or CRON.`);
6057
7169
  process.exit(1);
6058
7170
  }
6059
7171
  const api = createApiClient();
@@ -6066,7 +7178,7 @@ async function createTrigger(analysisId, kind, schedule, cmd) {
6066
7178
  async function deleteTrigger(triggerId) {
6067
7179
  const api = createApiClient();
6068
7180
  await api.analysis.deleteTrigger(triggerId);
6069
- console.log(chalk27.green(`\u2713 Deleted trigger ${triggerId}`));
7181
+ success(`Deleted trigger ${triggerId}`);
6070
7182
  }
6071
7183
  async function updateTriggerCmd(triggerId, options, cmd) {
6072
7184
  const outputFormat = getOutputFormat15(cmd);
@@ -6074,13 +7186,13 @@ async function updateTriggerCmd(triggerId, options, cmd) {
6074
7186
  if (options.active !== void 0) {
6075
7187
  const lc = options.active.toLowerCase();
6076
7188
  if (lc !== "true" && lc !== "false") {
6077
- console.error(chalk27.red(`Invalid --active value "${options.active}" \u2014 must be true or false.`));
7189
+ failure(`Invalid --active value "${options.active}" \u2014 must be true or false.`);
6078
7190
  process.exit(1);
6079
7191
  }
6080
7192
  activeFlag = lc === "true";
6081
7193
  }
6082
7194
  if (activeFlag === void 0 && !options.schedule) {
6083
- console.error(chalk27.red("Pass at least one of --active or --schedule."));
7195
+ failure("Pass at least one of --active or --schedule.");
6084
7196
  process.exit(1);
6085
7197
  }
6086
7198
  const api = createApiClient();
@@ -6110,9 +7222,9 @@ function registerAnalyzeCommand(program) {
6110
7222
  handleError(error);
6111
7223
  }
6112
7224
  });
6113
- analyze.command("get").description("Show details of an analysis").argument("[id]", "Analysis ID (defaults to the most recent)").action(async (id, _options, cmd) => {
7225
+ analyze.command("get").description("Show details of an analysis").argument("[id]", "Analysis ID (defaults to the most recent)").option("--full", "Print the introduction in full instead of abbreviating it").action(async (id, options, cmd) => {
6114
7226
  try {
6115
- await getAnalysisDetails(id, cmd);
7227
+ await getAnalysisDetails(id, options, cmd);
6116
7228
  } catch (error) {
6117
7229
  handleError(error);
6118
7230
  }
@@ -6364,7 +7476,7 @@ function registerAnalyzeCommand(program) {
6364
7476
  }
6365
7477
 
6366
7478
  // src/commands/data-sources/index.ts
6367
- import chalk28 from "chalk";
7479
+ import chalk26 from "chalk";
6368
7480
  function getOutputFormat16(cmd) {
6369
7481
  const config = loadConfig();
6370
7482
  const globalOpts = cmd.optsWithGlobals();
@@ -6453,17 +7565,36 @@ function runTableRow(run) {
6453
7565
  triggeredBy: run.triggeredBy ?? "\u2014"
6454
7566
  };
6455
7567
  }
7568
+ function resolveProjectId(explicit, cmd) {
7569
+ const globals = cmd.optsWithGlobals();
7570
+ const resolved = explicit ?? globals.project ?? loadConfig().defaults.project;
7571
+ if (!resolved) {
7572
+ usageError(
7573
+ "This command needs a project.",
7574
+ `Pass --project <id>, or set a default with 'diafunc config set defaults.project <id>'.`
7575
+ );
7576
+ }
7577
+ return resolved;
7578
+ }
6456
7579
  async function listDataSources(projectId, cmd) {
6457
7580
  const outputFormat = getOutputFormat16(cmd);
6458
7581
  const api = createApiClient();
6459
7582
  const sources = await api.storage.listDataSources(projectId);
6460
7583
  if (outputFormat === "human" && sources.length === 0) {
6461
- console.log(chalk28.dim("No data sources found."));
7584
+ empty("data sources");
6462
7585
  return;
6463
7586
  }
6464
7587
  format(sources.map(dataSourceTableRow), {
6465
7588
  format: outputFormat,
6466
- columns: ["id", "name", "type", "target", "schedule", "lastStatus", "lastRefreshAt"]
7589
+ columns: [
7590
+ { key: "id", kind: "id" },
7591
+ { key: "name" },
7592
+ { key: "type" },
7593
+ { key: "target" },
7594
+ { key: "schedule" },
7595
+ { key: "lastStatus", header: "last status", kind: "state" },
7596
+ { key: "lastRefreshAt", header: "last refresh", kind: "date" }
7597
+ ]
6467
7598
  });
6468
7599
  }
6469
7600
  async function getDataSource(id, cmd) {
@@ -6481,16 +7612,26 @@ async function showDashboard(projectId, cmd) {
6481
7612
  return;
6482
7613
  }
6483
7614
  const r = dashboard.rollup;
6484
- let line = chalk28.bold(`DataSources in ${projectId}: `) + `${r.totalSources} total, ${r.scheduledSources} scheduled, ${r.sourcesWithRecentFailure} failing recently`;
7615
+ let line = chalk26.bold(`DataSources in ${projectId}: `) + `${r.totalSources} total, ${r.scheduledSources} scheduled, ${r.sourcesWithRecentFailure} failing recently`;
6485
7616
  if (r.lastActivityAt) line += `, last activity ${r.lastActivityAt}`;
6486
7617
  console.log(line);
6487
7618
  if (dashboard.sources.length === 0) {
6488
- console.log(chalk28.dim("No data sources."));
7619
+ empty("data sources");
6489
7620
  return;
6490
7621
  }
6491
7622
  format(dashboard.sources.map(dashboardTableRow), {
6492
7623
  format: outputFormat,
6493
- columns: ["id", "name", "type", "schedule", "lastStatus", "lastRunAt", "nextScheduledAt", "recentFailures", "lastTransferred"]
7624
+ columns: [
7625
+ { key: "id", kind: "id" },
7626
+ { key: "name" },
7627
+ { key: "type" },
7628
+ { key: "schedule" },
7629
+ { key: "lastStatus", header: "last status", kind: "state" },
7630
+ { key: "lastRunAt", header: "last run", kind: "date" },
7631
+ { key: "nextScheduledAt", header: "next run", kind: "date" },
7632
+ { key: "recentFailures", header: "failures", kind: "number" },
7633
+ { key: "lastTransferred", header: "transferred" }
7634
+ ]
6494
7635
  });
6495
7636
  }
6496
7637
  async function createDataSource(options, cmd) {
@@ -6508,9 +7649,9 @@ async function createDataSource(options, cmd) {
6508
7649
  };
6509
7650
  const ds = await api.storage.createDataSource(request);
6510
7651
  if (outputFormat === "human") {
6511
- console.log(chalk28.green(`\u2713 Created data source ${ds.id}`));
6512
- console.log(chalk28.dim(` Last run: ${ds.lastRunStatus ?? "\u2014"}`));
6513
- if (ds.lastRunError) console.log(chalk28.dim(` Error: ${ds.lastRunError}`));
7652
+ success(`Created data source ${ds.id}`);
7653
+ console.log(chalk26.dim(` Last run: ${ds.lastRunStatus ?? "\u2014"}`));
7654
+ if (ds.lastRunError) console.log(chalk26.dim(` Error: ${ds.lastRunError}`));
6514
7655
  } else {
6515
7656
  format(ds, { format: outputFormat });
6516
7657
  }
@@ -6540,7 +7681,7 @@ async function updateDataSource(id, options, cmd) {
6540
7681
  const api = createApiClient();
6541
7682
  const ds = await api.storage.updateDataSource(id, request);
6542
7683
  if (outputFormat === "human") {
6543
- console.log(chalk28.green(`\u2713 Updated data source ${ds.id}`));
7684
+ success(`Updated data source ${ds.id}`);
6544
7685
  } else {
6545
7686
  format(ds, { format: outputFormat });
6546
7687
  }
@@ -6548,15 +7689,15 @@ async function updateDataSource(id, options, cmd) {
6548
7689
  async function deleteDataSource(id) {
6549
7690
  const api = createApiClient();
6550
7691
  await api.storage.deleteDataSource(id);
6551
- console.log(chalk28.green(`\u2713 Deleted data source ${id}`));
7692
+ success(`Deleted data source ${id}`);
6552
7693
  }
6553
7694
  async function refreshDataSource(id, cmd) {
6554
7695
  const outputFormat = getOutputFormat16(cmd);
6555
7696
  const api = createApiClient();
6556
7697
  const run = await api.storage.refreshDataSource(id);
6557
7698
  if (outputFormat === "human") {
6558
- console.log(chalk28.green(`\u2713 Refresh queued \u2014 run ${run.runId}, status ${run.status}`));
6559
- if (run.errorMessage) console.log(chalk28.red(` Error: ${run.errorMessage}`));
7699
+ success(`Refresh queued \u2014 run ${run.runId}, status ${run.status}`);
7700
+ if (run.errorMessage) console.log(chalk26.red(` Error: ${run.errorMessage}`));
6560
7701
  } else {
6561
7702
  format(run, { format: outputFormat });
6562
7703
  }
@@ -6566,12 +7707,21 @@ async function listRuns2(id, limit, cmd) {
6566
7707
  const api = createApiClient();
6567
7708
  const runs = await api.storage.listDataSourceRuns(id, limit);
6568
7709
  if (outputFormat === "human" && runs.length === 0) {
6569
- console.log(chalk28.dim("No runs yet."));
7710
+ empty("runs yet");
6570
7711
  return;
6571
7712
  }
6572
7713
  format(runs.map(runTableRow), {
6573
7714
  format: outputFormat,
6574
- columns: ["runId", "status", "startedAt", "finishedAt", "rows", "transferred", "credits", "triggeredBy"]
7715
+ columns: [
7716
+ { key: "runId", kind: "id" },
7717
+ { key: "status", kind: "state" },
7718
+ { key: "startedAt", header: "started", kind: "date" },
7719
+ { key: "finishedAt", header: "finished", kind: "date" },
7720
+ { key: "rows", kind: "number" },
7721
+ { key: "transferred" },
7722
+ { key: "credits" },
7723
+ { key: "triggeredBy", header: "triggered by" }
7724
+ ]
6575
7725
  });
6576
7726
  }
6577
7727
  async function getRun(id, runId, cmd) {
@@ -6586,7 +7736,7 @@ async function listConnectorTypes(cmd) {
6586
7736
  const types = await api.storage.listDataSourceConnectorTypes();
6587
7737
  if (outputFormat === "human") {
6588
7738
  if (types.length === 0) {
6589
- console.log(chalk28.dim("No connector types registered."));
7739
+ empty("connector types registered");
6590
7740
  return;
6591
7741
  }
6592
7742
  for (const t of types) console.log(t);
@@ -6596,9 +7746,13 @@ async function listConnectorTypes(cmd) {
6596
7746
  }
6597
7747
  function registerDataSourcesCommands(program) {
6598
7748
  const dataSources = program.command("data-sources").description("Manage scheduled DataSource imports (Google Sheets, S3 URL, JDBC)");
6599
- dataSources.command("list").description("List data sources (optionally scoped to a project)").option("--project-id <id>", "Filter by project ID").action(async (options, cmd) => {
7749
+ dataSources.command("list").description("List the data sources of one project").option("--project <id>", "Project ID; defaults to defaults.project from the config").addHelpText("after", `
7750
+ Examples:
7751
+ $ diafunc data-sources list --project <id>
7752
+ $ diafunc config set defaults.project <id> then --project can be omitted
7753
+ `).action(async (options, cmd) => {
6600
7754
  try {
6601
- await listDataSources(options.projectId, cmd);
7755
+ await listDataSources(resolveProjectId(options.project, cmd), cmd);
6602
7756
  } catch (error) {
6603
7757
  handleError(error);
6604
7758
  }
@@ -6670,7 +7824,7 @@ function registerDataSourcesCommands(program) {
6670
7824
  }
6671
7825
 
6672
7826
  // src/commands/table-exporters/index.ts
6673
- import chalk29 from "chalk";
7827
+ import chalk27 from "chalk";
6674
7828
  function getOutputFormat17(cmd) {
6675
7829
  const config = loadConfig();
6676
7830
  const globalOpts = cmd.optsWithGlobals();
@@ -6701,7 +7855,7 @@ function registerTableExportersCommands(program) {
6701
7855
  format: outputFormat,
6702
7856
  columns: ["id", "name", "format", "extension", "mimeType", "priority", "function", "createdBy"]
6703
7857
  });
6704
- console.log(chalk29.dim(`${list.length} exporter(s)`));
7858
+ console.log(chalk27.dim(`${list.length} exporter(s)`));
6705
7859
  } catch (error) {
6706
7860
  handleError(error);
6707
7861
  }
@@ -6713,7 +7867,7 @@ function registerTableExportersCommands(program) {
6713
7867
  const list = await api.storage.listUserDefinedExporters();
6714
7868
  const exporter = list.find((e) => e.id === id);
6715
7869
  if (!exporter) {
6716
- console.error(chalk29.red(`No exporter with id="${id}".`));
7870
+ failure(`No exporter with id="${id}".`);
6717
7871
  process.exit(1);
6718
7872
  }
6719
7873
  format(exporter, { format: outputFormat });
@@ -6742,7 +7896,7 @@ function registerTableExportersCommands(program) {
6742
7896
  format(created, { format: outputFormat });
6743
7897
  return;
6744
7898
  }
6745
- console.log(chalk29.green(`Registered exporter "${created.name}" (id=${created.id}, format=${created.format})`));
7899
+ success(`Registered exporter "${created.name}" (id=${created.id}, format=${created.format})`);
6746
7900
  } catch (error) {
6747
7901
  handleError(error);
6748
7902
  }
@@ -6751,7 +7905,7 @@ function registerTableExportersCommands(program) {
6751
7905
  try {
6752
7906
  const api = createApiClient();
6753
7907
  await api.storage.deleteUserDefinedExporter(id);
6754
- console.log(chalk29.green(`Deleted exporter id=${id}`));
7908
+ success(`Deleted exporter id=${id}`);
6755
7909
  } catch (error) {
6756
7910
  handleError(error);
6757
7911
  }
@@ -6759,14 +7913,14 @@ function registerTableExportersCommands(program) {
6759
7913
  }
6760
7914
 
6761
7915
  // src/commands/skeleton/index.ts
6762
- import chalk30 from "chalk";
7916
+ import chalk28 from "chalk";
6763
7917
  import * as fs9 from "fs";
6764
7918
  function getOutputFormat18(cmd) {
6765
7919
  const config = loadConfig();
6766
7920
  const globalOpts = cmd.optsWithGlobals();
6767
7921
  return globalOpts.output ?? config.defaults.output ?? "human";
6768
7922
  }
6769
- function resolveProjectId(localOption, cmd) {
7923
+ function resolveProjectId2(localOption, cmd) {
6770
7924
  if (localOption) return localOption;
6771
7925
  const globalOpts = cmd.optsWithGlobals();
6772
7926
  if (globalOpts.project) return globalOpts.project;
@@ -6812,7 +7966,7 @@ function skeletonTableRow(s) {
6812
7966
  }
6813
7967
  async function createSkeleton(options, cmd) {
6814
7968
  const outputFormat = getOutputFormat18(cmd);
6815
- const projectId = resolveProjectId(options.project, cmd);
7969
+ const projectId = resolveProjectId2(options.project, cmd);
6816
7970
  const template = resolveTemplate(options.template);
6817
7971
  const weight = parseWeight(options.weight);
6818
7972
  const request = {
@@ -6825,22 +7979,22 @@ async function createSkeleton(options, cmd) {
6825
7979
  const api = createApiClient();
6826
7980
  const skeleton = await api.storage.createSkeleton(request);
6827
7981
  if (outputFormat === "human") {
6828
- console.log(chalk30.green(`\u2713 Created skeleton ${skeleton.id}`));
6829
- console.log(chalk30.dim(` name: ${skeleton.name}`));
6830
- console.log(chalk30.dim(` template: ${skeleton.template}`));
6831
- console.log(chalk30.dim(` paramCount: ${skeleton.paramCount}`));
6832
- console.log(chalk30.dim(` weight: ${skeleton.weight}`));
7982
+ success(`Created skeleton ${skeleton.id}`);
7983
+ console.log(chalk28.dim(` name: ${skeleton.name}`));
7984
+ console.log(chalk28.dim(` template: ${skeleton.template}`));
7985
+ console.log(chalk28.dim(` paramCount: ${skeleton.paramCount}`));
7986
+ console.log(chalk28.dim(` weight: ${skeleton.weight}`));
6833
7987
  } else {
6834
7988
  format(skeleton, { format: outputFormat });
6835
7989
  }
6836
7990
  }
6837
7991
  async function listSkeletons(localProject, cmd) {
6838
7992
  const outputFormat = getOutputFormat18(cmd);
6839
- const projectId = resolveProjectId(localProject, cmd);
7993
+ const projectId = resolveProjectId2(localProject, cmd);
6840
7994
  const api = createApiClient();
6841
7995
  const skeletons = await api.storage.listSkeletons(projectId);
6842
7996
  if (outputFormat === "human" && skeletons.length === 0) {
6843
- console.log(chalk30.dim(`No skeletons in project ${projectId}.`));
7997
+ empty(`skeletons in project ${projectId}`);
6844
7998
  return;
6845
7999
  }
6846
8000
  format(skeletons.map(skeletonTableRow), {
@@ -6867,11 +8021,11 @@ async function updateSkeleton(id, options, cmd) {
6867
8021
  const api = createApiClient();
6868
8022
  const skeleton = await api.storage.updateSkeleton(id, request);
6869
8023
  if (outputFormat === "human") {
6870
- console.log(chalk30.green(`\u2713 Updated skeleton ${skeleton.id}`));
6871
- console.log(chalk30.dim(` name: ${skeleton.name}`));
6872
- console.log(chalk30.dim(` template: ${skeleton.template}`));
6873
- console.log(chalk30.dim(` paramCount: ${skeleton.paramCount}`));
6874
- console.log(chalk30.dim(` weight: ${skeleton.weight}`));
8024
+ success(`Updated skeleton ${skeleton.id}`);
8025
+ console.log(chalk28.dim(` name: ${skeleton.name}`));
8026
+ console.log(chalk28.dim(` template: ${skeleton.template}`));
8027
+ console.log(chalk28.dim(` paramCount: ${skeleton.paramCount}`));
8028
+ console.log(chalk28.dim(` weight: ${skeleton.weight}`));
6875
8029
  } else {
6876
8030
  format(skeleton, { format: outputFormat });
6877
8031
  }
@@ -6879,10 +8033,15 @@ async function updateSkeleton(id, options, cmd) {
6879
8033
  async function deleteSkeleton(id) {
6880
8034
  const api = createApiClient();
6881
8035
  await api.storage.deleteSkeleton(id);
6882
- console.log(chalk30.green(`\u2713 Deleted skeleton ${id}`));
8036
+ success(`Deleted skeleton ${id}`);
6883
8037
  }
6884
8038
  function registerSkeletonCommands(program) {
6885
- const skeleton = program.command("skeleton").description("Manage user-provided skeleton templates (project-scoped, capped at 100/project)");
8039
+ const skeleton = program.command("skeleton").description("Manage user-provided skeleton templates (project-scoped, capped at 100/project)").addHelpText("after", `
8040
+ Examples:
8041
+ $ diafunc skeleton list --project <id>
8042
+ $ diafunc skeleton create --project <id> --name linear --template 'a*x+b'
8043
+ `);
8044
+ ;
6886
8045
  skeleton.command("create").description("Create a skeleton. Parse errors from the engine are surfaced as stderr.").requiredOption("--name <name>", "Display name").requiredOption(
6887
8046
  "--template <expr>",
6888
8047
  'Skeleton template expression (e.g. "?*x+?"). Use "@file.txt" to read from a file; "@@\u2026" escapes a literal leading @.'
@@ -7183,7 +8342,7 @@ function registerCompletionCommand(program) {
7183
8342
  }
7184
8343
 
7185
8344
  // src/commands/whoami/index.ts
7186
- import chalk31 from "chalk";
8345
+ import chalk29 from "chalk";
7187
8346
  function registerWhoamiCommand(program) {
7188
8347
  program.command("whoami").description("Show the currently authenticated user").action(async (_options, cmd) => {
7189
8348
  try {
@@ -7193,8 +8352,8 @@ function registerWhoamiCommand(program) {
7193
8352
  const api = createApiClient();
7194
8353
  const user = await api.admin.getMyUser();
7195
8354
  if (outputFormat === "human") {
7196
- console.log(chalk31.bold(user.name) + chalk31.dim(` <${user.email}>`));
7197
- console.log(chalk31.dim(` Role: ${user.role} \xB7 Remaining credits: ${user.remainingCredits} \xB7 Profile: ${config.currentProfile}`));
8355
+ console.log(chalk29.bold(user.name) + chalk29.dim(` <${user.email}>`));
8356
+ console.log(chalk29.dim(` Role: ${user.role} \xB7 Remaining credits: ${user.remainingCredits} \xB7 Profile: ${config.currentProfile}`));
7198
8357
  } else {
7199
8358
  format(user, { format: outputFormat });
7200
8359
  }
@@ -7205,33 +8364,45 @@ function registerWhoamiCommand(program) {
7205
8364
  }
7206
8365
 
7207
8366
  // src/commands/utilization/index.ts
7208
- import chalk32 from "chalk";
8367
+ import chalk30 from "chalk";
7209
8368
  function getOutputFormat19(cmd) {
7210
8369
  const config = loadConfig();
7211
8370
  const globalOpts = cmd.optsWithGlobals();
7212
8371
  return globalOpts.output ?? config.defaults.output ?? "human";
7213
8372
  }
7214
- function printUtilizationHuman(u, label) {
7215
- const when = u.day !== null && u.day !== void 0 ? `${u.year}-${String(u.month).padStart(2, "0")}-${String(u.day).padStart(2, "0")}` : `${u.year}-${String(u.month).padStart(2, "0")}`;
7216
- if (label) {
7217
- console.log(chalk32.bold(label) + " " + chalk32.dim(when));
7218
- } else {
7219
- console.log(chalk32.bold(when));
8373
+ function windowLabel(u) {
8374
+ if (u.cycleStart) {
8375
+ return u.cycleEnd ? `billing cycle ${u.cycleStart} to ${u.cycleEnd}` : `billing cycle from ${u.cycleStart}`;
8376
+ }
8377
+ if (u.day !== null && u.day !== void 0) {
8378
+ return `${u.year}-${String(u.month).padStart(2, "0")}-${String(u.day).padStart(2, "0")}`;
7220
8379
  }
8380
+ return `billing cycle ${u.year}-${String(u.month).padStart(2, "0")}`;
8381
+ }
8382
+ function printUtilizationHuman(u, label) {
8383
+ const when = windowLabel(u);
8384
+ console.log(label ? chalk30.bold(label) + " " + chalk30.dim(when) : chalk30.bold(when));
7221
8385
  if (u.types.length === 0) {
7222
- console.log(chalk32.dim(" (no usage)"));
8386
+ console.log(chalk30.dim(" (no usage)"));
7223
8387
  return;
7224
8388
  }
7225
- for (const t of u.types) {
7226
- console.log(
7227
- ` ${t.type.padEnd(24)} ${chalk32.cyan(String(t.quantity).padStart(10))} ${chalk32.dim("credits:")} ${t.credits.toFixed(2)}`
7228
- );
8389
+ const types = [...u.types].sort((a, b) => b.credits - a.credits);
8390
+ const width = Math.max(...types.map((t) => t.type.length));
8391
+ for (const t of types) {
8392
+ const line = ` ${t.type.padEnd(width)} ${formatNumber(t.quantity).padStart(12)} ${chalk30.dim("credits")} ${t.credits.toFixed(2).padStart(10)}`;
8393
+ console.log(t.credits === 0 ? chalk30.dim(line) : line);
7229
8394
  }
7230
8395
  const total = u.totalCredits ?? u.types.reduce((s, t) => s + t.credits, 0);
7231
- console.log(chalk32.bold(` Total credits: ${total.toFixed(2)}`));
8396
+ console.log(chalk30.bold(` ${"Total".padEnd(width)} ${" ".repeat(12)} ${chalk30.dim("credits")} ${total.toFixed(2).padStart(10)}`));
7232
8397
  }
7233
8398
  function registerUtilizationCommand(program) {
7234
- const util = program.command("utilization").description("Show credit utilization");
8399
+ const util = program.command("utilization").description("Show credit utilization for the current billing cycle").addHelpText("after", `
8400
+ The billing cycle starts on your subscription anniversary, not on the first of the month.
8401
+
8402
+ Examples:
8403
+ $ diafunc utilization this cycle, by consumption type
8404
+ $ diafunc utilization history day by day across the cycle
8405
+ `);
7235
8406
  util.command("actual", { isDefault: true }).description("Show current utilization (default subcommand)").action(async (_options, cmd) => {
7236
8407
  try {
7237
8408
  const outputFormat = getOutputFormat19(cmd);
@@ -7253,7 +8424,7 @@ function registerUtilizationCommand(program) {
7253
8424
  const history = await api.admin.getUtilizationHistory();
7254
8425
  if (outputFormat === "human") {
7255
8426
  if (history.length === 0) {
7256
- console.log(chalk32.dim("No usage recorded."));
8427
+ empty("usage recorded");
7257
8428
  return;
7258
8429
  }
7259
8430
  for (const u of history) {
@@ -7270,7 +8441,6 @@ function registerUtilizationCommand(program) {
7270
8441
  }
7271
8442
 
7272
8443
  // src/commands/entity-branch/index.ts
7273
- import chalk33 from "chalk";
7274
8444
  function getOutputFormat20(cmd) {
7275
8445
  const config = loadConfig();
7276
8446
  const globalOpts = cmd.optsWithGlobals();
@@ -7314,7 +8484,7 @@ function registerEntityBranchCommands(program) {
7314
8484
  sourceEntityBranch: resolved.entityBranch,
7315
8485
  targetEntityBranch: targetBranch
7316
8486
  });
7317
- console.log(chalk33.green(`Entity branch "${targetBranch}" created from "${resolved.entityBranch}".`));
8487
+ success(`Entity branch "${targetBranch}" created from "${resolved.entityBranch}".`);
7318
8488
  } catch (error) {
7319
8489
  handleError(error);
7320
8490
  }
@@ -7322,18 +8492,37 @@ function registerEntityBranchCommands(program) {
7322
8492
  }
7323
8493
 
7324
8494
  // src/commands/subscription/index.ts
8495
+ var BILLING_INTERNALS = /* @__PURE__ */ new Set([
8496
+ "stripeSubscriptionId",
8497
+ "stripePriceId",
8498
+ "stripeCustomerId",
8499
+ "dunningStage",
8500
+ "dunningStartedAt",
8501
+ "nextRetryAt"
8502
+ ]);
8503
+ function forReader(subscription) {
8504
+ if (!subscription || typeof subscription !== "object") return subscription;
8505
+ return Object.fromEntries(
8506
+ Object.entries(subscription).filter(([key]) => !BILLING_INTERNALS.has(key))
8507
+ );
8508
+ }
7325
8509
  function getOutputFormat21(cmd) {
7326
8510
  const config = loadConfig();
7327
8511
  const globalOpts = cmd.optsWithGlobals();
7328
8512
  return globalOpts.output ?? config.defaults.output ?? "human";
7329
8513
  }
7330
8514
  function registerSubscriptionCommand(program) {
7331
- const sub = program.command("subscription").description("View subscription info");
8515
+ const sub = program.command("subscription").description("View subscription info").addHelpText("after", `
8516
+ Examples:
8517
+ $ diafunc subscription current plan, term and billing interval
8518
+ $ diafunc subscription current -o json including the billing-integration fields
8519
+ `);
7332
8520
  sub.command("current", { isDefault: true }).description("Show the current subscription").action(async (_options, cmd) => {
7333
8521
  try {
7334
8522
  const api = createApiClient();
8523
+ const outputFormat = getOutputFormat21(cmd);
7335
8524
  const s = await api.admin.getCurrentSubscription();
7336
- format(s, { format: getOutputFormat21(cmd) });
8525
+ format(outputFormat === "human" ? forReader(s) : s, { format: outputFormat });
7337
8526
  } catch (error) {
7338
8527
  handleError(error);
7339
8528
  }
@@ -7341,8 +8530,9 @@ function registerSubscriptionCommand(program) {
7341
8530
  sub.command("next").description("Show the next (upcoming) subscription").action(async (_options, cmd) => {
7342
8531
  try {
7343
8532
  const api = createApiClient();
8533
+ const outputFormat = getOutputFormat21(cmd);
7344
8534
  const s = await api.admin.getNextSubscription();
7345
- format(s, { format: getOutputFormat21(cmd) });
8535
+ format(outputFormat === "human" ? forReader(s) : s, { format: outputFormat });
7346
8536
  } catch (error) {
7347
8537
  handleError(error);
7348
8538
  }
@@ -7359,7 +8549,6 @@ function registerSubscriptionCommand(program) {
7359
8549
  }
7360
8550
 
7361
8551
  // src/commands/invoice/index.ts
7362
- import chalk34 from "chalk";
7363
8552
  import * as fs10 from "fs";
7364
8553
  function getOutputFormat22(cmd) {
7365
8554
  const config = loadConfig();
@@ -7367,14 +8556,26 @@ function getOutputFormat22(cmd) {
7367
8556
  return globalOpts.output ?? config.defaults.output ?? "human";
7368
8557
  }
7369
8558
  function registerInvoiceCommand(program) {
7370
- const invoice = program.command("invoice").description("View and download invoices");
8559
+ const invoice = program.command("invoice").description("View and download invoices").addHelpText("after", `
8560
+ Examples:
8561
+ $ diafunc invoice list
8562
+ $ diafunc invoice download 120 invoice-120.pdf
8563
+ `);
8564
+ ;
7371
8565
  invoice.command("list").description("List your invoices").action(async (_options, cmd) => {
7372
8566
  try {
7373
8567
  const api = createApiClient();
7374
8568
  const invoices = await api.admin.getInvoices();
7375
8569
  format(invoices, {
7376
8570
  format: getOutputFormat22(cmd),
7377
- columns: ["invoiceNumber", "issued", "periodFrom", "periodTo", "total", "status"]
8571
+ columns: [
8572
+ { key: "invoiceNumber", header: "number" },
8573
+ { key: "issued", kind: "date" },
8574
+ { key: "periodFrom", header: "from" },
8575
+ { key: "periodTo", header: "to" },
8576
+ { key: "total", kind: "number" },
8577
+ { key: "status", kind: "state" }
8578
+ ]
7378
8579
  });
7379
8580
  } catch (error) {
7380
8581
  handleError(error);
@@ -7387,7 +8588,7 @@ function registerInvoiceCommand(program) {
7387
8588
  const buffer = Buffer.from(await response.arrayBuffer());
7388
8589
  const outPath = options.out ?? fileName;
7389
8590
  fs10.writeFileSync(outPath, buffer);
7390
- console.log(chalk34.green(`Invoice saved to ${outPath}`));
8591
+ success(`Invoice saved to ${outPath}`);
7391
8592
  } catch (error) {
7392
8593
  handleError(error);
7393
8594
  }
@@ -7395,12 +8596,12 @@ function registerInvoiceCommand(program) {
7395
8596
  }
7396
8597
 
7397
8598
  // src/commands/shell/index.ts
7398
- import chalk35 from "chalk";
8599
+ import chalk31 from "chalk";
7399
8600
  import * as fs11 from "fs";
7400
8601
  import * as os3 from "os";
7401
8602
  import * as path8 from "path";
7402
8603
  import { spawn as spawn3 } from "child_process";
7403
- import { randomUUID as randomUUID3 } from "crypto";
8604
+ import { randomUUID as randomUUID2 } from "crypto";
7404
8605
  function extensionFor2(language) {
7405
8606
  const l = language.toLowerCase();
7406
8607
  if (l === "java") return "java";
@@ -7411,7 +8612,7 @@ function extensionFor2(language) {
7411
8612
  return "txt";
7412
8613
  }
7413
8614
  async function openInEditor(initial, ext) {
7414
- const tmpFile = path8.join(os3.tmpdir(), `diafunc-shell-${randomUUID3()}.${ext}`);
8615
+ const tmpFile = path8.join(os3.tmpdir(), `diafunc-shell-${randomUUID2()}.${ext}`);
7415
8616
  fs11.writeFileSync(tmpFile, initial);
7416
8617
  const editor = process.env.VISUAL ?? process.env.EDITOR ?? "vi";
7417
8618
  await new Promise((resolve, reject) => {
@@ -7443,7 +8644,7 @@ async function evaluate(api, fnRef, language, sourceCode) {
7443
8644
  sourceCode
7444
8645
  });
7445
8646
  await api.storage.saveEntities([entity]);
7446
- const evaluationId = randomUUID3();
8647
+ const evaluationId = timeUuid();
7447
8648
  const nowParts = utcNowParts();
7448
8649
  const result = await api.evaluation.call({
7449
8650
  evaluationId,
@@ -7461,31 +8662,31 @@ async function evaluate(api, fnRef, language, sourceCode) {
7461
8662
  }, false);
7462
8663
  if (result.outputs?.length) {
7463
8664
  for (const out of result.outputs) {
7464
- console.log(chalk35.dim(` [${out.type}]`) + " " + out.output);
8665
+ console.log(chalk31.dim(` [${out.type}]`) + " " + out.output);
7465
8666
  }
7466
8667
  }
7467
8668
  if (result.successful) {
7468
8669
  if (result.result) {
7469
- console.log(chalk35.green("=> ") + result.result);
8670
+ console.log(chalk31.green("=>") + " " + result.result);
7470
8671
  } else {
7471
- console.log(chalk35.dim("=> (no value)"));
8672
+ console.log(chalk31.dim("=> (no value)"));
7472
8673
  }
7473
8674
  const duration = result.completed - result.started;
7474
- console.log(chalk35.dim(` [${duration}ms \xB7 ${evaluationId}]`));
8675
+ console.log(chalk31.dim(` [${duration}ms \xB7 ${evaluationId}]`));
7475
8676
  } else {
7476
- console.log(chalk35.red("error: ") + result.error);
8677
+ console.log(chalk31.red("error: ") + result.error);
7477
8678
  if (result.lineNumber > 0) {
7478
- console.log(chalk35.dim(` at line ${result.lineNumber}, col ${result.columnNumber}`));
8679
+ console.log(chalk31.dim(` at line ${result.lineNumber}, col ${result.columnNumber}`));
7479
8680
  }
7480
8681
  }
7481
8682
  }
7482
8683
  function registerShellCommand(program) {
7483
- program.command("shell").description("Interactive REPL for function code evaluation").option("--function <ref>", "Function entity reference to use as scratch (required)").option("--language <lang>", "Source language", "JavaScript").action(async (options, cmd) => {
8684
+ program.command("shell").description("Interactive REPL for function code evaluation").option("--function <ref>", "Function entity reference to use as scratch (required)").option("--language <lang>", "Source language; defaults to the project's language").action(async (options, cmd) => {
7484
8685
  try {
7485
8686
  if (!options.function) {
7486
- console.error(chalk35.red("Missing --function <ref>."));
7487
- console.error(chalk35.dim("Pass an existing or new function entity reference to use as the shell target."));
7488
- console.error(chalk35.dim("Example: diafunc shell --function my-project/main/scratch/main --language JavaScript"));
8687
+ failure("Missing --function <ref>.");
8688
+ hint("Pass an existing or new function entity reference to use as the shell target.");
8689
+ hint("Example: diafunc shell --function my-project/main/scratch/main --language Kotlin");
7489
8690
  process.exit(1);
7490
8691
  }
7491
8692
  const config = loadConfig();
@@ -7496,18 +8697,19 @@ function registerShellCommand(program) {
7496
8697
  });
7497
8698
  const api = createApiClient();
7498
8699
  const { input: promptInput } = await import("@inquirer/prompts");
7499
- const { getUpdateNotice } = await import("./update-check-L55QNPYQ.js");
7500
- console.log(chalk35.bold("Diafunc shell") + chalk35.dim(` \xB7 function ${fnRef.entityId} \xB7 ${options.language}`));
7501
- console.log(chalk35.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
7502
- console.log(chalk35.dim("Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit"));
8700
+ const { getUpdateNotice } = await import("./update-check-4RHYIJHZ.js");
8701
+ const resolvedLanguage = await resolveLanguage(api, fnRef.projectId, options.language);
8702
+ console.log(chalk31.bold("Diafunc shell") + chalk31.dim(` \xB7 function ${fnRef.entityId} \xB7 ${resolvedLanguage}`));
8703
+ console.log(chalk31.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
8704
+ console.log(chalk31.dim("Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit"));
7503
8705
  const notice = await getUpdateNotice();
7504
- if (notice) console.log(chalk35.dim(notice));
8706
+ if (notice) console.log(chalk31.dim(notice));
7505
8707
  console.log();
7506
- let language = options.language;
8708
+ let language = resolvedLanguage;
7507
8709
  for (; ; ) {
7508
8710
  let line;
7509
8711
  try {
7510
- line = await promptInput({ message: chalk35.cyan.bold(`${language} >`) });
8712
+ line = await promptInput({ message: chalk31.cyan.bold(`${language} >`) });
7511
8713
  } catch {
7512
8714
  console.log();
7513
8715
  return;
@@ -7525,54 +8727,54 @@ function registerShellCommand(program) {
7525
8727
  case "help":
7526
8728
  case "h":
7527
8729
  case "?":
7528
- console.log(chalk35.dim(" /edit open $EDITOR for multi-line code"));
7529
- console.log(chalk35.dim(" /file <path> evaluate the contents of a file"));
7530
- console.log(chalk35.dim(" /lang <name> switch language (Java, JavaScript, Kotlin, Python, Scala)"));
7531
- console.log(chalk35.dim(" /quit exit the shell"));
8730
+ console.log(chalk31.dim(" /edit open $EDITOR for multi-line code"));
8731
+ console.log(chalk31.dim(" /file <path> evaluate the contents of a file"));
8732
+ console.log(chalk31.dim(" /lang <name> switch language (Java, JavaScript, Kotlin, Python, Scala)"));
8733
+ console.log(chalk31.dim(" /quit exit the shell"));
7532
8734
  continue;
7533
8735
  case "lang":
7534
8736
  if (arg) language = arg;
7535
- console.log(chalk35.dim(`Language: ${language}`));
8737
+ console.log(chalk31.dim(`Language: ${language}`));
7536
8738
  continue;
7537
8739
  case "edit": {
7538
8740
  const sourceCode = await openInEditor("", extensionFor2(language));
7539
8741
  if (!sourceCode.trim()) {
7540
- console.log(chalk35.dim("(empty \u2014 not evaluated)"));
8742
+ console.log(chalk31.dim("(empty \u2014 not evaluated)"));
7541
8743
  continue;
7542
8744
  }
7543
8745
  try {
7544
8746
  await evaluate(api, fnRef, language, sourceCode);
7545
8747
  } catch (e) {
7546
- console.error(chalk35.red(e.message));
8748
+ console.error(chalk31.red(e.message));
7547
8749
  }
7548
8750
  continue;
7549
8751
  }
7550
8752
  case "file": {
7551
8753
  if (!arg) {
7552
- console.log(chalk35.dim("usage: /file <path>"));
8754
+ console.log(chalk31.dim("usage: /file <path>"));
7553
8755
  continue;
7554
8756
  }
7555
8757
  if (!fs11.existsSync(arg)) {
7556
- console.log(chalk35.red(`file not found: ${arg}`));
8758
+ console.log(chalk31.red(`file not found: ${arg}`));
7557
8759
  continue;
7558
8760
  }
7559
8761
  const sourceCode = fs11.readFileSync(arg, "utf-8");
7560
8762
  try {
7561
8763
  await evaluate(api, fnRef, language, sourceCode);
7562
8764
  } catch (e) {
7563
- console.error(chalk35.red(e.message));
8765
+ console.error(chalk31.red(e.message));
7564
8766
  }
7565
8767
  continue;
7566
8768
  }
7567
8769
  default:
7568
- console.log(chalk35.dim(`Unknown command: /${cmd2}. Try /help.`));
8770
+ console.log(chalk31.dim(`Unknown command: /${cmd2}. Try /help.`));
7569
8771
  continue;
7570
8772
  }
7571
8773
  }
7572
8774
  try {
7573
8775
  await evaluate(api, fnRef, language, trimmed);
7574
8776
  } catch (e) {
7575
- console.error(chalk35.red(e.message));
8777
+ console.error(chalk31.red(e.message));
7576
8778
  }
7577
8779
  }
7578
8780
  } catch (error) {
@@ -7582,7 +8784,7 @@ function registerShellCommand(program) {
7582
8784
  }
7583
8785
 
7584
8786
  // src/commands/update/index.ts
7585
- import chalk36 from "chalk";
8787
+ import chalk32 from "chalk";
7586
8788
  import * as path9 from "path";
7587
8789
  import { spawn as spawn4 } from "child_process";
7588
8790
 
@@ -7628,14 +8830,14 @@ function registerUpdateCommand(program) {
7628
8830
  const install = detectInstall();
7629
8831
  const latest = await fetchLatestVersion();
7630
8832
  if (latest === package_default.version) {
7631
- console.log(chalk36.dim(`diafunc is already at the latest version (${package_default.version}).`));
8833
+ console.log(chalk32.dim(`diafunc is already at the latest version (${package_default.version}).`));
7632
8834
  return;
7633
8835
  }
7634
- console.log(chalk36.dim(`Current: ${package_default.version} \u2192 Available: ${latest}`));
8836
+ console.log(chalk32.dim(`Current: ${package_default.version} \u2192 Available: ${latest}`));
7635
8837
  if (install.method === "npm") {
7636
8838
  console.log();
7637
8839
  console.log("Installed via npm. Upgrade with:");
7638
- console.log(chalk36.bold(` npm install -g @diafunc/cli@${latest}`));
8840
+ console.log(chalk32.bold(` npm install -g @diafunc/cli@${latest}`));
7639
8841
  return;
7640
8842
  }
7641
8843
  const installDir = path9.dirname(install.binaryPath);
@@ -7649,7 +8851,7 @@ function registerUpdateCommand(program) {
7649
8851
  }
7650
8852
 
7651
8853
  // src/commands/uninstall/index.ts
7652
- import chalk37 from "chalk";
8854
+ import chalk33 from "chalk";
7653
8855
  import { spawn as spawn5 } from "child_process";
7654
8856
  import * as fs13 from "fs";
7655
8857
  import * as os4 from "os";
@@ -7661,11 +8863,11 @@ function registerUninstallCommand(program) {
7661
8863
  const configDir = path10.join(os4.homedir(), ".diafunc");
7662
8864
  if (install.method === "npm") {
7663
8865
  console.log("Installed via npm. Remove with:");
7664
- console.log(chalk37.bold(" npm uninstall -g @diafunc/cli"));
8866
+ console.log(chalk33.bold(" npm uninstall -g @diafunc/cli"));
7665
8867
  if (fs13.existsSync(configDir)) {
7666
8868
  console.log();
7667
8869
  console.log(`Config + credentials live at ${configDir} \u2014 remove manually with:`);
7668
- console.log(chalk37.bold(` rm -rf ${configDir}`));
8870
+ console.log(chalk33.bold(` rm -rf ${configDir}`));
7669
8871
  }
7670
8872
  return;
7671
8873
  }
@@ -7675,7 +8877,7 @@ function registerUninstallCommand(program) {
7675
8877
  default: false
7676
8878
  });
7677
8879
  if (!removeBinary) {
7678
- console.log(chalk37.dim("Aborted."));
8880
+ console.log(chalk33.dim("Aborted."));
7679
8881
  return;
7680
8882
  }
7681
8883
  let removeConfig = options.purge ?? false;
@@ -7687,7 +8889,7 @@ function registerUninstallCommand(program) {
7687
8889
  }
7688
8890
  if (removeConfig && fs13.existsSync(configDir)) {
7689
8891
  fs13.rmSync(configDir, { recursive: true, force: true });
7690
- console.log(chalk37.dim(`Removed ${configDir}`));
8892
+ console.log(chalk33.dim(`Removed ${configDir}`));
7691
8893
  }
7692
8894
  if (process.platform === "win32") {
7693
8895
  const cmd = `timeout /t 2 /nobreak >nul & del /f /q "${install.binaryPath}"`;
@@ -7697,13 +8899,13 @@ function registerUninstallCommand(program) {
7697
8899
  windowsHide: true
7698
8900
  });
7699
8901
  child.unref();
7700
- console.log(chalk37.dim(`Removing ${install.binaryPath} on exit...`));
8902
+ console.log(chalk33.dim(`Removing ${install.binaryPath} on exit...`));
7701
8903
  console.log();
7702
8904
  console.log("diafunc uninstalled.");
7703
8905
  return;
7704
8906
  }
7705
8907
  fs13.rmSync(install.binaryPath, { force: true });
7706
- console.log(chalk37.dim(`Removed ${install.binaryPath}`));
8908
+ console.log(chalk33.dim(`Removed ${install.binaryPath}`));
7707
8909
  console.log();
7708
8910
  console.log("diafunc uninstalled.");
7709
8911
  } catch (error) {
@@ -7713,14 +8915,38 @@ function registerUninstallCommand(program) {
7713
8915
  }
7714
8916
 
7715
8917
  // src/index.ts
8918
+ var HELP_EPILOGUE = `
8919
+ Getting started:
8920
+ $ diafunc auth login sign in
8921
+ $ diafunc analyze data.csv --targets price run an analysis and follow it
8922
+ $ diafunc analyze watch follow the latest run again
8923
+ $ diafunc analyze open open the finished notebook
8924
+
8925
+ Everyday:
8926
+ $ diafunc project list what you have
8927
+ $ diafunc search "housing" find it across every project
8928
+ $ diafunc chat ask the assistant
8929
+ $ diafunc status summary is the platform healthy
8930
+
8931
+ Output:
8932
+ Add --output json for scripting, or pipe any command to get tab-separated fields.
8933
+ Add --verbose to see the requests, --dry-run to preview a mutation.
8934
+
8935
+ Docs: https://diafunc.com/documentation
8936
+ `;
7716
8937
  function createProgram() {
7717
8938
  const program = new Command();
7718
- program.name("diafunc").description("Diafunc CLI \u2014 command-line interface for the Diafunc platform").version(package_default.version).option("-p, --profile <name>", "Profile to use").option("-o, --output <format>", "Output format: human, json, table").option("--project <id>", "Default project ID override").option("--branch <name>", "Default branch override").option("--dry-run", "Preview mutating operations without executing them").hook("preAction", (thisCommand) => {
8939
+ program.name("diafunc").description("Diafunc CLI \u2014 command-line interface for the Diafunc platform").version(package_default.version).option("-p, --profile <name>", "Profile to use").option("-o, --output <format>", "Output format: human, json, table (default: human)").option("--project <id>", "Default project ID override").option("--branch <name>", "Default branch override").option("--dry-run", "Preview mutating operations without executing them").option("--verbose", "Echo every HTTP request to stderr").option("--no-color", "Disable coloured output").showSuggestionAfterError().showHelpAfterError(`(run 'diafunc --help' to see the available commands)`).configureOutput({
8940
+ // Commander writes usage errors to stdout by default, which puts a complaint in the middle
8941
+ // of whatever a caller was capturing.
8942
+ writeErr: (str) => process.stderr.write(str)
8943
+ }).hook("preAction", (thisCommand) => {
7719
8944
  const opts = thisCommand.optsWithGlobals();
7720
- if (opts.dryRun) {
7721
- setDryRun(true);
7722
- }
8945
+ if (opts.dryRun) setDryRun(true);
8946
+ if (opts.verbose) setVerbose(true);
8947
+ if (opts.color === false) chalk34.level = 0;
7723
8948
  });
8949
+ program.addHelpText("after", HELP_EPILOGUE);
7724
8950
  registerAuthCommands(program);
7725
8951
  registerConfigCommands(program);
7726
8952
  registerProjectCommands(program);
@@ -7757,4 +8983,4 @@ function createProgram() {
7757
8983
  export {
7758
8984
  createProgram
7759
8985
  };
7760
- //# sourceMappingURL=chunk-2WJQPO4V.js.map
8986
+ //# sourceMappingURL=chunk-LRRLBTWM.js.map