@apet97/clockify-cli-115 5.0.3 → 6.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 (40) hide show
  1. package/README.md +96 -26
  2. package/dist/client.js +18 -15
  3. package/dist/closed-pipe.js +3 -0
  4. package/dist/commands/api.js +182 -61
  5. package/dist/commands/approvals.js +9 -7
  6. package/dist/commands/auditlog.js +11 -8
  7. package/dist/commands/balanceAssignment.js +10 -8
  8. package/dist/commands/clients.js +16 -7
  9. package/dist/commands/doctor.js +42 -25
  10. package/dist/commands/entries.js +29 -14
  11. package/dist/commands/expenses.js +64 -22
  12. package/dist/commands/helpers.js +28 -7
  13. package/dist/commands/invoices.js +12 -16
  14. package/dist/commands/leaf-command.js +8 -0
  15. package/dist/commands/log.js +4 -2
  16. package/dist/commands/projects.js +18 -9
  17. package/dist/commands/reports.js +73 -23
  18. package/dist/commands/resolve-refs.js +30 -53
  19. package/dist/commands/scheduling.js +94 -40
  20. package/dist/commands/shared-report-body.js +205 -0
  21. package/dist/commands/sharedReports.js +19 -215
  22. package/dist/commands/start.js +6 -4
  23. package/dist/commands/status.js +55 -19
  24. package/dist/commands/stop.js +15 -17
  25. package/dist/commands/tags.js +6 -4
  26. package/dist/commands/tasks.js +18 -23
  27. package/dist/commands/timeoff.js +23 -16
  28. package/dist/commands/users.js +7 -5
  29. package/dist/commands/webhooks.js +14 -12
  30. package/dist/completions.js +290 -55
  31. package/dist/config.js +10 -6
  32. package/dist/duration.js +5 -4
  33. package/dist/error-codes.js +34 -6
  34. package/dist/failure.js +87 -0
  35. package/dist/flags.js +74 -0
  36. package/dist/generated/version.js +1 -1
  37. package/dist/index.js +41 -105
  38. package/dist/output.js +62 -28
  39. package/dist/write-outcome.js +84 -0
  40. package/package.json +3 -3
@@ -1,7 +1,8 @@
1
- import { z } from "zod";
1
+ import { UsageError } from "../failure.js";
2
2
  import { printObject, printRecords } from "../output.js";
3
3
  import { printReceipt } from "../receipt.js";
4
- import { resolveBaseContext, resolveContext } from "./helpers.js";
4
+ import { dispatchedWrite } from "../write-outcome.js";
5
+ import { parseTimeViewMode, resolveBaseContext, resolveContext, TIME_VIEW_MODE_HELP } from "./helpers.js";
5
6
  import { leafCommand } from "./leaf-command.js";
6
7
  async function readReportBody(response) {
7
8
  const buffer = await response.arrayBuffer();
@@ -19,7 +20,7 @@ async function readReportBody(response) {
19
20
  return { body: text };
20
21
  }
21
22
  }
