@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,271 @@
1
+ import { closeSync, openSync, readFileSync, rmSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { Option } from "commander";
4
+ import { requireWorkspaceId } from "../config.js";
5
+ import { UsageError } from "../failure.js";
6
+ import { globalFlags, resolveFlags } from "../flags.js";
7
+ import { fixedColumns, printData, printObject, printRecords } from "../output.js";
8
+ import { printReceipt } from "../receipt.js";
9
+ import { dispatchedWrite } from "../write-outcome.js";
10
+ import { collect, parseIntArg, parseJson, parsePair, readTextInput, rootProgram } from "./helpers.js";
11
+ import { declareMutation, leafCommand } from "./leaf-command.js";
12
+ const EFFECTS = [
13
+ "read",
14
+ "business_write",
15
+ "external_side_effect",
16
+ "privileged",
17
+ "destructive",
18
+ ];
19
+ const LIST_KEYS = ["name", "effect", "method", "path", "command", "tool", "summary"];
20
+ const REQUEST_KEYS = ["ok", "dryRun", "operation", "effect", "method", "path", "query", "body"];
21
+ const WRITTEN_KEYS = ["written", "bytes"];
22
+ const OPERATION_KEYS = Object.keys({
23
+ name: true, operationId: true, method: true, path: true, service: true, server: true, tags: true, summary: true, description: true,
24
+ deprecated: true, effect: true, destructiveHint: true, openWorldHint: true, replacedBy: true, mcp: true, cli: true, media: true,
25
+ responseMedia: true, returnsSigningToken: true, input: true,
26
+ });
27
+ export async function requireOperation(reference) {
28
+ const { findOperation, searchOperations } = await import("clockify-sdk-ts-115/operations");
29
+ const operation = findOperation(reference);
30
+ if (operation !== undefined)
31
+ return operation;
32
+ const near = searchOperations(reference.replace(/[._-]/g, " ")).slice(0, 3).map(({ name }) => name);
33
+ throw new UsageError(`Unknown operation "${reference}". ` +
34
+ (near.length > 0 ? `Provide one of: ${near.join(", ")}.` : "Run `clk115 operations list`."));
35
+ }
36
+ export function resolvedRequest(operation, { workspaceId, path: params = {}, query, body }) {
37
+ const values = { ...params, workspaceId };
38
+ return {
39
+ operation: operation.name,
40
+ effect: operation.effect,
41
+ method: operation.method,
42
+ path: operation.path.replace(/\{(\w+)\}/g, (_, name) => encodeURIComponent(String(values[name]))),
43
+ ...(query && Object.keys(query).length > 0 && { query }),
44
+ ...(body !== undefined && { body: describeBody(body) }),
45
+ };
46
+ }
47
+ function describeBody(body) {
48
+ if (body instanceof Blob)
49
+ return `<${body.size} bytes>`;
50
+ if (Array.isArray(body))
51
+ return body.map(describeBody);
52
+ if (body === null || typeof body !== "object")
53
+ return body;
54
+ return Object.fromEntries(Object.entries(body).map(([key, value]) => [key, describeBody(value)]));
55
+ }
56
+ function coerce(schema, values) {
57
+ if (schema?.type === "array")
58
+ return values.map((value) => coerce(schema.items, [value]));
59
+ if (values.length > 1)
60
+ return values;
61
+ const value = values[0];
62
+ if ((schema?.type === "integer" || schema?.type === "number") && value.trim() !== "" && Number.isFinite(Number(value))) {
63
+ return Number(value);
64
+ }
65
+ if (schema?.type === "boolean" && (value === "true" || value === "false"))
66
+ return value === "true";
67
+ return value;
68
+ }
69
+ function parameters(schema, pairs) {
70
+ const values = new Map();
71
+ for (const [key, value] of pairs)
72
+ values.set(key, [...(values.get(key) ?? []), value]);
73
+ return Object.fromEntries([...values].map(([key, value]) => [key, coerce(schema?.properties?.[key], value)]));
74
+ }
75
+ function withFile(operation, body, file) {
76
+ if (file === undefined)
77
+ return body;
78
+ const fields = operation.input.properties?.body?.properties ?? {};
79
+ const field = Object.keys(fields).find((name) => fields[name].format === "binary");
80
+ if (field === undefined)
81
+ throw new UsageError(`--file does not apply: ${operation.name} takes no file.`);
82
+ let bytes;
83
+ try {
84
+ bytes = readFileSync(file);
85
+ }
86
+ catch (err) {
87
+ throw new UsageError(`--file ${JSON.stringify(file)} could not be read: ${err.message}; provide a readable file`);
88
+ }
89
+ return { ...body, [field]: new File([bytes], path.basename(file)) };
90
+ }
91
+ export const registerOperationsCommand = (program, services) => {
92
+ const operations = program
93
+ .command("operations")
94
+ .description("Find, inspect and call any of the API's operations.");
95
+ leafCommand(operations, "list", "read")
96
+ .description("List operations, or search them by what you want to do.")
97
+ .argument("[words...]", "What you want to do, for example: archive a client.")
98
+ .addOption(new Option("--effect <effect>", "Only operations with this effect.").choices(EFFECTS))
99
+ .option("--tag <tag>", "Only operations with this tag.")
100
+ .option("--limit <n>", "Maximum operations to print.", parseIntArg, 25)
101
+ .option("--all", "Print every match.", false)
102
+ .addHelpText("after", "\nExamples:\n" +
103
+ " $ clk115 operations list archive a client\n" +
104
+ " $ clk115 operations list --tag Invoices --effect read\n" +
105
+ " $ clk115 operations list --all --json\n")
106
+ .action(async function (words, opts) {
107
+ const output = fixedColumns(LIST_KEYS, resolveFlags(rootProgram(this)));
108
+ const catalog = await import("clockify-sdk-ts-115/operations");
109
+ const found = words.length > 0 ? catalog.searchOperations(words.join(" ")) : [...catalog.operations().values()];
110
+ const rows = found
111
+ .filter(({ effect }) => opts.effect === undefined || effect === opts.effect)
112
+ .filter(({ tags }) => opts.tag === undefined || tags.some((tag) => tag.toLowerCase() === opts.tag.toLowerCase()))
113
+ .slice(0, opts.all ? undefined : opts.limit)
114
+ .map(({ name, effect, method, path: route, cli, mcp, summary, deprecated }) => ({
115
+ name,
116
+ effect,
117
+ method,
118
+ path: route,
119
+ command: cli ?? null,
120
+ tool: mcp.curated ?? mcp.exact,
121
+ summary: (deprecated ? "Deprecated. " : "") + (summary ?? ""),
122
+ }));
123
+ const brief = output.mode === "table" && output.fields === undefined;
124
+ printRecords(brief ? rows.map(({ name, effect, command, summary }) => ({ name, effect, command, summary })) : rows, output);
125
+ });
126
+ leafCommand(operations, "show", "read")
127
+ .description("Show one operation: route, effect, input schema and the command or tool that covers it.")
128
+ .argument("<operation>", "Name (tags.create), operationId or exact MCP tool name.")
129
+ .addHelpText("after", "\nExamples:\n" + " $ clk115 operations show tags.create --json\n")
130
+ .action(async function (reference) {
131
+ const output = fixedColumns(OPERATION_KEYS, resolveFlags(rootProgram(this)));
132
+ const operation = await requireOperation(reference);
133
+ if (output.mode === "table" && output.fields === undefined) {
134
+ const { input, ...rest } = operation;
135
+ printObject(rest, output);
136
+ console.log(JSON.stringify(input, null, 2));
137
+ return;
138
+ }
139
+ printObject(operation, output);
140
+ });
141
+ leafCommand(operations, "call", "destructive")
142
+ .description("Call one operation. Input is checked against its schema before anything is sent.")
143
+ .argument("<operation>", "Name (tags.create), operationId or exact MCP tool name.")
144
+ .option("-p, --path <name=value>", "Path parameter (repeatable); workspaceId comes from the configuration.", collect, [])
145
+ .option("-q, --query <name=value>", "Query parameter (repeatable).", collect, [])
146
+ .option("--body <json|@file|->", "JSON body: inline, @file, or - for stdin.")
147
+ .option("--file <path>", "File to upload, for the operations that take one.")
148
+ .option("--output-file <path>", "Write the response to this new file instead of stdout.")
149
+ .option("--dry-run", "Print the request without sending it. Needs no credentials.", false)
150
+ .addHelpText("after", "\nExamples:\n" +
151
+ " $ clk115 operations call tags.list -q archived=false\n" +
152
+ " $ clk115 operations call tags.create --body '{\"name\":\"focus\"}' --dry-run\n" +
153
+ " $ clk115 operations call expenses.create --body @expense.json --file receipt.pdf\n" +
154
+ "\nAn operation that replaces a record resets the fields you leave out; `operations show` names the safe update.\n")
155
+ .action(async function (reference, opts) {
156
+ const operation = await requireOperation(reference);
157
+ const reads = operation.effect === "read";
158
+ declareMutation(this, !reads);
159
+ const { callOperation, operationInputProblems } = await import("clockify-sdk-ts-115/operations");
160
+ const root = rootProgram(this);
161
+ const output = resolveFlags(root);
162
+ const schema = operation.input.properties;
163
+ const text = await readTextInput(opts.body, "--body");
164
+ const body = withFile(operation, text === undefined ? undefined : parseJson(text, "--body"), opts.file);
165
+ const config = services.loadConfig(globalFlags(root));
166
+ const workspaceId = operation.path.includes("{workspaceId}") ? requireWorkspaceId(config) : undefined;
167
+ const input = {
168
+ workspaceId,
169
+ path: parameters(schema?.path, opts.path.map((pair) => parsePair(pair, "--path"))),
170
+ query: parameters(schema?.query, opts.query.map((pair) => parsePair(pair, "--query"))),
171
+ ...(body !== undefined && { body }),
172
+ };
173
+ const problems = operationInputProblems(operation, input);
174
+ if (problems.length > 0) {
175
+ throw new UsageError(`${operation.name}: ${problems.join("; ")}. Run \`clk115 operations show ${operation.name}\` for its input.`);
176
+ }
177
+ if (opts.dryRun) {
178
+ printObject({ ok: true, dryRun: true, ...resolvedRequest(operation, input) }, fixedColumns(REQUEST_KEYS, output));
179
+ return;
180
+ }
181
+ const { outputFile } = opts;
182
+ const shape = outputFile !== undefined && reads ? fixedColumns(WRITTEN_KEYS, output) : output;
183
+ const fileFitsStdout = !process.stdout.isTTY && output.mode === "table";
184
+ if (outputFile !== undefined)
185
+ requireNewFile(outputFile);
186
+ else if (answersWithFile(operation) && !fileFitsStdout)
187
+ throw new UsageError(IS_A_FILE);
188
+ const client = await services.buildClient(config, this);
189
+ const call = callOperation(client, operation.name, input);
190
+ const answer = reads ? await call : await dispatchedWrite(this, call);
191
+ const data = outputFile === undefined ? await responseData(operation, answer) : await written(outputFile, operation, answer);
192
+ if (Buffer.isBuffer(data)) {
193
+ if (!fileFitsStdout)
194
+ throw new Error(IS_A_FILE);
195
+ process.stdout.write(data);
196
+ }
197
+ else if (reads)
198
+ printData(data, shape);
199
+ else
200
+ printReceipt(operationReceipt(operation, input, data), output);
201
+ });
202
+ };
203
+ const IS_A_FILE = "The response is a file: pass --output-file, or redirect stdout without an output flag.";
204
+ export function answersWithFile({ responseMedia = [] }) {
205
+ return responseMedia.includes("application/octet-stream");
206
+ }
207
+ function isFileResponse(value) {
208
+ return value !== null && typeof value === "object" && "arrayBuffer" in value && typeof value.arrayBuffer === "function";
209
+ }
210
+ function withoutSigningToken({ returnsSigningToken }, data) {
211
+ if (!returnsSigningToken || data === undefined)
212
+ return data;
213
+ return JSON.parse(JSON.stringify(data, (key, value) => (key === "authToken" ? undefined : value)));
214
+ }
215
+ async function responseBytes(answer) {
216
+ return isFileResponse(answer) ? Buffer.from(await answer.arrayBuffer()) : answer;
217
+ }
218
+ export async function responseData(operation, answer) {
219
+ const { returnsSigningToken } = operation;
220
+ const raw = await responseBytes(answer);
221
+ const encoded = Buffer.isBuffer(raw) ? !answersWithFile(operation) : typeof raw === "string" && returnsSigningToken;
222
+ if (!encoded)
223
+ return withoutSigningToken(operation, raw);
224
+ try {
225
+ const text = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(raw));
226
+ return withoutSigningToken(operation, JSON.parse(text));
227
+ }
228
+ catch {
229
+ if (returnsSigningToken)
230
+ throw new Error("The response is not JSON and may contain a signing token, so it is not shown.");
231
+ return raw;
232
+ }
233
+ }
234
+ function requireNewFile(file) {
235
+ try {
236
+ closeSync(openSync(file, "wx"));
237
+ rmSync(file);
238
+ }
239
+ catch (err) {
240
+ throw new UsageError(`--output-file ${JSON.stringify(file)} could not be created: ${err.message}; provide a path that does not exist yet`);
241
+ }
242
+ }
243
+ async function written(file, operation, answer) {
244
+ const data = isFileResponse(answer) && !operation.returnsSigningToken ? await responseBytes(answer) : await responseData(operation, answer);
245
+ const bytes = Buffer.isBuffer(data) ? data : Buffer.from(`${JSON.stringify(data ?? null, null, 2)}\n`);
246
+ const descriptor = openSync(file, "wx");
247
+ try {
248
+ writeFileSync(descriptor, bytes);
249
+ return { written: file, bytes: bytes.length };
250
+ }
251
+ catch (err) {
252
+ rmSync(file, { force: true });
253
+ throw err;
254
+ }
255
+ finally {
256
+ closeSync(descriptor);
257
+ }
258
+ }
259
+ export function operationReceipt(operation, { path: params = {} }, data) {
260
+ const ids = Object.fromEntries(Object.entries(params).map(([name, value]) => [name, String(value)]));
261
+ const record = data !== null && typeof data === "object" && !Array.isArray(data)
262
+ ? data
263
+ : data === undefined || data === null ? {} : { result: data };
264
+ return {
265
+ ok: true,
266
+ action: operation.name,
267
+ entity: operation.name.split(".")[0],
268
+ ids: { ...ids, ...(typeof record.id === "string" && { id: record.id }) },
269
+ data: record,
270
+ };
271
+ }
@@ -1,14 +1,11 @@
1
1
  import { archiveThenDeleteProject } from "clockify-sdk-ts-115/ensure";
