@apet97/clockify-cli-115 6.0.0 → 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 (44) hide show
  1. package/README.md +167 -21
  2. package/dist/client.js +30 -7
  3. package/dist/commands/api.js +44 -76
  4. package/dist/commands/approvals.js +2 -5
  5. package/dist/commands/auth.js +229 -0
  6. package/dist/commands/batch.js +226 -0
  7. package/dist/commands/clients.js +11 -65
  8. package/dist/commands/doctor.js +65 -66
  9. package/dist/commands/expenses.js +21 -24
  10. package/dist/commands/helpers.js +46 -2
  11. package/dist/commands/leaf-command.js +7 -0
  12. package/dist/commands/manifest.js +63 -0
  13. package/dist/commands/operations.js +271 -0
  14. package/dist/commands/projects.js +10 -23
  15. package/dist/commands/reports.js +22 -7
  16. package/dist/commands/shared-report-body.js +3 -81
  17. package/dist/commands/sharedReports.js +1 -21
  18. package/dist/commands/skill.js +85 -0
  19. package/dist/commands/status.js +18 -12
  20. package/dist/commands/stop.js +3 -12
  21. package/dist/commands/tags.js +5 -7
  22. package/dist/commands/tasks.js +19 -120
  23. package/dist/commands/users.js +4 -14
  24. package/dist/commands/webhook-delivery.js +331 -0
  25. package/dist/commands/webhooks.js +31 -97
  26. package/dist/completions.js +2 -1
  27. package/dist/config.js +166 -63
  28. package/dist/credentials.js +164 -0
  29. package/dist/failure.js +4 -9
  30. package/dist/flags.js +14 -4
  31. package/dist/generated/version.js +1 -1
  32. package/dist/index.js +38 -14
  33. package/dist/interrupts.js +28 -0
  34. package/dist/output.js +137 -48
  35. package/dist/receipt.js +2 -10
  36. package/dist/stdin.js +6 -0
  37. package/dist/stdout.js +38 -0
  38. package/dist/write-outcome.js +1 -1
  39. package/package.json +5 -3
  40. package/plugin/.claude-plugin/plugin.json +16 -0
  41. package/plugin/skills/clockify-cli/SKILL.md +88 -0
  42. package/plugin/skills/clockify-mcp/SKILL.md +48 -0
  43. package/plugin/skills/clockify-sdk/SKILL.md +85 -0
  44. package/dist/error-codes.js +0 -300
