@apet97/clockify-cli-115 6.0.0 → 8.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 (48) 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/balanceAssignment.js +5 -12
  7. package/dist/commands/batch.js +226 -0
  8. package/dist/commands/clients.js +18 -79
  9. package/dist/commands/doctor.js +65 -66
  10. package/dist/commands/entries.js +5 -8
  11. package/dist/commands/expenses.js +29 -39
  12. package/dist/commands/helpers.js +68 -30
  13. package/dist/commands/invoices.js +3 -3
  14. package/dist/commands/leaf-command.js +7 -0
  15. package/dist/commands/manifest.js +63 -0
  16. package/dist/commands/operations.js +271 -0
  17. package/dist/commands/projects.js +17 -37
  18. package/dist/commands/reports.js +22 -7
  19. package/dist/commands/shared-report-body.js +14 -81
  20. package/dist/commands/sharedReports.js +8 -47
  21. package/dist/commands/skill.js +85 -0
  22. package/dist/commands/status.js +19 -13
  23. package/dist/commands/stop.js +3 -12
  24. package/dist/commands/tags.js +12 -21
  25. package/dist/commands/tasks.js +26 -134
  26. package/dist/commands/timeoff.js +1 -1
  27. package/dist/commands/users.js +4 -14
  28. package/dist/commands/webhook-delivery.js +331 -0
  29. package/dist/commands/webhooks.js +37 -110
  30. package/dist/completions.js +2 -1
  31. package/dist/config.js +166 -63
  32. package/dist/credentials.js +164 -0
  33. package/dist/failure.js +4 -9
  34. package/dist/flags.js +14 -4
  35. package/dist/generated/version.js +1 -1
  36. package/dist/index.js +38 -15
  37. package/dist/interrupts.js +28 -0
  38. package/dist/output.js +137 -48
  39. package/dist/receipt.js +2 -10
  40. package/dist/stdin.js +6 -0
  41. package/dist/stdout.js +38 -0
  42. package/dist/write-outcome.js +1 -1
  43. package/package.json +5 -3
  44. package/plugin/.claude-plugin/plugin.json +16 -0
  45. package/plugin/skills/clockify-cli/SKILL.md +88 -0
  46. package/plugin/skills/clockify-mcp/SKILL.md +48 -0
  47. package/plugin/skills/clockify-sdk/SKILL.md +85 -0
  48. package/dist/error-codes.js +0 -300
