@diafunc/cli 0.29.0 → 0.29.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  package_default
3
- } from "./chunk-CWZPEFGN.js";
3
+ } from "./chunk-WZQ5LS2M.js";
4
4
 
5
5
  // src/index.ts
6
- import chalk40 from "chalk";
6
+ import chalk41 from "chalk";
7
7
 
8
8
  // src/commands/auth/login.ts
9
9
  import chalk4 from "chalk";
@@ -258,13 +258,13 @@ function resolveEndpoint(config, profileOverride) {
258
258
  import chalk from "chalk";
259
259
 
260
260
  // src/client/errors.ts
261
- var LICENCE_REFUSALS = {
262
- licence_required: "A public project needs a licence. Name one with --licence <id>.",
263
- licence_not_selectable: "That licence cannot be chosen: it is not in the catalogue, or it is deprecated or withdrawn.",
264
- licence_share_alike_mismatch: "This project is a fork of a share-alike project, so it has to carry the licence of the project it was forked from.",
265
- licence_forbids_fork: "The licence of this project does not allow adaptations, so it cannot be forked."
261
+ var LICENSE_REFUSALS = {
262
+ licence_required: "A public project needs a license. Name one with --license <id>.",
263
+ licence_not_selectable: "That license cannot be chosen: it is not in the catalog, or it is deprecated or withdrawn.",
264
+ licence_share_alike_mismatch: "This project is a fork of a share-alike project, so it has to carry the license of the project it was forked from.",
265
+ licence_forbids_fork: "The license of this project does not allow adaptations, so it cannot be forked."
266
266
  };
267
- var LICENCE_LIST_REFUSALS = /* @__PURE__ */ new Set(["licence_required", "licence_not_selectable"]);
267
+ var LICENSE_LIST_REFUSALS = /* @__PURE__ */ new Set(["licence_required", "licence_not_selectable"]);
268
268
  var ApiError = class _ApiError extends Error {
269
269
  status;
270
270
  details;
@@ -281,7 +281,7 @@ var ApiError = class _ApiError extends Error {
281
281
  return new _ApiError(status, body.message, body.details, typeof body.error === "string" ? body.error : void 0);
282
282
  }
283
283
  toUserMessage() {
284
- const refusal = this.code && Object.prototype.hasOwnProperty.call(LICENCE_REFUSALS, this.code) ? LICENCE_REFUSALS[this.code] : void 0;
284
+ const refusal = this.code && Object.prototype.hasOwnProperty.call(LICENSE_REFUSALS, this.code) ? LICENSE_REFUSALS[this.code] : void 0;
285
285
  if (refusal) return refusal;
286
286
  const detail2 = this.readableMessage();
287
287
  switch (this.status) {
@@ -748,19 +748,19 @@ function createAdminService(client) {
748
748
  path: `/projects/${encodeURIComponent(projectId)}`
749
749
  });
750
750
  },
751
- // Licences: the catalogue answers anyone, signed in or not.
752
- async listLicences() {
751
+ // Licenses: the catalog answers anyone, signed in or not.
752
+ async listLicenses() {
753
753
  return client.request({
754
754
  method: "GET",
755
755
  service: SERVICE,
756
756
  path: "/licences"
757
757
  });
758
758
  },
759
- async getLicence(licenceId) {
759
+ async getLicense(licenseId) {
760
760
  return client.request({
761
761
  method: "GET",
762
762
  service: SERVICE,
763
- path: `/licences/${encodeURIComponent(licenceId)}`
763
+ path: `/licences/${encodeURIComponent(licenseId)}`
764
764
  });
765
765
  },
766
766
  async createProject(request) {
@@ -1074,7 +1074,7 @@ function createAdminService(client) {
1074
1074
  body: setting
1075
1075
  });
1076
1076
  },
1077
- // Platform settings: the operator-facing catalogue, distinct from the per-user settings above.
1077
+ // Platform settings: the operator-facing catalog, distinct from the per-user settings above.
1078
1078
  // Every entry carries its compiled default, so an unset override reads as null rather than absent.
1079
1079
  async listPlatformSettings() {
1080
1080
  return client.request({
@@ -1240,7 +1240,7 @@ function handleError(error) {
1240
1240
  failure(error.toUserMessage());
1241
1241
  if (error.status === 401 && !(error instanceof SignInRefusedError)) hint(`Run 'diafunc auth login' to sign in.`);
1242
1242
  if (error.status === 404) hint(`Check the id, or list what exists with the matching 'list' command.`);
1243
- if (error.code && LICENCE_LIST_REFUSALS.has(error.code)) hint(`List the licences that can be chosen with 'diafunc licence list'.`);
1243
+ if (error.code && LICENSE_LIST_REFUSALS.has(error.code)) hint(`List the licenses that can be chosen with 'diafunc license list'.`);
1244
1244
  process.exit(error.status === 401 || error.status === 403 ? EXIT_AUTH : EXIT_FAILURE);
1245
1245
  }
1246
1246
  if (error instanceof NetworkError) {
@@ -1289,7 +1289,7 @@ function registerLoginCommand(parent) {
1289
1289
  const client = createHttpClient();
1290
1290
  const admin = createAdminService(client);
1291
1291
  const user = await admin.getMyUser();
1292
- success("Authenticated successfully.");
1292
+ success("Signed in.");
1293
1293
  console.log(` User: ${chalk4.bold(user.name)}`);
1294
1294
  console.log(` Email: ${user.email}`);
1295
1295
  console.log(` Profile: ${config.currentProfile}`);
@@ -1317,7 +1317,7 @@ async function deviceCodeLogin(config, profile) {
1317
1317
  });
1318
1318
  if (!deviceResponse.ok) {
1319
1319
  const text2 = await deviceResponse.text();
1320
- failure(`Failed to start device-code flow: ${text2 || deviceResponse.statusText}`);
1320
+ failure(`The sign-in could not start: ${text2 || deviceResponse.statusText}`);
1321
1321
  process.exit(1);
1322
1322
  }
1323
1323
  const device = await deviceResponse.json();
@@ -1355,7 +1355,7 @@ async function deviceCodeLogin(config, profile) {
1355
1355
  const client = createHttpClient();
1356
1356
  const admin = createAdminService(client);
1357
1357
  const user = await admin.getMyUser();
1358
- success("Logged in successfully.");
1358
+ success("Signed in.");
1359
1359
  console.log(` User: ${chalk4.bold(user.name)}`);
1360
1360
  console.log(` Email: ${user.email}`);
1361
1361
  console.log(` Profile: ${config.currentProfile}`);
@@ -1940,6 +1940,14 @@ function createAnalysisService(client) {
1940
1940
  });
1941
1941
  },
1942
1942
  /** The depth the platform would give the caller's next analysis if its creation named none. */
1943
+ /** The depths an analysis is offered at, shallowest first: the one list every surface shows. */
1944
+ async getDepths() {
1945
+ return client.request({
1946
+ method: "GET",
1947
+ service: SERVICE2,
1948
+ path: "/depths"
1949
+ });
1950
+ },
1943
1951
  async getDepthDefault() {
1944
1952
  return client.request({
1945
1953
  method: "GET",
@@ -2046,6 +2054,69 @@ function createAnalysisService(client) {
2046
2054
  body: request
2047
2055
  });
2048
2056
  },
2057
+ // ----- The owner's notes ("What you know and what matters") ------------------------
2058
+ /** Stores the notes only; reading them into proposals is {@link interpretIntent}. */
2059
+ async patchIntent(analysisId, request) {
2060
+ return client.request({
2061
+ method: "PATCH",
2062
+ service: SERVICE2,
2063
+ path: `/${encodeURIComponent(analysisId)}/intent`,
2064
+ body: request
2065
+ });
2066
+ },
2067
+ /** Reads the notes against the setup in the body; nothing is applied. */
2068
+ async interpretIntent(analysisId, request, options = {}) {
2069
+ const query = {};
2070
+ if (options.force) query.force = "true";
2071
+ if (options.refine) query.refine = "true";
2072
+ return client.request({
2073
+ method: "POST",
2074
+ service: SERVICE2,
2075
+ path: `/${encodeURIComponent(analysisId)}/intent/interpretation`,
2076
+ query,
2077
+ body: request
2078
+ });
2079
+ },
2080
+ async getIntentInterpretation(analysisId) {
2081
+ return client.request({
2082
+ method: "GET",
2083
+ service: SERVICE2,
2084
+ path: `/${encodeURIComponent(analysisId)}/intent/interpretation`
2085
+ });
2086
+ },
2087
+ /** Confirms (applies), declines or re-proposes proposals of the stored interpretation. */
2088
+ async decideIntentItems(analysisId, request) {
2089
+ return client.request({
2090
+ method: "PATCH",
2091
+ service: SERVICE2,
2092
+ path: `/${encodeURIComponent(analysisId)}/intent/interpretation/items`,
2093
+ body: request
2094
+ });
2095
+ },
2096
+ async patchShapeExpectations(analysisId, request) {
2097
+ return client.request({
2098
+ method: "PATCH",
2099
+ service: SERVICE2,
2100
+ path: `/${encodeURIComponent(analysisId)}/shape-expectations`,
2101
+ body: request
2102
+ });
2103
+ },
2104
+ async patchRequestedPairs(analysisId, request) {
2105
+ return client.request({
2106
+ method: "PATCH",
2107
+ service: SERVICE2,
2108
+ path: `/${encodeURIComponent(analysisId)}/requested-pairs`,
2109
+ body: request
2110
+ });
2111
+ },
2112
+ async patchFocusFamilies(analysisId, request) {
2113
+ return client.request({
2114
+ method: "PATCH",
2115
+ service: SERVICE2,
2116
+ path: `/${encodeURIComponent(analysisId)}/focus-families`,
2117
+ body: request
2118
+ });
2119
+ },
2049
2120
  // ----- Data ingest ----------------------------------------------------------------
2050
2121
  async uploadDataMultipart(analysisId, formData) {
2051
2122
  return client.request({
@@ -3380,7 +3451,7 @@ function registerTokenCommands(parent) {
3380
3451
  validityDays: parseInt(options.days, 10)
3381
3452
  });
3382
3453
  if (outputFormat === "human") {
3383
- success("API token created successfully.");
3454
+ success("API token created.");
3384
3455
  console.log();
3385
3456
  console.log(` Token: ${chalk8.bold(result.token)}`);
3386
3457
  console.log(` Token ID: ${result.tokenId}`);
@@ -3574,6 +3645,55 @@ function getNestedValue(obj, path13) {
3574
3645
  // src/commands/project/index.ts
3575
3646
  import chalk13 from "chalk";
3576
3647
 
3648
+ // src/util/hidden-aliases.ts
3649
+ import { Help, Option } from "commander";
3650
+ var hidden = /* @__PURE__ */ new WeakMap();
3651
+ function hiddenAlias(cmd, alias) {
3652
+ cmd.alias(alias);
3653
+ const names = hidden.get(cmd) ?? /* @__PURE__ */ new Set();
3654
+ names.add(alias);
3655
+ hidden.set(cmd, names);
3656
+ return cmd;
3657
+ }
3658
+ function visibleAliases(cmd) {
3659
+ const names = hidden.get(cmd);
3660
+ return cmd.aliases().filter((alias) => !names?.has(alias));
3661
+ }
3662
+ function withVisibleAliasesOnly(cmd, render) {
3663
+ const target = cmd;
3664
+ const all = target._aliases;
3665
+ target._aliases = visibleAliases(cmd);
3666
+ try {
3667
+ return render();
3668
+ } finally {
3669
+ target._aliases = all;
3670
+ }
3671
+ }
3672
+ var HIDDEN_ALIAS_HELP = {
3673
+ subcommandTerm(cmd) {
3674
+ return withVisibleAliasesOnly(cmd, () => Help.prototype.subcommandTerm.call(this, cmd));
3675
+ },
3676
+ commandUsage(cmd) {
3677
+ return withVisibleAliasesOnly(cmd, () => Help.prototype.commandUsage.call(this, cmd));
3678
+ }
3679
+ };
3680
+ var optionTargets = /* @__PURE__ */ new WeakMap();
3681
+ function hiddenOptionAlias(oldFlags, target) {
3682
+ const option = new Option(oldFlags).hideHelp();
3683
+ optionTargets.set(option, target);
3684
+ return option;
3685
+ }
3686
+ function wireHiddenOptionAliases(cmd) {
3687
+ for (const option of cmd.options) {
3688
+ const target = optionTargets.get(option);
3689
+ if (!target) continue;
3690
+ cmd.on(`option:${option.name()}`, (value) => {
3691
+ cmd.setOptionValue(target, value);
3692
+ });
3693
+ }
3694
+ for (const sub of cmd.commands) wireHiddenOptionAliases(sub);
3695
+ }
3696
+
3577
3697
  // src/util/references.ts
3578
3698
  function parseEntityReference(ref, overrides) {
3579
3699
  const config = loadConfig();
@@ -3933,6 +4053,81 @@ async function projectNames(api, projectIds) {
3933
4053
  return names;
3934
4054
  }
3935
4055
 
4056
+ // src/util/entity-attributes.ts
4057
+ function encodeTextAttribute(value) {
4058
+ return Buffer.from(value, "utf-8").toString("base64");
4059
+ }
4060
+ function decodeTextAttribute(value) {
4061
+ if (value === null || value === void 0) return null;
4062
+ return Buffer.from(value, "base64").toString("utf-8");
4063
+ }
4064
+ function encodeLongAttribute(value) {
4065
+ if (!Number.isSafeInteger(value)) {
4066
+ throw new RangeError(`Not an integer attribute value: ${value}`);
4067
+ }
4068
+ const bytes = Buffer.alloc(8);
4069
+ bytes.writeBigInt64BE(BigInt(value));
4070
+ return bytes.toString("base64");
4071
+ }
4072
+
4073
+ // src/util/project-entity.ts
4074
+ function buildProjectRootEntity(args) {
4075
+ const now = Date.now();
4076
+ const attributes = {};
4077
+ const attributeTypes = {};
4078
+ if (args.name) {
4079
+ attributes.name = encodeTextAttribute(args.name);
4080
+ attributeTypes.name = "text";
4081
+ }
4082
+ if (args.description) {
4083
+ attributes.description = encodeTextAttribute(args.description);
4084
+ attributeTypes.description = "text";
4085
+ }
4086
+ return {
4087
+ projectId: args.projectId,
4088
+ projectBranch: "main",
4089
+ entityId: args.projectId,
4090
+ entityBranch: "main",
4091
+ head: true,
4092
+ version: 1,
4093
+ type: "project",
4094
+ attributes,
4095
+ attributeTypes,
4096
+ metaAttributes: {},
4097
+ metaAttributeTypes: {},
4098
+ tags: [],
4099
+ modified: now,
4100
+ created: now,
4101
+ versioned: false,
4102
+ versionTtl: null,
4103
+ retain: false,
4104
+ contentAvailable: false,
4105
+ contentLoaded: false,
4106
+ contentType: null,
4107
+ contentSize: null,
4108
+ content: null
4109
+ };
4110
+ }
4111
+ function withProjectTexts(root, texts) {
4112
+ const attributes = { ...root.attributes ?? {} };
4113
+ const attributeTypes = { ...root.attributeTypes ?? {} };
4114
+ if (texts.name !== void 0) {
4115
+ attributes.name = encodeTextAttribute(texts.name.trim());
4116
+ attributeTypes.name = "text";
4117
+ }
4118
+ if (texts.description !== void 0) {
4119
+ const description = texts.description.trim();
4120
+ if (description) {
4121
+ attributes.description = encodeTextAttribute(description);
4122
+ attributeTypes.description = "text";
4123
+ } else {
4124
+ delete attributes.description;
4125
+ delete attributeTypes.description;
4126
+ }
4127
+ }
4128
+ return { ...root, attributes, attributeTypes, content: null };
4129
+ }
4130
+
3936
4131
  // src/commands/entity/tags.ts
3937
4132
  import chalk12 from "chalk";
3938
4133
 
@@ -4204,11 +4399,13 @@ Showing ${capped.length} of ${projects.length}. Pass --limit 0 to see them all.`
4204
4399
  handleError(error);
4205
4400
  }
4206
4401
  });
4207
- 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).option("--licence <licenceId>", "Licence a public project is published under, an id of the licence catalogue (see 'diafunc licence list')").addHelpText("after", `
4402
+ project.command("create").description("Create a new project").option("--name <name>", "The project's name; without one, a project bundle imported into it names it").option("--description <text>", "The project's description").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).option("--license <licenseId>", "License a public project is published under, an id of the license catalog (see 'diafunc license list')").addOption(hiddenOptionAlias("--licence <licenseId>", "license")).addHelpText("after", `
4208
4403
  Examples:
4209
4404
  $ diafunc project create a private project
4210
- $ diafunc project create --visibility PUBLIC --licence CC-BY-4.0 a public one, open for reuse with attribution
4211
- $ diafunc licence list the licences that can be chosen
4405
+ $ diafunc project create --name "Vineyard yield" a private project with a name
4406
+ $ diafunc project import <projectId> guide.dfproj an unnamed one takes the bundle's name
4407
+ $ diafunc project create --visibility PUBLIC --license CC-BY-4.0 a public one, open for reuse with attribution
4408
+ $ diafunc license list the licenses that can be chosen
4212
4409
  `).action(async (options, cmd) => {
4213
4410
  try {
4214
4411
  const outputFormat = getOutputFormat2(cmd);
@@ -4217,19 +4414,25 @@ Examples:
4217
4414
  visibility: options.visibility.toUpperCase(),
4218
4415
  language: options.language,
4219
4416
  active: true,
4220
- ...options.licence ? { licenceId: options.licence } : {}
4417
+ ...options.license ? { licenceId: options.license } : {}
4221
4418
  });
4222
4419
  await api.storage.createProjectBranch({
4223
4420
  projectId: p.projectId,
4224
4421
  sourceProjectBranch: null,
4225
4422
  targetProjectBranch: "main"
4226
4423
  });
4424
+ await api.storage.saveEntities([buildProjectRootEntity({
4425
+ projectId: p.projectId,
4426
+ name: options.name,
4427
+ description: options.description
4428
+ })]);
4227
4429
  if (outputFormat === "human") {
4228
4430
  success("Project created.");
4431
+ if (options.name) console.log(` Name: ${options.name}`);
4229
4432
  console.log(` Project ID: ${chalk13.bold(p.projectId)}`);
4230
4433
  console.log(` Visibility: ${p.visibility}`);
4231
4434
  console.log(` Language: ${p.language}`);
4232
- if (p.licenceId) console.log(` Licence: ${p.licenceId}`);
4435
+ if (p.licenceId) console.log(` License: ${p.licenceId}`);
4233
4436
  } else {
4234
4437
  format(p, { format: outputFormat });
4235
4438
  }
@@ -4237,16 +4440,46 @@ Examples:
4237
4440
  handleError(error);
4238
4441
  }
4239
4442
  });
4240
- project.command("update").description("Update a project").argument("<projectId>", "Project ID").option("--visibility <visibility>", "PRIVATE or PUBLIC").option("--language <language>", "Project language").option("--active <bool>", "Whether the project is active (true/false)").option("--licence <licenceId>", "Licence a public project is published under, an id of the licence catalogue (CC-BY-4.0, CC0-1.0, diafunc-view-only, ...)").option("--data-source-name <name>", "Who published the data the project analyses; an empty value clears it").option("--data-source-url <url>", "Where the data was obtained, an http(s) address; an empty value clears it").action(async (projectId, options) => {
4241
- try {
4242
- const api = createApiClient();
4443
+ project.command("update").description("Update a project").argument("<projectId>", "Project ID").option("--name <name>", "The project's name, shown on Explore and in the project header").option("--description <text>", "The project's description, shown on Explore; an empty value removes it").option("--visibility <visibility>", "PRIVATE or PUBLIC").option("--language <language>", "Project language").option("--active <bool>", "Whether the project is active (true/false)").option("--license <licenseId>", "License a public project is published under, an id of the license catalog (CC-BY-4.0, CC0-1.0, diafunc-view-only, ...)").addOption(hiddenOptionAlias("--licence <licenseId>", "license")).option("--data-source-name <name>", "Who published the data the project analyzes; an empty value clears it").option("--data-source-url <url>", "Where the data was obtained, an http(s) address; an empty value clears it").addHelpText("after", `
4444
+ Examples:
4445
+ $ diafunc project update <projectId> --name "Vineyard yield" rename the project
4446
+ $ diafunc project update <projectId> --description "Yield per hectare" set the text Explore shows
4447
+ $ diafunc project update <projectId> --license CC-BY-4.0 publish it under another license
4448
+ `).action(async (projectId, options) => {
4449
+ try {
4450
+ const api = createApiClient();
4451
+ const projectOptions = ["visibility", "language", "active", "license", "dataSourceName", "dataSourceUrl"];
4452
+ const changesProject = projectOptions.some((key) => options[key] !== void 0);
4453
+ const changesTexts = options.name !== void 0 || options.description !== void 0;
4454
+ if (!changesProject && !changesTexts) {
4455
+ throw new Error("Nothing to update: give at least one option (see --help).");
4456
+ }
4457
+ if (options.name !== void 0 && !options.name.trim()) {
4458
+ throw new Error("A project name cannot be empty.");
4459
+ }
4460
+ if (changesTexts) {
4461
+ const root = await api.storage.getEntity({
4462
+ projectId,
4463
+ projectBranch: "main",
4464
+ entityId: projectId,
4465
+ entityBranch: "main"
4466
+ });
4467
+ await api.storage.saveEntities([withProjectTexts(root, {
4468
+ name: options.name,
4469
+ description: options.description
4470
+ })]);
4471
+ }
4472
+ if (!changesProject) {
4473
+ success(`Project "${projectId}" updated.`);
4474
+ return;
4475
+ }
4243
4476
  const current = await api.admin.getProject(projectId);
4244
4477
  const updated = {
4245
4478
  ...current,
4246
4479
  ...options.visibility ? { visibility: options.visibility.toUpperCase() } : {},
4247
4480
  ...options.language ? { language: options.language } : {},
4248
4481
  ...options.active !== void 0 ? { active: options.active === "true" } : {},
4249
- ...options.licence ? { licenceId: options.licence } : {},
4482
+ ...options.license ? { licenceId: options.license } : {},
4250
4483
  ...options.dataSourceName !== void 0 ? { dataSourceName: options.dataSourceName } : {},
4251
4484
  ...options.dataSourceUrl !== void 0 ? { dataSourceUrl: options.dataSourceUrl } : {}
4252
4485
  };
@@ -4363,7 +4596,7 @@ Examples:
4363
4596
  handleError(error);
4364
4597
  }
4365
4598
  });
4366
- project.command("import").description("Import a .dfproj (or any) bundle into a project").argument("<project>", "Target project reference (projectId or projectId/branch)").argument("<file>", "Path to the bundle").option("--on-conflict <policy>", "copy (default), overwrite, or skip", "copy").option("--preview", "Show the bundle inventory without importing").action(async (project2, file, options, cmd) => {
4599
+ project.command("import").description("Import a .dfproj (or any) bundle into a project").argument("<project>", "Target project reference (projectId or projectId/branch)").argument("<file>", "Path to the bundle").option("--on-conflict <policy>", "copy (default; copy only entities whose id already exists, under a new id), overwrite, or skip", "copy").option("--preview", "Show the bundle inventory without importing").action(async (project2, file, options, cmd) => {
4367
4600
  try {
4368
4601
  const outputFormat = getOutputFormat2(cmd);
4369
4602
  const overrides = getOverrides(cmd);
@@ -4560,7 +4793,7 @@ Examples:
4560
4793
  const api = createApiClient();
4561
4794
  const response = await api.admin.cancelTeam(teamId);
4562
4795
  success(
4563
- `Team "${teamId}" cancelled. Access ends ${response.endsAt ?? "at the end of the period"}.`,
4796
+ `Team "${teamId}" canceled. Access ends ${response.endsAt ?? "at the end of the period"}.`,
4564
4797
  { format: getOutputFormat3(cmd) }
4565
4798
  );
4566
4799
  } catch (error) {
@@ -4796,7 +5029,7 @@ function registerOwnershipCommands(team) {
4796
5029
  try {
4797
5030
  const api = createApiClient();
4798
5031
  await api.admin.cancelOwnershipTransfer(teamId);
4799
- success(`Cancelled the ownership transfer for team "${teamId}".`, {
5032
+ success(`Canceled the ownership transfer for team "${teamId}".`, {
4800
5033
  format: getOutputFormat3(cmd)
4801
5034
  });
4802
5035
  } catch (error) {
@@ -5015,7 +5248,7 @@ Examples:
5015
5248
  handleError(error);
5016
5249
  }
5017
5250
  });
5018
- entity.command("import").description("Import a .dfset (or any) bundle into a project").argument("<project>", "Target project reference (projectId or projectId/branch)").argument("<file>", "Path to the bundle").option("--on-conflict <policy>", "copy (default), overwrite, or skip", "copy").option("--preview", "Show the bundle inventory without importing").action(async (project, file, options, cmd) => {
5251
+ entity.command("import").description("Import a .dfset (or any) bundle into a project").argument("<project>", "Target project reference (projectId or projectId/branch)").argument("<file>", "Path to the bundle").option("--on-conflict <policy>", "copy (default; copy only entities whose id already exists, under a new id), overwrite, or skip", "copy").option("--preview", "Show the bundle inventory without importing").action(async (project, file, options, cmd) => {
5019
5252
  try {
5020
5253
  const outputFormat = getOutputFormat4(cmd);
5021
5254
  const overrides = getOverrides2(cmd);
@@ -5164,8 +5397,8 @@ function registerEventCommands(program) {
5164
5397
  });
5165
5398
  event.command("create").description("Create one or more events (body from JSON file or stdin)").argument("[file]", "JSON file containing a BareEvent array; defaults to stdin").action(async (file) => {
5166
5399
  try {
5167
- const fs18 = await import("fs");
5168
- const body = file ? fs18.readFileSync(file, "utf-8") : await new Promise((resolve2, reject) => {
5400
+ const fs19 = await import("fs");
5401
+ const body = file ? fs19.readFileSync(file, "utf-8") : await new Promise((resolve2, reject) => {
5169
5402
  let data = "";
5170
5403
  process.stdin.setEncoding("utf-8");
5171
5404
  process.stdin.on("data", (chunk) => {
@@ -5227,7 +5460,7 @@ function registerBranchCommands(program) {
5227
5460
  Examples:
5228
5461
  $ diafunc branch list <projectId>
5229
5462
  $ diafunc branch create <projectId> experiment
5230
- $ diafunc branch merge --from experiment --to main --entity <id>
5463
+ $ diafunc branch merge --source <projectId>/experiment/<entityId>/main --target <projectId>/main
5231
5464
  `);
5232
5465
  ;
5233
5466
  branch.command("list").description("List branches for a project").argument("[projectId]", "Project ID (uses default if omitted)").action(async (projectId, _options, cmd) => {
@@ -5395,7 +5628,7 @@ async function fetchWindow(fetchPart, window, maxCells = SNAPSHOT_MAX_CELLS) {
5395
5628
  }
5396
5629
  function describeWindow(window, rows, columns) {
5397
5630
  const whole = window.rows.from === 0 && window.rows.to === rows && window.columns.from === 0 && window.columns.to === columns;
5398
- const line = `Rows ${window.rows.from}\u2013${window.rows.to - 1} of ${rows} \xB7 columns ${window.columns.from}\u2013${window.columns.to - 1} of ${columns}`;
5631
+ const line = `Rows ${window.rows.from} to ${window.rows.to - 1} of ${rows} \xB7 columns ${window.columns.from} to ${window.columns.to - 1} of ${columns}`;
5399
5632
  return whole ? line : `${line} \xB7 use --rows/--cols for more`;
5400
5633
  }
5401
5634
  function decodeCellValue(value, type) {
@@ -5415,23 +5648,6 @@ function decodeCellValue(value, type) {
5415
5648
  return bytes.toString("utf-8");
5416
5649
  }
5417
5650
 
5418
- // src/util/entity-attributes.ts
5419
- function encodeTextAttribute(value) {
5420
- return Buffer.from(value, "utf-8").toString("base64");
5421
- }
5422
- function decodeTextAttribute(value) {
5423
- if (value === null || value === void 0) return null;
5424
- return Buffer.from(value, "base64").toString("utf-8");
5425
- }
5426
- function encodeLongAttribute(value) {
5427
- if (!Number.isSafeInteger(value)) {
5428
- throw new RangeError(`Not an integer attribute value: ${value}`);
5429
- }
5430
- const bytes = Buffer.alloc(8);
5431
- bytes.writeBigInt64BE(BigInt(value));
5432
- return bytes.toString("base64");
5433
- }
5434
-
5435
5651
  // src/util/table-entity.ts
5436
5652
  function buildTableEntity(args) {
5437
5653
  const now = Date.now();
@@ -5727,7 +5943,7 @@ Examples:
5727
5943
  const formats = await api.storage.getSupportedExportFormats();
5728
5944
  const format2 = formats.formats.find((f) => f.id.toLowerCase() === fmt.toLowerCase());
5729
5945
  if (!format2) {
5730
- failure(`Unknown format: "${fmt}". Run \`diafunc table export-formats\` to see the catalogue.`);
5946
+ failure(`Unknown format: "${fmt}". Run \`diafunc table export-formats\` to see the catalog.`);
5731
5947
  process.exit(1);
5732
5948
  }
5733
5949
  if (options.compression && !formats.compressionAlgorithms.includes(options.compression)) {
@@ -6011,7 +6227,7 @@ function getOverrides7(cmd) {
6011
6227
  function registerNotebookCommands(program) {
6012
6228
  const notebook = program.command("notebook").description("Export and import notebook bundles").addHelpText("after", `
6013
6229
  Examples:
6014
- $ diafunc notebook export <project> <notebookId> -o notebook.dfnb
6230
+ $ diafunc notebook export <project> <notebookId> --out notebook.dfnb
6015
6231
  $ diafunc notebook import <project> notebook.dfnb --preview
6016
6232
  $ diafunc notebook import <project> notebook.dfnb
6017
6233
  `);
@@ -6037,7 +6253,7 @@ Examples:
6037
6253
  handleError(error);
6038
6254
  }
6039
6255
  });
6040
- notebook.command("import").description("Import a .dfnb bundle into a project").argument("<project>", "Target project reference (projectId or projectId/branch)").argument("<file>", "Path to the .dfnb bundle").option("--on-conflict <policy>", "copy (default), overwrite, or skip", "copy").option("--preview", "Show the bundle inventory without importing").action(async (project, file, options, cmd) => {
6256
+ notebook.command("import").description("Import a .dfnb bundle into a project").argument("<project>", "Target project reference (projectId or projectId/branch)").argument("<file>", "Path to the .dfnb bundle").option("--on-conflict <policy>", "copy (default; copy only entities whose id already exists, under a new id), overwrite, or skip", "copy").option("--preview", "Show the bundle inventory without importing").action(async (project, file, options, cmd) => {
6041
6257
  try {
6042
6258
  const outputFormat = getOutputFormat9(cmd);
6043
6259
  const overrides = getOverrides7(cmd);
@@ -6306,7 +6522,7 @@ Examples:
6306
6522
  } else {
6307
6523
  if (outputFormat === "human") {
6308
6524
  if (result.successful) {
6309
- success("Function completed successfully.");
6525
+ success("Function completed.");
6310
6526
  if (result.result) {
6311
6527
  console.log(` Result: ${resultText(result.result, result.resultEncoding)}`);
6312
6528
  }
@@ -6573,47 +6789,786 @@ function extensionFor(language) {
6573
6789
  return "txt";
6574
6790
  }
6575
6791
 
6576
- // src/commands/trigger/index.ts
6577
- function getOutputFormat11(cmd) {
6578
- const config = loadConfig();
6579
- const globalOpts = cmd.optsWithGlobals();
6580
- return globalOpts.output ?? config.defaults.output ?? "human";
6792
+ // src/commands/analyze/intent.ts
6793
+ import * as fs9 from "fs";
6794
+ import chalk19 from "chalk";
6795
+
6796
+ // src/commands/analyze/columns.ts
6797
+ var MAX_COLUMNS_LISTED = 30;
6798
+ var MAX_NEAR_MATCHES = 3;
6799
+ function parseColumnList(text2) {
6800
+ const names = [];
6801
+ let i = 0;
6802
+ while (i < text2.length) {
6803
+ while (i < text2.length && isSpace(text2[i])) i++;
6804
+ if (i >= text2.length) break;
6805
+ if (text2[i] === '"') {
6806
+ let name = "";
6807
+ let closed = false;
6808
+ i++;
6809
+ while (i < text2.length) {
6810
+ if (text2[i] === '"' && text2[i + 1] === '"') {
6811
+ name += '"';
6812
+ i += 2;
6813
+ } else if (text2[i] === '"') {
6814
+ closed = true;
6815
+ i++;
6816
+ break;
6817
+ } else {
6818
+ name += text2[i++];
6819
+ }
6820
+ }
6821
+ if (!closed) {
6822
+ throw new CliError(`A double quote is opened and never closed in: ${text2}`, {
6823
+ exitCode: EXIT_USAGE,
6824
+ hint: QUOTING_HINT
6825
+ });
6826
+ }
6827
+ while (i < text2.length && isSpace(text2[i])) i++;
6828
+ if (i < text2.length && text2[i] !== ",") {
6829
+ throw new CliError(`Text follows a closing double quote without a comma in: ${text2}`, {
6830
+ exitCode: EXIT_USAGE,
6831
+ hint: QUOTING_HINT
6832
+ });
6833
+ }
6834
+ i++;
6835
+ if (name.length > 0) names.push(name);
6836
+ } else {
6837
+ const end = text2.indexOf(",", i);
6838
+ const name = text2.slice(i, end === -1 ? text2.length : end).trim();
6839
+ i = end === -1 ? text2.length : end + 1;
6840
+ if (name.length > 0) names.push(name);
6841
+ }
6842
+ }
6843
+ return names;
6581
6844
  }
6582
- function getOverrides9(cmd) {
6583
- const opts = cmd.optsWithGlobals();
6584
- return { project: opts.project, branch: opts.branch };
6845
+ var QUOTING_HINT = `Inside a list, put a name that contains a comma in double quotes and write a quote in it twice: '"a, b",c'.`;
6846
+ function isSpace(char) {
6847
+ return char === " " || char === " ";
6585
6848
  }
6586
- function registerTriggerCommands(program) {
6587
- const trigger = program.command("trigger").description("Manage function triggers").addHelpText("after", `
6588
- Examples:
6589
- $ diafunc trigger list <ref>
6590
- $ diafunc trigger create <ref> --expression '0 0 * * *'
6591
- $ diafunc trigger delete <ref> <triggerId>
6592
- `);
6593
- ;
6594
- trigger.command("list").description("List triggers for a function").argument("<ref>", "Function entity reference").action(async (ref, _options, cmd) => {
6595
- try {
6596
- const outputFormat = getOutputFormat11(cmd);
6597
- const overrides = getOverrides9(cmd);
6598
- const resolved = parseEntityReference(ref, overrides);
6599
- const api = createApiClient();
6600
- const triggers = await api.evaluation.getTriggers(
6601
- resolved.projectId,
6602
- resolved.projectBranch,
6603
- resolved.entityId,
6604
- resolved.entityBranch
6849
+ function quoteColumn(name) {
6850
+ return `"${name.replace(/"/g, '""')}"`;
6851
+ }
6852
+ function loose(name) {
6853
+ return name.trim().toLowerCase();
6854
+ }
6855
+ function matchColumn(name, columns) {
6856
+ if (columns.includes(name)) return { kind: "column", column: name };
6857
+ const wanted = loose(name);
6858
+ const candidates = columns.filter((column) => loose(column) === wanted);
6859
+ if (candidates.length === 1) return { kind: "column", column: candidates[0] };
6860
+ return candidates.length > 1 ? { kind: "ambiguous", candidates } : { kind: "unknown" };
6861
+ }
6862
+ function nearMatches(name, columns) {
6863
+ const wanted = loose(name);
6864
+ if (wanted.length === 0) return [];
6865
+ return columns.map((column) => ({ column, distance: distanceTo(wanted, loose(column)) })).filter((scored) => scored.distance !== null).sort((a, b) => a.distance - b.distance).slice(0, MAX_NEAR_MATCHES).map((scored) => scored.column);
6866
+ }
6867
+ function distanceTo(wanted, column) {
6868
+ const edits = editDistance(wanted, column);
6869
+ if (edits <= Math.max(1, Math.floor(Math.min(wanted.length, column.length) / 4))) return edits;
6870
+ if (wanted.length >= 3 && (column.includes(wanted) || wanted.includes(column)) && column.length > 0) {
6871
+ return 100 + Math.abs(column.length - wanted.length);
6872
+ }
6873
+ return null;
6874
+ }
6875
+ function editDistance(a, b) {
6876
+ let previous = Array.from({ length: b.length + 1 }, (_, j) => j);
6877
+ for (let i = 1; i <= a.length; i++) {
6878
+ const current = [i];
6879
+ for (let j = 1; j <= b.length; j++) {
6880
+ current[j] = Math.min(
6881
+ previous[j] + 1,
6882
+ current[j - 1] + 1,
6883
+ previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
6605
6884
  );
6606
- const summary = triggers.map((t) => ({
6607
- triggerId: t.triggerId,
6608
- type: t.type,
6885
+ }
6886
+ previous = current;
6887
+ }
6888
+ return previous[b.length];
6889
+ }
6890
+ function take(name, columns, into, problems) {
6891
+ const match = matchColumn(name, columns);
6892
+ if (match.kind === "column") {
6893
+ if (!into.includes(match.column)) into.push(match.column);
6894
+ return true;
6895
+ }
6896
+ if (match.kind === "ambiguous") problems.ambiguous.push({ name, candidates: match.candidates });
6897
+ else problems.unknown.push(name);
6898
+ return false;
6899
+ }
6900
+ function refuse(problems, columns, analysisId) {
6901
+ const sentences = [];
6902
+ if (problems.unknown.length === 1) {
6903
+ sentences.push(`${quoteColumn(problems.unknown[0])} is not a column of the analysis data.`);
6904
+ } else if (problems.unknown.length > 1) {
6905
+ sentences.push(`These are not columns of the analysis data: ${problems.unknown.map(quoteColumn).join(", ")}.`);
6906
+ }
6907
+ for (const { name, candidates } of problems.ambiguous) {
6908
+ sentences.push(`${quoteColumn(name)} matches more than one column: ${candidates.map(quoteColumn).join(", ")}. Type the one you mean exactly.`);
6909
+ }
6910
+ const hints = [];
6911
+ const near = [...new Set(problems.unknown.flatMap((name) => nearMatches(name, columns)))];
6912
+ if (near.length > 0) hints.push(`Did you mean ${near.map(quoteColumn).join(" or ")}?`);
6913
+ const listed2 = columns.slice(0, MAX_COLUMNS_LISTED).map(quoteColumn).join(", ");
6914
+ const more = columns.length > MAX_COLUMNS_LISTED ? ` and ${columns.length - MAX_COLUMNS_LISTED} more${analysisId ? ` ('diafunc analyze columns ${analysisId}' lists them all)` : ""}` : "";
6915
+ hints.push(`The columns are: ${listed2}${more}.`);
6916
+ if (problems.fromList) {
6917
+ hints.push(`A name that contains a comma is an argument of its own, or goes in double quotes inside a list: '"a, b",c'.`);
6918
+ }
6919
+ throw new CliError(sentences.join(" "), { exitCode: EXIT_USAGE, hint: hints.join("\n ") });
6920
+ }
6921
+ function resolveColumnArguments(given, columns, analysisId) {
6922
+ const resolved = [];
6923
+ if (columns.length === 0) {
6924
+ for (const name of given.flatMap(parseColumnList)) {
6925
+ if (!resolved.includes(name)) resolved.push(name);
6926
+ }
6927
+ return resolved;
6928
+ }
6929
+ const problems = { unknown: [], ambiguous: [], fromList: false };
6930
+ for (const argument of given) {
6931
+ if (argument.trim().length === 0) continue;
6932
+ const whole = matchColumn(argument, columns);
6933
+ if (whole.kind === "column") {
6934
+ if (!resolved.includes(whole.column)) resolved.push(whole.column);
6935
+ continue;
6936
+ }
6937
+ const names = parseColumnList(argument);
6938
+ const single = names.length === 1 && names[0] === argument.trim();
6939
+ for (const name of names) {
6940
+ if (!take(name, columns, resolved, problems) && !single) problems.fromList = true;
6941
+ }
6942
+ }
6943
+ if (problems.unknown.length > 0 || problems.ambiguous.length > 0) refuse(problems, columns, analysisId);
6944
+ return resolved;
6945
+ }
6946
+ function resolveColumnNames(names, columns, analysisId) {
6947
+ if (columns.length === 0) return [...names];
6948
+ const resolved = [];
6949
+ const problems = { unknown: [], ambiguous: [], fromList: false };
6950
+ for (const name of names) take(name, columns, resolved, problems);
6951
+ if (problems.unknown.length > 0 || problems.ambiguous.length > 0) refuse(problems, columns, analysisId);
6952
+ return resolved;
6953
+ }
6954
+ function resolveColumnArgument(given, columns, analysisId) {
6955
+ if (columns.length === 0) return given;
6956
+ return resolveColumnNames([given], columns, analysisId)[0];
6957
+ }
6958
+ function occurrences(value) {
6959
+ if (value === void 0) return void 0;
6960
+ return Array.isArray(value) ? value : [value];
6961
+ }
6962
+ function collectColumns(value, previous = []) {
6963
+ return previous.concat([value]);
6964
+ }
6965
+
6966
+ // src/commands/analyze/intent.ts
6967
+ var MAX_INTENT_LENGTH = 8e3;
6968
+ var MAX_PAIRS = 12;
6969
+ var MAX_FOCUS = 3;
6970
+ var CHART_KINDS = ["scatter", "groups", "counts"];
6971
+ var SHAPE_KINDS = ["increasing", "decreasing", "convex", "concave", "range"];
6972
+ var FOCUS_FAMILIES = [
6973
+ { id: "formula", label: "the formula" },
6974
+ { id: "accuracy", label: "how accurate the model is" },
6975
+ { id: "input_importance", label: "which inputs matter most" },
6976
+ { id: "search", label: "how the search went" },
6977
+ { id: "baselines", label: "the comparison with simple baselines" },
6978
+ { id: "partial_dependence", label: "how each input moves the prediction" },
6979
+ { id: "extrapolation", label: "behavior outside the observed range" },
6980
+ { id: "what_if", label: "what-if scenarios and sensitivity" },
6981
+ { id: "interactions", label: "interactions between inputs" },
6982
+ { id: "term_ablation", label: "what each term of the formula adds" },
6983
+ { id: "residuals", label: "errors and prediction intervals" },
6984
+ { id: "temporal", label: "behavior over time" },
6985
+ { id: "classification", label: "classification performance" },
6986
+ { id: "rating_levels", label: "the rating levels" },
6987
+ { id: "count_distribution", label: "the distribution of counts" },
6988
+ { id: "segments", label: "differences between groups" },
6989
+ { id: "fairness", label: "fairness across groups of people" },
6990
+ { id: "out_of_distribution", label: "inputs unlike the training data" },
6991
+ { id: "causality", label: "whether the relationships are causal" },
6992
+ { id: "deployment", label: "whether the model is ready to use" },
6993
+ { id: "multiple_targets", label: "how the targets relate to each other" },
6994
+ { id: "columns", label: "what each column holds" },
6995
+ { id: "correlations", label: "how the columns move together" },
6996
+ { id: "leakage", label: "columns that give the answer away" },
6997
+ { id: "duplicates", label: "duplicate rows" },
6998
+ { id: "trends", label: "trends over time in the data" },
6999
+ { id: "geography", label: "where the rows are located" }
7000
+ ];
7001
+ function notesFromOptions(options) {
7002
+ if (options.intent !== void 0 && options.intentFile !== void 0) {
7003
+ usageError("Give the notes with --intent or with --intent-file, not both.");
7004
+ }
7005
+ let text2 = options.intent;
7006
+ if (options.intentFile !== void 0) {
7007
+ if (!fs9.existsSync(options.intentFile)) {
7008
+ throw new CliError(`File not found: ${options.intentFile}`, { exitCode: EXIT_USAGE });
7009
+ }
7010
+ text2 = fs9.readFileSync(options.intentFile, "utf8");
7011
+ }
7012
+ if (text2 === void 0) return void 0;
7013
+ checkNotesLength(text2);
7014
+ return text2.trim();
7015
+ }
7016
+ function checkNotesLength(text2) {
7017
+ if (text2.length > MAX_INTENT_LENGTH) {
7018
+ usageError(`The notes are ${text2.length.toLocaleString("en-US")} characters long; at most ${MAX_INTENT_LENGTH.toLocaleString("en-US")} are kept.`, "Shorten them and run it again.");
7019
+ }
7020
+ }
7021
+ function checkedStatement(statement) {
7022
+ const text2 = statement.trim();
7023
+ const refuse2 = (why) => usageError(
7024
+ `'${statement}' is not a shape expectation: ${why}.`,
7025
+ "Write one of increasing(input), decreasing(input, from, to), convex(input), concave(input) or range(lower, upper), with 'check:' (the default) or 'require:' in front."
7026
+ );
7027
+ if (text2.length === 0) refuse2("it is empty");
7028
+ if (/[;\n]/.test(text2)) refuse2("give one expectation per statement");
7029
+ let body = text2;
7030
+ const colon = text2.indexOf(":");
7031
+ const open = text2.indexOf("(");
7032
+ if (colon > 0 && (open < 0 || colon < open)) {
7033
+ const mode = text2.slice(0, colon).trim().toLowerCase();
7034
+ if (mode !== "check" && mode !== "require") refuse2(`the mode '${mode}' is neither check nor require`);
7035
+ body = text2.slice(colon + 1).trim();
7036
+ }
7037
+ const kindEnd = body.indexOf("(");
7038
+ if (kindEnd <= 0 || !body.endsWith(")")) refuse2("it has no kind(arguments) form");
7039
+ const kind = body.slice(0, kindEnd).trim().toLowerCase();
7040
+ if (!SHAPE_KINDS.includes(kind)) refuse2(`'${kind}' is not a kind of expectation`);
7041
+ return text2;
7042
+ }
7043
+ function parseShapeFlag(given) {
7044
+ const equals = given.lastIndexOf("=");
7045
+ if (equals <= 0) {
7046
+ usageError(`'${given}' names no target.`, "Write --shape <target>=<statement>, for example --shape 'price=increasing(size_m2)'.");
7047
+ }
7048
+ const target = given.slice(0, equals).trim();
7049
+ if (target.length === 0) usageError(`'${given}' names no target.`);
7050
+ return { target, statement: checkedStatement(given.slice(equals + 1)) };
7051
+ }
7052
+ function shapesOf(given) {
7053
+ if (given === void 0 || given.length === 0) return null;
7054
+ const byTarget = {};
7055
+ for (const flag of given) {
7056
+ const { target, statement } = parseShapeFlag(flag);
7057
+ byTarget[target] ??= [];
7058
+ if (!byTarget[target].includes(statement)) byTarget[target].push(statement);
7059
+ }
7060
+ return byTarget;
7061
+ }
7062
+ function resolveShapeTargets(byTarget, columns, analysisId) {
7063
+ const resolved = {};
7064
+ for (const [target, statements] of Object.entries(byTarget)) {
7065
+ const column = resolveColumnArgument(target, columns, analysisId);
7066
+ resolved[column] = [...resolved[column] ?? [], ...statements.filter((s) => !(resolved[column] ?? []).includes(s))];
7067
+ }
7068
+ return resolved;
7069
+ }
7070
+ function boundText(text2) {
7071
+ const trimmed = text2.trim();
7072
+ const n = Number(trimmed);
7073
+ return Number.isFinite(n) ? n.toLocaleString("en-US", { maximumFractionDigits: 6 }) : trimmed;
7074
+ }
7075
+ function isOpen(text2) {
7076
+ if (text2 === void 0) return true;
7077
+ const t = text2.trim().toLowerCase();
7078
+ return t === "" || t === "inf" || t === "+inf" || t === "-inf" || t === "infinity" || t === "-infinity";
7079
+ }
7080
+ function expectationText(target, statement) {
7081
+ const read = /^\s*(?:(check|require)\s*:)?\s*([a-z]+)\s*\((.*)\)\s*$/i.exec(statement);
7082
+ if (!read) return `${target}: ${statement}`;
7083
+ const steer = (read[1] ?? "check").toLowerCase() === "require";
7084
+ const kind = read[2].toLowerCase();
7085
+ const args = read[3].split(",").map((a) => a.trim());
7086
+ const mode = steer ? "Steers the model" : "Checked";
7087
+ if (kind === "range") {
7088
+ const [lower, upper] = args;
7089
+ const sentence = !isOpen(lower) && !isOpen(upper) ? `${target} stays between ${boundText(lower)} and ${boundText(upper)}` : !isOpen(lower) ? `${target} is never below ${boundText(lower)}` : !isOpen(upper) ? `${target} is never above ${boundText(upper)}` : `${target} has no bound`;
7090
+ return `${sentence}. ${mode}.`;
7091
+ }
7092
+ const input = args[0];
7093
+ const shape = kind === "increasing" ? `does not fall as ${input} grows` : kind === "decreasing" ? `does not rise as ${input} grows` : kind === "convex" ? `curves upward as ${input} grows` : kind === "concave" ? `levels off as ${input} grows` : null;
7094
+ if (!shape) return `${target}: ${statement}`;
7095
+ const window = args.length === 3 && !(isOpen(args[1]) && isOpen(args[2])) ? ` (${input} ${boundText(args[1])} to ${boundText(args[2])})` : args.length === 1 ? ` (across the observed ${input} values)` : "";
7096
+ return `${target} ${shape}${window}. ${mode}.`;
7097
+ }
7098
+ function expectationLines(byTarget) {
7099
+ if (!byTarget) return [];
7100
+ return Object.entries(byTarget).flatMap(([target, statements]) => statements.map((s) => expectationText(target, s)));
7101
+ }
7102
+ function parsePair(given) {
7103
+ const entries = parseColumnList(given);
7104
+ const usage = `Write <first>,<second> or <first>,<second>,<kind> with kind one of ${CHART_KINDS.join(", ")}; a column whose name holds a comma goes in double quotes: '"a, b",price'.`;
7105
+ if (entries.length < 2 || entries.length > 3) {
7106
+ usageError(`'${given}' is not a chart: it names ${entries.length} ${entries.length === 1 ? "entry" : "entries"}.`, usage);
7107
+ }
7108
+ let kind = null;
7109
+ if (entries.length === 3) {
7110
+ const typed2 = entries[2].trim().toLowerCase();
7111
+ if (!CHART_KINDS.includes(typed2)) {
7112
+ usageError(`'${entries[2]}' is not a chart kind.`, usage);
7113
+ }
7114
+ kind = typed2;
7115
+ }
7116
+ if (entries[0] === entries[1]) usageError(`'${given}' names the same column twice; a chart needs two different columns.`);
7117
+ return { first: entries[0], second: entries[1], kind };
7118
+ }
7119
+ function pairsOf(given) {
7120
+ if (given === void 0) return null;
7121
+ const pairs = [];
7122
+ for (const entry of given) {
7123
+ if (entry.trim().length === 0) continue;
7124
+ const pair = parsePair(entry);
7125
+ if (!pairs.some((p) => p.first === pair.first && p.second === pair.second && p.kind === pair.kind)) pairs.push(pair);
7126
+ }
7127
+ if (pairs.length > MAX_PAIRS) usageError(`${pairs.length} charts are asked for; at most ${MAX_PAIRS} can be.`);
7128
+ return pairs;
7129
+ }
7130
+ function resolvePairs(pairs, columns, analysisId) {
7131
+ return pairs.map((pair) => {
7132
+ const [first, second] = resolveColumnNames([pair.first, pair.second], columns, analysisId);
7133
+ if (second === void 0) {
7134
+ usageError(`${quoteColumn(pair.first)} and ${quoteColumn(pair.second)} are the same column; a chart needs two different columns.`);
7135
+ }
7136
+ return { first, second, kind: pair.kind };
7137
+ });
7138
+ }
7139
+ function pairText(pair) {
7140
+ const how = pair.kind === "scatter" ? " as a scatter plot" : pair.kind === "groups" ? " by group" : pair.kind === "counts" ? " as counts" : "";
7141
+ return `${pair.second} against ${pair.first}${how}`;
7142
+ }
7143
+ function familyId(typed2) {
7144
+ return typed2.trim().toLowerCase().replace(/[- ]/g, "_");
7145
+ }
7146
+ function focusOf(given) {
7147
+ if (given === void 0) return null;
7148
+ const families = [];
7149
+ const unknown = [];
7150
+ for (const typed2 of given.flatMap((g) => g.split(","))) {
7151
+ if (typed2.trim().length === 0) continue;
7152
+ const id = familyId(typed2);
7153
+ if (!FOCUS_FAMILIES.some((f) => f.id === id)) unknown.push(typed2.trim());
7154
+ else if (!families.includes(id)) families.push(id);
7155
+ }
7156
+ if (unknown.length > 0) {
7157
+ usageError(
7158
+ `${unknown.map((u) => `'${u}'`).join(", ")} ${unknown.length === 1 ? "is not a question family" : "are not question families"}.`,
7159
+ `The families are: ${FOCUS_FAMILIES.map((f) => f.id).join(", ")}.`
7160
+ );
7161
+ }
7162
+ if (families.length > MAX_FOCUS) {
7163
+ usageError(`${families.length} families are named; at most ${MAX_FOCUS} can be in focus.`, "Name the ones that matter most.");
7164
+ }
7165
+ return families;
7166
+ }
7167
+ function focusText(id) {
7168
+ return FOCUS_FAMILIES.find((f) => f.id === id)?.label ?? id;
7169
+ }
7170
+ function intentRecipeLines(analysis) {
7171
+ const lines = [];
7172
+ const statements = Object.values(analysis.shapeExpectations ?? {}).flat();
7173
+ if (statements.length > 0) {
7174
+ const steering = statements.filter((s) => /^\s*require\s*:/i.test(s)).length;
7175
+ const checked = statements.length - steering;
7176
+ const parts = [checked > 0 ? `${checked} checked` : null, steering > 0 ? `${steering} ${steering === 1 ? "steers" : "steer"} the model` : null].filter(Boolean);
7177
+ lines.push(`Expectations: ${parts.join(", ")}`);
7178
+ }
7179
+ const pairs = analysis.requestedPairs ?? [];
7180
+ if (pairs.length > 0) lines.push(`Charts: ${pairs.map(pairText).join("; ")}`);
7181
+ const focus = analysis.focusFamilies ?? [];
7182
+ if (focus.length > 0) lines.push(`Focus: ${focus.map(focusText).join(", ")}`);
7183
+ return lines;
7184
+ }
7185
+ function interpretRequestOf(analysis, intent) {
7186
+ return {
7187
+ intent,
7188
+ targets: analysis.targets ?? [],
7189
+ segment: analysis.segment ?? null,
7190
+ inputExclusions: analysis.inputExclusions ?? [],
7191
+ targetKinds: analysis.targetKinds ?? {}
7192
+ };
7193
+ }
7194
+ var PROFILE_ATTEMPTS = 10;
7195
+ var PROFILE_INTERVAL_MS = 2e3;
7196
+ function waitingForProfile(interpretation) {
7197
+ return interpretation.status === "UNAVAILABLE" && (interpretation.findings ?? []).some((f) => /profiled/i.test(f.text ?? ""));
7198
+ }
7199
+ function isProfilePending(error) {
7200
+ return error instanceof ApiError && error.status === 400 && /profiled/i.test(error.message);
7201
+ }
7202
+ var pause2 = (ms) => new Promise((resolve2) => setTimeout(resolve2, ms));
7203
+ async function readNotes(api, analysisId, request, options = {}) {
7204
+ let interpretation = await api.analysis.interpretIntent(analysisId, request, options);
7205
+ for (let attempt = 1; attempt < PROFILE_ATTEMPTS && waitingForProfile(interpretation); attempt++) {
7206
+ await pause2(PROFILE_INTERVAL_MS);
7207
+ interpretation = await api.analysis.interpretIntent(analysisId, request, options);
7208
+ }
7209
+ return interpretation;
7210
+ }
7211
+ async function whenProfiled(save) {
7212
+ for (let attempt = 1; ; attempt++) {
7213
+ try {
7214
+ return await save();
7215
+ } catch (error) {
7216
+ if (attempt >= PROFILE_ATTEMPTS || !isProfilePending(error)) throw error;
7217
+ await pause2(PROFILE_INTERVAL_MS);
7218
+ }
7219
+ }
7220
+ }
7221
+ function effectLabel(item) {
7222
+ switch (item.effect) {
7223
+ case "checks":
7224
+ return item.steer ? "Steers the model" : "Checks the model";
7225
+ case "changes":
7226
+ return "Changes what is analyzed";
7227
+ case "presents":
7228
+ return item.kind === "pair" ? "Adds a chart" : item.kind === "question" ? "Adds a question" : item.kind === "focus" ? "Sets the focus" : "Changes what the report shows";
7229
+ case "note":
7230
+ return "A note only";
7231
+ case "unavailable":
7232
+ return "Not possible on this run";
7233
+ default:
7234
+ return item.effect;
7235
+ }
7236
+ }
7237
+ function stateLabel(state) {
7238
+ return state === "CONFIRMED" ? "Used" : state === "DECLINED" ? "Not used" : "Proposed";
7239
+ }
7240
+ function groupOf(item) {
7241
+ if (item.effect === "checks" || item.effect === "changes") return 0;
7242
+ if (item.effect === "presents") return 1;
7243
+ if (item.effect === "note") return 2;
7244
+ return 3;
7245
+ }
7246
+ var GROUP_HEADINGS = [
7247
+ "About the model and the data",
7248
+ "What the report shows",
7249
+ "Notes for the report",
7250
+ "Not possible on this run"
7251
+ ];
7252
+ function orderedItems(items) {
7253
+ return [...items].sort((a, b) => groupOf(a) - groupOf(b));
7254
+ }
7255
+ function printInterpretation(interpretation, analysisId) {
7256
+ const items = orderedItems(interpretation.items ?? []);
7257
+ if (interpretation.status === "EMPTY") {
7258
+ console.log(chalk19.dim("No notes to read."));
7259
+ hint(`Write them with 'diafunc analyze intent ${analysisId} "<text>"'.`);
7260
+ return;
7261
+ }
7262
+ if (interpretation.status === "UNAVAILABLE") {
7263
+ for (const finding of interpretation.findings ?? []) warn(finding.text);
7264
+ if ((interpretation.findings ?? []).length === 0) warn("Your notes could not be read just now. Nothing was changed.");
7265
+ return;
7266
+ }
7267
+ if (items.length === 0) console.log(chalk19.dim("Nothing in the notes could be turned into a proposal."));
7268
+ let group = -1;
7269
+ for (const item of items) {
7270
+ if (groupOf(item) !== group) {
7271
+ group = groupOf(item);
7272
+ heading(GROUP_HEADINGS[group]);
7273
+ }
7274
+ console.log(` ${chalk19.cyan(item.id)} ${stateLabel(item.state)} \xB7 ${effectLabel(item)}`);
7275
+ console.log(` ${item.statement}`);
7276
+ if (item.quote) detail(` from: "${item.quote}"`);
7277
+ }
7278
+ const notUnderstood = interpretation.notUnderstood ?? [];
7279
+ if (notUnderstood.length > 0) {
7280
+ heading("Not understood");
7281
+ for (const note of notUnderstood) console.log(` "${note.quote}"${note.reason ? `: ${note.reason}` : ""}`);
7282
+ }
7283
+ const rejections = interpretation.rejections ?? [];
7284
+ if (rejections.length > 0) {
7285
+ heading("Not used");
7286
+ for (const note of rejections) console.log(` "${note.quote}"${note.reason ? `: ${note.reason}` : ""}`);
7287
+ }
7288
+ const findings = interpretation.findings ?? [];
7289
+ if (findings.length > 0) {
7290
+ heading("Before you launch");
7291
+ for (const finding of findings) console.log(` ${finding.title ? `${finding.title}: ` : ""}${finding.text}`);
7292
+ }
7293
+ if (items.some((item) => item.state === "PROPOSED" && item.effect !== "unavailable")) {
7294
+ console.log();
7295
+ hint("Nothing changes until you confirm a proposal. Expectations are checked; add --steer to let one steer the model.");
7296
+ hint(`Use one with 'diafunc analyze intent confirm ${analysisId} <proposalId...>', or 'decline' it.`);
7297
+ }
7298
+ }
7299
+ async function promptIntentDecisions(prompter, interpretation) {
7300
+ const decisions = [];
7301
+ for (const item of orderedItems(interpretation.items ?? [])) {
7302
+ if (item.state !== "PROPOSED" || item.effect === "unavailable") continue;
7303
+ if (item.quote) detail(`from your notes: "${item.quote}"`);
7304
+ const use = await prompter.confirm({
7305
+ message: `${item.statement} (${effectLabel(item)}) Use it?`,
7306
+ default: item.effect === "presents"
7307
+ });
7308
+ if (!use) {
7309
+ decisions.push({ id: item.id, state: "DECLINED", steer: null });
7310
+ continue;
7311
+ }
7312
+ const steer = item.effect === "checks" ? await prompter.confirm({
7313
+ message: "Also use it to steer the model? Without steering it is checked and reported, and never decides which model is delivered.",
7314
+ default: false
7315
+ }) : null;
7316
+ decisions.push({ id: item.id, state: "CONFIRMED", steer });
7317
+ }
7318
+ return decisions;
7319
+ }
7320
+ function printUnavailable(interpretation) {
7321
+ for (const item of interpretation.items ?? []) {
7322
+ if (item.effect === "unavailable") warn(item.statement);
7323
+ }
7324
+ }
7325
+
7326
+ // src/prompting/resolvers.ts
7327
+ var PROJECT_ROLES = ["OWNER", "ADMIN", "DEVELOPER", "GUEST"];
7328
+ var TRIGGER_TYPES = ["CRON", "INTERVAL", "CONTINUOUS", "EVENT"];
7329
+ var ANALYSIS_TRIGGER_KINDS = ["ONCE", "CRON"];
7330
+ var VISIBILITIES = ["PRIVATE", "PUBLIC"];
7331
+ var SHELLS = ["bash", "zsh", "fish"];
7332
+ var CONFIG_KEYS = ["defaults.project", "defaults.branch", "defaults.output"];
7333
+ var ENTITY_TYPE_BY_GROUP = {
7334
+ table: "table",
7335
+ function: "function",
7336
+ trigger: "function",
7337
+ schedule: "function"
7338
+ };
7339
+ var TEXT = { kind: "text" };
7340
+ var TEXT_OR_EMPTY = { kind: "text", allowEmpty: true };
7341
+ var POSITIVE = { kind: "number", min: 0, integer: false, exclusive: true };
7342
+ var INDEX = { kind: "number", min: 0, integer: true };
7343
+ var BY_COMMAND = {
7344
+ "analyze segment": { "<name>": { kind: "analysisColumns", multiple: false, allowEmpty: true } },
7345
+ "analyze targets": { "<column>": { kind: "analysisColumns", multiple: true, allowEmpty: false } },
7346
+ "analyze input-exclusions": { "<column>": { kind: "analysisColumns", multiple: true, allowEmpty: true } },
7347
+ "analyze confirmed-inputs": { "<column>": { kind: "analysisColumns", multiple: true, allowEmpty: true } },
7348
+ "analyze questions": { "<question>": TEXT_OR_EMPTY },
7349
+ "analyze description": { "<text>": TEXT_OR_EMPTY },
7350
+ "analyze introduction": { "<markdown>": TEXT_OR_EMPTY },
7351
+ "analyze intent confirm": { "<proposalId>": TEXT },
7352
+ "analyze intent decline": { "<proposalId>": TEXT },
7353
+ "analyze intent reset": { "<proposalId>": TEXT },
7354
+ "analyze charts": { "<pair>": TEXT_OR_EMPTY },
7355
+ "analyze focus": { "<family>": { kind: "choices", choices: FOCUS_FAMILIES.map((f) => f.id) } },
7356
+ // Not the analysis picker: that one offers the reader's own analyses, and this command needs no account.
7357
+ "public show": { "<analysisId>": TEXT },
7358
+ "analyze presets save": { "--targets": TEXT, "--hours": POSITIVE, "--budget": POSITIVE },
7359
+ "branch merge": {
7360
+ "--source": { kind: "entity", form: "ref" },
7361
+ "--target": { kind: "project", withBranch: true }
7362
+ },
7363
+ "branch create": { "<branchName>": TEXT },
7364
+ "branch delete": { "<branchName>": { kind: "projectBranch", projectFrom: "projectId" } },
7365
+ "admin backup restore-project": { "<projectBranch>": { kind: "projectBranch", projectFrom: "projectId" } },
7366
+ "data-sources create": {
7367
+ "--project-id": { kind: "project", withBranch: false },
7368
+ "--project-branch": { kind: "projectBranch", projectFrom: "projectId" },
7369
+ "--target-entity-id": { kind: "entity", form: "id", contentType: "table", projectFrom: "projectId" },
7370
+ "--target-entity-branch": { kind: "text", defaultValue: "main" },
7371
+ "--type": { kind: "connectorType" }
7372
+ },
7373
+ "table-exporters create": {
7374
+ "--function-project": { kind: "project", withBranch: false },
7375
+ "--function-entity": { kind: "entity", form: "id", contentType: "function", projectFrom: "functionProject" },
7376
+ "--format": TEXT
7377
+ },
7378
+ "table exports get": { "--ref": { kind: "entity", form: "ref", contentType: "table" } },
7379
+ "table export": { "<format>": { kind: "exportFormat" } },
7380
+ "entity export": { "<entityIds>": { kind: "entity", form: "id", projectFrom: "project", multiple: true } },
7381
+ "notebook export": {
7382
+ "<notebookIds>": { kind: "entity", form: "id", contentType: "notebook", projectFrom: "project", multiple: true }
7383
+ },
7384
+ "entity tags set": { "<tags>": TEXT_OR_EMPTY },
7385
+ "project tags set": { "<tags>": TEXT_OR_EMPTY },
7386
+ "admin curated-tags create": { "--display-name": TEXT },
7387
+ "link delete": { "<linkId>": { kind: "link" } },
7388
+ "link create": { "<linkId>": TEXT },
7389
+ "config profile use": { "<name>": { kind: "profile" } },
7390
+ "config profile remove": { "<name>": { kind: "profile" } },
7391
+ "config get": { "<key>": { kind: "choice", choices: CONFIG_KEYS } },
7392
+ "config set": { "<key>": { kind: "choice", choices: CONFIG_KEYS } },
7393
+ "project members invite": { "<userId>": TEXT, "<role>": { kind: "choice", choices: PROJECT_ROLES } },
7394
+ "project members join": { "<userId>": TEXT },
7395
+ "trigger create": { "--type": { kind: "choice", choices: TRIGGER_TYPES } },
7396
+ "analyze triggers create": { "--kind": { kind: "choice", choices: ANALYSIS_TRIGGER_KINDS } },
7397
+ "function outputs": { "<evaluationId>": TEXT },
7398
+ "team create": { "--seats": { kind: "number", min: 1, integer: true } },
7399
+ "team seats preview": { "<count>": { kind: "number", min: 1, integer: true } },
7400
+ "team seats set": { "<count>": { kind: "number", min: 1, integer: true } }
7401
+ };
7402
+ var BY_NAME = {
7403
+ projectId: { kind: "project", withBranch: false },
7404
+ projectRef: { kind: "project", withBranch: true },
7405
+ project: { kind: "project", withBranch: true },
7406
+ teamId: { kind: "team" },
7407
+ invitationId: { kind: "teamInvitation" },
7408
+ analysisId: { kind: "analysis" },
7409
+ licenseId: { kind: "license" },
7410
+ sessionId: { kind: "chatSession" },
7411
+ tokenId: { kind: "apiToken" },
7412
+ resource: { kind: "tokenResource" },
7413
+ scopes: { kind: "choices", choices: VALID_SCOPES },
7414
+ evaluationId: { kind: "evaluation" },
7415
+ eventId: { kind: "event" },
7416
+ occurrenceId: { kind: "occurrence" },
7417
+ exportId: { kind: "tableExport" },
7418
+ invoiceNumber: { kind: "invoice" },
7419
+ fileName: { kind: "invoiceDocument" },
7420
+ shell: { kind: "choice", choices: SHELLS },
7421
+ vis: { kind: "choice", choices: VISIBILITIES },
7422
+ kind: { kind: "choice", choices: ANALYSIS_TRIGGER_KINDS },
7423
+ date: { kind: "date" },
7424
+ file: { kind: "file" },
7425
+ email: { kind: "text", email: true },
7426
+ index: INDEX,
7427
+ row: INDEX,
7428
+ col: INDEX,
7429
+ count: INDEX,
7430
+ version: { kind: "number", min: 1, integer: true },
7431
+ hours: POSITIVE,
7432
+ credits: POSITIVE,
7433
+ seats: { kind: "number", min: 1, integer: true },
7434
+ value: TEXT_OR_EMPTY,
7435
+ // Free text: names, messages and ids the reader is creating rather than choosing.
7436
+ name: TEXT,
7437
+ tag: TEXT,
7438
+ tags: TEXT,
7439
+ newId: TEXT,
7440
+ message: TEXT,
7441
+ query: TEXT,
7442
+ title: TEXT,
7443
+ token: TEXT,
7444
+ subscriptionToken: TEXT,
7445
+ forkProjectId: TEXT,
7446
+ targetBranch: TEXT,
7447
+ bucketName: TEXT,
7448
+ objectName: TEXT,
7449
+ template: TEXT,
7450
+ plan: TEXT,
7451
+ schedule: TEXT,
7452
+ consumerType: TEXT,
7453
+ consumerId: TEXT,
7454
+ format: TEXT,
7455
+ key: TEXT
7456
+ };
7457
+ function tokenOf(input) {
7458
+ return input.kind === "option" ? input.flag ?? `--${input.name}` : `<${input.name}>`;
7459
+ }
7460
+ function specFor(path13, input) {
7461
+ const exact = BY_COMMAND[path13]?.[tokenOf(input)];
7462
+ if (exact) return exact;
7463
+ const group = path13.split(" ")[0];
7464
+ const sub = path13.split(" ").slice(0, 2).join(" ");
7465
+ switch (input.name) {
7466
+ case "ref":
7467
+ case "sourceRef":
7468
+ case "targetRef":
7469
+ return { kind: "entity", form: "ref", contentType: ENTITY_TYPE_BY_GROUP[group] };
7470
+ case "userId":
7471
+ return group === "team" ? { kind: "teamMember" } : { kind: "projectMember" };
7472
+ case "id":
7473
+ if (sub === "analyze presets") return { kind: "preset" };
7474
+ if (group === "analyze") return { kind: "analysis" };
7475
+ if (group === "data-sources") return { kind: "dataSource" };
7476
+ if (group === "skeleton") return { kind: "skeleton" };
7477
+ if (group === "table-exporters") return { kind: "tableExporter" };
7478
+ if (group === "status") return { kind: "statusComponent" };
7479
+ return null;
7480
+ case "runId":
7481
+ if (group === "analyze") return { kind: "analysisRun" };
7482
+ if (group === "data-sources") return { kind: "dataSourceRun" };
7483
+ return null;
7484
+ case "triggerId":
7485
+ if (group === "analyze") return { kind: "analysisTrigger" };
7486
+ if (group === "trigger") return { kind: "functionTrigger" };
7487
+ return null;
7488
+ case "role":
7489
+ return { kind: "choice", choices: PROJECT_ROLES };
7490
+ case "type":
7491
+ return null;
7492
+ default:
7493
+ return BY_NAME[input.name] ?? null;
7494
+ }
7495
+ }
7496
+ function dependencies(spec) {
7497
+ switch (spec.kind) {
7498
+ case "teamMember":
7499
+ case "teamInvitation":
7500
+ return ["teamId"];
7501
+ case "projectMember":
7502
+ return ["projectId"];
7503
+ case "analysisColumns":
7504
+ return ["id"];
7505
+ case "evaluation":
7506
+ return ["ref", "date"];
7507
+ case "functionTrigger":
7508
+ case "event":
7509
+ case "tableExport":
7510
+ return ["ref"];
7511
+ case "occurrence":
7512
+ return ["ref", "eventId"];
7513
+ case "link":
7514
+ return ["sourceRef"];
7515
+ case "tokenResource":
7516
+ return ["resourceType"];
7517
+ case "dataSourceRun":
7518
+ return ["id"];
7519
+ case "invoiceDocument":
7520
+ return ["invoiceNumber"];
7521
+ case "projectBranch":
7522
+ return [spec.projectFrom];
7523
+ case "entity":
7524
+ return spec.projectFrom ? [spec.projectFrom] : [];
7525
+ default:
7526
+ return [];
7527
+ }
7528
+ }
7529
+
7530
+ // src/commands/trigger/index.ts
7531
+ function getOutputFormat11(cmd) {
7532
+ const config = loadConfig();
7533
+ const globalOpts = cmd.optsWithGlobals();
7534
+ return globalOpts.output ?? config.defaults.output ?? "human";
7535
+ }
7536
+ function getOverrides9(cmd) {
7537
+ const opts = cmd.optsWithGlobals();
7538
+ return { project: opts.project, branch: opts.branch };
7539
+ }
7540
+ function registerTriggerCommands(program) {
7541
+ const trigger = program.command("trigger").description("Manage function triggers").addHelpText("after", `
7542
+ Examples:
7543
+ $ diafunc trigger list <ref>
7544
+ $ diafunc trigger create <ref> --type CRON --expression '0 0 6 * * ?' every day at 06:00 (Quartz cron)
7545
+ $ diafunc trigger create <ref> --type INTERVAL --expression '15min' every 15 minutes
7546
+ $ diafunc trigger delete <ref> <triggerId>
7547
+ `);
7548
+ trigger.command("list").description("List triggers for a function").argument("<ref>", "Function entity reference").action(async (ref, _options, cmd) => {
7549
+ try {
7550
+ const outputFormat = getOutputFormat11(cmd);
7551
+ const overrides = getOverrides9(cmd);
7552
+ const resolved = parseEntityReference(ref, overrides);
7553
+ const api = createApiClient();
7554
+ const triggers = await api.evaluation.getTriggers(
7555
+ resolved.projectId,
7556
+ resolved.projectBranch,
7557
+ resolved.entityId,
7558
+ resolved.entityBranch
7559
+ );
7560
+ const summary = triggers.map((t) => ({
7561
+ triggerId: t.triggerId,
7562
+ type: t.type,
6609
7563
  active: t.active,
6610
7564
  expression: t.expression ?? "\u2014",
6611
7565
  fired: t.fired,
6612
- persistent: t.persistent
7566
+ persistent: t.persistent,
7567
+ createdBy: t.createdBy ? t.createdBy : "paused (save it again to resume)"
6613
7568
  }));
6614
7569
  format(summary, {
6615
7570
  format: outputFormat,
6616
- columns: ["triggerId", "type", "active", "expression", "fired", "persistent"]
7571
+ columns: ["triggerId", "type", "active", "expression", "fired", "persistent", "createdBy"]
6617
7572
  });
6618
7573
  } catch (error) {
6619
7574
  handleError(error);
@@ -6654,10 +7609,18 @@ Examples:
6654
7609
  handleError(error);
6655
7610
  }
6656
7611
  });
6657
- trigger.command("create").description("Create or update a trigger on a function").argument("<ref>", "Function entity reference").requiredOption("--type <type>", "Trigger type (SCHEDULE, EVENT, LINK, MANUAL)").option("--trigger-id <id>", "Trigger ID (auto-generated if omitted)").option("--expression <expr>", "Cron expression (for SCHEDULE) or event pattern").option("--origin <ref>", "Origin entity reference (for LINK/EVENT)").option("--persistent", "Persistent trigger (survives after first fire)").option("--inactive", "Create the trigger inactive").option("--max <n>", "Maximum fire count (0 = unlimited)", "0").option("--args <json>", "Arguments passed on fire (JSON object)").action(async (ref, options, cmd) => {
7612
+ trigger.command("create").description("Create or update a trigger on a function").argument("<ref>", "Function entity reference").requiredOption("--type <type>", `Trigger type (${TRIGGER_TYPES.join(", ")})`).option("--trigger-id <id>", "Trigger ID (auto-generated if omitted)").option("--expression <expr>", "CRON: a Quartz cron expression ('0 0 6 * * ?'); INTERVAL: a duration ('15min', '1h 30min')").option("--origin <ref>", "Origin entity reference (for EVENT)").option("--count <n>", "Runs started each time the trigger fires", "1").option("--persistent", "Persistent trigger (survives after first fire)").option("--inactive", "Create the trigger inactive").option("--max <n>", "Maximum fire count (0 = unlimited)", "0").option("--args <json>", "Arguments passed on fire (JSON object)").action(async (ref, options, cmd) => {
6658
7613
  try {
6659
7614
  const overrides = getOverrides9(cmd);
6660
7615
  const fn = parseEntityReference(ref, overrides);
7616
+ const type = String(options.type).toUpperCase();
7617
+ if (!TRIGGER_TYPES.includes(type)) {
7618
+ throw new Error(`Unknown trigger type "${options.type}": use one of ${TRIGGER_TYPES.join(", ")}.`);
7619
+ }
7620
+ const count = Number(options.count);
7621
+ if (!Number.isInteger(count) || count < 1) {
7622
+ throw new Error(`--count must be a whole number of at least 1, not "${options.count}".`);
7623
+ }
6661
7624
  const api = createApiClient();
6662
7625
  const args = options.args ? JSON.parse(options.args) : null;
6663
7626
  const types = args ? Object.fromEntries(
@@ -6677,14 +7640,14 @@ Examples:
6677
7640
  functionBranch: fn.entityBranch,
6678
7641
  triggerId: options.triggerId ?? null,
6679
7642
  bucketId: null,
6680
- type: options.type.toUpperCase(),
7643
+ type,
6681
7644
  expression: options.expression ?? null,
6682
7645
  conditions: null,
6683
7646
  conditionTypes: null,
6684
7647
  originEntityId,
6685
7648
  originEntityBranch,
6686
7649
  active: !options.inactive,
6687
- quantity: 0,
7650
+ quantity: count,
6688
7651
  fired: 0,
6689
7652
  maximum: options.max ? parseInt(options.max, 10) || null : null,
6690
7653
  evaluationIds: null,
@@ -6797,7 +7760,7 @@ function registerScheduleCommands(program) {
6797
7760
  resolved.entityId,
6798
7761
  resolved.entityBranch
6799
7762
  );
6800
- const scheduled = triggers.filter((t) => t.type === "SCHEDULE");
7763
+ const scheduled = triggers.filter((t) => t.type === "CRON" || t.type === "INTERVAL");
6801
7764
  const rows = scheduled.map((t) => ({
6802
7765
  triggerId: t.triggerId,
6803
7766
  expression: t.expression,
@@ -6817,12 +7780,12 @@ function registerScheduleCommands(program) {
6817
7780
  }
6818
7781
 
6819
7782
  // src/commands/chat/index.ts
6820
- import chalk20 from "chalk";
6821
- import * as fs9 from "fs";
7783
+ import chalk21 from "chalk";
7784
+ import * as fs10 from "fs";
6822
7785
  import * as path7 from "path";
6823
7786
 
6824
7787
  // src/output/markdown.ts
6825
- import chalk19 from "chalk";
7788
+ import chalk20 from "chalk";
6826
7789
  var CODE_OPEN = "\0c";
6827
7790
  var CODE_CLOSE = "\0";
6828
7791
  var MarkdownRenderer = class {
@@ -6858,25 +7821,25 @@ var MarkdownRenderer = class {
6858
7821
  if (fence) {
6859
7822
  const opening = !this.inFence;
6860
7823
  this.inFence = !this.inFence;
6861
- return opening && fence[1] ? [chalk19.dim(` ${fence[1]}`)] : [];
7824
+ return opening && fence[1] ? [chalk20.dim(` ${fence[1]}`)] : [];
6862
7825
  }
6863
7826
  if (this.inFence) {
6864
- return [chalk19.cyan(` ${line}`)];
7827
+ return [chalk20.cyan(` ${line}`)];
6865
7828
  }
6866
7829
  const heading2 = line.match(/^(#{1,6})\s+(.*)$/);
6867
7830
  if (heading2) {
6868
7831
  const text2 = inline(heading2[2]);
6869
- return ["", heading2[1].length <= 2 ? chalk19.bold.underline(text2) : chalk19.bold(text2)];
7832
+ return ["", heading2[1].length <= 2 ? chalk20.bold.underline(text2) : chalk20.bold(text2)];
6870
7833
  }
6871
7834
  if (/^\s*([-*_])\1{2,}\s*$/.test(line)) {
6872
- return [chalk19.dim("\u2500".repeat(Math.min(this.width, 60)))];
7835
+ return [chalk20.dim("\u2500".repeat(Math.min(this.width, 60)))];
6873
7836
  }
6874
7837
  const quote2 = line.match(/^\s*>\s?(.*)$/);
6875
- if (quote2) return [chalk19.dim(` \u2502 ${inline(quote2[1])}`)];
7838
+ if (quote2) return [chalk20.dim(` \u2502 ${inline(quote2[1])}`)];
6876
7839
  const bullet = line.match(/^(\s*)[-*+]\s+(.*)$/);
6877
7840
  if (bullet) {
6878
7841
  return wrapWithIndent(
6879
- `${bullet[1]}${chalk19.cyan("\u2022")} ${inline(bullet[2])}`,
7842
+ `${bullet[1]}${chalk20.cyan("\u2022")} ${inline(bullet[2])}`,
6880
7843
  bullet[1].length + 2,
6881
7844
  this.width
6882
7845
  );
@@ -6884,7 +7847,7 @@ var MarkdownRenderer = class {
6884
7847
  const numbered = line.match(/^(\s*)(\d+)\.\s+(.*)$/);
6885
7848
  if (numbered) {
6886
7849
  return wrapWithIndent(
6887
- `${numbered[1]}${chalk19.cyan(`${numbered[2]}.`)} ${inline(numbered[3])}`,
7850
+ `${numbered[1]}${chalk20.cyan(`${numbered[2]}.`)} ${inline(numbered[3])}`,
6888
7851
  numbered[1].length + numbered[2].length + 2,
6889
7852
  this.width
6890
7853
  );
@@ -6907,10 +7870,10 @@ function inline(text2) {
6907
7870
  codeSpans.push(code);
6908
7871
  return `${CODE_OPEN}${codeSpans.length - 1}${CODE_CLOSE}`;
6909
7872
  });
6910
- working = working.replace(/\*\*([^*]+)\*\*/g, (_m, t) => chalk19.bold(t)).replace(/__([^_]+)__/g, (_m, t) => chalk19.bold(t)).replace(/(^|[^*])\*([^*\n]+)\*/g, (_m, lead, t) => lead + chalk19.italic(t)).replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, label, url) => `${chalk19.underline(label)} ${chalk19.dim(`(${url})`)}`);
7873
+ working = working.replace(/\*\*([^*]+)\*\*/g, (_m, t) => chalk20.bold(t)).replace(/__([^_]+)__/g, (_m, t) => chalk20.bold(t)).replace(/(^|[^*])\*([^*\n]+)\*/g, (_m, lead, t) => lead + chalk20.italic(t)).replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, label, url) => `${chalk20.underline(label)} ${chalk20.dim(`(${url})`)}`);
6911
7874
  return working.replace(
6912
7875
  new RegExp(`${CODE_OPEN}(\\d+)${CODE_CLOSE}`, "g"),
6913
- (_m, i) => chalk19.yellow(codeSpans[Number(i)])
7876
+ (_m, i) => chalk20.yellow(codeSpans[Number(i)])
6914
7877
  );
6915
7878
  }
6916
7879
 
@@ -6923,7 +7886,7 @@ function getOutputFormat13(cmd) {
6923
7886
  async function streamOneTurn(message, sessionId, projectId, branch, signal) {
6924
7887
  const api = createApiClient();
6925
7888
  const status = new Status();
6926
- status.set([` ${chalk20.magenta(SPINNER)} ${chalk20.dim("thinking")}`]);
7889
+ status.set([` ${chalk21.magenta(SPINNER)} ${chalk21.dim("thinking")}`]);
6927
7890
  status.start();
6928
7891
  let response;
6929
7892
  try {
@@ -7000,19 +7963,19 @@ var HELP = [
7000
7963
  ];
7001
7964
  async function runChatRepl(options) {
7002
7965
  const { input: promptInput } = await import("@inquirer/prompts");
7003
- const { getUpdateNotice } = await import("./update-check-7CVBVYDK.js");
7966
+ const { getUpdateNotice } = await import("./update-check-BH7IMKZN.js");
7004
7967
  let sessionId = options.session;
7005
7968
  let lastReportedSession;
7006
- console.log(chalk20.bold("Diafunc chat") + chalk20.dim(" \xB7 /help for commands, /quit to exit"));
7007
- if (options.project) console.log(chalk20.dim(`Project context: ${options.project}`));
7008
- if (sessionId) console.log(chalk20.dim(`Continuing session ${sessionId}`));
7969
+ console.log(chalk21.bold("Diafunc chat") + chalk21.dim(" \xB7 /help for commands, /quit to exit"));
7970
+ if (options.project) console.log(chalk21.dim(`Project context: ${options.project}`));
7971
+ if (sessionId) console.log(chalk21.dim(`Continuing session ${sessionId}`));
7009
7972
  const notice = await getUpdateNotice();
7010
- if (notice) console.log(chalk20.dim(notice));
7973
+ if (notice) console.log(chalk21.dim(notice));
7011
7974
  console.log();
7012
7975
  for (; ; ) {
7013
7976
  let line;
7014
7977
  try {
7015
- line = await promptInput({ message: chalk20.cyan.bold("you >") });
7978
+ line = await promptInput({ message: chalk21.cyan.bold("you >") });
7016
7979
  } catch {
7017
7980
  console.log();
7018
7981
  return;
@@ -7030,27 +7993,27 @@ async function runChatRepl(options) {
7030
7993
  case "new":
7031
7994
  sessionId = void 0;
7032
7995
  lastReportedSession = void 0;
7033
- console.log(chalk20.dim("Started a new session."));
7996
+ console.log(chalk21.dim("Started a new session."));
7034
7997
  continue;
7035
7998
  case "clear":
7036
7999
  console.clear();
7037
8000
  continue;
7038
8001
  case "session":
7039
8002
  if (!arg) {
7040
- console.log(chalk20.dim(`Current session: ${sessionId ?? "(new)"}`));
8003
+ console.log(chalk21.dim(`Current session: ${sessionId ?? "(new)"}`));
7041
8004
  } else {
7042
8005
  sessionId = arg;
7043
8006
  lastReportedSession = void 0;
7044
- console.log(chalk20.dim(`Switched to session ${sessionId}`));
8007
+ console.log(chalk21.dim(`Switched to session ${sessionId}`));
7045
8008
  }
7046
8009
  continue;
7047
8010
  case "help":
7048
8011
  case "h":
7049
8012
  case "?":
7050
- for (const l of HELP) console.log(chalk20.dim(l));
8013
+ for (const l of HELP) console.log(chalk21.dim(l));
7051
8014
  continue;
7052
8015
  default:
7053
- console.log(chalk20.dim(`Unknown command: /${cmd}. Try /help.`));
8016
+ console.log(chalk21.dim(`Unknown command: /${cmd}. Try /help.`));
7054
8017
  continue;
7055
8018
  }
7056
8019
  }
@@ -7063,19 +8026,19 @@ async function runChatRepl(options) {
7063
8026
  sessionId = result.sessionId || sessionId;
7064
8027
  console.log();
7065
8028
  if (controller.signal.aborted) {
7066
- console.log(chalk20.dim(" (cancelled)"));
8029
+ console.log(chalk21.dim(" (canceled)"));
7067
8030
  } else {
7068
8031
  const parts = [`${result.input} in / ${result.output} out`];
7069
8032
  if (sessionId && sessionId !== lastReportedSession) {
7070
8033
  parts.push(`session ${sessionId}`);
7071
8034
  lastReportedSession = sessionId;
7072
8035
  }
7073
- console.log(chalk20.dim(` ${parts.join(" \xB7 ")}`));
8036
+ console.log(chalk21.dim(` ${parts.join(" \xB7 ")}`));
7074
8037
  }
7075
8038
  console.log();
7076
8039
  } catch (error) {
7077
8040
  if (controller.signal.aborted) {
7078
- console.log(chalk20.dim(" (cancelled)"));
8041
+ console.log(chalk21.dim(" (canceled)"));
7079
8042
  console.log();
7080
8043
  } else {
7081
8044
  failure(`Request failed: ${error.message}`);
@@ -7119,7 +8082,7 @@ Examples:
7119
8082
  if (outputFormat === "human") {
7120
8083
  console.log(renderMarkdown(response.content));
7121
8084
  console.log();
7122
- console.log(chalk20.dim(
8085
+ console.log(chalk21.dim(
7123
8086
  ` session ${response.sessionId} \xB7 ${response.inputTokens} in / ${response.outputTokens} out`
7124
8087
  ));
7125
8088
  } else {
@@ -7187,7 +8150,7 @@ Examples:
7187
8150
  sessionId = event.sessionId ?? "";
7188
8151
  console.log();
7189
8152
  console.log();
7190
- console.log(chalk20.dim(`Session: ${sessionId} | Tokens: ${event.inputTokens} in, ${event.outputTokens} out`));
8153
+ console.log(chalk21.dim(`Session: ${sessionId} | Tokens: ${event.inputTokens} in, ${event.outputTokens} out`));
7191
8154
  } else if (event.type === "error") {
7192
8155
  failure(`Error: ${event.content}`);
7193
8156
  }
@@ -7203,12 +8166,12 @@ Examples:
7203
8166
  });
7204
8167
  chat.command("upload").description("Upload a file for chat context").argument("<file>", "File to upload").action(async (file) => {
7205
8168
  try {
7206
- if (!fs9.existsSync(file)) {
8169
+ if (!fs10.existsSync(file)) {
7207
8170
  failure(`File not found: ${file}`);
7208
8171
  process.exit(1);
7209
8172
  }
7210
8173
  const api = createApiClient();
7211
- const fileBuffer = fs9.readFileSync(file);
8174
+ const fileBuffer = fs10.readFileSync(file);
7212
8175
  const blob = new Blob([fileBuffer]);
7213
8176
  const formData = new FormData();
7214
8177
  formData.append("file", blob, path7.basename(file));
@@ -7247,11 +8210,11 @@ Examples:
7247
8210
  const api = createApiClient();
7248
8211
  const detail2 = await api.language.getSession(sessionId);
7249
8212
  if (outputFormat === "human") {
7250
- console.log(chalk20.bold(detail2.title) + chalk20.dim(` (${detail2.sessionId})`));
8213
+ console.log(chalk21.bold(detail2.title) + chalk21.dim(` (${detail2.sessionId})`));
7251
8214
  console.log();
7252
8215
  for (const msg of detail2.messages) {
7253
- const role = msg.role === "user" ? chalk20.cyan.bold("You") : chalk20.magenta.bold("Diafunc");
7254
- console.log(`${role} ${chalk20.dim(msg.created)}`);
8216
+ const role = msg.role === "user" ? chalk21.cyan.bold("You") : chalk21.magenta.bold("Diafunc");
8217
+ console.log(`${role} ${chalk21.dim(msg.created)}`);
7255
8218
  console.log(msg.content);
7256
8219
  console.log();
7257
8220
  }
@@ -7284,7 +8247,7 @@ Examples:
7284
8247
  }
7285
8248
 
7286
8249
  // src/commands/search/index.ts
7287
- import chalk21 from "chalk";
8250
+ import chalk22 from "chalk";
7288
8251
  function getOutputFormat14(cmd) {
7289
8252
  const config = loadConfig();
7290
8253
  const globalOpts = cmd.optsWithGlobals();
@@ -7346,7 +8309,7 @@ whose discovered model has the better quality comes first; inside one project th
7346
8309
  });
7347
8310
  }
7348
8311
  if (page.nextCursor && isInteractive()) {
7349
- console.log(chalk21.dim(`More results available. Raise --limit to see them.`));
8312
+ console.log(chalk22.dim(`More results available. Raise --limit to see them.`));
7350
8313
  }
7351
8314
  } catch (error) {
7352
8315
  handleError(error);
@@ -7368,12 +8331,12 @@ function renderResults(items) {
7368
8331
  for (const item of items) {
7369
8332
  const name = item.name || "(unnamed)";
7370
8333
  console.log();
7371
- console.log(`${chalk21.dim(`[${item.contentType}]`)} ${chalk21.bold(name)}${qualityNote(item)}`);
8334
+ console.log(`${chalk22.dim(`[${item.contentType}]`)} ${chalk22.bold(name)}${qualityNote(item)}`);
7372
8335
  const raw = item.snippetField === "name" ? item.description : item.snippet ?? item.description;
7373
8336
  const line = raw ? collapse(raw) : null;
7374
8337
  if (line && stripHighlight(line) !== name) console.log(` ${highlight(line)}`);
7375
8338
  const ref = item.entityId ? `${item.projectId}/${item.projectBranch}/${item.entityId}/${item.entityBranch ?? "main"}` : item.projectId;
7376
- console.log(` ${chalk21.dim(ref)}`);
8339
+ console.log(` ${chalk22.dim(ref)}`);
7377
8340
  }
7378
8341
  console.log();
7379
8342
  }
@@ -7381,16 +8344,16 @@ function qualityNote(item) {
7381
8344
  if (item.contentType !== "project" || typeof item.quality !== "number" || !Number.isFinite(item.quality)) {
7382
8345
  return "";
7383
8346
  }
7384
- return chalk21.dim(` quality ${percent(item.quality).trim()}`);
8347
+ return chalk22.dim(` quality ${percent(item.quality).trim()}`);
7385
8348
  }
7386
8349
  var HIGHLIGHT_OPEN = /<mark>/g;
7387
8350
  var HIGHLIGHT_CLOSE = /<\/mark>/g;
7388
8351
  function highlight(text2) {
7389
8352
  const parts = text2.split(HIGHLIGHT_OPEN);
7390
8353
  return parts.map((part, i) => {
7391
- if (i === 0) return chalk21.dim(part);
8354
+ if (i === 0) return chalk22.dim(part);
7392
8355
  const [marked, ...rest] = part.split(HIGHLIGHT_CLOSE);
7393
- return chalk21.bold.cyan(marked) + chalk21.dim(rest.join(""));
8356
+ return chalk22.bold.cyan(marked) + chalk22.dim(rest.join(""));
7394
8357
  }).join("");
7395
8358
  }
7396
8359
  function stripHighlight(text2) {
@@ -7405,7 +8368,7 @@ function collapse(text2) {
7405
8368
  import { readFile } from "fs/promises";
7406
8369
 
7407
8370
  // src/commands/admin/curated-tags.ts
7408
- import chalk22 from "chalk";
8371
+ import chalk23 from "chalk";
7409
8372
  function getOutputFormat15(cmd) {
7410
8373
  const config = loadConfig();
7411
8374
  const globalOpts = cmd.optsWithGlobals();
@@ -7421,7 +8384,7 @@ var COLUMNS = [
7421
8384
  function curatedTagOf(typed2) {
7422
8385
  const tag = normalizeTag(typed2);
7423
8386
  if (tag === "") usageError(`"${typed2}" is not a usable tag: a tag needs at least one letter or digit.`);
7424
- if (tag !== typed2) console.error(chalk22.dim(`"${typed2}" is written as "${tag}", the form tags are searched by.`));
8387
+ if (tag !== typed2) console.error(chalk23.dim(`"${typed2}" is written as "${tag}", the form tags are searched by.`));
7425
8388
  return tag;
7426
8389
  }
7427
8390
  function parseSortOrder(raw) {
@@ -7687,7 +8650,7 @@ function registerAdminCommands(program) {
7687
8650
  );
7688
8651
  const api = createApiClient();
7689
8652
  await api.storage.restoreFullBackup({ bucketName, objectName });
7690
- success(`Full restore initiated from ${bucketName}/${objectName}.`);
8653
+ success(`Full restore started from ${bucketName}/${objectName}.`);
7691
8654
  } catch (error) {
7692
8655
  handleError(error);
7693
8656
  }
@@ -7698,10 +8661,10 @@ function registerAdminCommands(program) {
7698
8661
  const { project } = cmd.optsWithGlobals();
7699
8662
  if (project) {
7700
8663
  await api.index.rebuildProject(project);
7701
- success(`Index rebuild initiated for project "${project}".`);
8664
+ success(`Index rebuild started for project "${project}".`);
7702
8665
  } else {
7703
8666
  await api.index.rebuildAll();
7704
- success("Index rebuild initiated for all projects.");
8667
+ success("Index rebuild started for all projects.");
7705
8668
  }
7706
8669
  } catch (error) {
7707
8670
  handleError(error);
@@ -7744,7 +8707,7 @@ function registerAdminCommands(program) {
7744
8707
  }
7745
8708
 
7746
8709
  // src/commands/status/summary.ts
7747
- import chalk23 from "chalk";
8710
+ import chalk24 from "chalk";
7748
8711
 
7749
8712
  // src/client/services/status.ts
7750
8713
  function createStatusService() {
@@ -7770,24 +8733,24 @@ function createStatusService() {
7770
8733
 
7771
8734
  // src/commands/status/summary.ts
7772
8735
  var STATE_COLORS = {
7773
- UP: chalk23.green,
7774
- DEGRADED: chalk23.yellow,
7775
- DOWN: chalk23.red,
7776
- UNKNOWN: chalk23.gray
8736
+ UP: chalk24.green,
8737
+ DEGRADED: chalk24.yellow,
8738
+ DOWN: chalk24.red,
8739
+ UNKNOWN: chalk24.gray
7777
8740
  };
7778
8741
  function stateColor(state) {
7779
- return STATE_COLORS[state] ?? chalk23.gray;
8742
+ return STATE_COLORS[state] ?? chalk24.gray;
7780
8743
  }
7781
8744
  function stateSymbol(state) {
7782
8745
  switch (state) {
7783
8746
  case "UP":
7784
- return chalk23.green("\u25CF");
8747
+ return chalk24.green("\u25CF");
7785
8748
  case "DEGRADED":
7786
- return chalk23.yellow("\u25CF");
8749
+ return chalk24.yellow("\u25CF");
7787
8750
  case "DOWN":
7788
- return chalk23.red("\u25CF");
8751
+ return chalk24.red("\u25CF");
7789
8752
  default:
7790
- return chalk23.gray("\u25CB");
8753
+ return chalk24.gray("\u25CB");
7791
8754
  }
7792
8755
  }
7793
8756
  function registerSummaryCommand(parent) {
@@ -7812,20 +8775,20 @@ function registerSummaryCommand(parent) {
7812
8775
  const label = stateColor(domain.state)(domain.state.padEnd(10));
7813
8776
  console.log(` ${stateSymbol(domain.state)} ${label} ${domain.name}`);
7814
8777
  if (domain.componentIds.length > 0) {
7815
- console.log(` ${chalk23.dim(domain.componentIds.join(", "))}`);
8778
+ console.log(` ${chalk24.dim(domain.componentIds.join(", "))}`);
7816
8779
  }
7817
8780
  }
7818
8781
  console.log();
7819
8782
  if (summary.openIncidents > 0) {
7820
- console.log(chalk23.yellow(` ${summary.openIncidents} active incident(s)`));
8783
+ console.log(chalk24.yellow(` ${summary.openIncidents} active incident(s)`));
7821
8784
  } else {
7822
- console.log(chalk23.dim(" No active incidents"));
8785
+ console.log(chalk24.dim(" No active incidents"));
7823
8786
  }
7824
- console.log(chalk23.dim(
8787
+ console.log(chalk24.dim(
7825
8788
  `
7826
8789
  Platform v${version.platformVersion} \xB7 checked ${formatInstant(summary.timestamp)}`
7827
8790
  ));
7828
- console.log(chalk23.dim(` Drill into one with 'diafunc status component <id>'.`));
8791
+ console.log(chalk24.dim(` Drill into one with 'diafunc status component <id>'.`));
7829
8792
  console.log();
7830
8793
  } catch (error) {
7831
8794
  handleError(error);
@@ -7834,17 +8797,17 @@ function registerSummaryCommand(parent) {
7834
8797
  }
7835
8798
 
7836
8799
  // src/commands/status/component.ts
7837
- import chalk24 from "chalk";
8800
+ import chalk25 from "chalk";
7838
8801
  function stateSymbol2(state) {
7839
8802
  switch (state) {
7840
8803
  case "UP":
7841
- return chalk24.green("\u25CF");
8804
+ return chalk25.green("\u25CF");
7842
8805
  case "DEGRADED":
7843
- return chalk24.yellow("\u25CF");
8806
+ return chalk25.yellow("\u25CF");
7844
8807
  case "DOWN":
7845
- return chalk24.red("\u25CF");
8808
+ return chalk25.red("\u25CF");
7846
8809
  default:
7847
- return chalk24.gray("\u25CB");
8810
+ return chalk25.gray("\u25CB");
7848
8811
  }
7849
8812
  }
7850
8813
  function registerComponentCommand(parent) {
@@ -7869,7 +8832,7 @@ function registerComponentCommand(parent) {
7869
8832
  return;
7870
8833
  }
7871
8834
  console.log();
7872
- console.log(` ${stateSymbol2(match.state)} ${chalk24.bold(match.id)} ${match.version ? chalk24.dim("v" + match.version) : ""}`);
8835
+ console.log(` ${stateSymbol2(match.state)} ${chalk25.bold(match.id)} ${match.version ? chalk25.dim("v" + match.version) : ""}`);
7873
8836
  console.log(` State: ${renderState(match.state)}`);
7874
8837
  if (match.lastCheckAt) {
7875
8838
  console.log(` Last check: ${formatInstant(match.lastCheckAt)}`);
@@ -7878,7 +8841,7 @@ function registerComponentCommand(parent) {
7878
8841
  console.log();
7879
8842
  console.log(" Checks:");
7880
8843
  for (const check of match.checks) {
7881
- const cat = check.category ? chalk24.dim(` (${check.category})`) : "";
8844
+ const cat = check.category ? chalk25.dim(` (${check.category})`) : "";
7882
8845
  console.log(` ${stateSymbol2(check.state)} ${check.name}${cat}`);
7883
8846
  }
7884
8847
  }
@@ -7890,12 +8853,12 @@ function registerComponentCommand(parent) {
7890
8853
  }
7891
8854
 
7892
8855
  // src/commands/status/incidents.ts
7893
- import chalk25 from "chalk";
8856
+ import chalk26 from "chalk";
7894
8857
  var SEVERITY_COLORS = {
7895
- ERROR: chalk25.red,
7896
- WARNING: chalk25.yellow,
7897
- INFO: chalk25.blue,
7898
- MAINTENANCE: chalk25.cyan
8858
+ ERROR: chalk26.red,
8859
+ WARNING: chalk26.yellow,
8860
+ INFO: chalk26.blue,
8861
+ MAINTENANCE: chalk26.cyan
7899
8862
  };
7900
8863
  function registerIncidentsCommand(parent) {
7901
8864
  parent.command("incidents").description("List recent incidents").option("-w, --window <window>", "Time window (e.g. 24h, 48h)", "24h").action(async (options, cmd) => {
@@ -7909,22 +8872,22 @@ function registerIncidentsCommand(parent) {
7909
8872
  return;
7910
8873
  }
7911
8874
  if (incidents.length === 0) {
7912
- console.log(chalk25.dim(`
8875
+ console.log(chalk26.dim(`
7913
8876
  No incidents in the last ${options.window}.
7914
8877
  `));
7915
8878
  return;
7916
8879
  }
7917
8880
  console.log();
7918
8881
  for (const incident of incidents) {
7919
- const color = SEVERITY_COLORS[incident.severity] ?? chalk25.gray;
8882
+ const color = SEVERITY_COLORS[incident.severity] ?? chalk26.gray;
7920
8883
  const severity = color(incident.severity.padEnd(8));
7921
8884
  const time = incident.startedAt ? new Date(incident.startedAt).toLocaleString() : "";
7922
- const resolved = incident.resolvedAt ? chalk25.green(" [resolved]") : chalk25.yellow(" [open]");
8885
+ const resolved = incident.resolvedAt ? chalk26.green(" [resolved]") : chalk26.yellow(" [open]");
7923
8886
  console.log(` ${severity} ${incident.summary}${resolved}`);
7924
- console.log(chalk25.dim(` ${time}`));
8887
+ console.log(chalk26.dim(` ${time}`));
7925
8888
  for (const update of incident.updates) {
7926
8889
  const updateTime = new Date(update.at).toLocaleTimeString();
7927
- console.log(chalk25.dim(` ${updateTime} ${update.status} ${update.message}`));
8890
+ console.log(chalk26.dim(` ${updateTime} ${update.status} ${update.message}`));
7928
8891
  }
7929
8892
  console.log();
7930
8893
  }
@@ -7940,7 +8903,7 @@ function registerStatusCommands(program) {
7940
8903
  Examples:
7941
8904
  $ diafunc status summary everything, at a glance
7942
8905
  $ diafunc status component storage one service in detail
7943
- $ diafunc status incidents --days 7
8906
+ $ diafunc status incidents --window 168h
7944
8907
  `);
7945
8908
  ;
7946
8909
  registerSummaryCommand(status);
@@ -7949,12 +8912,12 @@ Examples:
7949
8912
  }
7950
8913
 
7951
8914
  // src/commands/analyze/index.ts
7952
- import * as fs11 from "fs";
8915
+ import * as fs12 from "fs";
7953
8916
  import * as path9 from "path";
7954
8917
  import { spawn as spawn2 } from "child_process";
7955
8918
 
7956
8919
  // src/commands/analyze/watch-view.ts
7957
- import chalk26 from "chalk";
8920
+ import chalk27 from "chalk";
7958
8921
 
7959
8922
  // src/client/types/analysis.ts
7960
8923
  var RUN_PHASE_LABELS = {
@@ -7974,6 +8937,7 @@ function phaseLabel(run) {
7974
8937
  if (run.state === "DISPATCHING") return STARTING;
7975
8938
  if (run.phase && RUN_PHASE_LABELS[run.phase]) return RUN_PHASE_LABELS[run.phase];
7976
8939
  if (run.state === "RUNNING" && !((run.progressTotal ?? 0) > 0)) return RUN_PHASE_LABELS.PREPARING;
8940
+ if (run.state === "CANCELLED") return "Canceled";
7977
8941
  return run.state.charAt(0) + run.state.slice(1).toLowerCase();
7978
8942
  }
7979
8943
  function waitLabel(run) {
@@ -8009,7 +8973,7 @@ function latestRunSentence(state) {
8009
8973
  case "FAILED":
8010
8974
  return "The latest run failed.";
8011
8975
  case "CANCELLED":
8012
- return "The latest run was cancelled.";
8976
+ return "The latest run was canceled.";
8013
8977
  case "QUEUED":
8014
8978
  return "The latest run is waiting for a slot.";
8015
8979
  case "DISPATCHING":
@@ -8021,7 +8985,7 @@ function latestRunSentence(state) {
8021
8985
  function cancelSentence(run) {
8022
8986
  switch (run.state) {
8023
8987
  case "CANCELLED":
8024
- return `Cancelled run ${run.runId}.`;
8988
+ return `Canceled run ${run.runId}.`;
8025
8989
  case "COMPLETED":
8026
8990
  return `Run ${run.runId} had already completed.`;
8027
8991
  case "FAILED":
@@ -8039,7 +9003,7 @@ function terminalSentence(state, duration, credits = null) {
8039
9003
  case "COMPLETED":
8040
9004
  return `Analysis completed in ${duration}${cost}.`;
8041
9005
  case "CANCELLED":
8042
- return `Analysis cancelled after ${duration}${cost}.`;
9006
+ return `Analysis canceled after ${duration}${cost}.`;
8043
9007
  default:
8044
9008
  return `Analysis failed after ${duration}${cost}.`;
8045
9009
  }
@@ -8050,7 +9014,7 @@ function isImporting(dataImport) {
8050
9014
  function importingLabel(dataImport) {
8051
9015
  const progress = dataImport.progress;
8052
9016
  if (progress === null || progress === void 0 || !Number.isFinite(progress)) return "Importing data";
8053
- return `Importing data, ${Math.floor(Math.max(0, Math.min(progress, 1)) * 100)} %`;
9017
+ return `Importing data, ${Math.floor(Math.max(0, Math.min(progress, 1)) * 100)}%`;
8054
9018
  }
8055
9019
  function verdictLabel(run) {
8056
9020
  switch (run.validity) {
@@ -8114,219 +9078,58 @@ function renderWatchBlock(input) {
8114
9078
  const lines = [];
8115
9079
  const step = stepCounter(run);
8116
9080
  const headline = [
8117
- chalk26.cyan(SPINNER),
8118
- chalk26.bold(phaseLabel(run)),
8119
- step ? chalk26.dim(step) : null
9081
+ chalk27.cyan(SPINNER),
9082
+ chalk27.bold(phaseLabel(run)),
9083
+ step ? chalk27.dim(step) : null
8120
9084
  ].filter(Boolean).join(" ");
8121
9085
  lines.push(` ${headline}`);
8122
9086
  const fraction = overallProgress(run);
8123
- const elapsed = chalk26.dim(formatDurationPrecise(elapsedMs));
9087
+ const elapsed = chalk27.dim(formatDurationPrecise(elapsedMs));
8124
9088
  if (fraction === null) {
8125
- lines.push(` ${chalk26.dim("working")} ${elapsed}`);
9089
+ lines.push(` ${chalk27.dim("working")} ${elapsed}`);
8126
9090
  } else {
8127
9091
  const ceiling = remainingCeiling(run, budgetHours);
8128
9092
  lines.push(
8129
- ` ${bar(fraction)} ${percent(fraction)} ${elapsed}` + (ceiling !== null ? chalk26.dim(` \xB7 at most ${formatDurationPrecise(ceiling)} remaining`) : "")
8130
- );
8131
- }
8132
- const detail2 = caption ?? phaseDetail(run);
8133
- if (detail2) lines.push(` ${chalk26.dim(detail2)}`);
8134
- if (run.retryAttempts && run.retryAttempts > 0) {
8135
- lines.push(` ${chalk26.yellow("!")} ${chalk26.dim(
8136
- `restarted ${run.retryAttempts === 1 ? "once" : `${run.retryAttempts} times`} after an interruption; progress restarts from the beginning`
8137
- )}`);
8138
- }
8139
- return lines;
8140
- }
8141
-
8142
- // src/commands/analyze/wizard.ts
8143
- import chalk27 from "chalk";
8144
-
8145
- // src/commands/analyze/columns.ts
8146
- var MAX_COLUMNS_LISTED = 30;
8147
- var MAX_NEAR_MATCHES = 3;
8148
- function parseColumnList(text2) {
8149
- const names = [];
8150
- let i = 0;
8151
- while (i < text2.length) {
8152
- while (i < text2.length && isSpace(text2[i])) i++;
8153
- if (i >= text2.length) break;
8154
- if (text2[i] === '"') {
8155
- let name = "";
8156
- let closed = false;
8157
- i++;
8158
- while (i < text2.length) {
8159
- if (text2[i] === '"' && text2[i + 1] === '"') {
8160
- name += '"';
8161
- i += 2;
8162
- } else if (text2[i] === '"') {
8163
- closed = true;
8164
- i++;
8165
- break;
8166
- } else {
8167
- name += text2[i++];
8168
- }
8169
- }
8170
- if (!closed) {
8171
- throw new CliError(`A double quote is opened and never closed in: ${text2}`, {
8172
- exitCode: EXIT_USAGE,
8173
- hint: QUOTING_HINT
8174
- });
8175
- }
8176
- while (i < text2.length && isSpace(text2[i])) i++;
8177
- if (i < text2.length && text2[i] !== ",") {
8178
- throw new CliError(`Text follows a closing double quote without a comma in: ${text2}`, {
8179
- exitCode: EXIT_USAGE,
8180
- hint: QUOTING_HINT
8181
- });
8182
- }
8183
- i++;
8184
- if (name.length > 0) names.push(name);
8185
- } else {
8186
- const end = text2.indexOf(",", i);
8187
- const name = text2.slice(i, end === -1 ? text2.length : end).trim();
8188
- i = end === -1 ? text2.length : end + 1;
8189
- if (name.length > 0) names.push(name);
8190
- }
8191
- }
8192
- return names;
8193
- }
8194
- var QUOTING_HINT = `Inside a list, put a name that contains a comma in double quotes and write a quote in it twice: '"a, b",c'.`;
8195
- function isSpace(char) {
8196
- return char === " " || char === " ";
8197
- }
8198
- function quoteColumn(name) {
8199
- return `"${name.replace(/"/g, '""')}"`;
8200
- }
8201
- function loose(name) {
8202
- return name.trim().toLowerCase();
8203
- }
8204
- function matchColumn(name, columns) {
8205
- if (columns.includes(name)) return { kind: "column", column: name };
8206
- const wanted = loose(name);
8207
- const candidates = columns.filter((column) => loose(column) === wanted);
8208
- if (candidates.length === 1) return { kind: "column", column: candidates[0] };
8209
- return candidates.length > 1 ? { kind: "ambiguous", candidates } : { kind: "unknown" };
8210
- }
8211
- function nearMatches(name, columns) {
8212
- const wanted = loose(name);
8213
- if (wanted.length === 0) return [];
8214
- return columns.map((column) => ({ column, distance: distanceTo(wanted, loose(column)) })).filter((scored) => scored.distance !== null).sort((a, b) => a.distance - b.distance).slice(0, MAX_NEAR_MATCHES).map((scored) => scored.column);
8215
- }
8216
- function distanceTo(wanted, column) {
8217
- const edits = editDistance(wanted, column);
8218
- if (edits <= Math.max(1, Math.floor(Math.min(wanted.length, column.length) / 4))) return edits;
8219
- if (wanted.length >= 3 && (column.includes(wanted) || wanted.includes(column)) && column.length > 0) {
8220
- return 100 + Math.abs(column.length - wanted.length);
8221
- }
8222
- return null;
8223
- }
8224
- function editDistance(a, b) {
8225
- let previous = Array.from({ length: b.length + 1 }, (_, j) => j);
8226
- for (let i = 1; i <= a.length; i++) {
8227
- const current = [i];
8228
- for (let j = 1; j <= b.length; j++) {
8229
- current[j] = Math.min(
8230
- previous[j] + 1,
8231
- current[j - 1] + 1,
8232
- previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
8233
- );
8234
- }
8235
- previous = current;
8236
- }
8237
- return previous[b.length];
8238
- }
8239
- function take(name, columns, into, problems) {
8240
- const match = matchColumn(name, columns);
8241
- if (match.kind === "column") {
8242
- if (!into.includes(match.column)) into.push(match.column);
8243
- return true;
8244
- }
8245
- if (match.kind === "ambiguous") problems.ambiguous.push({ name, candidates: match.candidates });
8246
- else problems.unknown.push(name);
8247
- return false;
8248
- }
8249
- function refuse(problems, columns, analysisId) {
8250
- const sentences = [];
8251
- if (problems.unknown.length === 1) {
8252
- sentences.push(`${quoteColumn(problems.unknown[0])} is not a column of the analysis data.`);
8253
- } else if (problems.unknown.length > 1) {
8254
- sentences.push(`These are not columns of the analysis data: ${problems.unknown.map(quoteColumn).join(", ")}.`);
8255
- }
8256
- for (const { name, candidates } of problems.ambiguous) {
8257
- sentences.push(`${quoteColumn(name)} matches more than one column: ${candidates.map(quoteColumn).join(", ")}. Type the one you mean exactly.`);
8258
- }
8259
- const hints = [];
8260
- const near = [...new Set(problems.unknown.flatMap((name) => nearMatches(name, columns)))];
8261
- if (near.length > 0) hints.push(`Did you mean ${near.map(quoteColumn).join(" or ")}?`);
8262
- const listed2 = columns.slice(0, MAX_COLUMNS_LISTED).map(quoteColumn).join(", ");
8263
- const more = columns.length > MAX_COLUMNS_LISTED ? ` and ${columns.length - MAX_COLUMNS_LISTED} more${analysisId ? ` ('diafunc analyze columns ${analysisId}' lists them all)` : ""}` : "";
8264
- hints.push(`The columns are: ${listed2}${more}.`);
8265
- if (problems.fromList) {
8266
- hints.push(`A name that contains a comma is an argument of its own, or goes in double quotes inside a list: '"a, b",c'.`);
8267
- }
8268
- throw new CliError(sentences.join(" "), { exitCode: EXIT_USAGE, hint: hints.join("\n ") });
8269
- }
8270
- function resolveColumnArguments(given, columns, analysisId) {
8271
- const resolved = [];
8272
- if (columns.length === 0) {
8273
- for (const name of given.flatMap(parseColumnList)) {
8274
- if (!resolved.includes(name)) resolved.push(name);
8275
- }
8276
- return resolved;
9093
+ ` ${bar(fraction)} ${percent(fraction)} ${elapsed}` + (ceiling !== null ? chalk27.dim(` \xB7 at most ${formatDurationPrecise(ceiling)} remaining`) : "")
9094
+ );
8277
9095
  }
8278
- const problems = { unknown: [], ambiguous: [], fromList: false };
8279
- for (const argument of given) {
8280
- if (argument.trim().length === 0) continue;
8281
- const whole = matchColumn(argument, columns);
8282
- if (whole.kind === "column") {
8283
- if (!resolved.includes(whole.column)) resolved.push(whole.column);
8284
- continue;
8285
- }
8286
- const names = parseColumnList(argument);
8287
- const single = names.length === 1 && names[0] === argument.trim();
8288
- for (const name of names) {
8289
- if (!take(name, columns, resolved, problems) && !single) problems.fromList = true;
8290
- }
9096
+ const detail2 = caption ?? phaseDetail(run);
9097
+ if (detail2) lines.push(` ${chalk27.dim(detail2)}`);
9098
+ if (run.retryAttempts && run.retryAttempts > 0) {
9099
+ lines.push(` ${chalk27.yellow("!")} ${chalk27.dim(
9100
+ `restarted ${run.retryAttempts === 1 ? "once" : `${run.retryAttempts} times`} after an interruption; progress restarts from the beginning`
9101
+ )}`);
8291
9102
  }
8292
- if (problems.unknown.length > 0 || problems.ambiguous.length > 0) refuse(problems, columns, analysisId);
8293
- return resolved;
8294
- }
8295
- function resolveColumnNames(names, columns, analysisId) {
8296
- if (columns.length === 0) return [...names];
8297
- const resolved = [];
8298
- const problems = { unknown: [], ambiguous: [], fromList: false };
8299
- for (const name of names) take(name, columns, resolved, problems);
8300
- if (problems.unknown.length > 0 || problems.ambiguous.length > 0) refuse(problems, columns, analysisId);
8301
- return resolved;
8302
- }
8303
- function resolveColumnArgument(given, columns, analysisId) {
8304
- if (columns.length === 0) return given;
8305
- return resolveColumnNames([given], columns, analysisId)[0];
8306
- }
8307
- function occurrences(value) {
8308
- if (value === void 0) return void 0;
8309
- return Array.isArray(value) ? value : [value];
8310
- }
8311
- function collectColumns(value, previous = []) {
8312
- return previous.concat([value]);
9103
+ return lines;
8313
9104
  }
8314
9105
 
8315
9106
  // src/commands/analyze/wizard.ts
8316
- var DEPTH_PRESETS = [
8317
- { name: "Express", hours: "1", budget: "500" },
8318
- { name: "Quick", hours: "2", budget: "2000" },
8319
- { name: "Standard", hours: "4", budget: "10000" },
8320
- { name: "Thorough", hours: "8", budget: "40000" },
8321
- { name: "Deep", hours: "24", budget: "150000" }
8322
- ];
8323
- var STARTING_DEPTH_RULE = "Defaults to the account's starting depth: Express (1 hour, 500 credits) until the account has a finished analysis, Standard (4 hours, 10,000 credits) afterwards.";
9107
+ import chalk28 from "chalk";
9108
+ var STARTING_DEPTH_RULE = "Defaults to the account's starting depth: Express (1 hour, 500 credits) until the account has a finished analysis, Standard (4 hours, 4,000 credits) afterwards.";
9109
+ function creditsLabel(budget) {
9110
+ const n = Number(budget);
9111
+ return `${Number.isFinite(n) ? n.toLocaleString("en-US") : budget} credits`;
9112
+ }
9113
+ function timeLabel(hours) {
9114
+ const h = Number(hours);
9115
+ if (!Number.isFinite(h) || h <= 0) return `${hours} hours`;
9116
+ const trim = (v) => Number.isInteger(v) ? v.toString() : (Math.round(v * 10) / 10).toString();
9117
+ if (h < 24) return h === 1 ? "1 hour" : `${trim(h)} hours`;
9118
+ const days = h / 24;
9119
+ if (days < 14) return days === 1 ? "1 day" : `${trim(Math.round(days * 10) / 10)} days`;
9120
+ return `${Math.round(days / 7)} weeks`;
9121
+ }
9122
+ function findDepth(depths, nameOrCredits) {
9123
+ const wanted = nameOrCredits.trim();
9124
+ const credits = wanted.replace(/[,_]/g, "");
9125
+ return depths.find((step) => step.name.toLowerCase() === wanted.toLowerCase() || step.budget === credits);
9126
+ }
8324
9127
  function depthOf(hours, budget) {
8325
9128
  const h = hours?.trim();
8326
9129
  const b = budget?.trim();
8327
9130
  return h && b ? { hours: h, budget: b } : null;
8328
9131
  }
8329
- async function promptCreationFields(prompter, supplied, fallbackName, licences) {
9132
+ async function promptCreationFields(prompter, supplied, fallbackName, licenses) {
8330
9133
  const name = supplied.name ?? await prompter.input({
8331
9134
  message: "Analysis name",
8332
9135
  default: fallbackName,
@@ -8344,34 +9147,34 @@ async function promptCreationFields(prompter, supplied, fallbackName, licences)
8344
9147
  ]
8345
9148
  });
8346
9149
  const answers = { name: name.trim(), description: description.trim() || null, visibility };
8347
- const licenceId = supplied.licenceId ?? (visibility === "PUBLIC" && licences ? await promptLicence(prompter, await licences()) : void 0);
8348
- if (licenceId) answers.licenceId = licenceId;
9150
+ const licenseId = supplied.licenceId ?? (visibility === "PUBLIC" && licenses ? await promptLicense(prompter, await licenses()) : void 0);
9151
+ if (licenseId) answers.licenceId = licenseId;
8349
9152
  return answers;
8350
9153
  }
8351
- var ALL_LICENCES = ":all";
8352
- async function promptLicence(prompter, catalogue) {
8353
- const selectable = catalogue.filter((l) => l.state === "ACTIVE");
9154
+ var ALL_LICENSES = ":all";
9155
+ async function promptLicense(prompter, catalog) {
9156
+ const selectable = catalog.filter((l) => l.state === "ACTIVE");
8354
9157
  if (selectable.length === 0) return void 0;
8355
9158
  const choice = (l) => ({ name: `${l.name} (${l.licenceId})`, value: l.licenceId, description: l.summary ?? void 0 });
8356
9159
  const recommended = selectable.filter((l) => l.recommended);
8357
9160
  const others = selectable.filter((l) => !l.recommended);
8358
9161
  if (recommended.length === 0 || others.length === 0) {
8359
- return prompter.select({ message: "Licence", default: selectable[0].licenceId, choices: selectable.map(choice) });
9162
+ return prompter.select({ message: "License", default: selectable[0].licenceId, choices: selectable.map(choice) });
8360
9163
  }
8361
9164
  const picked = await prompter.select({
8362
- message: "Licence",
9165
+ message: "License",
8363
9166
  default: recommended[0].licenceId,
8364
9167
  choices: [
8365
9168
  ...recommended.map(choice),
8366
- { name: "Another licence\u2026", value: ALL_LICENCES, description: `${others.length} more in the catalogue.` }
9169
+ { name: "Another license\u2026", value: ALL_LICENSES, description: `${others.length} more in the catalog.` }
8367
9170
  ]
8368
9171
  });
8369
- if (picked !== ALL_LICENCES) return picked;
8370
- return prompter.select({ message: "Licence (all)", default: others[0].licenceId, choices: selectable.map(choice) });
9172
+ if (picked !== ALL_LICENSES) return picked;
9173
+ return prompter.select({ message: "License (all)", default: others[0].licenceId, choices: selectable.map(choice) });
8371
9174
  }
8372
- function matchDepthPreset(hours, budget) {
9175
+ function matchDepthPreset(depths, hours, budget) {
8373
9176
  if (!hours || !budget) return null;
8374
- return DEPTH_PRESETS.find((p) => p.hours === hours && p.budget === budget) ?? null;
9177
+ return depths.find((p) => p.hours === hours && p.budget === budget) ?? null;
8375
9178
  }
8376
9179
  function defaultTargets(columns) {
8377
9180
  const named = columns.filter((c) => c.name && c.name.length > 0);
@@ -8386,6 +9189,7 @@ function positiveNumber(label) {
8386
9189
  }
8387
9190
  async function promptRunFields(prompter, options) {
8388
9191
  const { columns, depthDefault } = options;
9192
+ const depths = options.depths ?? [];
8389
9193
  const named = columns.filter((c) => c.name && c.name.length > 0);
8390
9194
  let supplied = { ...options.supplied };
8391
9195
  const nothingSupplied = supplied.targets === void 0 && supplied.segment === void 0 && supplied.questions === void 0 && supplied.hours === void 0 && supplied.budget === void 0;
@@ -8407,6 +9211,7 @@ async function promptRunFields(prompter, options) {
8407
9211
  targets: preset.targets.length > 0 ? preset.targets : void 0,
8408
9212
  questions: preset.questions.length > 0 ? preset.questions : void 0,
8409
9213
  segment: preset.segmentKey ?? void 0,
9214
+ intent: supplied.intent,
8410
9215
  hours: preset.time || void 0,
8411
9216
  budget: preset.budget || void 0
8412
9217
  };
@@ -8419,7 +9224,7 @@ async function promptRunFields(prompter, options) {
8419
9224
  targets = await prompter.checkbox({
8420
9225
  message: "Target columns: what should the analysis predict?",
8421
9226
  choices: named.map((c) => ({
8422
- name: c.valueType ? `${c.name} ${chalk27.dim(`(${c.valueType})`)}` : c.name,
9227
+ name: c.valueType ? `${c.name} ${chalk28.dim(`(${c.valueType})`)}` : c.name,
8423
9228
  value: c.name,
8424
9229
  checked: preselected.has(c.name)
8425
9230
  })),
@@ -8448,7 +9253,7 @@ async function promptRunFields(prompter, options) {
8448
9253
  choices: [
8449
9254
  { name: "No segmentation", value: null },
8450
9255
  ...remaining.map((c) => ({
8451
- name: c.valueType ? `${c.name} ${chalk27.dim(`(${c.valueType})`)}` : c.name,
9256
+ name: c.valueType ? `${c.name} ${chalk28.dim(`(${c.valueType})`)}` : c.name,
8452
9257
  value: c.name
8453
9258
  }))
8454
9259
  ]
@@ -8473,19 +9278,27 @@ async function promptRunFields(prompter, options) {
8473
9278
  questions = collected.length > 0 ? collected : null;
8474
9279
  }
8475
9280
  }
9281
+ let intent = supplied.intent ?? null;
9282
+ if (supplied.intent === void 0) {
9283
+ const typed2 = await prompter.input({
9284
+ message: "What you know and what matters (optional, private to you; blank to skip)",
9285
+ validate: (value) => value.length <= MAX_INTENT_LENGTH || `At most ${MAX_INTENT_LENGTH.toLocaleString("en-US")} characters; --intent-file takes longer notes.`
9286
+ });
9287
+ intent = typed2.trim() || null;
9288
+ }
8476
9289
  let hours = supplied.hours;
8477
9290
  let budget = supplied.budget;
8478
- if (hours === void 0 && budget === void 0) {
9291
+ if (hours === void 0 && budget === void 0 && depths.length > 0) {
8479
9292
  const chosen = await prompter.select({
8480
- message: "Depth: how long may the search run, and what may it spend?",
8481
- default: matchDepthPreset(depthDefault?.hours, depthDefault?.budget) ?? void 0,
9293
+ message: "Depth: what may the analysis spend, and how long may it take?",
9294
+ default: matchDepthPreset(depths, depthDefault?.hours, depthDefault?.budget) ?? void 0,
8482
9295
  choices: [
8483
- ...DEPTH_PRESETS.map((p) => ({
8484
- name: p.name,
9296
+ ...depths.map((p) => ({
9297
+ name: `${p.name}: ${creditsLabel(p.budget)}, up to ${timeLabel(p.hours)}`,
8485
9298
  value: p,
8486
- description: `${p.hours}h \xB7 ${p.budget} credits`
9299
+ description: p.longRun ? "A long analysis: it runs for days and shares the server. If the platform restarts, its search starts again; the interrupted attempt is not charged." : void 0
8487
9300
  })),
8488
- { name: "Set your own", value: null }
9301
+ { name: "Set your own time and credits", value: null }
8489
9302
  ]
8490
9303
  });
8491
9304
  if (chosen) {
@@ -8511,6 +9324,7 @@ async function promptRunFields(prompter, options) {
8511
9324
  targets: targets ?? [],
8512
9325
  segment,
8513
9326
  questions,
9327
+ intent,
8514
9328
  hours: hours.trim(),
8515
9329
  budget: budget.trim()
8516
9330
  };
@@ -8523,24 +9337,25 @@ function describePreset(preset) {
8523
9337
  if (preset.segmentKey) parts.push(`segmented by ${preset.segmentKey}`);
8524
9338
  return parts.join(" \xB7 ");
8525
9339
  }
8526
- function summaryLines(creation, run) {
9340
+ function summaryLines(creation, run, depths = []) {
8527
9341
  const lines = [
8528
9342
  `Name: ${creation.name}`,
8529
9343
  `Visibility: ${creation.visibility === "PUBLIC" ? "Public" : "Private"}`
8530
9344
  ];
8531
- if (creation.licenceId) lines.push(`Licence: ${creation.licenceId}`);
9345
+ if (creation.licenceId) lines.push(`License: ${creation.licenceId}`);
8532
9346
  lines.push(`Targets: ${run.targets.join(", ")}`);
8533
9347
  if (run.segment) lines.push(`Segment: ${run.segment}`);
8534
9348
  if (run.questions && run.questions.length > 0) {
8535
9349
  lines.push(`Questions: ${run.questions.length}`);
8536
9350
  }
8537
- lines.push(`Depth: ${depthLabel(run)}`);
9351
+ if (run.intent) lines.push("Notes: written (private to you)");
9352
+ lines.push(`Depth: ${depthLabel(run, depths)}`);
8538
9353
  return lines;
8539
9354
  }
8540
- function depthLabel(depth) {
8541
- const preset = matchDepthPreset(depth.hours, depth.budget);
9355
+ function depthLabel(depth, depths = []) {
9356
+ const preset = matchDepthPreset(depths, depth.hours, depth.budget);
8542
9357
  const named = preset ? `${preset.name}, ` : "";
8543
- return `${named}${depth.hours}h \xB7 ${depth.budget} credits`;
9358
+ return `${named}${creditsLabel(depth.budget)}, up to ${timeLabel(depth.hours)}`;
8544
9359
  }
8545
9360
  function missingRunFields(recipe) {
8546
9361
  const missing = [];
@@ -8555,7 +9370,8 @@ function suppliedFromAnalysis(analysis) {
8555
9370
  hours: analysis.hours?.trim() ? analysis.hours : void 0,
8556
9371
  budget: analysis.budget?.trim() ? analysis.budget : void 0,
8557
9372
  segment: analysis.segment ?? null,
8558
- questions: analysis.questions ?? null
9373
+ questions: analysis.questions ?? null,
9374
+ intent: analysis.intent ?? null
8559
9375
  };
8560
9376
  }
8561
9377
  var FIELD_COMMANDS = {
@@ -8577,10 +9393,10 @@ function joinList(items) {
8577
9393
  }
8578
9394
 
8579
9395
  // src/prompting/prompter.ts
8580
- var PromptCancelled = class extends Error {
9396
+ var PromptCanceled = class extends Error {
8581
9397
  constructor() {
8582
- super("Cancelled.");
8583
- this.name = "PromptCancelled";
9398
+ super("Canceled.");
9399
+ this.name = "PromptCanceled";
8584
9400
  }
8585
9401
  };
8586
9402
  function createInquirerPrompter() {
@@ -8589,7 +9405,7 @@ function createInquirerPrompter() {
8589
9405
  try {
8590
9406
  return await work();
8591
9407
  } catch (error) {
8592
- if (error instanceof Error && error.name === "ExitPromptError") throw new PromptCancelled();
9408
+ if (error instanceof Error && error.name === "ExitPromptError") throw new PromptCanceled();
8593
9409
  throw error;
8594
9410
  }
8595
9411
  };
@@ -8632,7 +9448,7 @@ function whyNoPrompt(outputFormat, noInteractive) {
8632
9448
  }
8633
9449
 
8634
9450
  // src/commands/analyze/data-import.ts
8635
- import chalk28 from "chalk";
9451
+ import chalk29 from "chalk";
8636
9452
 
8637
9453
  // src/commands/analyze/details.ts
8638
9454
  function analysisDetails(analysis, endpoint, verdict = null) {
@@ -8641,7 +9457,7 @@ function analysisDetails(analysis, endpoint, verdict = null) {
8641
9457
  name: analysis.name,
8642
9458
  description: analysis.description,
8643
9459
  visibility: sentenceCase(analysis.visibility),
8644
- licence: licenceText(analysis),
9460
+ license: licenseText(analysis),
8645
9461
  introduction: analysis.introduction,
8646
9462
  data: dataShape(analysis.rowCount, analysis.columnCount),
8647
9463
  dataImport: analysis.dataImport?.message ?? null,
@@ -8651,6 +9467,11 @@ function analysisDetails(analysis, endpoint, verdict = null) {
8651
9467
  confirmedInputs: analysis.confirmedInputs,
8652
9468
  questions: analysis.questions,
8653
9469
  segment: analysis.segment,
9470
+ // The platform sends the notes to their owner only; for anyone else they are null and the line is empty.
9471
+ intent: analysis.intent ?? null,
9472
+ expectations: joinedLines(expectationLines(analysis.shapeExpectations)),
9473
+ charts: joinedLines((analysis.requestedPairs ?? []).map(pairText)),
9474
+ focus: joinedLines((analysis.focusFamilies ?? []).map(focusText)),
8654
9475
  hours: hoursText(analysis.hours),
8655
9476
  budget: creditsText(analysis.budget),
8656
9477
  constraints: constraintsText(analysis),
@@ -8674,16 +9495,20 @@ function analysisDetails(analysis, endpoint, verdict = null) {
8674
9495
  { key: "name", header: "Name" },
8675
9496
  { key: "description", header: "Description" },
8676
9497
  { key: "visibility", header: "Visibility" },
8677
- { key: "licence", header: "Licence" },
9498
+ { key: "license", header: "License" },
8678
9499
  { key: "introduction", header: "Introduction" },
8679
9500
  { key: "data", header: "Data" },
8680
9501
  { key: "dataImport", header: "Data import" },
8681
9502
  { key: "targets", header: "Targets" },
8682
9503
  { key: "targetKinds", header: "Target kinds" },
8683
- { key: "inputExclusions", header: "Columns left out of the fit" },
9504
+ { key: "inputExclusions", header: "Columns left out as inputs" },
8684
9505
  { key: "confirmedInputs", header: "Known before the target" },
8685
9506
  { key: "questions", header: "Questions" },
8686
9507
  { key: "segment", header: "Segment" },
9508
+ { key: "intent", header: "Your notes" },
9509
+ { key: "expectations", header: "Expectations" },
9510
+ { key: "charts", header: "Charts you asked for" },
9511
+ { key: "focus", header: "Focus" },
8687
9512
  { key: "hours", header: "Time limit" },
8688
9513
  { key: "budget", header: "Credit budget" },
8689
9514
  { key: "constraints", header: "Constraints" },
@@ -8703,7 +9528,10 @@ function analysisDetails(analysis, endpoint, verdict = null) {
8703
9528
  ];
8704
9529
  return { data, columns };
8705
9530
  }
8706
- function licenceText(analysis) {
9531
+ function joinedLines(lines) {
9532
+ return lines.length > 0 ? lines.join("\n") : null;
9533
+ }
9534
+ function licenseText(analysis) {
8707
9535
  if (analysis.licenceId) return analysis.licenceId;
8708
9536
  return analysis.visibility === "PUBLIC" ? "none chosen" : null;
8709
9537
  }
@@ -8765,12 +9593,12 @@ function constraintsText(analysis) {
8765
9593
  var IMPORT_POLL_INTERVAL_MS = 2e3;
8766
9594
  function renderImportBlock(dataImport, elapsedMs) {
8767
9595
  const title = dataImport.state === "STOPPING" ? "Stopping the data import" : "Importing data";
8768
- const lines = [` ${chalk28.cyan(SPINNER)} ${chalk28.bold(title)}`];
8769
- const elapsed = chalk28.dim(formatDurationPrecise(elapsedMs));
9596
+ const lines = [` ${chalk29.cyan(SPINNER)} ${chalk29.bold(title)}`];
9597
+ const elapsed = chalk29.dim(formatDurationPrecise(elapsedMs));
8770
9598
  if (dataImport.state === "IMPORTING" && dataImport.progress !== null && dataImport.progress !== void 0) {
8771
9599
  lines.push(` ${bar(dataImport.progress)} ${percent(dataImport.progress)} ${elapsed}`);
8772
9600
  } else {
8773
- lines.push(` ${chalk28.dim(dataImport.message)} ${elapsed}`);
9601
+ lines.push(` ${chalk29.dim(dataImport.message)} ${elapsed}`);
8774
9602
  }
8775
9603
  return lines;
8776
9604
  }
@@ -8802,10 +9630,10 @@ async function followImport(ctx, first) {
8802
9630
  try {
8803
9631
  for (; ; ) {
8804
9632
  if (ctx.live) status.set(renderImportBlock(current, Date.now() - since));
8805
- const pause2 = sleep3(IMPORT_POLL_INTERVAL_MS);
8806
- const woke = await Promise.race([pause2.done, interrupted]);
9633
+ const pause3 = sleep3(IMPORT_POLL_INTERVAL_MS);
9634
+ const woke = await Promise.race([pause3.done, interrupted]);
8807
9635
  if (woke === "interrupted") {
8808
- pause2.cancel();
9636
+ pause3.cancel();
8809
9637
  status.stop();
8810
9638
  warn("Stopped waiting. The import keeps running on the platform.");
8811
9639
  hint(`See how far it is with 'diafunc analyze get ${analysisId}'.`);
@@ -8938,7 +9766,7 @@ async function queueRun(api, analysisId) {
8938
9766
  }
8939
9767
 
8940
9768
  // src/commands/analyze/sources.ts
8941
- import * as fs10 from "fs";
9769
+ import * as fs11 from "fs";
8942
9770
  import * as path8 from "path";
8943
9771
  var CAUTIONS = /* @__PURE__ */ new Set([
8944
9772
  "UNEVEN_COLUMNS",
@@ -9033,12 +9861,12 @@ function planLines(plan) {
9033
9861
  }
9034
9862
  function multipart(file) {
9035
9863
  const formData = new FormData();
9036
- formData.append("content", new Blob([fs10.readFileSync(file)]), path8.basename(file));
9864
+ formData.append("content", new Blob([fs11.readFileSync(file)]), path8.basename(file));
9037
9865
  return formData;
9038
9866
  }
9039
9867
  async function uploadSeveral(api, analysisId, files, choices, human) {
9040
9868
  for (const file of files) {
9041
- if (!fs10.existsSync(file)) {
9869
+ if (!fs11.existsSync(file)) {
9042
9870
  throw new CliError(`File not found: ${file}`, { exitCode: EXIT_USAGE });
9043
9871
  }
9044
9872
  }
@@ -9158,19 +9986,75 @@ function budgetHoursOf(hours) {
9158
9986
  return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
9159
9987
  }
9160
9988
  function multipartFromFile(file) {
9161
- const buffer = fs11.readFileSync(file);
9989
+ const buffer = fs12.readFileSync(file);
9162
9990
  const blob = new Blob([buffer]);
9163
9991
  const formData = new FormData();
9164
9992
  formData.append("content", blob, path9.basename(file));
9165
9993
  return formData;
9166
9994
  }
9167
9995
  function reportCommandError(error) {
9168
- if (error instanceof PromptCancelled) throw error;
9996
+ if (error instanceof PromptCanceled) throw error;
9169
9997
  handleError(error);
9170
9998
  }
9999
+ var DEPTH_HELP = "A step of the depth ladder, by name or credits (for example standard, deep or 32000); not together with --hours and --budget";
10000
+ function launchIntentOf(options) {
10001
+ return {
10002
+ notes: notesFromOptions(options),
10003
+ shapes: shapesOf(options.shape),
10004
+ pairs: pairsOf(options.pair),
10005
+ focus: focusOf(options.focus)
10006
+ };
10007
+ }
10008
+ function creationIntent(launch) {
10009
+ const fields = {};
10010
+ if (launch.notes) fields.intent = launch.notes;
10011
+ if (launch.focus && launch.focus.length > 0) fields.focusFamilies = launch.focus;
10012
+ return fields;
10013
+ }
10014
+ async function saveLaunchFields(api, analysisId, columns, launch) {
10015
+ const names = columns.map((c) => c.name).filter((name) => name && name.length > 0);
10016
+ const pickUp = (what, command) => (error) => {
10017
+ const message = error instanceof ApiError ? error.toUserMessage() : error instanceof Error ? error.message : String(error);
10018
+ throw new CliError(message, {
10019
+ exitCode: error instanceof CliError ? error.exitCode : EXIT_FAILURE,
10020
+ hint: [
10021
+ error instanceof CliError ? error.hint : void 0,
10022
+ `Analysis ${analysisId} is created and holds the data. Set the ${what} with '${command}' and start it with 'diafunc analyze rerun ${analysisId}'.`
10023
+ ].filter(Boolean).join("\n ")
10024
+ });
10025
+ };
10026
+ if (launch.shapes) {
10027
+ try {
10028
+ const byTarget = resolveShapeTargets(launch.shapes, names, analysisId);
10029
+ await withStatus("Saving the expectations", () => whenProfiled(
10030
+ () => api.analysis.patchShapeExpectations(analysisId, { byTarget })
10031
+ ));
10032
+ } catch (error) {
10033
+ pickUp("expectations", `diafunc analyze expectations ${analysisId} --target <target> <statement...>`)(error);
10034
+ }
10035
+ }
10036
+ if (launch.pairs && launch.pairs.length > 0) {
10037
+ try {
10038
+ const pairs = resolvePairs(launch.pairs, names, analysisId);
10039
+ await withStatus("Saving the charts", () => api.analysis.patchRequestedPairs(analysisId, { pairs }));
10040
+ } catch (error) {
10041
+ pickUp("charts", `diafunc analyze charts ${analysisId} <first>,<second>[,<kind>]...`)(error);
10042
+ }
10043
+ }
10044
+ }
10045
+ async function readNotesUnattended(api, analysis, notes, outputFormat) {
10046
+ const reading = () => readNotes(api, analysis.analysisId, interpretRequestOf(analysis, notes));
10047
+ const interpretation = outputFormat === "human" ? await withStatus("Reading your notes", reading) : await reading();
10048
+ if (outputFormat !== "human") {
10049
+ process.stdout.write(JSON.stringify({ type: "intent", ...interpretation }) + "\n");
10050
+ return;
10051
+ }
10052
+ printInterpretation(interpretation, analysis.analysisId);
10053
+ console.log();
10054
+ }
9171
10055
  async function runAnalysis(files, options, cmd) {
9172
10056
  for (const candidate of files) {
9173
- if (!fs11.existsSync(candidate)) {
10057
+ if (!fs12.existsSync(candidate)) {
9174
10058
  failure(`File not found: ${candidate}`);
9175
10059
  process.exit(EXIT_FAILURE);
9176
10060
  }
@@ -9179,7 +10063,9 @@ async function runAnalysis(files, options, cmd) {
9179
10063
  const outputFormat = getOutputFormat17(cmd);
9180
10064
  const noInteractive = noInteractiveFlag(cmd);
9181
10065
  const interactive = canPrompt(outputFormat, noInteractive);
10066
+ const launch = launchIntentOf(options);
9182
10067
  const api = createApiClient();
10068
+ applyDepthOption(options, options.depth === void 0 ? [] : await readDepths(api));
9183
10069
  let presetTargets;
9184
10070
  if (options.preset) {
9185
10071
  const opt = await api.analysis.getPreset(options.preset);
@@ -9209,12 +10095,12 @@ async function runAnalysis(files, options, cmd) {
9209
10095
  name: options.name,
9210
10096
  description: options.description,
9211
10097
  visibility: options.visibility === void 0 ? void 0 : parseVisibility(options.visibility),
9212
- licenceId: options.licence
9213
- }, fallbackName, () => api.admin.listLicences()) : {
10098
+ licenceId: options.license
10099
+ }, fallbackName, () => api.admin.listLicenses()) : {
9214
10100
  name: options.name ?? fallbackName,
9215
10101
  description: options.description?.trim() || null,
9216
10102
  visibility: options.visibility === void 0 ? "PRIVATE" : parseVisibility(options.visibility),
9217
- licenceId: options.licence
10103
+ licenceId: options.license
9218
10104
  };
9219
10105
  const request = {
9220
10106
  name: creation.name,
@@ -9230,6 +10116,7 @@ async function runAnalysis(files, options, cmd) {
9230
10116
  };
9231
10117
  const created = await withStatus(`Creating analysis "${creation.name}"`, () => api.analysis.create({
9232
10118
  ...request,
10119
+ ...creationIntent(launch),
9233
10120
  ...creation.licenceId ? { licenceId: creation.licenceId } : {}
9234
10121
  }));
9235
10122
  if (isDryRun()) {
@@ -9249,7 +10136,7 @@ async function runAnalysis(files, options, cmd) {
9249
10136
  }
9250
10137
  );
9251
10138
  }
9252
- detail(`depth: ${depthLabel(stored)}${created.depthPreselection ? " (the account's starting depth)" : ""}`);
10139
+ detail(`depth: ${depthLabel(stored, await readDepths(api))}${created.depthPreselection ? " (the account's starting depth)" : ""}`);
9253
10140
  }
9254
10141
  await sendData(importContext(api, created.analysisId, cmd, "stream"), () => files.length > 1 ? uploadSeveral(api, created.analysisId, files, stackChoices(options, files), outputFormat === "human") : uploadOne(api, created.analysisId, file, asUploadedOf(options.asUploaded, files), outputFormat === "human"));
9255
10142
  const columns = await readColumns(api, created.analysisId);
@@ -9265,17 +10152,23 @@ async function runAnalysis(files, options, cmd) {
9265
10152
  targets: named.targets,
9266
10153
  segment: named.segment,
9267
10154
  questions: options.question === void 0 ? void 0 : questionsOf(options.question),
10155
+ intent: launch.notes === void 0 ? void 0 : launch.notes || null,
9268
10156
  hours: options.hours,
9269
10157
  budget: options.budget
9270
- }, columns, creation.licenceId);
10158
+ }, columns, creation.licenceId, { launch, storedNotes: launch.notes || null });
9271
10159
  if (configuredHours === null) return;
9272
10160
  runHours = configuredHours;
9273
10161
  } else {
9274
- await withStatus("Saving the analysis settings", () => api.analysis.update(created.analysisId, {
10162
+ const saved = await withStatus("Saving the analysis settings", () => api.analysis.update(created.analysisId, {
9275
10163
  ...recipe,
9276
10164
  targets: named.targets ?? null,
9277
10165
  segment: named.segment ?? null
9278
10166
  }));
10167
+ await saveLaunchFields(api, created.analysisId, columns, launch);
10168
+ if (launch.notes) {
10169
+ await readNotesUnattended(api, { ...created, ...saved, analysisId: created.analysisId }, launch.notes, outputFormat);
10170
+ if (outputFormat === "human") hint(`Confirmed proposals take part from the next run: 'diafunc analyze rerun ${created.analysisId}'.`);
10171
+ }
9279
10172
  }
9280
10173
  const run = await withStatus("Queuing analysis run", () => queueRun(api, created.analysisId));
9281
10174
  detail(`runId: ${run.runId}`);
@@ -9306,13 +10199,14 @@ function namedColumns(analysisId, columns, interactive, given) {
9306
10199
  const segment = given.segment === void 0 || given.segment === "" ? void 0 : read(() => resolveColumnArgument(given.segment, names, analysisId));
9307
10200
  return { targets, segment };
9308
10201
  }
9309
- async function configureInteractively(api, prompter, analysisId, recipe, supplied, knownColumns, licenceId) {
10202
+ async function configureInteractively(api, prompter, analysisId, recipe, supplied, knownColumns, licenceId, fromCommandLine) {
9310
10203
  const columns = knownColumns ?? await readColumns(api, analysisId);
9311
10204
  const presets = await readPresets(api);
9312
10205
  const depthAsked = supplied.hours === void 0 || supplied.budget === void 0;
9313
10206
  const depthDefault = depthAsked ? await readDepthDefault(api, recipe) : null;
10207
+ const depths = await readDepths(api);
9314
10208
  console.log();
9315
- const answers = await promptRunFields(prompter, { columns, presets, supplied, depthDefault });
10209
+ const answers = await promptRunFields(prompter, { columns, presets, supplied, depthDefault, depths });
9316
10210
  console.log();
9317
10211
  const saved = await withStatus("Saving the analysis settings", () => api.analysis.update(analysisId, {
9318
10212
  ...recipe,
@@ -9322,6 +10216,16 @@ async function configureInteractively(api, prompter, analysisId, recipe, supplie
9322
10216
  hours: answers.hours,
9323
10217
  budget: answers.budget
9324
10218
  }));
10219
+ const recipeNow = await settleNotes(
10220
+ api,
10221
+ prompter,
10222
+ analysisId,
10223
+ saved,
10224
+ columns,
10225
+ answers.intent,
10226
+ fromCommandLine ?? { launch: null, storedNotes: supplied.intent ?? null },
10227
+ { targets: answers.targets, segment: answers.segment }
10228
+ );
9325
10229
  console.log();
9326
10230
  heading("Ready to run");
9327
10231
  const identity = {
@@ -9331,7 +10235,8 @@ async function configureInteractively(api, prompter, analysisId, recipe, supplie
9331
10235
  ...licenceId ? { licenceId } : {}
9332
10236
  };
9333
10237
  const depth = depthOf(saved?.hours, saved?.budget) ?? { hours: answers.hours, budget: answers.budget };
9334
- for (const line of summaryLines(identity, { ...answers, ...depth })) detail(line);
10238
+ for (const line of summaryLines(identity, { ...answers, ...depth }, depths)) detail(line);
10239
+ for (const line of intentRecipeLines(recipeNow ?? {})) detail(line);
9335
10240
  console.log();
9336
10241
  if (!await prompter.confirm({ message: "Start the analysis?", default: true })) {
9337
10242
  warn("Not started. The analysis and these settings are saved.");
@@ -9340,6 +10245,65 @@ async function configureInteractively(api, prompter, analysisId, recipe, supplie
9340
10245
  }
9341
10246
  return depth.hours;
9342
10247
  }
10248
+ async function settleNotes(api, prompter, analysisId, saved, columns, notes, given, setup) {
10249
+ let touched = false;
10250
+ if (given.launch && (given.launch.shapes || (given.launch.pairs?.length ?? 0) > 0)) {
10251
+ await saveLaunchFields(api, analysisId, columns, given.launch);
10252
+ touched = true;
10253
+ }
10254
+ if (notes && notes !== given.storedNotes) {
10255
+ await withStatus("Saving your notes", () => api.analysis.patchIntent(analysisId, { intent: notes }));
10256
+ }
10257
+ if (notes && !isDryRun()) {
10258
+ const base = { ...saved, analysisId, targets: saved?.targets ?? setup.targets, segment: saved?.segment ?? setup.segment };
10259
+ const interpretation = await withStatus("Reading your notes", () => readNotes(api, analysisId, interpretRequestOf(base, notes)));
10260
+ if (interpretation.status !== "READY") {
10261
+ printInterpretation(interpretation, analysisId);
10262
+ } else {
10263
+ printUnavailable(interpretation);
10264
+ for (const note of [...interpretation.notUnderstood ?? [], ...interpretation.rejections ?? []]) {
10265
+ warn(`Not used: "${note.quote}"${note.reason ? `: ${note.reason}` : ""}`);
10266
+ }
10267
+ const decisions = await promptIntentDecisions(prompter, interpretation);
10268
+ if (decisions.length > 0) {
10269
+ await withStatus("Saving your decisions", () => api.analysis.decideIntentItems(analysisId, { decisions }));
10270
+ touched = true;
10271
+ }
10272
+ }
10273
+ }
10274
+ if (!touched || isDryRun()) return saved;
10275
+ try {
10276
+ return (await api.analysis.get(analysisId)).analysis ?? saved;
10277
+ } catch (error) {
10278
+ if (isAuthenticationFailure(error)) throw error;
10279
+ return saved;
10280
+ }
10281
+ }
10282
+ async function readDepths(api) {
10283
+ try {
10284
+ return await api.analysis.getDepths() ?? [];
10285
+ } catch {
10286
+ return [];
10287
+ }
10288
+ }
10289
+ function applyDepthOption(options, depths) {
10290
+ if (options.depth === void 0) return;
10291
+ if (options.hours !== void 0 || options.budget !== void 0) {
10292
+ usageError("Name a depth with --depth, or a time limit and a credit budget with --hours and --budget, not both.");
10293
+ }
10294
+ if (depths.length === 0) {
10295
+ usageError("The depths could not be read from the platform.", "Pass --hours and --budget instead.");
10296
+ }
10297
+ const step = findDepth(depths, options.depth);
10298
+ if (!step) {
10299
+ usageError(
10300
+ `There is no depth '${options.depth}'.`,
10301
+ `Name one of ${depths.map((d) => d.name).join(", ")}, or its credits (for example --depth 4000).`
10302
+ );
10303
+ }
10304
+ options.hours = step.hours;
10305
+ options.budget = step.budget;
10306
+ }
9343
10307
  async function readDepthDefault(api, stored) {
9344
10308
  try {
9345
10309
  const answer = await api.analysis.getDepthDefault();
@@ -9539,7 +10503,11 @@ async function getAnalysisDetails(analysisId, options, cmd) {
9539
10503
  format(result.analysis, { format: outputFormat });
9540
10504
  return;
9541
10505
  }
9542
- const analysis = options.full ? result.analysis : { ...result.analysis, introduction: abbreviate(result.analysis.introduction) };
10506
+ const analysis = options.full ? result.analysis : {
10507
+ ...result.analysis,
10508
+ introduction: abbreviate(result.analysis.introduction),
10509
+ intent: abbreviate(result.analysis.intent ?? null)
10510
+ };
9543
10511
  const config = loadConfig();
9544
10512
  const endpoint = config.profiles[config.currentProfile]?.endpoint ?? "https://diafunc.com";
9545
10513
  const details = analysisDetails(analysis, endpoint, await resultVerdict(api, result.analysis));
@@ -9547,6 +10515,9 @@ async function getAnalysisDetails(analysisId, options, cmd) {
9547
10515
  if (!options.full && isLong(result.analysis.introduction)) {
9548
10516
  hint("Introduction abbreviated. Pass --full to print it whole.");
9549
10517
  }
10518
+ if (!options.full && isLong(result.analysis.intent ?? null)) {
10519
+ hint("Your notes abbreviated. Pass --full, or run 'diafunc analyze intent " + result.analysis.analysisId + "', to print them whole.");
10520
+ }
9550
10521
  }
9551
10522
  async function resultVerdict(api, analysis) {
9552
10523
  if (!analysis.resultRunId) return null;
@@ -9665,13 +10636,29 @@ async function openAnalysis(analysisId) {
9665
10636
  hint("The notebook is not available yet. Run the analysis first.");
9666
10637
  }
9667
10638
  }
10639
+ function windowedShapes(shapes) {
10640
+ if (!shapes) return null;
10641
+ for (const statement of Object.values(shapes).flat()) {
10642
+ const args = /\((.*)\)\s*$/.exec(statement)?.[1].split(",") ?? [];
10643
+ if (!/range\s*\(/i.test(statement) && args.length !== 3) {
10644
+ usageError(
10645
+ `'${statement}' has no window, and an analysis without data has no observed range to bind it to.`,
10646
+ "Give the window, for example increasing(size_m2, 20, 200), or set the expectation after the upload with 'diafunc analyze expectations <id> --target <target> <statement...>'."
10647
+ );
10648
+ }
10649
+ }
10650
+ return shapes;
10651
+ }
9668
10652
  function typedColumns(given) {
9669
10653
  const entries = occurrences(given);
9670
10654
  return entries === void 0 ? null : resolveColumnArguments(entries, []);
9671
10655
  }
9672
10656
  async function createAnalysis(options, cmd) {
9673
10657
  const outputFormat = getOutputFormat17(cmd);
10658
+ const launch = launchIntentOf(options);
10659
+ const shapes = windowedShapes(launch.shapes);
9674
10660
  const api = createApiClient();
10661
+ applyDepthOption(options, options.depth === void 0 ? [] : await readDepths(api));
9675
10662
  const visibility = parseVisibility(options.visibility);
9676
10663
  const request = {
9677
10664
  name: options.name ?? "CLI Analysis",
@@ -9685,13 +10672,19 @@ async function createAnalysis(options, cmd) {
9685
10672
  };
9686
10673
  const created = await api.analysis.create({
9687
10674
  ...request,
9688
- ...options.licence ? { licenceId: options.licence } : {}
10675
+ ...creationIntent(launch),
10676
+ ...shapes ? { shapeExpectations: shapes } : {},
10677
+ ...launch.pairs && launch.pairs.length > 0 ? { requestedPairs: launch.pairs } : {},
10678
+ ...options.license ? { licenceId: options.license } : {}
9689
10679
  });
9690
10680
  if (isDryRun()) {
9691
10681
  hint("Dry run: nothing was created.");
9692
10682
  return;
9693
10683
  }
9694
10684
  format(created, { format: outputFormat });
10685
+ if (launch.notes && outputFormat === "human") {
10686
+ hint(`Your notes are stored. Read them into proposals once the data is uploaded: 'diafunc analyze intent read ${created.analysisId}'.`);
10687
+ }
9695
10688
  }
9696
10689
  async function deleteAnalysis(analysisId) {
9697
10690
  const api = createApiClient();
@@ -9724,6 +10717,223 @@ async function patchColumns(analysisId, given, send, successLabel, cmd) {
9724
10717
  const columns = resolveColumnArguments(occurrences(given) ?? [], await columnNames(api, analysisId), analysisId);
9725
10718
  await patchAndPrint(analysisId, "", () => send(api, columns), successLabel, cmd);
9726
10719
  }
10720
+ async function ownAnalysis(api, analysisId) {
10721
+ const found = await api.analysis.get(analysisId);
10722
+ if (!found.analysis) {
10723
+ failure(`Analysis not found: ${analysisId}`);
10724
+ process.exit(EXIT_FAILURE);
10725
+ }
10726
+ return found.analysis;
10727
+ }
10728
+ async function notesCommand(analysisId, text2, options, cmd) {
10729
+ const outputFormat = getOutputFormat17(cmd);
10730
+ const api = createApiClient();
10731
+ const given = [text2 !== void 0, options.file !== void 0, options.clear === true].filter(Boolean).length;
10732
+ if (given > 1) usageError("Give the notes as text, with --file, or clear them with --clear: one of the three.");
10733
+ if (given === 0) {
10734
+ const analysis = await ownAnalysis(api, analysisId);
10735
+ if (outputFormat !== "human") {
10736
+ format({ analysisId, intent: analysis.intent ?? null }, { format: outputFormat });
10737
+ return;
10738
+ }
10739
+ if (!analysis.intent) {
10740
+ empty("notes");
10741
+ hint(`Write them with 'diafunc analyze intent ${analysisId} "<text>"'. Only you can read them.`);
10742
+ return;
10743
+ }
10744
+ console.log(analysis.intent);
10745
+ hint(`Only you can read these notes. Read them into proposals with 'diafunc analyze intent read ${analysisId}'.`);
10746
+ return;
10747
+ }
10748
+ let notes;
10749
+ if (options.clear) {
10750
+ notes = null;
10751
+ } else if (options.file !== void 0) {
10752
+ notes = notesFromOptions({ intentFile: options.file }) || null;
10753
+ } else {
10754
+ checkNotesLength(text2);
10755
+ notes = text2.trim() || null;
10756
+ }
10757
+ const updated = await api.analysis.patchIntent(analysisId, { intent: notes });
10758
+ if (isDryRun()) {
10759
+ hint("Dry run: nothing was changed.");
10760
+ return;
10761
+ }
10762
+ if (outputFormat !== "human") {
10763
+ format(updated, { format: outputFormat });
10764
+ return;
10765
+ }
10766
+ if (notes === null) {
10767
+ success(`Notes cleared for analysis ${analysisId}.`);
10768
+ hint("Proposals you confirmed earlier stay in place until you decline them.");
10769
+ return;
10770
+ }
10771
+ success(`Notes saved for analysis ${analysisId}. Only you can read them.`);
10772
+ hint(`Read them into proposals with 'diafunc analyze intent read ${analysisId}'. Nothing changes until you confirm one.`);
10773
+ }
10774
+ async function readNotesCommand(analysisId, options, cmd) {
10775
+ const outputFormat = getOutputFormat17(cmd);
10776
+ const api = createApiClient();
10777
+ const analysis = await ownAnalysis(api, analysisId);
10778
+ if (!analysis.intent) {
10779
+ if (outputFormat !== "human") {
10780
+ format(
10781
+ { status: "EMPTY", hash: null, derivedAt: null, items: [], notUnderstood: [], rejections: [], findings: [] },
10782
+ { format: outputFormat }
10783
+ );
10784
+ return;
10785
+ }
10786
+ empty("notes");
10787
+ hint(`Write them first with 'diafunc analyze intent ${analysisId} "<text>"'.`);
10788
+ return;
10789
+ }
10790
+ const reading = () => readNotes(
10791
+ api,
10792
+ analysisId,
10793
+ interpretRequestOf(analysis, analysis.intent),
10794
+ { force: options.force, refine: options.refine }
10795
+ );
10796
+ const interpretation = outputFormat === "human" ? await withStatus("Reading your notes", reading) : await reading();
10797
+ if (isDryRun()) {
10798
+ hint("Dry run: the notes were not read.");
10799
+ return;
10800
+ }
10801
+ if (outputFormat !== "human") {
10802
+ format(interpretation, { format: outputFormat });
10803
+ return;
10804
+ }
10805
+ printInterpretation(interpretation, analysisId);
10806
+ }
10807
+ async function decideCommand(state, analysisId, ids, options, cmd) {
10808
+ const outputFormat = getOutputFormat17(cmd);
10809
+ const wanted = [...new Set(ids.flatMap((id) => id.split(",")).map((id) => id.trim()).filter((id) => id.length > 0))];
10810
+ if (wanted.length === 0) usageError("Name at least one proposal.", `The ids are in 'diafunc analyze intent read ${analysisId}'.`);
10811
+ if (options.steer !== void 0 && state !== "CONFIRMED") {
10812
+ usageError("--steer and --no-steer go with confirm only.");
10813
+ }
10814
+ const api = createApiClient();
10815
+ const stored = await api.analysis.getIntentInterpretation(analysisId);
10816
+ const known = new Map((stored.items ?? []).map((item) => [item.id, item]));
10817
+ const unknown = wanted.filter((id) => !known.has(id));
10818
+ if (unknown.length > 0) {
10819
+ usageError(
10820
+ `${unknown.map((id) => `'${id}'`).join(", ")} ${unknown.length === 1 ? "is not a proposal" : "are not proposals"} of analysis ${analysisId}.`,
10821
+ `List the proposals with 'diafunc analyze intent read ${analysisId}'.`
10822
+ );
10823
+ }
10824
+ if (options.steer !== void 0) {
10825
+ const notExpectations = wanted.filter((id) => known.get(id)?.effect !== "checks");
10826
+ if (notExpectations.length > 0) {
10827
+ usageError(`Only an expectation can steer the model; ${notExpectations.map((id) => `'${id}'`).join(", ")} ${notExpectations.length === 1 ? "is" : "are"} not one.`);
10828
+ }
10829
+ }
10830
+ const decisions = wanted.map((id) => ({ id, state, steer: options.steer ?? null }));
10831
+ const decided = await api.analysis.decideIntentItems(analysisId, { decisions });
10832
+ if (isDryRun()) {
10833
+ hint("Dry run: nothing was changed.");
10834
+ return;
10835
+ }
10836
+ if (outputFormat !== "human") {
10837
+ format(decided, { format: outputFormat });
10838
+ return;
10839
+ }
10840
+ const verb = state === "CONFIRMED" ? "Using" : state === "DECLINED" ? "Not using" : "Open again:";
10841
+ for (const item of (decided.items ?? []).filter((i) => wanted.includes(i.id))) {
10842
+ success(`${verb} ${item.id}: ${item.statement}`);
10843
+ }
10844
+ if (state === "CONFIRMED") hint(`It takes part from the next run: 'diafunc analyze rerun ${analysisId}'.`);
10845
+ }
10846
+ async function expectationsCommand(analysisId, given, options, cmd) {
10847
+ const outputFormat = getOutputFormat17(cmd);
10848
+ const api = createApiClient();
10849
+ const analysis = await ownAnalysis(api, analysisId);
10850
+ const current = analysis.shapeExpectations ?? {};
10851
+ const statements = given.filter((g) => g.trim().length > 0);
10852
+ if (options.clear && statements.length > 0) usageError("Give statements or --clear, not both.");
10853
+ if (!options.clear && statements.length === 0) {
10854
+ const shown = options.target === void 0 ? current : Object.fromEntries(Object.entries(current).filter(([target]) => target === options.target));
10855
+ if (outputFormat !== "human") {
10856
+ format({ analysisId, shapeExpectations: shown }, { format: outputFormat });
10857
+ return;
10858
+ }
10859
+ const lines = expectationLines(shown);
10860
+ if (lines.length === 0) {
10861
+ empty("expectations");
10862
+ hint(`Set one with 'diafunc analyze expectations ${analysisId} --target <target> "increasing(<input>)"'.`);
10863
+ return;
10864
+ }
10865
+ for (const line of lines) console.log(line);
10866
+ hint("An expectation is checked and reported; one written with require: also steers the model.");
10867
+ return;
10868
+ }
10869
+ const columns = await columnNames(api, analysisId);
10870
+ const targetOf = (typed2) => resolveColumnArgument(typed2, columns, analysisId);
10871
+ const byTarget = Object.fromEntries(Object.entries(current).map(([t, s]) => [t, [...s]]));
10872
+ if (options.clear) {
10873
+ if (options.target === void 0) {
10874
+ for (const target of Object.keys(byTarget)) delete byTarget[target];
10875
+ } else {
10876
+ delete byTarget[targetOf(options.target)];
10877
+ }
10878
+ } else {
10879
+ const named = {};
10880
+ for (const entry of statements) {
10881
+ let target;
10882
+ let statement;
10883
+ if (options.target !== void 0) {
10884
+ target = targetOf(options.target);
10885
+ statement = checkedStatement(entry);
10886
+ } else if (entry.includes("=")) {
10887
+ const read = parseShapeFlag(entry);
10888
+ target = targetOf(read.target);
10889
+ statement = read.statement;
10890
+ } else if ((analysis.targets ?? []).length === 1) {
10891
+ target = analysis.targets[0];
10892
+ statement = checkedStatement(entry);
10893
+ } else {
10894
+ usageError(
10895
+ `'${entry}' names no target, and the analysis has ${(analysis.targets ?? []).length === 0 ? "none yet" : "several"}.`,
10896
+ `Pass --target <target>, or write <target>=<statement>.`
10897
+ );
10898
+ }
10899
+ named[target] ??= [];
10900
+ if (!named[target].includes(statement)) named[target].push(statement);
10901
+ }
10902
+ Object.assign(byTarget, named);
10903
+ }
10904
+ const updated = await api.analysis.patchShapeExpectations(analysisId, { byTarget });
10905
+ if (isDryRun()) {
10906
+ hint("Dry run: nothing was changed.");
10907
+ return;
10908
+ }
10909
+ if (outputFormat !== "human") {
10910
+ format(updated, { format: outputFormat });
10911
+ return;
10912
+ }
10913
+ success(`Expectations updated for analysis ${analysisId}.`);
10914
+ for (const line of expectationLines(updated?.shapeExpectations)) detail(line);
10915
+ }
10916
+ async function chartsCommand(analysisId, given, cmd) {
10917
+ const api = createApiClient();
10918
+ const pairs = resolvePairs(pairsOf(given) ?? [], await columnNames(api, analysisId), analysisId);
10919
+ await patchAndPrint(
10920
+ analysisId,
10921
+ pairs.map(pairText).join("; "),
10922
+ () => api.analysis.patchRequestedPairs(analysisId, { pairs }),
10923
+ "Charts",
10924
+ cmd
10925
+ );
10926
+ }
10927
+ async function focusCommand(analysisId, given, cmd) {
10928
+ const families = focusOf(given) ?? [];
10929
+ await patchAndPrint(
10930
+ analysisId,
10931
+ families.map(focusText).join(", "),
10932
+ (api, aid) => api.analysis.patchFocusFamilies(aid, { families }),
10933
+ "Focus",
10934
+ cmd
10935
+ );
10936
+ }
9727
10937
  function collectAsUploaded(value, previous) {
9728
10938
  return [...Array.isArray(previous) ? previous : [], value];
9729
10939
  }
@@ -9787,7 +10997,7 @@ async function uploadData(analysisId, files, options, cmd) {
9787
10997
  `For example: diafunc analyze upload ${analysisId} data.csv`
9788
10998
  );
9789
10999
  }
9790
- if (!fs11.existsSync(file)) {
11000
+ if (!fs12.existsSync(file)) {
9791
11001
  throw new CliError(`File not found: ${file}`, { exitCode: EXIT_USAGE });
9792
11002
  }
9793
11003
  }
@@ -10012,11 +11222,21 @@ async function updateTriggerCmd(triggerId, options, cmd) {
10012
11222
  format(trigger, { format: outputFormat });
10013
11223
  }
10014
11224
  var COLUMN_LIST_HELP = "one argument each or comma-separated; a name that contains a comma is an argument of its own, or goes in double quotes inside a list";
10015
- var LICENCE_HELP = "With PUBLIC: the licence the analysis's project is published under, an id of the licence catalogue (see 'diafunc licence list')";
11225
+ var LICENSE_HELP = "With PUBLIC: the license the analysis's project is published under, an id of the license catalog (see 'diafunc license list')";
10016
11226
  var TARGETS_HELP = `Target column names: repeat the flag or separate them with commas; a name that contains a comma is one flag of its own, or goes in double quotes inside a list`;
11227
+ var INTENT_HELP = "What you know about the data and what matters to you, in your own words. Private to you. It is read into proposals; nothing changes until you confirm one";
11228
+ var SHAPE_HELP = "An expectation about a target's shape, <target>=<statement>, for example price=increasing(size_m2); checked and reported, or with require: in front also steering the model; repeat the flag for several";
11229
+ var PAIR_QUOTING_HELP = `A column whose name holds a comma goes in double quotes: '"a, b",price'`;
11230
+ var PAIR_HELP = `A chart to add to the report: the second column against the first, with kind scatter, groups or counts, or none; at most ${MAX_PAIRS}; repeat the flag for several. ${PAIR_QUOTING_HELP}`;
11231
+ var FOCUS_HELP = `A question family that matters most to you, for example extrapolation or input_importance; at most ${MAX_FOCUS}, most important first; repeat the flag for several`;
11232
+ var FOCUS_FAMILY_LINES = FOCUS_FAMILIES.map((f) => ` ${f.id.padEnd(20)}${f.label}`).join("\n");
11233
+ var FOCUS_FAMILIES_HELP = `
11234
+ Question families:
11235
+ ${FOCUS_FAMILY_LINES}
11236
+ `;
10017
11237
  function registerAnalyzeCommand(program) {
10018
11238
  const analyze = program.command("analyze").description("Run and manage automatic analyses");
10019
- analyze.command("run", { isDefault: true }).description("Create an analysis from a data file, configure it and run it (the default: `analyze <file>`)").argument("[files...]", "Data file to analyze (CSV, Excel and more than 45 file formats; see `table import-formats`). Several files are combined into one table: files with the same columns are stacked, a file that shares a key adds its columns").option("--name <name>", "Analysis name (asked for, or derived from the filename)").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC (default: PRIVATE)").option("--licence <licenceId>", LICENCE_HELP).option("--hours <hours>", `Time limit (hours). ${STARTING_DEPTH_RULE}`).option("--budget <credits>", `Credit budget. ${STARTING_DEPTH_RULE}`).option("--targets <columns>", `${TARGETS_HELP} (required when not interactive)`, collectColumns).option("--question <text>", "A question for the analysis to answer; repeat the flag for several", collectQuestion).option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction shown at the top of the notebook").option("--preset <id>", "Apply a saved preset as defaults (explicit flags override it)").option("--no-file-column", "With several files: do not add the column that records the file each row came from").option("--keep-duplicates", "With several files: keep rows that occur in more than one file").option("--rows-of <file>", "With several files that can be read two ways: the file in which one row is one observation").option("--as-uploaded [file]", AS_UPLOADED_HELP, collectAsUploaded).action(async (files, options, cmd) => {
11239
+ analyze.command("run", { isDefault: true }).description("Create an analysis from a data file, configure it and run it (the default: `analyze <file>`)").argument("[files...]", "Data file to analyze (CSV, Excel and more than 45 file formats; see `table import-formats`). Several files are combined into one table: files with the same columns are stacked, a file that shares a key adds its columns").option("--name <name>", "Analysis name (asked for, or derived from the filename)").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC (default: PRIVATE)").option("--license <licenseId>", LICENSE_HELP).addOption(hiddenOptionAlias("--licence <licenseId>", "license")).option("--depth <name or credits>", DEPTH_HELP).option("--hours <hours>", `Time limit (hours) for a depth of your own. ${STARTING_DEPTH_RULE}`).option("--budget <credits>", `Credit budget for a depth of your own. ${STARTING_DEPTH_RULE}`).option("--targets <columns>", `${TARGETS_HELP} (required when not interactive)`, collectColumns).option("--question <text>", "A question for the analysis to answer; repeat the flag for several", collectQuestion).option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction shown at the top of the notebook").option("--preset <id>", "Apply a saved preset as defaults (explicit flags override it)").option("--no-file-column", "With several files: do not add the column that records the file each row came from").option("--keep-duplicates", "With several files: keep rows that occur in more than one file").option("--rows-of <file>", "With several files that can be read two ways: the file in which one row is one observation").option("--as-uploaded [file]", AS_UPLOADED_HELP, collectAsUploaded).option("--intent <text>", INTENT_HELP).option("--intent-file <path>", "Read the notes from a file instead (for notes longer than a line)").option("--shape <target=statement>", SHAPE_HELP, collectQuestion).option("--pair <first,second[,kind]>", PAIR_HELP, collectQuestion).option("--focus <family>", FOCUS_HELP, collectQuestion).action(async (files, options, cmd) => {
10020
11240
  try {
10021
11241
  if (files.length === 0) {
10022
11242
  analyze.help();
@@ -10034,7 +11254,7 @@ function registerAnalyzeCommand(program) {
10034
11254
  handleError(error);
10035
11255
  }
10036
11256
  });
10037
- 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").addHelpText("after", REPORT_TERMS_HELP).action(async (id, options, cmd) => {
11257
+ analyze.command("get").description("Show details of an analysis").argument("[id]", "Analysis ID (defaults to the most recent)").option("--full", "Print the introduction and your notes in full instead of abbreviating them").addHelpText("after", REPORT_TERMS_HELP).action(async (id, options, cmd) => {
10038
11258
  try {
10039
11259
  await getAnalysisDetails(id, options, cmd);
10040
11260
  } catch (error) {
@@ -10062,14 +11282,14 @@ function registerAnalyzeCommand(program) {
10062
11282
  reportCommandError(error);
10063
11283
  }
10064
11284
  });
10065
- analyze.command("create").description("Create an analysis without uploading data or running it").option("--name <name>", "Analysis name").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC", "PRIVATE").option("--licence <licenceId>", LICENCE_HELP).option("--hours <hours>", `Time limit (hours). ${STARTING_DEPTH_RULE}`).option("--budget <credits>", `Credit budget. ${STARTING_DEPTH_RULE}`).option("--targets <columns>", TARGETS_HELP, collectColumns).option("--question <text>", "A question for the analysis to answer; repeat the flag for several", collectQuestion).option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction shown at the top of the notebook").action(async (options, cmd) => {
11285
+ analyze.command("create").description("Create an analysis without uploading data or running it").option("--name <name>", "Analysis name").option("--description <text>", "Analysis description").option("--visibility <vis>", "PRIVATE or PUBLIC", "PRIVATE").option("--license <licenseId>", LICENSE_HELP).addOption(hiddenOptionAlias("--licence <licenseId>", "license")).option("--depth <name or credits>", DEPTH_HELP).option("--hours <hours>", `Time limit (hours) for a depth of your own. ${STARTING_DEPTH_RULE}`).option("--budget <credits>", `Credit budget for a depth of your own. ${STARTING_DEPTH_RULE}`).option("--targets <columns>", TARGETS_HELP, collectColumns).option("--question <text>", "A question for the analysis to answer; repeat the flag for several", collectQuestion).option("--segment <name>", "Column to segment the analysis by").option("--introduction <markdown>", "Markdown introduction shown at the top of the notebook").option("--intent <text>", INTENT_HELP).option("--intent-file <path>", "Read the notes from a file instead (for notes longer than a line)").option("--shape <target=statement>", SHAPE_HELP, collectQuestion).option("--pair <first,second[,kind]>", PAIR_HELP, collectQuestion).option("--focus <family>", FOCUS_HELP, collectQuestion).action(async (options, cmd) => {
10066
11286
  try {
10067
11287
  await createAnalysis(options, cmd);
10068
11288
  } catch (error) {
10069
11289
  handleError(error);
10070
11290
  }
10071
11291
  });
10072
- analyze.command("delete").description("Delete an analysis, cancelling any run still in flight").argument("<id>", "Analysis ID").option("-y, --yes", "Skip confirmation prompt (for CI / scripted use)").action(async (id, options) => {
11292
+ analyze.command("delete").description("Delete an analysis, canceling any run still in flight").argument("<id>", "Analysis ID").option("-y, --yes", "Skip confirmation prompt (for CI / scripted use)").action(async (id, options) => {
10073
11293
  try {
10074
11294
  await confirmDestructive(`This will permanently delete analysis "${id}".`, { yes: options.yes, resourceId: id });
10075
11295
  await deleteAnalysis(id);
@@ -10103,10 +11323,10 @@ function registerAnalyzeCommand(program) {
10103
11323
  handleError(error);
10104
11324
  }
10105
11325
  });
10106
- analyze.command("visibility").description("Set analysis visibility (PRIVATE or PUBLIC)").argument("<id>", "Analysis ID").argument("<vis>", "PRIVATE or PUBLIC").option("--licence <licenceId>", LICENCE_HELP).addHelpText("after", `
11326
+ analyze.command("visibility").description("Set analysis visibility (PRIVATE or PUBLIC)").argument("<id>", "Analysis ID").argument("<vis>", "PRIVATE or PUBLIC").option("--license <licenseId>", LICENSE_HELP).addOption(hiddenOptionAlias("--licence <licenseId>", "license")).addHelpText("after", `
10107
11327
  Examples:
10108
- $ diafunc analyze visibility <id> PUBLIC --licence CC-BY-4.0 publish under a licence
10109
- $ diafunc analyze visibility <id> PRIVATE withdraw it; the licence is kept for later
11328
+ $ diafunc analyze visibility <id> PUBLIC --license CC-BY-4.0 publish under a license
11329
+ $ diafunc analyze visibility <id> PRIVATE withdraw it; the license is kept for later
10110
11330
  `).action(async (id, vis, options, cmd) => {
10111
11331
  try {
10112
11332
  const visibility = parseVisibility(vis);
@@ -10115,7 +11335,7 @@ Examples:
10115
11335
  visibility,
10116
11336
  (api, aid, v) => api.analysis.patchVisibility(aid, {
10117
11337
  visibility: v,
10118
- ...options.licence ? { licenceId: options.licence } : {}
11338
+ ...options.license ? { licenceId: options.license } : {}
10119
11339
  }),
10120
11340
  "Visibility",
10121
11341
  cmd
@@ -10176,13 +11396,13 @@ Examples:
10176
11396
  handleError(error);
10177
11397
  }
10178
11398
  });
10179
- analyze.command("input-exclusions").description("Set the columns every fit leaves out as an input (a single empty string leaves nothing out)").argument("<id>", "Analysis ID").argument("<column...>", `Column names, ${COLUMN_LIST_HELP}`).action(async (id, given, _options, cmd) => {
11399
+ analyze.command("input-exclusions").description("Set the columns the analysis leaves out as inputs (a single empty string leaves nothing out)").argument("<id>", "Analysis ID").argument("<column...>", `Column names, ${COLUMN_LIST_HELP}`).action(async (id, given, _options, cmd) => {
10180
11400
  try {
10181
11401
  await patchColumns(
10182
11402
  id,
10183
11403
  given,
10184
11404
  (api, columns) => api.analysis.patchInputExclusions(id, { columns }),
10185
- "Columns left out of the fit",
11405
+ "Columns left out as inputs",
10186
11406
  cmd
10187
11407
  );
10188
11408
  } catch (error) {
@@ -10202,31 +11422,85 @@ Examples:
10202
11422
  handleError(error);
10203
11423
  }
10204
11424
  });
10205
- analyze.command("questions").description("Set the questions the analysis answers, one argument per question").argument("<id>", "Analysis ID").argument("<question...>", "The questions, each quoted as one argument (a single empty string clears them)").action(async (id, given, _options, cmd) => {
11425
+ analyze.command("questions").description("Set the questions the analysis answers, one argument per question").argument("<id>", "Analysis ID").argument("<question...>", "The questions, each quoted as one argument (a single empty string clears them)").action(async (id, given, _options, cmd) => {
11426
+ try {
11427
+ const questions = questionsOf(Array.isArray(given) ? given : [given]) ?? [];
11428
+ await patchAndPrint(
11429
+ id,
11430
+ questions.join(" | "),
11431
+ (api, aid) => api.analysis.patchQuestions(aid, { questions }),
11432
+ "Questions",
11433
+ cmd
11434
+ );
11435
+ } catch (error) {
11436
+ handleError(error);
11437
+ }
11438
+ });
11439
+ analyze.command("segment").description("Set or clear the segmentation column (empty string clears)").argument("<id>", "Analysis ID").argument("<name>", "Column name, matched against the columns of the analysis data (empty string to clear)").action(async (id, name, _options, cmd) => {
11440
+ try {
11441
+ const api = createApiClient();
11442
+ const segment = name === "" ? null : resolveColumnArgument(name, await columnNames(api, id), id);
11443
+ await patchAndPrint(
11444
+ id,
11445
+ name,
11446
+ () => api.analysis.patchSegment(id, { segment }),
11447
+ "Segment",
11448
+ cmd
11449
+ );
11450
+ } catch (error) {
11451
+ handleError(error);
11452
+ }
11453
+ });
11454
+ const intent = analyze.command("intent").description('Your private notes ("What you know and what matters"), read into proposals that apply only when you confirm them');
11455
+ intent.command("notes", { isDefault: true }).description("Show your notes, or set them (an empty text or --clear clears them). Only you can read them; storing them does not read them").argument("<id>", "Analysis ID").argument("[text]", `The notes, in your own words (at most ${MAX_INTENT_LENGTH.toLocaleString("en-US")} characters)`).option("--file <path>", "Read the notes from a file").option("--clear", "Clear the notes").action(async (id, text2, options, cmd) => {
11456
+ try {
11457
+ await notesCommand(id, text2, options, cmd);
11458
+ } catch (error) {
11459
+ handleError(error);
11460
+ }
11461
+ });
11462
+ intent.command("read").description("Read your notes into proposals and print them. Nothing changes until you confirm one").argument("<id>", "Analysis ID").option("--force", "Read them again even when nothing changed since the last reading").option("--refine", "Read them for a refinement of the analysis, where a row focus can be applied").action(async (id, options, cmd) => {
11463
+ try {
11464
+ await readNotesCommand(id, options, cmd);
11465
+ } catch (error) {
11466
+ handleError(error);
11467
+ }
11468
+ });
11469
+ const decisions = [
11470
+ { name: "confirm", state: "CONFIRMED", description: "Use proposals: each is applied to the analysis from the next run. An expectation is checked; --steer lets it steer the model too" },
11471
+ { name: "decline", state: "DECLINED", description: "Do not use proposals; one that was applied is taken back out" },
11472
+ { name: "reset", state: "PROPOSED", description: "Open proposals again, undoing the decision; one that was applied is taken back out" }
11473
+ ];
11474
+ for (const decision of decisions) {
11475
+ const command = intent.command(decision.name).description(decision.description).argument("<id>", "Analysis ID").argument("<proposalId...>", "Proposal ids, as 'analyze intent read' prints them");
11476
+ if (decision.state === "CONFIRMED") {
11477
+ command.option("--steer", "Also let the expectations steer which model is delivered").option("--no-steer", "Check and report the expectations only (the default for a new one)");
11478
+ }
11479
+ command.action(async (id, ids, options, cmd) => {
11480
+ try {
11481
+ await decideCommand(decision.state, id, ids, options, cmd);
11482
+ } catch (error) {
11483
+ handleError(error);
11484
+ }
11485
+ });
11486
+ }
11487
+ analyze.command("expectations").description("Show or set expectations about a target's shape. Each is checked and reported; one written with require: also steers the model").argument("<id>", "Analysis ID").argument("[statements...]", "Statements such as increasing(size_m2), decreasing(price, 1, 20), convex(x), concave(x) or range(0, inf), each with check: (the default) or require: in front; without --target written <target>=<statement>. A window left open is the input's observed range").option("--target <target>", "The target the statements are about; with --clear, the target to clear").option("--clear", "Clear the expectations of the target named, or all of them").action(async (id, statements, options, cmd) => {
11488
+ try {
11489
+ await expectationsCommand(id, statements, options, cmd);
11490
+ } catch (error) {
11491
+ handleError(error);
11492
+ }
11493
+ });
11494
+ analyze.command("charts").description(`Set the charts to add to the report, at most ${MAX_PAIRS} (a single empty string clears them)`).argument("<id>", "Analysis ID").argument("<pair...>", `Each <first>,<second>[,<kind>]: the second column against the first; kind is scatter, groups or counts, or left out for the chart rules to choose. ${PAIR_QUOTING_HELP}`).action(async (id, given, _options, cmd) => {
10206
11495
  try {
10207
- const questions = questionsOf(Array.isArray(given) ? given : [given]) ?? [];
10208
- await patchAndPrint(
10209
- id,
10210
- questions.join(" | "),
10211
- (api, aid) => api.analysis.patchQuestions(aid, { questions }),
10212
- "Questions",
10213
- cmd
10214
- );
11496
+ await chartsCommand(id, given, cmd);
10215
11497
  } catch (error) {
10216
11498
  handleError(error);
10217
11499
  }
10218
11500
  });
10219
- analyze.command("segment").description("Set or clear the segmentation column (empty string clears)").argument("<id>", "Analysis ID").argument("<name>", "Column name, matched against the columns of the analysis data (empty string to clear)").action(async (id, name, _options, cmd) => {
11501
+ analyze.command("focus").description(`Set what matters most to you, as question families, most important first, at most ${MAX_FOCUS} (a single empty string clears them). The report answers these first`).argument("<id>", "Analysis ID").argument("<family...>", "Question families, for example extrapolation or input_importance").addHelpText("after", FOCUS_FAMILIES_HELP).action(async (id, given, _options, cmd) => {
10220
11502
  try {
10221
- const api = createApiClient();
10222
- const segment = name === "" ? null : resolveColumnArgument(name, await columnNames(api, id), id);
10223
- await patchAndPrint(
10224
- id,
10225
- name,
10226
- () => api.analysis.patchSegment(id, { segment }),
10227
- "Segment",
10228
- cmd
10229
- );
11503
+ await focusCommand(id, given, cmd);
10230
11504
  } catch (error) {
10231
11505
  handleError(error);
10232
11506
  }
@@ -10407,7 +11681,7 @@ async function listPublicAnalyses(options, cmd) {
10407
11681
  { key: "projectId", kind: "id" },
10408
11682
  { key: "publishedAt", header: "published", kind: "date" },
10409
11683
  { key: "changedAt", header: "changed", kind: "date" },
10410
- { key: "licenceId", header: "licence" }
11684
+ { key: "licenceId", header: "license" }
10411
11685
  ]
10412
11686
  });
10413
11687
  }
@@ -10494,44 +11768,44 @@ Examples:
10494
11768
  });
10495
11769
  }
10496
11770
 
10497
- // src/commands/licence/index.ts
10498
- import chalk29 from "chalk";
11771
+ // src/commands/license/index.ts
11772
+ import chalk30 from "chalk";
10499
11773
  function getOutputFormat19(cmd) {
10500
11774
  const config = loadConfig();
10501
11775
  const globalOpts = cmd.optsWithGlobals();
10502
11776
  return globalOpts.output ?? config.defaults.output ?? "human";
10503
11777
  }
10504
- var LICENCE_MARKS = [
11778
+ var LICENSE_MARKS = [
10505
11779
  { mark: "C", flag: "commercialUse", meaning: "commercial use" },
10506
11780
  { mark: "D", flag: "derivatives", meaning: "adaptations and forks" },
10507
11781
  { mark: "R", flag: "redistribution", meaning: "redistribution" },
10508
11782
  { mark: "BY", flag: "attributionRequired", meaning: "attribution required" },
10509
11783
  { mark: "SA", flag: "shareAlike", meaning: "share-alike" }
10510
11784
  ];
10511
- function licenceMarks(licence) {
10512
- const marks = LICENCE_MARKS.filter(({ flag }) => licence[flag] === true).map(({ mark }) => mark);
11785
+ function licenseMarks(license) {
11786
+ const marks = LICENSE_MARKS.filter(({ flag }) => license[flag] === true).map(({ mark }) => mark);
10513
11787
  return marks.length > 0 ? marks.join(" ") : null;
10514
11788
  }
10515
11789
  function stateWord(state) {
10516
11790
  return state.toLowerCase();
10517
11791
  }
10518
- async function listLicences(cmd) {
11792
+ async function listLicenses(cmd) {
10519
11793
  const outputFormat = getOutputFormat19(cmd);
10520
11794
  const api = createApiClient();
10521
- const licences = await api.admin.listLicences();
11795
+ const licenses = await api.admin.listLicenses();
10522
11796
  if (outputFormat === "json") {
10523
- format(licences, { format: outputFormat });
11797
+ format(licenses, { format: outputFormat });
10524
11798
  return;
10525
11799
  }
10526
- if (licences.length === 0 && outputFormat === "human") {
10527
- empty("licences");
11800
+ if (licenses.length === 0 && outputFormat === "human") {
11801
+ empty("licenses");
10528
11802
  return;
10529
11803
  }
10530
- format(licences.map((l) => ({
11804
+ format(licenses.map((l) => ({
10531
11805
  licenceId: l.licenceId,
10532
11806
  name: l.name,
10533
11807
  state: stateWord(l.state),
10534
- flags: licenceMarks(l),
11808
+ flags: licenseMarks(l),
10535
11809
  recommended: l.recommended
10536
11810
  })), {
10537
11811
  format: outputFormat,
@@ -10544,42 +11818,42 @@ async function listLicences(cmd) {
10544
11818
  ]
10545
11819
  });
10546
11820
  if (outputFormat === "human") {
10547
- console.error(chalk29.dim(
11821
+ console.error(chalk30.dim(
10548
11822
  `
10549
- Flags: ${LICENCE_MARKS.map(({ mark, meaning }) => `${mark} ${meaning}`).join(", ")}. A deprecated licence stays on the projects that carry it and cannot be chosen.`
11823
+ Flags: ${LICENSE_MARKS.map(({ mark, meaning }) => `${mark} ${meaning}`).join(", ")}. A deprecated license stays on the projects that carry it and cannot be chosen.`
10550
11824
  ));
10551
11825
  }
10552
11826
  }
10553
- async function showLicence(licenceId, cmd) {
11827
+ async function showLicense(licenseId, cmd) {
10554
11828
  const outputFormat = getOutputFormat19(cmd);
10555
11829
  const api = createApiClient();
10556
- let licence;
11830
+ let license;
10557
11831
  try {
10558
- licence = await api.admin.getLicence(licenceId);
11832
+ license = await api.admin.getLicense(licenseId);
10559
11833
  } catch (error) {
10560
11834
  if (error instanceof ApiError && error.status === 404) {
10561
- throw new CliError(`No licence "${licenceId}" in the catalogue.`, {
10562
- hint: `List the licences with 'diafunc licence list'.`
11835
+ throw new CliError(`No license "${licenseId}" in the catalog.`, {
11836
+ hint: `List the licenses with 'diafunc license list'.`
10563
11837
  });
10564
11838
  }
10565
11839
  throw error;
10566
11840
  }
10567
11841
  if (outputFormat !== "human") {
10568
- format(licence, { format: outputFormat });
11842
+ format(license, { format: outputFormat });
10569
11843
  return;
10570
11844
  }
10571
11845
  format({
10572
- licenceId: licence.licenceId,
10573
- name: licence.name,
10574
- state: stateWord(licence.state),
10575
- summary: licence.summary,
10576
- url: licence.url,
10577
- commercialUse: licence.commercialUse,
10578
- derivatives: licence.derivatives,
10579
- redistribution: licence.redistribution,
10580
- attributionRequired: licence.attributionRequired,
10581
- shareAlike: licence.shareAlike,
10582
- recommended: licence.recommended
11846
+ licenceId: license.licenceId,
11847
+ name: license.name,
11848
+ state: stateWord(license.state),
11849
+ summary: license.summary,
11850
+ url: license.url,
11851
+ commercialUse: license.commercialUse,
11852
+ derivatives: license.derivatives,
11853
+ redistribution: license.redistribution,
11854
+ attributionRequired: license.attributionRequired,
11855
+ shareAlike: license.shareAlike,
11856
+ recommended: license.recommended
10583
11857
  }, {
10584
11858
  format: outputFormat,
10585
11859
  columns: [
@@ -10587,7 +11861,7 @@ async function showLicence(licenceId, cmd) {
10587
11861
  { key: "name", header: "Name" },
10588
11862
  { key: "state", header: "State", kind: "state" },
10589
11863
  { key: "summary", header: "Summary" },
10590
- { key: "url", header: "Licence text" },
11864
+ { key: "url", header: "License text" },
10591
11865
  { key: "commercialUse", header: "Commercial use", kind: "boolean" },
10592
11866
  { key: "derivatives", header: "Adaptations and forks", kind: "boolean" },
10593
11867
  { key: "redistribution", header: "Redistribution", kind: "boolean" },
@@ -10597,24 +11871,24 @@ async function showLicence(licenceId, cmd) {
10597
11871
  ]
10598
11872
  });
10599
11873
  }
10600
- function registerLicenceCommands(program) {
10601
- const licence = program.command("licence").description("The licences a public project can be published under (no sign-in needed)").addHelpText("after", `
11874
+ function registerLicenseCommands(program) {
11875
+ const license = hiddenAlias(program.command("license"), "licence").description("The licenses a public project can be published under (no sign-in needed)").addHelpText("after", `
10602
11876
  Examples:
10603
- $ diafunc licence list the licences that can be chosen
10604
- $ diafunc licence show CC-BY-4.0 one licence and what it allows
10605
- $ diafunc project create --visibility PUBLIC --licence CC-BY-4.0
10606
- $ diafunc analyze visibility <id> PUBLIC --licence CC0-1.0
11877
+ $ diafunc license list the licenses that can be chosen
11878
+ $ diafunc license show CC-BY-4.0 one license and what it allows
11879
+ $ diafunc project create --visibility PUBLIC --license CC-BY-4.0
11880
+ $ diafunc analyze visibility <id> PUBLIC --license CC0-1.0
10607
11881
  `);
10608
- licence.command("list").description("List the licence catalogue: the active and the deprecated licences, in catalogue order").action(async (_options, cmd) => {
11882
+ license.command("list").description("List the license catalog: the active and the deprecated licenses, in catalog order").action(async (_options, cmd) => {
10609
11883
  try {
10610
- await listLicences(cmd);
11884
+ await listLicenses(cmd);
10611
11885
  } catch (error) {
10612
11886
  handleError(error);
10613
11887
  }
10614
11888
  });
10615
- licence.command("show").description("Show one licence, in any state, and what it allows").argument("<licenceId>", "Licence ID (CC-BY-4.0, CC0-1.0, diafunc-view-only, ...)").action(async (licenceId, _options, cmd) => {
11889
+ license.command("show").description("Show one license, in any state, and what it allows").argument("<licenseId>", "License ID (CC-BY-4.0, CC0-1.0, diafunc-view-only, ...)").action(async (licenseId, _options, cmd) => {
10616
11890
  try {
10617
- await showLicence(licenceId, cmd);
11891
+ await showLicense(licenseId, cmd);
10618
11892
  } catch (error) {
10619
11893
  handleError(error);
10620
11894
  }
@@ -10622,7 +11896,7 @@ Examples:
10622
11896
  }
10623
11897
 
10624
11898
  // src/commands/data-sources/index.ts
10625
- import chalk30 from "chalk";
11899
+ import chalk31 from "chalk";
10626
11900
  function getOutputFormat20(cmd) {
10627
11901
  const config = loadConfig();
10628
11902
  const globalOpts = cmd.optsWithGlobals();
@@ -10758,7 +12032,7 @@ async function showDashboard(projectId, cmd) {
10758
12032
  return;
10759
12033
  }
10760
12034
  const r = dashboard.rollup;
10761
- let line = chalk30.bold(`DataSources in ${projectId}: `) + `${r.totalSources} total, ${r.scheduledSources} scheduled, ${r.sourcesWithRecentFailure} failing recently`;
12035
+ let line = chalk31.bold(`DataSources in ${projectId}: `) + `${r.totalSources} total, ${r.scheduledSources} scheduled, ${r.sourcesWithRecentFailure} failing recently`;
10762
12036
  if (r.lastActivityAt) line += `, last activity ${r.lastActivityAt}`;
10763
12037
  console.log(line);
10764
12038
  if (dashboard.sources.length === 0) {
@@ -10819,9 +12093,9 @@ async function createForAnalysis(api, options, human) {
10819
12093
  if (human) {
10820
12094
  success(`Added ${source.fileName} to analysis ${analysisId} from data source ${source.dataSourceId ?? ""}`.trimEnd());
10821
12095
  for (const line of planLines(build.plan)) {
10822
- console.log(line.caution ? chalk30.yellow(` ${line.text}`) : chalk30.dim(` ${line.text}`));
12096
+ console.log(line.caution ? chalk31.yellow(` ${line.text}`) : chalk31.dim(` ${line.text}`));
10823
12097
  }
10824
- console.log(chalk30.dim(options.scheduleCron ? ` Refreshes ${humanizeCron(options.scheduleCron)}; each refresh replaces the file and builds the data again.` : " No schedule of its own: refresh it with `data-sources refresh`, or let a trigger fetch it before a run (`analyze triggers create --refresh-first`)."));
12098
+ console.log(chalk31.dim(options.scheduleCron ? ` Refreshes ${humanizeCron(options.scheduleCron)}; each refresh replaces the file and builds the data again.` : " No schedule of its own: refresh it with `data-sources refresh`, or let a trigger fetch it before a run (`analyze triggers create --refresh-first`)."));
10825
12099
  }
10826
12100
  return { source, build };
10827
12101
  }
@@ -10849,8 +12123,8 @@ async function createDataSource(options, cmd) {
10849
12123
  const ds = await api.storage.createDataSource(request);
10850
12124
  if (outputFormat === "human") {
10851
12125
  success(`Created data source ${ds.id}`);
10852
- console.log(chalk30.dim(` Last run: ${ds.lastRunStatus ?? "\u2014"}`));
10853
- if (ds.lastRunError) console.log(chalk30.dim(` Error: ${ds.lastRunError}`));
12126
+ console.log(chalk31.dim(` Last run: ${ds.lastRunStatus ?? "\u2014"}`));
12127
+ if (ds.lastRunError) console.log(chalk31.dim(` Error: ${ds.lastRunError}`));
10854
12128
  } else {
10855
12129
  format(ds, { format: outputFormat });
10856
12130
  }
@@ -10896,7 +12170,7 @@ async function refreshDataSource(id, cmd) {
10896
12170
  const run = await api.storage.refreshDataSource(id);
10897
12171
  if (outputFormat === "human") {
10898
12172
  success(`Refresh queued: run ${run.runId}, status ${run.status}.`);
10899
- if (run.errorMessage) console.log(chalk30.red(` Error: ${run.errorMessage}`));
12173
+ if (run.errorMessage) console.log(chalk31.red(` Error: ${run.errorMessage}`));
10900
12174
  } else {
10901
12175
  format(run, { format: outputFormat });
10902
12176
  }
@@ -11023,7 +12297,7 @@ Examples:
11023
12297
  }
11024
12298
 
11025
12299
  // src/commands/table-exporters/index.ts
11026
- import chalk31 from "chalk";
12300
+ import chalk32 from "chalk";
11027
12301
  function getOutputFormat21(cmd) {
11028
12302
  const config = loadConfig();
11029
12303
  const globalOpts = cmd.optsWithGlobals();
@@ -11054,7 +12328,7 @@ function registerTableExportersCommands(program) {
11054
12328
  format: outputFormat,
11055
12329
  columns: ["id", "name", "format", "extension", "mimeType", "priority", "function", "createdBy"]
11056
12330
  });
11057
- console.log(chalk31.dim(`${list.length} exporter(s)`));
12331
+ console.log(chalk32.dim(`${list.length} exporter(s)`));
11058
12332
  } catch (error) {
11059
12333
  handleError(error);
11060
12334
  }
@@ -11112,8 +12386,8 @@ function registerTableExportersCommands(program) {
11112
12386
  }
11113
12387
 
11114
12388
  // src/commands/skeleton/index.ts
11115
- import chalk32 from "chalk";
11116
- import * as fs12 from "fs";
12389
+ import chalk33 from "chalk";
12390
+ import * as fs13 from "fs";
11117
12391
  function getOutputFormat22(cmd) {
11118
12392
  const config = loadConfig();
11119
12393
  const globalOpts = cmd.optsWithGlobals();
@@ -11125,7 +12399,7 @@ function resolveProjectId2(cmd) {
11125
12399
  const config = loadConfig();
11126
12400
  if (config.defaults.project) return config.defaults.project;
11127
12401
  throw new Error(
11128
- "No project specified. Pass --project <id>, set the global --project flag, or run `diafunc config defaults project <id>`."
12402
+ "No project specified. Pass --project <id>, set the global --project flag, or run `diafunc config set defaults.project <id>`."
11129
12403
  );
11130
12404
  }
11131
12405
  function resolveTemplate(raw) {
@@ -11137,10 +12411,10 @@ function resolveTemplate(raw) {
11137
12411
  if (!file) {
11138
12412
  throw new Error("--template @ requires a filename after the @, e.g. --template @template.txt");
11139
12413
  }
11140
- if (!fs12.existsSync(file)) {
12414
+ if (!fs13.existsSync(file)) {
11141
12415
  throw new Error(`Template file not found: ${file}`);
11142
12416
  }
11143
- return fs12.readFileSync(file, "utf-8").trim();
12417
+ return fs13.readFileSync(file, "utf-8").trim();
11144
12418
  }
11145
12419
  return raw;
11146
12420
  }
@@ -11179,10 +12453,10 @@ async function createSkeleton(options, cmd) {
11179
12453
  const skeleton = await api.storage.createSkeleton(request);
11180
12454
  if (outputFormat === "human") {
11181
12455
  success(`Created skeleton ${skeleton.id}`);
11182
- console.log(chalk32.dim(` name: ${skeleton.name}`));
11183
- console.log(chalk32.dim(` template: ${skeleton.template}`));
11184
- console.log(chalk32.dim(` paramCount: ${skeleton.paramCount}`));
11185
- console.log(chalk32.dim(` weight: ${skeleton.weight}`));
12456
+ console.log(chalk33.dim(` name: ${skeleton.name}`));
12457
+ console.log(chalk33.dim(` template: ${skeleton.template}`));
12458
+ console.log(chalk33.dim(` paramCount: ${skeleton.paramCount}`));
12459
+ console.log(chalk33.dim(` weight: ${skeleton.weight}`));
11186
12460
  } else {
11187
12461
  format(skeleton, { format: outputFormat });
11188
12462
  }
@@ -11221,10 +12495,10 @@ async function updateSkeleton(id, options, cmd) {
11221
12495
  const skeleton = await api.storage.updateSkeleton(id, request);
11222
12496
  if (outputFormat === "human") {
11223
12497
  success(`Updated skeleton ${skeleton.id}`);
11224
- console.log(chalk32.dim(` name: ${skeleton.name}`));
11225
- console.log(chalk32.dim(` template: ${skeleton.template}`));
11226
- console.log(chalk32.dim(` paramCount: ${skeleton.paramCount}`));
11227
- console.log(chalk32.dim(` weight: ${skeleton.weight}`));
12498
+ console.log(chalk33.dim(` name: ${skeleton.name}`));
12499
+ console.log(chalk33.dim(` template: ${skeleton.template}`));
12500
+ console.log(chalk33.dim(` paramCount: ${skeleton.paramCount}`));
12501
+ console.log(chalk33.dim(` weight: ${skeleton.weight}`));
11228
12502
  } else {
11229
12503
  format(skeleton, { format: outputFormat });
11230
12504
  }
@@ -11241,7 +12515,7 @@ Examples:
11241
12515
  $ diafunc skeleton create --project <id> --name linear --template 'a*x+b'
11242
12516
  `);
11243
12517
  ;
11244
- skeleton.command("create").description("Create a skeleton. Parse errors from the engine are surfaced as stderr.").requiredOption("--name <name>", "Display name").requiredOption(
12518
+ skeleton.command("create").description("Create a skeleton. A template the platform cannot parse is reported on stderr.").requiredOption("--name <name>", "Display name").requiredOption(
11245
12519
  "--template <expr>",
11246
12520
  'Skeleton template expression (e.g. "?*x+?"). Use "@file.txt" to read from a file; "@@\u2026" escapes a literal leading @.'
11247
12521
  ).option("--weight <number>", "Sampling weight (positive; server default applies if omitted)").action(async (options, cmd) => {
@@ -11549,7 +12823,7 @@ function registerCompletionCommand(program) {
11549
12823
  }
11550
12824
 
11551
12825
  // src/commands/whoami/index.ts
11552
- import chalk33 from "chalk";
12826
+ import chalk34 from "chalk";
11553
12827
  function registerWhoamiCommand(program) {
11554
12828
  program.command("whoami").description("Show the currently authenticated user").action(async (_options, cmd) => {
11555
12829
  try {
@@ -11559,8 +12833,8 @@ function registerWhoamiCommand(program) {
11559
12833
  const api = createApiClient();
11560
12834
  const user = await api.admin.getMyUser();
11561
12835
  if (outputFormat === "human") {
11562
- console.log(chalk33.bold(user.name) + chalk33.dim(` <${user.email}>`));
11563
- console.log(chalk33.dim(` Role: ${user.role} \xB7 Remaining credits: ${user.remainingCredits} \xB7 Profile: ${config.currentProfile}`));
12836
+ console.log(chalk34.bold(user.name) + chalk34.dim(` <${user.email}>`));
12837
+ console.log(chalk34.dim(` Role: ${user.role} \xB7 Remaining credits: ${user.remainingCredits} \xB7 Profile: ${config.currentProfile}`));
11564
12838
  } else {
11565
12839
  format(user, { format: outputFormat });
11566
12840
  }
@@ -11571,7 +12845,7 @@ function registerWhoamiCommand(program) {
11571
12845
  }
11572
12846
 
11573
12847
  // src/commands/utilization/index.ts
11574
- import chalk34 from "chalk";
12848
+ import chalk35 from "chalk";
11575
12849
  function getOutputFormat23(cmd) {
11576
12850
  const config = loadConfig();
11577
12851
  const globalOpts = cmd.optsWithGlobals();
@@ -11588,19 +12862,19 @@ function windowLabel(u) {
11588
12862
  }
11589
12863
  function printUtilizationHuman(u, label) {
11590
12864
  const when2 = windowLabel(u);
11591
- console.log(label ? chalk34.bold(label) + " " + chalk34.dim(when2) : chalk34.bold(when2));
12865
+ console.log(label ? chalk35.bold(label) + " " + chalk35.dim(when2) : chalk35.bold(when2));
11592
12866
  if (u.types.length === 0) {
11593
- console.log(chalk34.dim(" (no usage)"));
12867
+ console.log(chalk35.dim(" (no usage)"));
11594
12868
  return;
11595
12869
  }
11596
12870
  const types = [...u.types].sort((a, b) => b.credits - a.credits);
11597
12871
  const width = Math.max(...types.map((t) => t.type.length));
11598
12872
  for (const t of types) {
11599
- const line = ` ${t.type.padEnd(width)} ${formatNumber(t.quantity).padStart(12)} ${chalk34.dim("credits")} ${t.credits.toFixed(2).padStart(10)}`;
11600
- console.log(t.credits === 0 ? chalk34.dim(line) : line);
12873
+ const line = ` ${t.type.padEnd(width)} ${formatNumber(t.quantity).padStart(12)} ${chalk35.dim("credits")} ${t.credits.toFixed(2).padStart(10)}`;
12874
+ console.log(t.credits === 0 ? chalk35.dim(line) : line);
11601
12875
  }
11602
12876
  const total = u.totalCredits ?? u.types.reduce((s, t) => s + t.credits, 0);
11603
- console.log(chalk34.bold(` ${"Total".padEnd(width)} ${" ".repeat(12)} ${chalk34.dim("credits")} ${total.toFixed(2).padStart(10)}`));
12877
+ console.log(chalk35.bold(` ${"Total".padEnd(width)} ${" ".repeat(12)} ${chalk35.dim("credits")} ${total.toFixed(2).padStart(10)}`));
11604
12878
  }
11605
12879
  function formatDailyHistory(history) {
11606
12880
  const spentOn = (u) => u.dailyCredits ?? u.types.reduce((sum, t) => sum + (t.dailyCredits ?? 0), 0);
@@ -11617,14 +12891,14 @@ function formatDailyHistory(history) {
11617
12891
  for (const u of history) {
11618
12892
  const spent = spentOn(u);
11619
12893
  total += spent;
11620
- const line = `${windowLabel(u).padEnd(width)} ${amount(spent)} ${chalk34.dim("credits")}`;
11621
- lines.push(spent > 0 ? chalk34.bold(line) : chalk34.dim(line));
12894
+ const line = `${windowLabel(u).padEnd(width)} ${amount(spent)} ${chalk35.dim("credits")}`;
12895
+ lines.push(spent > 0 ? chalk35.bold(line) : chalk35.dim(line));
11622
12896
  for (const t of costly(u)) {
11623
12897
  lines.push(` ${t.type.padEnd(width - 2)} ${amount(t.dailyCredits ?? 0)}`);
11624
12898
  }
11625
12899
  }
11626
12900
  lines.push("");
11627
- lines.push(chalk34.bold(`${totalLabel.padEnd(width)} ${amount(total)} ${chalk34.dim("credits")}`));
12901
+ lines.push(chalk35.bold(`${totalLabel.padEnd(width)} ${amount(total)} ${chalk35.dim("credits")}`));
11628
12902
  return lines;
11629
12903
  }
11630
12904
  function registerUtilizationCommand(program) {
@@ -11780,7 +13054,7 @@ Examples:
11780
13054
  }
11781
13055
 
11782
13056
  // src/commands/invoice/index.ts
11783
- import * as fs13 from "fs";
13057
+ import * as fs14 from "fs";
11784
13058
  function getOutputFormat26(cmd) {
11785
13059
  const config = loadConfig();
11786
13060
  const globalOpts = cmd.optsWithGlobals();
@@ -11818,7 +13092,7 @@ Examples:
11818
13092
  const response = await api.admin.downloadInvoice(invoiceNumber, fileName);
11819
13093
  const buffer = Buffer.from(await response.arrayBuffer());
11820
13094
  const outPath = options.out ?? fileName;
11821
- fs13.writeFileSync(outPath, buffer);
13095
+ fs14.writeFileSync(outPath, buffer);
11822
13096
  success(`Invoice saved to ${outPath}`);
11823
13097
  } catch (error) {
11824
13098
  handleError(error);
@@ -11827,8 +13101,8 @@ Examples:
11827
13101
  }
11828
13102
 
11829
13103
  // src/commands/shell/index.ts
11830
- import chalk35 from "chalk";
11831
- import * as fs14 from "fs";
13104
+ import chalk36 from "chalk";
13105
+ import * as fs15 from "fs";
11832
13106
  import * as os4 from "os";
11833
13107
  import * as path10 from "path";
11834
13108
  import { spawn as spawn3 } from "child_process";
@@ -11844,15 +13118,15 @@ function extensionFor2(language) {
11844
13118
  }
11845
13119
  async function openInEditor(initial, ext) {
11846
13120
  const tmpFile = path10.join(os4.tmpdir(), `diafunc-shell-${randomUUID4()}.${ext}`);
11847
- fs14.writeFileSync(tmpFile, initial);
13121
+ fs15.writeFileSync(tmpFile, initial);
11848
13122
  const editor = process.env.VISUAL ?? process.env.EDITOR ?? "vi";
11849
13123
  await new Promise((resolve2, reject) => {
11850
13124
  const child = spawn3(editor, [tmpFile], { stdio: "inherit" });
11851
13125
  child.on("exit", (code) => code === 0 ? resolve2() : reject(new Error(`Editor exited with ${code}`)));
11852
13126
  child.on("error", reject);
11853
13127
  });
11854
- const content = fs14.readFileSync(tmpFile, "utf-8");
11855
- fs14.unlinkSync(tmpFile);
13128
+ const content = fs15.readFileSync(tmpFile, "utf-8");
13129
+ fs15.unlinkSync(tmpFile);
11856
13130
  return content;
11857
13131
  }
11858
13132
  function utcNowParts() {
@@ -11893,21 +13167,21 @@ async function evaluate(api, fnRef, language, sourceCode) {
11893
13167
  }, false);
11894
13168
  if (result.outputs?.length) {
11895
13169
  for (const out of result.outputs) {
11896
- console.log(chalk35.dim(` [${out.type}]`) + " " + out.output);
13170
+ console.log(chalk36.dim(` [${out.type}]`) + " " + out.output);
11897
13171
  }
11898
13172
  }
11899
13173
  if (result.successful) {
11900
13174
  if (result.result) {
11901
- console.log(chalk35.green("=>") + " " + resultText(result.result, result.resultEncoding));
13175
+ console.log(chalk36.green("=>") + " " + resultText(result.result, result.resultEncoding));
11902
13176
  } else {
11903
- console.log(chalk35.dim("=> (no value)"));
13177
+ console.log(chalk36.dim("=> (no value)"));
11904
13178
  }
11905
13179
  const duration = result.completed - result.started;
11906
- console.log(chalk35.dim(` [${duration}ms \xB7 ${evaluationId}]`));
13180
+ console.log(chalk36.dim(` [${duration}ms \xB7 ${evaluationId}]`));
11907
13181
  } else {
11908
- console.log(chalk35.red("error: ") + result.error);
13182
+ console.log(chalk36.red("error: ") + result.error);
11909
13183
  if (result.lineNumber > 0) {
11910
- console.log(chalk35.dim(` at line ${result.lineNumber}, col ${result.columnNumber}`));
13184
+ console.log(chalk36.dim(` at line ${result.lineNumber}, col ${result.columnNumber}`));
11911
13185
  }
11912
13186
  }
11913
13187
  }
@@ -11928,19 +13202,19 @@ function registerShellCommand(program) {
11928
13202
  });
11929
13203
  const api = createApiClient();
11930
13204
  const { input: promptInput } = await import("@inquirer/prompts");
11931
- const { getUpdateNotice } = await import("./update-check-7CVBVYDK.js");
13205
+ const { getUpdateNotice } = await import("./update-check-BH7IMKZN.js");
11932
13206
  const resolvedLanguage = await resolveLanguage(api, fnRef.projectId, options.language);
11933
- console.log(chalk35.bold("Diafunc shell") + chalk35.dim(` \xB7 function ${fnRef.entityId} \xB7 ${resolvedLanguage}`));
11934
- console.log(chalk35.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
11935
- console.log(chalk35.dim("Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit"));
13207
+ console.log(chalk36.bold("Diafunc shell") + chalk36.dim(` \xB7 function ${fnRef.entityId} \xB7 ${resolvedLanguage}`));
13208
+ console.log(chalk36.dim(`Endpoint: ${config.profiles[config.currentProfile]?.endpoint}`));
13209
+ console.log(chalk36.dim("Commands: /edit (multi-line in $EDITOR), /lang <name>, /file <path>, /help, /quit"));
11936
13210
  const notice = await getUpdateNotice();
11937
- if (notice) console.log(chalk35.dim(notice));
13211
+ if (notice) console.log(chalk36.dim(notice));
11938
13212
  console.log();
11939
13213
  let language = resolvedLanguage;
11940
13214
  for (; ; ) {
11941
13215
  let line;
11942
13216
  try {
11943
- line = await promptInput({ message: chalk35.cyan.bold(`${language} >`) });
13217
+ line = await promptInput({ message: chalk36.cyan.bold(`${language} >`) });
11944
13218
  } catch {
11945
13219
  console.log();
11946
13220
  return;
@@ -11958,54 +13232,54 @@ function registerShellCommand(program) {
11958
13232
  case "help":
11959
13233
  case "h":
11960
13234
  case "?":
11961
- console.log(chalk35.dim(" /edit open $EDITOR for multi-line code"));
11962
- console.log(chalk35.dim(" /file <path> evaluate the contents of a file"));
11963
- console.log(chalk35.dim(" /lang <name> switch language (Java, JavaScript, Kotlin, Python, Scala)"));
11964
- console.log(chalk35.dim(" /quit exit the shell"));
13235
+ console.log(chalk36.dim(" /edit open $EDITOR for multi-line code"));
13236
+ console.log(chalk36.dim(" /file <path> evaluate the contents of a file"));
13237
+ console.log(chalk36.dim(" /lang <name> switch language (Java, JavaScript, Kotlin, Python, Scala)"));
13238
+ console.log(chalk36.dim(" /quit exit the shell"));
11965
13239
  continue;
11966
13240
  case "lang":
11967
13241
  if (arg) language = arg;
11968
- console.log(chalk35.dim(`Language: ${language}`));
13242
+ console.log(chalk36.dim(`Language: ${language}`));
11969
13243
  continue;
11970
13244
  case "edit": {
11971
13245
  const sourceCode = await openInEditor("", extensionFor2(language));
11972
13246
  if (!sourceCode.trim()) {
11973
- console.log(chalk35.dim("(empty; not evaluated)"));
13247
+ console.log(chalk36.dim("(empty; not evaluated)"));
11974
13248
  continue;
11975
13249
  }
11976
13250
  try {
11977
13251
  await evaluate(api, fnRef, language, sourceCode);
11978
13252
  } catch (e) {
11979
- console.error(chalk35.red(e.message));
13253
+ console.error(chalk36.red(e.message));
11980
13254
  }
11981
13255
  continue;
11982
13256
  }
11983
13257
  case "file": {
11984
13258
  if (!arg) {
11985
- console.log(chalk35.dim("usage: /file <path>"));
13259
+ console.log(chalk36.dim("usage: /file <path>"));
11986
13260
  continue;
11987
13261
  }
11988
- if (!fs14.existsSync(arg)) {
11989
- console.log(chalk35.red(`file not found: ${arg}`));
13262
+ if (!fs15.existsSync(arg)) {
13263
+ console.log(chalk36.red(`file not found: ${arg}`));
11990
13264
  continue;
11991
13265
  }
11992
- const sourceCode = fs14.readFileSync(arg, "utf-8");
13266
+ const sourceCode = fs15.readFileSync(arg, "utf-8");
11993
13267
  try {
11994
13268
  await evaluate(api, fnRef, language, sourceCode);
11995
13269
  } catch (e) {
11996
- console.error(chalk35.red(e.message));
13270
+ console.error(chalk36.red(e.message));
11997
13271
  }
11998
13272
  continue;
11999
13273
  }
12000
13274
  default:
12001
- console.log(chalk35.dim(`Unknown command: /${cmd2}. Try /help.`));
13275
+ console.log(chalk36.dim(`Unknown command: /${cmd2}. Try /help.`));
12002
13276
  continue;
12003
13277
  }
12004
13278
  }
12005
13279
  try {
12006
13280
  await evaluate(api, fnRef, language, trimmed);
12007
13281
  } catch (e) {
12008
- console.error(chalk35.red(e.message));
13282
+ console.error(chalk36.red(e.message));
12009
13283
  }
12010
13284
  }
12011
13285
  } catch (error) {
@@ -12015,19 +13289,19 @@ function registerShellCommand(program) {
12015
13289
  }
12016
13290
 
12017
13291
  // src/commands/update/index.ts
12018
- import chalk36 from "chalk";
13292
+ import chalk37 from "chalk";
12019
13293
  import * as path11 from "path";
12020
13294
  import { spawn as spawn4 } from "child_process";
12021
13295
 
12022
13296
  // src/util/install-method.ts
12023
- import * as fs15 from "fs";
13297
+ import * as fs16 from "fs";
12024
13298
  function detectInstall() {
12025
13299
  const exec = process.execPath;
12026
13300
  const exe = exec.replace(/\\/g, "/").toLowerCase();
12027
13301
  const isNode = exe.endsWith("/node") || exe.endsWith("/node.exe");
12028
13302
  return {
12029
13303
  method: isNode ? "npm" : "binary",
12030
- binaryPath: isNode ? exec : fs15.realpathSync(exec)
13304
+ binaryPath: isNode ? exec : fs16.realpathSync(exec)
12031
13305
  };
12032
13306
  }
12033
13307
 
@@ -12061,14 +13335,14 @@ function registerUpdateCommand(program) {
12061
13335
  const install = detectInstall();
12062
13336
  const latest = await fetchLatestVersion();
12063
13337
  if (latest === package_default.version) {
12064
- console.log(chalk36.dim(`diafunc is already at the latest version (${package_default.version}).`));
13338
+ console.log(chalk37.dim(`diafunc is already at the latest version (${package_default.version}).`));
12065
13339
  return;
12066
13340
  }
12067
- console.log(chalk36.dim(`Current: ${package_default.version} \u2192 Available: ${latest}`));
13341
+ console.log(chalk37.dim(`Current: ${package_default.version} \u2192 Available: ${latest}`));
12068
13342
  if (install.method === "npm") {
12069
13343
  console.log();
12070
13344
  console.log("Installed via npm. Upgrade with:");
12071
- console.log(chalk36.bold(` npm install -g @diafunc/cli@${latest}`));
13345
+ console.log(chalk37.bold(` npm install -g @diafunc/cli@${latest}`));
12072
13346
  return;
12073
13347
  }
12074
13348
  const installDir = path11.dirname(install.binaryPath);
@@ -12082,9 +13356,9 @@ function registerUpdateCommand(program) {
12082
13356
  }
12083
13357
 
12084
13358
  // src/commands/uninstall/index.ts
12085
- import chalk37 from "chalk";
13359
+ import chalk38 from "chalk";
12086
13360
  import { spawn as spawn5 } from "child_process";
12087
- import * as fs16 from "fs";
13361
+ import * as fs17 from "fs";
12088
13362
  import * as os5 from "os";
12089
13363
  import * as path12 from "path";
12090
13364
  function registerUninstallCommand(program) {
@@ -12094,11 +13368,11 @@ function registerUninstallCommand(program) {
12094
13368
  const configDir = path12.join(os5.homedir(), ".diafunc");
12095
13369
  if (install.method === "npm") {
12096
13370
  console.log("Installed via npm. Remove with:");
12097
- console.log(chalk37.bold(" npm uninstall -g @diafunc/cli"));
12098
- if (fs16.existsSync(configDir)) {
13371
+ console.log(chalk38.bold(" npm uninstall -g @diafunc/cli"));
13372
+ if (fs17.existsSync(configDir)) {
12099
13373
  console.log();
12100
13374
  console.log(`Config and credentials live at ${configDir}. Remove them manually with:`);
12101
- console.log(chalk37.bold(` rm -rf ${configDir}`));
13375
+ console.log(chalk38.bold(` rm -rf ${configDir}`));
12102
13376
  }
12103
13377
  return;
12104
13378
  }
@@ -12108,19 +13382,19 @@ function registerUninstallCommand(program) {
12108
13382
  default: false
12109
13383
  });
12110
13384
  if (!removeBinary) {
12111
- console.log(chalk37.dim("Aborted."));
13385
+ console.log(chalk38.dim("Aborted."));
12112
13386
  return;
12113
13387
  }
12114
13388
  let removeConfig = options.purge ?? false;
12115
- if (!options.purge && !options.yes && fs16.existsSync(configDir)) {
13389
+ if (!options.purge && !options.yes && fs17.existsSync(configDir)) {
12116
13390
  removeConfig = await confirm({
12117
13391
  message: `Also remove ${configDir} (config + credentials)?`,
12118
13392
  default: false
12119
13393
  });
12120
13394
  }
12121
- if (removeConfig && fs16.existsSync(configDir)) {
12122
- fs16.rmSync(configDir, { recursive: true, force: true });
12123
- console.log(chalk37.dim(`Removed ${configDir}`));
13395
+ if (removeConfig && fs17.existsSync(configDir)) {
13396
+ fs17.rmSync(configDir, { recursive: true, force: true });
13397
+ console.log(chalk38.dim(`Removed ${configDir}`));
12124
13398
  }
12125
13399
  if (process.platform === "win32") {
12126
13400
  const cmd = `timeout /t 2 /nobreak >nul & del /f /q "${install.binaryPath}"`;
@@ -12130,13 +13404,13 @@ function registerUninstallCommand(program) {
12130
13404
  windowsHide: true
12131
13405
  });
12132
13406
  child.unref();
12133
- console.log(chalk37.dim(`Removing ${install.binaryPath} on exit...`));
13407
+ console.log(chalk38.dim(`Removing ${install.binaryPath} on exit...`));
12134
13408
  console.log();
12135
13409
  console.log("diafunc uninstalled.");
12136
13410
  return;
12137
13411
  }
12138
- fs16.rmSync(install.binaryPath, { force: true });
12139
- console.log(chalk37.dim(`Removed ${install.binaryPath}`));
13412
+ fs17.rmSync(install.binaryPath, { force: true });
13413
+ console.log(chalk38.dim(`Removed ${install.binaryPath}`));
12140
13414
  console.log();
12141
13415
  console.log("diafunc uninstalled.");
12142
13416
  } catch (error) {
@@ -12146,9 +13420,9 @@ function registerUninstallCommand(program) {
12146
13420
  }
12147
13421
 
12148
13422
  // src/prompting/command.ts
12149
- import { Command } from "commander";
12150
- var commanderOriginal = Command.prototype;
12151
- var DiafuncCommand = class _DiafuncCommand extends Command {
13423
+ import { Command as Command2 } from "commander";
13424
+ var commanderOriginal = Command2.prototype;
13425
+ var DiafuncCommand = class _DiafuncCommand extends Command2 {
12152
13426
  /** Gaps recorded during the current parse, in the order commander found them. */
12153
13427
  pendingInputs = [];
12154
13428
  /** Set on the program only; every command reads it from there. */
@@ -12200,210 +13474,11 @@ var DiafuncCommand = class _DiafuncCommand extends Command {
12200
13474
  };
12201
13475
 
12202
13476
  // src/prompting/fill.ts
12203
- import chalk39 from "chalk";
12204
-
12205
- // src/prompting/resolvers.ts
12206
- var PROJECT_ROLES = ["OWNER", "ADMIN", "DEVELOPER", "GUEST"];
12207
- var TRIGGER_TYPES = ["SCHEDULE", "EVENT", "LINK", "MANUAL"];
12208
- var ANALYSIS_TRIGGER_KINDS = ["ONCE", "CRON"];
12209
- var VISIBILITIES = ["PRIVATE", "PUBLIC"];
12210
- var SHELLS = ["bash", "zsh", "fish"];
12211
- var CONFIG_KEYS = ["defaults.project", "defaults.branch", "defaults.output"];
12212
- var ENTITY_TYPE_BY_GROUP = {
12213
- table: "table",
12214
- function: "function",
12215
- trigger: "function",
12216
- schedule: "function"
12217
- };
12218
- var TEXT = { kind: "text" };
12219
- var TEXT_OR_EMPTY = { kind: "text", allowEmpty: true };
12220
- var POSITIVE = { kind: "number", min: 0, integer: false, exclusive: true };
12221
- var INDEX = { kind: "number", min: 0, integer: true };
12222
- var BY_COMMAND = {
12223
- "analyze segment": { "<name>": { kind: "analysisColumns", multiple: false, allowEmpty: true } },
12224
- "analyze targets": { "<column>": { kind: "analysisColumns", multiple: true, allowEmpty: false } },
12225
- "analyze input-exclusions": { "<column>": { kind: "analysisColumns", multiple: true, allowEmpty: true } },
12226
- "analyze confirmed-inputs": { "<column>": { kind: "analysisColumns", multiple: true, allowEmpty: true } },
12227
- "analyze questions": { "<question>": TEXT_OR_EMPTY },
12228
- "analyze description": { "<text>": TEXT_OR_EMPTY },
12229
- "analyze introduction": { "<markdown>": TEXT_OR_EMPTY },
12230
- // Not the analysis picker: that one offers the reader's own analyses, and this command needs no account.
12231
- "public show": { "<analysisId>": TEXT },
12232
- "analyze presets save": { "--targets": TEXT, "--hours": POSITIVE, "--budget": POSITIVE },
12233
- "branch merge": {
12234
- "--source": { kind: "entity", form: "ref" },
12235
- "--target": { kind: "project", withBranch: true }
12236
- },
12237
- "branch create": { "<branchName>": TEXT },
12238
- "branch delete": { "<branchName>": { kind: "projectBranch", projectFrom: "projectId" } },
12239
- "admin backup restore-project": { "<projectBranch>": { kind: "projectBranch", projectFrom: "projectId" } },
12240
- "data-sources create": {
12241
- "--project-id": { kind: "project", withBranch: false },
12242
- "--project-branch": { kind: "projectBranch", projectFrom: "projectId" },
12243
- "--target-entity-id": { kind: "entity", form: "id", contentType: "table", projectFrom: "projectId" },
12244
- "--target-entity-branch": { kind: "text", defaultValue: "main" },
12245
- "--type": { kind: "connectorType" }
12246
- },
12247
- "table-exporters create": {
12248
- "--function-project": { kind: "project", withBranch: false },
12249
- "--function-entity": { kind: "entity", form: "id", contentType: "function", projectFrom: "functionProject" },
12250
- "--format": TEXT
12251
- },
12252
- "table exports get": { "--ref": { kind: "entity", form: "ref", contentType: "table" } },
12253
- "table export": { "<format>": { kind: "exportFormat" } },
12254
- "entity export": { "<entityIds>": { kind: "entity", form: "id", projectFrom: "project", multiple: true } },
12255
- "notebook export": {
12256
- "<notebookIds>": { kind: "entity", form: "id", contentType: "notebook", projectFrom: "project", multiple: true }
12257
- },
12258
- "entity tags set": { "<tags>": TEXT_OR_EMPTY },
12259
- "project tags set": { "<tags>": TEXT_OR_EMPTY },
12260
- "admin curated-tags create": { "--display-name": TEXT },
12261
- "link delete": { "<linkId>": { kind: "link" } },
12262
- "link create": { "<linkId>": TEXT },
12263
- "config profile use": { "<name>": { kind: "profile" } },
12264
- "config profile remove": { "<name>": { kind: "profile" } },
12265
- "config get": { "<key>": { kind: "choice", choices: CONFIG_KEYS } },
12266
- "config set": { "<key>": { kind: "choice", choices: CONFIG_KEYS } },
12267
- "project members invite": { "<userId>": TEXT, "<role>": { kind: "choice", choices: PROJECT_ROLES } },
12268
- "project members join": { "<userId>": TEXT },
12269
- "trigger create": { "--type": { kind: "choice", choices: TRIGGER_TYPES } },
12270
- "analyze triggers create": { "--kind": { kind: "choice", choices: ANALYSIS_TRIGGER_KINDS } },
12271
- "function outputs": { "<evaluationId>": TEXT },
12272
- "team create": { "--seats": { kind: "number", min: 1, integer: true } },
12273
- "team seats preview": { "<count>": { kind: "number", min: 1, integer: true } },
12274
- "team seats set": { "<count>": { kind: "number", min: 1, integer: true } }
12275
- };
12276
- var BY_NAME = {
12277
- projectId: { kind: "project", withBranch: false },
12278
- projectRef: { kind: "project", withBranch: true },
12279
- project: { kind: "project", withBranch: true },
12280
- teamId: { kind: "team" },
12281
- invitationId: { kind: "teamInvitation" },
12282
- analysisId: { kind: "analysis" },
12283
- licenceId: { kind: "licence" },
12284
- sessionId: { kind: "chatSession" },
12285
- tokenId: { kind: "apiToken" },
12286
- resource: { kind: "tokenResource" },
12287
- scopes: { kind: "choices", choices: VALID_SCOPES },
12288
- evaluationId: { kind: "evaluation" },
12289
- eventId: { kind: "event" },
12290
- occurrenceId: { kind: "occurrence" },
12291
- exportId: { kind: "tableExport" },
12292
- invoiceNumber: { kind: "invoice" },
12293
- fileName: { kind: "invoiceDocument" },
12294
- shell: { kind: "choice", choices: SHELLS },
12295
- vis: { kind: "choice", choices: VISIBILITIES },
12296
- kind: { kind: "choice", choices: ANALYSIS_TRIGGER_KINDS },
12297
- date: { kind: "date" },
12298
- file: { kind: "file" },
12299
- email: { kind: "text", email: true },
12300
- index: INDEX,
12301
- row: INDEX,
12302
- col: INDEX,
12303
- count: INDEX,
12304
- version: { kind: "number", min: 1, integer: true },
12305
- hours: POSITIVE,
12306
- credits: POSITIVE,
12307
- seats: { kind: "number", min: 1, integer: true },
12308
- value: TEXT_OR_EMPTY,
12309
- // Free text: names, messages and ids the reader is creating rather than choosing.
12310
- name: TEXT,
12311
- tag: TEXT,
12312
- tags: TEXT,
12313
- newId: TEXT,
12314
- message: TEXT,
12315
- query: TEXT,
12316
- title: TEXT,
12317
- token: TEXT,
12318
- subscriptionToken: TEXT,
12319
- forkProjectId: TEXT,
12320
- targetBranch: TEXT,
12321
- bucketName: TEXT,
12322
- objectName: TEXT,
12323
- template: TEXT,
12324
- plan: TEXT,
12325
- schedule: TEXT,
12326
- consumerType: TEXT,
12327
- consumerId: TEXT,
12328
- format: TEXT,
12329
- key: TEXT
12330
- };
12331
- function tokenOf(input) {
12332
- return input.kind === "option" ? input.flag ?? `--${input.name}` : `<${input.name}>`;
12333
- }
12334
- function specFor(path13, input) {
12335
- const exact = BY_COMMAND[path13]?.[tokenOf(input)];
12336
- if (exact) return exact;
12337
- const group = path13.split(" ")[0];
12338
- const sub = path13.split(" ").slice(0, 2).join(" ");
12339
- switch (input.name) {
12340
- case "ref":
12341
- case "sourceRef":
12342
- case "targetRef":
12343
- return { kind: "entity", form: "ref", contentType: ENTITY_TYPE_BY_GROUP[group] };
12344
- case "userId":
12345
- return group === "team" ? { kind: "teamMember" } : { kind: "projectMember" };
12346
- case "id":
12347
- if (sub === "analyze presets") return { kind: "preset" };
12348
- if (group === "analyze") return { kind: "analysis" };
12349
- if (group === "data-sources") return { kind: "dataSource" };
12350
- if (group === "skeleton") return { kind: "skeleton" };
12351
- if (group === "table-exporters") return { kind: "tableExporter" };
12352
- if (group === "status") return { kind: "statusComponent" };
12353
- return null;
12354
- case "runId":
12355
- if (group === "analyze") return { kind: "analysisRun" };
12356
- if (group === "data-sources") return { kind: "dataSourceRun" };
12357
- return null;
12358
- case "triggerId":
12359
- if (group === "analyze") return { kind: "analysisTrigger" };
12360
- if (group === "trigger") return { kind: "functionTrigger" };
12361
- return null;
12362
- case "role":
12363
- return { kind: "choice", choices: PROJECT_ROLES };
12364
- case "type":
12365
- return null;
12366
- default:
12367
- return BY_NAME[input.name] ?? null;
12368
- }
12369
- }
12370
- function dependencies(spec) {
12371
- switch (spec.kind) {
12372
- case "teamMember":
12373
- case "teamInvitation":
12374
- return ["teamId"];
12375
- case "projectMember":
12376
- return ["projectId"];
12377
- case "analysisColumns":
12378
- return ["id"];
12379
- case "evaluation":
12380
- return ["ref", "date"];
12381
- case "functionTrigger":
12382
- case "event":
12383
- case "tableExport":
12384
- return ["ref"];
12385
- case "occurrence":
12386
- return ["ref", "eventId"];
12387
- case "link":
12388
- return ["sourceRef"];
12389
- case "tokenResource":
12390
- return ["resourceType"];
12391
- case "dataSourceRun":
12392
- return ["id"];
12393
- case "invoiceDocument":
12394
- return ["invoiceNumber"];
12395
- case "projectBranch":
12396
- return [spec.projectFrom];
12397
- case "entity":
12398
- return spec.projectFrom ? [spec.projectFrom] : [];
12399
- default:
12400
- return [];
12401
- }
12402
- }
13477
+ import chalk40 from "chalk";
12403
13478
 
12404
13479
  // src/prompting/pickers.ts
12405
- import * as fs17 from "fs";
12406
- import chalk38 from "chalk";
13480
+ import * as fs18 from "fs";
13481
+ import chalk39 from "chalk";
12407
13482
  var SEARCH_THRESHOLD = 10;
12408
13483
  var TYPE_IT = "\0type-it";
12409
13484
  async function askFor(spec, input, ctx) {
@@ -12491,7 +13566,7 @@ async function askFor(spec, input, ctx) {
12491
13566
  const invoices = await ctx.api().admin.getInvoices();
12492
13567
  for (const i of invoices) ctx.prefill.set(`invoiceKind:${i.invoiceNumber}`, i.kind ?? "INVOICE");
12493
13568
  return invoices.map((i) => ({
12494
- label: `#${i.invoiceNumber} ${i.periodFrom ?? ""}\u2013${i.periodTo ?? ""}`,
13569
+ label: `#${i.invoiceNumber} ${i.periodFrom ?? ""} to ${i.periodTo ?? ""}`,
12495
13570
  value: String(i.invoiceNumber),
12496
13571
  hint: `${i.status ?? ""} \xB7 ${i.total ?? ""} ${i.currency ?? ""}`.trim()
12497
13572
  }));
@@ -12525,8 +13600,8 @@ async function askFor(spec, input, ctx) {
12525
13600
  return listed(ctx, "profiles", messageFor(input, "Profile"), async () => Object.keys(loadConfig().profiles).map((p) => ({ label: p, value: p })));
12526
13601
  case "statusComponent":
12527
13602
  return listed(ctx, "components", messageFor(input, "Component"), async () => (await createStatusService().getComponents()).map((c) => ({ label: c.id, value: c.id, hint: `${c.state} \xB7 ${c.domainId}` })));
12528
- case "licence":
12529
- return listed(ctx, "licences", messageFor(input, "Licence"), async () => (await ctx.api().admin.listLicences()).map((l) => ({ label: l.name, value: l.licenceId, hint: `${l.state.toLowerCase()} \xB7 ${l.licenceId}` })));
13603
+ case "license":
13604
+ return listed(ctx, "licenses", messageFor(input, "License"), async () => (await ctx.api().admin.listLicenses()).map((l) => ({ label: l.name, value: l.licenceId, hint: `${l.state.toLowerCase()} \xB7 ${l.licenceId}` })));
12530
13605
  case "choice":
12531
13606
  return choose(ctx, question(input), spec.choices.map((c) => ({ label: c, value: c })));
12532
13607
  case "choices": {
@@ -12539,7 +13614,7 @@ async function askFor(spec, input, ctx) {
12539
13614
  }
12540
13615
  case "file":
12541
13616
  return typed(ctx, question(input), {
12542
- validate: (value) => fs17.existsSync(value.trim()) || `No file at ${value.trim()}.`
13617
+ validate: (value) => fs18.existsSync(value.trim()) || `No file at ${value.trim()}.`
12543
13618
  });
12544
13619
  case "number":
12545
13620
  return typed(ctx, question(input), { validate: numberRule(spec) });
@@ -12753,7 +13828,7 @@ function typedValue(ctx, message) {
12753
13828
  return typed(ctx, message);
12754
13829
  }
12755
13830
  function typeItChoice() {
12756
- return { name: chalk38.dim("Type it instead"), value: TYPE_IT };
13831
+ return { name: chalk39.dim("Type it instead"), value: TYPE_IT };
12757
13832
  }
12758
13833
  function text(ctx, name) {
12759
13834
  const value = ctx.known.get(name);
@@ -12783,7 +13858,7 @@ function capitalize(value) {
12783
13858
  return value.charAt(0).toUpperCase() + value.slice(1);
12784
13859
  }
12785
13860
  function labelled(label, hint2) {
12786
- return hint2 && hint2 !== label ? `${label} ${chalk38.dim(hint2)}` : label;
13861
+ return hint2 && hint2 !== label ? `${label} ${chalk39.dim(hint2)}` : label;
12787
13862
  }
12788
13863
  function numberRule(spec) {
12789
13864
  return (raw) => {
@@ -12829,7 +13904,7 @@ async function fillPendingInputs(actionCommand) {
12829
13904
  known: knownValues(actionCommand),
12830
13905
  globals: actionCommand.optsWithGlobals(),
12831
13906
  prefill: /* @__PURE__ */ new Map(),
12832
- note: (line) => process.stderr.write(chalk39.dim(` ${line}
13907
+ note: (line) => process.stderr.write(chalk40.dim(` ${line}
12833
13908
  `))
12834
13909
  };
12835
13910
  for (const item of orderByDependencies(pending)) {
@@ -12838,7 +13913,7 @@ async function fillPendingInputs(actionCommand) {
12838
13913
  ctx.known.set(item.input.name, value);
12839
13914
  }
12840
13915
  const log = env.log ?? ((line) => console.log(line));
12841
- log(chalk39.dim(` Equivalent: ${equivalentCommand(actionCommand)}`));
13916
+ log(chalk40.dim(` Equivalent: ${equivalentCommand(actionCommand)}`));
12842
13917
  }
12843
13918
  function commandChain(cmd) {
12844
13919
  const chain = [];
@@ -12935,7 +14010,7 @@ Docs: https://diafunc.com/documentation
12935
14010
  function createProgram(environment = {}) {
12936
14011
  const program = new DiafuncCommand();
12937
14012
  program.promptEnvironment = environment;
12938
- program.name("diafunc").description("Diafunc CLI: the command-line interface for the Diafunc platform").version(package_default.version).option("-p, --profile <name>", "Profile to use").option("-o, --output <format>", "Output format: human, json, table (default: human)").option("--project <id>", "Project to work in (overrides defaults.project)").option("--branch <name>", "Project branch (overrides defaults.branch)").option("--dry-run", "Preview mutating operations without executing them").option("--verbose", "Echo every HTTP request to stderr").option("--no-color", "Disable coloured output").option("--no-interactive", "Never prompt: a missing required input fails as it would in a script").showSuggestionAfterError().showHelpAfterError(`(run 'diafunc --help' to see the available commands)`).configureHelp({ showGlobalOptions: true }).configureOutput({
14013
+ program.name("diafunc").description("Diafunc CLI: the command-line interface for the Diafunc platform").version(package_default.version).option("-p, --profile <name>", "Profile to use").option("-o, --output <format>", "Output format: human, json, table (default: human)").option("--project <id>", "Project to work in (overrides defaults.project)").option("--branch <name>", "Project branch (overrides defaults.branch)").option("--dry-run", "Preview mutating operations without executing them").option("--verbose", "Echo every HTTP request to stderr").option("--no-color", "Disable colored output").option("--no-interactive", "Never prompt: a missing required input fails as it would in a script").showSuggestionAfterError().showHelpAfterError(`(run 'diafunc --help' to see the available commands)`).configureHelp({ showGlobalOptions: true, ...HIDDEN_ALIAS_HELP }).configureOutput({
12939
14014
  // Commander writes usage errors to stdout by default, which puts a complaint in the middle
12940
14015
  // of whatever a caller was capturing.
12941
14016
  writeErr: (str) => process.stderr.write(str)
@@ -12943,7 +14018,7 @@ function createProgram(environment = {}) {
12943
14018
  const opts = thisCommand.optsWithGlobals();
12944
14019
  if (opts.dryRun) setDryRun(true);
12945
14020
  if (opts.verbose) setVerbose(true);
12946
- if (opts.color === false) chalk40.level = 0;
14021
+ if (opts.color === false) chalk41.level = 0;
12947
14022
  }).hook("preAction", (_thisCommand, actionCommand) => fillPendingInputs(actionCommand));
12948
14023
  program.addHelpText("after", HELP_EPILOGUE);
12949
14024
  registerAuthCommands(program);
@@ -12965,7 +14040,7 @@ function createProgram(environment = {}) {
12965
14040
  registerStatusCommands(program);
12966
14041
  registerAnalyzeCommand(program);
12967
14042
  registerPublicCommands(program);
12968
- registerLicenceCommands(program);
14043
+ registerLicenseCommands(program);
12969
14044
  registerDataSourcesCommands(program);
12970
14045
  registerTableExportersCommands(program);
12971
14046
  registerSkeletonCommands(program);
@@ -12978,13 +14053,14 @@ function createProgram(environment = {}) {
12978
14053
  registerShellCommand(program);
12979
14054
  registerUpdateCommand(program);
12980
14055
  registerUninstallCommand(program);
14056
+ wireHiddenOptionAliases(program);
12981
14057
  return program;
12982
14058
  }
12983
14059
 
12984
14060
  export {
12985
14061
  EXIT_CANCELLED,
12986
14062
  handleError,
12987
- PromptCancelled,
14063
+ PromptCanceled,
12988
14064
  createProgram
12989
14065
  };
12990
- //# sourceMappingURL=chunk-T7BPK4LW.js.map
14066
+ //# sourceMappingURL=chunk-6QBACH4J.js.map