@@ -0,0 +1,229 @@
1
+ import { entityId } from "clockify-sdk-ts-115/operation-receipt";
2
+ import { requireHeaderValue, requireRoute } from "../client.js";
3
+ import { loadProfiles, loginConfig, missingApiKey, requireProfile, requireProfileName, saveProfile, saveProfiles, selectedProfile, } from "../config.js";
4
+ import { UsageError } from "../failure.js";
5
+ import { globalFlags, resolveFlags } from "../flags.js";
6
+ import { signalExitCode } from "../interrupts.js";
7
+ import { AlreadyReportedError, fixedColumns, printObject, printRecords, printWarning } from "../output.js";
8
+ import { printReceipt } from "../receipt.js";
9
+ import { resolveBaseContext, rootProgram } from "./helpers.js";
10
+ import { leafCommand } from "./leaf-command.js";
11
+ const STATUS_KEYS = ["ok", "source", "profile", "host", "workspaceId", "userId", "user"];
12
+ const LIST_KEYS = ["profile", "current", "host", "workspaceId", "key"];
13
+ async function keychain(services) {
14
+ const credentials = await import("../credentials.js");
15
+ return { ...credentials, store: services.credentials ?? credentials.systemCredentialStore };
16
+ }
17
+ async function reachableWorkspace(client, wanted) {
18
+ const workspaces = (await client.workspaces.list());
19
+ const found = workspaces.find(({ id }) => id === wanted);
20
+ if (found?.id !== undefined)
21
+ return { id: found.id, name: found.name ?? "" };
22
+ const choices = workspaces.map(({ id, name }) => `${id ?? "?"} (${name ?? "unnamed"})`).join(", ");
23
+ throw new UsageError(wanted === undefined
24
+ ? `Clockify names no current workspace for this key; pass --workspace with one of: ${choices}.`
25
+ : `This key cannot reach workspace ${wanted}; pass --workspace with one of: ${choices}.`);
26
+ }
27
+ function childEnvironment({ workspaceId, baseUrl, region, subdomain }, apiKey) {
28
+ const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !/^CLOCKIFY_(?:API_KEY|ADDON_TOKEN|WORKSPACE_ID|BASE_URL|REGION|SUBDOMAIN|PROFILE)$/.test(name)));
29
+ return {
30
+ ...env,
31
+ CLOCKIFY_API_KEY: apiKey,
32
+ ...(workspaceId !== undefined && { CLOCKIFY_WORKSPACE_ID: workspaceId }),
33
+ ...(baseUrl !== undefined && { CLOCKIFY_BASE_URL: baseUrl }),
34
+ ...((region !== undefined || baseUrl === undefined) && { CLOCKIFY_REGION: region ?? "global" }),
35
+ ...(subdomain !== undefined && { CLOCKIFY_SUBDOMAIN: subdomain }),
36
+ };
37
+ }
38
+ async function runChild(command, args, env) {
39
+ const { spawn } = await import("node:child_process");
40
+ const child = spawn(command, args, { env, stdio: "inherit" });
41
+ const onTerminal = [process.stdin, process.stdout, process.stderr].some(({ isTTY }) => isTTY);
42
+ const forward = (signal) => {
43
+ if (signal !== "SIGINT" || !onTerminal)
44
+ child.kill(signal);
45
+ };
46
+ const signals = ["SIGTERM", "SIGHUP", "SIGINT"];
47
+ for (const signal of signals)
48
+ process.on(signal, forward);
49
+ try {
50
+ return await new Promise((resolve, reject) => {
51
+ child.on("error", (err) => {
52
+ reject(new Error(`Could not run ${command}: ${err.message}`));
53
+ });
54
+ child.on("close", (code, signal) => {
55
+ resolve(code ?? (signal === null ? 1 : signalExitCode(signal)));
56
+ });
57
+ });
58
+ }
59
+ finally {
60
+ for (const signal of signals)
61
+ process.off(signal, forward);
62
+ }
63
+ }
64
+ export const registerAuthCommand = (program, services) => {
65
+ const auth = program.command("auth").description("Keep API keys in the OS keychain, one per named profile.");
66
+ leafCommand(auth, "login", "local")
67
+ .description("Check an API key with Clockify, then keep it in the OS keychain under a profile.")
68
+ .addHelpText("after", "\nExamples:\n" +
69
+ " $ clk115 auth login\n" +
70
+ " $ pass show clockify/sandbox | clk115 auth login --profile sandbox --workspace 64c777ddd3fcab07cfbb210c\n" +
71
+ "\nThe key is read from stdin, or from a hidden prompt in a terminal. It is never an argument and never in the rc file.\n" +
72
+ "The first profile becomes the current one. CLOCKIFY_API_KEY in the environment wins over the current profile.\n" +
73
+ "A new profile uses the global host unless you pass --region, --subdomain or --base-url.\n")
74
+ .action(async function () {
75
+ const root = rootProgram(this);
76
+ const flags = globalFlags(root);
77
+ const output = resolveFlags(root);
78
+ const known = loadProfiles();
79
+ const name = requireProfileName(selectedProfile(flags, known.current) ?? "default");
80
+ const config = loginConfig(name, flags, known.profiles);
81
+ const { credentialAccount, credentialHost, readSecret, requireStorableKey, store, storeVerified } = await keychain(services);
82
+ const account = credentialAccount(config);
83
+ if (account === undefined)
84
+ throw new UsageError(`The host "${credentialHost(config)}" cannot name a stored key.`);
85
+ const credentials = store();
86
+ const apiKey = requireStorableKey(await (services.readSecret ?? readSecret)());
87
+ const client = await services.buildClient({ ...config, apiKey });
88
+ const user = await client.users.getCurrentUser();
89
+ const workspace = await reachableWorkspace(client, config.workspaceId ?? user.activeWorkspace ?? user.defaultWorkspace);
90
+ const undo = await storeVerified(credentials, account, apiKey);
91
+ const { profile: _name, ...routing } = { ...config, workspaceId: workspace.id };
92
+ let saved;
93
+ try {
94
+ saved = saveProfile(name, routing);
95
+ }
96
+ catch (err) {
97
+ await undo();
98
+ throw err;
99
+ }
100
+ const { current, previous } = saved;
101
+ const replaced = previous && credentialAccount({ ...previous, profile: name });
102
+ const warnings = process.env.CLOCKIFY_API_KEY?.trim() ? ["CLOCKIFY_API_KEY is set and wins unless you pass --profile."] : [];
103
+ if (replaced !== undefined && replaced !== account) {
104
+ await credentials.delete(replaced).catch((err) => {
105
+ const reason = err instanceof Error ? err.message : String(err);
106
+ warnings.push(`The replaced key, ${replaced}, is still in ${credentials.name}: ${reason}`);
107
+ });
108
+ }
109
+ for (const warning of warnings)
110
+ printWarning(warning, output);
111
+ printReceipt({
112
+ ok: true,
113
+ action: "auth.login",
114
+ entity: "profile",
115
+ ids: { profile: name, workspaceId: workspace.id, userId: entityId(user) ?? "" },
116
+ data: {
117
+ profile: name,
118
+ current: current === name,
119
+ host: credentialHost(config),
120
+ workspaceId: workspace.id,
121
+ workspace: workspace.name,
122
+ user: user.name,
123
+ storedIn: credentials.name,
124
+ },
125
+ warnings,
126
+ next: [
127
+ current === name
128
+ ? { command: "clk115 status", reason: "Show the workspace and the running timer." }
129
+ : { command: `clk115 auth use ${name}`, reason: `The current profile is still ${current}.` },
130
+ ],
131
+ }, output);
132
+ });
133
+ leafCommand(auth, "status", "read")
134
+ .description("Show which credential is used, and check it with Clockify.")
135
+ .addHelpText("after", "\nExamples:\n $ clk115 auth status\n $ clk115 auth status --profile sandbox --json\n")
136
+ .action(async function () {
137
+ const output = fixedColumns(STATUS_KEYS, resolveFlags(rootProgram(this)));
138
+ const { client, config } = await resolveBaseContext(this, services, output);
139
+ const { credentialHost } = await keychain(services);
140
+ const user = await client.users.getCurrentUser();
141
+ printObject({
142
+ ok: true,
143
+ source: config.apiKey === undefined ? "profile" : "CLOCKIFY_API_KEY",
144
+ ...(config.profile !== undefined && { profile: config.profile }),
145
+ host: credentialHost(config),
146
+ workspaceId: config.workspaceId ?? null,
147
+ userId: entityId(user) ?? null,
148
+ user: user.name,
149
+ }, output);
150
+ });
151
+ leafCommand(auth, "list", "read")
152
+ .description("List the profiles and whether each has a key in the keychain.")
153
+ .addHelpText("after", "\nExamples:\n $ clk115 auth list\n $ clk115 auth list --json\n")
154
+ .action(async function () {
155
+ const output = fixedColumns(LIST_KEYS, resolveFlags(rootProgram(this)));
156
+ const { current, profiles } = loadProfiles();
157
+ const { credentialHost, storedApiKey, store } = await keychain(services);
158
+ const rows = [];
159
+ for (const [profile, routing] of Object.entries(profiles)) {
160
+ const key = await storedApiKey({ ...routing, profile }, store);
161
+ rows.push({
162
+ profile,
163
+ current: profile === current,
164
+ host: credentialHost(routing),
165
+ workspaceId: routing.workspaceId ?? "",
166
+ key: key === undefined ? "missing" : "stored",
167
+ });
168
+ }
169
+ printRecords(rows, output);
170
+ });
171
+ leafCommand(auth, "use <profile>", "local")
172
+ .description("Make a profile the current one.")
173
+ .addHelpText("after", "\nExamples:\n $ clk115 auth use sandbox\n")
174
+ .action(function (name) {
175
+ const output = resolveFlags(rootProgram(this));
176
+ const { profiles } = loadProfiles();
177
+ const { workspaceId } = requireProfile(profiles, name);
178
+ saveProfiles({ current: name, profiles });
179
+ printReceipt({
180
+ ok: true,
181
+ action: "auth.use",
182
+ entity: "profile",
183
+ ids: { profile: name },
184
+ data: { profile: name, current: true, workspaceId: workspaceId ?? "" },
185
+ }, output);
186
+ });
187
+ leafCommand(auth, "logout", "local")
188
+ .description("Delete a profile and its key from the keychain. The key itself stays valid in Clockify.")
189
+ .addHelpText("after", "\nExamples:\n $ clk115 auth logout\n $ clk115 auth logout --profile sandbox\n")
190
+ .action(async function () {
191
+ const root = rootProgram(this);
192
+ const output = resolveFlags(root);
193
+ const { current, profiles } = loadProfiles();
194
+ const name = selectedProfile(globalFlags(root), current);
195
+ if (name === undefined)
196
+ throw new UsageError("No profile is selected; pass --profile <name>.");
197
+ const { [name]: _removed, ...rest } = profiles;
198
+ const { credentialAccount, store } = await keychain(services);
199
+ const account = credentialAccount({ ...requireProfile(profiles, name), profile: name });
200
+ const deleted = account !== undefined && (await store().delete(account));
201
+ saveProfiles({ current: current === name ? undefined : current, profiles: rest });
202
+ printReceipt({
203
+ ok: true,
204
+ action: "auth.logout",
205
+ entity: "profile",
206
+ ids: { profile: name },
207
+ data: { profile: name, key: deleted ? "deleted" : "was not stored" },
208
+ changed: { deleted: [{ type: "profile", id: name }] },
209
+ }, output);
210
+ });
211
+ leafCommand(auth, "exec <command...>", "local")
212
+ .description("Run a program with the selected credential in its environment.")
213
+ .addHelpText("after", "\nExamples:\n" +
214
+ " $ clk115 auth exec -- clockify115-mcp\n" +
215
+ " $ clk115 auth exec --profile sandbox -- node nightly-export.mjs\n" +
216
+ "\nThe program gets CLOCKIFY_API_KEY with the workspace and host it belongs to. The key, add-on token, profile,\n" +
217
+ "workspace and host variables of this environment are not passed on.\n")
218
+ .action(async function ([command = "", ...args]) {
219
+ const config = services.loadConfig(globalFlags(rootProgram(this)));
220
+ await requireRoute(config);
221
+ const { storedApiKey, store } = await keychain(services);
222
+ const apiKey = config.apiKey ?? (await storedApiKey(config, store));
223
+ if (apiKey === undefined)
224
+ throw missingApiKey(config);
225
+ const code = await runChild(command, args, childEnvironment(config, requireHeaderValue(apiKey)));
226
+ if (code !== 0)
227
+ throw new AlreadyReportedError(code);
228
+ });
229
+ };
@@ -0,0 +1,226 @@
1
+ import { setTimeout as delay } from "node:timers/promises";
2
+ import { Option } from "commander";
3
+ import { requireWorkspaceId } from "../config.js";
4
+ import { UsageError } from "../failure.js";
5
+ import { globalFlags, resolveFlags } from "../flags.js";
6
+ import { watchInterrupts } from "../interrupts.js";
7
+ import { AlreadyReportedError, dataLines, fixedColumns, printWarning, rowLine, warnUnknownPaths } from "../output.js";
8
+ import { writeLine } from "../stdout.js";
9
+ import { parseIntArg, readTextInput, rootProgram } from "./helpers.js";
10
+ import { declareMutation, leafCommand } from "./leaf-command.js";
11
+ import { answersWithFile, requireOperation, resolvedRequest, responseData } from "./operations.js";
12
+ const ROW_KEYS = new Set(["operation", "path", "query", "body", "id"]);
13
+ const RESULT_KEYS = ["index", "id", "operation", "outcome", "data", "error", "code", "retryAfterSeconds", "recovery"];
14
+ const DRY_RUN_KEYS = ["index", "id", "operation", "effect", "method", "path", "query", "body", "dryRun"];
15
+ const SHOWN_PROBLEMS = 20;
16
+ const RATE_LIMIT_WAITS = 3;
17
+ const LONGEST_WAIT_MS = 60_000;
18
+ const IS_A_FILE = "The response is a file; use `clk115 operations call --output-file`.";
19
+ async function parseRows(text, workspaceId) {
20
+ const { operationInputProblems } = await import("clockify-sdk-ts-115/operations");
21
+ const rows = [];
22
+ const problems = [];
23
+ for (const [number, line] of text.split("\n").entries()) {
24
+ if (line.trim() === "")
25
+ continue;
26
+ const at = `line ${number + 1}`;
27
+ let value;
28
+ try {
29
+ const parsed = JSON.parse(line);
30
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
31
+ throw new Error("not a JSON object");
32
+ value = parsed;
33
+ const unknown = Object.keys(value).filter((key) => !ROW_KEYS.has(key));
34
+ if (unknown.length > 0)
35
+ throw new Error(`unknown key ${unknown.join(", ")}; use ${[...ROW_KEYS].join(", ")}`);
36
+ if (typeof value.operation !== "string")
37
+ throw new Error("operation is missing");
38
+ if (value.id !== undefined && typeof value.id !== "string")
39
+ throw new Error("id is not a string");
40
+ }
41
+ catch (err) {
42
+ problems.push(`${at}: ${err.message}`);
43
+ continue;
44
+ }
45
+ try {
46
+ const operation = await requireOperation(value.operation);
47
+ if (answersWithFile(operation))
48
+ throw new UsageError(IS_A_FILE);
49
+ const input = {
50
+ ...(operation.path.includes("{workspaceId}") && { workspaceId: workspaceId() }),
51
+ ...(value.path !== undefined && { path: value.path }),
52
+ ...(value.query !== undefined && { query: value.query }),
53
+ ...(value.body !== undefined && { body: value.body }),
54
+ };
55
+ problems.push(...operationInputProblems(operation, input).map((problem) => `${at}: ${problem}`));
56
+ rows.push({ index: rows.length, ...(value.id !== undefined && { id: value.id }), operation, input });
57
+ }
58
+ catch (err) {
59
+ if (!(err instanceof UsageError))
60
+ throw err;
61
+ problems.push(`${at}: ${err.message}`);
62
+ }
63
+ }
64
+ if (problems.length > 0) {
65
+ const more = problems.length > SHOWN_PROBLEMS ? ` (and ${problems.length - SHOWN_PROBLEMS} more)` : "";
66
+ throw new UsageError(`Nothing was sent. ${problems.slice(0, SHOWN_PROBLEMS).join("; ")}${more}.`);
67
+ }
68
+ if (rows.length === 0)
69
+ throw new UsageError("The batch has no rows; provide one JSON object per line.");
70
+ return rows;
71
+ }
72
+ function described({ index, id, operation }) {
73
+ return { index, ...(id !== undefined && { id }), operation: operation.name };
74
+ }
75
+ async function loadSdk() {
76
+ const operations = await import("clockify-sdk-ts-115/operations");
77
+ return { ...operations, ...(await import("clockify-sdk-ts-115/errors")) };
78
+ }
79
+ const INTERRUPTED = "interrupted";
80
+ const interrupted = ({ stop }) => stop.signal.reason === INTERRUPTED;
81
+ async function attempt(sdk, client, row, control) {
82
+ const { stop, quit } = control;
83
+ for (let waits = 0;; waits += 1) {
84
+ try {
85
+ const options = { maxRetries: 0, abortSignal: quit.signal };
86
+ const data = await responseData(row.operation, await sdk.callOperation(client, row.operation.name, row.input, options));
87
+ if (Buffer.isBuffer(data))
88
+ return { ...described(row), outcome: "failed", error: IS_A_FILE, code: "error" };
89
+ return { ...described(row), outcome: "ok", data: data ?? null };
90
+ }
91
+ catch (err) {
92
+ const promoted = sdk.promoteApiError(err);
93
+ if (promoted instanceof sdk.RateLimitError) {
94
+ const wait = promoted.retryAfterMs ?? 1000 * 2 ** waits;
95
+ if (waits < RATE_LIMIT_WAITS && wait <= LONGEST_WAIT_MS) {
96
+ await delay(wait, undefined, { signal: stop.signal }).catch(() => undefined);
97
+ if (!stop.signal.aborted)
98
+ continue;
99
+ if (interrupted(control))
100
+ control.cut += 1;
101
+ }
102
+ stop.abort();
103
+ }
104
+ if (quit.signal.aborted)
105
+ control.cut += 1;
106
+ const outcome = row.operation.effect === "read"
107
+ ? "failed"
108
+ : sdk.classifyWriteOutcome(err) === "definitely-failed" ? "rejected" : "unknown";
109
+ const classified = sdk.classifyClockifyError(err);
110
+ return {
111
+ ...described(row),
112
+ outcome,
113
+ error: sdk.clockifyErrorDetail(err),
114
+ code: classified?.code ?? "error",
115
+ ...(promoted instanceof sdk.RateLimitError &&
116
+ promoted.retryAfterMs !== undefined && { retryAfterSeconds: Math.ceil(promoted.retryAfterMs / 1000) }),
117
+ ...(outcome === "unknown"
118
+ ? { recovery: "Read the record back before sending this row again. The write may have applied." }
119
+ : classified && { recovery: classified.recovery }),
120
+ };
121
+ }
122
+ }
123
+ }
124
+ export const registerBatchCommand = (program, services) => {
125
+ leafCommand(program, "batch", "destructive")
126
+ .description("Run many operations from NDJSON rows. Every row is checked before the first request.")
127
+ .argument("[source]", "@file, or - for stdin.", "-")
128
+ .addOption(new Option("--on-error <action>", "What to do after a failed row. A write with an unknown outcome always stops the batch.")
129
+ .choices(["stop", "continue"])
130
+ .default("stop"))
131
+ .addOption(new Option("--concurrency <n>", "Requests in flight, 1 to 8.").argParser(parseIntArg).default(1))
132
+ .option("--max-requests <n>", "Refuse a batch with more rows.", parseIntArg, 1000)
133
+ .option("--dry-run", "Check the rows and print the requests without sending them. Needs no credentials.", false)
134
+ .addHelpText("after", "\nExamples:\n" +
135
+ ' $ echo \'{"operation":"tags.create","body":{"name":"focus"}}\' | clk115 batch --dry-run\n' +
136
+ " $ clk115 batch @rows.ndjson --on-error continue > results.ndjson\n" +
137
+ "\nA row is {operation, path?, query?, body?, id?}. A result is {index, id?, operation, outcome, data | error}.\n" +
138
+ "Outcomes: ok, rejected (nothing changed), unknown (read back first), failed (a read), skipped (not sent).\n" +
139
+ "A row is sent again only after a 429, up to three times, when the wait is at most a minute. Interrupting the\n" +
140
+ "batch lets the requests in flight finish; interrupting it again gives them up. Every row is reported either\n" +
141
+ "way. Exit code 1 means that at least one row is not ok, 2 that nothing was sent, and 128 plus the signal\n" +
142
+ "number that an interrupt cut the batch short.\n")
143
+ .action(async function (source, opts) {
144
+ declareMutation(this, false);
145
+ const root = rootProgram(this);
146
+ const output = fixedColumns(opts.dryRun ? DRY_RUN_KEYS : RESULT_KEYS, resolveFlags(root));
147
+ if (opts.concurrency > 8)
148
+ throw new UsageError("--concurrency must be at most 8.");
149
+ if (source !== "-" && !source.startsWith("@"))
150
+ throw new UsageError("Provide the rows as @file or - for stdin.");
151
+ const config = services.loadConfig(globalFlags(root));
152
+ const rows = await parseRows((await readTextInput(source, "batch")) ?? "", () => requireWorkspaceId(config));
153
+ if (rows.length > opts.maxRequests) {
154
+ throw new UsageError(`Nothing was sent. The batch has ${rows.length} rows; pass --max-requests ${rows.length} to allow it.`);
155
+ }
156
+ const streams = output.mode === "table" || output.mode === "ndjson";
157
+ if (opts.dryRun) {
158
+ const requests = rows.map((row) => ({ ...described(row), ...resolvedRequest(row.operation, row.input), dryRun: true }));
159
+ for (const line of streams ? requests.map((request) => rowLine(request, output)) : dataLines(requests, output)) {
160
+ await writeLine(line);
161
+ }
162
+ if (streams)
163
+ warnUnknownPaths(requests, output);
164
+ return;
165
+ }
166
+ const client = await services.buildClient(config, this);
167
+ const sdk = await loadSdk();
168
+ const counts = { ok: 0, rejected: 0, unknown: 0, failed: 0, skipped: 0 };
169
+ const results = [];
170
+ let unwritten = 0;
171
+ const control = { stop: new AbortController(), quit: new AbortController(), cut: 0 };
172
+ const { stop, quit } = control;
173
+ const interrupts = watchInterrupts(() => {
174
+ printWarning("Waiting for the requests in flight. Interrupt again to give them up.", output);
175
+ stop.abort(INTERRUPTED);
176
+ }, () => {
177
+ quit.abort();
178
+ });
179
+ const report = async (lines) => {
180
+ try {
181
+ for (const line of lines)
182
+ await writeLine(line, interrupts.abandoned);
183
+ }
184
+ catch {
185
+ unwritten += 1;
186
+ stop.abort();
187
+ }
188
+ };
189
+ let next = 0;
190
+ const worker = async () => {
191
+ while (next < rows.length) {
192
+ const row = rows[next++];
193
+ const result = stop.signal.aborted
194
+ ? { ...described(row), outcome: "skipped" }
195
+ : await attempt(sdk, client, row, control);
196
+ if (result.outcome === "skipped" && interrupted(control))
197
+ control.cut += 1;
198
+ counts[result.outcome] += 1;
199
+ if (result.outcome === "unknown" || (result.outcome !== "ok" && opts.onError === "stop"))
200
+ stop.abort();
201
+ results.push(result);
202
+ if (streams)
203
+ await report([rowLine(result, output)]);
204
+ }
205
+ };
206
+ try {
207
+ await Promise.all(Array.from({ length: Math.min(opts.concurrency, rows.length) }, worker));
208
+ if (!streams)
209
+ await report(dataLines(results, output));
210
+ }
211
+ finally {
212
+ interrupts.release();
213
+ }
214
+ if (unwritten > 0) {
215
+ printWarning("The output could not be written. Every result:", output);
216
+ for (const result of results)
217
+ console.error(JSON.stringify(result));
218
+ }
219
+ else if (streams)
220
+ warnUnknownPaths(results, output);
221
+ if (counts.ok === rows.length && unwritten === 0)
222
+ return;
223
+ printWarning(Object.entries(counts).filter(([, count]) => count > 0).map(([outcome, count]) => `${count} ${outcome}`).join(", "), output);
224
+ throw new AlreadyReportedError(control.cut > 0 || interrupts.abandoned.aborted ? interrupts.exitCode() : 1);
225
+ });
226
+ };
@@ -1,4 +1,5 @@
1
1
  import { archiveThenDeleteClient } from "clockify-sdk-ts-115/ensure";
