@deliverd/sdk 0.1.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/LICENSE +21 -0
- package/README.md +282 -0
- package/dist/approvals.d.ts +133 -0
- package/dist/approvals.d.ts.map +1 -0
- package/dist/approvals.js +228 -0
- package/dist/dev.d.ts +46 -0
- package/dist/dev.d.ts.map +1 -0
- package/dist/dev.js +147 -0
- package/dist/duration.d.ts +10 -0
- package/dist/duration.d.ts.map +1 -0
- package/dist/duration.js +10 -0
- package/dist/errors.d.ts +44 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +58 -0
- package/dist/http.d.ts +45 -0
- package/dist/http.d.ts.map +1 -0
- package/dist/http.js +135 -0
- package/dist/index.d.ts +103 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +144 -0
- package/dist/messages.d.ts +24 -0
- package/dist/messages.d.ts.map +1 -0
- package/dist/messages.js +70 -0
- package/dist/reports.d.ts +76 -0
- package/dist/reports.d.ts.map +1 -0
- package/dist/reports.js +168 -0
- package/dist/types.d.ts +179 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +11 -0
- package/dist/webhooks.d.ts +49 -0
- package/dist/webhooks.d.ts.map +1 -0
- package/dist/webhooks.js +77 -0
- package/package.json +55 -0
- package/src/approvals.ts +286 -0
- package/src/dev.ts +213 -0
- package/src/duration.ts +21 -0
- package/src/errors.ts +62 -0
- package/src/http.ts +185 -0
- package/src/index.ts +212 -0
- package/src/messages.ts +78 -0
- package/src/reports.ts +217 -0
- package/src/types.ts +213 -0
- package/src/webhooks.ts +98 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,MAAM,MAAM,cAAc,GAAG,SAAS,GAAG,UAAU,GAAG,UAAU,GAAG,SAAS,GAAG,WAAW,CAAC;AAC3F,MAAM,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|
|
|
1
|
+
/**
|
|
2
|
+
* The API's objects, by hand.
|
|
3
|
+
*
|
|
4
|
+
* Not imported from the server's zod schemas on purpose: this package is
|
|
5
|
+
* published to npm and must not drag the monorepo's internals with it. The
|
|
6
|
+
* cost of that is drift, so `apps/web/src/lib/services/api-approvals.test.ts`
|
|
7
|
+
* holds these shapes to the schemas the API actually validates — a field added
|
|
8
|
+
* there and not here fails the build on the server side, where someone is
|
|
9
|
+
* looking.
|
|
10
|
+
*/
|
|
11
|
+
export {};
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import type { WebhookEvent } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Verifying what Deliverd sends you.
|
|
4
|
+
*
|
|
5
|
+
* The scheme is Stripe's — a timestamp and a signature in one header, the
|
|
6
|
+
* timestamp inside the signed material — so this is the verification everyone
|
|
7
|
+
* has written before. It is here anyway because a receiver that skips it is
|
|
8
|
+
* accepting anything anyone posts at the URL, and "write your own HMAC check"
|
|
9
|
+
* is the step every integration guide shows and half of them get wrong.
|
|
10
|
+
*
|
|
11
|
+
* Kept byte-for-byte with the server's own `lib/webhooks/signature.ts`;
|
|
12
|
+
* `sdk-parity.test.ts` on the server holds the two together.
|
|
13
|
+
*/
|
|
14
|
+
export declare const SIGNATURE_HEADER = "deliverd-signature";
|
|
15
|
+
export declare const EVENT_HEADER = "deliverd-event";
|
|
16
|
+
export declare const DELIVERY_HEADER = "deliverd-delivery";
|
|
17
|
+
/** How old a signature may be. Five minutes, as the server sends. */
|
|
18
|
+
export declare const TOLERANCE_SECONDS = 300;
|
|
19
|
+
export declare function signedPayload(timestamp: number, body: string): string;
|
|
20
|
+
/**
|
|
21
|
+
* Whether the header is this secret's signature over this body, recently.
|
|
22
|
+
*
|
|
23
|
+
* `body` must be the raw request body, before any JSON parsing — a re-encoded
|
|
24
|
+
* object is a different string and will never verify. In Express that means
|
|
25
|
+
* `express.raw({ type: "application/json" })`; in Next.js `await request.text()`.
|
|
26
|
+
*/
|
|
27
|
+
export declare function verifySignature(secret: string, body: string, header: string | null | undefined, options?: {
|
|
28
|
+
now?: number;
|
|
29
|
+
toleranceSeconds?: number;
|
|
30
|
+
}): boolean;
|
|
31
|
+
/**
|
|
32
|
+
* Verify and parse in one step, the way a handler wants it.
|
|
33
|
+
*
|
|
34
|
+
* Throws rather than returning null, because a webhook route that treats an
|
|
35
|
+
* unverifiable body as "no event" answers 200 and tells the sender everything
|
|
36
|
+
* is fine.
|
|
37
|
+
*/
|
|
38
|
+
export declare function constructEvent(secret: string, body: string, header: string | null | undefined, options?: {
|
|
39
|
+
now?: number;
|
|
40
|
+
toleranceSeconds?: number;
|
|
41
|
+
}): WebhookEvent;
|
|
42
|
+
export declare class Webhooks {
|
|
43
|
+
verifySignature: typeof verifySignature;
|
|
44
|
+
constructEvent: typeof constructEvent;
|
|
45
|
+
readonly signatureHeader = "deliverd-signature";
|
|
46
|
+
readonly eventHeader = "deliverd-event";
|
|
47
|
+
readonly deliveryHeader = "deliverd-delivery";
|
|
48
|
+
}
|
|
49
|
+
//# sourceMappingURL=webhooks.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webhooks.d.ts","sourceRoot":"","sources":["../src/webhooks.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/C;;;;;;;;;;;GAWG;AAEH,eAAO,MAAM,gBAAgB,uBAAuB,CAAC;AACrD,eAAO,MAAM,YAAY,mBAAmB,CAAC;AAC7C,eAAO,MAAM,eAAe,sBAAsB,CAAC;AAEnD,qEAAqE;AACrE,eAAO,MAAM,iBAAiB,MAAM,CAAC;AAErC,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAErE;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EACjC,OAAO,GAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAAO,GACxD,OAAO,CAsBT;AAED;;;;;;GAMG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EACjC,OAAO,GAAE;IAAE,GAAG,CAAC,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,MAAM,CAAA;CAAO,GACxD,YAAY,CAad;AAED,qBAAa,QAAQ;IACnB,eAAe,yBAAmB;IAClC,cAAc,wBAAkB;IAChC,QAAQ,CAAC,eAAe,wBAAoB;IAC5C,QAAQ,CAAC,WAAW,oBAAgB;IACpC,QAAQ,CAAC,cAAc,uBAAmB;CAC3C"}
|
package/dist/webhooks.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { DeliverdError } from "./errors.js";
|
|
3
|
+
/**
|
|
4
|
+
* Verifying what Deliverd sends you.
|
|
5
|
+
*
|
|
6
|
+
* The scheme is Stripe's — a timestamp and a signature in one header, the
|
|
7
|
+
* timestamp inside the signed material — so this is the verification everyone
|
|
8
|
+
* has written before. It is here anyway because a receiver that skips it is
|
|
9
|
+
* accepting anything anyone posts at the URL, and "write your own HMAC check"
|
|
10
|
+
* is the step every integration guide shows and half of them get wrong.
|
|
11
|
+
*
|
|
12
|
+
* Kept byte-for-byte with the server's own `lib/webhooks/signature.ts`;
|
|
13
|
+
* `sdk-parity.test.ts` on the server holds the two together.
|
|
14
|
+
*/
|
|
15
|
+
export const SIGNATURE_HEADER = "deliverd-signature";
|
|
16
|
+
export const EVENT_HEADER = "deliverd-event";
|
|
17
|
+
export const DELIVERY_HEADER = "deliverd-delivery";
|
|
18
|
+
/** How old a signature may be. Five minutes, as the server sends. */
|
|
19
|
+
export const TOLERANCE_SECONDS = 300;
|
|
20
|
+
export function signedPayload(timestamp, body) {
|
|
21
|
+
return `${timestamp}.${body}`;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Whether the header is this secret's signature over this body, recently.
|
|
25
|
+
*
|
|
26
|
+
* `body` must be the raw request body, before any JSON parsing — a re-encoded
|
|
27
|
+
* object is a different string and will never verify. In Express that means
|
|
28
|
+
* `express.raw({ type: "application/json" })`; in Next.js `await request.text()`.
|
|
29
|
+
*/
|
|
30
|
+
export function verifySignature(secret, body, header, options = {}) {
|
|
31
|
+
if (!header)
|
|
32
|
+
return false;
|
|
33
|
+
const now = options.now ?? Math.floor(Date.now() / 1000);
|
|
34
|
+
const tolerance = options.toleranceSeconds ?? TOLERANCE_SECONDS;
|
|
35
|
+
const parts = new Map(header.split(",").map((p) => {
|
|
36
|
+
const at = p.indexOf("=");
|
|
37
|
+
return [p.slice(0, at).trim(), p.slice(at + 1).trim()];
|
|
38
|
+
}));
|
|
39
|
+
const t = Number(parts.get("t"));
|
|
40
|
+
const v1 = parts.get("v1");
|
|
41
|
+
if (!Number.isFinite(t) || !v1)
|
|
42
|
+
return false;
|
|
43
|
+
if (Math.abs(now - t) > tolerance)
|
|
44
|
+
return false;
|
|
45
|
+
const expected = createHmac("sha256", secret).update(signedPayload(t, body)).digest("hex");
|
|
46
|
+
const a = Buffer.from(expected, "utf8");
|
|
47
|
+
const b = Buffer.from(v1, "utf8");
|
|
48
|
+
// Length first: timingSafeEqual throws on a mismatch, which leaks length.
|
|
49
|
+
if (a.length !== b.length)
|
|
50
|
+
return false;
|
|
51
|
+
return timingSafeEqual(a, b);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Verify and parse in one step, the way a handler wants it.
|
|
55
|
+
*
|
|
56
|
+
* Throws rather than returning null, because a webhook route that treats an
|
|
57
|
+
* unverifiable body as "no event" answers 200 and tells the sender everything
|
|
58
|
+
* is fine.
|
|
59
|
+
*/
|
|
60
|
+
export function constructEvent(secret, body, header, options = {}) {
|
|
61
|
+
if (!verifySignature(secret, body, header, options)) {
|
|
62
|
+
throw new DeliverdError(400, "invalid_signature", "The signature did not verify. Check the endpoint's secret, and that you passed the raw request body rather than a re-encoded object.");
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
return JSON.parse(body);
|
|
66
|
+
}
|
|
67
|
+
catch (cause) {
|
|
68
|
+
throw new DeliverdError(400, "invalid_json", "The body verified but is not JSON.", undefined, { cause });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
export class Webhooks {
|
|
72
|
+
verifySignature = verifySignature;
|
|
73
|
+
constructEvent = constructEvent;
|
|
74
|
+
signatureHeader = SIGNATURE_HEADER;
|
|
75
|
+
eventHeader = EVENT_HEADER;
|
|
76
|
+
deliveryHeader = DELIVERY_HEADER;
|
|
77
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@deliverd/sdk",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Add human approval to any AI agent. Ask a person, wait for the answer, act on it.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"default": "./dist/index.js"
|
|
12
|
+
}
|
|
13
|
+
},
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"src",
|
|
17
|
+
"!src/**/*.test.ts",
|
|
18
|
+
"README.md",
|
|
19
|
+
"LICENSE"
|
|
20
|
+
],
|
|
21
|
+
"publishConfig": {
|
|
22
|
+
"access": "public"
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"build": "tsc",
|
|
26
|
+
"typecheck": "tsc --noEmit",
|
|
27
|
+
"prepublishOnly": "npm run build"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@types/node": "^20",
|
|
31
|
+
"typescript": "^5",
|
|
32
|
+
"vitest": "^4.1.11"
|
|
33
|
+
},
|
|
34
|
+
"engines": {
|
|
35
|
+
"node": ">=20"
|
|
36
|
+
},
|
|
37
|
+
"license": "MIT",
|
|
38
|
+
"keywords": [
|
|
39
|
+
"ai",
|
|
40
|
+
"agent",
|
|
41
|
+
"approval",
|
|
42
|
+
"human-in-the-loop",
|
|
43
|
+
"mcp",
|
|
44
|
+
"deliverd"
|
|
45
|
+
],
|
|
46
|
+
"homepage": "https://deliverd.dev/developers",
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "git+https://github.com/davidpreid/deliverd.git",
|
|
50
|
+
"directory": "packages/sdk"
|
|
51
|
+
},
|
|
52
|
+
"bugs": {
|
|
53
|
+
"url": "https://github.com/davidpreid/deliverd/issues"
|
|
54
|
+
}
|
|
55
|
+
}
|
package/src/approvals.ts
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
1
|
+
import { DeliverdError, DeliverdTimeoutError } from "./errors.js";
|
|
2
|
+
import type { HttpClient } from "./http.js";
|
|
3
|
+
import { durationMs, type Duration } from "./duration.js";
|
|
4
|
+
import type {
|
|
5
|
+
ApprovalData,
|
|
6
|
+
ApprovalQuestion,
|
|
7
|
+
CreateApprovalInput,
|
|
8
|
+
Decision,
|
|
9
|
+
ListApprovalsInput,
|
|
10
|
+
} from "./types.js";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Ask a person before you act.
|
|
14
|
+
*
|
|
15
|
+
* The point of this module is one line — `await approval.wait()` — and
|
|
16
|
+
* everything in it exists to make that line safe to write in a real agent:
|
|
17
|
+
* polling that backs off instead of hammering, a question from the approver
|
|
18
|
+
* answered without leaving the wait, and an end that is guaranteed by the
|
|
19
|
+
* request's own expiry rather than by hope.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* How often to ask, as the wait gets longer. Milliseconds.
|
|
24
|
+
*
|
|
25
|
+
* The first one is deliberately quick. Most approvals take minutes, but the
|
|
26
|
+
* ones that take two seconds are the ones somebody is watching — a demo, a
|
|
27
|
+
* deploy with the approver stood next to you — and a client whose first look
|
|
28
|
+
* is two seconds away makes an instant decision feel like a slow one. One
|
|
29
|
+
* cheap early request buys that, and against a limit of 120 a minute it costs
|
|
30
|
+
* nothing. After a few polls the schedule is somebody's afternoon, not a
|
|
31
|
+
* progress bar.
|
|
32
|
+
*/
|
|
33
|
+
export const POLL_SCHEDULE = [250, 750, 2_000, 4_000, 8_000, 15_000, 30_000] as const;
|
|
34
|
+
const POLL_CEILING = 60_000;
|
|
35
|
+
|
|
36
|
+
/** Development mode: the approver is imaginary and instant, so keep up. */
|
|
37
|
+
export const FAST_POLL_SCHEDULE = [10, 25, 50, 100] as const;
|
|
38
|
+
|
|
39
|
+
function pollDelay(poll: number, schedule: readonly number[]): number {
|
|
40
|
+
const base = schedule[Math.min(poll, schedule.length - 1)] ?? POLL_CEILING;
|
|
41
|
+
// Jitter, so a hundred agents started by the same cron do not arrive together.
|
|
42
|
+
return base * 0.75 + Math.random() * base * 0.5;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface WaitOptions {
|
|
46
|
+
/**
|
|
47
|
+
* Called when the approver asks the requester something. Return the answer
|
|
48
|
+
* and the wait posts it and carries on; return `null` to leave it for a
|
|
49
|
+
* person. Without this a question simply sits there — the approver is
|
|
50
|
+
* waiting on you, and nothing will move until it is answered or they decide
|
|
51
|
+
* anyway.
|
|
52
|
+
*/
|
|
53
|
+
onQuestion?: (question: ApprovalQuestion, approval: ApprovalData) => Promise<string | null> | string | null;
|
|
54
|
+
/** Called after every poll, for a progress line in a CLI. */
|
|
55
|
+
onPoll?: (approval: ApprovalData) => void;
|
|
56
|
+
/**
|
|
57
|
+
* Give up after this many milliseconds and throw `DeliverdTimeoutError`.
|
|
58
|
+
* Omitted, the wait ends when the request does — which, for a request with
|
|
59
|
+
* no `expiresAt`, may be never. Set one or the other.
|
|
60
|
+
*/
|
|
61
|
+
timeout?: number;
|
|
62
|
+
signal?: AbortSignal;
|
|
63
|
+
/**
|
|
64
|
+
* How long between polls, as the wait lengthens. Rarely worth changing —
|
|
65
|
+
* development mode uses it to keep up with an approver who is instant.
|
|
66
|
+
*/
|
|
67
|
+
pollIntervals?: readonly number[];
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* A request, and what you can do with it.
|
|
72
|
+
*
|
|
73
|
+
* The data is a snapshot; `wait()` and `refresh()` replace it in place, so a
|
|
74
|
+
* handle held across a wait reads the settled request rather than the one you
|
|
75
|
+
* created.
|
|
76
|
+
*/
|
|
77
|
+
export class Approval {
|
|
78
|
+
constructor(
|
|
79
|
+
private readonly http: HttpClient,
|
|
80
|
+
private data: ApprovalData
|
|
81
|
+
) {}
|
|
82
|
+
|
|
83
|
+
get id(): string { return this.data.id; }
|
|
84
|
+
get status(): ApprovalData["status"] { return this.data.status; }
|
|
85
|
+
/** The page the approver decides on. Put it in your own UI or logs. */
|
|
86
|
+
get url(): string { return this.data.url; }
|
|
87
|
+
get title(): string { return this.data.title; }
|
|
88
|
+
/** Their reason, when they gave one. */
|
|
89
|
+
get note(): string | null { return this.data.note; }
|
|
90
|
+
get decidedBy(): string | null { return this.data.decidedBy; }
|
|
91
|
+
get decidedAt(): string | null { return this.data.decidedAt; }
|
|
92
|
+
get questions(): ApprovalQuestion[] { return this.data.questions; }
|
|
93
|
+
/** Questions the approver is still waiting on you to answer. */
|
|
94
|
+
get openQuestions(): ApprovalQuestion[] { return this.data.questions.filter((q) => !q.answer); }
|
|
95
|
+
|
|
96
|
+
/** The one to branch on. False for rejected, expired and cancelled alike. */
|
|
97
|
+
get approved(): boolean { return this.data.status === "approved"; }
|
|
98
|
+
get rejected(): boolean { return this.data.status === "rejected"; }
|
|
99
|
+
get expired(): boolean { return this.data.status === "expired"; }
|
|
100
|
+
get cancelled(): boolean { return this.data.status === "cancelled"; }
|
|
101
|
+
get pending(): boolean { return this.data.status === "pending"; }
|
|
102
|
+
|
|
103
|
+
/** Everything the API returned, if you want a field the getters do not name. */
|
|
104
|
+
toJSON(): ApprovalData { return this.data; }
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The answer, flattened — what `approve()` hands back.
|
|
108
|
+
*
|
|
109
|
+
* `approved` is a boolean so `if (decision.approved)` reads as the sentence
|
|
110
|
+
* it is; `status` is the narrowing union for a switch. Both, because people
|
|
111
|
+
* write both and neither should be the wrong one.
|
|
112
|
+
*/
|
|
113
|
+
toDecision(): Decision {
|
|
114
|
+
const status = this.data.status === "pending" ? "expired" : this.data.status;
|
|
115
|
+
return {
|
|
116
|
+
approved: this.data.status === "approved",
|
|
117
|
+
status,
|
|
118
|
+
note: this.data.note,
|
|
119
|
+
decidedBy: this.data.decidedBy,
|
|
120
|
+
decidedAt: this.data.decidedAt,
|
|
121
|
+
id: this.data.id,
|
|
122
|
+
url: this.data.url,
|
|
123
|
+
approval: this,
|
|
124
|
+
} as Decision;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
async refresh(signal?: AbortSignal): Promise<this> {
|
|
128
|
+
this.data = await this.http.request<ApprovalData>({
|
|
129
|
+
method: "GET",
|
|
130
|
+
path: `/approvals/${this.data.id}`,
|
|
131
|
+
signal,
|
|
132
|
+
});
|
|
133
|
+
return this;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Answer a question the approver asked. Only the requester may. */
|
|
137
|
+
async answer(questionId: string, answer: string, signal?: AbortSignal): Promise<this> {
|
|
138
|
+
this.data = await this.http.request<ApprovalData>({
|
|
139
|
+
method: "POST",
|
|
140
|
+
path: `/approvals/${this.data.id}/answers`,
|
|
141
|
+
body: { questionId, answer },
|
|
142
|
+
signal,
|
|
143
|
+
});
|
|
144
|
+
return this;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/** Withdraw it. The row stays as evidence of what was asked and dropped. */
|
|
148
|
+
async cancel(signal?: AbortSignal): Promise<this> {
|
|
149
|
+
this.data = await this.http.request<ApprovalData>({
|
|
150
|
+
method: "POST",
|
|
151
|
+
path: `/approvals/${this.data.id}/cancel`,
|
|
152
|
+
signal,
|
|
153
|
+
});
|
|
154
|
+
return this;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Block until a person decides, then return.
|
|
159
|
+
*
|
|
160
|
+
* Resolves on approved, rejected, expired and cancelled — it does not throw
|
|
161
|
+
* on a no, because a refusal is an answer and `if (approval.approved)` is
|
|
162
|
+
* the line that should follow. It throws only when the wait itself failed:
|
|
163
|
+
* a timeout, an abort, or the API being unreachable.
|
|
164
|
+
*/
|
|
165
|
+
async wait(options: WaitOptions = {}): Promise<this> {
|
|
166
|
+
const deadline = options.timeout !== undefined ? Date.now() + options.timeout : undefined;
|
|
167
|
+
let poll = 0;
|
|
168
|
+
|
|
169
|
+
// Already settled, or answered between create and wait.
|
|
170
|
+
if (!this.pending) return this;
|
|
171
|
+
|
|
172
|
+
for (;;) {
|
|
173
|
+
if (options.signal?.aborted) {
|
|
174
|
+
throw new DeliverdError(0, "aborted", "The wait was aborted.", undefined, {
|
|
175
|
+
cause: options.signal.reason,
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
if (deadline !== undefined && Date.now() >= deadline) {
|
|
179
|
+
throw new DeliverdTimeoutError(
|
|
180
|
+
`Nobody decided "${this.data.title}" within the timeout. It is still open at ${this.data.url}.`
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
const delay = pollDelay(poll++, options.pollIntervals ?? POLL_SCHEDULE);
|
|
185
|
+
const remaining = deadline === undefined ? delay : Math.min(delay, deadline - Date.now());
|
|
186
|
+
await wait(Math.max(0, remaining), options.signal);
|
|
187
|
+
|
|
188
|
+
await this.refresh(options.signal);
|
|
189
|
+
options.onPoll?.(this.data);
|
|
190
|
+
|
|
191
|
+
if (options.onQuestion) {
|
|
192
|
+
for (const question of this.openQuestions) {
|
|
193
|
+
const answer = await options.onQuestion(question, this.data);
|
|
194
|
+
if (typeof answer === "string" && answer.trim()) {
|
|
195
|
+
await this.answer(question.id, answer, options.signal);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
if (!this.pending) return this;
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function wait(ms: number, signal?: AbortSignal): Promise<void> {
|
|
206
|
+
return new Promise((resolve, reject) => {
|
|
207
|
+
if (signal?.aborted) {
|
|
208
|
+
return reject(new DeliverdError(0, "aborted", "The wait was aborted."));
|
|
209
|
+
}
|
|
210
|
+
const timer = setTimeout(() => {
|
|
211
|
+
signal?.removeEventListener("abort", onAbort);
|
|
212
|
+
resolve();
|
|
213
|
+
}, ms);
|
|
214
|
+
const onAbort = () => {
|
|
215
|
+
clearTimeout(timer);
|
|
216
|
+
reject(new DeliverdError(0, "aborted", "The wait was aborted."));
|
|
217
|
+
};
|
|
218
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export class Approvals {
|
|
223
|
+
constructor(private readonly http: HttpClient) {}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Ask. Returns as soon as the request is filed — the approvers are being
|
|
227
|
+
* told while this resolves — so call `wait()` next, or keep the id and poll
|
|
228
|
+
* later.
|
|
229
|
+
*/
|
|
230
|
+
async create(input: CreateApprovalInput, signal?: AbortSignal): Promise<Approval> {
|
|
231
|
+
const data = await this.http.request<ApprovalData>({
|
|
232
|
+
method: "POST",
|
|
233
|
+
path: "/approvals",
|
|
234
|
+
body: input,
|
|
235
|
+
signal,
|
|
236
|
+
});
|
|
237
|
+
return new Approval(this.http, data);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async get(id: string, signal?: AbortSignal): Promise<Approval> {
|
|
241
|
+
const data = await this.http.request<ApprovalData>({
|
|
242
|
+
method: "GET",
|
|
243
|
+
path: `/approvals/${id}`,
|
|
244
|
+
signal,
|
|
245
|
+
});
|
|
246
|
+
return new Approval(this.http, data);
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
async list(input: ListApprovalsInput = {}, signal?: AbortSignal): Promise<Approval[]> {
|
|
250
|
+
const { approvals } = await this.http.request<{ approvals: ApprovalData[] }>({
|
|
251
|
+
method: "GET",
|
|
252
|
+
path: "/approvals",
|
|
253
|
+
query: { status: input.status, externalId: input.externalId, limit: input.limit },
|
|
254
|
+
signal,
|
|
255
|
+
});
|
|
256
|
+
return approvals.map((a) => new Approval(this.http, a));
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Ask and wait, for the common case where there is nothing to do in
|
|
261
|
+
* between. `const { approved } = await deliverd.approvals.request({…})`.
|
|
262
|
+
*/
|
|
263
|
+
async request(
|
|
264
|
+
input: CreateApprovalInput,
|
|
265
|
+
options: WaitOptions = {}
|
|
266
|
+
): Promise<Approval> {
|
|
267
|
+
const approval = await this.create(input, options.signal);
|
|
268
|
+
return approval.wait(options);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* The same request as before, when there was one.
|
|
273
|
+
*
|
|
274
|
+
* Best effort, and worth being exact about what that means: it looks for a
|
|
275
|
+
* request with this `externalId` and returns it rather than filing a second.
|
|
276
|
+
* That makes an agent safe to restart — a crash between "asked" and
|
|
277
|
+
* "recorded that I asked" does not produce two notifications for one
|
|
278
|
+
* decision. Two *concurrent* calls can still both find nothing and both
|
|
279
|
+
* create; real idempotency needs a key the server enforces, and that is
|
|
280
|
+
* server work, not something a client can promise.
|
|
281
|
+
*/
|
|
282
|
+
async findByExternalId(externalId: string, signal?: AbortSignal): Promise<Approval | null> {
|
|
283
|
+
const found = await this.list({ externalId, limit: 1 }, signal);
|
|
284
|
+
return found[0] ?? null;
|
|
285
|
+
}
|
|
286
|
+
}
|