@apet97/clockify-cli-115 5.0.4 → 7.0.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 (55) hide show
  1. package/README.md +255 -39
  2. package/dist/client.js +43 -17
  3. package/dist/closed-pipe.js +3 -0
  4. package/dist/commands/api.js +192 -103
  5. package/dist/commands/approvals.js +9 -10
  6. package/dist/commands/auditlog.js +11 -8
  7. package/dist/commands/auth.js +229 -0
  8. package/dist/commands/balanceAssignment.js +10 -8
  9. package/dist/commands/batch.js +226 -0
  10. package/dist/commands/clients.js +27 -72
  11. package/dist/commands/doctor.js +98 -82
  12. package/dist/commands/entries.js +29 -14
  13. package/dist/commands/expenses.js +75 -36
  14. package/dist/commands/helpers.js +74 -9
  15. package/dist/commands/invoices.js +12 -16
  16. package/dist/commands/leaf-command.js +15 -0
  17. package/dist/commands/log.js +4 -2
  18. package/dist/commands/manifest.js +63 -0
  19. package/dist/commands/operations.js +271 -0
  20. package/dist/commands/projects.js +28 -32
  21. package/dist/commands/reports.js +54 -21
  22. package/dist/commands/resolve-refs.js +30 -53
  23. package/dist/commands/scheduling.js +94 -40
  24. package/dist/commands/shared-report-body.js +127 -0
  25. package/dist/commands/sharedReports.js +19 -235
  26. package/dist/commands/skill.js +85 -0
  27. package/dist/commands/start.js +6 -4
  28. package/dist/commands/status.js +69 -27
  29. package/dist/commands/stop.js +7 -18
  30. package/dist/commands/tags.js +11 -11
  31. package/dist/commands/tasks.js +27 -133
  32. package/dist/commands/timeoff.js +23 -16
  33. package/dist/commands/users.js +11 -19
  34. package/dist/commands/webhook-delivery.js +331 -0
  35. package/dist/commands/webhooks.js +40 -104
  36. package/dist/completions.js +291 -55
  37. package/dist/config.js +168 -61
  38. package/dist/credentials.js +164 -0
  39. package/dist/duration.js +5 -4
  40. package/dist/failure.js +82 -0
  41. package/dist/flags.js +84 -0
  42. package/dist/generated/version.js +1 -1
  43. package/dist/index.js +68 -108
  44. package/dist/interrupts.js +28 -0
  45. package/dist/output.js +189 -66
  46. package/dist/receipt.js +2 -10
  47. package/dist/stdin.js +6 -0
  48. package/dist/stdout.js +38 -0
  49. package/dist/write-outcome.js +84 -0
  50. package/package.json +6 -4
  51. package/plugin/.claude-plugin/plugin.json +16 -0
  52. package/plugin/skills/clockify-cli/SKILL.md +88 -0
  53. package/plugin/skills/clockify-mcp/SKILL.md +48 -0
  54. package/plugin/skills/clockify-sdk/SKILL.md +85 -0
  55. package/dist/error-codes.js +0 -272