2
+ import { clientUpdate } from "clockify-sdk-ts-115/updates";
2
3
  import { PartialDeleteError, UsageError } from "../failure.js";
3
4
  import { printObject, printRecords } from "../output.js";
4
5
  import { printReceipt } from "../receipt.js";
@@ -8,51 +9,6 @@ import { leafCommand } from "./leaf-command.js";
8
9
  function quoteShellArgument(value) {
9
10
  return `'${value.replaceAll("'", "'\"'\"'")}'`;
10
11
  }
11
- function requireClientName(value, source) {
12
- if (typeof value !== "string" || value.trim() === "") {
13
- throw new Error(`${source} is missing the required client name; refusing to mutate.`);
14
- }
15
- return value;
16
- }
17
- function optionalClientString(value, field) {
18
- if (value === undefined)
19
- return undefined;
20
- if (typeof value !== "string") {
21
- throw new Error(`Current client has invalid ${field}; refusing to mutate.`);
22
- }
23
- return value;
24
- }
25
- function optionalNullableClientString(value, field) {
26
- if (value === null)
27
- return undefined;
28
- return optionalClientString(value, field);
29
- }
30
- function requiredClientArchived(value) {
31
- if (typeof value !== "boolean") {
32
- throw new Error("Current client has invalid or missing archived state; refusing to mutate.");
33
- }
34
- return value;
35
- }
36
- function reconstructClientBody(current, suppliedName) {
37
- const body = {
38
- name: suppliedName !== undefined
39
- ? requireClientName(suppliedName, "Client update request")
40
- : requireClientName(current.name, "Current client"),
41
- };
42
- const address = optionalNullableClientString(current.address, "address");
43
- if (address !== undefined)
44
- body.address = address;
45
- if (current.ccEmails != null)
46
- body.ccEmails = current.ccEmails;
47
- const email = optionalNullableClientString(current.email, "email");
48
- if (email !== undefined)
49
- body.email = email;
50
- const note = optionalNullableClientString(current.note, "note");
51
- if (note !== undefined)
52
- body.note = note;
53
- body.archived = requiredClientArchived(current.archived);
54
- return body;
55
- }
56
12
  export const registerClientsCommand = (program, services) => {
57
13
  const clients = program.command("clients").description("Manage clients.");
58
14
  leafCommand(clients, "list", "read")
@@ -146,25 +102,15 @@ export const registerClientsCommand = (program, services) => {
146
102
  throw new UsageError("clients.update needs a change: provide at least one client field.");
147
103
  }
148
104
  const { client, workspaceId, output } = await resolveContext(this, services);
149
- const current = (await client.clients.get({
150
- workspaceId,
151
- clientId: id,
152
- }));
153
- const body = reconstructClientBody(current, opts.name);
154
- let changed = opts.name !== undefined && opts.name !== current.name;
155
- if (opts.note !== undefined) {
156
- changed = changed || opts.note !== body.note;
157
- body.note = opts.note;
158
- }
159
- if (opts.address !== undefined) {
160
- changed = changed || opts.address !== body.address;
161
- body.address = opts.address;
162
- }
163
- if (opts.archived !== undefined) {
164
- changed = changed || opts.archived !== body.archived;
165
- body.archived = opts.archived;
166
- }
167
- if (!changed) {
105
+ const patch = {
106
+ name: opts.name,
107
+ note: opts.note,
108
+ address: opts.address,
109
+ archived: opts.archived,
110
+ };
111
+ const current = await client.clients.get({ workspaceId, clientId: id });
112
+ const body = clientUpdate.body(current, patch);
113
+ if (clientUpdate.changed(current, patch).length === 0) {
168
114
  throw new Error("clients.update values are unchanged; provide a different value.");
169
115
  }
170
116
  const req = {
@@ -205,7 +151,7 @@ export const registerClientsCommand = (program, services) => {
205
151
  await dispatchedWrite(this, client.clients.update({
206
152
  workspaceId: currentWorkspaceId,
207
153
  clientId,
208
- body: reconstructClientBody({ ...current, archived: true }),
154
+ body: clientUpdate.body(current, { archived: true }),
209
155
  }));
210
156
  archivedByCall = true;
211
157
  },