@apet97/clockify-cli-115 0.1.1 → 0.3.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.
@@ -1,12 +1,12 @@
1
1
  import { printRecords } from "../output.js";
2
2
  import { printReceipt } from "../receipt.js";
3
3
  import { clampPageSize, parseFloatArg, parseIntArg, promoteDateBoundary, resolveContext, } from "./helpers.js";
4
+ import { leafCommand } from "./leaf-command.js";
4
5
  export const registerSchedulingCommand = (program, services) => {
5
6
  const scheduling = program
6
7
  .command("scheduling")
7
8
  .description("Capacity scheduling assignments.");
8
- scheduling
9
- .command("list")
9
+ leafCommand(scheduling, "list", "read")
10
10
  .description("List scheduling assignments over a date range. --from/--to are required (the endpoint 400s without them).")
11
11
  .requiredOption("--from <date>", "Range start (YYYY-MM-DD or RFC3339). Required.")
12
12
  .requiredOption("--to <date>", "Range end (YYYY-MM-DD or RFC3339). Required.")
@@ -41,8 +41,7 @@ export const registerSchedulingCommand = (program, services) => {
41
41
  });
42
42
  printRecords(rows, output);
43
43
  });
44
- scheduling
45
- .command("create")
44
+ leafCommand(scheduling, "create", "write")
46
45
  .description("Create a scheduling assignment (defaults to draft; pass --publish to publish).")
47
46
  .requiredOption("--user <id>", "User ID to assign.")
48
47
  .requiredOption("--project <id>", "Project ID.")
@@ -1,7 +1,8 @@
1
- import { wireBody } from "clockify-sdk-ts-115/requests";
1
+ import { z } from "zod";
2
2
  import { printObject } from "../output.js";
3
3
  import { printReceipt } from "../receipt.js";
4
4
  import { resolveContext } from "./helpers.js";
