@diafunc/cli 0.29.1 → 0.30.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.
package/README.md CHANGED
@@ -203,7 +203,7 @@ Nothing is asked when stdin or stdout is not a terminal, with `--output json`, o
203
203
  | `diafunc schedule` | Schedule function execution and list/stop scheduled runs |
204
204
  | `diafunc chat` | AI chat REPL (default), plus `send` / `stream` / `upload`, `usage`, and `session list/show/rename/delete` |
205
205
  | `diafunc search` | Search entities across projects; equally relevant results lead with the project whose model has the better quality, or the newest with `--sort newest` |
206
- | `diafunc analyze` | Run an automatic analysis on a data file and follow it live (interactive when run from a terminal), plus `list`, `get`, `watch`, `open`, `runs`, `cancel`, `upload`, `stop-import`, `visibility` (`--license` to publish), `presets`, `triggers`, and your private notes with `intent` (read into proposals that apply only when you confirm them), `expectations`, `charts` and `focus` (see [doc/analyze.md](./doc/analyze.md)) |
206
+ | `diafunc analyze` | Run an automatic analysis on a data file and follow it live (interactive when run from a terminal), plus `list`, `get`, `watch`, `open`, `report` (the report as Markdown), `export-model` (the model as code or a formula), `runs`, `cancel`, `upload`, `stop-import`, `visibility` (`--license` to publish), `presets`, `triggers`, and your private notes with `intent` (read into proposals that apply only when you confirm them), `expectations`, `charts` and `focus` (see [doc/analyze.md](./doc/analyze.md)) |
207
207
  | `diafunc public` | Read the analyses their owners made public, without signing in: `list` (paged, `--all`, `--changed-since`, with each one's license) and `show` (see [doc/public.md](./doc/public.md)) |
208
208
  | `diafunc license` | The licenses a public project can be published under, without signing in: `list` and `show`; `project create`, `analyze` and `analyze visibility` take `--license <id>` (see [doc/licenses.md](./doc/licenses.md)) |
209
209
  | `diafunc subscription` | View your current and upcoming subscription, plus available plans |
@@ -4,13 +4,13 @@ import {
4
4
  PromptCanceled,
5
5
  createProgram,
6
6
  handleError
7
- } from "../chunk-6QBACH4J.js";
7
+ } from "../chunk-5AB7E3K4.js";
8
8
  import {
9
9
  getUpdateNotice
10
- } from "../chunk-CSLLHHQU.js";
10
+ } from "../chunk-CL2LMFXH.js";
11
11
  import {
12
12
  package_default
13
- } from "../chunk-WZQ5LS2M.js";
13
+ } from "../chunk-GZI6AECR.js";
14
14
 
15
15
  // bin/diafunc.ts
16
16
  import chalk2 from "chalk";
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  package_default
3
- } from "./chunk-WZQ5LS2M.js";
3
+ } from "./chunk-GZI6AECR.js";
4
4
 
5
5
  // src/index.ts
6
6
  import chalk41 from "chalk";
@@ -2244,6 +2244,29 @@ function createAnalysisService(client) {
2244
2244
  path: `/${encodeURIComponent(analysisId)}/navigation`
2245
2245
  });
2246
2246
  },
2247
+ /**
2248
+ * The report as Markdown. Without `chapter`: the summary and the outline of chapter titles.
2249
+ * `chapter` is a title, or a path of titles separated by `>` (`Age > Correlation`). `maxBytes` is
2250
+ * clamped by the platform to 4-256 KiB, 32 KiB when absent. A chapter that does not fit comes in
2251
+ * parts; `part` (from 1) names the one to read and is ignored without `chapter`.
2252
+ */
2253
+ async getReportMarkdown(analysisId, options = {}) {
2254
+ return client.request({
2255
+ method: "GET",
2256
+ service: SERVICE2,
2257
+ path: `/${encodeURIComponent(analysisId)}/report.md`,
2258
+ query: { chapter: options.chapter, part: options.part, maxBytes: options.maxBytes }
2259
+ });
2260
+ },
2261
+ /** The model of one target as source code or a formula in `language`; `target` is needed when there are several. */
2262
+ async exportModel(analysisId, options) {
2263
+ return client.request({
2264
+ method: "GET",
2265
+ service: SERVICE2,
2266
+ path: `/${encodeURIComponent(analysisId)}/model-export`,
2267
+ query: { language: options.language, target: options.target }
2268
+ });
2269
+ },
2247
2270
  // ----- Runs -----------------------------------------------------------------------
