@deliverd/sdk 0.2.0 → 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.
package/README.md CHANGED
@@ -107,8 +107,6 @@ request it already made rather than asking a second time.
107
107
 
108
108
  ## Answering the approver
109
109
 
110
- ## Answering the approver
111
-
112
110
  The thing that makes this more than a pause button: a person can ask your
113
111
  agent a question from the approval page, and your agent can answer it without
114
112
  anyone leaving what they are doing.
@@ -156,16 +154,64 @@ neither can be waited on for ever, which is what `await` means.
156
154
  ```ts
157
155
  await deliverd.approve({ title }); // ask permission, and wait for the answer
158
156
  await deliverd.review({ title, reportId, reviewers }); // ask whether it is right
157
+ await deliverd.collect({ title, questions, respondents }); // ask for what you lack
159
158
  await deliverd.confirm({ title }); // a yes or no on something small → boolean
160
159
  await deliverd.publish({ title, content }); // get the work to the people who need it
161
160
  ```
162
161
 
163
- `collect()` — a human filling in what your agent is missing — is the last one,
164
- and it is **not in this package yet**, because the API behind it is not built.
165
- It is a stage of
166
- [the plan](https://github.com/davidpreid/deliverd/blob/main/docs/control-layer.md).
167
- Shipping it now as a method that throws would put a lie in your autocomplete,
168
- which is worse than its absence.
162
+ All five. Each one is a person your agent needs and cannot be.
163
+
164
+ ## Collecting
165
+
166
+ `approve()` asks permission, `review()` asks judgement, and this asks for a
167
+ fact — a figure, a date, a choice between options, the sentence only they can
168
+ write.
169
+
170
+ ```ts
171
+ const { complete, answers } = await deliverd.collect({
172
+ title: "Before I file the Q3 return",
173
+ respondents: ["finance@firm.example"],
174
+ questions: [
175
+ { prompt: "Headcount at 30 September", kind: "number" },
176
+ { prompt: "Any disposals in the quarter?", kind: "boolean" },
177
+ { prompt: "Which basis?", kind: "choice", options: ["Accrual", "Cash"] },
178
+ ],
179
+ });
180
+
181
+ if (!complete) return escalate();
182
+ file(answers["Headcount at 30 September"]);
183
+ ```
184
+
185
+ `answers` is keyed by the question you asked, and carries the first submitted
186
+ reply to each. Check `complete` before using it: a request that expired has
187
+ whatever arrived and no more, and what you do without the figure is usually
188
+ not what you do with it. Use `responses` when several people were asked and
189
+ you need all of them rather than the first.
190
+
191
+ Seven kinds of question: `text`, `long_text`, `number`, `date`, `choice`,
192
+ `multi_choice` and `boolean`. Every answer is checked against the kind that
193
+ asked for it before it is stored, and a required question blocks submission —
194
+ so a number field gives you a number, not the string a person typed.
195
+
196
+ There are no file questions. Answers are typed values, and a `file` kind with
197
+ no storage behind it would be a promise the page could not keep.
198
+
199
+ A respondent must be **an active member of your organisation, or a guest the
200
+ organisation already knows**. Anyone else is refused rather than emailed,
201
+ which is what stops an agent reaching an address of its choosing.
202
+
203
+ ```ts
204
+ await deliverd.collections.create(input); // ask without waiting
205
+ await deliverd.collections.get(id);
206
+ await deliverd.collections.list({ status: "pending" });
207
+ await deliverd.collections.findByExternalId("q3_close");
208
+ await collection.wait({ onPoll });
209
+ await collection.cancel();
210
+ ```
211
+
212
+ There is no method that submits an answer, and no endpoint behind one. People
213
+ answer on the page. They get one reminder before the due date and no more,
214
+ because a nudge that arrives twice teaches people to ignore the first.
169
215
 
170
216
  ## Reviewing
171
217
 
@@ -0,0 +1,78 @@
1
+ import type { HttpClient } from "./http.js";
2
+ import type { AnswerValue, CollectedAnswers, CollectionData, CreateCollectionInput, ListCollectionsInput } from "./types.js";
3
+ /**
4
+ * Ask people for what you do not have.
5
+ *
6
+ * The third of the three, and the one that goes the other way. `approve()`
7
+ * asks permission, `review()` asks judgement, and this asks for a fact: a
8
+ * figure, a date, a choice between options, the sentence only they can write.
9
+ */
10
+ export interface CollectWaitOptions {
11
+ /** Called after every poll, for a progress line in a CLI. */
12
+ onPoll?: (collection: CollectionData) => void;
13
+ /**
14
+ * Give up after this many milliseconds and throw `DeliverdTimeoutError`.
15
+ * Omitted, the wait ends when the request does — which, with no `expiresAt`,
16
+ * may be never. Set one or the other.
17
+ */
18
+ timeout?: number;
19
+ signal?: AbortSignal;
20
+ pollIntervals?: readonly number[];
21
+ }
22
+ /** A request for answers, and what you can do with it. */
23
+ export declare class Collection {
24
+ private readonly http;
25
+ private data;
26
+ constructor(http: HttpClient, data: CollectionData);
27
+ get id(): string;
28
+ get status(): CollectionData["status"];
29
+ /** The page the people you asked will fill in. */
30
+ get url(): string;
31
+ get title(): string;
32
+ get responses(): CollectionData["responses"];
33
+ get submittedCount(): number;
34
+ get askedCount(): number;
35
+ /** The one to branch on. False for expired and cancelled. */
36
+ get complete(): boolean;
37
+ get expired(): boolean;
38
+ get cancelled(): boolean;
39
+ get pending(): boolean;
40
+ toJSON(): CollectionData;
41
+ /**
42
+ * The first submitted answer to each question, keyed by its prompt.
43
+ *
44
+ * The shape most callers want, because most callers asked one person for
45
+ * three facts. When several people answered the same question, later
46
+ * replies do not overwrite the first — use `responses` when you need all of
47
+ * them, and note that this returns the earliest submission rather than a
48
+ * merge, since silently blending two people's answers would be worse than
49
+ * making you choose.
50
+ */
51
+ get answers(): Record<string, AnswerValue>;
52
+ toCollected(): CollectedAnswers;
53
+ refresh(signal?: AbortSignal): Promise<this>;
54
+ /** Withdraw it. The row stays as evidence of what was asked and dropped. */
55
+ cancel(signal?: AbortSignal): Promise<this>;
56
+ /**
57
+ * Block until enough people have answered, then return.
58
+ *
59
+ * Resolves on every ending, including expiry — which is an answer of a
60
+ * kind, and one you must handle rather than treat as an error, because the
61
+ * thing you do without the figure is usually different from the thing you
62
+ * do with it.
63
+ */
64
+ wait(options?: CollectWaitOptions): Promise<this>;
65
+ }
66
+ export declare class Collections {
67
+ private readonly http;
68
+ constructor(http: HttpClient);
69
+ /** Ask. Returns as soon as the request is filed; call `wait()` next. */
70
+ create(input: CreateCollectionInput, signal?: AbortSignal): Promise<Collection>;
71
+ get(id: string, signal?: AbortSignal): Promise<Collection>;
72
+ list(input?: ListCollectionsInput, signal?: AbortSignal): Promise<Collection[]>;
73
+ /** Ask and wait, for the common case where there is nothing to do between. */
74
+ request(input: CreateCollectionInput, options?: CollectWaitOptions): Promise<Collection>;
75
+ /** The same request as before, when there was one — so a restart does not ask twice. */
76
+ findByExternalId(externalId: string, signal?: AbortSignal): Promise<Collection | null>;
77
+ }
78
+ //# sourceMappingURL=collections.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"collections.d.ts","sourceRoot":"","sources":["../src/collections.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAE5C,OAAO,KAAK,EACV,WAAW,EACX,gBAAgB,EAChB,cAAc,EACd,qBAAqB,EACrB,oBAAoB,EACrB,MAAM,YAAY,CAAC;AAEpB;;;;;;GAMG;AAEH,MAAM,WAAW,kBAAkB;IACjC,6DAA6D;IAC7D,MAAM,CAAC,EAAE,CAAC,UAAU,EAAE,cAAc,KAAK,IAAI,CAAC;IAC9C;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACnC;AAOD,0DAA0D;AAC1D,qBAAa,UAAU;IAEnB,OAAO,CAAC,QAAQ,CAAC,IAAI;IACrB,OAAO,CAAC,IAAI;gBADK,IAAI,EAAE,UAAU,EACzB,IAAI,EAAE,cAAc;IAG9B,IAAI,EAAE,IAAI,MAAM,CAAyB;IACzC,IAAI,MAAM,IAAI,cAAc,CAAC,QAAQ,CAAC,CAA6B;IACnE,kDAAkD;IAClD,IAAI,GAAG,IAAI,MAAM,CAA0B;IAC3C,IAAI,KAAK,IAAI,MAAM,CAA4B;IAC/C,IAAI,SAAS,IAAI,cAAc,CAAC,WAAW,CAAC,CAAgC;IAC5E,IAAI,cAAc,IAAI,MAAM,CAAqC;IACjE,IAAI,UAAU,IAAI,MAAM,CAAiC;IAEzD,6DAA6D;IAC7D,IAAI,QAAQ,IAAI,OAAO,CAA4C;IACnE,IAAI,OAAO,IAAI,OAAO,CAA2C;IACjE,IAAI,SAAS,IAAI,OAAO,CAA6C;IACrE,IAAI,OAAO,IAAI,OAAO,CAA2C;IAEjE,MAAM,IAAI,cAAc;IAExB;;;;;;;;;OASG;IACH,IAAI,OAAO,IAAI,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,CASzC;IAED,WAAW,IAAI,gBAAgB;IAazB,OAAO,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IASlD,4EAA4E;IACtE,MAAM,CAAC,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC;IASjD;;;;;;;OAOG;IACG,IAAI,CAAC,OAAO,GAAE,kBAAuB,GAAG,OAAO,CAAC,IAAI,CAAC;CAyB5D;AAmBD,qBAAa,WAAW;IACV,OAAO,CAAC,QAAQ,CAAC,IAAI;gBAAJ,IAAI,EAAE,UAAU;IAE7C,wEAAwE;IAClE,MAAM,CAAC,KAAK,EAAE,qBAAqB,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC;IAU/E,GAAG,CAAC,EAAE,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,CAAC;IAS1D,IAAI,CAAC,KAAK,GAAE,oBAAyB,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC;IAUzF,8EAA8E;IACxE,OAAO,CACX,KAAK,EAAE,qBAAqB,EAC5B,OAAO,GAAE,kBAAuB,GAC/B,OAAO,CAAC,UAAU,CAAC;IAKtB,wFAAwF;IAClF,gBAAgB,CAAC,UAAU,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC;CAI7F"}
@@ -0,0 +1,170 @@
1
+ import { DeliverdError, DeliverdTimeoutError } from "./errors.js";
2
+ import { POLL_SCHEDULE } from "./approvals.js";
3
+ function pollDelay(poll, schedule) {
4
+ const base = schedule[Math.min(poll, schedule.length - 1)] ?? 60_000;
5
+ return base * 0.75 + Math.random() * base * 0.5;
6
+ }
7
+ /** A request for answers, and what you can do with it. */
8
+ export class Collection {
9
+ http;
10
+ data;
11
+ constructor(http, data) {
12
+ this.http = http;
13
+ this.data = data;
14
+ }
15
+ get id() { return this.data.id; }
16
+ get status() { return this.data.status; }
17
+ /** The page the people you asked will fill in. */
18
+ get url() { return this.data.url; }
19
+ get title() { return this.data.title; }
20
+ get responses() { return this.data.responses; }
21
+ get submittedCount() { return this.data.submittedCount; }
22
+ get askedCount() { return this.data.askedCount; }
23
+ /** The one to branch on. False for expired and cancelled. */
24
+ get complete() { return this.data.status === "complete"; }
25
+ get expired() { return this.data.status === "expired"; }
26
+ get cancelled() { return this.data.status === "cancelled"; }
27
+ get pending() { return this.data.status === "pending"; }
28
+ toJSON() { return this.data; }
29
+ /**
30
+ * The first submitted answer to each question, keyed by its prompt.
31
+ *
32
+ * The shape most callers want, because most callers asked one person for
33
+ * three facts. When several people answered the same question, later
34
+ * replies do not overwrite the first — use `responses` when you need all of
35
+ * them, and note that this returns the earliest submission rather than a
36
+ * merge, since silently blending two people's answers would be worse than
37
+ * making you choose.
38
+ */
39
+ get answers() {
40
+ const out = {};
41
+ for (const reply of this.data.responses) {
42
+ if (reply.status !== "submitted")
43
+ continue;
44
+ for (const answer of reply.answers) {
45
+ if (!(answer.question in out))
46
+ out[answer.question] = answer.value;
47
+ }
48
+ }
49
+ return out;
50
+ }
51
+ toCollected() {
52
+ const status = this.data.status === "pending" ? "expired" : this.data.status;
53
+ return {
54
+ complete: this.data.status === "complete",
55
+ status,
56
+ responses: this.data.responses.filter((r) => r.status === "submitted"),
57
+ answers: this.answers,
58
+ id: this.data.id,
59
+ url: this.data.url,
60
+ collection: this.data,
61
+ };
62
+ }
63
+ async refresh(signal) {
64
+ this.data = await this.http.request({
65
+ method: "GET",
66
+ path: `/collections/${this.data.id}`,
67
+ signal,
68
+ });
69
+ return this;
70
+ }
71
+ /** Withdraw it. The row stays as evidence of what was asked and dropped. */
72
+ async cancel(signal) {
73
+ this.data = await this.http.request({
74
+ method: "POST",
75
+ path: `/collections/${this.data.id}/cancel`,
76
+ signal,
77
+ });
78
+ return this;
79
+ }
80
+ /**
81
+ * Block until enough people have answered, then return.
82
+ *
83
+ * Resolves on every ending, including expiry — which is an answer of a
84
+ * kind, and one you must handle rather than treat as an error, because the
85
+ * thing you do without the figure is usually different from the thing you
86
+ * do with it.
87
+ */
88
+ async wait(options = {}) {
89
+ const deadline = options.timeout !== undefined ? Date.now() + options.timeout : undefined;
90
+ let poll = 0;
91
+ if (!this.pending)
92
+ return this;
93
+ for (;;) {
94
+ if (options.signal?.aborted) {
95
+ throw new DeliverdError(0, "aborted", "The wait was aborted.", undefined, {
96
+ cause: options.signal.reason,
97
+ });
98
+ }
99
+ if (deadline !== undefined && Date.now() >= deadline) {
100
+ throw new DeliverdTimeoutError(`Nobody finished answering "${this.data.title}" within the timeout. It is still open at ${this.data.url}.`);
101
+ }
102
+ const delay = pollDelay(poll++, options.pollIntervals ?? POLL_SCHEDULE);
103
+ const remaining = deadline === undefined ? delay : Math.min(delay, deadline - Date.now());
104
+ await sleep(Math.max(0, remaining), options.signal);
105
+ await this.refresh(options.signal);
106
+ options.onPoll?.(this.data);
107
+ if (!this.pending)
108
+ return this;
109
+ }
110
+ }
111
+ }
112
+ function sleep(ms, signal) {
113
+ return new Promise((resolve, reject) => {
114
+ if (signal?.aborted) {
115
+ return reject(new DeliverdError(0, "aborted", "The wait was aborted."));
116
+ }
117
+ const timer = setTimeout(() => {
118
+ signal?.removeEventListener("abort", onAbort);
119
+ resolve();
120
+ }, ms);
121
+ const onAbort = () => {
122
+ clearTimeout(timer);
123
+ reject(new DeliverdError(0, "aborted", "The wait was aborted."));
124
+ };
125
+ signal?.addEventListener("abort", onAbort, { once: true });
126
+ });
127
+ }
128
+ export class Collections {
129
+ http;
130
+ constructor(http) {
131
+ this.http = http;
132
+ }
133
+ /** Ask. Returns as soon as the request is filed; call `wait()` next. */
134
+ async create(input, signal) {
135
+ const data = await this.http.request({
136
+ method: "POST",
137
+ path: "/collections",
138
+ body: input,
139
+ signal,
140
+ });
141
+ return new Collection(this.http, data);
142
+ }
143
+ async get(id, signal) {
144
+ const data = await this.http.request({
145
+ method: "GET",
146
+ path: `/collections/${id}`,
147
+ signal,
148
+ });
149
+ return new Collection(this.http, data);
150
+ }
151
+ async list(input = {}, signal) {
152
+ const { collections } = await this.http.request({
153
+ method: "GET",
154
+ path: "/collections",
155
+ query: { status: input.status, externalId: input.externalId, limit: input.limit },
156
+ signal,
157
+ });
158
+ return collections.map((c) => new Collection(this.http, c));
159
+ }
160
+ /** Ask and wait, for the common case where there is nothing to do between. */
161
+ async request(input, options = {}) {
162
+ const collection = await this.create(input, options.signal);
163
+ return collection.wait(options);
164
+ }
165
+ /** The same request as before, when there was one — so a restart does not ask twice. */
166
+ async findByExternalId(externalId, signal) {
167
+ const found = await this.list({ externalId, limit: 1 }, signal);
168
+ return found[0] ?? null;
169
+ }
170
+ }
package/dist/dev.d.ts CHANGED
@@ -36,7 +36,7 @@ export interface DevelopmentOptions {
36
36
  log?: boolean;
37
37
  }
38
38
  /**
39
- * A `fetch` that serves the approvals and reviews APIs from memory.
39
+ * A `fetch` that serves the approvals, reviews and collections APIs from memory.
40
40
  *
41
41
  * Deliberately narrow: it answers the calls the primitives make and 501s the
42
42
  * rest, with a message saying so, rather than pretending to be the whole API
package/dist/dev.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"dev.d.ts","sourceRoot":"","sources":["../src/dev.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAc,MAAM,YAAY,CAAC;AAE3D;;;;;;;;;;;;;;;;;;GAkBG;AAEH,MAAM,MAAM,kBAAkB,GAAG,UAAU,GAAG,UAAU,GAAG,SAAS,GAAG,UAAU,CAAC;AAElF,MAAM,WAAW,kBAAkB;IACjC;;;;OAIG;IACH,OAAO,CAAC,EAAE,kBAAkB,GAAG,CAAC,CAAC,OAAO,EAAE,YAAY,KAAK,kBAAkB,CAAC,CAAC;IAC/E,+DAA+D;IAC/D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,6DAA6D;IAC7D,GAAG,CAAC,EAAE,OAAO,CAAC;CACf;AAcD;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,kBAAuB,GAAG,OAAO,UAAU,CAAC,KAAK,CAyK1F"}
1
+ {"version":3,"file":"dev.d.ts","sourceRoot":"","sources":["../src/dev.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAA8B,MAAM,YAAY,CAAC;AAE3E;;;;;;;;;;;;;;;;;;GAkBG;AAEH,MAAM,MAAM,kBAAkB,GAAG,UAAU,GAAG,UAAU,GAAG,SAAS,GAAG,UAAU,CAAC;AAElF,MAAM,WAAW,kBAAkB;IACjC;;;;OAIG;IACH,OAAO,CAAC,EAAE,kBAAkB,GAAG,CAAC,CAAC,OAAO,EAAE,YAAY,KAAK,kBAAkB,CAAC,CAAC;IAC/E,+DAA+D;IAC/D,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,qDAAqD;IACrD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,6DAA6D;IAC7D,GAAG,CAAC,EAAE,OAAO,CAAC;CACf;AAcD;;;;;;GAMG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,GAAE,kBAAuB,GAAG,OAAO,UAAU,CAAC,KAAK,CAyP1F"}
package/dist/dev.js CHANGED
@@ -1,7 +1,7 @@
1
1
  const DEFAULT_QUESTION = "Has this been through staging?";
2
2
  let counter = 0;
3
3
  /**
4
- * A `fetch` that serves the approvals and reviews APIs from memory.
4
+ * A `fetch` that serves the approvals, reviews and collections APIs from memory.
5
5
  *
6
6
  * Deliberately narrow: it answers the calls the primitives make and 501s the
7
7
  * rest, with a message saying so, rather than pretending to be the whole API
@@ -10,6 +10,7 @@ let counter = 0;
10
10
  export function developmentFetch(options = {}) {
11
11
  const store = new Map();
12
12
  const reviewStore = new Map();
13
+ const collectionStore = new Map();
13
14
  return (async (input, init) => {
14
15
  const url = new URL(String(input));
15
16
  const path = url.pathname.replace(/^\/api\/v1/, "");
@@ -155,10 +156,82 @@ export function developmentFetch(options = {}) {
155
156
  reviews: externalId ? all.filter((r) => r.externalId === externalId) : all,
156
157
  });
157
158
  }
159
+ if (method === "POST" && path === "/collections") {
160
+ const id = `col_dev_${++counter}`;
161
+ const outcome = resolveOutcome(options.outcome, body);
162
+ const asked = (body.respondents ?? []).map(String);
163
+ const questions = (body.questions ?? []).map((q, i) => ({
164
+ id: `q_dev_${i + 1}`,
165
+ prompt: String(q.prompt ?? "Question"),
166
+ help: q.help ?? null,
167
+ kind: q.kind ?? "text",
168
+ required: q.required !== false,
169
+ options: q.options ?? [],
170
+ }));
171
+ const data = {
172
+ id,
173
+ status: "pending",
174
+ url: `https://deliverd.dev/collect/${id}`,
175
+ title: String(body.title ?? "Untitled"),
176
+ instructions: body.instructions ?? null,
177
+ reportId: body.reportId ?? null,
178
+ externalId: body.externalId ?? null,
179
+ metadata: body.metadata ?? {},
180
+ requestedBy: "You (development mode)",
181
+ requiredResponses: body.requiredResponses ?? (asked.length || 1),
182
+ questions,
183
+ responses: asked.map((who) => ({
184
+ respondent: who,
185
+ status: "pending",
186
+ submittedAt: null,
187
+ answers: [],
188
+ })),
189
+ submittedCount: 0,
190
+ askedCount: asked.length,
191
+ settledAt: null,
192
+ dueAt: body.dueAt ?? null,
193
+ expiresAt: body.expiresAt ?? null,
194
+ createdAt: new Date().toISOString(),
195
+ };
196
+ collectionStore.set(id, {
197
+ data,
198
+ settleAt: Date.now() + (options.delay ?? 0),
199
+ /*
200
+ * A simulated rejection becomes an expiry here: there is no way to
201
+ * say no to a question, only to leave it unanswered, and that is the
202
+ * ending a caller most needs to have thought about.
203
+ */
204
+ expire: outcome === "rejected",
205
+ timeout: outcome === "timeout",
206
+ });
207
+ if (options.log !== false)
208
+ announceCollection(data, outcome);
209
+ return json(data, 201);
210
+ }
211
+ const collectionMatch = /^\/collections\/([^/]+)(\/cancel)?$/.exec(path);
212
+ if (collectionMatch) {
213
+ const stored = collectionStore.get(collectionMatch[1]);
214
+ if (!stored) {
215
+ return json({ error: { code: "not_found", message: "No such request in this development session." } }, 404);
216
+ }
217
+ if (collectionMatch[2] === "/cancel") {
218
+ stored.data.status = "cancelled";
219
+ return json(stored.data);
220
+ }
221
+ settleCollection(stored);
222
+ return json(stored.data);
223
+ }
224
+ if (method === "GET" && path === "/collections") {
225
+ const externalId = url.searchParams.get("externalId");
226
+ const all = [...collectionStore.values()].map((c) => c.data);
227
+ return json({
228
+ collections: externalId ? all.filter((c) => c.externalId === externalId) : all,
229
+ });
230
+ }
158
231
  return json({
159
232
  error: {
160
233
  code: "not_in_development_mode",
161
- message: `Development mode simulates approvals and reviews only, and something called ${method} ${path}. Use a real API key for the rest of the API.`,
234
+ message: `Development mode simulates approvals, reviews and collections only, and something called ${method} ${path}. Use a real API key for the rest of the API.`,
162
235
  },
163
236
  }, 501);
