@deliverd/sdk 0.2.0 → 0.4.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/src/flows.ts ADDED
@@ -0,0 +1,185 @@
1
+ import type { HttpClient } from "./http.js";
2
+ import type { CreateFlowInput, FlowData, ListFlowsInput } from "./types.js";
3
+ /*
4
+ * Type-only, and therefore erased: `index.ts` imports this file at runtime,
5
+ * and a value import back would be a cycle. What the handle needs from the
6
+ * client is its three primitives with their real signatures, so that
7
+ * `flow.approve({…})` is checked exactly as `deliverd.approve({…})` is.
8
+ */
9
+ import type {
10
+ ApproveOptions,
11
+ CollectOptions,
12
+ Decision,
13
+ ReviewOptions,
14
+ ReviewOutcome,
15
+ } from "./index.js";
16
+ import type { CollectedAnswers } from "./types.js";
17
+
18
+ /**
19
+ * A flow: the thread that ties one job's approvals, reviews, collections and
20
+ * publishes together.
21
+ *
22
+ * The reason it exists in this SDK rather than only in the API is the handle
23
+ * below. An agent doing a multi-step job would otherwise carry a `flowId`
24
+ * through every call and pass it by hand each time — which works right up
25
+ * until one call is written without it, and that step is then missing from
26
+ * the history with nothing to say so. `flow.approve()` cannot forget.
27
+ *
28
+ * It groups and nothing else. Nothing waits on a flow; nothing is blocked by
29
+ * one; there are no steps to declare up front. Do the work in the order you
30
+ * want it done and name the flow as you go.
31
+ */
32
+
33
+ /** The three primitives a flow can start on your behalf, with their real signatures. */
34
+ export interface FlowPrimitives {
35
+ approve(options: ApproveOptions): Promise<Decision>;
36
+ review(options: ReviewOptions): Promise<ReviewOutcome>;
37
+ collect(options: CollectOptions): Promise<CollectedAnswers>;
38
+ }
39
+
40
+ export class Flow {
41
+ constructor(
42
+ private readonly http: HttpClient,
43
+ private data: FlowData,
44
+ private readonly client: FlowPrimitives
45
+ ) {}
46
+
47
+ get id(): string { return this.data.id; }
48
+ get status(): FlowData["status"] { return this.data.status; }
49
+ /** The timeline page a person can open. */
50
+ get url(): string { return this.data.url; }
51
+ get title(): string { return this.data.title; }
52
+ get members(): FlowData["members"] { return this.data.members; }
53
+ get timeline(): NonNullable<FlowData["timeline"]> { return this.data.timeline ?? []; }
54
+ get memberCount(): number { return this.data.memberCount; }
55
+ get openCount(): number { return this.data.openCount; }
56
+
57
+ get open(): boolean { return this.data.status === "open"; }
58
+ get complete(): boolean { return this.data.status === "complete"; }
59
+ get cancelled(): boolean { return this.data.status === "cancelled"; }
60
+
61
+ /**
62
+ * Nothing in it is waiting on anybody *at this moment*.
63
+ *
64
+ * Not a claim that the job is finished — you may be about to add the next
65
+ * step, and an empty flow is never settled. Branch on it to decide whether
66
+ * to move on; call `complete()` to say the work is over.
67
+ */
68
+ get allSettled(): boolean { return this.data.allSettled; }
69
+
70
+ toJSON(): FlowData { return this.data; }
71
+
72
+ async refresh(signal?: AbortSignal): Promise<this> {
73
+ this.data = await this.http.request<FlowData>({
74
+ method: "GET",
75
+ path: `/flows/${this.data.id}`,
76
+ signal,
77
+ });
78
+ return this;
79
+ }
80
+
81
+ /**
82
+ * Ask permission, inside this flow. Exactly `deliverd.approve()` with the
83
+ * flow already named — which is the point: a `flowId` passed by hand at
84
+ * four call sites is one that gets left off the fifth.
85
+ */
86
+ approve(options: Omit<ApproveOptions, "flowId">): Promise<Decision> {
87
+ return this.client.approve({ ...options, flowId: this.data.id });
88
+ }
89
+
90
+ /** Ask for judgement, inside this flow. */
91
+ review(options: Omit<ReviewOptions, "flowId">): Promise<ReviewOutcome> {
92
+ return this.client.review({ ...options, flowId: this.data.id });
93
+ }
94
+
95
+ /** Ask for facts, inside this flow. */
96
+ collect(options: Omit<CollectOptions, "flowId">): Promise<CollectedAnswers> {
97
+ return this.client.collect({ ...options, flowId: this.data.id });
98
+ }
99
+
100
+ /**
101
+ * Say the work is done. It stops taking new members from here.
102
+ *
103
+ * Named `close()` rather than `complete()` so it does not collide with the
104
+ * `complete` getter above, which every other primitive in this SDK also
105
+ * has; `flow.complete` asks, `flow.close()` decides.
106
+ *
107
+ * Allowed with steps still outstanding, and how many is recorded — a flow
108
+ * that could not be closed until every reviewer replied would be one that
109
+ * stayed open for ever.
110
+ */
111
+ async close(signal?: AbortSignal): Promise<this> {
112
+ this.data = await this.http.request<FlowData>({
113
+ method: "POST",
114
+ path: `/flows/${this.data.id}/complete`,
115
+ signal,
116
+ });
117
+ return this;
118
+ }
119
+
120
+ /** Call it off. The flow and its members stay as evidence; nothing inside is cancelled. */
121
+ async cancel(signal?: AbortSignal): Promise<this> {
122
+ this.data = await this.http.request<FlowData>({
123
+ method: "POST",
124
+ path: `/flows/${this.data.id}/cancel`,
125
+ signal,
126
+ });
127
+ return this;
128
+ }
129
+ }
130
+
131
+ export class Flows {
132
+ constructor(
133
+ private readonly http: HttpClient,
134
+ private readonly client: FlowPrimitives
135
+ ) {}
136
+
137
+ async create(input: CreateFlowInput, signal?: AbortSignal): Promise<Flow> {
138
+ const data = await this.http.request<FlowData>({
139
+ method: "POST",
140
+ path: "/flows",
141
+ body: input,
142
+ signal,
143
+ });
144
+ return new Flow(this.http, data, this.client);
145
+ }
146
+
147
+ async get(id: string, signal?: AbortSignal): Promise<Flow> {
148
+ const data = await this.http.request<FlowData>({
149
+ method: "GET",
150
+ path: `/flows/${id}`,
151
+ signal,
152
+ });
153
+ return new Flow(this.http, data, this.client);
154
+ }
155
+
156
+ async list(input: ListFlowsInput = {}, signal?: AbortSignal): Promise<Flow[]> {
157
+ const { flows } = await this.http.request<{ flows: FlowData[] }>({
158
+ method: "GET",
159
+ path: "/flows",
160
+ query: { status: input.status, externalId: input.externalId, limit: input.limit },
161
+ signal,
162
+ });
163
+ return flows.map((f) => new Flow(this.http, f, this.client));
164
+ }
165
+
166
+ /** The same job as before, when there was one — so a restart extends it rather than starting a second. */
167
+ async findByExternalId(externalId: string, signal?: AbortSignal): Promise<Flow | null> {
168
+ const found = await this.list({ externalId, limit: 1 }, signal);
169
+ return found[0] ?? null;
170
+ }
171
+
172
+ /**
173
+ * The flow for this reference, started if it does not exist yet.
174
+ *
175
+ * What a restartable agent actually wants: one line that is correct on the
176
+ * first run and on the fourth. Without it the caller writes the lookup, the
177
+ * branch and the create by hand, and a crash between the lookup and the
178
+ * create leaves two flows for one job.
179
+ */
180
+ async resume(input: CreateFlowInput & { externalId: string }, signal?: AbortSignal): Promise<Flow> {
181
+ const existing = await this.findByExternalId(input.externalId, signal);
182
+ if (existing && existing.open) return existing;
183
+ return this.create(input, signal);
184
+ }
185
+ }
package/src/index.ts CHANGED
@@ -2,12 +2,16 @@ import { HttpClient, type ClientOptions } from "./http.js";
2
2
  import { Approvals, FAST_POLL_SCHEDULE, type WaitOptions } from "./approvals.js";