@@ -0,0 +1,164 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createInterface } from "node:readline";
3
+ import { Writable } from "node:stream";
4
+ import { UsageError } from "./failure.js";
5
+ import { signalExitCode } from "./interrupts.js";
6
+ import { AlreadyReportedError } from "./output.js";
7
+ import { readStdin } from "./stdin.js";
8
+ const SERVICE = "clockify115-cli";
9
+ const ITEM_NOT_FOUND = 44;
10
+ const PROMPT_TIMEOUT_MS = 120_000;
11
+ const NOTHING_READ = "No API key was read; provide it on stdin or at the prompt.";
12
+ const ACCOUNT = /^[A-Za-z0-9_-]+@(?:https?:\/\/)?[A-Za-z0-9.:[\]-]+$/;
13
+ export function credentialHost({ baseUrl, region, subdomain }) {
14
+ if (baseUrl !== undefined)
15
+ return URL.canParse(baseUrl) ? new URL(baseUrl).origin : "invalid-base-url";
16
+ return subdomain === undefined ? (region ?? "global") : `${subdomain}.${region ?? "global"}`;
17
+ }
18
+ export function credentialAccount(config) {
19
+ const account = `${config.profile ?? ""}@${credentialHost(config)}`;
20
+ return ACCOUNT.test(account) ? account : undefined;
21
+ }
22
+ async function run(command, args, input = "") {
23
+ const { CLOCKIFY_API_KEY: _key, CLOCKIFY_ADDON_TOKEN: _token, ...env } = process.env;
24
+ const child = spawn(command, args, { env, stdio: ["pipe", "pipe", "pipe"] });
25
+ const timer = setTimeout(() => child.kill(), PROMPT_TIMEOUT_MS);
26
+ let stdout = "";
27
+ let stderr = "";
28
+ child.stdout.setEncoding("utf8").on("data", (text) => (stdout += text));
29
+ child.stderr.setEncoding("utf8").on("data", (text) => (stderr += text));
30
+ child.stdin.on("error", () => undefined);
31
+ child.stdin.end(input);
32
+ try {
33
+ return await new Promise((resolve, reject) => {
34
+ child.on("error", (err) => {
35
+ reject(new Error(`Could not run ${command}: ${err.message}. Set CLOCKIFY_API_KEY instead.`));
36
+ });
37
+ child.on("close", (code) => {
38
+ resolve({ code, stdout, stderr });
39
+ });
40
+ });
41
+ }
42
+ finally {
43
+ clearTimeout(timer);
44
+ }
45
+ }
46
+ function failed(store, action, { code, stderr }) {
47
+ const reason = stderr.trim().slice(0, 300) || `exit ${code ?? "by signal"}`;
48
+ return new Error(`Could not ${action} the API key in ${store}: ${reason}`);
49
+ }
50
+ export function macosKeychain(command = "/usr/bin/security", keychain = []) {
51
+ const name = "the macOS keychain";
52
+ const item = (account) => ["-s", SERVICE, "-a", account];
53
+ return {
54
+ name,
55
+ async get(account) {
56
+ const result = await run(command, ["find-generic-password", ...item(account), "-w", ...keychain]);
57
+ if (result.code === ITEM_NOT_FOUND)
58
+ return undefined;
59
+ if (result.code !== 0)
60
+ throw failed(name, "read", result);
61
+ return result.stdout.replace(/\n$/, "");
62
+ },
63
+ async set(account, secret) {
64
+ const words = ["add-generic-password", "-U", ...item(account), "-w", secret, ...keychain];
65
+ const result = await run(command, ["-i"], `${words.map((word) => `"${word}"`).join(" ")}\n`);
66
+ if (result.code !== 0)
67
+ throw failed(name, "store", result);
68
+ },
69
+ async delete(account) {
70
+ const result = await run(command, ["delete-generic-password", ...item(account), ...keychain]);
71
+ if (result.code === ITEM_NOT_FOUND)
72
+ return false;
73
+ if (result.code !== 0)
74
+ throw failed(name, "delete", result);
75
+ return true;
76
+ },
77
+ };
78
+ }
79
+ export function secretService(command = "secret-tool") {
80
+ const name = "the Secret Service keyring";
81
+ const item = (account) => ["service", SERVICE, "account", account];
82
+ const get = async (account) => {
83
+ const result = await run(command, ["lookup", ...item(account)]);
84
+ if (result.code === 0 && result.stdout !== "")
85
+ return result.stdout;
86
+ if (result.code === 1 && result.stderr.trim() === "")
87
+ return undefined;
88
+ throw failed(name, "read", result);
89
+ };
90
+ return {
91
+ name,
92
+ get,
93
+ async set(account, secret) {
94
+ const result = await run(command, ["store", "--label", `clk115 ${account}`, ...item(account)], secret);
95
+ if (result.code !== 0)
96
+ throw failed(name, "store", result);
97
+ },
98
+ async delete(account) {
99
+ if ((await get(account)) === undefined)
100
+ return false;
101
+ const result = await run(command, ["clear", ...item(account)]);
102
+ if (result.code !== 0)
103
+ throw failed(name, "delete", result);
104
+ return true;
105
+ },
106
+ };
107
+ }
108
+ export function systemCredentialStore(platform = process.platform) {
109
+ if (platform === "darwin")
110
+ return macosKeychain();
111
+ if (platform === "linux")
112
+ return secretService();
113
+ throw new UsageError(`clk115 has no credential store on ${platform}; set CLOCKIFY_API_KEY in the environment.`);
114
+ }
115
+ export function requireStorableKey(text) {
116
+ const key = text.trim();
117
+ if (key === "")
118
+ throw new UsageError(NOTHING_READ);
119
+ if (!/^[A-Za-z0-9+/=_.-]{8,512}$/.test(key)) {
120
+ throw new UsageError("That does not look like a Clockify API key; provide the key exactly as Clockify shows it.");
121
+ }
122
+ return key;
123
+ }
124
+ export async function storeVerified(store, account, key) {
125
+ const previous = await store.get(account);
126
+ const undo = async () => {
127
+ await (previous === undefined ? store.delete(account) : store.set(account, previous)).catch(() => undefined);
128
+ };
129
+ await store.set(account, key);
130
+ if ((await store.get(account)) === key)
131
+ return undo;
132
+ await undo();
133
+ throw new Error(`Could not read the API key back from ${store.name}, so it was not kept. Set CLOCKIFY_API_KEY instead.`);
134
+ }
135
+ export async function storedApiKey(config, store) {
136
+ const account = credentialAccount(config);
137
+ return account === undefined ? undefined : await store().get(account);
138
+ }
139
+ export async function readSecret() {
140
+ if (!process.stdin.isTTY)
141
+ return await readStdin();
142
+ const silent = new Writable({
143
+ write(_chunk, _encoding, done) {
144
+ done();
145
+ },
146
+ });
147
+ const reader = createInterface({ input: process.stdin, output: silent, terminal: true });
148
+ process.stderr.write("Clockify API key (hidden): ");
149
+ try {
150
+ return await new Promise((resolve, reject) => {
151
+ reader.once("line", resolve);
152
+ reader.once("SIGINT", () => {
153
+ reject(new AlreadyReportedError(signalExitCode("SIGINT")));
154
+ });
155
+ reader.once("close", () => {
156
+ reject(new UsageError(NOTHING_READ));
157
+ });
158
+ });
159
+ }
160
+ finally {
161
+ reader.close();
162
+ process.stderr.write("\n");
163
+ }
164
+ }
package/dist/duration.js CHANGED
@@ -1,7 +1,8 @@
1
+ import { UsageError } from "./failure.js";
1
2
  export function parseDuration(input) {
2
3
  const trimmed = input.trim();
3
4
  if (trimmed === "") {
4
- throw new Error('duration is missing; provide a form like "1h30m", "45m", "90", or ISO "PT1H30M"');
5
+ throw new UsageError('duration is missing; provide a form like "1h30m", "45m", "90", or ISO "PT1H30M"');
5
6
  }
6
7
  if (/^PT/i.test(trimmed)) {
7
8
  return requirePositive(parseIsoDuration(trimmed), input);
@@ -16,7 +17,7 @@ export function parseDuration(input) {
16
17
  re.lastIndex = offset;
17
18
  const match = re.exec(trimmed);
18
19
  if (match === null) {
19
- throw new Error(`could not parse duration ${JSON.stringify(input)}; use forms like "1h30m", "45m", "90", or ISO "PT1H30M"`);
20
+ throw new UsageError(`could not parse duration ${JSON.stringify(input)}; use forms like "1h30m", "45m", "90", or ISO "PT1H30M"`);
20
21
  }
21
22
  const value = Number(match[1]);
22
23
  const unit = (match[2] ?? "").toLowerCase();
@@ -27,7 +28,7 @@ export function parseDuration(input) {
27
28
  }
28
29
  function requirePositive(seconds, input) {
29
30
  if (seconds <= 0) {
30
- throw new Error(`duration ${JSON.stringify(input)} must be positive; a zero-length entry records nothing`);
31
+ throw new UsageError(`duration ${JSON.stringify(input)} must be positive; a zero-length entry records nothing`);
31
32
  }
32
33
  return seconds;
33
34
  }
@@ -35,7 +36,7 @@ function parseIsoDuration(input) {
35
36
  const re = /^PT(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?$/i;
36
37
  const match = re.exec(input);
37
38
  if (!match || (match[1] == null && match[2] == null && match[3] == null)) {
38
- throw new Error(`could not parse ISO duration ${JSON.stringify(input)}; provide a form like "PT1H30M"`);
39
+ throw new UsageError(`could not parse ISO duration ${JSON.stringify(input)}; provide a form like "PT1H30M"`);
39
40
  }
40
41
  const hours = match[1] != null ? Number(match[1]) : 0;
41
42
  const minutes = match[2] != null ? Number(match[2]) : 0;
@@ -0,0 +1,82 @@
1
+ import { recoveryForCode } from "clockify-sdk-ts-115/error-codes";
2
+ import { AlreadyReportedError, printError, UsageError, } from "./output.js";
3
+ import { failureStatus, writeFailure } from "./write-outcome.js";
4
+ export { UsageError } from "./output.js";
5
+ export class LookupError extends Error {
6
+ lookupState;
7
+ constructor(lookupState, message) {
8
+ super(message);
9
+ this.lookupState = lookupState;
10
+ }
11
+ }
12
+ export class PartialDeleteError extends Error {
13
+ completedStage;
14
+ next;
15
+ archiveAction;
16
+ constructor(cause, completedStage, next, archiveAction) {
17
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
18
+ this.completedStage = completedStage;
19
+ this.next = next;
20
+ this.archiveAction = archiveAction;
21
+ }
22
+ }
23
+ const COMMANDER_EXIT_ZERO_CODES = new Set([
24
+ "commander.helpDisplayed",
25
+ "commander.help",
26
+ "commander.version",
27
+ ]);
28
+ function isCommanderFailure(err) {
29
+ return (typeof err === "object" &&
30
+ err !== null &&
31
+ typeof err.code === "string" &&
32
+ err.code.startsWith("commander."));
33
+ }
34
+ function helpInvocation(command) {
35
+ const names = [];
36
+ for (let current = command; current?.parent != null; current = current.parent) {
37
+ names.unshift(current.name());
38
+ }
39
+ return ["clk115", ...names, "--help"].join(" ");
40
+ }
41
+ function redactInlineOptionValues(message) {
42
+ return message.replace(/'(--?[^\s'=]+)=[^']*'/g, "'$1=<redacted>'");
43
+ }
44
+ function usage(failedCommand) {
45
+ return {
46
+ code: "invalid_request",
47
+ recovery: `Run \`${helpInvocation(failedCommand)}\` for usage.`,
48
+ retryable: false,
49
+ };
50
+ }
51
+ export async function reportFailure(err, output, failedCommand) {
52
+ const write = await writeFailure(failedCommand, err instanceof PartialDeleteError ? err.cause : err);
53
+ if (isCommanderFailure(err)) {
54
+ if (COMMANDER_EXIT_ZERO_CODES.has(err.code))
55
+ return err.exitCode ?? 0;
56
+ const message = redactInlineOptionValues(err.message.replace(/^error: /, ""));
57
+ printError(message, output, undefined, usage(failedCommand), undefined, write);
58
+ return 2;
59
+ }
60
+ if (err instanceof AlreadyReportedError)
61
+ return err.exitCode;
62
+ if (err instanceof UsageError && (!write || write.stage === "before_dispatch")) {
63
+ printError(err.message, output, undefined, usage(failedCommand), undefined, write);
64
+ return 2;
65
+ }
66
+ const { classifyClockifyError, clockifyErrorDetail } = await import("clockify-sdk-ts-115/errors");
67
+ const partial = err instanceof PartialDeleteError ? err : undefined;
68
+ if (partial)
69
+ err = partial.cause;
70
+ const message = clockifyErrorDetail(err);
71
+ const classified = err instanceof LookupError
72
+ ? {
73
+ code: err.lookupState === "not_found" ? "not_found" : "invalid_request",
74
+ recovery: err.lookupState === "not_found" ? recoveryForCode("not_found") : "Provide the 24-character id instead.",
75
+ retryable: false,
76
+ }
77
+ : classifyClockifyError(err);
78
+ const statusCode = failureStatus(err);
79
+ const details = { ...write, ...(err instanceof LookupError && { lookupState: err.lookupState }) };
80
+ printError(message, output, statusCode, classified, partial, details);
81
+ return 1;
82
+ }
package/dist/flags.js ADDED
@@ -0,0 +1,84 @@
1
+ import { InvalidArgumentError } from "commander";
2
+ import { UsageError } from "./failure.js";
3
+ export const OUTPUT_MODES = ["table", "json", "ndjson", "csv"];
4
+ export function colorEnabled(colorFlag, stream, env = process.env) {
5
+ if (colorFlag === false)
6
+ return false;
7
+ if (env.NO_COLOR !== undefined && env.NO_COLOR !== "")
8
+ return false;
9
+ const forced = env.FORCE_COLOR;
10
+ if (forced !== undefined && forced !== "")
11
+ return forced !== "0" && forced !== "false";
12
+ return stream.isTTY === true && env.TERM !== "dumb";
13
+ }
14
+ export function resolveFlags(program) {
15
+ const opts = program.opts();
16
+ const jsonShaping = opts.select !== undefined || opts.compact === true;
17
+ let mode = resolveMode(opts.output, opts.json);
18
+ if (jsonShaping && (mode === "table" || mode === "csv")) {
19
+ if (opts.output !== undefined) {
20
+ throw new UsageError(`--select and --compact shape JSON output; use them with --output json or ndjson, not --output ${mode}.`);
21
+ }
22
+ mode = "json";
23
+ }
24
+ const resolved = { mode, ...colorOptions(opts.color) };
25
+ if (opts.compact)
26
+ resolved.compact = true;
27
+ if (opts.select !== undefined)
28
+ resolved.select = opts.select;
29
+ if (opts.fields !== undefined)
30
+ resolved.fields = opts.fields;
31
+ return resolved;
32
+ }
33
+ export function resolveFlagsSafe(program) {
34
+ try {
35
+ return resolveFlags(program);
36
+ }
37
+ catch {
38
+ return { mode: "table", ...colorOptions(program.opts().color) };
39
+ }
40
+ }
41
+ function colorOptions(colorFlag) {
42
+ return {
43
+ color: colorEnabled(colorFlag, process.stdout),
44
+ errorColor: colorEnabled(colorFlag, process.stderr),
45
+ };
46
+ }
47
+ export function parseOutputMode(value) {
48
+ const match = OUTPUT_MODES.find((mode) => mode === value);
49
+ if (!match) {
50
+ throw new InvalidArgumentError(`Provide one of: ${OUTPUT_MODES.join(", ")}.`);
51
+ }
52
+ return match;
53
+ }
54
+ function resolveMode(output, json) {
55
+ if (output === undefined) {
56
+ return json ? "json" : "table";
57
+ }
58
+ const match = OUTPUT_MODES.find((mode) => mode === output);
59
+ if (!match) {
60
+ throw new Error(`Unsupported output mode "${output}". Provide one of: ${OUTPUT_MODES.join(", ")}.`);
61
+ }
62
+ return match;
63
+ }
64
+ export function parseFields(value) {
65
+ const fields = value.split(",").map((field) => field.trim()).filter(Boolean);
66
+ if (fields.length === 0)
67
+ throw new InvalidArgumentError("Provide at least one field name.");
68
+ return fields;
69
+ }
70
+ export function globalFlags(program) {
71
+ const opts = program.opts();
72
+ const out = {};
73
+ if (opts.workspace)
74
+ out.workspace = opts.workspace;
75
+ if (opts.baseUrl)
76
+ out.baseUrl = opts.baseUrl;
77
+ if (opts.region)
78
+ out.region = opts.region;
79
+ if (opts.subdomain)
80
+ out.subdomain = opts.subdomain;
81
+ if (opts.profile)
82
+ out.profile = opts.profile;
83
+ return out;
84
+ }
@@ -1 +1 @@
1
- export const PACKAGE_VERSION = "5.0.4";
1
+ export const PACKAGE_VERSION = "7.0.0";
package/dist/index.js CHANGED
@@ -1,12 +1,14 @@
1
1
  #!/usr/bin/env node
2
2
  import { realpathSync } from "node:fs";
3
3
  import { pathToFileURL } from "node:url";
4
- import { clockifyErrorDetail } from "clockify-sdk-ts-115/errors";
5
- import { Command, InvalidArgumentError } from "commander";
4
+ import { Argument, Command } from "commander";
6
5
  import { buildClient } from "./client.js";
6
+ import { isClosedPipeError } from "./closed-pipe.js";
7
7
  import { registerApiCommand } from "./commands/api.js";
8
8
  import { registerApprovalsCommand } from "./commands/approvals.js";
9
9
  import { registerAuditLogCommand } from "./commands/auditlog.js";
10
+ import { registerAuthCommand } from "./commands/auth.js";
11
+ import { registerBatchCommand } from "./commands/batch.js";
10
12
  import { registerClientsCommand } from "./commands/clients.js";
11
13
  import { registerDoctorCommand } from "./commands/doctor.js";
12
14
  import { registerEntriesCommand } from "./commands/entries.js";
@@ -14,10 +16,13 @@ import { registerExpensesCommand } from "./commands/expenses.js";
14
16
  import { registerInvoicesCommand } from "./commands/invoices.js";
15
17
  import { leafCommand } from "./commands/leaf-command.js";
16
18
  import { registerLogCommand } from "./commands/log.js";
19
+ import { registerCommandsCommand } from "./commands/manifest.js";
20
+ import { registerOperationsCommand } from "./commands/operations.js";
17
21
  import { registerProjectsCommand } from "./commands/projects.js";
18
22
  import { registerReportsCommand } from "./commands/reports.js";
19
23
  import { registerSchedulingCommand } from "./commands/scheduling.js";
20
24
  import { registerSharedReportsCommand } from "./commands/sharedReports.js";
25
+ import { registerSkillCommand } from "./commands/skill.js";
21
26
  import { registerStartCommand } from "./commands/start.js";
22
27
  import { registerStatusCommand } from "./commands/status.js";
23
28
  import { registerStopCommand } from "./commands/stop.js";
@@ -26,10 +31,14 @@ import { registerTasksCommand } from "./commands/tasks.js";
26
31
  import { registerTimeOffCommand } from "./commands/timeoff.js";
27
32
  import { registerUsersCommand } from "./commands/users.js";
28
33
  import { registerWebhooksCommand } from "./commands/webhooks.js";
29
- import { parseCompletionShell, renderCompletion } from "./completions.js";
30
- import { loadConfig } from "./config.js";
34
+ import { COMPLETION_SHELLS, parseCompletionShell, renderCompletion } from "./completions.js";
35
+ import { loadConfig, requireProfileName } from "./config.js";
36
+ import { reportFailure } from "./failure.js";
37
+ import { parseFields, parseOutputMode, resolveFlags, resolveFlagsSafe } from "./flags.js";
31
38
  import { PACKAGE_VERSION } from "./generated/version.js";
32
- import { AlreadyReportedError, printError, } from "./output.js";
39
+ import { printData } from "./output.js";
40
+ import { outputWasAbandoned, writeFilesInFull } from "./stdout.js";
41
+ export { globalFlags, resolveFlags } from "./flags.js";
33
42
  const defaultServices = {
34
43
  loadConfig,
35
44
  buildClient,
@@ -44,14 +53,18 @@ export function buildProgram(services = defaultServices) {
44
53
  .option("--base-url <url>", "Override Clockify API base URL (or CLOCKIFY_BASE_URL env var). Only a Clockify host or a loopback host is accepted; arbitrary hosts are rejected.")
45
54
  .option("--region <name>", "Clockify routing region: global, eu, us, uk, au, or developer (or CLOCKIFY_REGION env var). Mutually exclusive with --base-url.")
46
55
  .option("--subdomain <label>", "Workspace subdomain for reports routing; requires --region eu/us/uk/au (or CLOCKIFY_SUBDOMAIN env var).")
56
+ .option("--profile <name>", "Profile from `clk115 auth login` (or CLOCKIFY_PROFILE env var).", requireProfileName)
47
57
  .option("--json", "Emit machine-readable JSON instead of human-friendly tables.", false)
48
- .option("--output <mode>", "Output mode: table, json, or ndjson.", parseOutputMode)
49
- .option("--compact", "Print compact JSON without indentation.", false)
50
- .option("--select <path>", "Select a dot-path before printing JSON or NDJSON.")
51
- .option("--no-color", "Disable ANSI color output.")
52
- .showHelpAfterError(true);
58
+ .option("--output <mode>", "Output mode: table, json, ndjson, or csv.", parseOutputMode)
59
+ .option("--fields <list>", "Comma-separated fields to print, in that order; dots reach nested fields.", parseFields)
60
+ .option("--compact", "Print compact JSON without indentation (implies --output json).", false)
61
+ .option("--select <path>", "Select a dot-path before printing JSON or NDJSON (implies --output json).")
62
+ .option("--no-color", "Disable ANSI color output (NO_COLOR and FORCE_COLOR are also honored).");
53
63
  registerApiCommand(program, services);
64
+ registerOperationsCommand(program, services);
65
+ registerBatchCommand(program, services);
54
66
  registerStatusCommand(program, services);
67
+ registerAuthCommand(program, services);
55
68
  registerDoctorCommand(program, services);
56
69
  registerStartCommand(program, services);
57
70
  registerStopCommand(program, services);
@@ -71,119 +84,52 @@ export function buildProgram(services = defaultServices) {
71
84
  registerSharedReportsCommand(program, services);
72
85
  registerUsersCommand(program, services);
73
86
  registerApprovalsCommand(program, services);
87
+ registerCommandsCommand(program, services);
88
+ registerSkillCommand(program, services);
74
89
  leafCommand(program, "completion", "read")
75
- .argument("[shell]", "Shell to generate completion for: zsh, bash, or fish.", "zsh")
90
+ .addArgument(new Argument("[shell]", "Shell to generate completion for: zsh, bash, or fish.")
91
+ .choices(COMPLETION_SHELLS)
92
+ .argParser(parseCompletionShell)
93
+ .default("zsh"))
76
94
  .description("Print shell completion script for zsh, bash, or fish.")
77
95
  .addHelpText("after", "\nExamples:\n" +
78
96
  " $ clk115 completion zsh >> ~/.zshrc\n" +
79
97
  " $ clk115 completion bash\n")
80
98
  .action((shell) => {
81
- console.log(renderCompletion(parseCompletionShell(shell)));
99
+ const output = resolveFlags(program);
100
+ const script = renderCompletion(parseCompletionShell(shell), program);
101
+ if (output.mode === "json" || output.mode === "ndjson")
102
+ printData(script, output);
103
+ else
104
+ console.log(script);
82
105
  });
83
106
  return program;
84
107
  }
85
- function isTty(stream) {
86
- return stream.isTTY === true;
87
- }
88
- export function resolveFlags(program) {
89
- const opts = program.opts();
90
- const mode = resolveMode(opts.output, opts.json);
91
- const resolved = {
92
- mode,
93
- color: opts.color !== false && isTty(process.stdout),
94
- };
95
- if (opts.compact)
96
- resolved.compact = true;
97
- if (opts.select !== undefined)
98
- resolved.select = opts.select;
99
- return resolved;
100
- }
101
- function resolveFlagsSafe(program) {
102
- try {
103
- return resolveFlags(program);
104
- }
105
- catch {
106
- const opts = program.opts();
107
- return {
108
- mode: "table",
109
- color: opts.color !== false && isTty(process.stdout),
110
- };
111
- }
112
- }
113
- function parseOutputMode(value) {
114
- const modes = ["table", "json", "ndjson"];
115
- const match = modes.find((mode) => mode === value);
116
- if (!match) {
117
- throw new InvalidArgumentError("Provide one of: table, json, ndjson.");
118
- }
119
- return match;
120
- }
121
- function resolveMode(output, json) {
122
- if (output === undefined) {
123
- return json ? "json" : "table";
124
- }
125
- const modes = ["table", "json", "ndjson"];
126
- const match = modes.find((mode) => mode === output);
127
- if (!match) {
128
- throw new Error(`Unsupported output mode "${output}". Provide one of: table, json, ndjson.`);
129
- }
130
- return match;
131
- }
132
- export function globalFlags(program) {
133
- const opts = program.opts();
134
- const out = {};
135
- if (opts.workspace)
136
- out.workspace = opts.workspace;
137
- if (opts.baseUrl)
138
- out.baseUrl = opts.baseUrl;
139
- if (opts.region)
140
- out.region = opts.region;
141
- if (opts.subdomain)
142
- out.subdomain = opts.subdomain;
143
- return out;
144
- }
145
108
  export async function main(argv, services = defaultServices) {
146
109
  const program = buildProgram(services);
147
- const applyExitOverride = (cmd) => {
110
+ let active;
111
+ const prepare = (cmd) => {
148
112
  cmd.exitOverride();
113
+ cmd.configureOutput({
114
+ outputError: () => {
115
+ active = cmd;
116
+ },
117
+ });
149
118
  for (const sub of cmd.commands)
150
- applyExitOverride(sub);
119
+ prepare(sub);
151
120
  };
152
- applyExitOverride(program);
121
+ prepare(program);
122
+ program.hook("preAction", (_root, actionCommand) => {
123
+ active = actionCommand;
124
+ });
153
125
  try {
154
126
  await program.parseAsync(argv);
155
127
  return 0;
156
128
  }
157
129
  catch (err) {
158
- if (isCommanderHelpError(err)) {
159
- return err.exitCode ?? 0;
160
- }
161
- if (err instanceof AlreadyReportedError) {
162
- return 1;
163
- }
164
- const message = clockifyErrorDetail(err);
165
- const statusCode = err.statusCode;
166
- const flags = resolveFlagsSafe(program);
167
- printError(message, { mode: flags.mode, color: flags.color }, statusCode);
168
- return isCommanderUsageError(err) ? 2 : 1;
130
+ return reportFailure(err, resolveFlagsSafe(program), active);
169
131
  }
170
132
  }
171
- function isCommanderHelpError(err) {
172
- return (typeof err === "object" &&
173
- err !== null &&
174
- "code" in err &&
175
- typeof err.code === "string" &&
176
- (err.code === "commander.helpDisplayed" ||
177
- err.code === "commander.help" ||
178
- err.code === "commander.version"));
179
- }
180
- function isCommanderUsageError(err) {
181
- return (typeof err === "object" &&
182
- err !== null &&
183
- "code" in err &&
184
- typeof err.code === "string" &&
185
- err.code.startsWith("commander."));
186
- }
187
133
  function isDirectInvocation(argv1) {
188
134
  if (argv1 === undefined)
189
135
  return false;
@@ -194,14 +140,28 @@ function isDirectInvocation(argv1) {
194
140
  return false;
195
141
  }
196
142
  }
197
- const invokedDirectly = typeof process !== "undefined" &&
198
- Array.isArray(process.argv) &&
199
- isDirectInvocation(process.argv[1]);
200
- if (invokedDirectly) {
143
+ function leaveAfterStderr() {
144
+ const leave = () => {
145
+ process.exit();
146
+ };
147
+ process.stderr.write("", leave);
148
+ setTimeout(leave, 3000);
149
+ }
150
+ if (isDirectInvocation(process.argv[1])) {
151
+ writeFilesInFull();
152
+ process.stderr.on("error", () => undefined);
153
+ process.stdout.on("error", (err) => {
154
+ if (isClosedPipeError(err) || process.exitCode === 1)
155
+ return;
156
+ console.error(`fatal: the output could not be written: ${err.message}`);
157
+ process.exitCode = 1;
158
+ });
201
159
  main(process.argv).then((code) => {
202
- process.exitCode = code;
160
+ process.exitCode ||= code;
161
+ if (outputWasAbandoned())
162
+ leaveAfterStderr();
203
163
  }, (err) => {
204
- console.error(`fatal: ${clockifyErrorDetail(err)}`);
164
+ console.error(`fatal: ${err instanceof Error ? err.message : String(err)}`);
205
165
  process.exitCode = 1;
206
166
  });
207
167
  }
@@ -0,0 +1,28 @@
1
+ import { constants } from "node:os";
2
+ const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
3
+ const UNREAD_OUTPUT_MS = 1000;
4
+ export const signalExitCode = (signal) => 128 + constants.signals[signal];
5
+ export function watchInterrupts(onStop, onQuit) {
6
+ let exitCode;
7
+ const abandoned = new AbortController();
8
+ const release = () => {
9
+ for (const signal of SIGNALS)
10
+ process.off(signal, handle);
11
+ };
12
+ const handle = (signal) => {
13
+ if (exitCode === undefined) {
14
+ exitCode = signalExitCode(signal);
15
+ onStop();
16
+ }
17
+ else if (signal !== "SIGHUP") {
18
+ release();
19
+ onQuit();
20
+ setTimeout(() => {
21
+ abandoned.abort();
22
+ }, UNREAD_OUTPUT_MS).unref();
23
+ }
24
+ };
25
+ for (const signal of SIGNALS)
26
+ process.on(signal, handle);
27
+ return { exitCode: () => exitCode, abandoned: abandoned.signal, release };
28
+ }