2
+ import { projectUpdate } from "clockify-sdk-ts-115/updates";
3
+ import { PartialDeleteError, UsageError } from "../failure.js";
2
4
  import { printObject, printRecords } from "../output.js";
3
5
  import { printReceipt } from "../receipt.js";
6
+ import { dispatchedWrite } from "../write-outcome.js";
4
7
  import { clampPageSize, parseIntArg, resolveContext } from "./helpers.js";
5
8
  import { leafCommand } from "./leaf-command.js";
6
- function projectUpdateCarryFields(current) {
7
- if (typeof current.billable !== "boolean" || typeof current.public !== "boolean") {
8
- throw new Error("Cannot update project safely: the current project did not return boolean billable and public fields.");
9
- }
10
- return { billable: current.billable, isPublic: current.public };
11
- }
12
9
  export const registerProjectsCommand = (program, services) => {
13
10
  const projects = program.command("projects").description("Manage projects.");
14
11
  leafCommand(projects, "list", "read")
@@ -68,7 +65,7 @@ export const registerProjectsCommand = (program, services) => {
68
65
  ...(opts.billable ? { billable: true } : {}),
69
66
  },
70
67
  };
71
- const created = (await client.projects.create(req));
68
+ const created = (await dispatchedWrite(this, client.projects.create(req)));
72
69
  const data = {
73
70
  id: created.id ?? "",
74
71
  name: created.name ?? "",
@@ -121,25 +118,20 @@ export const registerProjectsCommand = (program, services) => {
121
118
  opts.billable !== undefined ||
122
119
  opts.archived !== undefined;
123
120
  if (!hasChanges) {
124
- throw new Error("projects.update needs a change: provide at least one project field.");
121
+ throw new UsageError("projects.update needs a change: provide at least one project field.");
125
122
  }
126
123
  const { client, workspaceId, output } = await resolveContext(this, services);
127
124
  const current = await client.projects.get({ workspaceId, projectId: id });
128
- const body = projectUpdateCarryFields(current);
129
- if (opts.name)
130
- body.name = opts.name;
131
- if (opts.client)
132
- body.clientId = opts.client;
133
- if (opts.color)
134
- body.color = opts.color;
135
- if (opts.note !== undefined)
136
- body.note = opts.note;
137
- if (opts.billable !== undefined)
138
- body.billable = opts.billable;
139
- if (opts.archived !== undefined)
140
- body.archived = opts.archived;
125
+ const body = projectUpdate.body(current, {
126
+ name: opts.name || undefined,
127
+ clientId: opts.client || undefined,
128
+ color: opts.color || undefined,
129
+ note: opts.note,
130
+ billable: opts.billable,
131
+ archived: opts.archived,
132
+ });
141
133
  const req = { workspaceId, projectId: id, body };
142
- const updated = (await client.projects.update(req));
134
+ const updated = (await dispatchedWrite(this, client.projects.update(req)));
143
135
  const data = { id: updated.id ?? id, name: updated.name ?? "" };
144
136
  printReceipt({
145
137
  ok: true,
@@ -162,26 +154,30 @@ export const registerProjectsCommand = (program, services) => {
162
154
  .addHelpText("after", "\nExamples:\n" + " $ clk115 projects delete project_123\n")
163
155
  .action(async function (id) {
164
156
  const { client, workspaceId, output } = await resolveContext(this, services);
157
+ let archivedByCall = false;
165
158
  await archiveThenDeleteProject({
166
159
  workspaceId,
167
160
  id,
168
161
  adapter: {
169
162
  getCurrent: ({ workspaceId: currentWorkspaceId, id: projectId }) => client.projects.get({ workspaceId: currentWorkspaceId, projectId }),
170
163
  archive: async ({ workspaceId: currentWorkspaceId, id: projectId, current, }) => {
171
- const preserved = projectUpdateCarryFields(current);
172
- await client.projects.update({
164
+ await dispatchedWrite(this, client.projects.update({
173
165
  workspaceId: currentWorkspaceId,
174
166
  projectId,
175
- name: current.name,
176
- ...preserved,
177
- archived: true,
178
- });
167
+ ...projectUpdate.body(current, { name: current.name, archived: true }),
168
+ }));
169
+ archivedByCall = true;
179
170
  },
180
171
  delete: async ({ workspaceId: currentWorkspaceId, id: projectId }) => {
181
- await client.projects.delete({
182
- workspaceId: currentWorkspaceId,
183
- projectId,
184
- });
172
+ try {
173
+ await dispatchedWrite(this, client.projects.delete({
174
+ workspaceId: currentWorkspaceId,
175
+ projectId,
176
+ }));
177
+ }
178
+ catch (cause) {
179
+ throw new PartialDeleteError(cause, "archived", `clk115 projects get ${id} --json`, archivedByCall ? "archived_by_call" : "already_archived");
180
+ }
185
181
  },
186
182
  },
187
183
  });
@@ -1,9 +1,20 @@
1
1
  import { REPORT_PERIODS, isExactWeeklyRange, parseWeeklyDateTime, resolveInstant, resolvePeriod, } from "clockify-sdk-ts-115/dates";
2
2
  import { detailedFilter, summaryFilter, weeklyFilter } from "clockify-sdk-ts-115/reports";
3
- import { printObject } from "../output.js";
4
- import { clampPageSize, parseIntArg, resolveContext } from "./helpers.js";
3
+ import { UsageError } from "../failure.js";
4
+ import { printData, printObject, printWarning } from "../output.js";
5
+ import { clampPageSize, parseIntArg, parseTimeViewMode, resolveContext, TIME_VIEW_MODE_HELP } from "./helpers.js";
5
6
  import { leafCommand } from "./leaf-command.js";
6
7
  import { resolveClientId, resolveProjectId } from "./resolve-refs.js";
8
+ function printReport(report, lists, output) {
9
+ const answer = (report ?? { totals: [] });
10
+ const isReport = ["totals", ...lists].some((list) => Array.isArray(answer[list]));
11
+ const rows = lists.map((list) => answer[list]).find((list) => Array.isArray(list) && list.length > 0);
12
+ if (output.mode === "csv" && isReport)
13
+ printData(rows ?? [], output);
14
+ else
15
+ printObject(report, output);
16
+ return rows ?? [];
17
+ }
7
18
  function resolveRange(opts) {
8
19
  const now = new Date();
9
20
  const periodInput = (opts.period ?? "this_month")
@@ -11,20 +22,20 @@ function resolveRange(opts) {
11
22
  .toLowerCase()
12
23
  .replace(/[\s-]+/g, "_");
13
24
  if (!REPORT_PERIODS.includes(periodInput)) {
14
- throw new Error(`Unknown --period "${opts.period}". Provide one of: ${REPORT_PERIODS.join(", ")}.`);
25
+ throw new UsageError(`Unknown --period "${opts.period}". Provide one of: ${REPORT_PERIODS.join(", ")}.`);
15
26
  }
16
27
  const range = resolvePeriod(now, periodInput);
17
28
  let { dateRangeStart, dateRangeEnd } = range;
18
29
  if (opts.from) {
19
30
  const start = resolveInstant(now, opts.from, "start");
20
31
  if (!start)
21
- throw new Error(`--from "${opts.from}" is not a valid date, ISO timestamp, or period; provide YYYY-MM-DD, an ISO timestamp, or a period name.`);
32
+ throw new UsageError(`--from "${opts.from}" is not a valid date, ISO timestamp, or period; provide YYYY-MM-DD, an ISO timestamp, or a period name.`);
22
33
  dateRangeStart = start;
23
34
  }
24
35
  if (opts.to) {
25
36
  const end = resolveInstant(now, opts.to, "end");
26
37
  if (!end)
27
- throw new Error(`--to "${opts.to}" is not a valid date, ISO timestamp, or period; provide YYYY-MM-DD, an ISO timestamp, or a period name.`);
38
+ throw new UsageError(`--to "${opts.to}" is not a valid date, ISO timestamp, or period; provide YYYY-MM-DD, an ISO timestamp, or a period name.`);
28
39
  dateRangeEnd = end;
29
40
  }
30
41
  return { dateRangeStart, dateRangeEnd };
@@ -45,7 +56,7 @@ function resolveWeeklyRange(opts) {
45
56
  dateRangeEnd = isExactWeeklyRange(dateRangeStart, exclusive) ? exclusive : inclusive;
46
57
  }
47
58
  if (!isExactWeeklyRange(dateRangeStart, dateRangeEnd)) {
48
- throw new Error("Weekly reports require one exact seven-day interval (exclusive next-midnight end or inclusive final-day 23:59:59 end). Provide --from and --to for one Monday-Sunday window or use --period last_week.");
59
+ throw new UsageError("Weekly reports require one exact seven-day interval (exclusive next-midnight end or inclusive final-day 23:59:59 end). Provide --from and --to for one Monday-Sunday window or use --period last_week.");
49
60
  }
50
61
  return { dateRangeStart, dateRangeEnd };
51
62
  }
@@ -54,7 +65,7 @@ function inspectWeeklyInput(raw, option) {
54
65
  return undefined;
55
66
  const trimmed = raw.trim();
56
67
  if (trimmed.length === 0) {
57
- throw new Error(`${option} must not be empty; provide YYYY-MM-DD, a full-seconds weekly timestamp, or a period name.`);
68
+ throw new UsageError(`${option} must not be empty; provide YYYY-MM-DD, a full-seconds weekly timestamp, or a period name.`);
58
69
  }
59
70
  if (isDateOnly(trimmed)) {
60
71
  if (parseWeeklyDateTime(`${trimmed}T00:00:00`) === undefined) {
@@ -73,7 +84,7 @@ function isDateOnly(value) {
73
84
  return /^\d{4}-\d{2}-\d{2}$/u.test(value);
74
85
  }
75
86
  function invalidWeeklyInput(option, raw) {
76
- return new Error(`${option} "${raw}" is not a valid date, full-seconds weekly timestamp, or period; use YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS[.fffffffff][Z].`);
87
+ return new UsageError(`${option} "${raw}" is not a valid date, full-seconds weekly timestamp, or period; use YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS[.fffffffff][Z].`);
77
88
  }
78
89
  function idFilter(ids) {
79
90
  return { ids, contains: "CONTAINS" };
@@ -95,29 +106,32 @@ function parseSummaryGroups(raw) {
95
106
  .map((group) => group.trim().toUpperCase())
96
107
  .filter(Boolean);
97
108
  if (groups.length === 0 || groups.length > 3) {
98
- throw new Error(`--groups must contain between one and three summary groups; provide 1-3 of: ${SUMMARY_GROUPS.join(", ")}.`);
109
+ throw new UsageError(`--groups must contain between one and three summary groups; provide 1-3 of: ${SUMMARY_GROUPS.join(", ")}.`);
99
110
  }
100
111
  const unknown = groups.find((group) => !SUMMARY_GROUPS.includes(group));
101
112
  if (unknown) {
102
- throw new Error(`Unknown summary group: ${unknown}. Provide one of: ${SUMMARY_GROUPS.join(", ")}.`);
113
+ throw new UsageError(`Unknown summary group: ${unknown}. Provide one of: ${SUMMARY_GROUPS.join(", ")}.`);
103
114
  }
104
115
  return groups;
105
116
  }
106
117
  function parseWeeklyGroup(raw) {
107
118
  const group = String(raw).toUpperCase();
108
119
  if (group !== "USER" && group !== "PROJECT") {
109
- throw new Error("Unknown --group for the weekly report. Provide one of: USER, PROJECT.");
120
+ throw new UsageError("Unknown --group for the weekly report. Provide one of: USER, PROJECT.");
110
121
  }
111
122
  return group;
112
123
  }
113
124
  function parseWeeklySubgroup(raw) {
114
125
  const subgroup = String(raw).toUpperCase();
115
126
  if (subgroup !== "TIME") {
116
- throw new Error("Unknown --subgroup for the weekly report. Provide one of: TIME.");
127
+ throw new UsageError("Unknown --subgroup for the weekly report. Provide one of: TIME.");
117
128
  }
118
129
  return subgroup;
119
130
  }
120
131
  const PERIOD_HELP = `Named period: ${REPORT_PERIODS.join(", ")} (default this_month).`;
132
+ function optionalTimeViewMode(opts) {
133
+ return opts.timeViewMode === undefined ? undefined : parseTimeViewMode(opts.timeViewMode);
134
+ }
121
135
  export const registerReportsCommand = (program, services) => {
122
136
  const reports = program.command("reports").description("Run Clockify reports (read-only).");
123
137
  leafCommand(reports, "summary", "read")
@@ -132,16 +146,20 @@ export const registerReportsCommand = (program, services) => {
132
146
  .option("--billable", "Only billable time.", false)
133
147
  .option("--project <name|id...>", "Scope to one or more project names or ids.")
134
148
  .option("--client <name|id...>", "Scope to one or more client names or ids.")
149
+ .option("--time-view-mode <mode>", TIME_VIEW_MODE_HELP)
135
150
  .action(async function (opts) {
136
- const { client, workspaceId, output } = await resolveContext(this, services);
137
151
  const { dateRangeStart, dateRangeEnd } = resolveRange(opts);
138
152
  const groups = parseSummaryGroups(opts.groups);
153
+ const timeViewMode = optionalTimeViewMode(opts);
154
+ const { client, workspaceId, output } = await resolveContext(this, services);
139
155
  const req = {
140
156
  workspaceId,
141
157
  dateRangeStart,
142
158
  dateRangeEnd,
143
159
  summaryFilter: summaryFilter(groups),
144
160
  };
161
+ if (timeViewMode !== undefined)
162
+ req.timeViewMode = timeViewMode;
145
163
  if (opts.billable)
146
164
  req.billable = true;
147
165
  if (Array.isArray(opts.project) && opts.project.length > 0) {
@@ -153,7 +171,7 @@ export const registerReportsCommand = (program, services) => {
153
171
  req.clients = idFilter(ids);
154
172
  }
155
173
  const data = await client.reports.summary(req);
156
- printObject(data, output);
174
+ printReport(data, ["groupOne"], output);
157
175
  });
158
176
  leafCommand(reports, "detailed", "read")
159
177
  .description("Detailed report listing individual time entries over a date range.")
@@ -163,20 +181,28 @@ export const registerReportsCommand = (program, services) => {
163
181
  .option("--to <date>", "Range end; overrides --period.")
164
182
  .option("--page <n>", "Page number.", parseIntArg, 1)
165
183
  .option("--page-size <n>", "Entries per page (max 1000).", parseIntArg, 50)
184
+ .option("--time-view-mode <mode>", TIME_VIEW_MODE_HELP)
166
185
  .action(async function (opts) {
186
+ const timeViewMode = optionalTimeViewMode(opts);
167
187
  const { client, workspaceId, output } = await resolveContext(this, services);
168
188
  const { dateRangeStart, dateRangeEnd } = resolveRange(opts);
189
+ const { page } = opts;
190
+ const pageSize = clampPageSize(opts.pageSize, 1000);
169
191
  const req = {
170
192
  workspaceId,
171
193
  dateRangeStart,
172
194
  dateRangeEnd,
173
195
  detailedFilter: detailedFilter({
174
- page: opts.page,
175
- pageSize: clampPageSize(opts.pageSize, 1000),
196
+ page,
197
+ pageSize,
176
198
  }),
199
+ ...(timeViewMode !== undefined ? { timeViewMode } : {}),
177
200
  };
178
201
  const data = await client.reports.detailed(req);
179
- printObject(data, output);
202
+ const entries = printReport(data, ["timeentries", "timeEntries"], output);
203
+ if (entries.length >= pageSize) {
204
+ printWarning(`Page ${page} is full (${entries.length} entries). Read on with --page ${page + 1}.`, output);
205
+ }
180
206
  });
181
207
  leafCommand(reports, "weekly", "read")
182
208
  .description("Weekly report for one exact seven-day interval.")
@@ -186,17 +212,21 @@ export const registerReportsCommand = (program, services) => {
186
212
  .option("--to <date>", "Range end; overrides --period.")
187
213
  .option("--group <group>", "Top grouping: USER or PROJECT.", "USER")
188
214
  .option("--subgroup <subgroup>", "Subgrouping (TIME).", "TIME")
215
+ .option("--time-view-mode <mode>", TIME_VIEW_MODE_HELP)
189
216
  .action(async function (opts) {
190
- const { client, workspaceId, output } = await resolveContext(this, services);
191
217
  const { dateRangeStart, dateRangeEnd } = resolveWeeklyRange(opts);
218
+ const timeViewMode = optionalTimeViewMode(opts);
219
+ const filter = weeklyFilter(parseWeeklyGroup(opts.group), parseWeeklySubgroup(opts.subgroup));
220
+ const { client, workspaceId, output } = await resolveContext(this, services);
192
221
  const req = {
193
222
  workspaceId,
194
223
  dateRangeStart,
195
224
  dateRangeEnd,
196
- weeklyFilter: weeklyFilter(parseWeeklyGroup(opts.group), parseWeeklySubgroup(opts.subgroup)),
225
+ weeklyFilter: filter,
226
+ ...(timeViewMode !== undefined ? { timeViewMode } : {}),
197
227
  };
198
228
  const data = await client.reports.weekly(req);
199
- printObject(data, output);
229
+ printReport(data, ["groupOne"], output);
200
230
  });
201
231
  leafCommand(reports, "attendance", "read")
202
232
  .description("Attendance report of clock-in/out activity over a date range.")
@@ -204,7 +234,9 @@ export const registerReportsCommand = (program, services) => {
204
234
  .option("--period <p>", PERIOD_HELP)
205
235
  .option("--from <date>", "Range start; overrides --period.")
206
236
  .option("--to <date>", "Range end; overrides --period.")
237
+ .option("--time-view-mode <mode>", TIME_VIEW_MODE_HELP)
207
238
  .action(async function (opts) {
239
+ const timeViewMode = optionalTimeViewMode(opts);
208
240
  const { client, workspaceId, output } = await resolveContext(this, services);
209
241
  const { dateRangeStart, dateRangeEnd } = resolveRange(opts);
210
242
  const req = {
@@ -212,8 +244,9 @@ export const registerReportsCommand = (program, services) => {
212
244
  dateRangeStart,
213
245
  dateRangeEnd,
214
246
  attendanceFilter: {},
247
+ ...(timeViewMode !== undefined ? { timeViewMode } : {}),
215
248
  };
216
249
  const data = await client.reports.attendance(req);
217
- printObject(data, output);
250
+ printReport(data, ["groupOne", "entities"], output);
218
251
  });
219
252
  };