@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.
- package/README.md +96 -26
- package/dist/client.js +18 -15
- package/dist/closed-pipe.js +3 -0
- package/dist/commands/api.js +182 -61
- package/dist/commands/approvals.js +9 -7
- package/dist/commands/auditlog.js +11 -8
- package/dist/commands/balanceAssignment.js +10 -8
- package/dist/commands/clients.js +16 -7
- package/dist/commands/doctor.js +42 -25
- package/dist/commands/entries.js +29 -14
- package/dist/commands/expenses.js +64 -22
- package/dist/commands/helpers.js +28 -7
- package/dist/commands/invoices.js +12 -16
- package/dist/commands/leaf-command.js +8 -0
- package/dist/commands/log.js +4 -2
- package/dist/commands/projects.js +18 -9
- package/dist/commands/reports.js +73 -23
- package/dist/commands/resolve-refs.js +30 -53
- package/dist/commands/scheduling.js +94 -40
- package/dist/commands/shared-report-body.js +205 -0
- package/dist/commands/sharedReports.js +19 -215
- package/dist/commands/start.js +6 -4
- package/dist/commands/status.js +55 -19
- package/dist/commands/stop.js +15 -17
- package/dist/commands/tags.js +6 -4
- package/dist/commands/tasks.js +18 -23
- package/dist/commands/timeoff.js +23 -16
- package/dist/commands/users.js +7 -5
- package/dist/commands/webhooks.js +14 -12
- package/dist/completions.js +290 -55
- package/dist/config.js +10 -6
- package/dist/duration.js +5 -4
- package/dist/error-codes.js +34 -6
- package/dist/failure.js +87 -0
- package/dist/flags.js +74 -0
- package/dist/generated/version.js +1 -1
- package/dist/index.js +41 -105
- package/dist/output.js +62 -28
- package/dist/write-outcome.js +84 -0
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -3,8 +3,8 @@
|
|
|
3
3
|
Command-line interface for [Clockify](https://clockify.me/), built on
|
|
4
4
|
top of `clockify-sdk-ts-115`.
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
`clockify-sdk-ts-115 ^
|
|
6
|
+
Version in this checkout: `6.0.0`. Requires Node.js `>=22.13.0` and
|
|
7
|
+
`clockify-sdk-ts-115 ^6.0.0`.
|
|
8
8
|
|
|
9
9
|
Two binaries, identical behavior:
|
|
10
10
|
|
|
@@ -15,7 +15,6 @@ Two binaries, identical behavior:
|
|
|
15
15
|
npm ci && make sdk-codegen # from the repo root, once
|
|
16
16
|
npm run build -w clockify-sdk-ts-115 # build the workspace-linked SDK
|
|
17
17
|
cd cli
|
|
18
|
-
npm install
|
|
19
18
|
npm run build
|
|
20
19
|
npm link
|
|
21
20
|
export CLOCKIFY_API_KEY=... # from Clockify > Profile > API Keys
|
|
@@ -27,6 +26,8 @@ clk115 start "WIP refactor" -p "Acme Corp"
|
|
|
27
26
|
clk115 stop
|
|
28
27
|
```
|
|
29
28
|
|
|
29
|
+
See the [MCP host compatibility guide](../docs/mcp-host-compatibility.md) for client setup and Reports App support.
|
|
30
|
+
|
|
30
31
|
## Configuration
|
|
31
32
|
|
|
32
33
|
In precedence order (highest wins):
|
|
@@ -51,7 +52,6 @@ Rc file shape:
|
|
|
51
52
|
```json
|
|
52
53
|
{
|
|
53
54
|
"workspaceId": "65b382b6…",
|
|
54
|
-
"baseUrl": "https://api.clockify.me/api/v1",
|
|
55
55
|
"region": "eu",
|
|
56
56
|
"subdomain": "acme"
|
|
57
57
|
}
|
|
@@ -80,13 +80,56 @@ With `--output ndjson`, the CLI writes each array item as one JSON value on its
|
|
|
80
80
|
own line, without a wrapping array; a non-array result is one line.
|
|
81
81
|
|
|
82
82
|
In `json` and `ndjson` modes, errors go to stderr as `{"ok": false, "error":
|
|
83
|
-
"...", "code": "...", "recovery": "...", "retryable": true|false}`.
|
|
83
|
+
"...", "code": "...", "recovery": "...", "retryable": true|false}`. An API
|
|
84
|
+
failure also carries `"status"` (the HTTP status) and, when Clockify returned
|
|
85
|
+
one, `"serverCode"` (its numeric body code, e.g. `403` with `4030`); usage and
|
|
86
|
+
local errors omit both. Mutation failures also report `stage` and `replaySafe`.
|
|
87
|
+
A failed prerequisite read can be retried when `retryable` is true. After an
|
|
88
|
+
ambiguous or applied write, read the record back before taking further action.
|
|
89
|
+
A raw response that cannot be rendered exits 1 with its HTTP status.
|
|
84
90
|
Successful write commands in JSON and NDJSON include receipt fields:
|
|
85
91
|
`ok`, `action`, `entity`, `ids`, `changed`, `warnings`, and `next`.
|
|
86
92
|
Legacy top-level fields such as `id` remain for simple shell scripts.
|
|
87
93
|
Read-only commands (e.g. `status`, `entries list`) print the requested
|
|
88
94
|
object or array directly, with no `ok` wrapper. `--no-color` disables
|
|
89
|
-
ANSI codes, and
|
|
95
|
+
ANSI codes, and color is off when a stream is not a TTY unless `FORCE_COLOR`
|
|
96
|
+
enables it.
|
|
97
|
+
|
|
98
|
+
A failed delete can follow a successful update. For tasks, clients and projects,
|
|
99
|
+
the error includes `completedStage` (`marked_done` or `archived`) and a `next`
|
|
100
|
+
command to inspect the resource. The command exits 1 and leaves concurrent
|
|
101
|
+
edits intact after the delete attempt. `completedStage` names the state the
|
|
102
|
+
resource had reached. For clients and projects, `archiveAction` says who brought
|
|
103
|
+
it there: `archived_by_call`, or `already_archived` before this command ran.
|
|
104
|
+
|
|
105
|
+
`status` reports `timerState`. An `unavailable` state carries `timerStateReason`:
|
|
106
|
+
`user_id_missing`, `response_unrecognized` or `workspace_not_set`. Only a list
|
|
107
|
+
that Clockify returned and that holds no running entry of yours is `idle`.
|
|
108
|
+
|
|
109
|
+
Scheduling with `--publish` publishes all drafts for the selected user in the
|
|
110
|
+
start/end window. The receipt identifies that window in `publishScope`.
|
|
111
|
+
A create response that identifies no assignment exits 1 and publishes nothing.
|
|
112
|
+
The write may have applied, so the error has `replaySafe: false` and gives the
|
|
113
|
+
command that lists the window.
|
|
114
|
+
When a scheduling publish response is lost, the CLI reads the assignment back.
|
|
115
|
+
A verified publication exits 0. A refused publish or verified draft exits 1
|
|
116
|
+
with the created assignment ID and publish request. If the read cannot verify
|
|
117
|
+
publication, the receipt says `published: "unknown"` and gives a read-back
|
|
118
|
+
command to run before retrying.
|
|
119
|
+
|
|
120
|
+
`expenses list` prints a JSON array, one expense per NDJSON line, or a table.
|
|
121
|
+
Reaching `--limit` returns the requested prefix. Reaching `--max-pages` first
|
|
122
|
+
can leave matching expenses unexamined. In either case the command exits 0
|
|
123
|
+
and warns on stderr. To continue, keep the same filters and page size and
|
|
124
|
+
append the printed `--page N --offset M --max-pages K` flags. At the last
|
|
125
|
+
supported page the warning says when there is no further cursor.
|
|
126
|
+
|
|
127
|
+
Add `--with-meta` for machine-readable scan metadata. JSON then returns
|
|
128
|
+
`{"items":[…],"meta":{…}}`. NDJSON appends one final `{"meta":{…}}` line,
|
|
129
|
+
even for zero expenses. With NDJSON, `--select` applies to the expense rows.
|
|
130
|
+
Complete scans report `meta.hasMore: false`. When a cursor is available,
|
|
131
|
+
`nextPage`, `nextOffset` (defaults to zero), and `nextMaxPages` provide the
|
|
132
|
+
three continuation values.
|
|
90
133
|
|
|
91
134
|
### Money units
|
|
92
135
|
|
|
@@ -94,11 +137,19 @@ Clockify's wire units are not uniform, and the CLI keeps its established
|
|
|
94
137
|
`amount` field names for JSON compatibility:
|
|
95
138
|
|
|
96
139
|
- `expenses create --amount` and `expenses update --amount` accept major
|
|
97
|
-
currency units, so `42.50` means 42.50 in the selected currency.
|
|
98
|
-
|
|
99
|
-
|
|
140
|
+
currency units, so `42.50` means 42.50 in the selected currency. An amount
|
|
141
|
+
above 9007199254740991 exits 2, because the number sent could differ from the
|
|
142
|
+
one typed.
|
|
143
|
+
- `expenses list` exposes the response total as `totalMinor` in minor units
|
|
144
|
+
(42.50 is `4250` for a two-decimal currency), with `amountSource: "total"`.
|
|
145
|
+
An omitted total gives `totalMinor: null`, `amountSource: "unavailable"`, and
|
|
146
|
+
an em dash in the table. Legacy JSON `amount` falls back to the per-unit
|
|
147
|
+
amount, quantity or zero.
|
|
100
148
|
- Invoice `amount` values from `invoices list` and `invoices create` receipts
|
|
101
|
-
are also minor units.
|
|
149
|
+
are also minor units. `invoices list` adds `totalMinor` and `amountSource` with
|
|
150
|
+
the same rules: an omitted amount gives `totalMinor: null`,
|
|
151
|
+
`amountSource: "unavailable"`, and an em dash in the table, while legacy JSON
|
|
152
|
+
`amount` stays `0`.
|
|
102
153
|
|
|
103
154
|
Use an emitted `currency` value when present; otherwise apply the workspace or
|
|
104
155
|
entity currency. The raw `api` command always returns Clockify's response
|
|
@@ -114,8 +165,8 @@ without unit conversion.
|
|
|
114
165
|
| `clk115 start [description] [-p project] [-t task] [--tag tag…] [--billable]` | Start a timer. Resolves project, task, and tag names to IDs. |
|
|
115
166
|
| `clk115 stop` | Stop the running timer for the current user. |
|
|
116
167
|
| `clk115 log <duration> <description> [-p project] [-t task] [--tag tag…] [--billable] [--end iso]` | Log a finished entry. Resolves project, task, and tag names to IDs. Duration accepts `1h30m`, `90m`, or `PT1H30M`. |
|
|
117
|
-
| `clk115 entries list [--limit N] [--page N] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--description text]` | List time entries for the current user. |
|
|
118
|
-
| `clk115 entries get-many --ids id1,id2 [--hydrated]` | Look up several time entries by ID
|
|
168
|
+
| `clk115 entries list [--limit N] [--page N] [--from YYYY-MM-DD] [--to YYYY-MM-DD] [--description text] [--time-view-mode mode]` | List time entries for the current user. |
|
|
169
|
+
| `clk115 entries get-many --ids id1,id2 [--hydrated]` | Look up several time entries by ID. Hydrated rows include project, task and tag detail. |
|
|
119
170
|
| `clk115 entries delete <id>` | Delete a time entry. |
|
|
120
171
|
| `clk115 projects list [--limit N] [--page N] [--name text] [--archived] [--client id]` | List projects. |
|
|
121
172
|
| `clk115 projects create <name> [--client id] [--color hex] [--billable]` | Create a project. |
|
|
@@ -142,7 +193,7 @@ without unit conversion.
|
|
|
142
193
|
| `clk115 webhooks delete <id>` | Delete a webhook subscription. |
|
|
143
194
|
| `clk115 invoices list [--limit N] [--page N]` | List invoices in the workspace. |
|
|
144
195
|
| `clk115 invoices create --client id --number N --currency USD --issued YYYY-MM-DD --due YYYY-MM-DD [--time-view-mode mode]` | Create an invoice draft. |
|
|
145
|
-
| `clk115 expenses list [--limit N] [--page-size N] [--max-pages N] [--page N] [--start date] [--end date]` | List workspace expenses; date bounds are applied client-side across bounded pages. |
|
|
196
|
+
| `clk115 expenses list [--limit N] [--page-size N] [--max-pages N] [--page N] [--offset N] [--with-meta] [--start date] [--end date]` | List workspace expenses; date bounds are applied client-side across bounded pages. |
|
|
146
197
|
| `clk115 expenses get <id>` | Get one expense by ID. |
|
|
147
198
|
| `clk115 expenses create --amount N --category id --date YYYY-MM-DD [--user id] [--project id] [--task id] [--notes text] [--billable\|--no-billable]` | Create an expense (scalar body; --user defaults to the API-key owner). |
|
|
148
199
|
| `clk115 expenses update <id> --amount N --category id --date YYYY-MM-DD --user id [--project id] [--task id] [--notes text] [--billable\|--no-billable]` | Update an expense (full replace of amount, category, date). |
|
|
@@ -156,12 +207,12 @@ without unit conversion.
|
|
|
156
207
|
| `clk115 scheduling list --from date --to date [--limit N] [--page N] [--name text]` | List scheduling assignments. |
|
|
157
208
|
| `clk115 scheduling create --user id --project id --start date --end date --hours-per-day N [--task id --note text --billable --include-non-working-days --publish]` | Create a scheduling assignment. Drafts by default; pass `--publish` to publish. |
|
|
158
209
|
| `clk115 audit-log search --start RFC3339 --end RFC3339 --actions A,B,… [--authors ids --authors-mode CONTAINS\|DOES_NOT_CONTAIN --page N --limit N]` | Search the workspace audit log. Window must be ≤ 31 days. |
|
|
159
|
-
| `clk115 reports summary [--period p] [--from date] [--to date] [--groups PROJECT,TASK] [--billable] [--project name\|id…] [--client name\|id…]` | Summary report totals over a date range, grouped per --groups. Read-only. |
|
|
160
|
-
| `clk115 reports detailed [--period p] [--from date] [--to date] [--page N] [--page-size N]` | Detailed report listing individual time entries over a date range. Read-only. |
|
|
161
|
-
| `clk115 reports weekly [--period p] [--from date] [--to date] [--group USER\|PROJECT] [--subgroup TIME]` | Weekly report over exactly one seven-calendar-day window. Read-only. |
|
|
162
|
-
| `clk115 reports attendance [--period p] [--from date] [--to date]` | Attendance report of clock-in/out activity over a date range. Read-only. |
|
|
210
|
+
| `clk115 reports summary [--period p] [--from date] [--to date] [--groups PROJECT,TASK] [--billable] [--project name\|id…] [--client name\|id…] [--time-view-mode mode]` | Summary report totals over a date range, grouped per --groups. Read-only. |
|
|
211
|
+
| `clk115 reports detailed [--period p] [--from date] [--to date] [--page N] [--page-size N] [--time-view-mode mode]` | Detailed report listing individual time entries over a date range. Read-only. |
|
|
212
|
+
| `clk115 reports weekly [--period p] [--from date] [--to date] [--group USER\|PROJECT] [--subgroup TIME] [--time-view-mode mode]` | Weekly report over exactly one seven-calendar-day window. Read-only. |
|
|
213
|
+
| `clk115 reports attendance [--period p] [--from date] [--to date] [--time-view-mode mode]` | Attendance report of clock-in/out activity over a date range. Read-only. |
|
|
163
214
|
| `clk115 shared-reports list` | List the workspace's shared (public-link) reports. Read-only. |
|
|
164
|
-
| `clk115 shared-reports view <id> [--export-type JSON_V1\|JSON\|CSV]` | View a shared report's text-safe rendered data by ID (not workspace-scoped). XLSX/PDF are rejected before the request until output-file streaming exists. Read-only. |
|
|
215
|
+
| `clk115 shared-reports view <id> [--export-type JSON_V1\|JSON\|CSV] [--time-view-mode mode]` | View a shared report's text-safe rendered data by ID (not workspace-scoped). XLSX/PDF are rejected before the request until output-file streaming exists. Read-only. |
|
|
165
216
|
| `clk115 shared-reports create --name X --type T --filter json [--public\|--no-public]` | Create a shared (public-link) report. |
|
|
166
217
|
| `clk115 shared-reports update <id> --name X --type T --filter json [--public\|--no-public]` | Replace a shared report by ID (full replace of name, type, and filter). |
|
|
167
218
|
| `clk115 shared-reports delete <id>` | Delete a shared report. |
|
|
@@ -191,7 +242,7 @@ Log a 90-minute entry that ended now:
|
|
|
191
242
|
clk115 log 1h30m "RFC review"
|
|
192
243
|
```
|
|
193
244
|
|
|
194
|
-
Log a 30-minute entry
|
|
245
|
+
Log a 30-minute entry ending at a specific UTC time, in JSON for
|
|
195
246
|
piping into `jq`:
|
|
196
247
|
|
|
197
248
|
```sh
|
|
@@ -220,6 +271,21 @@ stops because it hit `--max-pages`, the collection is incomplete and a `WARN`
|
|
|
220
271
|
line goes to **stderr**; stdout stays byte-identical either way, so pipelines
|
|
221
272
|
are unaffected and a script can detect truncation without parsing output.
|
|
222
273
|
|
|
274
|
+
An exact duplicate of the previous page stops the walk before adding its rows.
|
|
275
|
+
The warning identifies an endpoint that ignores pagination. Raw HTTP errors
|
|
276
|
+
use the same Clockify body-code classification as curated commands. A failed
|
|
277
|
+
response whose body cannot be read keeps its HTTP status, and `--include-headers`
|
|
278
|
+
prints it with `data: null` and the read failure as `bodyError`.
|
|
279
|
+
|
|
280
|
+
### Binary responses
|
|
281
|
+
|
|
282
|
+
For binary exports, redirect stdout to a file or pipe it to another program.
|
|
283
|
+
The CLI writes the response bytes verbatim. A terminal, JSON/NDJSON mode,
|
|
284
|
+
`--include-headers` and `--all` cannot carry them. An `Accept` header that names
|
|
285
|
+
only binary types then fails before any request is sent (exit 2). Without one,
|
|
286
|
+
the CLI learns the type from the response and fails after the request was sent
|
|
287
|
+
(exit 1), so a write may already have applied.
|
|
288
|
+
|
|
223
289
|
## Shell completion
|
|
224
290
|
|
|
225
291
|
`clk115 completion <shell>` prints a completion script for `bash`, `zsh`, or
|
|
@@ -228,24 +294,29 @@ completion location:
|
|
|
228
294
|
|
|
229
295
|
```sh
|
|
230
296
|
# bash (Linux)
|
|
297
|
+
mkdir -p ~/.local/share/bash-completion/completions
|
|
231
298
|
clk115 completion bash > ~/.local/share/bash-completion/completions/clk115
|
|
232
299
|
|
|
233
|
-
# zsh —
|
|
234
|
-
|
|
300
|
+
# zsh — add ~/.zfunc to fpath before running compinit in .zshrc
|
|
301
|
+
mkdir -p ~/.zfunc
|
|
302
|
+
clk115 completion zsh > ~/.zfunc/_clk115
|
|
235
303
|
|
|
236
304
|
# fish
|
|
305
|
+
mkdir -p ~/.config/fish/completions
|
|
237
306
|
clk115 completion fish > ~/.config/fish/completions/clk115.fish
|
|
238
307
|
```
|
|
239
308
|
|
|
309
|
+
With `--json` or `--output ndjson`, the completion script is one JSON string.
|
|
310
|
+
|
|
240
311
|
For a one-off in the current shell: `source <(clk115 completion bash)`. The
|
|
241
312
|
`clockify115` binary accepts the same subcommand. See `examples/` for runnable
|
|
242
313
|
scripts.
|
|
243
314
|
|
|
244
315
|
## Exit codes
|
|
245
316
|
|
|
246
|
-
- `0` — success
|
|
247
|
-
- `1` —
|
|
248
|
-
- `2` —
|
|
317
|
+
- `0` — success, including `--help` and `--version`
|
|
318
|
+
- `1` — runtime or API failure (missing credentials, HTTP errors, network failures)
|
|
319
|
+
- `2` — usage or local input validation error (unknown flag, missing required argument, invalid enum/date/filter rejected before any request is sent)
|
|
249
320
|
|
|
250
321
|
## Development
|
|
251
322
|
|
|
@@ -254,7 +325,6 @@ git clone https://github.com/apet97/clockify-ts-sdk
|
|
|
254
325
|
cd clockify-ts-sdk && npm ci && make sdk-codegen # populate the gitignored generated SDK sources
|
|
255
326
|
npm run build -w clockify-sdk-ts-115 # build the workspace-linked SDK
|
|
256
327
|
cd cli
|
|
257
|
-
npm install
|
|
258
328
|
npm run dev -- status # via tsx, no build needed
|
|
259
329
|
npm test # unit tests across duration / config / output / CLI contract / mock server
|
|
260
330
|
npm run build # tsc → dist/
|
|
@@ -262,7 +332,7 @@ node dist/index.js status # smoke test (or invoke installed clk115/clockify11
|
|
|
262
332
|
```
|
|
263
333
|
|
|
264
334
|
`clockify-sdk-ts-115` is workspace-linked for local development and is a
|
|
265
|
-
`^
|
|
335
|
+
`^6.0.0` peer dependency for published consumers.
|
|
266
336
|
|
|
267
337
|
## License
|
|
268
338
|
|
package/dist/client.js
CHANGED
|
@@ -1,9 +1,14 @@
|
|
|
1
|
+
import { isMutationCommand } from "./commands/leaf-command.js";
|
|
1
2
|
import { requireApiKey } from "./config.js";
|
|
3
|
+
import { observeWriteTransport } from "./write-outcome.js";
|
|
2
4
|
export const REGIONAL_PREFIXES = ["eu", "us", "uk", "au"];
|
|
3
5
|
export const KNOWN_REGIONS = ["global", ...REGIONAL_PREFIXES, "developer"];
|
|
4
|
-
export function buildRoutingOptions(region, subdomain) {
|
|
6
|
+
export function buildRoutingOptions(region, subdomain, baseUrl) {
|
|
5
7
|
if (region === undefined && subdomain === undefined)
|
|
6
8
|
return undefined;
|
|
9
|
+
if (baseUrl !== undefined) {
|
|
10
|
+
throw new Error("clk115: --region/--subdomain and --base-url configure the same thing two different ways; provide only one of them.");
|
|
11
|
+
}
|
|
7
12
|
if (subdomain !== undefined) {
|
|
8
13
|
if (region === undefined || !REGIONAL_PREFIXES.includes(region)) {
|
|
9
14
|
throw new Error(`--subdomain requires --region (got ${JSON.stringify(region)}). Provide one of: ${REGIONAL_PREFIXES.join(", ")}.`);
|
|
@@ -31,22 +36,20 @@ export function unconfirmedRegionNotice(routing) {
|
|
|
31
36
|
const host = routing.profile === "subdomain" ? `${routing.subdomain} (${routing.region})` : routing.profile;
|
|
32
37
|
return `clk115: using the unconfirmed "${host}" Clockify profile. Only the global profile is live-confirmed; drop --region/--subdomain (and CLOCKIFY_REGION/CLOCKIFY_SUBDOMAIN or the rc-file entry) to route to api.clockify.me.`;
|
|
33
38
|
}
|
|
34
|
-
export async function buildClient(config) {
|
|
35
|
-
const
|
|
36
|
-
const routing =
|
|
37
|
-
if (routing !== undefined && config.baseUrl !== undefined) {
|
|
38
|
-
throw new Error("clk115: --region/--subdomain and --base-url configure the same thing two different ways; provide only one of them.");
|
|
39
|
-
}
|
|
39
|
+
export async function buildClient(config, command) {
|
|
40
|
+
const transport = command && isMutationCommand(command) ? observeWriteTransport(command) : undefined;
|
|
41
|
+
const { client, routing } = await createRoutedClient(config, requireApiKey(config), transport);
|
|
40
42
|
const notice = unconfirmedRegionNotice(routing);
|
|
41
43
|
if (notice !== undefined)
|
|
42
44
|
process.stderr.write(`${notice}\n`);
|
|
45
|
+
return client;
|
|
46
|
+
}
|
|
47
|
+
export async function createRoutedClient(config, apiKey, transport) {
|
|
48
|
+
const routing = buildRoutingOptions(config.region, config.subdomain, config.baseUrl);
|
|
43
49
|
const { createClockifyClient } = await import("clockify-sdk-ts-115");
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
allowNonClockifyHttpsHost: false,
|
|
50
|
-
...(config.baseUrl !== undefined ? { environment: config.baseUrl } : {}),
|
|
51
|
-
});
|
|
50
|
+
const options = { apiKey, allowNonClockifyHttpsHost: false, ...(transport && { fetch: transport }) };
|
|
51
|
+
const client = routing === undefined
|
|
52
|
+
? createClockifyClient({ ...options, ...(config.baseUrl !== undefined && { environment: config.baseUrl }) })
|
|
53
|
+
: createClockifyClient({ ...options, routing });
|
|
54
|
+
return { client, routing };
|
|
52
55
|
}
|
package/dist/commands/api.js
CHANGED
|
@@ -1,88 +1,177 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
2
|
+
import { UsageError } from "../failure.js";
|
|
3
|
+
import { resolveFlags } from "../flags.js";
|
|
4
|
+
import { AlreadyReportedError, printJson, printNdjson, printWarning, } from "../output.js";
|
|
5
|
+
import { dispatchedWrite, writeFailure } from "../write-outcome.js";
|
|
6
|
+
import { parseIntArg, resolveBaseContext, rootProgram } from "./helpers.js";
|
|
5
7
|
import { leafCommand } from "./leaf-command.js";
|
|
6
8
|
const METHODS = new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
|
|
9
|
+
const CREDENTIAL_HEADERS = new Set(["x-api-key", "x-addon-token"]);
|
|
10
|
+
const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
|
|
7
11
|
export const registerApiCommand = (program, services) => {
|
|
8
12
|
leafCommand(program, "api", "destructive")
|
|
9
13
|
.description("Call a Clockify API path directly through the SDK client.")
|
|
10
14
|
.addHelpText("after", "\nExamples:\n" +
|
|
11
15
|
" $ clk115 api GET /workspaces/{workspaceId}/tags\n" +
|
|
12
16
|
" $ clk115 api POST /workspaces/{workspaceId}/tags --body '{\"name\":\"focus\"}'\n" +
|
|
13
|
-
" $ clk115 api GET /workspaces/{workspaceId}/projects --all --page-size 100\n"
|
|
17
|
+
" $ clk115 api GET /workspaces/{workspaceId}/projects --all --page-size 100\n" +
|
|
18
|
+
"\nPaths resolve against the regular API base (https://api.clockify.me/api/v1).\n" +
|
|
19
|
+
"Reports-host endpoints need --base-url https://reports.api.clockify.me/v1,\n" +
|
|
20
|
+
"or use the curated `clk115 reports` and `clk115 audit-log` commands.\n")
|
|
14
21
|
.argument("<method>", "HTTP method: GET, POST, PUT, PATCH, or DELETE.")
|
|
15
22
|
.argument("<path>", "API path, e.g. /workspaces/{workspaceId}/tags.")
|
|
16
23
|
.option("-q, --query <key=value>", "Query parameter (repeatable).", collect, [])
|
|
17
|
-
.option("-H, --header <key=value>", "Request header (repeatable).", collect, [])
|
|
24
|
+
.option("-H, --header <key=value>", "Request header as key=value or 'Key: value' (repeatable).", collect, [])
|
|
18
25
|
.option("--body <json|@file|->", "JSON body: inline, @file, or - for stdin.")
|
|
19
26
|
.option("--all", "Walk page/page-size pagination, honoring Last-Page when present.", false)
|
|
20
27
|
.option("--page-size <n>", "Page size for --all.", parseIntArg, 50)
|
|
21
28
|
.option("--max-pages <n>", "Maximum pages for --all.", parseIntArg, 20)
|
|
22
29
|
.option("--include-headers", "Include status and response headers in output.", false)
|
|
23
30
|
.action(async function (methodArg, pathArg, options) {
|
|
24
|
-
const { client, config, output } = await resolveBaseContext(this, services);
|
|
25
31
|
const method = methodArg.toUpperCase();
|
|
26
32
|
if (!METHODS.has(method)) {
|
|
27
|
-
throw new
|
|
33
|
+
throw new UsageError(`Unsupported method "${methodArg}". Provide one of: GET, POST, PUT, PATCH, DELETE.`);
|
|
28
34
|
}
|
|
35
|
+
requireRelativePath(pathArg);
|
|
36
|
+
const query = options.query.map((value) => parsePair(value, "--query"));
|
|
37
|
+
const headers = parseHeaders(options.header);
|
|
38
|
+
validatePagingFlags(this, method, options);
|
|
39
|
+
const body = readBody(options.body);
|
|
40
|
+
if (body !== undefined && method === "GET") {
|
|
41
|
+
throw new UsageError("--body cannot be sent with GET; use POST, PUT, PATCH, or DELETE.");
|
|
42
|
+
}
|
|
43
|
+
if (body !== undefined && !hasHeader(headers, "content-type")) {
|
|
44
|
+
requireJson(body);
|
|
45
|
+
}
|
|
46
|
+
const output = resolveFlags(rootProgram(this));
|
|
47
|
+
const binaryConflict = process.stdout.isTTY || output.mode !== "table" || options.includeHeaders || options.all;
|
|
48
|
+
const accept = new Headers(headers).get("accept");
|
|
49
|
+
if (binaryConflict && accept && accept.split(",").every(type => !type.includes("*") && isBinaryMediaType(type))) {
|
|
50
|
+
throw new UsageError("Binary Accept header: redirect or pipe stdout without JSON, NDJSON, --all, or --include-headers.");
|
|
51
|
+
}
|
|
52
|
+
const { client, config } = await resolveBaseContext(this, services, output);
|
|
29
53
|
const path = resolvePath(pathArg, config.workspaceId);
|
|
30
|
-
const query = parseQueryPairs(options.query);
|
|
31
|
-
const headers = parsePairs(options.header);
|
|
32
54
|
if (options.all) {
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
if (options.includeHeaders) {
|
|
37
|
-
throw new Error("--include-headers is not supported with --all; each page's status and headers are consumed by the pagination walk.");
|
|
55
|
+
const { items, stop } = await fetchAllPages(client, path, query, headers, options.pageSize, options.maxPages);
|
|
56
|
+
if (stop === "repeated") {
|
|
57
|
+
printWarning("The endpoint ignores pagination (repeated page); returning the preceding pages.", output);
|
|
38
58
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
const prefix = output.color ? pc.yellow("WARN") : "WARN";
|
|
42
|
-
console.error(`${prefix} --all stopped at the --max-pages limit (${options.maxPages}); the results are incomplete. Re-run with a larger --max-pages.`);
|
|
59
|
+
else if (stop === "truncated") {
|
|
60
|
+
printWarning(`--all stopped at the --max-pages limit (${options.maxPages}); the results are incomplete. Re-run with a larger --max-pages.`, output);
|
|
43
61
|
}
|
|
44
62
|
printApiOutput(items, output);
|
|
45
63
|
return;
|
|
46
64
|
}
|
|
47
|
-
const
|
|
48
|
-
const response = await
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
65
|
+
const request = client.fetch(buildPath(path, query), requestInit(method, headers, body));
|
|
66
|
+
const response = method === "GET" ? await request : await dispatchedWrite(this, request);
|
|
67
|
+
if (isBinaryResponse(response)) {
|
|
68
|
+
if (!response.ok || binaryConflict) {
|
|
69
|
+
await response.body?.cancel().catch(() => undefined);
|
|
70
|
+
if (!response.ok)
|
|
71
|
+
throw await rawApiError(response, undefined);
|
|
72
|
+
throw Object.assign(new Error("Binary response: redirect or pipe stdout without JSON, NDJSON, or --include-headers."), { statusCode: response.status });
|
|
73
|
+
}
|
|
74
|
+
process.stdout.write(Buffer.from(await response.arrayBuffer()));
|
|
75
|
+
return;
|
|
54
76
|
}
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
77
|
+
if (response.ok) {
|
|
78
|
+
const data = await readResponseData(response);
|
|
79
|
+
printApiOutput(responsePayload(response, data, options.includeHeaders), output);
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
const { data, readError } = await readErrorData(response);
|
|
83
|
+
const cause = await rawApiError(response, data, undefined, readError);
|
|
84
|
+
if (!options.includeHeaders)
|
|
85
|
+
throw cause;
|
|
86
|
+
const payload = {
|
|
87
|
+
status: response.status,
|
|
88
|
+
headers: Object.fromEntries(response.headers),
|
|
89
|
+
data,
|
|
90
|
+
...(readError && { bodyError: readError.message }),
|
|
91
|
+
};
|
|
92
|
+
const write = await writeFailure(this, cause);
|
|
93
|
+
if (write) {
|
|
94
|
+
const { classifyClockifyError } = await import("clockify-sdk-ts-115/errors");
|
|
95
|
+
const classified = classifyClockifyError(cause);
|
|
96
|
+
Object.assign(payload, { retryable: classified?.retryable, recovery: classified?.recovery }, write);
|
|
58
97
|
}
|
|
98
|
+
printApiOutput(payload, output);
|
|
99
|
+
throw new AlreadyReportedError();
|
|
59
100
|
});
|
|
60
101
|
};
|
|
61
102
|
function collect(value, previous) {
|
|
62
103
|
previous.push(value);
|
|
63
104
|
return previous;
|
|
64
105
|
}
|
|
65
|
-
function
|
|
66
|
-
return Object.fromEntries(values.map(parsePair));
|
|
67
|
-
}
|
|
68
|
-
function parseQueryPairs(values) {
|
|
69
|
-
return values.map(parsePair);
|
|
70
|
-
}
|
|
71
|
-
function parsePair(value) {
|
|
106
|
+
function parsePair(value, flag) {
|
|
72
107
|
const index = value.indexOf("=");
|
|
73
108
|
if (index <= 0) {
|
|
74
|
-
throw new
|
|
109
|
+
throw new UsageError(`${flag} expected key=value, received "${value}".`);
|
|
75
110
|
}
|
|
76
111
|
const key = value.slice(0, index).trim();
|
|
77
112
|
if (!key) {
|
|
78
|
-
throw new
|
|
113
|
+
throw new UsageError(`${flag} expected a non-empty key in "${value}".`);
|
|
79
114
|
}
|
|
80
115
|
return [key, value.slice(index + 1)];
|
|
81
116
|
}
|
|
82
|
-
function
|
|
83
|
-
|
|
84
|
-
|
|
117
|
+
function parseHeaders(values) {
|
|
118
|
+
const headers = {};
|
|
119
|
+
for (const value of values) {
|
|
120
|
+
const colon = value.indexOf(":");
|
|
121
|
+
const equals = value.indexOf("=");
|
|
122
|
+
const [rawKey, rawValue] = colon > 0 && (equals === -1 || colon < equals)
|
|
123
|
+
? [value.slice(0, colon).trim(), value.slice(colon + 1).trim()]
|
|
124
|
+
: parsePair(value, "--header");
|
|
125
|
+
if (!HEADER_NAME.test(rawKey)) {
|
|
126
|
+
throw new UsageError(`--header name ${JSON.stringify(rawKey)} is not a valid HTTP header name.`);
|
|
127
|
+
}
|
|
128
|
+
if (/[\r\n\0]/.test(rawValue)) {
|
|
129
|
+
throw new UsageError(`--header ${rawKey} value must not contain CR, LF, or NUL characters.`);
|
|
130
|
+
}
|
|
131
|
+
if (CREDENTIAL_HEADERS.has(rawKey.toLowerCase())) {
|
|
132
|
+
throw new UsageError(`--header ${rawKey} is not accepted: the SDK sets credentials itself. Provide them through CLOCKIFY_API_KEY or CLOCKIFY_ADDON_TOKEN.`);
|
|
133
|
+
}
|
|
134
|
+
headers[rawKey] = rawValue;
|
|
135
|
+
}
|
|
136
|
+
return headers;
|
|
137
|
+
}
|
|
138
|
+
function hasHeader(headers, name) {
|
|
139
|
+
return Object.keys(headers).some((key) => key.toLowerCase() === name);
|
|
140
|
+
}
|
|
141
|
+
function requireRelativePath(path) {
|
|
142
|
+
if (!path.startsWith("/") || path.startsWith("//")) {
|
|
143
|
+
throw new UsageError("API path must start with a single /, relative to the API base URL (e.g. /workspaces/{workspaceId}/tags).");
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
function validatePagingFlags(command, method, options) {
|
|
147
|
+
if (!options.all) {
|
|
148
|
+
for (const [option, flag] of [
|
|
149
|
+
["pageSize", "--page-size"],
|
|
150
|
+
["maxPages", "--max-pages"],
|
|
151
|
+
]) {
|
|
152
|
+
if (command.getOptionValueSource(option) === "cli") {
|
|
153
|
+
throw new UsageError(`${flag} only applies with --all; for a single page pass -q page-size=N instead.`);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
if (method !== "GET") {
|
|
159
|
+
throw new UsageError("--all is only supported for GET requests.");
|
|
160
|
+
}
|
|
161
|
+
if (options.includeHeaders) {
|
|
162
|
+
throw new UsageError("--include-headers is not supported with --all; each page's status and headers are consumed by the pagination walk.");
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
function requireJson(body) {
|
|
166
|
+
try {
|
|
167
|
+
JSON.parse(body);
|
|
168
|
+
}
|
|
169
|
+
catch (err) {
|
|
170
|
+
const detail = err instanceof Error ? err.message : String(err);
|
|
171
|
+
throw new UsageError(`--body is not valid JSON (${detail}); provide valid JSON, or set a Content-Type header to send another format.`);
|
|
85
172
|
}
|
|
173
|
+
}
|
|
174
|
+
function resolvePath(path, workspaceId) {
|
|
86
175
|
if (path.includes("{workspaceId}")) {
|
|
87
176
|
if (!workspaceId) {
|
|
88
177
|
throw new Error("Path uses {workspaceId}; provide --workspace or CLOCKIFY_WORKSPACE_ID.");
|
|
@@ -124,7 +213,7 @@ function readBody(body) {
|
|
|
124
213
|
}
|
|
125
214
|
catch (err) {
|
|
126
215
|
const detail = err instanceof Error ? err.message : String(err);
|
|
127
|
-
throw new
|
|
216
|
+
throw new UsageError(`--body ${JSON.stringify(body)} could not be read: ${detail}; provide a readable JSON file path or pipe the body on stdin`);
|
|
128
217
|
}
|
|
129
218
|
}
|
|
130
219
|
return body;
|
|
@@ -132,42 +221,51 @@ function readBody(body) {
|
|
|
132
221
|
async function fetchAllPages(client, path, query, headers, pageSize, maxPages) {
|
|
133
222
|
const items = [];
|
|
134
223
|
const callerQuery = query.filter(([key]) => key !== "page" && key !== "page-size");
|
|
135
|
-
let
|
|
136
|
-
|
|
224
|
+
let state = { kind: "walking", page: 1 };
|
|
225
|
+
let previousPage;
|
|
226
|
+
while (state.kind === "walking") {
|
|
227
|
+
const page = state.page;
|
|
137
228
|
const pagePath = buildPath(path, [
|
|
138
229
|
...callerQuery,
|
|
139
230
|
["page", String(page)],
|
|
140
231
|
["page-size", String(pageSize)],
|
|
141
232
|
]);
|
|
142
233
|
const response = await client.fetch(pagePath, requestInit("GET", headers));
|
|
143
|
-
|
|
234
|
+
if (isBinaryResponse(response)) {
|
|
235
|
+
await response.body?.cancel().catch(() => undefined);
|
|
236
|
+
if (!response.ok)
|
|
237
|
+
throw await rawApiError(response, undefined, page);
|
|
238
|
+
throw Object.assign(new Error("--all expects JSON pages; pipe a binary response without --all."), { statusCode: response.status });
|
|
239
|
+
}
|
|
144
240
|
if (!response.ok) {
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
});
|
|
241
|
+
const { data, readError } = await readErrorData(response);
|
|
242
|
+
throw await rawApiError(response, data, page, readError);
|
|
148
243
|
}
|
|
244
|
+
const data = await readResponseData(response);
|
|
149
245
|
if (!Array.isArray(data)) {
|
|
150
246
|
throw new Error("--all expects each page to return a JSON array.");
|
|
151
247
|
}
|
|
152
248
|
const lastPage = parseLastPageHeader(response.headers.get("Last-Page"));
|
|
153
|
-
|
|
154
|
-
if (
|
|
155
|
-
|
|
249
|
+
const fingerprint = JSON.stringify(data);
|
|
250
|
+
if (fingerprint === previousPage) {
|
|
251
|
+
state = { kind: "repeated" };
|
|
156
252
|
break;
|
|
157
253
|
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
254
|
+
previousPage = fingerprint;
|
|
255
|
+
items.push(...data);
|
|
256
|
+
if (data.length === 0 ||
|
|
257
|
+
lastPage === true ||
|
|
258
|
+
(lastPage === undefined && data.length < pageSize)) {
|
|
259
|
+
state = { kind: "complete" };
|
|
161
260
|
}
|
|
162
|
-
if (
|
|
163
|
-
|
|
261
|
+
else if (page >= maxPages) {
|
|
262
|
+
state = { kind: "truncated" };
|
|
164
263
|
}
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
break;
|
|
264
|
+
else {
|
|
265
|
+
state = { kind: "walking", page: page + 1 };
|
|
168
266
|
}
|
|
169
267
|
}
|
|
170
|
-
return { items,
|
|
268
|
+
return { items, stop: state.kind };
|
|
171
269
|
}
|
|
172
270
|
function parseLastPageHeader(value) {
|
|
173
271
|
if (value == null)
|
|
@@ -179,8 +277,23 @@ function parseLastPageHeader(value) {
|
|
|
179
277
|
return false;
|
|
180
278
|
return undefined;
|
|
181
279
|
}
|
|
182
|
-
function
|
|
183
|
-
|
|
280
|
+
async function rawApiError(response, body, page, cause) {
|
|
281
|
+
const { ClockifyApiError } = await import("clockify-sdk-ts-115");
|
|
282
|
+
return new ClockifyApiError({
|
|
283
|
+
message: `HTTP ${response.status}${page === undefined ? "" : ` on page ${page}`}`,
|
|
284
|
+
statusCode: response.status,
|
|
285
|
+
rawResponse: response,
|
|
286
|
+
body,
|
|
287
|
+
...(cause && { cause }),
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
function isBinaryResponse(response) {
|
|
291
|
+
return response.body !== null && isBinaryMediaType(response.headers.get("content-type") ?? "");
|
|
292
|
+
}
|
|
293
|
+
function isBinaryMediaType(value) {
|
|
294
|
+
const media = value.split(";", 1)[0]?.trim().toLowerCase();
|
|
295
|
+
return Boolean(media && !media.startsWith("text/") &&
|
|
296
|
+
!/(?:[+/](?:json|xml|javascript|x-www-form-urlencoded))$/.test(media));
|
|
184
297
|
}
|
|
185
298
|
async function readResponseData(response) {
|
|
186
299
|
const text = await response.text();
|
|
@@ -194,6 +307,14 @@ async function readResponseData(response) {
|
|
|
194
307
|
return text;
|
|
195
308
|
}
|
|
196
309
|
}
|
|
310
|
+
async function readErrorData(response) {
|
|
311
|
+
try {
|
|
312
|
+
return { data: await readResponseData(response) };
|
|
313
|
+
}
|
|
314
|
+
catch (cause) {
|
|
315
|
+
return { data: null, readError: cause instanceof Error ? cause : new Error(String(cause)) };
|
|
316
|
+
}
|
|
317
|
+
}
|
|
197
318
|
function responsePayload(response, data, includeHeaders) {
|
|
198
319
|
if (!includeHeaders) {
|
|
199
320
|
return data;
|