3
3
  import { Comments, Reports } from "./reports.js";
4
4
  import { Reviews, type ReviewWaitOptions } from "./reviews.js";
5
+ import { Collections, type CollectWaitOptions } from "./collections.js";
6
+ import { Flows } from "./flows.js";
5
7
  import { Webhooks } from "./webhooks.js";
6
8
  import { developmentFetch, type DevelopmentOptions } from "./dev.js";
7
9
  import { durationMs, type Duration } from "./duration.js";
8
10
  import { DeliverdError } from "./errors.js";
9
11
  import type {
12
+ CollectedAnswers,
10
13
  CreateApprovalInput,
14
+ CreateCollectionInput,
11
15
  CreateReviewInput,
12
16
  Decision,
13
17
  PublishReportInput,
@@ -18,6 +22,8 @@ import type {
18
22
  export { Approval, Approvals, POLL_SCHEDULE, type WaitOptions } from "./approvals.js";
19
23
  export { Comments, Reports } from "./reports.js";
20
24
  export { Review, Reviews, type ReviewWaitOptions } from "./reviews.js";
25
+ export { Collection, Collections, type CollectWaitOptions } from "./collections.js";
26
+ export { Flow, Flows, type FlowPrimitives } from "./flows.js";
21
27
  export {
22
28
  constructEvent,
23
29
  DELIVERY_HEADER,
@@ -88,6 +94,24 @@ export interface ReviewOptions extends Omit<CreateReviewInput, "expiresAt"> {
88
94
  reuse?: boolean;
89
95
  }
90
96
 
97
+ /** Everything `collect()` takes, plus the conveniences it adds on top. */
98
+ export interface CollectOptions extends Omit<CreateCollectionInput, "expiresAt"> {
99
+ /** `"4h"`, `"30m"`, `"2d"`, or milliseconds. Default 24 hours. */
100
+ expiresIn?: Duration;
101
+ /** An exact moment instead, if you have one. */
102
+ expiresAt?: string;
103
+ /** Called after each poll — a progress line in a CLI. */
104
+ onPoll?: CollectWaitOptions["onPoll"];
105
+ /** Give up waiting after this. The request stays open until it expires. */
106
+ timeout?: Duration;
107
+ signal?: AbortSignal;
108
+ /**
109
+ * With an `externalId`, reuse an existing request rather than filing a
110
+ * second one, so a restarted agent does not ask the same people twice.
111
+ */
112
+ reuse?: boolean;
113
+ }
114
+
91
115
  /**
92
116
  * Deliverd: you build the action, Deliverd handles the human.
93
117
  *
@@ -110,6 +134,8 @@ export interface ReviewOptions extends Omit<CreateReviewInput, "expiresAt"> {
110
134
  export class Deliverd {
111
135
  readonly approvals: Approvals;
112
136
  readonly reviews: Reviews;
137
+ readonly collections: Collections;
138
+ readonly flows: Flows;
113
139
  readonly reports: Reports;
114
140
  readonly comments: Comments;
115
141
  readonly webhooks: Webhooks;
@@ -131,6 +157,13 @@ export class Deliverd {
131
157
 
132
158
  this.approvals = new Approvals(this.http);
133
159
  this.reviews = new Reviews(this.http);
160
+ this.collections = new Collections(this.http);
161
+ /*
162
+ * The handle takes the client so `flow.approve()` is the same call as
163
+ * `deliverd.approve()` with the flow filled in, rather than a second
164
+ * implementation that can drift from it.
165
+ */
166
+ this.flows = new Flows(this.http, this);
134
167
  this.reports = new Reports(this.http);
135
168
  this.comments = new Comments(this.http);
136
169
  this.webhooks = new Webhooks();
@@ -258,6 +291,62 @@ export class Deliverd {
258
291
  return settled.toOutcome();
259
292
  }
260
293
 
294
+ /**
295
+ * Ask people for what you do not have, and wait for it.
296
+ *
297
+ * `approve()` asks permission, `review()` asks judgement, and this asks for
298
+ * a fact — a figure, a date, a choice between options, the sentence only
299
+ * they can write.
300
+ *
301
+ * ```ts
302
+ * const { answers } = await deliverd.collect({
303
+ * title: "Before I file the Q3 return",
304
+ * respondents: ["finance@firm.example"],
305
+ * questions: [
306
+ * { prompt: "Headcount at 30 September", kind: "number" },
307
+ * { prompt: "Any disposals in the quarter?", kind: "boolean" },
308
+ * ],
309
+ * });
310
+ * ```
311
+ *
312
+ * `answers` is keyed by the question you asked. Check `complete` before you
313
+ * use it: a request that expired has whatever arrived and no more, and the
314
+ * thing you do without the figure is usually not the thing you do with it.
315
+ */
316
+ async collect(options: CollectOptions): Promise<CollectedAnswers> {
317
+ const { expiresIn, timeout, onPoll, signal, reuse, ...input } = options;
318
+
319
+ if (input.externalId && reuse !== false) {
320
+ const existing = await this.collections.findByExternalId(input.externalId, signal);
321
+ if (existing) {
322
+ const settled = await existing.wait({
323
+ onPoll,
324
+ signal,
325
+ timeout: durationOrUndefined(timeout),
326
+ ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
327
+ });
328
+ return settled.toCollected();
329
+ }
330
+ }
331
+
332
+ const collection = await this.collections.create(
333
+ {
334
+ ...input,
335
+ expiresAt:
336
+ options.expiresAt ??
337
+ new Date(Date.now() + durationMs(expiresIn ?? DEFAULT_EXPIRY)).toISOString(),
338
+ },
339
+ signal
340
+ );
341
+ const settled = await collection.wait({
342
+ onPoll,
343
+ signal,
344
+ timeout: durationOrUndefined(timeout) ?? (this.development ? 2_000 : undefined),
345
+ ...(this.development ? { pollIntervals: FAST_POLL_SCHEDULE } : {}),
346
+ });
347
+ return settled.toCollected();
348
+ }
349
+
261
350
  /** Publish HTML to a secure URL. The other half of the product, one call in. */
262
351
  publish(input: PublishReportInput, signal?: AbortSignal): Promise<PublishResult> {
263
352
  return this.reports.publish(input, signal);
package/src/types.ts CHANGED
@@ -78,6 +78,12 @@ export interface CreateApprovalInput {
78
78
  expiresAt?: string;
79
79
  /** Your own reference, returned unchanged and searchable. */
80
80
  externalId?: string;
81
+ /**
82
+ * The flow this belongs to, when it is one step of a larger piece of work.
83
+ * Must be an open flow in your organisation. `flow.approve()` and its
84
+ * siblings set this for you.
85
+ */
86
+ flowId?: string;
81
87
  metadata?: Record<string, unknown>;
82
88
  }
83
89
 
@@ -205,7 +211,10 @@ export type WebhookEventName =
205
211
  | "approval.answered"
206
212
  | "review.requested"
207
213
  | "review.approved"
208
- | "review.changes_requested";
214
+ | "review.changes_requested"
215
+ | "collection.requested"
216
+ | "collection.completed"
217
+ | "flow.completed";
209
218
 
210
219
  export interface WebhookEvent {
211
220
  event: WebhookEventName;
@@ -251,6 +260,12 @@ export interface CreateReviewInput {
251
260
  expiresAt?: string;
252
261
  /** Your own reference, returned unchanged and searchable. */
253
262
  externalId?: string;
263
+ /**
264
+ * The flow this belongs to, when it is one step of a larger piece of work.
265
+ * Must be an open flow in your organisation. `flow.approve()` and its
266
+ * siblings set this for you.
267
+ */
268
+ flowId?: string;
254
269
  metadata?: Record<string, unknown>;
255
270
  }
256
271
 
@@ -310,3 +325,187 @@ export interface ListReviewsInput {
310
325
  reportId?: string;
311
326
  limit?: number;
312
327
  }
328
+
329
+ /* ── Collections ──────────────────────────────────────────────────────────── */
330
+
331
+ export type CollectionStatus = "pending" | "complete" | "expired" | "cancelled";
332
+
333
+ export type QuestionKind =
334
+ | "text"
335
+ | "long_text"
336
+ | "number"
337
+ | "date"
338
+ | "choice"
339
+ | "multi_choice"
340
+ | "boolean";
341
+
342
+ /** What an answer can hold, shaped by its question's kind. */
343
+ export type AnswerValue = string | number | boolean | string[];
344
+
345
+ export interface QuestionInput {
346
+ /** The question, as you would ask it out loud. */
347
+ prompt: string;
348
+ /** The sentence under the field that stops the wrong answer being given. */
349
+ help?: string;
350
+ kind: QuestionKind;
351
+ /** Required unless you say otherwise; a required question blocks submission. */
352
+ required?: boolean;
353
+ /** For `choice` and `multi_choice`. At least two, or it is not a question. */
354
+ options?: string[];
355
+ }
356
+
357
+ export interface CreateCollectionInput {
358
+ /** What you need, as a headline the person sees first. */
359
+ title: string;
360
+ /** Why you are asking, shown above the questions. */
361
+ instructions?: string;
362
+ questions: QuestionInput[];
363
+ /**
364
+ * Emails or user ids. An active member, or a guest the organisation already
365
+ * knows — anyone else is refused rather than emailed.
366
+ */
367
+ respondents: string[];
368
+ /** How many submitted replies complete it; everyone asked, when omitted. */
369
+ requiredResponses?: number;
370
+ /** A published report the request is about. */
371
+ reportId?: string;
372
+ /** Shown to the person, and what the single reminder is measured against. */
373
+ dueAt?: string;
374
+ /** After this the request closes unanswered. ISO 8601. */
375
+ expiresAt?: string;
376
+ externalId?: string;
377
+ /**
378
+ * The flow this belongs to, when it is one step of a larger piece of work.
379
+ * Must be an open flow in your organisation. `flow.approve()` and its
380
+ * siblings set this for you.
381
+ */
382
+ flowId?: string;
383
+ metadata?: Record<string, unknown>;
384
+ }
385
+
386
+ export interface CollectionQuestion {
387
+ id: string;
388
+ prompt: string;
389
+ help: string | null;
390
+ kind: QuestionKind;
391
+ required: boolean;
392
+ options: string[];
393
+ }
394
+
395
+ export interface CollectionReply {
396
+ /** Who answered, as a name rather than an id. */
397
+ respondent: string;
398
+ status: "pending" | "submitted";
399
+ submittedAt: string | null;
400
+ /** Empty until they submit: a half-typed draft is not what they meant to say. */
401
+ answers: { question: string; kind: QuestionKind; value: AnswerValue }[];
402
+ }
403
+
404
+ export interface CollectionData {
405
+ id: string;
406
+ status: CollectionStatus;
407
+ /** The page the person fills in. */
408
+ url: string;
409
+ title: string;
410
+ instructions: string | null;
411
+ reportId: string | null;
412
+ externalId: string | null;
413
+ metadata: Record<string, unknown>;
414
+ requestedBy: string;
415
+ requiredResponses: number;
416
+ questions: CollectionQuestion[];
417
+ responses: CollectionReply[];
418
+ submittedCount: number;
419
+ askedCount: number;
420
+ settledAt: string | null;
421
+ dueAt: string | null;
422
+ expiresAt: string | null;
423
+ createdAt: string;
424
+ }
425
+
426
+ /** The answers, flattened — what `collect()` hands back. */
427
+ export interface CollectedAnswers {
428
+ /** True when enough people replied; false if it expired or was withdrawn. */
429
+ complete: boolean;
430
+ status: Exclude<CollectionStatus, "pending">;
431
+ /** Every submitted reply, in the order they arrived. */
432
+ responses: CollectionReply[];
433
+ /**
434
+ * The first submitted answer to each question, by its prompt — the shape
435
+ * most callers want when they asked one person for three facts.
436
+ */
437
+ answers: Record<string, AnswerValue>;
438
+ id: string;
439
+ url: string;
440
+ collection: CollectionData;
441
+ }
442
+
443
+ export interface ListCollectionsInput {
444
+ status?: CollectionStatus;
445
+ externalId?: string;
446
+ limit?: number;
447
+ }
448
+
449
+ /* ── Flows ────────────────────────────────────────────────────────────────── */
450
+
451
+ export type FlowStatus = "open" | "complete" | "cancelled";
452
+ export type FlowMemberKind = "approval" | "review" | "collection" | "report";
453
+
454
+ export interface FlowMember {
455
+ kind: FlowMemberKind;
456
+ id: string;
457
+ title: string;
458
+ /** The member's own status word, which differs by kind. */
459
+ status: string;
460
+ /** Still waiting on somebody. Always false for a report. */
461
+ open: boolean;
462
+ createdAt: string;
463
+ }
464
+
465
+ /** One line of the history: what happened, who did it, when. */
466
+ export interface FlowEvent {
467
+ event: string;
468
+ actor: string;
469
+ actorType: string;
470
+ resourceType: string | null;
471
+ resourceId: string | null;
472
+ at: string;
473
+ }
474
+
475
+ export interface FlowData {
476
+ id: string;
477
+ status: FlowStatus;
478
+ /** The timeline page a person can open. */
479
+ url: string;
480
+ title: string;
481
+ description: string | null;
482
+ externalId: string | null;
483
+ metadata: Record<string, unknown>;
484
+ startedBy: string;
485
+ members: FlowMember[];
486
+ memberCount: number;
487
+ openCount: number;
488
+ /** Nothing outstanding right now — not a claim that the job is finished. */
489
+ allSettled: boolean;
490
+ /** Present on a single read, absent from a list. */
491
+ timeline?: FlowEvent[];
492
+ settledAt: string | null;
493
+ createdAt: string;
494
+ }
495
+
496
+ export interface CreateFlowInput {
497
+ /** What this piece of work is, as the timeline will be titled. */
498
+ title: string;
499
+ /** What it is for, for whoever reads the history a year from now. */
500
+ description?: string;
501
+ workspaceId?: string;
502
+ /** Your own reference. Pass it and use `resume()` so a restart does not start a second flow. */
503
+ externalId?: string;
504
+ metadata?: Record<string, unknown>;
505
+ }
506
+
507
+ export interface ListFlowsInput {
508
+ status?: FlowStatus;
509
+ externalId?: string;
510
+ limit?: number;
511
+ }