@@ -0,0 +1,331 @@
1
+ import { CLOCKIFY_WEBHOOK_EVENT_NAMES } from "clockify-sdk-ts-115/webhook-events";
2
+ import { CLOCKIFY_SIGNATURE_HEADER, CLOCKIFY_WEBHOOK_EVENT_HEADER, createWebhookReceiver, undeliveredWebhookEvents, } from "clockify-sdk-ts-115/webhooks";
3
+ import { InvalidArgumentError, Option } from "commander";
4
+ import { UsageError } from "../failure.js";
5
+ import { resolveFlags } from "../flags.js";
6
+ import { watchInterrupts } from "../interrupts.js";
7
+ import { AlreadyReportedError, fixedColumns, printObject, printRecords, printWarning, rowLine, } from "../output.js";
8
+ import { writeLine } from "../stdout.js";
9
+ import { isSuccess } from "../write-outcome.js";
10
+ import { parseIntArg, parseJson, readTextInput, resolveContext, rootProgram } from "./helpers.js";
11
+ import { leafCommand } from "./leaf-command.js";
12
+ const HEADER_VALUE = /^[\x20-\x7e]+$/;
13
+ const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
14
+ const LISTEN_KEYS = ["event", "payload", "forwarded"];
15
+ const TRIGGER_KEYS = ["ok", "event", "url", "status"];
16
+ const RECOVER_KEYS = ["id", "event", "status", "statusCode", "retryCount", "respondedAt", "payload", "forwarded"];
17
+ function parsePort(value) {
18
+ const port = value === "0" ? 0 : parseIntArg(value);
19
+ if (port > 65_535)
20
+ throw new InvalidArgumentError("must be at most 65535.");
21
+ return port;
22
+ }
23
+ function parseLoopbackUrl(value) {
24
+ const url = URL.canParse(value) ? new URL(value) : undefined;
25
+ if (url?.protocol !== "http:" || !LOOPBACK.has(url.hostname) || url.username !== "" || url.password !== "") {
26
+ throw new InvalidArgumentError("must be an http:// URL on localhost, 127.0.0.1 or [::1].");
27
+ }
28
+ return url.href;
29
+ }
30
+ function parseDeliveryStatus(value) {
31
+ const status = value.toUpperCase();
32
+ if (status !== "FAILED" && status !== "RETRYING")
33
+ throw new InvalidArgumentError("must be FAILED or RETRYING.");
34
+ return status;
35
+ }
36
+ async function signingSecret(command, services, { webhook, secretStdin }) {
37
+ if ((webhook === undefined) === (secretStdin !== true)) {
38
+ throw new UsageError("Provide the signing secret with exactly one of --webhook <id> and --secret-stdin.");
39
+ }
40
+ if (webhook === undefined) {
41
+ const secret = ((await readTextInput("-", "--secret-stdin")) ?? "").trim();
42
+ if (secret === "")
43
+ throw new UsageError("--secret-stdin read nothing; provide the webhook's signing secret on stdin.");
44
+ if (!HEADER_VALUE.test(secret))
45
+ throw new UsageError("--secret-stdin must be one line of printable ASCII.");
46
+ return secret;
47
+ }
48
+ const { client, workspaceId } = await resolveContext(command, services);
49
+ return await webhookSecret(client, workspaceId, webhook);
50
+ }
51
+ async function webhookSecret(client, workspaceId, webhookId) {
52
+ const { authToken } = await client.webhooks.get({ workspaceId, webhookId });
53
+ if (!authToken)
54
+ throw new Error(`Clockify did not return the signing secret of webhook ${webhookId}.`);
55
+ if (!HEADER_VALUE.test(authToken))
56
+ throw new Error(`The signing secret of webhook ${webhookId} does not fit into a header.`);
57
+ return authToken;
58
+ }
59
+ function reason(error) {
60
+ const { message, code } = error;
61
+ return message || code || String(error);
62
+ }
63
+ async function deliver(url, event, secret, body, signal) {
64
+ try {
65
+ const response = await fetch(url, {
66
+ method: "POST",
67
+ redirect: "manual",
68
+ ...(signal && { signal }),
69
+ headers: {
70
+ "Content-Type": "application/json",
71
+ [CLOCKIFY_SIGNATURE_HEADER]: secret,
72
+ ...(event !== undefined && { [CLOCKIFY_WEBHOOK_EVENT_HEADER]: event }),
73
+ },
74
+ body,
75
+ });
76
+ await response.body?.cancel();
77
+ return response.status;
78
+ }
79
+ catch (error) {
80
+ const { cause } = error;
81
+ throw new Error(`Could not reach ${url}: ${reason(cause ?? error)}`);
82
+ }
83
+ }
84
+ async function serve(port, stop, quit, handle) {
85
+ const { createServer } = await import("node:http");
86
+ const server = createServer();
87
+ const sockets = new Set();
88
+ const unanswered = new Set();
89
+ const handling = new Set();
90
+ const close = () => {
91
+ server.close();
92
+ const busy = new Set([...unanswered].filter(({ complete }) => complete).map(({ socket }) => socket));
93
+ for (const socket of sockets)
94
+ if (!busy.has(socket))
95
+ socket.destroySoon();
96
+ };
97
+ stop.addEventListener("abort", close);
98
+ quit.addEventListener("abort", () => {
99
+ server.closeAllConnections();
100
+ });
101
+ try {
102
+ await new Promise((resolve, reject) => {
103
+ server.on("close", resolve);
104
+ server.on("error", (err) => {
105
+ reject(new Error(`Could not listen on 127.0.0.1:${port}: ${err.message}`));
106
+ });
107
+ server.on("connection", (socket) => {
108
+ sockets.add(socket);
109
+ socket.on("close", () => sockets.delete(socket));
110
+ });
111
+ server.on("request", (request, response) => {
112
+ unanswered.add(request);
113
+ response.on("close", () => {
114
+ unanswered.delete(request);
115
+ if (stop.aborted)
116
+ close();
117
+ });
118
+ const handled = handle(request, response).catch(reject).finally(() => handling.delete(handled));
119
+ handling.add(handled);
120
+ });
121
+ server.listen(port, "127.0.0.1", () => {
122
+ process.stderr.write(`Listening on http://127.0.0.1:${server.address().port}\n`);
123
+ if (stop.aborted)
124
+ close();
125
+ });
126
+ });
127
+ await Promise.all(handling);
128
+ }
129
+ finally {
130
+ server.close();
131
+ server.closeAllConnections();
132
+ }
133
+ }
134
+ async function* recorded(chunks, received) {
135
+ for await (const chunk of chunks) {
136
+ received.push(chunk);
137
+ yield chunk;
138
+ }
139
+ }
140
+ const secretOptions = (command) => command
141
+ .option("--webhook <id>", "Webhook whose signing secret is used. It is read from Clockify.")
142
+ .option("--secret-stdin", "Read the signing secret from stdin instead. Needs no credentials.");
143
+ export function registerWebhookDeliveryCommands(webhooks, services) {
144
+ leafCommand(webhooks, "events", "read")
145
+ .description("List the event names a webhook can subscribe to. Needs no credentials.")
146
+ .addHelpText("after", "\nExamples:\n $ clk115 webhooks events\n")
147
+ .action(function () {
148
+ const output = fixedColumns(["event"], resolveFlags(rootProgram(this)));
149
+ printRecords(CLOCKIFY_WEBHOOK_EVENT_NAMES.map((event) => ({ event })), output);
150
+ });
151
+ secretOptions(leafCommand(webhooks, "listen", "local"))
152
+ .description("Receive deliveries on a loopback port, verify each one and print it as a JSON line.")
153
+ .addOption(new Option("--port <n>", "Loopback port; 0 picks a free one.").argParser(parsePort).default(4040))
154
+ .addOption(new Option("--forward <url>", "Pass each verified delivery to this loopback URL and answer as it does.").argParser(parseLoopbackUrl))
155
+ .option("--max <n>", "Stop after printing this many verified deliveries.", parseIntArg)
156
+ .addHelpText("after", "\nExamples:\n" +
157
+ " $ clk115 webhooks listen --webhook 64c777ddd3fcab07cfbb210c --forward http://localhost:3000/hooks\n" +
158
+ " $ echo local-secret | clk115 webhooks listen --secret-stdin --max 1 > delivery.json\n" +
159
+ "\nClockify delivers to public https:// URLs only, so put your own tunnel in front of the port.\n" +
160
+ "A delivery that the handler does not accept, or that cannot be printed, is answered with 500, and Clockify\n" +
161
+ "sends it again. An interrupt before --max deliveries exits with 128 plus the signal number.\n")
162
+ .action(async function (opts) {
163
+ const output = fixedColumns(LISTEN_KEYS, resolveFlags(rootProgram(this)));
164
+ if (output.mode === "csv")
165
+ throw new UsageError("webhooks listen prints JSON lines; --output csv does not apply.");
166
+ const secret = await signingSecret(this, services, opts);
167
+ const stop = new AbortController();
168
+ const quit = new AbortController();
169
+ const interrupts = watchInterrupts(() => {
170
+ stop.abort();
171
+ }, () => {
172
+ quit.abort();
173
+ });
174
+ const { forward, max } = opts;
175
+ let taken = 0;
176
+ let printed = 0;
177
+ let unwritten = 0;
178
+ const print = async (delivery) => {
179
+ try {
180
+ await writeLine(rowLine(delivery, output), interrupts.abandoned);
181
+ }
182
+ catch (error) {
183
+ unwritten += 1;
184
+ throw new Error(`The delivery could not be printed: ${reason(error)}`);
185
+ }
186
+ printed += 1;
187
+ };
188
+ const receiver = (received) => createWebhookReceiver({
189
+ expectedToken: secret,
190
+ handlers: {},
191
+ onUnhandled: async ({ event, payload }) => {
192
+ if (taken === max)
193
+ throw new Error(`--max ${max} was reached.`);
194
+ taken += 1;
195
+ let status;
196
+ try {
197
+ if (forward !== undefined)
198
+ status = await deliver(forward, event, secret, Buffer.concat(received), quit.signal);
199
+ await print({ event: event ?? null, payload, ...(status !== undefined && { forwarded: status }) });
200
+ }
201
+ catch (error) {
202
+ taken -= 1;
203
+ throw error;
204
+ }
205
+ if (status !== undefined && !isSuccess(status))
206
+ throw new Error(`${forward ?? ""} answered ${status}`);
207
+ },
208
+ onError: (error) => {
209
+ printWarning(reason(error), output);
210
+ },
211
+ });
212
+ const answer = async (request, response) => {
213
+ const { method, headers } = request;
214
+ const received = [];
215
+ await receiver(received).node({ method, headers, [Symbol.asyncIterator]: () => recorded(request, received) }, response);
216
+ if (response.statusCode !== 200)
217
+ printWarning(`Answered ${response.statusCode} to ${method ?? ""}.`, output);
218
+ if (unwritten > 0 || printed === max)
219
+ stop.abort();
220
+ };
221
+ try {
222
+ await serve(opts.port, stop.signal, quit.signal, answer);
223
+ }
224
+ finally {
225
+ interrupts.release();
226
+ }
227
+ const interrupted = interrupts.exitCode();
228
+ if (unwritten > 0)
229
+ throw new AlreadyReportedError(interrupts.abandoned.aborted ? interrupted : 1);
230
+ if (interrupted !== undefined && max !== undefined && printed < max)
231
+ throw new AlreadyReportedError(interrupted);
232
+ });
233
+ secretOptions(leafCommand(webhooks, "trigger <event>", "local"))
234
+ .description("Send a signed delivery to a handler on this machine.")
235
+ .requiredOption("--data <json>", "The payload as JSON, as @file, or as - for stdin.")
236
+ .addOption(new Option("--url <url>", "Loopback URL of the handler.").argParser(parseLoopbackUrl).default("http://127.0.0.1:4040/"))
237
+ .addHelpText("after", "\nExamples:\n" +
238
+ " $ echo local-secret | clk115 webhooks trigger NEW_TAG --secret-stdin --data '{\"id\":\"t1\",\"name\":\"focus\"}'\n" +
239
+ " $ clk115 webhooks trigger NEW_TIME_ENTRY --webhook 64c777ddd3fcab07cfbb210c --data @entry.json --url http://localhost:3000/hooks\n")
240
+ .action(async function (name, opts) {
241
+ const output = fixedColumns(TRIGGER_KEYS, resolveFlags(rootProgram(this)));
242
+ const event = name.toUpperCase();
243
+ if (!CLOCKIFY_WEBHOOK_EVENT_NAMES.includes(event)) {
244
+ throw new UsageError(`Unknown webhook event: ${name}. Run \`clk115 webhooks events\` for the names.`);
245
+ }
246
+ if (opts.data === "-" && opts.secretStdin) {
247
+ throw new UsageError("--data - and --secret-stdin both read stdin; provide the payload as @file.");
248
+ }
249
+ const payload = parseJson((await readTextInput(opts.data, "--data")) ?? "", "--data");
250
+ if (payload === null || typeof payload !== "object" || Array.isArray(payload)) {
251
+ throw new UsageError("--data must be a JSON object.");
252
+ }
253
+ const secret = await signingSecret(this, services, opts);
254
+ const status = await deliver(opts.url, event, secret, JSON.stringify(payload));
255
+ printObject({ ok: isSuccess(status), event, url: opts.url, status }, output);
256
+ if (!isSuccess(status))
257
+ throw new AlreadyReportedError();
258
+ });
259
+ leafCommand(webhooks, "recover <id>", "local")
260
+ .description("List the deliveries of a webhook that Clockify could not complete, and optionally hand them to a local handler.")
261
+ .option("--status <status>", "Delivery state to list: FAILED or RETRYING.", parseDeliveryStatus, "FAILED")
262
+ .addOption(new Option("--forward <url>", "Send each recorded body, signed, to this loopback URL.").argParser(parseLoopbackUrl))
263
+ .option("--limit <n>", "List at most this many deliveries.", parseIntArg, 100)
264
+ .addHelpText("after", "\nExamples:\n" +
265
+ " $ clk115 webhooks recover 64c777ddd3fcab07cfbb210c\n" +
266
+ " $ clk115 webhooks recover 64c777ddd3fcab07cfbb210c --forward http://localhost:3000/hooks --json\n" +
267
+ "\nClockify keeps its delivery log for 7 days. The log does not change when a delivery is forwarded,\n" +
268
+ "so a handler that runs twice must recognise a record it already has. An interrupt, or a failure after the\n" +
269
+ "first delivery, still prints what was listed and forwarded until then.\n")
270
+ .action(async function (id, opts) {
271
+ const output = fixedColumns(RECOVER_KEYS, resolveFlags(rootProgram(this)));
272
+ const { client, workspaceId } = await resolveContext(this, services, output);
273
+ const { forward, limit, status } = opts;
274
+ const withPayload = output.mode !== "table" || output.fields !== undefined;
275
+ const secret = forward === undefined ? "" : await webhookSecret(client, workspaceId, id);
276
+ const rows = [];
277
+ let refused = 0;
278
+ let cut = 0;
279
+ const print = () => {
280
+ printRecords(rows, output);
281
+ };
282
+ const quit = new AbortController();
283
+ const interrupts = watchInterrupts(() => {
284
+ printWarning("Finishing the delivery in progress. Interrupt again to give it up.", output);
285
+ }, () => {
286
+ quit.abort();
287
+ });
288
+ const events = undeliveredWebhookEvents(client, { workspaceId, webhookId: id, status, signal: quit.signal });
289
+ try {
290
+ for await (const { body, payload, ...row } of events) {
291
+ if (rows.length === limit) {
292
+ printWarning(`--limit ${limit} was reached; there are more deliveries.`, output);
293
+ break;
294
+ }
295
+ if (interrupts.exitCode() !== undefined) {
296
+ cut += 1;
297
+ break;
298
+ }
299
+ let forwarded;
300
+ if (forward !== undefined) {
301
+ forwarded = body === undefined
302
+ ? "no recorded body"
303
+ : await deliver(forward, row.event, secret, body, quit.signal).catch(reason);
304
+ if (typeof forwarded !== "number" || !isSuccess(forwarded))
305
+ refused += 1;
306
+ }
307
+ const recordedBody = withPayload && { payload: payload ?? body ?? null };
308
+ rows.push({ ...row, ...recordedBody, ...(forwarded !== undefined && { forwarded }) });
309
+ if (quit.signal.aborted)
310
+ cut += 1;
311
+ }
312
+ }
313
+ catch (err) {
314
+ if (!quit.signal.aborted) {
315
+ if (rows.length > 0)
316
+ print();
317
+ throw err;
318
+ }
319
+ cut += 1;
320
+ }
321
+ finally {
322
+ interrupts.release();
323
+ }
324
+ if (cut === 0 || rows.length > 0)
325
+ print();
326
+ if (refused > 0)
327
+ printWarning(`${refused} of ${rows.length} deliveries were not accepted.`, output);
328
+ if (cut > 0 || refused > 0)
329
+ throw new AlreadyReportedError(cut > 0 ? interrupts.exitCode() : 1);
330
+ });
331
+ }
@@ -1,103 +1,45 @@
1
+ import { webhooksOf } from "clockify-sdk-ts-115/lookup";
1
2
  import { requestOptions } from "clockify-sdk-ts-115/request-options";
