@zinn-dev/cli 0.40.0 → 0.41.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +166 -38
  2. package/index.js +24 -13
  3. package/package.json +7 -2
  4. package/skills/zinn/SKILL.md +63 -0
  5. package/src/actor.d.ts +2 -1
  6. package/src/actor.js +78 -11
  7. package/src/capabilities-schema.d.ts +163 -0
  8. package/src/capabilities-schema.js +124 -0
  9. package/src/capabilities.d.ts +21 -0
  10. package/src/capabilities.js +22 -0
  11. package/src/database.d.ts +1 -1
  12. package/src/database.js +4 -4
  13. package/src/errors.d.ts +158 -0
  14. package/src/errors.js +224 -0
  15. package/src/input.d.ts +116 -0
  16. package/src/input.js +119 -0
  17. package/src/lib.d.ts +42 -7
  18. package/src/lib.js +213 -17
  19. package/src/presentation/activity-presentation.js +16 -2
  20. package/src/presentation/column-presentation.d.ts +3 -5
  21. package/src/presentation/info-presentation.d.ts +4 -0
  22. package/src/presentation/info-presentation.js +96 -0
  23. package/src/presentation/task-presentation.d.ts +2 -10
  24. package/src/project.d.ts +6 -0
  25. package/src/project.js +23 -10
  26. package/src/result-schemas.d.ts +987 -0
  27. package/src/result-schemas.js +220 -0
  28. package/src/results.d.ts +23 -0
  29. package/src/results.js +17 -0
  30. package/src/routes/activity-router.d.ts +71 -0
  31. package/src/routes/activity-router.js +59 -11
  32. package/src/routes/backup-router.d.ts +17 -0
  33. package/src/routes/backup-router.js +15 -3
  34. package/src/routes/capabilities-router.d.ts +21 -0
  35. package/src/routes/capabilities-router.js +28 -0
  36. package/src/routes/comment-router.d.ts +183 -4
  37. package/src/routes/comment-router.js +136 -29
  38. package/src/routes/info-router.d.ts +21 -0
  39. package/src/routes/info-router.js +29 -0
  40. package/src/routes/label-router.d.ts +165 -0
  41. package/src/routes/label-router.js +111 -29
  42. package/src/routes/migrate-router.d.ts +17 -0
  43. package/src/routes/migrate-router.js +17 -5
  44. package/src/routes/project-router.d.ts +349 -0
  45. package/src/routes/project-router.js +278 -92
  46. package/src/routes/reindex-router.d.ts +17 -0
  47. package/src/routes/reindex-router.js +15 -3
  48. package/src/routes/relation-router.d.ts +108 -12
  49. package/src/routes/relation-router.js +74 -14
  50. package/src/routes/restore-router.d.ts +29 -0
  51. package/src/routes/restore-router.js +30 -13
  52. package/src/routes/router.d.ts +1 -1
  53. package/src/routes/router.js +44 -25
  54. package/src/routes/routes.d.ts +1565 -0
  55. package/src/routes/routes.js +5 -1
  56. package/src/routes/task-router.d.ts +861 -0
  57. package/src/routes/task-router.js +419 -163
  58. package/src/text-edit.d.ts +20 -2
  59. package/src/text-edit.js +22 -10
  60. package/src/types.d.ts +14 -0
@@ -1,28 +1,124 @@
1
- import type { TaskRelationType, TaskWithKey } from "@zinn-dev/core";
2
- type PresentedRelation = {
3
- type: TaskRelationType;
4
- direction: "outgoing" | "incoming" | null;
5
- task: {
6
- key: string;
7
- column: string;
8
- title: string;
9
- status: "Active" | "Archived";
10
- };
11
- };
1
+ import type { PresentedRelation } from "../result-schemas.js";
2
+ import type { TaskWithKey } from "@zinn-dev/core";
12
3
  export declare function presentRelations(taskMatch: TaskWithKey): Array<PresentedRelation>;
13
4
  export declare function formatRelations(relations: Array<PresentedRelation>): string;