2248
2271
  async runAnalysis(analysisId) {
2249
2272
  return client.request({
@@ -3411,7 +3434,16 @@ function createApiClient(options = {}) {
3411
3434
  }
3412
3435
 
3413
3436
  // src/commands/auth/token.ts
3414
- var VALID_RESOURCE_TYPES = ["project", "team"];
3437
+ var VALID_RESOURCE_TYPES = ["project", "team", "user"];
3438
+ function requireResourceUnlessPersonal(create) {
3439
+ const internals = create;
3440
+ const report = internals.missingMandatoryOptionValue.bind(create);
3441
+ internals.missingMandatoryOptionValue = (option) => {
3442
+ const type = String(create.getOptionValue("resourceType") ?? "").trim().toLowerCase();
3443
+ if (option.attributeName() === "resource" && type === "user") return;
3444
+ report(option);
3445
+ };
3446
+ }
3415
3447
  var VALID_SCOPES = [
3416
3448
  "project:read",
3417
3449
  "project:write",
@@ -3420,9 +3452,19 @@ var VALID_SCOPES = [
3420
3452
  "evaluation:read",
3421
3453
  "evaluation:execute"
3422
3454
  ];
3455
+ var TOKEN_CREATE_HELP = `
3456
+ A project token reaches one project, a team token the projects of one team. A personal token
3457
+ (--resource-type user) acts for your own account across the projects you can reach, limited by
3458
+ its scopes. No API token reaches account settings: password, sign-in methods, billing and tokens.
3459
+
3460
+ $ diafunc auth token create --name ci --resource <projectId> --scopes project:read,storage:read
3461
+ $ diafunc auth token create --name assistant --resource-type user --scopes project:read,project:write
3462
+ `;
3423
3463
  function registerTokenCommands(parent) {
3424
3464
  const token = parent.command("token").description("Manage API tokens");
3425
- token.command("create").description("Create a new API token").requiredOption("--name <name>", "Token name").requiredOption("--resource <id>", "Resource ID (project or team)").requiredOption("--scopes <scopes>", `Comma-separated scopes: ${VALID_SCOPES.join(", ")}`).option("--resource-type <type>", `Resource type: ${VALID_RESOURCE_TYPES.join(", ")}`, "project").option("--days <days>", "Validity in days (default: 365)", "365").action(async (options, cmd) => {
3465
+ const create = token.command("create").description("Create a new API token for a project, a team, or your own account").requiredOption("--name <name>", "Token name").requiredOption("--resource <id>", "Project or team ID (not needed with --resource-type user)").requiredOption("--scopes <scopes>", `Comma-separated scopes: ${VALID_SCOPES.join(", ")}`).option("--resource-type <type>", `Resource type: ${VALID_RESOURCE_TYPES.join(", ")}`, "project").option("--days <days>", "Validity in days (default: 365)", "365").addHelpText("after", TOKEN_CREATE_HELP);
3466
+ requireResourceUnlessPersonal(create);
3467
+ create.action(async (options, cmd) => {
3426
3468
  try {
3427
3469
  const config = loadConfig();
3428
3470
  const globalOpts = cmd.optsWithGlobals();
@@ -3445,7 +3487,9 @@ function registerTokenCommands(parent) {
3445
3487
  const api = createApiClient();
3446
3488
  const result = await api.admin.createApiToken({
3447
3489
  name: options.name,
3448
- resourceId: options.resource,
3490
+ // A personal token's resource is the caller's own account, which the platform fills in.
3491
+ // A given id is passed on; the platform refuses one that is not the caller's.
3492
+ ...options.resource !== void 0 ? { resourceId: options.resource } : {},
3449
3493
  resourceType,
3450
3494
  scopes,
3451
3495
  validityDays: parseInt(options.days, 10)
@@ -3475,7 +3519,7 @@ function registerTokenCommands(parent) {
3475
3519
  const tokens = options.resource ? await api.admin.getApiTokensByResource(options.resource) : await api.admin.getApiTokens();
3476
3520
  format(tokens, {
3477
3521
  format: outputFormat,
3478
- columns: ["tokenId", "name", "resourceId", "scopes", "createdAt", "expiresAt"]
3522
+ columns: ["tokenId", "name", "resourceType", "resourceId", "scopes", "createdAt", "expiresAt"]
3479
3523
  });
3480
3524
  } catch (error) {
3481
3525
  handleError(error);
@@ -7323,6 +7367,98 @@ function printUnavailable(interpretation) {
7323
7367
  }
7324
7368
  }
7325
7369
 
7370
+ // src/commands/analyze/report.ts
7371
+ var EXPORT_LANGUAGES = [
7372
+ "formula",
7373
+ "python",
7374
+ "r",
7375
+ "sql",
7376
+ "javascript",
7377
+ "java",
7378
+ "kotlin",
7379
+ "c",
7380
+ "latex"
7381
+ ];
7382
+ function writeText(text2) {
7383
+ if (text2.length === 0) return;
7384
+ process.stdout.write(text2);
7385
+ if (!text2.endsWith("\n")) process.stdout.write("\n");
7386
+ }
7387
+ function parseMaxBytes(given) {
7388
+ if (given === void 0) return void 0;
7389
+ const trimmed = given.trim();
7390
+ if (!/^\d+$/.test(trimmed) || Number(trimmed) <= 0) {
7391
+ usageError(
7392
+ `--max-bytes must be a whole number of bytes, not "${given}".`,
7393
+ "The platform reads between 4096 and 262144; without the flag it reads 32768."
7394
+ );
7395
+ }
7396
+ return Number(trimmed);
7397
+ }
7398
+ function parsePart(given, chapter) {
7399
+ if (given === void 0) return void 0;
7400
+ const trimmed = given.trim();
7401
+ if (!/^\d+$/.test(trimmed) || Number(trimmed) < 1) {
7402
+ usageError(`--part must be a whole number from 1, not "${given}".`);
7403
+ }
7404
+ if (chapter === void 0) {
7405
+ usageError(
7406
+ "--part reads one part of a chapter, so it needs --chapter.",
7407
+ "Without --chapter the command prints the summary, which does not come in parts."
7408
+ );
7409
+ }
7410
+ return Number(trimmed);
7411
+ }
7412
+ function parseExportLanguage(given) {
7413
+ const language = given.trim().toLowerCase();
7414
+ if (!EXPORT_LANGUAGES.includes(language)) {
7415
+ usageError(
7416
+ `"${given}" is not a language a model can be exported in.`,
7417
+ `Choose one of: ${EXPORT_LANGUAGES.join(", ")}.`
7418
+ );
7419
+ }
7420
+ return language;
7421
+ }
7422
+ async function printReport(analysisId, options) {
7423
+ const maxBytes = parseMaxBytes(options.maxBytes);
7424
+ const chapter = options.chapter?.trim() || void 0;
7425
+ const part = parsePart(options.part, chapter);
7426
+ const api = createApiClient();
7427
+ const markdown = await api.analysis.getReportMarkdown(analysisId, { chapter, part, maxBytes });
7428
+ writeText(markdown);
7429
+ }
7430
+ async function printModelExport(analysisId, options) {
7431
+ const language = parseExportLanguage(options.language);
7432
+ const target = options.target?.trim() || void 0;
7433
+ const api = createApiClient();
7434
+ const source = await api.analysis.exportModel(analysisId, { language, target });
7435
+ writeText(source);
7436
+ }
7437
+ var REPORT_HELP = `
7438
+ Without --chapter it prints the summary of the report and the titles of its chapters. Name a
7439
+ chapter to read it whole with the chapters below it. A title several chapters share is narrowed
7440
+ by naming chapters above it, separated by ">":
7441
+
7442
+ $ diafunc analyze report <id>
7443
+ $ diafunc analyze report <id> --chapter "Age > Correlation"
7444
+ $ diafunc analyze report <id> --max-bytes 131072 > report.md
7445
+
7446
+ A chapter larger than --max-bytes comes in parts. Each part ends with a line naming the next;
7447
+ read it with --part:
7448
+
7449
+ $ diafunc analyze report <id> --chapter Data --part 2
7450
+
7451
+ A title no chapter carries prints a sentence saying so, followed by the titles there are.
7452
+ Figures are not drawn; the numbers behind them are in the chapter's tables and values.
7453
+ `;
7454
+ var EXPORT_MODEL_HELP = `
7455
+ Prints the model the analysis found for one target, as a formula or as source code. With
7456
+ several targets, name one with --target. Public analyses can be exported too.
7457
+
7458
+ $ diafunc analyze export-model <id> --language formula
7459
+ $ diafunc analyze export-model <id> --language python --target price > model.py
7460
+ `;
7461
+
7326
7462
  // src/prompting/resolvers.ts
7327
7463
  var PROJECT_ROLES = ["OWNER", "ADMIN", "DEVELOPER", "GUEST"];
7328
7464
  var TRIGGER_TYPES = ["CRON", "INTERVAL", "CONTINUOUS", "EVENT"];
@@ -7355,6 +7491,7 @@ var BY_COMMAND = {
7355
7491
  "analyze focus": { "<family>": { kind: "choices", choices: FOCUS_FAMILIES.map((f) => f.id) } },
7356
7492
  // Not the analysis picker: that one offers the reader's own analyses, and this command needs no account.
7357
7493
  "public show": { "<analysisId>": TEXT },
7494
+ "analyze export-model": { "--language": { kind: "choice", choices: EXPORT_LANGUAGES } },
7358
7495
  "analyze presets save": { "--targets": TEXT, "--hours": POSITIVE, "--budget": POSITIVE },
7359
7496
  "branch merge": {
7360
7497
  "--source": { kind: "entity", form: "ref" },
@@ -7963,7 +8100,7 @@ var HELP = [
7963
8100
  ];
7964
8101
  async function runChatRepl(options) {
7965
8102
  const { input: promptInput } = await import("@inquirer/prompts");
7966
- const { getUpdateNotice } = await import("./update-check-BH7IMKZN.js");
8103
+ const { getUpdateNotice } = await import("./update-check-KHHHTIDF.js");
7967
8104
  let sessionId = options.session;
7968
8105
  let lastReportedSession;
7969
8106
  console.log(chalk21.bold("Diafunc chat") + chalk21.dim(" \xB7 /help for commands, /quit to exit"));
@@ -9560,7 +9697,7 @@ function dataShape(rows, columns) {
9560
9697
  }
9561
9698
  function qualityText(analysis, verdict) {
9562
9699
  if (verdict?.validity === "not_valid") return "not shown: the result is not valid";
9563
- const figure = analysis.heldOutQuality != null ? qualityPercent(analysis.heldOutQuality) : analysis.resultRunQuality != null ? `${qualityPercent(analysis.resultRunQuality)} on the training rows` : null;
9700
+ const figure = analysis.heldOutQuality != null ? qualityPercent(analysis.heldOutQuality) + rowsText(analysis.heldOutRows, analysis.searchRows) : analysis.resultRunQuality != null ? `${qualityPercent(analysis.resultRunQuality)} on the training rows` : null;
9564
9701
  if (figure == null) return null;
9565
9702
  return verdict?.validity === "needs_review" ? `${figure}, needs review` : figure;
9566
9703
  }
@@ -9569,12 +9706,17 @@ function targetResultsText(analysis) {
9569
9706
  if (results.length === 0) return null;
9570
9707
  const lines = results.map((r) => {
9571
9708
  const name = r.title ?? r.target ?? "target";
9572
- return r.quality != null ? `${name}: ${qualityPercent(r.quality)}` : name;
9709
+ return r.quality != null ? `${name}: ${qualityPercent(r.quality)}${rowsText(r.heldOutRows, r.searchRows)}` : name;
9573
9710
  });
9574
9711
  const more = (analysis.targetResultCount ?? results.length) - results.length;
9575
9712
  if (more > 0) lines.push(`and ${formatNumber(more)} more`);
9576
9713
  return lines.join("\n");
9577
9714
  }
9715
+ function rowsText(heldOutRows, searchRows) {
9716
+ if (heldOutRows == null || !(heldOutRows > 0)) return "";
9717
+ const measured = ` on ${formatNumber(heldOutRows)} held-out ${heldOutRows === 1 ? "row" : "rows"}`;
9718
+ return searchRows != null && searchRows > 0 ? `${measured}, found on ${formatNumber(searchRows)} ${searchRows === 1 ? "row" : "rows"}` : measured;
9719
+ }
9578
9720
  function errorPercent(error) {
9579
9721
  return `${formatNumber(Math.round(error * 1e3) / 10)}%`;
9580
9722
  }
@@ -11275,6 +11417,20 @@ function registerAnalyzeCommand(program) {
11275
11417
  handleError(error);
11276
11418
  }
11277
11419
  });
11420
+ analyze.command("report").description("Print the report of an analysis as Markdown: the summary and the chapter titles, or one chapter").argument("<id>", "Analysis ID").option("--chapter <title or path>", 'A chapter title, or a path of titles separated by ">" (for example "Age > Correlation")').option("--part <n>", "With --chapter: the part to read of a chapter that comes in parts, from 1 (default: 1)").option("--max-bytes <n>", "Largest answer in bytes; the platform reads 4096 to 262144 (default: 32768)").addHelpText("after", REPORT_HELP).action(async (id, options) => {
11421
+ try {
11422
+ await printReport(id, options);
11423
+ } catch (error) {
11424
+ handleError(error);
11425
+ }
11426
+ });
11427
+ analyze.command("export-model").description("Print the model of a target as a formula or as source code").argument("<id>", "Analysis ID").requiredOption("--language <language>", `One of: ${EXPORT_LANGUAGES.join(", ")}`).option("--target <name>", "The target whose model to export (required when the analysis has several)").addHelpText("after", EXPORT_MODEL_HELP).action(async (id, options) => {
11428
+ try {
11429
+ await printModelExport(id, options);
11430
+ } catch (error) {
11431
+ handleError(error);
11432
+ }
11433
+ });
11278
11434
  analyze.command("rerun").description("Queue a fresh run on an existing analysis (asks for anything a run still needs). A run cannot start while the data is still being imported").argument("<id>", "Analysis ID to rerun").action(async (id, _options, cmd) => {
11279
11435
  try {
11280
11436
  await rerunAnalysis(id, cmd);
@@ -13202,7 +13358,7 @@ function registerShellCommand(program) {
13202
13358
  });
13203
13359
  const api = createApiClient();
13204
13360
  const { input: promptInput } = await import("@inquirer/prompts");
13205
- const { getUpdateNotice } = await import("./update-check-BH7IMKZN.js");
13361
+ const { getUpdateNotice } = await import("./update-check-KHHHTIDF.js");
13206
13362
  const resolvedLanguage = await resolveLanguage(api, fnRef.projectId, options.language);
13207
13363
  console.log(chalk36.bold("Diafunc shell") + chalk36.dim(` \xB7 function ${fnRef.entityId} \xB7 ${resolvedLanguage}`));
13208
13364
  console.log(chalk36.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
@@ -14063,4 +14219,4 @@ export {
14063
14219
  PromptCanceled,
14064
14220
  createProgram
14065
14221
  };
14066
- //# sourceMappingURL=chunk-6QBACH4J.js.map
14222
+ //# sourceMappingURL=chunk-5AB7E3K4.js.map