22
- const SHARED_REPORT_TYPES = [
23
+ export const SHARED_REPORT_TYPES = [
23
24
  "SUMMARY",
24
25
  "DETAILED",
25
26
  "WEEKLY",
@@ -40,9 +41,9 @@ const SHARED_REPORT_TYPES = [
40
41
  "TIMEOFF_BALANCE",
41
42
  "EXPENSE_SUMMARY",
42
43
  ];
43
- const SHARED_REPORT_FILTER_EXPORT_TYPES = ["JSON_V1", "JSON", "CSV", "XLSX", "PDF"];
44
+ export const SHARED_REPORT_FILTER_EXPORT_TYPES = ["JSON_V1", "JSON", "CSV", "XLSX", "PDF"];
44
45
  const SHARED_REPORT_VIEW_EXPORT_TYPES = ["JSON_V1", "JSON", "CSV"];
45
- const SUMMARY_GROUPS = [
46
+ export const SUMMARY_GROUPS = [
46
47
  "CLIENT",
47
48
  "PROJECT",
48
49
  "TASK",
@@ -53,208 +54,6 @@ const SUMMARY_GROUPS = [
53
54
  "USER",
54
55
  "TAG",
55
56
  ];
56
- const nonEmptyStringSchema = z
57
- .string()
58
- .refine((value) => value.trim() !== "", "must be a non-empty string.");
59
- const dateStringSchema = nonEmptyStringSchema.refine((value) => !Number.isNaN(Date.parse(value)), "must be a valid date string.");
60
- const upperCaseString = (value) => typeof value === "string" ? value.toUpperCase() : value;
61
- const sharedReportTypeSchema = z.preprocess(upperCaseString, z.enum(SHARED_REPORT_TYPES));
62
- const sharedReportExportTypeSchema = z.preprocess(upperCaseString, z.enum(SHARED_REPORT_FILTER_EXPORT_TYPES));
63
- const openObjectSchema = z.record(z.string(), z.unknown());
64
- const INT_MESSAGE = { error: "provide a whole integer" };
65
- const sharedUsersFilterSchema = z
66
- .object({
67
- contains: z.enum(["CONTAINS", "DOES_NOT_CONTAIN", "CONTAINS_ONLY"]).optional(),
68
- ids: z.array(z.string()).optional(),
69
- status: z.enum(["ALL", "ACTIVE", "INACTIVE"]).optional(),
70
- })
71
- .strict();
72
- const sharedAttendanceFilterSchema = z
73
- .object({
74
- page: z.number().int(INT_MESSAGE).optional(),
75
- pageSize: z.number().int(INT_MESSAGE).optional(),
76
- users: sharedUsersFilterSchema.optional(),
77
- })
78
- .strict();
79
- const sharedDetailedFilterSchema = z
80
- .object({
81
- auditFilter: openObjectSchema.optional(),
82
- options: openObjectSchema.optional(),
83
- page: z.number().int(INT_MESSAGE).optional(),
84
- pageSize: z.number().int(INT_MESSAGE).optional(),
85
- sortColumn: nonEmptyStringSchema.optional(),
86
- sortOrder: z.enum(["ASCENDING", "DESCENDING"]).optional(),
87
- })
88
- .strict();
89
- const sharedSummaryFilterSchema = z
90
- .object({
91
- groups: z
92
- .array(z.enum(SUMMARY_GROUPS))
93
- .min(1, { error: `provide 1-3 of: ${SUMMARY_GROUPS.join(", ")}` })
94
- .max(3, { error: `provide at most 3 of: ${SUMMARY_GROUPS.join(", ")}` }),
95
- sortColumn: nonEmptyStringSchema.optional(),
96
- })
97
- .strict();
98
- const sharedWeeklyFilterSchema = z
99
- .object({
100
- group: z.enum(["PROJECT", "USER"]),
101
- subgroup: z.literal("TIME"),
102
- })
103
- .strict();
104
- const sharedReportFilterSchema = z
105
- .object({
106
- attendanceFilter: sharedAttendanceFilterSchema.optional(),
107
- dateRangeEnd: dateStringSchema,
108
- dateRangeStart: dateStringSchema,
109
- detailedFilter: sharedDetailedFilterSchema.optional(),
110
- exportType: sharedReportExportTypeSchema,
111
- summaryFilter: sharedSummaryFilterSchema.optional(),
112
- weeklyFilter: sharedWeeklyFilterSchema.optional(),
113
- })
114
- .strict();
115
- const sharedReportBodyShape = {
116
- filter: sharedReportFilterSchema,
117
- isPublic: z.boolean().optional(),
118
- name: nonEmptyStringSchema,
119
- type: sharedReportTypeSchema,
120
- };
121
- const sharedReportCreateBodySchema = z.object(sharedReportBodyShape).strict();
122
- const sharedReportUpdateBodySchema = z.object(sharedReportBodyShape).strict();
123
- function toSharedUsersFilter(value) {
124
- return {
125
- ...(value.contains !== undefined ? { contains: value.contains } : {}),
126
- ...(value.ids !== undefined ? { ids: value.ids } : {}),
127
- ...(value.status !== undefined ? { status: value.status } : {}),
128
- };
129
- }
130
- function toSharedReportFilter(value) {
131
- return {
132
- dateRangeEnd: value.dateRangeEnd,
133
- dateRangeStart: value.dateRangeStart,
134
- exportType: value.exportType,
135
- ...(value.attendanceFilter !== undefined
136
- ? {
137
- attendanceFilter: {
138
- ...(value.attendanceFilter.page !== undefined
139
- ? { page: value.attendanceFilter.page }
140
- : {}),
141
- ...(value.attendanceFilter.pageSize !== undefined
142
- ? { pageSize: value.attendanceFilter.pageSize }
143
- : {}),
144
- ...(value.attendanceFilter.users !== undefined
145
- ? { users: toSharedUsersFilter(value.attendanceFilter.users) }
146
- : {}),
147
- },
148
- }
149
- : {}),
150
- ...(value.detailedFilter !== undefined
151
- ? {
152
- detailedFilter: {
153
- ...(value.detailedFilter.auditFilter !== undefined
154
- ? { auditFilter: value.detailedFilter.auditFilter }
155
- : {}),
156
- ...(value.detailedFilter.options !== undefined
157
- ? { options: value.detailedFilter.options }
158
- : {}),
159
- ...(value.detailedFilter.page !== undefined
160
- ? { page: value.detailedFilter.page }
161
- : {}),
162
- ...(value.detailedFilter.pageSize !== undefined
163
- ? { pageSize: value.detailedFilter.pageSize }
164
- : {}),
165
- ...(value.detailedFilter.sortColumn !== undefined
166
- ? { sortColumn: value.detailedFilter.sortColumn }
167
- : {}),
168
- ...(value.detailedFilter.sortOrder !== undefined
169
- ? { sortOrder: value.detailedFilter.sortOrder }
170
- : {}),
171
- },
172
- }
173
- : {}),
174
- ...(value.summaryFilter !== undefined
175
- ? {
176
- summaryFilter: {
177
- groups: value.summaryFilter.groups,
178
- ...(value.summaryFilter.sortColumn !== undefined
179
- ? { sortColumn: value.summaryFilter.sortColumn }
180
- : {}),
181
- },
182
- }
183
- : {}),
184
- ...(value.weeklyFilter !== undefined
185
- ? {
186
- weeklyFilter: {
187
- group: value.weeklyFilter.group,
188
- subgroup: value.weeklyFilter.subgroup,
189
- },
190
- }
191
- : {}),
192
- };
193
- }
194
- function toSharedReportBody(value) {
195
- return {
196
- filter: toSharedReportFilter(value.filter),
197
- name: value.name,
198
- type: value.type,
199
- ...(value.isPublic !== undefined ? { isPublic: value.isPublic } : {}),
200
- };
201
- }
202
- function parseFilterJson(raw) {
203
- if (typeof raw !== "string") {
204
- throw new Error("--filter must be a JSON object.");
205
- }
206
- try {
207
- return JSON.parse(raw);
208
- }
209
- catch {
210
- throw new Error(`--filter must be a JSON object, e.g. '{"dateRangeStart":"…","dateRangeEnd":"…"}'`);
211
- }
212
- }
213
- function schemaIssueLabel(issue, operation) {
214
- const [root, ...path] = issue.path;
215
- if (root === "filter") {
216
- return path.length > 0 ? `--filter ${path.join(".")}` : "--filter";
217
- }
218
- if (root === "name")
219
- return "--name";
220
- if (root === "type")
221
- return "--type";
222
- return operation;
223
- }
224
- function sharedReportValidationError(error, operation, rawType) {
225
- const invalidTypeIssue = error.issues.find((issue) => issue.path[0] === "type" && issue.code === "invalid_value");
226
- if (invalidTypeIssue !== undefined) {
227
- return new Error(`Unknown --type "${String(rawType)}". Provide one of: ${SHARED_REPORT_TYPES.join(", ")}.`);
228
- }
229
- const issue = error.issues[0];
230
- if (issue === undefined)
231
- return new Error(`${operation}: invalid request.`);
232
- if (issue.path.length === 1 &&
233
- issue.path[0] === "filter" &&
234
- issue.code === "invalid_type" &&
235
- issue.expected === "object") {
236
- return new Error("--filter must be a JSON object.");
237
- }
238
- const label = schemaIssueLabel(issue, operation);
239
- if (issue.code === "unrecognized_keys") {
240
- const fieldKind = issue.path[0] === "filter" ? "filter field(s)" : "field(s)";
241
- return new Error(`${label} has unknown ${fieldKind}: ${issue.keys.join(", ")}.`);
242
- }
243
- return new Error(`${label}: ${issue.message}`);
244
- }
245
- function parseSharedReportBody(schema, opts, operation) {
246
- const candidate = {
247
- name: opts.name,
248
- type: opts.type,
249
- filter: parseFilterJson(opts.filter),
250
- ...(opts.public !== undefined ? { isPublic: opts.public } : {}),
251
- };
252
- const result = schema.safeParse(candidate);
253
- if (!result.success) {
254
- throw sharedReportValidationError(result.error, operation, opts.type);
255
- }
256
- return toSharedReportBody(result.data);
257
- }
258
57
  export const registerSharedReportsCommand = (program, services) => {
259
58
  const shared = program
260
59
  .command("shared-reports")
@@ -277,6 +76,7 @@ export const registerSharedReportsCommand = (program, services) => {
277
76
  leafCommand(shared, "view", "read")
278
77
  .argument("<id>", "Shared-report ID.")
279
78
  .option("--export-type <type>", "Text-safe export type: JSON_V1, JSON, or CSV (default JSON_V1).")
79
+ .option("--time-view-mode <mode>", TIME_VIEW_MODE_HELP)
280
80
  .description("View a shared report's rendered data by ID (reports host; not workspace-scoped).")
281
81
  .addHelpText("after", "\nExamples:\n" +
282
82
  " $ clk115 shared-reports view report_123\n" +
@@ -284,16 +84,18 @@ export const registerSharedReportsCommand = (program, services) => {
284
84
  .action(async function (id, opts) {
285
85
  const candidate = opts.exportType ? String(opts.exportType).toUpperCase() : "JSON_V1";
286
86
  if (candidate === "XLSX" || candidate === "PDF") {
287
- throw new Error(`--export-type ${candidate} is unavailable because the CLI cannot stream binary output to a file yet. Provide one of: ${SHARED_REPORT_VIEW_EXPORT_TYPES.join(", ")}. Run \`clk115 shared-reports list\` and open the report link for binary downloads.`);
87
+ throw new UsageError(`--export-type ${candidate} is unavailable because the CLI cannot stream binary output to a file yet. Provide one of: ${SHARED_REPORT_VIEW_EXPORT_TYPES.join(", ")}. Run \`clk115 shared-reports list\` and open the report link for binary downloads.`);
288
88
  }
289
89
  if (!SHARED_REPORT_VIEW_EXPORT_TYPES.includes(candidate)) {
290
- throw new Error(`Unknown --export-type "${String(opts.exportType)}". Provide one of: ${SHARED_REPORT_VIEW_EXPORT_TYPES.join(", ")}.`);
90
+ throw new UsageError(`Unknown --export-type "${String(opts.exportType)}". Provide one of: ${SHARED_REPORT_VIEW_EXPORT_TYPES.join(", ")}.`);
291
91
  }
92
+ const timeViewMode = opts.timeViewMode === undefined ? undefined : parseTimeViewMode(opts.timeViewMode);
292
93
  const { client, output } = await resolveBaseContext(this, services);
293
94
  const exportType = candidate;
294
95
  const response = await client.sharedReports.view({
295
96
  sharedReportId: id,
296
97
  exportType,
98
+ ...(timeViewMode !== undefined ? { timeViewMode } : {}),
297
99
  });
298
100
  printObject(await readReportBody(response), output);
299
101
  });
@@ -308,10 +110,11 @@ export const registerSharedReportsCommand = (program, services) => {
308
110
  " $ clk115 shared-reports create --name \"Q3 Summary\" --type SUMMARY \\\n" +
309
111
  " --filter '{\"dateRangeStart\":\"2026-07-01\",\"dateRangeEnd\":\"2026-09-30\",\"exportType\":\"JSON_V1\"}' --public\n")
310
112
  .action(async function (opts) {
113
+ const { parseSharedReportBody } = await import("./shared-report-body.js");
114
+ const body = parseSharedReportBody(opts, "shared-reports.create");
311
115
  const { client, workspaceId, output } = await resolveContext(this, services);
312
- const body = parseSharedReportBody(sharedReportCreateBodySchema, opts, "shared-reports.create");
313
116
  const request = { workspaceId, body };
314
- const created = (await client.sharedReports.create(request));
117
+ const created = (await dispatchedWrite(this, client.sharedReports.create(request)));
315
118
  const data = { id: created.id ?? "", name: created.name ?? opts.name };
316
119
  printReceipt({
317
120
  ok: true,
@@ -338,16 +141,17 @@ export const registerSharedReportsCommand = (program, services) => {
338
141
  .description("Replace a shared report by ID (full replace of name, type, and filter).")
339
142
  .addHelpText("after", "\nExamples:\n" +
340
143
  " $ clk115 shared-reports update report_123 --name \"Q3 Summary\" \\\n" +
341
- " --type SUMMARY --filter '{}'\n")
144
+ " --type SUMMARY --filter '{\"dateRangeStart\":\"2026-07-01\",\"dateRangeEnd\":\"2026-09-30\",\"exportType\":\"JSON_V1\"}'\n")
342
145
  .action(async function (id, opts) {
146
+ const { parseSharedReportBody } = await import("./shared-report-body.js");
147
+ const body = parseSharedReportBody(opts, "shared-reports.update");
343
148
  const { client, workspaceId, output } = await resolveContext(this, services);
344
- const body = parseSharedReportBody(sharedReportUpdateBodySchema, opts, "shared-reports.update");
345
149
  const request = {
346
150
  workspaceId,
347
151
  sharedReportId: id,
348
152
  body,
349
153
  };
350
- const updated = (await client.sharedReports.update(request));
154
+ const updated = (await dispatchedWrite(this, client.sharedReports.update(request)));
351
155
  const data = { id: updated.id ?? id, name: updated.name ?? opts.name };
352
156
  printReceipt({
353
157
  ok: true,
@@ -370,7 +174,7 @@ export const registerSharedReportsCommand = (program, services) => {
370
174
  .addHelpText("after", "\nExamples:\n" + " $ clk115 shared-reports delete report_123\n")
371
175
  .action(async function (id) {
372
176
  const { client, workspaceId, output } = await resolveContext(this, services);
373
- await client.sharedReports.delete({ workspaceId, sharedReportId: id });
177
+ await dispatchedWrite(this, client.sharedReports.delete({ workspaceId, sharedReportId: id }));
374
178
  printReceipt({
375
179
  ok: true,
376
180
  action: "shared-reports.delete",
@@ -1,4 +1,6 @@
1
+ import { UsageError } from "../failure.js";
1
2
  import { printReceipt } from "../receipt.js";
3
+ import { dispatchedWrite } from "../write-outcome.js";
2
4
  import { resolveContext } from "./helpers.js";
3
5
  import { leafCommand } from "./leaf-command.js";
4
6
  import { resolveProjectId, resolveTaskId, resolveTagIds } from "./resolve-refs.js";
@@ -14,13 +16,13 @@ export const registerStartCommand = (program, services) => {
14
16
  .option("--tag <name...>", "Tag name(s) or ID(s). Repeat the flag for multiple tags.")
15
17
  .option("--billable", "Mark the entry as billable.", false)
16
18
  .action(async function (description, opts) {
19
+ if (opts.task && !opts.project) {
20
+ throw new UsageError("--task requires --project: a task can only be resolved within a project.");
21
+ }
17
22
  const { client, workspaceId, output } = await resolveContext(this, services);
18
23
  const projectId = opts.project
19
24
  ? await resolveProjectId(client, workspaceId, opts.project)
20
25
  : undefined;
21
- if (opts.task && !projectId) {
22
- throw new Error("--task requires --project: a task can only be resolved within a project.");
23
- }
24
26
  const taskId = opts.task && projectId
25
27
  ? await resolveTaskId(client, workspaceId, projectId, opts.task)
26
28
  : undefined;
@@ -41,7 +43,7 @@ export const registerStartCommand = (program, services) => {
41
43
  if (opts.billable)
42
44
  body.billable = true;
43
45
  const req = { workspaceId, body };
44
- const created = await client.timeEntries.create(req);
46
+ const created = await dispatchedWrite(this, client.timeEntries.create(req));
45
47
  const entry = created;
46
48
  const data = {
47
49
  id: entry.id ?? "",
@@ -1,9 +1,12 @@
1
- import { iterAll } from "clockify-sdk-ts-115/iter";
2
1
  import { entityId } from "clockify-sdk-ts-115/operation-receipt";
3
2
  import { formatIsoDuration } from "../duration.js";
4
3
  import { printObject } from "../output.js";
5
4
  import { resolveBaseContext } from "./helpers.js";
6
5
  import { leafCommand } from "./leaf-command.js";
6
+ const TIMER_UNAVAILABLE = {
7
+ user_id_missing: "(timer lookup skipped: current user ID unavailable)",
8
+ response_unrecognized: "(timer state unknown: unrecognized response to the timer lookup)",
9
+ };
7
10
  export const registerStatusCommand = (program, services) => {
8
11
  leafCommand(program, "status", "read")
9
12
  .description("Show the configured workspace, current user, and running timer.")
@@ -13,39 +16,69 @@ export const registerStatusCommand = (program, services) => {
13
16
  .action(async function () {
14
17
  const { client, config, output } = await resolveBaseContext(this, services);
15
18
  const user = await client.users.getCurrentUser();
19
+ let statusState;
16
20
  if (!config.workspaceId) {
17
21
  const workspaces = (await client.workspaces.list());
22
+ statusState = {
23
+ kind: "workspace_unconfigured",
24
+ availableWorkspaces: workspaces.map((w) => ({
25
+ id: w.id ?? "",
26
+ name: w.name ?? "",
27
+ })),
28
+ };
29
+ }
30
+ else {
31
+ const workspaceId = config.workspaceId;
32
+ const userId = entityId(user);
33
+ if (userId?.trim()) {
34
+ const entries = normaliseEntries(await client.timeEntries.listForUser({
35
+ workspaceId,
36
+ userId,
37
+ "in-progress": true,
38
+ "page-size": 1,
39
+ }));
40
+ const entry = entries?.find((candidate) => isOwn(candidate, user) && isRunning(candidate));
41
+ if (entries === undefined) {
42
+ statusState = { kind: "unavailable", workspaceId, reason: "response_unrecognized" };
43
+ }
44
+ else {
45
+ statusState = entry === undefined ? { kind: "idle", workspaceId } : { kind: "timer_running", workspaceId, entry };
46
+ }
47
+ }
48
+ else {
49
+ statusState = { kind: "unavailable", workspaceId, reason: "user_id_missing" };
50
+ }
51
+ }
52
+ if (statusState.kind === "workspace_unconfigured") {
18
53
  printObject({
19
54
  userId: entityId(user) ?? "",
20
55
  email: user.email ?? "",
21
56
  workspaceId: "(not set)",
22
- availableWorkspaces: workspaces.map((w) => ({ id: w.id ?? "", name: w.name ?? "" })),
57
+ timerState: "unavailable",
58
+ timerStateReason: "workspace_not_set",
59
+ availableWorkspaces: statusState.availableWorkspaces,
23
60
  hint: "Set CLOCKIFY_WORKSPACE_ID (or pass --workspace, or add workspaceId to ~/.clockifyrc.json) to one of the ids above.",
24
61
  }, output);
25
62
  return;
26
63
  }
27
- const workspaceId = config.workspaceId;
28
- let running = null;
29
- for await (const entry of iterAll(async (req) => normaliseEntries(await client.timeEntries.listInProgress(req)), { workspaceId }, { pageSize: 200, maxPages: 1000 })) {
30
- if (isOwn(entry, user)) {
31
- running = entry;
32
- break;
33
- }
34
- }
35
64
  printObject({
36
- workspaceId,
65
+ workspaceId: statusState.workspaceId,
37
66
  userId: entityId(user) ?? "",
38
67
  email: user.email ?? "",
39
68
  name: user.name ?? "",
40
- runningEntry: running
69
+ timerState: statusState.kind,
70
+ ...(statusState.kind === "unavailable" && { timerStateReason: statusState.reason }),
71
+ runningEntry: statusState.kind === "timer_running"
41
72
  ? {
42
- id: entityId(running),
43
- description: running.description ?? "",
44
- projectId: running.projectId ?? "",
45
- startedAt: extractStart(running),
46
- elapsed: formatRunningElapsed(running),
73
+ id: entityId(statusState.entry),
74
+ description: statusState.entry.description ??
75
+ "",
76
+ projectId: statusState.entry
77
+ .projectId ?? "",
78
+ startedAt: extractStart(statusState.entry),
79
+ elapsed: formatRunningElapsed(statusState.entry),
47
80
  }
48
- : "(no timer running)",
81
+ : statusState.kind === "idle" ? "(no timer running)" : TIMER_UNAVAILABLE[statusState.reason],
49
82
  }, output);
50
83
  });
51
84
  };
@@ -57,13 +90,16 @@ function normaliseEntries(resp) {
57
90
  if (Array.isArray(candidate))
58
91
  return candidate;
59
92
  }
60
- return [];
93
+ return undefined;
61
94
  }
62
95
  function isOwn(entry, user) {
63
96
  const entryUserId = entry.userId;
64
97
  const userId = entityId(user);
65
98
  return entryUserId !== undefined && userId !== undefined && entryUserId === userId;
66
99
  }
100
+ function isRunning(entry) {
101
+ return entry.timeInterval?.end == null;
102
+ }
67
103
  function extractStart(entry) {
68
104
  const interval = entry.timeInterval;
69
105
  return interval?.start ?? "";
@@ -1,7 +1,6 @@
1
- import { iterAll } from "clockify-sdk-ts-115/iter";
2
- import { entityId } from "clockify-sdk-ts-115/operation-receipt";
3
1
  import { printReceipt } from "../receipt.js";
4
- import { resolveContext } from "./helpers.js";
2
+ import { dispatchedWrite } from "../write-outcome.js";
3
+ import { requireCurrentUserId, resolveContext } from "./helpers.js";
5
4
  import { leafCommand } from "./leaf-command.js";
6
5
  export const registerStopCommand = (program, services) => {
7
6
  leafCommand(program, "stop", "write")
@@ -11,20 +10,19 @@ export const registerStopCommand = (program, services) => {
11
10
  " $ clk115 stop --json\n")
12
11
  .action(async function () {
13
12
  const { client, workspaceId, output } = await resolveContext(this, services);
14
- const user = await client.users.getCurrentUser();
15
- const userId = entityId(user);
16
- if (!userId) {
17
- throw new Error("could not determine user ID from getCurrentUser response");
13
+ const userId = await requireCurrentUserId(client);
14
+ let timerState = { kind: "idle" };
15
+ const entries = await client.timeEntries.listForUser({
16
+ workspaceId,
17
+ userId,
18
+ "in-progress": true,
19
+ "page-size": 1,
20
+ });
21
+ const running = entries.find((entry) => entry.userId === userId && entry.id && entry.timeInterval?.end == null);
22
+ if (running?.id && running.userId) {
23
+ timerState = { kind: "running", entry: { id: running.id, userId: running.userId } };
18
24
  }
19
- let running;
20
- for await (const item of iterAll((req) => client.timeEntries.listInProgress(req), { workspaceId }, { pageSize: 200, maxPages: 1000 })) {
21
- const entry = item;
22
- if (entry.userId === userId && entry.id) {
23
- running = entry;
24
- break;
25
- }
26
- }
27
- if (!running) {
25
+ if (timerState.kind === "idle") {
28
26
  printReceipt({
29
27
  ok: true,
30
28
  action: "timer.stop",
@@ -37,7 +35,7 @@ export const registerStopCommand = (program, services) => {
37
35
  return;
38
36
  }
39
37
  const end = new Date().toISOString();
40
- const stopped = await client.timeEntries.updateForUser({ workspaceId, userId, end });
38
+ const stopped = await dispatchedWrite(this, client.timeEntries.updateForUser({ workspaceId, userId, end }));
41
39
  const entry = stopped;
42
40
  const data = {
43
41
  ...entry,
@@ -1,5 +1,7 @@
1
+ import { UsageError } from "../failure.js";
1
2
  import { printObject, printRecords } from "../output.js";
2
3
  import { printReceipt } from "../receipt.js";
4
+ import { dispatchedWrite } from "../write-outcome.js";
3
5
  import { clampPageSize, parseIntArg, resolveContext } from "./helpers.js";
4
6
  import { leafCommand } from "./leaf-command.js";
5
7
  export const registerTagsCommand = (program, services) => {
@@ -42,7 +44,7 @@ export const registerTagsCommand = (program, services) => {
42
44
  .action(async function (name) {
43
45
  const { client, workspaceId, output } = await resolveContext(this, services);
44
46
  const req = { workspaceId, body: { name } };
45
- const created = (await client.tags.create(req));
47
+ const created = (await dispatchedWrite(this, client.tags.create(req)));
46
48
  const data = { id: created.id ?? "", name: created.name ?? "" };
47
49
  printReceipt({
48
50
  ok: true,
@@ -76,7 +78,7 @@ export const registerTagsCommand = (program, services) => {
76
78
  " $ clk115 tags update tag_123 --archived\n")
77
79
  .action(async function (id, opts) {
78
80
  if (!opts.name && opts.archived === undefined) {
79
- throw new Error("tags.update needs a change: provide at least one tag field.");
81
+ throw new UsageError("tags.update needs a change: provide at least one tag field.");
80
82
  }
81
83
  const { client, workspaceId, output } = await resolveContext(this, services);
82
84
  const current = opts.name && opts.archived !== undefined
@@ -87,7 +89,7 @@ export const registerTagsCommand = (program, services) => {
87
89
  archived: opts.archived ?? current.archived ?? false,
88
90
  };
89
91
  const req = { workspaceId, tagId: id, body };
90
- const updated = (await client.tags.update(req));
92
+ const updated = (await dispatchedWrite(this, client.tags.update(req)));
91
93
  const data = { id: updated.id ?? id, name: updated.name ?? "" };
92
94
  printReceipt({
93
95
  ok: true,
@@ -105,7 +107,7 @@ export const registerTagsCommand = (program, services) => {
105
107
  .addHelpText("after", "\nExamples:\n" + " $ clk115 tags delete tag_123\n")
106
108
  .action(async function (id) {
107
109
  const { client, workspaceId, output } = await resolveContext(this, services);
108
- await client.tags.delete({ workspaceId, tagId: id });
110
+ await dispatchedWrite(this, client.tags.delete({ workspaceId, tagId: id }));
109
111
  printReceipt({
110
112
  ok: true,
111
113
  action: "tags.delete",
@@ -1,5 +1,7 @@
1
+ import { PartialDeleteError, UsageError } from "../failure.js";
1
2
  import { printObject, printRecords } from "../output.js";
2
3
  import { printReceipt } from "../receipt.js";
4
+ import { dispatchedWrite } from "../write-outcome.js";
3
5
  import { clampPageSize, parseIntArg, resolveContext } from "./helpers.js";
4
6
  import { leafCommand } from "./leaf-command.js";
5
7
  function requireTaskName(value, source) {
@@ -8,10 +10,11 @@ function requireTaskName(value, source) {
8
10
  }
9
11
  return value;
10
12
  }
11
- function taskStatus(value, source) {
13
+ function taskStatus(value, source, operatorInput = false) {
12
14
  const status = String(value).toUpperCase();
13
15
  if (status !== "ACTIVE" && status !== "DONE") {
14
- throw new Error(`${source} has unknown task status: ${String(value)}; provide ACTIVE or DONE`);
16
+ const message = `${source} has unknown task status: ${String(value)}; provide ACTIVE or DONE`;
17
+ throw operatorInput ? new UsageError(message) : new Error(message);
15
18
  }
16
19
  return status;
17
20
  }
@@ -139,7 +142,7 @@ export const registerTasksCommand = (program, services) => {
139
142
  projectId,
140
143
  body,
141
144
  };
142
- const created = (await client.tasks.create(req));
145
+ const created = (await dispatchedWrite(this, client.tasks.create(req)));
143
146
  const data = { id: created.id ?? "", name: created.name ?? name };
144
147
  printReceipt({
145
148
  ok: true,
@@ -180,15 +183,18 @@ export const registerTasksCommand = (program, services) => {
180
183
  " $ clk115 tasks update project_123 task_456 --status DONE\n" +
181
184
  " $ clk115 tasks update project_123 task_456 --name \"New name\"\n")
182
185
  .action(async function (projectId, id, opts) {
183
- const { client, workspaceId, output } = await resolveContext(this, services);
184
186
  const hasChanges = opts.name !== undefined ||
185
187
  opts.status !== undefined ||
186
188
  opts.estimate !== undefined ||
187
189
  opts.billable !== undefined ||
188
190
  opts.assignee !== undefined;
189
191
  if (!hasChanges) {
190
- throw new Error("tasks.update needs a change: provide at least one task field.");
192
+ throw new UsageError("tasks.update needs a change: provide at least one task field.");
191
193
  }
194
+ const requestedStatus = opts.status === undefined
195
+ ? undefined
196
+ : taskStatus(opts.status, "Task update request", true);
197
+ const { client, workspaceId, output } = await resolveContext(this, services);
192
198
  const current = (await client.tasks.get({
193
199
  workspaceId,
194
200
  projectId,
@@ -196,10 +202,9 @@ export const registerTasksCommand = (program, services) => {
196
202
  }));
197
203
  const body = reconstructTaskBody(current, opts.name);
198
204
  let changed = opts.name !== undefined && opts.name !== current.name;
199
- if (opts.status !== undefined) {
200
- const status = taskStatus(opts.status, "Task update request");
201
- changed = changed || status !== body.status;
202
- body.status = status;
205
+ if (requestedStatus !== undefined) {
206
+ changed = changed || requestedStatus !== body.status;
207
+ body.status = requestedStatus;
203
208
  }
204
209
  if (opts.estimate !== undefined) {
205
210
  changed = changed || opts.estimate !== body.estimate;
@@ -222,7 +227,7 @@ export const registerTasksCommand = (program, services) => {
222
227
  taskId: id,
223
228
  body,
224
229
  };
225
- const updated = (await client.tasks.update(req));
230
+ const updated = (await dispatchedWrite(this, client.tasks.update(req)));
226
231
  const data = { id: updated.id ?? id, name: updated.name ?? body.name };
227
232
  printReceipt({
228
233
  ok: true,
@@ -263,24 +268,14 @@ export const registerTasksCommand = (program, services) => {
263
268
  taskId: id,
264
269
  body: { ...originalBody, status: "DONE" },
265
270
  };
266
- await client.tasks.update(doneRequest);
271
+ await dispatchedWrite(this, client.tasks.update(doneRequest));
267
272
  }
268
273
  try {
269
- await client.tasks.delete({ workspaceId, projectId, taskId: id });
274
+ await dispatchedWrite(this, client.tasks.delete({ workspaceId, projectId, taskId: id }));
270
275
  }
271
276
  catch (error) {
272
277
  if (changedStatus) {
273
- const rollbackRequest = {
274
- workspaceId,
275
- projectId,
276
- taskId: id,
277
- body: originalBody,
278
- };
279
- try {
280
- await client.tasks.update(rollbackRequest);
281
- }
282
- catch {
283
- }
278
+ throw new PartialDeleteError(error, "marked_done", `clk115 tasks get ${projectId} ${id} --json`);
284
279
  }
285
280
  throw error;
286
281
  }