3
+ import { WEBHOOK_TRIGGER_SOURCE_TYPES, webhookTriggerSource } from "clockify-sdk-ts-115/updates";
4
+ import { CLOCKIFY_WEBHOOK_EVENT_NAMES } from "clockify-sdk-ts-115/webhook-events";
2
5
  import { assertSafeWebhookUrl } from "clockify-sdk-ts-115/webhooks";
3
6
  import { UsageError } from "../failure.js";
4
7
  import { printRecords } from "../output.js";
5
8
  import { printReceipt } from "../receipt.js";
6
9
  import { dispatchedWrite } from "../write-outcome.js";
7
- import { resolveContext, splitList } from "./helpers.js";
10
+ import { printDeleted, resolveContext, splitList } from "./helpers.js";
8
11
  import { leafCommand } from "./leaf-command.js";
12
+ import { registerWebhookDeliveryCommands } from "./webhook-delivery.js";
9
13
  const WEBHOOK_LIST_TYPES = ["USER_CREATED", "SYSTEM", "ADDON"];
10
- const WEBHOOK_TRIGGER_SOURCE_TYPES = [
11
- "PROJECT_ID",
12
- "USER_ID",
13
- "TAG_ID",
14
- "TASK_ID",
15
- "WORKSPACE_ID",
16
- "ASSIGNMENT_ID",
17
- "EXPENSE_ID",
18
- ];
19
- const WEBHOOK_EVENT_TYPES = [
20
- "NEW_TIME_ENTRY",
21
- "TIME_ENTRY_UPDATED",
22
- "TIME_ENTRY_DELETED",
23
- "TIME_ENTRY_SPLIT",
24
- "TIME_ENTRY_RESTORED",
25
- "NEW_TIMER_STARTED",
26
- "TIMER_STOPPED",
27
- "NEW_PROJECT",
28
- "PROJECT_UPDATED",
29
- "PROJECT_DELETED",
30
- "NEW_TASK",
31
- "TASK_UPDATED",
32
- "TASK_DELETED",
33
- "NEW_CLIENT",
34
- "CLIENT_UPDATED",
35
- "CLIENT_DELETED",
36
- "NEW_TAG",
37
- "TAG_UPDATED",
38
- "TAG_DELETED",
39
- "USER_JOINED_WORKSPACE",
40
- "USER_DELETED_FROM_WORKSPACE",
41
- "USER_DEACTIVATED_ON_WORKSPACE",
42
- "USER_ACTIVATED_ON_WORKSPACE",
43
- "USER_EMAIL_CHANGED",
44
- "USER_UPDATED",
45
- "USERS_INVITED_TO_WORKSPACE",
46
- "LIMITED_USERS_ADDED_TO_WORKSPACE",
47
- "NEW_INVOICE",
48
- "INVOICE_UPDATED",
49
- "NEW_APPROVAL_REQUEST",
50
- "APPROVAL_REQUEST_STATUS_UPDATED",
51
- "TIME_OFF_REQUESTED",
52
- "TIME_OFF_REQUEST_UPDATED",
53
- "TIME_OFF_REQUEST_APPROVED",
54
- "TIME_OFF_REQUEST_REJECTED",
55
- "TIME_OFF_REQUEST_STARTED",
56
- "TIME_OFF_REQUEST_WITHDRAWN",
57
- "BALANCE_UPDATED",
58
- "EXPENSE_CREATED",
59
- "EXPENSE_UPDATED",
60
- "EXPENSE_DELETED",
61
- "EXPENSE_RESTORED",
62
- "ASSIGNMENT_CREATED",
63
- "ASSIGNMENT_UPDATED",
64
- "ASSIGNMENT_DELETED",
65
- "ASSIGNMENT_PUBLISHED",
66
- "USER_GROUP_CREATED",
67
- "USER_GROUP_UPDATED",
68
- "USER_GROUP_DELETED",
69
- "COST_RATE_UPDATED",
70
- "BILLABLE_RATE_UPDATED",
71
- ];
72
- const USER_ID_TRIGGER_EVENTS = new Set([
73
- "USER_EMAIL_CHANGED",
74
- "USER_UPDATED",
75
- ]);
76
- const webhookEventsExhaustive = true;
77
- void webhookEventsExhaustive;
78
14
  function nonEmptyString(value, field) {
79
15
  if (typeof value !== "string" || value.trim() === "") {
80
16
  throw new UsageError(`webhooks.create: ${field} must be a non-empty string.`);
81
17
  }
82
18
  return value;
83
19
  }