164
237
  });
@@ -242,3 +315,69 @@ function announceReview(data, verdict, willHang) {
242
315
  ];
243
316
  console.log(lines.join("\n"));
244
317
  }
318
+ /**
319
+ * Everyone answers, at the same moment, with a plausible value for the kind
320
+ * of question asked. Plausible rather than empty, because a caller writing
321
+ * `answers["Headcount at 30 September"] + 1` should find out here that it is
322
+ * a number, not in production.
323
+ */
324
+ function settleCollection(stored) {
325
+ if (stored.timeout || stored.data.status !== "pending")
326
+ return;
327
+ if (Date.now() < stored.settleAt)
328
+ return;
329
+ if (stored.expire) {
330
+ stored.data.status = "expired";
331
+ stored.data.settledAt = new Date().toISOString();
332
+ return;
333
+ }
334
+ const at = new Date().toISOString();
335
+ stored.data.responses = stored.data.responses.map((r) => ({
336
+ ...r,
337
+ status: "submitted",
338
+ submittedAt: at,
339
+ answers: stored.data.questions.map((q) => ({
340
+ question: q.prompt,
341
+ kind: q.kind,
342
+ value: sampleAnswer(q),
343
+ })),
344
+ }));
345
+ stored.data.submittedCount = stored.data.responses.length;
346
+ stored.data.status = "complete";
347
+ stored.data.settledAt = at;
348
+ }
349
+ function sampleAnswer(q) {
350
+ switch (q.kind) {
351
+ case "number":
352
+ return 42;
353
+ case "boolean":
354
+ return true;
355
+ case "date":
356
+ return new Date().toISOString().slice(0, 10);
357
+ case "choice":
358
+ return q.options[0] ?? "";
359
+ case "multi_choice":
360
+ return q.options.slice(0, 1);
361
+ case "long_text":
362
+ return "Simulated: a longer answer than a line.";
363
+ default:
364
+ return "Simulated answer";
365
+ }
366
+ }
367
+ function announceCollection(data, outcome) {
368
+ const lines = [
369
+ ` ┌─ Deliverd · development mode ─────────────────────────`,
370
+ ` │ ${data.title}`,
371
+ ` │ Asking: ${data.questions.map((q) => q.prompt).join(" · ") || "nothing"}`,
372
+ ` │ Of: ${data.responses.map((r) => r.respondent).join(", ") || "nobody named"}`,
373
+ ` │`,
374
+ ` │ Simulating: ${outcome === "timeout"
375
+ ? "nobody answers"
376
+ : outcome === "rejected"
377
+ ? "it expires unanswered"
378
+ : "everyone answers"}`,
379
+ ` └───────────────────────────────────────────────────────`,
380
+ "",
381
+ ];
382
+ console.log(lines.join("\n"));
383
+ }
package/dist/index.d.ts CHANGED
@@ -2,13 +2,15 @@ import { HttpClient, type ClientOptions } from "./http.js";
2
2
  import { Approvals, 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";
5
6
  import { Webhooks } from "./webhooks.js";
6
7
  import { type DevelopmentOptions } from "./dev.js";
7
8
  import { type Duration } from "./duration.js";
8
- import type { CreateApprovalInput, CreateReviewInput, Decision, PublishReportInput, PublishResult, ReviewOutcome } from "./types.js";
9
+ import type { CollectedAnswers, CreateApprovalInput, CreateCollectionInput, CreateReviewInput, Decision, PublishReportInput, PublishResult, ReviewOutcome } from "./types.js";
9
10
  export { Approval, Approvals, POLL_SCHEDULE, type WaitOptions } from "./approvals.js";
10
11
  export { Comments, Reports } from "./reports.js";
11
12
  export { Review, Reviews, type ReviewWaitOptions } from "./reviews.js";
13
+ export { Collection, Collections, type CollectWaitOptions } from "./collections.js";
12
14
  export { constructEvent, DELIVERY_HEADER, EVENT_HEADER, SIGNATURE_HEADER, TOLERANCE_SECONDS, verifySignature, Webhooks, } from "./webhooks.js";
13
15
  export { DeliverdError, DeliverdTimeoutError } from "./errors.js";
14
16
  export { DEFAULT_BASE_URL, type ClientOptions } from "./http.js";
@@ -66,6 +68,23 @@ export interface ReviewOptions extends Omit<CreateReviewInput, "expiresAt"> {
66
68
  */
67
69
  reuse?: boolean;
68
70
  }
71
+ /** Everything `collect()` takes, plus the conveniences it adds on top. */
72
+ export interface CollectOptions extends Omit<CreateCollectionInput, "expiresAt"> {
73
+ /** `"4h"`, `"30m"`, `"2d"`, or milliseconds. Default 24 hours. */
74
+ expiresIn?: Duration;
75
+ /** An exact moment instead, if you have one. */
76
+ expiresAt?: string;
77
+ /** Called after each poll — a progress line in a CLI. */
78
+ onPoll?: CollectWaitOptions["onPoll"];
79
+ /** Give up waiting after this. The request stays open until it expires. */
80
+ timeout?: Duration;
81
+ signal?: AbortSignal;
82
+ /**
83
+ * With an `externalId`, reuse an existing request rather than filing a
84
+ * second one, so a restarted agent does not ask the same people twice.
85
+ */
86
+ reuse?: boolean;
87
+ }
69
88
  /**
70
89
  * Deliverd: you build the action, Deliverd handles the human.
71
90
  *
@@ -88,6 +107,7 @@ export interface ReviewOptions extends Omit<CreateReviewInput, "expiresAt"> {
88
107
  export declare class Deliverd {
89
108
  readonly approvals: Approvals;
90
109
  readonly reviews: Reviews;
110
+ readonly collections: Collections;
91
111
  readonly reports: Reports;
92
112
  readonly comments: Comments;
93
113
  readonly webhooks: Webhooks;
@@ -137,6 +157,29 @@ export declare class Deliverd {
137
157
  * you say otherwise, so a wait always ends.
138
158
  */
139
159
  review(options: ReviewOptions): Promise<ReviewOutcome>;
160
+ /**
161
+ * Ask people for what you do not have, and wait for it.
162
+ *
163
+ * `approve()` asks permission, `review()` asks judgement, and this asks for
164
+ * a fact — a figure, a date, a choice between options, the sentence only
165
+ * they can write.
166
+ *
167
+ * ```ts
168
+ * const { answers } = await deliverd.collect({
169
+ * title: "Before I file the Q3 return",
170
+ * respondents: ["finance@firm.example"],
171
+ * questions: [
172
+ * { prompt: "Headcount at 30 September", kind: "number" },
173
+ * { prompt: "Any disposals in the quarter?", kind: "boolean" },
174
+ * ],
175
+ * });
176
+ * ```
177
+ *
178
+ * `answers` is keyed by the question you asked. Check `complete` before you
179
+ * use it: a request that expired has whatever arrived and no more, and the
180
+ * thing you do without the figure is usually not the thing you do with it.
181
+ */
182
+ collect(options: CollectOptions): Promise<CollectedAnswers>;
140
183
  /** Publish HTML to a secure URL. The other half of the product, one call in. */
141
184
  publish(input: PublishReportInput, signal?: AbortSignal): Promise<PublishResult>;
142
185
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,KAAK,aAAa,EAAE,MAAM,WAAW,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAsB,KAAK,WAAW,EAAE,MAAM,gBAAgB,CAAC;AACjF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,EAAE,OAAO,EAAE,KAAK,iBAAiB,EAAE,MAAM,cAAc,CAAC;AAC/D,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,EAAoB,KAAK,kBAAkB,EAAE,MAAM,UAAU,CAAC;AACrE,OAAO,EAAc,KAAK,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE1D,OAAO,KAAK,EACV,mBA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