@infaris/calendar-cli 0.9.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/dist/api.js ADDED
@@ -0,0 +1,409 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { extname } from "node:path";
3
+ import { getValidCredentials } from "./auth.js";
4
+ export const PRODUCTS = [
5
+ "general",
6
+ "pulseguard",
7
+ "pulsefiles",
8
+ "pulseqr",
9
+ "pulsecalendar",
10
+ "pulsesupport",
11
+ "pulsemail",
12
+ "ipulse",
13
+ ];
14
+ export const STATUSES = ["not_started", "in_progress", "done"];
15
+ export const PRIORITIES = ["high", "medium", "low"];
16
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
17
+ /**
18
+ * Resolve a user-supplied task reference (either a task key like "427"/"#427"
19
+ * or the task's internal UUID) to its UUID, since the update/delete routes
20
+ * only accept the UUID.
21
+ */
22
+ export async function resolveTaskId(idOrKey) {
23
+ if (UUID_RE.test(idOrKey))
24
+ return idOrKey;
25
+ const key = idOrKey.replace(/^#/, "");
26
+ const { res } = await authedFetch(`/api/work/tasks?key=${encodeURIComponent(key)}`, { method: "GET" });
27
+ if (!res.ok)
28
+ throw new Error(await describeError(res));
29
+ const data = (await res.json());
30
+ const task = data.tasks[0];
31
+ if (!task)
32
+ throw new Error(`No task found for #${key}`);
33
+ return task.id;
34
+ }
35
+ export function taskDueDate(value) {
36
+ if (value === undefined)
37
+ return undefined;
38
+ const date = new Date(value);
39
+ if (!value.trim() || Number.isNaN(date.getTime()))
40
+ throw new Error("Invalid due date. Use an ISO date or datetime.");
41
+ return date.toISOString();
42
+ }
43
+ export async function authedFetch(path, init) {
44
+ const creds = await getValidCredentials();
45
+ const res = await fetch(`${creds.baseUrl}${path}`, {
46
+ ...init,
47
+ redirect: init.redirect ?? "error",
48
+ signal: init.signal ?? AbortSignal.timeout(30_000),
49
+ headers: {
50
+ ...(init.headers ?? {}),
51
+ authorization: `Bearer ${creds.accessToken}`,
52
+ },
53
+ });
54
+ return { res, baseUrl: creds.baseUrl };
55
+ }
56
+ export async function createTask(input) {
57
+ const { res, baseUrl } = await authedFetch("/api/work/tasks", {
58
+ method: "POST",
59
+ headers: { "content-type": "application/json" },
60
+ body: JSON.stringify({ ...input, dueDate: taskDueDate(input.dueDate) }),
61
+ });
62
+ if (!res.ok) {
63
+ throw new Error(await describeError(res));
64
+ }
65
+ const data = (await res.json());
66
+ return { task: data.task, baseUrl };
67
+ }
68
+ export async function listTasks(filters) {
69
+ const params = new URLSearchParams();
70
+ if (filters.relationNumber)
71
+ params.set("relationNumber", filters.relationNumber);
72
+ if (filters.status)
73
+ params.set("status", filters.status);
74
+ if (filters.search)
75
+ params.set("search", filters.search);
76
+ if (filters.includeDone)
77
+ params.set("includeDone", "true");
78
+ if (filters.assigneeId)
79
+ params.set("assigneeId", filters.assigneeId);
80
+ const query = params.toString();
81
+ const { res, baseUrl } = await authedFetch(`/api/work/tasks${query ? `?${query}` : ""}`, { method: "GET" });
82
+ if (!res.ok) {
83
+ throw new Error(await describeError(res));
84
+ }
85
+ const data = (await res.json());
86
+ return { tasks: data.tasks, baseUrl };
87
+ }
88
+ export async function listTeamMembers() {
89
+ const { res, baseUrl } = await authedFetch("/api/work/members", {
90
+ method: "GET",
91
+ });
92
+ if (!res.ok)
93
+ throw new Error(await describeError(res));
94
+ const data = (await res.json());
95
+ return { members: data.members ?? [], baseUrl };
96
+ }
97
+ export async function updateTask(input) {
98
+ const { id, ...body } = input;
99
+ const { res, baseUrl } = await authedFetch(`/api/work/tasks/${id}`, {
100
+ method: "PATCH",
101
+ headers: { "content-type": "application/json" },
102
+ body: JSON.stringify({
103
+ ...body,
104
+ dueDate: body.dueDate === null ? null : taskDueDate(body.dueDate),
105
+ }),
106
+ });
107
+ if (!res.ok) {
108
+ throw new Error(await describeError(res));
109
+ }
110
+ const data = (await res.json());
111
+ return { task: data.task, baseUrl };
112
+ }
113
+ export async function deleteTask(id) {
114
+ const { res, baseUrl } = await authedFetch(`/api/work/tasks/${id}`, {
115
+ method: "DELETE",
116
+ });
117
+ if (!res.ok) {
118
+ throw new Error(await describeError(res));
119
+ }
120
+ return { baseUrl };
121
+ }
122
+ // --- Task attachments ---
123
+ export const MAX_ATTACHMENT_BYTES = 10 * 1024 * 1024;
124
+ const EXTENSION_MIME_TYPES = {
125
+ ".png": "image/png",
126
+ ".jpg": "image/jpeg",
127
+ ".jpeg": "image/jpeg",
128
+ ".gif": "image/gif",
129
+ ".webp": "image/webp",
130
+ ".svg": "image/svg+xml",
131
+ ".pdf": "application/pdf",
132
+ };
133
+ function guessMimeType(filePath) {
134
+ return (EXTENSION_MIME_TYPES[extname(filePath).toLowerCase()] ??
135
+ "application/octet-stream");
136
+ }
137
+ /** Uploads one file as an attachment on an existing task (mirrors the 10 MB server limit). */
138
+ export async function addTaskAttachment(taskId, filePath) {
139
+ const fileBytes = readFileSync(filePath);
140
+ if (fileBytes.byteLength > MAX_ATTACHMENT_BYTES) {
141
+ throw new Error(`${filePath} exceeds the 10 MB attachment limit`);
142
+ }
143
+ const fileName = filePath.split(/[/\\]/).pop() || "attachment";
144
+ const form = new FormData();
145
+ form.set("file", new Blob([fileBytes], { type: guessMimeType(filePath) }), fileName);
146
+ const { res, baseUrl } = await authedFetch(`/api/work/tasks/${taskId}/attachments`, { method: "POST", body: form });
147
+ if (!res.ok) {
148
+ throw new Error(await describeError(res));
149
+ }
150
+ const data = (await res.json());
151
+ return { attachment: data.attachment, baseUrl };
152
+ }
153
+ export async function getSettings() {
154
+ const { res, baseUrl } = await authedFetch("/api/settings", {
155
+ method: "GET",
156
+ });
157
+ if (!res.ok)
158
+ throw new Error(await describeError(res));
159
+ const raw = (await res.json());
160
+ if (!raw)
161
+ return { settings: null, baseUrl };
162
+ return {
163
+ settings: {
164
+ defaultCalendarId: raw.defaultCalendarId ?? null,
165
+ defaultEventDuration: raw.defaultEventDuration ?? 60,
166
+ workingHoursStart: raw.workingHoursStart ?? 9,
167
+ workingHoursEnd: raw.workingHoursEnd ?? 17,
168
+ showWeekends: raw.showWeekends ?? true,
169
+ weekStartsOn: raw.weekStartsOn ?? 1,
170
+ timezone: raw.timezone ?? "Europe/Amsterdam",
171
+ timeFormat: raw.timeFormat ?? "24h",
172
+ },
173
+ baseUrl,
174
+ };
175
+ }
176
+ export async function updateDefaultCalendar(defaultCalendarId) {
177
+ // Read first so the CLI remains safe against older Calendar servers
178
+ // where a partial PUT could reset unrelated settings such as reminders.
179
+ const { res: currentRes } = await authedFetch("/api/settings", {
180
+ method: "GET",
181
+ });
182
+ if (!currentRes.ok)
183
+ throw new Error(await describeError(currentRes));
184
+ const currentSettings = (await currentRes.json()) ?? {};
185
+ const { res, baseUrl } = await authedFetch("/api/settings", {
186
+ method: "PUT",
187
+ headers: { "content-type": "application/json" },
188
+ body: JSON.stringify({ ...currentSettings, defaultCalendarId }),
189
+ });
190
+ if (!res.ok)
191
+ throw new Error(await describeError(res));
192
+ const settings = (await res.json());
193
+ return { settings, baseUrl };
194
+ }
195
+ export async function listCalendars() {
196
+ const { res, baseUrl } = await authedFetch("/api/calendars", {
197
+ method: "GET",
198
+ });
199
+ if (!res.ok)
200
+ throw new Error(await describeError(res));
201
+ const accounts = (await res.json());
202
+ return { accounts, baseUrl };
203
+ }
204
+ export async function listEvents(filters) {
205
+ const params = new URLSearchParams();
206
+ params.set("start", filters.start.toISOString());
207
+ params.set("end", filters.end.toISOString());
208
+ if (filters.calendarId)
209
+ params.set("calendarId", filters.calendarId);
210
+ if (filters.expand !== false)
211
+ params.set("expand", "1");
212
+ const { res, baseUrl } = await authedFetch(`/api/events?${params.toString()}`, {
213
+ method: "GET",
214
+ });
215
+ if (!res.ok)
216
+ throw new Error(await describeError(res));
217
+ const all = (await res.json());
218
+ // Defensive range filter: the events API returns recurring masters that may
219
+ // sit outside the requested window (and only expands them when the server
220
+ // supports ?expand=1). Keep only events that actually overlap [start, end].
221
+ const startMs = filters.start.getTime();
222
+ const endMs = filters.end.getTime();
223
+ const events = all.filter((e) => {
224
+ const s = new Date(e.startTime).getTime();
225
+ const en = new Date(e.endTime).getTime();
226
+ return s <= endMs && en >= startMs;
227
+ });
228
+ return { events, baseUrl };
229
+ }
230
+ export async function createEvent(input) {
231
+ const { res, baseUrl } = await authedFetch("/api/events", {
232
+ method: "POST",
233
+ headers: { "content-type": "application/json" },
234
+ body: JSON.stringify(input),
235
+ });
236
+ if (!res.ok)
237
+ throw new Error(await describeError(res));
238
+ const event = (await res.json());
239
+ return { event, baseUrl };
240
+ }
241
+ export async function updateEvent(input) {
242
+ const { res, baseUrl } = await authedFetch("/api/events", {
243
+ method: "PUT",
244
+ headers: { "content-type": "application/json" },
245
+ body: JSON.stringify(input),
246
+ });
247
+ if (!res.ok)
248
+ throw new Error(await describeError(res));
249
+ const event = (await res.json());
250
+ return { event, baseUrl };
251
+ }
252
+ export async function deleteEvent(id) {
253
+ const { res, baseUrl } = await authedFetch(`/api/events?id=${encodeURIComponent(id)}`, { method: "DELETE" });
254
+ if (!res.ok)
255
+ throw new Error(await describeError(res));
256
+ return { baseUrl };
257
+ }
258
+ /**
259
+ * Find a single event (or recurring occurrence) by id within a date window.
260
+ * The events API has no by-id route, so we scan an expanded range and match on
261
+ * either the concrete id or the master `recurringEventId`.
262
+ */
263
+ export async function findEvent(id, window) {
264
+ const { events, baseUrl } = await listEvents({ ...window, expand: true });
265
+ const masterId = id.split(":")[0];
266
+ const event = events.find((e) => e.id === id) ??
267
+ events.find((e) => (e.recurringEventId ?? e.id) === masterId) ??
268
+ null;
269
+ return { event, baseUrl };
270
+ }
271
+ export async function listHours(input) {
272
+ const params = new URLSearchParams({ from: input.from, to: input.to });
273
+ if (input.userId)
274
+ params.set("userId", input.userId);
275
+ const { res, baseUrl } = await authedFetch(`/api/work/hours?${params.toString()}`, { method: "GET" });
276
+ if (!res.ok)
277
+ throw new Error(await describeError(res));
278
+ const hours = (await res.json());
279
+ return { hours, baseUrl };
280
+ }
281
+ export async function upsertHours(input) {
282
+ const { res, baseUrl } = await authedFetch("/api/work/hours", {
283
+ method: "PUT",
284
+ headers: { "content-type": "application/json" },
285
+ body: JSON.stringify(input),
286
+ });
287
+ if (!res.ok)
288
+ throw new Error(await describeError(res));
289
+ const data = (await res.json());
290
+ return { entry: data.entry, baseUrl };
291
+ }
292
+ export async function deleteHours(input) {
293
+ const params = new URLSearchParams({ workedOn: input.workedOn });
294
+ if (input.userId)
295
+ params.set("userId", input.userId);
296
+ const { res, baseUrl } = await authedFetch(`/api/work/hours?${params.toString()}`, { method: "DELETE" });
297
+ if (!res.ok)
298
+ throw new Error(await describeError(res));
299
+ const data = (await res.json());
300
+ return { deleted: Boolean(data.deleted), baseUrl };
301
+ }
302
+ /**
303
+ * Stages a mail draft in the user's own webmail (never sends). Returns the URL
304
+ * to open in `/dashboard/mail` to review, edit and send it.
305
+ */
306
+ export async function createMailDraft(input) {
307
+ let attachmentBase64;
308
+ let attachmentFilename;
309
+ let attachmentMimeType;
310
+ if (input.attachmentPath) {
311
+ const fileBytes = readFileSync(input.attachmentPath);
312
+ if (fileBytes.byteLength > MAX_ATTACHMENT_BYTES) {
313
+ throw new Error(`${input.attachmentPath} exceeds the 10 MB attachment limit`);
314
+ }
315
+ attachmentBase64 = fileBytes.toString("base64");
316
+ attachmentFilename =
317
+ input.attachmentPath.split(/[/\\]/).pop() || "attachment";
318
+ attachmentMimeType = guessMimeType(input.attachmentPath);
319
+ }
320
+ const { res, baseUrl } = await authedFetch("/api/mail/drafts", {
321
+ method: "POST",
322
+ headers: { "content-type": "application/json" },
323
+ body: JSON.stringify({
324
+ to: input.to,
325
+ subject: input.subject,
326
+ html: input.html,
327
+ fromAddress: input.fromAddress,
328
+ attachmentBase64,
329
+ attachmentFilename,
330
+ attachmentMimeType,
331
+ }),
332
+ });
333
+ if (!res.ok) {
334
+ throw new Error(await describeError(res));
335
+ }
336
+ const data = (await res.json());
337
+ return { ...data, baseUrl };
338
+ }
339
+ async function describeError(res) {
340
+ let detail = "";
341
+ try {
342
+ const body = (await res.json());
343
+ if (body?.error)
344
+ detail = `: ${body.error}`;
345
+ }
346
+ catch {
347
+ /* ignore */
348
+ }
349
+ if (res.status === 401) {
350
+ return `Unauthorized${detail}. Run \`infaris-calendar login\`.`;
351
+ }
352
+ if (res.status === 403) {
353
+ return `Forbidden${detail}. Your account needs admin access in Calendar.`;
354
+ }
355
+ return `Request failed (${res.status})${detail}`;
356
+ }
357
+ /** Full ticket context, including separately stored attachments. */
358
+ export async function getTaskContext(reference) {
359
+ const id = await resolveTaskId(reference);
360
+ const [detail, files, children, history] = await Promise.all([
361
+ authedFetch(`/api/work/tasks/${id}`, { method: "GET" }),
362
+ authedFetch(`/api/work/tasks/${id}/attachments`, { method: "GET" }),
363
+ authedFetch(`/api/work/tasks/${id}/subtasks`, { method: "GET" }),
364
+ authedFetch(`/api/work/tasks/${id}/comments`, { method: "GET" }),
365
+ ]);
366
+ if (!detail.res.ok)
367
+ throw new Error(await describeError(detail.res));
368
+ if (!files.res.ok)
369
+ throw new Error(await describeError(files.res));
370
+ if (!children.res.ok)
371
+ throw new Error(await describeError(children.res));
372
+ if (!history.res.ok)
373
+ throw new Error(await describeError(history.res));
374
+ const { task } = (await detail.res.json());
375
+ const { attachments } = (await files.res.json());
376
+ const { subtasks } = (await children.res.json());
377
+ const { comments, origin } = (await history.res.json());
378
+ return {
379
+ task: { ...task, subtasks, comments },
380
+ origin,
381
+ attachments,
382
+ url: `${detail.baseUrl}/t/${task.taskKey}`,
383
+ baseUrl: detail.baseUrl,
384
+ };
385
+ }
386
+ export async function commentOnTask(reference, body) {
387
+ if (!body.trim())
388
+ throw new Error("Comment body required");
389
+ const id = await resolveTaskId(reference);
390
+ const { res } = await authedFetch(`/api/work/tasks/${id}/comments`, {
391
+ method: "POST",
392
+ headers: { "content-type": "application/json" },
393
+ body: JSON.stringify({ body }),
394
+ });
395
+ if (!res.ok)
396
+ throw new Error(await describeError(res));
397
+ return res.json();
398
+ }
399
+ export async function linkTaskPullRequest(reference, input) {
400
+ const id = await resolveTaskId(reference);
401
+ const { res } = await authedFetch(`/api/work/tasks/${id}/github/pull-requests`, {
402
+ method: "POST",
403
+ headers: { "content-type": "application/json" },
404
+ body: JSON.stringify({ input, repo: "InfarisHQ/monorepo" }),
405
+ });
406
+ if (!res.ok)
407
+ throw new Error(await describeError(res));
408
+ return res.json();
409
+ }