14
5
  export declare const relationRouter: {
15
6
  create: {
7
+ summary: string;
8
+ effects: {
9
+ domain: "create";
10
+ storage: "normal-open";
11
+ };
12
+ confirmation: {
13
+ kind: "none";
14
+ };
15
+ input: {
16
+ readonly options: {
17
+ readonly type: {
18
+ readonly type: "string";
19
+ readonly required: true;
20
+ readonly value: {
21
+ readonly kind: "enum";
22
+ readonly name: "type";
23
+ readonly choices: ("related" | "dependency" | "duplicate" | "subtask")[];
24
+ };
25
+ };
26
+ };
27
+ readonly forms: readonly [{
28
+ readonly id: "default";
29
+ readonly positionals: readonly [{
30
+ readonly name: "source-task-key";
31
+ readonly min: 1;
32
+ readonly max: 1;
33
+ readonly value: {
34
+ readonly kind: "task-key";
35
+ };
36
+ }, {
37
+ readonly name: "target-task-key";
38
+ readonly min: 1;
39
+ readonly max: 1;
40
+ readonly value: {
41
+ readonly kind: "task-key";
42
+ };
43
+ }];
44
+ }];
45
+ readonly constraints: readonly [];
46
+ };
47
+ results: import("../results.js").CommandResult[];
16
48
  run: (args: string[]) => void;
17
49
  help: string;
18
50
  };
19
51
  list: {
52
+ summary: string;
53
+ effects: {
54
+ domain: "read";
55
+ storage: "normal-open";
56
+ };
57
+ confirmation: {
58
+ kind: "none";
59
+ };
60
+ input: {
61
+ readonly options: {};
62
+ readonly forms: readonly [{
63
+ readonly id: "default";
64
+ readonly positionals: readonly [{
65
+ readonly name: "task-key";
66
+ readonly min: 1;
67
+ readonly max: 1;
68
+ readonly value: {
69
+ readonly kind: "task-key";
70
+ };
71
+ }];
72
+ }];
73
+ readonly constraints: readonly [];
74
+ };
75
+ results: import("../results.js").CommandResult[];
20
76
  run: (args: string[]) => void;
21
77
  help: string;
22
78
  };
23
79
  delete: {
80
+ summary: string;
81
+ effects: {
82
+ domain: "delete";
83
+ storage: "normal-open";
84
+ };
85
+ confirmation: {
86
+ kind: "none";
87
+ };
88
+ input: {
89
+ readonly options: {
90
+ readonly type: {
91
+ readonly type: "string";
92
+ readonly required: true;
93
+ readonly value: {
94
+ readonly kind: "enum";
95
+ readonly name: "type";
96
+ readonly choices: ("related" | "dependency" | "duplicate" | "subtask")[];
97
+ };
98
+ };
99
+ };
100
+ readonly forms: readonly [{
101
+ readonly id: "default";
102
+ readonly positionals: readonly [{
103
+ readonly name: "source-task-key";
104
+ readonly min: 1;
105
+ readonly max: 1;
106
+ readonly value: {
107
+ readonly kind: "task-key";
108
+ };
109
+ }, {
110
+ readonly name: "target-task-key";
111
+ readonly min: 1;
112
+ readonly max: 1;
113
+ readonly value: {
114
+ readonly kind: "task-key";
115
+ };
116
+ }];
117
+ }];
118
+ readonly constraints: readonly [];
119
+ };
120
+ results: import("../results.js").CommandResult[];
24
121
  run: (args: string[]) => void;
25
122
  help: string;
26
123
  };
27
124
  };
28
- export {};
@@ -1,6 +1,8 @@
1
+ import { jsonResult } from "../results.js";
1
2
  import { parseArgs } from "node:util";
2
- import { column, relation, relationCreateSchema, task } from "@zinn-dev/core";
3
- import { output, quit, validatePositionals, validateUniqueOptions } from "../lib.js";
3
+ import { column, relation, relationTypeSchema, task } from "@zinn-dev/core";
4
+ import { generateCommandUsage, taskKeyPositional } from "../input.js";
5
+ import { output, quit, requireStringOption, validatePositionals, validateUniqueOptions, } from "../lib.js";
4
6
  import { currentActor } from "../actor.js";
5
7
  import { formatCellSeparator, formatRows } from "../presentation/row-layout.js";
6
8
  import { columnNameCell } from "../presentation/column-presentation.js";