20
+ function usage(check) {
21
+ try {
22
+ return check();
23
+ }
24
+ catch (error) {
25
+ throw new UsageError(`webhooks.create: ${error instanceof Error ? error.message : String(error)}`);
26
+ }
27
+ }
84
28
  function webhookEvent(value) {
85
29
  const event = String(value).toUpperCase();
86
- if (!WEBHOOK_EVENT_TYPES.includes(event)) {
30
+ const match = CLOCKIFY_WEBHOOK_EVENT_NAMES.find((name) => name === event);
31
+ if (match === undefined) {
87
32
  throw new UsageError(`Unknown webhook event: ${String(value)}. Provide a Clockify webhook event type such as NEW_PROJECT or NEW_TIME_ENTRY.`);
88
33
  }
89
- return event;
34
+ return match;
90
35
  }
91
- function webhookTriggerSourceType(value) {
92
- const raw = value ?? "WORKSPACE_ID";
93
- if (typeof raw !== "string") {
94
- throw new UsageError("Unknown trigger source type. Provide one of: PROJECT_ID, USER_ID, TAG_ID, TASK_ID, WORKSPACE_ID, ASSIGNMENT_ID, EXPENSE_ID.");
36
+ function webhookTriggerSourceType(value = "WORKSPACE_ID") {
37
+ const type = value.toUpperCase();
38
+ const match = WEBHOOK_TRIGGER_SOURCE_TYPES.find((candidate) => candidate === type);
39
+ if (match === undefined) {
40
+ throw new UsageError(`Unknown trigger source type: ${value}. Provide one of: ${WEBHOOK_TRIGGER_SOURCE_TYPES.join(", ")}.`);
95
41
  }
96
- const type = raw.toUpperCase();
97
- if (!WEBHOOK_TRIGGER_SOURCE_TYPES.includes(type)) {
98
- throw new UsageError(`Unknown trigger source type: ${raw}. Provide one of: PROJECT_ID, USER_ID, TAG_ID, TASK_ID, WORKSPACE_ID, ASSIGNMENT_ID, EXPENSE_ID.`);
99
- }
100
- return type;
42
+ return match;
101
43
  }
102
44
  export const registerWebhooksCommand = (program, services) => {
103
45
  const webhooks = program.command("webhooks").description("Manage outbound webhooks.");
@@ -118,8 +60,7 @@ export const registerWebhooksCommand = (program, services) => {
118
60
  }
119
61
  const { client, workspaceId, output } = await resolveContext(this, services);
120
62
  const options = type ? requestOptions({ queryParams: { type } }) : undefined;
121
- const response = (await client.webhooks.list({ workspaceId }, options));
122
- const items = Array.isArray(response) ? response : (response.webhooks ?? []);
63
+ const items = webhooksOf(await client.webhooks.list({ workspaceId }, options));
123
64
  const rows = items.map((raw) => {
124
65
  const w = raw;
125
66
  return {
@@ -146,26 +87,18 @@ export const registerWebhooksCommand = (program, services) => {
146
87
  .action(async function (opts) {
147
88
  const name = nonEmptyString(opts.name, "name");
148
89
  const url = nonEmptyString(opts.url, "url");
149
- try {
150
- assertSafeWebhookUrl(url);
151
- }
152
- catch (err) {
153
- throw new UsageError(`webhooks.create: ${err instanceof Error ? err.message : String(err)}`);
154
- }
90
+ usage(() => assertSafeWebhookUrl(url));
155
91
  const event = webhookEvent(opts.event);
156
92
  const triggerSourceType = webhookTriggerSourceType(opts.triggerSourceType);
157
- if (USER_ID_TRIGGER_EVENTS.has(event) && triggerSourceType !== "USER_ID") {
158
- throw new UsageError(`webhooks.create: ${event} requires USER_ID trigger sources.`);
159
- }
160
93
  const { client, workspaceId, output } = await resolveContext(this, services);
161
- const triggerSource = triggerSourceType === "WORKSPACE_ID"
162
- ? [workspaceId]
163
- : opts.triggerSource
94
+ const triggerSource = usage(() => webhookTriggerSource({
95
+ workspaceId,
96
+ webhookEvent: event,
97
+ triggerSourceType,
98
+ triggerSource: triggerSourceType !== "WORKSPACE_ID" && opts.triggerSource
164
99
  ? splitList(String(opts.triggerSource))
165
- : [];
166
- if (triggerSource.length === 0) {
167
- throw new UsageError(`webhooks.create: trigger source is required for ${triggerSourceType}.`);
168
- }
100
+ : [],
101
+ }));
169
102
  const body = {
170
103
  name,
171
104
  url,
@@ -174,7 +107,7 @@ export const registerWebhooksCommand = (program, services) => {
174
107
  triggerSource,
175
108
  };
176
109
  const request = { workspaceId, body };
177
- const created = (await dispatchedWrite(this, client.webhooks.create(request)));
110
+ const created = await dispatchedWrite(this, client.webhooks.create(request));
178
111
  const data = {
179
112
  id: created.id ?? "",
180
113
  name: created.name ?? "",
@@ -204,19 +137,13 @@ export const registerWebhooksCommand = (program, services) => {
204
137
  .action(async function (id) {
205
138
  const { client, workspaceId, output } = await resolveContext(this, services);
206
139
  await dispatchedWrite(this, client.webhooks.delete({ workspaceId, webhookId: id }));
207
- printReceipt({
208
- ok: true,
140
+ printDeleted(output, {
209
141
  action: "webhooks.delete",
210
142
  entity: "webhook",
143
+ id,
211
144
  ids: { webhookId: id },
212
- data: { id, deleted: true, message: `deleted webhook ${id}` },
213
- changed: { deleted: [{ type: "webhook", id }] },
214
- next: [
215
- {
216
- command: "clk115 webhooks list --json",
217
- reason: "Verify the webhook no longer appears.",
218
- },
219
- ],
220
- }, output);
145
+ list: "webhooks list",
146
+ });
221
147
  });
148
+ registerWebhookDeliveryCommands(webhooks, services);
222
149
  };
@@ -1,10 +1,11 @@
1
1
  import { InvalidArgumentError } from "commander";
2
2
  import { KNOWN_REGIONS } from "./client.js";
3
3
  import { TIME_VIEW_MODES } from "./commands/helpers.js";
4
+ import { OUTPUT_MODES } from "./flags.js";
4
5
  export const COMPLETION_SHELLS = ["zsh", "bash", "fish"];
5
6
  const BINARIES = ["clk115", "clockify115"];
6
7
  const FLAG_VALUES = {
7
- "--output": ["table", "json", "ndjson"],
8
+ "--output": OUTPUT_MODES,
8
9
  "--region": KNOWN_REGIONS,
9
10
  "--time-view-mode": TIME_VIEW_MODES,
10
11
  };