@deliverd/sdk 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,247 +1,247 @@
1
- import { listOrCollect, type PageOf } from "./paging.js";
2
- import { DeliverdError, DeliverdTimeoutError } from "./errors.js";
3
- import type { HttpClient } from "./http.js";
4
- import { POLL_SCHEDULE } from "./approvals.js";
5
- import type {
6
- AnswerValue,
7
- CollectedAnswers,
8
- CollectionData,
9
- CreateCollectionInput,
10
- ListCollectionsInput,
11
- } from "./types.js";
12
-
13
- /**
14
- * Ask people for what you do not have.
15
- *
16
- * The third of the three, and the one that goes the other way. `approve()`
17
- * asks permission, `review()` asks judgement, and this asks for a fact: a
18
- * figure, a date, a choice between options, the sentence only they can write.
19
- */
20
-
21
- export interface CollectWaitOptions {
22
- /** Called after every poll, for a progress line in a CLI. */
23
- onPoll?: (collection: CollectionData) => void;
24
- /**
25
- * Give up after this many milliseconds and throw `DeliverdTimeoutError`.
26
- * Omitted, the wait ends when the request does — which, with no `expiresAt`,
27
- * may be never. Set one or the other.
28
- */
29
- timeout?: number;
30
- signal?: AbortSignal;
31
- pollIntervals?: readonly number[];
32
- }
33
-
34
- function pollDelay(poll: number, schedule: readonly number[]): number {
35
- const base = schedule[Math.min(poll, schedule.length - 1)] ?? 60_000;
36
- return base * 0.75 + Math.random() * base * 0.5;
37
- }
38
-
39
- /** A request for answers, and what you can do with it. */
40
- export class Collection {
41
- constructor(
42
- private readonly http: HttpClient,
43
- private data: CollectionData
44
- ) {}
45
-
46
- /**
47
- * The secret this request's callbacks are signed with, when you gave a
48
- * `callbackUrl`. Only on the handle `create()` returned — the API hands it
49
- * over once and never again — so keep it with whatever will receive the
50
- * callback, and check each one with
51
- * `deliverd.webhooks.constructCallback(callbackSecret, rawBody, signature)`.
52
- */
53
- callbackSecret: string | null = null;
54
-
55
- get id(): string { return this.data.id; }
56
- get status(): CollectionData["status"] { return this.data.status; }
57
- /** The page the people you asked will fill in. */
58
- get url(): string { return this.data.url; }
59
- get title(): string { return this.data.title; }
60
- get responses(): CollectionData["responses"] { return this.data.responses; }
61
- get submittedCount(): number { return this.data.submittedCount; }
62
- get askedCount(): number { return this.data.askedCount; }
63
-
64
- /** The one to branch on. False for expired and cancelled. */
65
- get complete(): boolean { return this.data.status === "complete"; }
66
- get expired(): boolean { return this.data.status === "expired"; }
67
- get cancelled(): boolean { return this.data.status === "cancelled"; }
68
- get pending(): boolean { return this.data.status === "pending"; }
69
-
70
- toJSON(): CollectionData { return this.data; }
71
-
72
- /**
73
- * The first submitted answer to each question, keyed by its prompt.
74
- *
75
- * The shape most callers want, because most callers asked one person for
76
- * three facts. When several people answered the same question, later
77
- * replies do not overwrite the first — use `responses` when you need all of
78
- * them, and note that this returns the earliest submission rather than a
79
- * merge, since silently blending two people's answers would be worse than
80
- * making you choose.
81
- */
82
- get answers(): Record<string, AnswerValue> {
83
- const out: Record<string, AnswerValue> = {};
84
- for (const reply of this.data.responses) {
85
- if (reply.status !== "submitted") continue;
86
- for (const answer of reply.answers) {
87
- if (!(answer.question in out)) out[answer.question] = answer.value;
88
- }
89
- }
90
- return out;
91
- }
92
-
93
- toCollected(): CollectedAnswers {
94
- const status = this.data.status === "pending" ? "expired" : this.data.status;
95
- return {
96
- complete: this.data.status === "complete",
97
- status,
98
- responses: this.data.responses.filter((r) => r.status === "submitted"),
99
- answers: this.answers,
100
- id: this.data.id,
101
- url: this.data.url,
102
- collection: this.data,
103
- } as CollectedAnswers;
104
- }
105
-
106
- async refresh(signal?: AbortSignal): Promise<this> {
107
- this.data = await this.http.request<CollectionData>({
108
- method: "GET",
109
- path: `/collections/${this.data.id}`,
110
- signal,
111
- });
112
- return this;
113
- }
114
-
115
- /** Withdraw it. The row stays as evidence of what was asked and dropped. */
116
- async cancel(signal?: AbortSignal): Promise<this> {
117
- this.data = await this.http.request<CollectionData>({
118
- method: "POST",
119
- path: `/collections/${this.data.id}/cancel`,
120
- signal,
121
- });
122
- return this;
123
- }
124
-
125
- /**
126
- * Block until enough people have answered, then return.
127
- *
128
- * Resolves on every ending, including expiry — which is an answer of a
129
- * kind, and one you must handle rather than treat as an error, because the
130
- * thing you do without the figure is usually different from the thing you
131
- * do with it.
132
- */
133
- async wait(options: CollectWaitOptions = {}): Promise<this> {
134
- const deadline = options.timeout !== undefined ? Date.now() + options.timeout : undefined;
135
- let poll = 0;
136
- if (!this.pending) return this;
137
-
138
- for (;;) {
139
- if (options.signal?.aborted) {
140
- throw new DeliverdError(0, "aborted", "The wait was aborted.", undefined, {
141
- cause: options.signal.reason,
142
- });
143
- }
144
- if (deadline !== undefined && Date.now() >= deadline) {
145
- throw new DeliverdTimeoutError(
146
- `Nobody finished answering "${this.data.title}" within the timeout. It is still open at ${this.data.url}.`
147
- );
148
- }
149
- const delay = pollDelay(poll++, options.pollIntervals ?? POLL_SCHEDULE);
150
- const remaining = deadline === undefined ? delay : Math.min(delay, deadline - Date.now());
151
- await sleep(Math.max(0, remaining), options.signal);
152
-
153
- await this.refresh(options.signal);
154
- options.onPoll?.(this.data);
155
- if (!this.pending) return this;
156
- }
157
- }
158
- }
159
-
160
- function sleep(ms: number, signal?: AbortSignal): Promise<void> {
161
- return new Promise((resolve, reject) => {
162
- if (signal?.aborted) {
163
- return reject(new DeliverdError(0, "aborted", "The wait was aborted."));
164
- }
165
- const timer = setTimeout(() => {
166
- signal?.removeEventListener("abort", onAbort);
167
- resolve();
168
- }, ms);
169
- const onAbort = () => {
170
- clearTimeout(timer);
171
- reject(new DeliverdError(0, "aborted", "The wait was aborted."));
172
- };
173
- signal?.addEventListener("abort", onAbort, { once: true });
174
- });
175
- }
176
-
177
- export class Collections {
178
- constructor(private readonly http: HttpClient) {}
179
-
180
- /** Ask. Returns as soon as the request is filed; call `wait()` next. */
181
- async create(input: CreateCollectionInput, signal?: AbortSignal): Promise<Collection> {
182
- const data = await this.http.request<CollectionData>({
183
- method: "POST",
184
- path: "/collections",
185
- body: input,
186
- signal,
187
- });
188
- const created = new Collection(this.http, data);
189
- created.callbackSecret = (data as CollectionData & { callbackSecret?: string }).callbackSecret ?? null;
190
- return created;
191
- }
192
-
193
- async get(id: string, signal?: AbortSignal): Promise<Collection> {
194
- const data = await this.http.request<CollectionData>({
195
- method: "GET",
196
- path: `/collections/${id}`,
197
- signal,
198
- });
199
- return new Collection(this.http, data);
200
- }
201
-
202
- /**
203
- * The organisation's collections, newest first.
204
- *
205
- * With no `limit` this is every one of them: the API says where each page
206
- * stopped and this follows the cursor to the end. With a `limit` it is one
207
- * page of that size, and `listPage` hands back the cursor to continue from.
208
- */
209
- async list(input: ListCollectionsInput = {}, signal?: AbortSignal): Promise<Collection[]> {
210
- return listOrCollect(input, async (q: { limit?: number; cursor?: string }) => {
211
- const page = await this.listPage({ ...input, ...q }, signal);
212
- return { items: page.items, nextCursor: page.nextCursor };
213
- });
214
- }
215
-
216
- /** One page, and the cursor to continue from — null when it is the end. */
217
- async listPage(
218
- input: ListCollectionsInput = {},
219
- signal?: AbortSignal
220
- ): Promise<PageOf<Collection>> {
221
- const { collections, nextCursor } = await this.http.request<{
222
- collections: CollectionData[];
223
- nextCursor: string | null;
224
- }>({
225
- method: "GET",
226
- path: "/collections",
227
- query: { status: input.status, externalId: input.externalId, limit: input.limit, cursor: input.cursor },
228
- signal,
229
- });
230
- return { items: collections.map((r) => new Collection(this.http, r)), nextCursor };
231
- }
232
-
233
- /** Ask and wait, for the common case where there is nothing to do between. */
234
- async request(
235
- input: CreateCollectionInput,
236
- options: CollectWaitOptions = {}
237
- ): Promise<Collection> {
238
- const collection = await this.create(input, options.signal);
239
- return collection.wait(options);
240
- }
241
-
242
- /** The same request as before, when there was one — so a restart does not ask twice. */
243
- async findByExternalId(externalId: string, signal?: AbortSignal): Promise<Collection | null> {
244
- const found = await this.list({ externalId, limit: 1 }, signal);
245
- return found[0] ?? null;
246
- }
247
- }
1
+ import { listOrCollect, type PageOf } from "./paging.js";
2
+ import { DeliverdError, DeliverdTimeoutError } from "./errors.js";
3
+ import type { HttpClient } from "./http.js";
4
+ import { POLL_SCHEDULE } from "./approvals.js";
5
+ import type {
6
+ AnswerValue,
7
+ CollectedAnswers,
8
+ CollectionData,
9
+ CreateCollectionInput,
10
+ ListCollectionsInput,
11
+ } from "./types.js";
12
+
13
+ /**
14
+ * Ask people for what you do not have.
15
+ *
16
+ * The third of the three, and the one that goes the other way. `approve()`
17
+ * asks permission, `review()` asks judgement, and this asks for a fact: a
18
+ * figure, a date, a choice between options, the sentence only they can write.
19
+ */
20
+
21
+ export interface CollectWaitOptions {
22
+ /** Called after every poll, for a progress line in a CLI. */
23
+ onPoll?: (collection: CollectionData) => void;
24
+ /**
25
+ * Give up after this many milliseconds and throw `DeliverdTimeoutError`.
26
+ * Omitted, the wait ends when the request does — which, with no `expiresAt`,
27
+ * may be never. Set one or the other.
28
+ */
29
+ timeout?: number;
30
+ signal?: AbortSignal;
31
+ pollIntervals?: readonly number[];
32
+ }
33
+
34
+ function pollDelay(poll: number, schedule: readonly number[]): number {
35
+ const base = schedule[Math.min(poll, schedule.length - 1)] ?? 60_000;
36
+ return base * 0.75 + Math.random() * base * 0.5;
37
+ }
38
+
39
+ /** A request for answers, and what you can do with it. */
40
+ export class Collection {
41
+ constructor(
42
+ private readonly http: HttpClient,
43
+ private data: CollectionData
44
+ ) {}
45
+
46
+ /**
47
+ * The secret this request's callbacks are signed with, when you gave a
48
+ * `callbackUrl`. Only on the handle `create()` returned — the API hands it
49
+ * over once and never again — so keep it with whatever will receive the
50
+ * callback, and check each one with
51
+ * `deliverd.webhooks.constructCallback(callbackSecret, rawBody, signature)`.
52
+ */
53
+ callbackSecret: string | null = null;
54
+
55
+ get id(): string { return this.data.id; }
56
+ get status(): CollectionData["status"] { return this.data.status; }
57
+ /** The page the people you asked will fill in. */
58
+ get url(): string { return this.data.url; }
59
+ get title(): string { return this.data.title; }
60
+ get responses(): CollectionData["responses"] { return this.data.responses; }
61
+ get submittedCount(): number { return this.data.submittedCount; }
62
+ get askedCount(): number { return this.data.askedCount; }
63
+
64
+ /** The one to branch on. False for expired and cancelled. */
65
+ get complete(): boolean { return this.data.status === "complete"; }
66
+ get expired(): boolean { return this.data.status === "expired"; }
67
+ get cancelled(): boolean { return this.data.status === "cancelled"; }
68
+ get pending(): boolean { return this.data.status === "pending"; }
69
+
70
+ toJSON(): CollectionData { return this.data; }
71
+
72
+ /**
73
+ * The first submitted answer to each question, keyed by its prompt.
74
+ *
75
+ * The shape most callers want, because most callers asked one person for
76
+ * three facts. When several people answered the same question, later
77
+ * replies do not overwrite the first — use `responses` when you need all of
78
+ * them, and note that this returns the earliest submission rather than a
79
+ * merge, since silently blending two people's answers would be worse than
80
+ * making you choose.
81
+ */
82
+ get answers(): Record<string, AnswerValue> {
83
+ const out: Record<string, AnswerValue> = {};
84
+ for (const reply of this.data.responses) {
85
+ if (reply.status !== "submitted") continue;
86
+ for (const answer of reply.answers) {
87
+ if (!(answer.question in out)) out[answer.question] = answer.value;
88
+ }
89
+ }
90
+ return out;
91
+ }
92
+
93
+ toCollected(): CollectedAnswers {
94
+ const status = this.data.status === "pending" ? "expired" : this.data.status;
95
+ return {
96
+ complete: this.data.status === "complete",
97
+ status,
98
+ responses: this.data.responses.filter((r) => r.status === "submitted"),
99
+ answers: this.answers,
100
+ id: this.data.id,
101
+ url: this.data.url,
102
+ collection: this.data,
103
+ } as CollectedAnswers;
104
+ }
105
+
106
+ async refresh(signal?: AbortSignal): Promise<this> {
107
+ this.data = await this.http.request<CollectionData>({
108
+ method: "GET",
109
+ path: `/collections/${this.data.id}`,
110
+ signal,
111
+ });
112
+ return this;
113
+ }
114
+
115
+ /** Withdraw it. The row stays as evidence of what was asked and dropped. */
116
+ async cancel(signal?: AbortSignal): Promise<this> {
117
+ this.data = await this.http.request<CollectionData>({
118
+ method: "POST",
119
+ path: `/collections/${this.data.id}/cancel`,
120
+ signal,
121
+ });
122
+ return this;
123
+ }
124
+
125
+ /**
126
+ * Block until enough people have answered, then return.
127
+ *
128
+ * Resolves on every ending, including expiry — which is an answer of a
129
+ * kind, and one you must handle rather than treat as an error, because the
130
+ * thing you do without the figure is usually different from the thing you
131
+ * do with it.
132
+ */
133
+ async wait(options: CollectWaitOptions = {}): Promise<this> {
134
+ const deadline = options.timeout !== undefined ? Date.now() + options.timeout : undefined;
135
+ let poll = 0;
136
+ if (!this.pending) return this;
137
+
138
+ for (;;) {
139
+ if (options.signal?.aborted) {
140
+ throw new DeliverdError(0, "aborted", "The wait was aborted.", undefined, {
141
+ cause: options.signal.reason,
142
+ });
143
+ }
144
+ if (deadline !== undefined && Date.now() >= deadline) {
145
+ throw new DeliverdTimeoutError(
146
+ `Nobody finished answering "${this.data.title}" within the timeout. It is still open at ${this.data.url}.`
147
+ );
148
+ }
149
+ const delay = pollDelay(poll++, options.pollIntervals ?? POLL_SCHEDULE);
150
+ const remaining = deadline === undefined ? delay : Math.min(delay, deadline - Date.now());
151
+ await sleep(Math.max(0, remaining), options.signal);
152
+
153
+ await this.refresh(options.signal);
154
+ options.onPoll?.(this.data);
155
+ if (!this.pending) return this;
156
+ }
157
+ }
158
+ }
159
+
160
+ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
161
+ return new Promise((resolve, reject) => {
162
+ if (signal?.aborted) {
163
+ return reject(new DeliverdError(0, "aborted", "The wait was aborted."));
164
+ }
165
+ const timer = setTimeout(() => {
166
+ signal?.removeEventListener("abort", onAbort);
167
+ resolve();
168
+ }, ms);
169
+ const onAbort = () => {
170
+ clearTimeout(timer);
171
+ reject(new DeliverdError(0, "aborted", "The wait was aborted."));
172
+ };
173
+ signal?.addEventListener("abort", onAbort, { once: true });
174
+ });
175
+ }
176
+
177
+ export class Collections {
178
+ constructor(private readonly http: HttpClient) {}
179
+
180
+ /** Ask. Returns as soon as the request is filed; call `wait()` next. */
181
+ async create(input: CreateCollectionInput, signal?: AbortSignal): Promise<Collection> {
182
+ const data = await this.http.request<CollectionData>({
183
+ method: "POST",
184
+ path: "/collections",
185
+ body: input,
186
+ signal,
187
+ });
188
+ const created = new Collection(this.http, data);
189
+ created.callbackSecret = (data as CollectionData & { callbackSecret?: string }).callbackSecret ?? null;
190
+ return created;
191
+ }
192
+
193
+ async get(id: string, signal?: AbortSignal): Promise<Collection> {
194
+ const data = await this.http.request<CollectionData>({
195
+ method: "GET",
196
+ path: `/collections/${id}`,
197
+ signal,
198
+ });
199
+ return new Collection(this.http, data);
200
+ }
201
+
202
+ /**
203
+ * The organisation's collections, newest first.
204
+ *
205
+ * With no `limit` this is every one of them: the API says where each page
206
+ * stopped and this follows the cursor to the end. With a `limit` it is one
207
+ * page of that size, and `listPage` hands back the cursor to continue from.
208
+ */
209
+ async list(input: ListCollectionsInput = {}, signal?: AbortSignal): Promise<Collection[]> {
210
+ return listOrCollect(input, async (q: { limit?: number; cursor?: string }) => {
211
+ const page = await this.listPage({ ...input, ...q }, signal);
212
+ return { items: page.items, nextCursor: page.nextCursor };
213
+ });
214
+ }
215
+
216
+ /** One page, and the cursor to continue from — null when it is the end. */
217
+ async listPage(
218
+ input: ListCollectionsInput = {},
219
+ signal?: AbortSignal
220
+ ): Promise<PageOf<Collection>> {
221
+ const { collections, nextCursor } = await this.http.request<{
222
+ collections: CollectionData[];
223
+ nextCursor: string | null;
224
+ }>({
225
+ method: "GET",
226
+ path: "/collections",
227
+ query: { status: input.status, externalId: input.externalId, limit: input.limit, cursor: input.cursor },
228
+ signal,
229
+ });
230
+ return { items: collections.map((r) => new Collection(this.http, r)), nextCursor };
231
+ }
232
+
233
+ /** Ask and wait, for the common case where there is nothing to do between. */
234
+ async request(
235
+ input: CreateCollectionInput,
236
+ options: CollectWaitOptions = {}
237
+ ): Promise<Collection> {
238
+ const collection = await this.create(input, options.signal);
239
+ return collection.wait(options);
240
+ }
241
+
242
+ /** The same request as before, when there was one — so a restart does not ask twice. */
243
+ async findByExternalId(externalId: string, signal?: AbortSignal): Promise<Collection | null> {
244
+ const found = await this.list({ externalId, limit: 1 }, signal);
245
+ return found[0] ?? null;
246
+ }
247
+ }