@@ -30,7 +32,7 @@ export function presentRelations(taskMatch) {
30
32
  export function formatRelations(relations) {
31
33
  return formatRows(relations.map((entry) => {
32
34
  const isOutgoing = entry.direction === "outgoing";
33
- let label;
35
+ let label = entry.type;
34
36
  switch (entry.type) {
35
37
  case "related": {
36
38
  label = "Related to";
@@ -61,23 +63,66 @@ export function formatRelations(relations) {
61
63
  function parseRelationArgs(args) {
62
64
  const { values, positionals, tokens } = parseArgs({
63
65
  args,
64
- options: { type: { type: "string" } },
66
+ options: relationInputs.create.options,
65
67
  allowPositionals: true,
66
68
  strict: true,
67
69
  tokens: true,
68
70
  });
69
- validateUniqueOptions(tokens);
70
- validatePositionals(positionals, ["<source-task-key>", "<target-task-key>"]);
71
- const typeResult = relationCreateSchema.shape.relation_type.safeParse(values.type);
71
+ validateUniqueOptions(tokens, relationInputs.create.options);
72
+ validatePositionals(positionals, relationInputs.create.forms[0]);
73
+ const type = requireStringOption(relationInputs.create.options.type, values.type, "type", `--type must be one of these: ${relationInputs.create.options.type.value.choices.join(", ")}`);
74
+ const typeResult = relationTypeSchema.safeParse(type);
72
75
  if (!typeResult.success) {
73
- quit(`--type must be one of these: ${relationCreateSchema.shape.relation_type.options.join(", ")}`);
76
+ quit(`--type must be one of these: ${relationTypeSchema.options.join(", ")}`, undefined, {
77
+ argument: "--type",
78
+ });
74
79
  }
75
80
  const sourceTaskKey = positionals[0];
76
81
  const targetTaskKey = positionals[1];
77
82
  return { sourceTaskKey, targetTaskKey, relation_type: typeResult.data };
78
83
  }
84
+ const relationInputs = {
85
+ create: {
86
+ options: {
87
+ type: {
88
+ type: "string",
89
+ required: true,
90
+ value: {
91
+ kind: "enum",
92
+ name: "type",
93
+ choices: relationTypeSchema.options,
94
+ },
95
+ },
96
+ },
97
+ forms: [
98
+ {
99
+ id: "default",
100
+ positionals: [
101
+ { ...taskKeyPositional, name: "source-task-key" },
102
+ { ...taskKeyPositional, name: "target-task-key" },
103
+ ],
104
+ },
105
+ ],
106
+ constraints: [],
107
+ },
108
+ list: {
109
+ options: {},
110
+ forms: [
111
+ {
112
+ id: "default",
113
+ positionals: [taskKeyPositional],
114
+ },
115
+ ],
116
+ constraints: [],
117
+ },
118
+ };
79
119
  export const relationRouter = {
80
120
  create: {
121
+ summary: "Create a relation between two tasks.",
122
+ effects: { domain: "create", storage: "normal-open" },
123
+ confirmation: { kind: "none" },
124
+ input: relationInputs.create,
125
+ results: [jsonResult("RelationChange")],
81
126
  run: (args) => {
82
127
  const props = parseRelationArgs(args);
83
128
  const { sourceTaskKey, targetTaskKey } = props;
@@ -99,7 +144,7 @@ export const relationRouter = {
99
144
  return `${r.source} ${label} ${r.target}`;
100
145
  });
101
146
  },
102
- help: `Usage: zinn task relation create <source-task-key> <target-task-key> --type <type>
147
+ help: `${generateCommandUsage("task relation create", relationInputs.create)}
103
148
 
104
149
  Create a relation between two tasks.
105
150
 
@@ -119,12 +164,22 @@ Tasks from separate projects can be related to each other. Tasks can also be rel
119
164
  Example: zinn task relation create APP-1 APP-2 --type dependency`,
120
165
  },
121
166
  list: {
167
+ summary: "Show incoming and outgoing relations with connected task keys, columns and titles.",
168
+ effects: { domain: "read", storage: "normal-open" },
169
+ confirmation: { kind: "none" },
170
+ input: relationInputs.list,
171
+ results: [jsonResult("RelationList")],
122
172
  run: (args) => {
123
- const { positionals } = parseArgs({ args, allowPositionals: true, strict: true });
124
- validatePositionals(positionals, ["<task-key>"]);
173
+ const { positionals } = parseArgs({
174
+ options: relationInputs.list.options,
175
+ args,
176
+ allowPositionals: true,
177
+ strict: true,
178
+ });
179
+ validatePositionals(positionals, relationInputs.list.forms[0]);
125
180
  output(presentRelations(task.getByKey(positionals[0])), formatRelations);
126
181
  },
127
- help: `Usage: zinn task relation list <task-key>
182
+ help: `${generateCommandUsage("task relation list", relationInputs.list)}
128
183
 
129
184
  Show incoming and outgoing relations with connected task keys, columns and titles.
130
185
  Archived connected tasks are included and marked Archived.
@@ -133,6 +188,11 @@ An empty list prints nothing.
133
188
  Example: zinn task relation list APP-1`,
134
189
  },
135
190
  delete: {
191
+ summary: "Remove only the specified relation. No confirmation is required.",
192
+ effects: { domain: "delete", storage: "normal-open" },
193
+ confirmation: { kind: "none" },
194
+ input: relationInputs.create,
195
+ results: [jsonResult("RelationChange")],
136
196
  run: (args) => {
137
197
  const props = parseRelationArgs(args);
138
198
  relation.delete(props, currentActor());
@@ -145,11 +205,11 @@ Example: zinn task relation list APP-1`,
145
205
  };
146
206
  output(deleted, (r) => `Deleted ${r.type} relation from ${r.source} to ${r.target}`);
147
207
  },
148
- help: `Usage: zinn task relation delete <source-task-key> <target-task-key> --type <type>
208
+ help: `${generateCommandUsage("task relation delete", relationInputs.create)}
149
209
 
150
210
  Remove only the specified relation. No confirmation is required.
151
211
 
152
- Types: ${relationCreateSchema.shape.relation_type.options.join(", ")}.
212
+ Types: ${relationTypeSchema.options.join(", ")}.
153
213
 
154
214
  For related, either task order works.
155
215
  For dependency, duplicate, and subtask, use the creation direction:
@@ -1,4 +1,33 @@
1
1
  export declare const restoreCommand: {
2
+ summary: string;
3
+ effects: {
4
+ domain: "replace";
5
+ storage: "restore";
6
+ };
7
+ confirmation: {
8
+ kind: "prompt";
9
+ description: string;
10
+ };
11
+ input: {
12
+ readonly options: {
13
+ readonly yes: {
14
+ readonly type: "boolean";
15
+ };
16
+ };
17
+ readonly forms: readonly [{
18
+ readonly id: "default";
19
+ readonly positionals: readonly [{
20
+ readonly name: "path";
21
+ readonly min: 1;
22
+ readonly max: 1;
23
+ readonly value: {
24
+ readonly kind: "path";
25
+ };
26
+ }];
27
+ }];
28
+ readonly constraints: readonly [];
29
+ };
30
+ results: import("../results.js").CommandResult[];
2
31
  run: (args: string[]) => Promise<void>;
3
32
  help: string;
4
33
  };
@@ -1,21 +1,38 @@
1
1
  import { parseArgs } from "node:util";
2
2
  import { resolve } from "node:path";
3
3
  import { backup, RestoreRefusedError, getStorage } from "@zinn-dev/core";
4
+ import { jsonResult } from "../results.js";
4
5
  import { reportLockWait } from "../database.js";
5
- import { askConfirmation, output, validatePositionals, validateUniqueOptions } from "../lib.js";
6
+ import { confirmationDescription } from "../lib.js";
7
+ import { generateCommandUsage } from "../input.js";
8
+ import { askConfirmation, diagnostic, output, validatePositionals, validateUniqueOptions, } from "../lib.js";
6
9
  import packageJson from "../../package.json" with { type: "json" };
7
10
  const build = { client: "cli", version: packageJson.version };
11
+ const restoreInputs = {
12
+ command: {
13
+ options: { yes: { type: "boolean" } },
14
+ forms: [
15
+ { id: "default", positionals: [{ name: "path", min: 1, max: 1, value: { kind: "path" } }] },
16
+ ],
17
+ constraints: [],
18
+ },
19
+ };
8
20
  export const restoreCommand = {
21
+ summary: "Replace the database with the one in a backup file, such as one saved by `zinn backup` or by an upgrade, after confirmation.",
22
+ effects: { domain: "replace", storage: "restore" },
23
+ confirmation: { kind: "prompt", description: confirmationDescription },
24
+ input: restoreInputs.command,
25
+ results: [jsonResult("Restore")],
9
26
  run: async (args) => {
10
27
  const { positionals, values, tokens } = parseArgs({
11
28
  args,
12
29
  strict: true,
13
30
  allowPositionals: true,
14
31
  tokens: true,
15
- options: { yes: { type: "boolean" } },
32
+ options: restoreInputs.command.options,
16
33
  });
17
- validateUniqueOptions(tokens);
18
- validatePositionals(positionals, ["<path>"]);
34
+ validateUniqueOptions(tokens, restoreInputs.command.options);
35
+ validatePositionals(positionals, restoreInputs.command.forms[0]);
19
36
  const path = resolve(positionals[0]);
20
37
  const { databasePath, backupDirectory } = getStorage();
21
38
  const isPreconfirmed = values.yes === true;
@@ -23,7 +40,7 @@ export const restoreCommand = {
23
40
  if (!isPreconfirmed) {
24
41
  backup.check({ ...build, path });
25
42
  }
26
- const isConfirmed = await askConfirmation(`Replace the database at ${databasePath} with the backup ${path}? Its current board is saved to ${backupDirectory} first.`, isPreconfirmed);
43
+ const isConfirmed = await askConfirmation(`Replace the database at ${databasePath} with the backup ${path}? The current database is saved to ${backupDirectory} first.`, isPreconfirmed);
27
44
  if (!isConfirmed) {
28
45
  output(null, () => `Restore cancelled. The database at ${databasePath} is unchanged`);
29
46
  return;
@@ -31,10 +48,10 @@ export const restoreCommand = {
31
48
  try {
32
49
  const result = backup.restore({ ...build, path, onWait: reportLockWait });
33
50
  output(result, (r) => {
34
- const restored = `Restored the board from ${path} at schema version ${r.restoredVersion}.`;
51
+ const restored = `Restored the database from ${path} at schema version ${r.restoredVersion}.`;
35
52
  return r.backupPath == null
36
- ? `${restored} There was no board to save`
37
- : `${restored} The board it replaced was saved to ${r.backupPath}`;
53
+ ? `${restored} There was no database to save`
54
+ : `${restored} The database it replaced was saved to ${r.backupPath}`;
38
55
  });
39
56
  }
40
57
  catch (error) {
@@ -45,23 +62,23 @@ export const restoreCommand = {
45
62
  typeof error.code === "string" &&
46
63
  error.code.startsWith("SQLITE_CORRUPT");
47
64
  if (isDamagedDatabase) {
48
- console.error(`The database at ${databasePath} is damaged. Nothing was changed. To restore it:\n` +
65
+ diagnostic(`The database at ${databasePath} is damaged. Nothing was changed. To restore it:\n` +
49
66
  `1. Close every program that has the database open.\n` +
50
67
  `2. Move ${databasePath}, ${databasePath}-wal and ${databasePath}-shm out of the data folder, keeping any that exist together. Keep these files; do not delete them.\n` +
51
68
  `3. Run the same zinn restore command again to create the database from the backup.`);
52
69
  }
53
70
  else {
54
- console.error(`The database is unchanged. Backups taken before each restore attempt are kept in ${backupDirectory}.`);
71
+ diagnostic(`The database is unchanged. Backups taken before each restore attempt are kept in ${backupDirectory}.`);
55
72
  }
56
73
  }
57
74
  throw error;
58
75
  }
59
76
  },
60
- help: `Usage: zinn restore <path> [--yes]
77
+ help: `${generateCommandUsage("restore", restoreInputs.command)}
61
78
 
62
- Replace the board with the one in a backup file, such as one saved by \`zinn backup\` or by an upgrade, after confirmation.
79
+ Replace the database with the one in a backup file, such as one saved by \`zinn backup\` or by an upgrade, after confirmation.
63
80
 
64
- The current board is saved first, in the same place as \`zinn backup\`, and the restore is applied completely or not at all.
81
+ The current database is saved first, in the same place as \`zinn backup\`, and the restore is applied completely or not at all.
65
82
  A backup with an older schema version is restored at that version. Zinn then upgrades it like any older database: by itself, except for ~/.zinn run from a source checkout, which needs \`zinn migrate\`.
66
83
  Restoring onto a missing database creates it.
67
84
  Fails, leaving the database as it is, when the backup has a newer schema version than this Zinn or none at all, is damaged, or is not a Zinn database.
@@ -1,6 +1,6 @@
1
1
  import type { ParsedRoute, RouteDef } from "../types.js";
2
2
  export declare function parseRoutes(routesDef: RouteDef, prefix?: string): ParsedRoute[];
3
- export declare function createRouter(routesDef: RouteDef): {
3
+ export declare function createRouter(routesDef: RouteDef, beforeRun?: (command: ParsedRoute) => void | Promise<void>): {
4
4
  route: (args: Array<string>) => Promise<void>;
5
5
  help: string;
6
6
  };
@@ -1,20 +1,22 @@
1
1
  import { parseArgs } from "node:util";
2
- import { failureMessage, isAllowLegacyReadFlag, isHelpFlag, isJsonFlag, quit, setLegacyReadAllowed, setOutputMode, UsageError, validateUniqueOptions, } from "../lib.js";
2
+ import { routerOptions, helpSpellings, versionSpellings, usageLabel } from "../input.js";
3
+ import { dashValueHelp, diagnostic, flushDiagnostics, isAllowLegacyReadFlag, isHelpFlag, isRouterFlag, parseArgsMessage, prepareOutput, quit, renderFailure, setLegacyReadAllowed, UsageError, validateUniqueOptions, } from "../lib.js";
4
+ // ZINN_DEBUG=1 prints routing detail on stderr, so stdout and `--json` results stay unchanged.
5
+ function isDebugOutputEnabled() {
6
+ return process.env.ZINN_DEBUG === "1";
7
+ }
3
8
  function getIsRunnable(obj) {
4
9
  return Object.hasOwn(obj, "run");
5
10
  }
6
- function isRouterFlag(arg) {
7
- return isJsonFlag(arg) || isAllowLegacyReadFlag(arg);
8
- }
9
11
  // --json and --allow-legacy-read can each be given once, like a command's own flags.
10
12
  function validateRouterFlags(routableArgs) {
11
13
  const { tokens } = parseArgs({
12
14
  args: routableArgs.filter(isRouterFlag),
13
- options: { json: { type: "boolean" }, "allow-legacy-read": { type: "boolean" } },
15
+ options: routerOptions,
14
16
  strict: true,
15
17
  tokens: true,
16
18
  });
17
- validateUniqueOptions(tokens);
19
+ validateUniqueOptions(tokens, routerOptions);
18
20
  }
19
21
  /** The usage lines that open a command's help, up to its first blank line. */
20
22
  function getUsage(help) {
@@ -52,11 +54,11 @@ function getRootHelp(parsedRoutes) {
52
54
  // TODO: maybe "brand" text that is exported and used here for title and desc
53
55
  return `ZINN - A kanban workflow in the terminal
54
56
 
55
- Usage: zinn <command>
57
+ ${usageLabel}zinn <command>
56
58
 
57
59
  Options:
58
- -h, --help Show help
59
- -v, --version Show version
60
+ ${helpSpellings.join(", ")} Show help
61
+ ${versionSpellings.join(", ")} Show version
60
62
  --json Print command output as JSON
61
63
  --allow-legacy-read Read a database without a schema version, best effort and read-only
62
64
 
@@ -67,6 +69,7 @@ Run zinn <namespace> --help or zinn <command> --help for more information.
67
69
  --help shows help for the command words before it and runs nothing. The rest of the line is ignored.
68
70
  -- ends the options: everything after it is considered a plain word, even if it starts with a dash (e.g. 'zinn project column create SHOP -- -later').
69
71
  Flags after it are not read.
72
+ ${dashValueHelp("--description")}
70
73
  Running zinn without a command shows this help.`;
71
74
  }
72
75
  function getNamespaceHelp(parsedRoutes, namespace) {
@@ -74,7 +77,7 @@ function getNamespaceHelp(parsedRoutes, namespace) {
74
77
  if (commands === "") {
75
78
  return null;
76
79
  }
77
- return `Usage: zinn ${namespace} <command>\n\nCommands:\n${commands}`;
80
+ return `${usageLabel}zinn ${namespace} <command>\n\nCommands:\n${commands}`;
78
81
  }
79
82
  // The longest leading run of words that names a namespace, or the root namespace "" when none does.
80
83
  function findNearestNamespace(parsedRoutes, words) {
@@ -97,18 +100,20 @@ function routeToNamespace(parsedRoutes, words, isHelpRequest) {
97
100
  return;
98
101
  }
99
102
  if (unknownWord == null) {
100
- quit(`Missing a command for "${commandName}"`, help);
103
+ quit(`Missing a command for "${commandName}"`, help, { argument: "command" });
101
104
  }
102
105
  const reason = `Unrecognized command "${unknownWord}" for "${commandName}"`;
103
106
  if (isHelpRequest) {
104
- quit(reason, help);
107
+ quit(reason, help, { argument: "command" });
105
108
  }
106
- quit(`${reason}. Run \`${commandName} --help\` for a list of available commands`);
109
+ quit(`${reason}. Run \`${commandName} --help\` for a list of available commands`, undefined, {
110
+ argument: "command",
111
+ });
107
112
  }
108
113
  export function parseRoutes(routesDef, prefix) {
109
114
  const routeDefinitions = [];
110
- if (process.env.DEBUG) {
111
- console.debug(`::router.parseRoutes[${prefix ?? ""}]`, routesDef);
115
+ if (isDebugOutputEnabled()) {
116
+ diagnostic(`::router.parseRoutes[${prefix ?? ""}] ${Object.keys(routesDef).join(" ")}`);
112
117
  }
113
118
  for (const key of Object.keys(routesDef)) {
114
119
  const definition = routesDef[key];
@@ -124,15 +129,13 @@ export function parseRoutes(routesDef, prefix) {
124
129
  }
125
130
  return routeDefinitions;
126
131
  }
127
- async function route(parsedRoutes, rawArgs) {
132
+ async function route(parsedRoutes, rawArgs, beforeRun) {
133
+ prepareOutput(rawArgs);
128
134
  // Anything after "--" belongs to the command, so "--json" there is search text, not a flag.
129
135
  const separatorIndex = rawArgs.indexOf("--");
130
136
  const routableArgs = separatorIndex === -1 ? rawArgs : rawArgs.slice(0, separatorIndex);
131
137
  const passthroughArgs = separatorIndex === -1 ? [] : rawArgs.slice(separatorIndex);
132
138
  const filteredRoutableArgs = routableArgs.filter((arg) => !isRouterFlag(arg));
133
- if (routableArgs.some(isJsonFlag)) {
134
- setOutputMode("json");
135
- }
136
139
  if (routableArgs.some(isAllowLegacyReadFlag)) {
137
140
  setLegacyReadAllowed(true);
138
141
  }
@@ -153,8 +156,8 @@ async function route(parsedRoutes, rawArgs) {
153
156
  break;
154
157
  }
155
158
  }
156
- if (process.env.DEBUG) {
157
- console.log("::router.route", { args, result: parsedRoutes.map((r) => r.command), match });
159
+ if (isDebugOutputEnabled()) {
160
+ diagnostic(`::router.route ${match?.command ?? "namespace"}`);
158
161
  }
159
162
  if (match == null) {
160
163
  routeToNamespace(parsedRoutes, args, isHelpRequest);
@@ -167,19 +170,35 @@ async function route(parsedRoutes, rawArgs) {
167
170
  validateRouterFlags(routableArgs);
168
171
  const commandArgs = args.slice(nestingLevel);
169
172
  try {
173
+ await beforeRun?.(match);
170
174
  await match.run(commandArgs);
171
175
  }
172
176
  catch (err) {
173
177
  if (err instanceof UsageError) {
174
- quit(err.message, getUsage(match.help));
178
+ err.help = getUsage(match.help);
179
+ throw err;
180
+ }
181
+ const suggestFor = (flag) => match.guessedFlags?.[flag]?.(commandArgs);
182
+ const parseArgsReason = parseArgsMessage(err, rawArgs, suggestFor);
183
+ if (parseArgsReason != null) {
184
+ const argument = /(?:Unknown option|Option) '(-[^' ]+)/.exec(err.message)?.[1];
185
+ quit(parseArgsReason, getUsage(match.help), argument === undefined ? undefined : { argument });
175
186
  }
176
- quit(failureMessage(err, `Something went wrong while running "${match.command}" with args: ${commandArgs.join(",")}`));
187
+ throw err;
177
188
  }
178
189
  }
179
- export function createRouter(routesDef) {
190
+ export function createRouter(routesDef, beforeRun) {
180
191
  const parsedRoutes = parseRoutes(routesDef);
181
192
  return {
182
- route: (args) => route(parsedRoutes, args),
193
+ route: async (args) => {
194
+ try {
195
+ await route(parsedRoutes, args, beforeRun);
196
+ flushDiagnostics();
197
+ }
198
+ catch (error) {
199
+ renderFailure(error);
200
+ }
201
+ },
183
202
  help: getRootHelp(parsedRoutes),
184
203
  };
185
204
  }