5
+ import { leafCommand } from "./leaf-command.js";
5
6
  async function readReportBody(response) {
6
7
  const text = new TextDecoder().decode(await response.arrayBuffer());
7
8
  if (!text)
@@ -38,39 +39,221 @@ const SHARED_REPORT_TYPES = [
38
39
  "TIMEOFF_BALANCE",
39
40
  "EXPENSE_SUMMARY",
40
41
  ];
41
- function parseFilter(raw) {
42
+ const SHARED_REPORT_EXPORT_TYPES = ["JSON_V1", "JSON", "CSV", "XLSX", "PDF"];
43
+ const SUMMARY_GROUPS = [
44
+ "CLIENT",
45
+ "PROJECT",
46
+ "TASK",
47
+ "DATE",
48
+ "WEEK",
49
+ "MONTH",
50
+ "TIMEENTRY",
51
+ "USER",
52
+ "TAG",
53
+ ];
54
+ const nonEmptyStringSchema = z
55
+ .string()
56
+ .refine((value) => value.trim() !== "", "must be a non-empty string.");
57
+ const dateStringSchema = nonEmptyStringSchema.refine((value) => !Number.isNaN(Date.parse(value)), "must be a valid date string.");
58
+ const upperCaseString = (value) => typeof value === "string" ? value.toUpperCase() : value;
59
+ const sharedReportTypeSchema = z.preprocess(upperCaseString, z.enum(SHARED_REPORT_TYPES));
60
+ const sharedReportExportTypeSchema = z.preprocess(upperCaseString, z.enum(SHARED_REPORT_EXPORT_TYPES));
61
+ const openObjectSchema = z.record(z.unknown());
62
+ const sharedUsersFilterSchema = z
63
+ .object({
64
+ contains: z.enum(["CONTAINS", "DOES_NOT_CONTAIN", "CONTAINS_ONLY"]).optional(),
65
+ ids: z.array(z.string()).optional(),
66
+ status: z.enum(["ALL", "ACTIVE", "INACTIVE"]).optional(),
67
+ })
68
+ .strict();
69
+ const sharedAttendanceFilterSchema = z
70
+ .object({
71
+ page: z.number().finite().int().optional(),
72
+ pageSize: z.number().finite().int().optional(),
73
+ users: sharedUsersFilterSchema.optional(),
74
+ })
75
+ .strict();
76
+ const sharedDetailedFilterSchema = z
77
+ .object({
78
+ auditFilter: openObjectSchema.optional(),
79
+ options: openObjectSchema.optional(),
80
+ page: z.number().finite().int().optional(),
81
+ pageSize: z.number().finite().int().optional(),
82
+ sortColumn: nonEmptyStringSchema.optional(),
83
+ sortOrder: z.enum(["ASCENDING", "DESCENDING"]).optional(),
84
+ })
85
+ .strict();
86
+ const sharedSummaryFilterSchema = z
87
+ .object({
88
+ groups: z.array(z.enum(SUMMARY_GROUPS)).min(1).max(3),
89
+ sortColumn: nonEmptyStringSchema.optional(),
90
+ })
91
+ .strict();
92
+ const sharedWeeklyFilterSchema = z
93
+ .object({
94
+ group: z.enum(["PROJECT", "USER"]),
95
+ subgroup: z.literal("TIME"),
96
+ })
97
+ .strict();
98
+ const sharedReportFilterSchema = z
99
+ .object({
100
+ attendanceFilter: sharedAttendanceFilterSchema.optional(),
101
+ dateRangeEnd: dateStringSchema,
102
+ dateRangeStart: dateStringSchema,
103
+ detailedFilter: sharedDetailedFilterSchema.optional(),
104
+ exportType: sharedReportExportTypeSchema,
105
+ summaryFilter: sharedSummaryFilterSchema.optional(),
106
+ weeklyFilter: sharedWeeklyFilterSchema.optional(),
107
+ })
108
+ .strict();
109
+ const sharedReportBodyShape = {
110
+ filter: sharedReportFilterSchema,
111
+ isPublic: z.boolean().optional(),
112
+ name: nonEmptyStringSchema,
113
+ type: sharedReportTypeSchema,
114
+ };
115
+ const sharedReportCreateBodySchema = z.object(sharedReportBodyShape).strict();
116
+ const sharedReportUpdateBodySchema = z.object(sharedReportBodyShape).strict();
117
+ function toSharedReportFilter(value) {
118
+ return {
119
+ dateRangeEnd: value.dateRangeEnd,
120
+ dateRangeStart: value.dateRangeStart,
121
+ exportType: value.exportType,
122
+ ...(value.attendanceFilter !== undefined
123
+ ? {
124
+ attendanceFilter: {
125
+ ...(value.attendanceFilter.page !== undefined
126
+ ? { page: value.attendanceFilter.page }
127
+ : {}),
128
+ ...(value.attendanceFilter.pageSize !== undefined
129
+ ? { pageSize: value.attendanceFilter.pageSize }
130
+ : {}),
131
+ ...(value.attendanceFilter.users !== undefined
132
+ ? { users: value.attendanceFilter.users }
133
+ : {}),
134
+ },
135
+ }
136
+ : {}),
137
+ ...(value.detailedFilter !== undefined
138
+ ? {
139
+ detailedFilter: {
140
+ ...(value.detailedFilter.auditFilter !== undefined
141
+ ? { auditFilter: value.detailedFilter.auditFilter }
142
+ : {}),
143
+ ...(value.detailedFilter.options !== undefined
144
+ ? { options: value.detailedFilter.options }
145
+ : {}),
146
+ ...(value.detailedFilter.page !== undefined
147
+ ? { page: value.detailedFilter.page }
148
+ : {}),
149
+ ...(value.detailedFilter.pageSize !== undefined
150
+ ? { pageSize: value.detailedFilter.pageSize }
151
+ : {}),
152
+ ...(value.detailedFilter.sortColumn !== undefined
153
+ ? { sortColumn: value.detailedFilter.sortColumn }
154
+ : {}),
155
+ ...(value.detailedFilter.sortOrder !== undefined
156
+ ? { sortOrder: value.detailedFilter.sortOrder }
157
+ : {}),
158
+ },
159
+ }
160
+ : {}),
161
+ ...(value.summaryFilter !== undefined
162
+ ? {
163
+ summaryFilter: {
164
+ groups: value.summaryFilter.groups,
165
+ ...(value.summaryFilter.sortColumn !== undefined
166
+ ? { sortColumn: value.summaryFilter.sortColumn }
167
+ : {}),
168
+ },
169
+ }
170
+ : {}),
171
+ ...(value.weeklyFilter !== undefined
172
+ ? {
173
+ weeklyFilter: {
174
+ group: value.weeklyFilter.group,
175
+ subgroup: value.weeklyFilter.subgroup,
176
+ },
177
+ }
178
+ : {}),
179
+ };
180
+ }
181
+ function toSharedReportBody(value) {
182
+ return {
183
+ filter: toSharedReportFilter(value.filter),
184
+ name: value.name,
185
+ type: value.type,
186
+ ...(value.isPublic !== undefined ? { isPublic: value.isPublic } : {}),
187
+ };
188
+ }
189
+ function parseFilterJson(raw) {
190
+ if (typeof raw !== "string") {
191
+ throw new Error("--filter must be a JSON object.");
192
+ }
42
193
  try {
43
- const parsed = JSON.parse(raw);
44
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
45
- throw new Error("not an object");
46
- }
47
- return parsed;
194
+ return JSON.parse(raw);
48
195
  }
49
196
  catch {
50
197
  throw new Error(`--filter must be a JSON object, e.g. '{"dateRangeStart":"…","dateRangeEnd":"…"}'`);
51
198
  }
52
199
  }
53
- function requireType(raw) {
54
- const type = String(raw).toUpperCase();
55
- if (!SHARED_REPORT_TYPES.includes(type)) {
56
- throw new Error(`Unknown --type "${raw}". Use one of: ${SHARED_REPORT_TYPES.join(", ")}.`);
200
+ function schemaIssueLabel(issue, operation) {
201
+ const [root, ...path] = issue.path;
202
+ if (root === "filter") {
203
+ return path.length > 0 ? `--filter ${path.join(".")}` : "--filter";
57
204
  }
58
- return type;
205
+ if (root === "name")
206
+ return "--name";
207
+ if (root === "type")
208
+ return "--type";
209
+ return operation;
210
+ }
211
+ function sharedReportValidationError(error, operation, rawType) {
212
+ const invalidTypeIssue = error.issues.find((issue) => issue.path[0] === "type" && issue.code === z.ZodIssueCode.invalid_enum_value);
213
+ if (invalidTypeIssue !== undefined) {
214
+ return new Error(`Unknown --type "${String(rawType)}". Use one of: ${SHARED_REPORT_TYPES.join(", ")}.`);
215
+ }
216
+ const issue = error.issues[0];
217
+ if (issue === undefined)
218
+ return new Error(`${operation}: invalid request.`);
219
+ if (issue.path.length === 1 &&
220
+ issue.path[0] === "filter" &&
221
+ issue.code === z.ZodIssueCode.invalid_type &&
222
+ issue.expected === "object") {
223
+ return new Error("--filter must be a JSON object.");
224
+ }
225
+ const label = schemaIssueLabel(issue, operation);
226
+ if (issue.code === z.ZodIssueCode.unrecognized_keys) {
227
+ const fieldKind = issue.path[0] === "filter" ? "filter field(s)" : "field(s)";
228
+ return new Error(`${label} has unknown ${fieldKind}: ${issue.keys.join(", ")}.`);
229
+ }
230
+ return new Error(`${label}: ${issue.message}`);
231
+ }
232
+ function parseSharedReportBody(schema, opts, operation) {
233
+ const candidate = {
234
+ name: opts.name,
235
+ type: opts.type,
236
+ filter: parseFilterJson(opts.filter),
237
+ ...(opts.public === true ? { isPublic: true } : {}),
238
+ };
239
+ const result = schema.safeParse(candidate);
240
+ if (!result.success) {
241
+ throw sharedReportValidationError(result.error, operation, opts.type);
242
+ }
243
+ return toSharedReportBody(result.data);
59
244
  }
60
245
  export const registerSharedReportsCommand = (program, services) => {
61
246
  const shared = program
62
247
  .command("shared-reports")
63
248
  .description("Manage shared (public-link) reports.");
64
- shared
65
- .command("list")
249
+ leafCommand(shared, "list", "read")
66
250
  .description("List the workspace's shared (public-link) reports.")
67
251
  .action(async function () {
68
252
  const { client, workspaceId, output } = await resolveContext(this, services);
69
253
  const result = await client.sharedReports.list({ workspaceId });
70
254
  printObject(result, output);
71
255
  });
72
- shared
73
- .command("view")
256
+ leafCommand(shared, "view", "read")
74
257
  .argument("<id>", "Shared-report ID.")
75
258
  .option("--export-type <type>", "Export type: JSON_V1, JSON, CSV, XLSX, or PDF (default JSON_V1).")
76
259
  .description("View a shared report's rendered data by ID (reports host; not workspace-scoped).")
@@ -83,8 +266,7 @@ export const registerSharedReportsCommand = (program, services) => {
83
266
  });
84
267
  printObject(await readReportBody(response), output);
85
268
  });
86
- shared
87
- .command("create")
269
+ leafCommand(shared, "create", "write")
88
270
  .requiredOption("--name <text>", "Shared-report name.")
89
271
  .requiredOption("--type <type>", `Report type: ${SHARED_REPORT_TYPES.join(", ")}.`)
90
272
  .requiredOption("--filter <json>", "Report filter object as a JSON string.")
@@ -92,14 +274,9 @@ export const registerSharedReportsCommand = (program, services) => {
92
274
  .description("Create a shared (public-link) report.")
93
275
  .action(async function (opts) {
94
276
  const { client, workspaceId, output } = await resolveContext(this, services);
95
- const body = {
96
- name: opts.name,
97
- type: requireType(opts.type),
98
- filter: parseFilter(opts.filter),
99
- };
100
- if (opts.public)
101
- body.isPublic = true;
102
- const created = (await client.sharedReports.create(wireBody({ workspaceId, body })));
277
+ const body = parseSharedReportBody(sharedReportCreateBodySchema, opts, "shared-reports.create");
278
+ const request = { workspaceId, body };
279
+ const created = (await client.sharedReports.create(request));
103
280
  const data = { id: created.id ?? "", name: created.name ?? opts.name };
104
281
  printReceipt({
105
282
  ok: true,
@@ -116,8 +293,7 @@ export const registerSharedReportsCommand = (program, services) => {
116
293
  ],
117
294
  }, output);
118
295
  });
119
- shared
120
- .command("update")
296
+ leafCommand(shared, "update", "write")
121
297
  .argument("<id>", "Shared-report ID.")
122
298
  .requiredOption("--name <text>", "Shared-report name.")
123
299
  .requiredOption("--type <type>", `Report type: ${SHARED_REPORT_TYPES.join(", ")}.`)
@@ -126,18 +302,13 @@ export const registerSharedReportsCommand = (program, services) => {
126
302
  .description("Replace a shared report by ID (full replace of name, type, and filter).")
127
303
  .action(async function (id, opts) {
128
304
  const { client, workspaceId, output } = await resolveContext(this, services);
129
- const body = {
130
- name: opts.name,
131
- type: requireType(opts.type),
132
- filter: parseFilter(opts.filter),
133
- };
134
- if (opts.public)
135
- body.isPublic = true;
136
- const updated = (await client.sharedReports.update(wireBody({
305
+ const body = parseSharedReportBody(sharedReportUpdateBodySchema, opts, "shared-reports.update");
306
+ const request = {
137
307
  workspaceId,
138
308
  sharedReportId: id,
139
309
  body,
140
- })));
310
+ };
311
+ const updated = (await client.sharedReports.update(request));
141
312
  const data = { id: updated.id ?? id, name: updated.name ?? opts.name };
142
313
  printReceipt({
143
314
  ok: true,
@@ -154,8 +325,7 @@ export const registerSharedReportsCommand = (program, services) => {
154
325
  ],
155
326
  }, output);
156
327
  });
157
- shared
158
- .command("delete")
328
+ leafCommand(shared, "delete", "destructive")
159
329
  .argument("<id>", "Shared-report ID.")
160
330
  .description("Delete a shared report by ID.")
161
331
  .action(async function (id) {
@@ -1,10 +1,10 @@
1
1
  import { entityId } from "clockify-sdk-ts-115/operation-receipt";
2
2
  import { printReceipt } from "../receipt.js";
3
3
  import { resolveContext } from "./helpers.js";
4
+ import { leafCommand } from "./leaf-command.js";
4
5
  import { resolveProjectId, resolveTaskId, resolveTagIds } from "./resolve-refs.js";
5
6
  export const registerStartCommand = (program, services) => {
6
- program
7
- .command("start")
7
+ leafCommand(program, "start", "write")
8
8
  .description("Start a running time entry. Resolves project/task/tag names to IDs automatically.")
9
9
  .argument("[description]", "Description for the time entry.")
10
10
  .option("-p, --project <name>", "Project name or ID.")
@@ -2,9 +2,9 @@ import { entityId } from "clockify-sdk-ts-115/operation-receipt";
2
2
  import { formatIsoDuration } from "../duration.js";
3
3
  import { printObject } from "../output.js";
4
4
  import { resolveBaseContext } from "./helpers.js";
5
+ import { leafCommand } from "./leaf-command.js";
5
6
  export const registerStatusCommand = (program, services) => {
6
- program
7
- .command("status")
7
+ leafCommand(program, "status", "read")
8
8
  .description("Show the configured workspace, current user, and running timer.")
9
9
  .action(async function () {
10
10
  const { client, config, output } = await resolveBaseContext(this, services);
@@ -2,9 +2,9 @@ import { entityId } from "clockify-sdk-ts-115/operation-receipt";
2
2
  import { printSuccess } from "../output.js";
3
3
  import { printReceipt } from "../receipt.js";
4
4
  import { resolveContext } from "./helpers.js";
5
+ import { leafCommand } from "./leaf-command.js";
5
6
  export const registerStopCommand = (program, services) => {
6
- program
7
- .command("stop")
7
+ leafCommand(program, "stop", "write")
8
8
  .description("Stop the running timer for the current user.")
9
9
  .action(async function () {
10
10
  const { client, workspaceId, output } = await resolveContext(this, services);
@@ -1,9 +1,10 @@
1
1
  import { printObject, printRecords } from "../output.js";
2
2
  import { printReceipt } from "../receipt.js";
3
3
  import { clampPageSize, parseIntArg, resolveContext } from "./helpers.js";
4
+ import { leafCommand } from "./leaf-command.js";
4
5
  export const registerTagsCommand = (program, services) => {
5
6
  const tags = program.command("tags").description("Manage tags.");
6
- tags.command("list")
7
+ leafCommand(tags, "list", "read")
7
8
  .description("List tags in the workspace.")
8
9
  .option("--limit <n>", "Items per page (default 25, max 200).", parseIntArg, 25)
9
10
  .option("--page <n>", "Page number.", parseIntArg, 1)
@@ -31,7 +32,7 @@ export const registerTagsCommand = (program, services) => {
31
32
  });
32
33
  printRecords(rows, output);
33
34
  });
34
- tags.command("create")
35
+ leafCommand(tags, "create", "write")
35
36
  .argument("<name>", "Tag name.")
36
37
  .description("Create a tag in the workspace.")
37
38
  .action(async function (name) {
@@ -51,7 +52,7 @@ export const registerTagsCommand = (program, services) => {
51
52
  ],
52
53
  }, output);
53
54
  });
54
- tags.command("get")
55
+ leafCommand(tags, "get", "read")
55
56
  .argument("<id>", "Tag ID.")
56
57
  .description("Get one tag by ID.")
57
58
  .action(async function (id) {
@@ -59,7 +60,7 @@ export const registerTagsCommand = (program, services) => {
59
60
  const tag = await client.tags.get({ workspaceId, tagId: id });
60
61
  printObject(tag, output);
61
62
  });
62
- tags.command("update")
63
+ leafCommand(tags, "update", "write")
63
64
  .argument("<id>", "Tag ID.")
64
65
  .option("--name <text>", "New tag name.")
65
66
  .option("--archived", "Archive the tag.")
@@ -85,7 +86,7 @@ export const registerTagsCommand = (program, services) => {
85
86
  next: [{ command: "clk115 tags list --json", reason: "Verify the update." }],
86
87
  }, output);
87
88
  });
88
- tags.command("delete")
89
+ leafCommand(tags, "delete", "destructive")
89
90
  .argument("<id>", "Tag ID.")
90
91
  .description("Delete a tag by ID.")
91
92
  .action(async function (id) {