@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
package/dist/dev.d.ts
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { ApprovalData } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Development mode: the whole loop, on your machine, with nobody in it.
|
|
4
|
+
*
|
|
5
|
+
* ```ts
|
|
6
|
+
* const deliverd = new Deliverd({ mode: "development" });
|
|
7
|
+
* const decision = await deliverd.approve({ title: "Deploy production" });
|
|
8
|
+
* ```
|
|
9
|
+
*
|
|
10
|
+
* No key, no network, no colleague to interrupt — and the four things that
|
|
11
|
+
* can happen to a real request all reachable before you have an account:
|
|
12
|
+
* approved, rejected, nobody answered, and somebody asked you a question.
|
|
13
|
+
* That last one is the path people forget to write, which is exactly why it
|
|
14
|
+
* should be one line to try.
|
|
15
|
+
*
|
|
16
|
+
* Implemented as a stand-in `fetch` rather than a branch inside the client,
|
|
17
|
+
* so development mode runs the *same* code as production — the same retries,
|
|
18
|
+
* the same error mapping, the same polling in `wait()`. A simulator that
|
|
19
|
+
* bypassed all that would prove your integration works against the simulator.
|
|
20
|
+
*/
|
|
21
|
+
export type DevelopmentOutcome = "approved" | "rejected" | "timeout" | "question";
|
|
22
|
+
export interface DevelopmentOptions {
|
|
23
|
+
/**
|
|
24
|
+
* What the imaginary approver does. Default `approved`, or the value of
|
|
25
|
+
* `DELIVERD_DEV_OUTCOME`, so a whole test suite can be flipped from the
|
|
26
|
+
* command line without touching the code.
|
|
27
|
+
*/
|
|
28
|
+
outcome?: DevelopmentOutcome | ((request: ApprovalData) => DevelopmentOutcome);
|
|
29
|
+
/** How long they take to do it, in milliseconds. Default 0. */
|
|
30
|
+
delay?: number;
|
|
31
|
+
/** What they say. Defaults suit the outcome. */
|
|
32
|
+
note?: string;
|
|
33
|
+
/** What they ask, when the outcome is `question`. */
|
|
34
|
+
question?: string;
|
|
35
|
+
/** Print what the approver would have seen. Default true. */
|
|
36
|
+
log?: boolean;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* A `fetch` that serves the approvals API from memory.
|
|
40
|
+
*
|
|
41
|
+
* Deliberately narrow: it answers the calls the primitives make and 501s the
|
|
42
|
+
* rest, with a message saying so, rather than pretending to be the whole API
|
|
43
|
+
* and quietly returning something plausible.
|
|
44
|
+
*/
|
|
45
|
+
export declare function developmentFetch(options?: DevelopmentOptions): typeof globalThis.fetch;
|
|
46
|
+
//# sourceMappingURL=dev.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dev.d.ts","sourceRoot":"","sources":["../src/dev.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAE/C;;;;;;;;;;;;;;;;;;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,CAmG1F"}
|
package/dist/dev.js
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
const DEFAULT_QUESTION = "Has this been through staging?";
|
|
2
|
+
let counter = 0;
|
|
3
|
+
/**
|
|
4
|
+
* A `fetch` that serves the approvals API from memory.
|
|
5
|
+
*
|
|
6
|
+
* Deliberately narrow: it answers the calls the primitives make and 501s the
|
|
7
|
+
* rest, with a message saying so, rather than pretending to be the whole API
|
|
8
|
+
* and quietly returning something plausible.
|
|
9
|
+
*/
|
|
10
|
+
export function developmentFetch(options = {}) {
|
|
11
|
+
const store = new Map();
|
|
12
|
+
return (async (input, init) => {
|
|
13
|
+
const url = new URL(String(input));
|
|
14
|
+
const path = url.pathname.replace(/^\/api\/v1/, "");
|
|
15
|
+
const method = (init?.method ?? "GET").toUpperCase();
|
|
16
|
+
const body = init?.body ? JSON.parse(String(init.body)) : {};
|
|
17
|
+
const json = (payload, status = 200) => new Response(JSON.stringify(payload), {
|
|
18
|
+
status,
|
|
19
|
+
headers: { "content-type": "application/json" },
|
|
20
|
+
});
|
|
21
|
+
if (method === "POST" && path === "/approvals") {
|
|
22
|
+
const id = `apr_dev_${++counter}`;
|
|
23
|
+
const outcome = resolveOutcome(options.outcome, body);
|
|
24
|
+
const data = {
|
|
25
|
+
id,
|
|
26
|
+
status: "pending",
|
|
27
|
+
url: `https://deliverd.dev/approve/${id}`,
|
|
28
|
+
title: String(body.title ?? "Untitled"),
|
|
29
|
+
description: body.description ?? null,
|
|
30
|
+
risk: body.risk ?? "medium",
|
|
31
|
+
factors: body.factors ?? [],
|
|
32
|
+
links: body.links ?? [],
|
|
33
|
+
reportId: body.reportId ?? null,
|
|
34
|
+
externalId: body.externalId ?? null,
|
|
35
|
+
metadata: body.metadata ?? {},
|
|
36
|
+
requestedBy: "You (development mode)",
|
|
37
|
+
approvers: body.approvers ?? [],
|
|
38
|
+
decidedBy: null,
|
|
39
|
+
decidedAt: null,
|
|
40
|
+
note: null,
|
|
41
|
+
expiresAt: body.expiresAt ?? null,
|
|
42
|
+
questions: outcome === "question"
|
|
43
|
+
? [
|
|
44
|
+
{
|
|
45
|
+
id: `q_dev_${counter}`,
|
|
46
|
+
question: options.question ?? DEFAULT_QUESTION,
|
|
47
|
+
answer: null,
|
|
48
|
+
askedAt: new Date().toISOString(),
|
|
49
|
+
answeredAt: null,
|
|
50
|
+
},
|
|
51
|
+
]
|
|
52
|
+
: [],
|
|
53
|
+
createdAt: new Date().toISOString(),
|
|
54
|
+
};
|
|
55
|
+
store.set(id, {
|
|
56
|
+
data,
|
|
57
|
+
decideAt: Date.now() + (options.delay ?? 0),
|
|
58
|
+
outcome,
|
|
59
|
+
options,
|
|
60
|
+
});
|
|
61
|
+
if (options.log !== false)
|
|
62
|
+
announce(data, outcome);
|
|
63
|
+
return json(data, 201);
|
|
64
|
+
}
|
|
65
|
+
const match = /^\/approvals\/([^/]+)(\/answers|\/cancel)?$/.exec(path);
|
|
66
|
+
if (match) {
|
|
67
|
+
const stored = store.get(match[1]);
|
|
68
|
+
if (!stored) {
|
|
69
|
+
return json({ error: { code: "not_found", message: "No such approval in this development session." } }, 404);
|
|
70
|
+
}
|
|
71
|
+
if (match[2] === "/answers") {
|
|
72
|
+
const question = stored.data.questions.find((q) => q.id === body.questionId);
|
|
73
|
+
if (!question) {
|
|
74
|
+
return json({ error: { code: "question_not_found", message: "No such question." } }, 404);
|
|
75
|
+
}
|
|
76
|
+
question.answer = String(body.answer);
|
|
77
|
+
question.answeredAt = new Date().toISOString();
|
|
78
|
+
// Answered: the imaginary approver is satisfied and approves.
|
|
79
|
+
stored.outcome = "approved";
|
|
80
|
+
stored.decideAt = Date.now() + (stored.options.delay ?? 0);
|
|
81
|
+
if (stored.options.log !== false) {
|
|
82
|
+
console.log(` ↳ answered: ${question.answer}\n`);
|
|
83
|
+
}
|
|
84
|
+
return json(stored.data);
|
|
85
|
+
}
|
|
86
|
+
if (match[2] === "/cancel") {
|
|
87
|
+
stored.data.status = "cancelled";
|
|
88
|
+
return json(stored.data);
|
|
89
|
+
}
|
|
90
|
+
settle(stored);
|
|
91
|
+
return json(stored.data);
|
|
92
|
+
}
|
|
93
|
+
return json({
|
|
94
|
+
error: {
|
|
95
|
+
code: "not_in_development_mode",
|
|
96
|
+
message: `Development mode simulates approvals only, and something called ${method} ${path}. Use a real API key for the rest of the API.`,
|
|
97
|
+
},
|
|
98
|
+
}, 501);
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
function resolveOutcome(outcome, body) {
|
|
102
|
+
const fromEnv = process.env.DELIVERD_DEV_OUTCOME;
|
|
103
|
+
const chosen = outcome ?? fromEnv ?? "approved";
|
|
104
|
+
return typeof chosen === "function" ? chosen(body) : chosen;
|
|
105
|
+
}
|
|
106
|
+
/** Move a pending request to its outcome once the imaginary approver has had time. */
|
|
107
|
+
function settle(stored) {
|
|
108
|
+
if (stored.data.status !== "pending")
|
|
109
|
+
return;
|
|
110
|
+
if (Date.now() < stored.decideAt)
|
|
111
|
+
return;
|
|
112
|
+
if (stored.outcome === "timeout")
|
|
113
|
+
return;
|
|
114
|
+
if (stored.outcome === "question" && stored.data.questions.some((q) => !q.answer))
|
|
115
|
+
return;
|
|
116
|
+
stored.data.status = stored.outcome === "rejected" ? "rejected" : "approved";
|
|
117
|
+
stored.data.decidedBy = "approver@development.invalid";
|
|
118
|
+
stored.data.decidedAt = new Date().toISOString();
|
|
119
|
+
stored.data.note =
|
|
120
|
+
stored.options.note ??
|
|
121
|
+
(stored.data.status === "rejected" ? "Not yet — development mode says no." : null);
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* What the approver would have seen, in the terminal.
|
|
125
|
+
*
|
|
126
|
+
* The reason this is worth the lines: the title and the factors are copy
|
|
127
|
+
* somebody has to read on a phone at nine at night, and the only way to know
|
|
128
|
+
* whether it reads well is to see it written out.
|
|
129
|
+
*/
|
|
130
|
+
function announce(data, outcome) {
|
|
131
|
+
const lines = [
|
|
132
|
+
"",
|
|
133
|
+
" ┌─ Deliverd · development mode ─────────────────────────",
|
|
134
|
+
` │ ${data.title}`,
|
|
135
|
+
];
|
|
136
|
+
if (data.description)
|
|
137
|
+
lines.push(` │ ${data.description}`);
|
|
138
|
+
lines.push(` │ Risk: ${data.risk}`);
|
|
139
|
+
for (const factor of data.factors) {
|
|
140
|
+
const mark = factor.status === "ok" ? "✓" : factor.status === "warning" ? "⚠" : "·";
|
|
141
|
+
lines.push(` │ ${mark} ${factor.label}`);
|
|
142
|
+
}
|
|
143
|
+
if (data.approvers.length > 0)
|
|
144
|
+
lines.push(` │ To: ${data.approvers.join(", ")}`);
|
|
145
|
+
lines.push(" │", ` │ Simulating: ${outcome}${outcome === "question" ? " (needs an onQuestion handler)" : ""}`, " └───────────────────────────────────────────────────────", "");
|
|
146
|
+
console.log(lines.join("\n"));
|
|
147
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `expiresIn: "4h"` rather than an ISO timestamp the caller has to compute.
|
|
3
|
+
*
|
|
4
|
+
* Milliseconds are accepted too, because a number is what a timer takes and
|
|
5
|
+
* making somebody write `"3600000ms"` would be the kind of ceremony this SDK
|
|
6
|
+
* exists to remove.
|
|
7
|
+
*/
|
|
8
|
+
export type Duration = number | `${number}${"s" | "m" | "h" | "d"}`;
|
|
9
|
+
export declare function durationMs(value: Duration): number;
|
|
10
|
+
//# sourceMappingURL=duration.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"duration.d.ts","sourceRoot":"","sources":["../src/duration.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG,GAAG,MAAM,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,EAAE,CAAC;AAIpE,wBAAgB,UAAU,CAAC,KAAK,EAAE,QAAQ,GAAG,MAAM,CASlD"}
|
package/dist/duration.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
const UNITS = { s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 };
|
|
2
|
+
export function durationMs(value) {
|
|
3
|
+
if (typeof value === "number")
|
|
4
|
+
return value;
|
|
5
|
+
const match = /^(\d+(?:\.\d+)?)([smhd])$/.exec(value.trim());
|
|
6
|
+
if (!match) {
|
|
7
|
+
throw new TypeError(`Could not read "${value}" as a duration. Use a number of milliseconds, or a string like "30m", "4h" or "2d".`);
|
|
8
|
+
}
|
|
9
|
+
return Number(match[1]) * UNITS[match[2]];
|
|
10
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every failure the SDK raises, with the API's own code on it.
|
|
3
|
+
*
|
|
4
|
+
* One class rather than a hierarchy: callers branch on `code`, which is the
|
|
5
|
+
* string the API document lists, and a `instanceof` tree would make that the
|
|
6
|
+
* second way to ask the same question. The helpers below name the handful of
|
|
7
|
+
* cases worth branching on so nobody has to memorise the codes.
|
|
8
|
+
*/
|
|
9
|
+
export declare class DeliverdError extends Error {
|
|
10
|
+
/** HTTP status, or 0 when the request never got a response. */
|
|
11
|
+
readonly status: number;
|
|
12
|
+
/** The API's error code: `not_found`, `rate_limited`, `self_approval`… */
|
|
13
|
+
readonly code: string;
|
|
14
|
+
/** Whatever the API attached — validation issues, the unknown approvers. */
|
|
15
|
+
readonly details?: unknown | undefined;
|
|
16
|
+
/** The one thing to do next, when we know it. Also the tail of `message`. */
|
|
17
|
+
readonly hint?: string;
|
|
18
|
+
constructor(
|
|
19
|
+
/** HTTP status, or 0 when the request never got a response. */
|
|
20
|
+
status: number,
|
|
21
|
+
/** The API's error code: `not_found`, `rate_limited`, `self_approval`… */
|
|
22
|
+
code: string, message: string,
|
|
23
|
+
/** Whatever the API attached — validation issues, the unknown approvers. */
|
|
24
|
+
details?: unknown | undefined, options?: {
|
|
25
|
+
cause?: unknown;
|
|
26
|
+
});
|
|
27
|
+
/** The key is missing, wrong, or lacks the scope the call needs. */
|
|
28
|
+
get isAuth(): boolean;
|
|
29
|
+
/** Slow down; the client already retried and gave up. */
|
|
30
|
+
get isRateLimit(): boolean;
|
|
31
|
+
/** Nothing there, or nothing this key may see. */
|
|
32
|
+
get isNotFound(): boolean;
|
|
33
|
+
/**
|
|
34
|
+
* The request was fine and the state was not: someone published between
|
|
35
|
+
* your read and your write, a version is awaiting approval, a question was
|
|
36
|
+
* already answered. Re-read and try again.
|
|
37
|
+
*/
|
|
38
|
+
get isConflict(): boolean;
|
|
39
|
+
}
|
|
40
|
+
/** Thrown when a wait is abandoned rather than answered. */
|
|
41
|
+
export declare class DeliverdTimeoutError extends DeliverdError {
|
|
42
|
+
constructor(message: string);
|
|
43
|
+
}
|
|
44
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAEA;;;;;;;GAOG;AACH,qBAAa,aAAc,SAAQ,KAAK;IAKpC,+DAA+D;aAC/C,MAAM,EAAE,MAAM;IAC9B,0EAA0E;aAC1D,IAAI,EAAE,MAAM;IAE5B,4EAA4E;aAC5D,OAAO,CAAC,EAAE,OAAO;IAVnC,6EAA6E;IAC7E,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC;;IAGrB,+DAA+D;IAC/C,MAAM,EAAE,MAAM;IAC9B,0EAA0E;IAC1D,IAAI,EAAE,MAAM,EAC5B,OAAO,EAAE,MAAM;IACf,4EAA4E;IAC5D,OAAO,CAAC,EAAE,OAAO,YAAA,EACjC,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,OAAO,CAAA;KAAE;IAQ/B,oEAAoE;IACpE,IAAI,MAAM,IAAI,OAAO,CAEpB;IAED,yDAAyD;IACzD,IAAI,WAAW,IAAI,OAAO,CAEzB;IAED,kDAAkD;IAClD,IAAI,UAAU,IAAI,OAAO,CAExB;IAED;;;;OAIG;IACH,IAAI,UAAU,IAAI,OAAO,CAExB;CACF;AAED,4DAA4D;AAC5D,qBAAa,oBAAqB,SAAQ,aAAa;gBACzC,OAAO,EAAE,MAAM;CAI5B"}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { explain } from "./messages.js";
|
|
2
|
+
/**
|
|
3
|
+
* Every failure the SDK raises, with the API's own code on it.
|
|
4
|
+
*
|
|
5
|
+
* One class rather than a hierarchy: callers branch on `code`, which is the
|
|
6
|
+
* string the API document lists, and a `instanceof` tree would make that the
|
|
7
|
+
* second way to ask the same question. The helpers below name the handful of
|
|
8
|
+
* cases worth branching on so nobody has to memorise the codes.
|
|
9
|
+
*/
|
|
10
|
+
export class DeliverdError extends Error {
|
|
11
|
+
status;
|
|
12
|
+
code;
|
|
13
|
+
details;
|
|
14
|
+
/** The one thing to do next, when we know it. Also the tail of `message`. */
|
|
15
|
+
hint;
|
|
16
|
+
constructor(
|
|
17
|
+
/** HTTP status, or 0 when the request never got a response. */
|
|
18
|
+
status,
|
|
19
|
+
/** The API's error code: `not_found`, `rate_limited`, `self_approval`… */
|
|
20
|
+
code, message,
|
|
21
|
+
/** Whatever the API attached — validation issues, the unknown approvers. */
|
|
22
|
+
details, options) {
|
|
23
|
+
const explained = explain(code, message);
|
|
24
|
+
super(explained.message, options);
|
|
25
|
+
this.status = status;
|
|
26
|
+
this.code = code;
|
|
27
|
+
this.details = details;
|
|
28
|
+
this.name = "DeliverdError";
|
|
29
|
+
this.hint = explained.hint;
|
|
30
|
+
}
|
|
31
|
+
/** The key is missing, wrong, or lacks the scope the call needs. */
|
|
32
|
+
get isAuth() {
|
|
33
|
+
return this.status === 401 || this.status === 403;
|
|
34
|
+
}
|
|
35
|
+
/** Slow down; the client already retried and gave up. */
|
|
36
|
+
get isRateLimit() {
|
|
37
|
+
return this.status === 429;
|
|
38
|
+
}
|
|
39
|
+
/** Nothing there, or nothing this key may see. */
|
|
40
|
+
get isNotFound() {
|
|
41
|
+
return this.status === 404;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The request was fine and the state was not: someone published between
|
|
45
|
+
* your read and your write, a version is awaiting approval, a question was
|
|
46
|
+
* already answered. Re-read and try again.
|
|
47
|
+
*/
|
|
48
|
+
get isConflict() {
|
|
49
|
+
return this.status === 409;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
/** Thrown when a wait is abandoned rather than answered. */
|
|
53
|
+
export class DeliverdTimeoutError extends DeliverdError {
|
|
54
|
+
constructor(message) {
|
|
55
|
+
super(0, "timeout", message);
|
|
56
|
+
this.name = "DeliverdTimeoutError";
|
|
57
|
+
}
|
|
58
|
+
}
|
package/dist/http.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one place a request is made.
|
|
3
|
+
*
|
|
4
|
+
* No dependencies: Node 20 has `fetch`, and an SDK that drags a request
|
|
5
|
+
* library into every agent runtime for the sake of four verbs is a tax on
|
|
6
|
+
* everyone who installs it.
|
|
7
|
+
*
|
|
8
|
+
* Retries are deliberately narrow. A 429 or a 5xx or a dropped connection is
|
|
9
|
+
* worth repeating; a 4xx is the API saying the request itself is wrong, and it
|
|
10
|
+
* will be just as wrong in a second. `Retry-After` is honoured when the server
|
|
11
|
+
* sends one, because guessing against a server that has told you the answer is
|
|
12
|
+
* how a client turns a rate limit into an outage.
|
|
13
|
+
*/
|
|
14
|
+
export interface ClientOptions {
|
|
15
|
+
/** A `dlv_` key from Settings → API tokens, or an OAuth access token. */
|
|
16
|
+
apiKey: string;
|
|
17
|
+
/** Override for self-hosted or preview deployments. */
|
|
18
|
+
baseUrl?: string;
|
|
19
|
+
/** Attempts for a retryable failure, the first included. Default 3. */
|
|
20
|
+
maxRetries?: number;
|
|
21
|
+
/** Per-request timeout in milliseconds. Default 30000. */
|
|
22
|
+
timeout?: number;
|
|
23
|
+
/** Swapped in tests; defaults to the global. */
|
|
24
|
+
fetch?: typeof globalThis.fetch;
|
|
25
|
+
}
|
|
26
|
+
export declare const DEFAULT_BASE_URL = "https://deliverd.dev";
|
|
27
|
+
interface RequestOptions {
|
|
28
|
+
method: string;
|
|
29
|
+
path: string;
|
|
30
|
+
body?: unknown;
|
|
31
|
+
query?: Record<string, string | number | undefined>;
|
|
32
|
+
signal?: AbortSignal;
|
|
33
|
+
}
|
|
34
|
+
export declare class HttpClient {
|
|
35
|
+
readonly baseUrl: string;
|
|
36
|
+
private readonly apiKey;
|
|
37
|
+
private readonly maxRetries;
|
|
38
|
+
private readonly timeout;
|
|
39
|
+
private readonly doFetch;
|
|
40
|
+
constructor(options: ClientOptions);
|
|
41
|
+
request<T>(options: RequestOptions): Promise<T>;
|
|
42
|
+
}
|
|
43
|
+
export declare const USER_AGENT = "deliverd-sdk";
|
|
44
|
+
export {};
|
|
45
|
+
//# sourceMappingURL=http.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;GAYG;AAEH,MAAM,WAAW,aAAa;IAC5B,yEAAyE;IACzE,MAAM,EAAE,MAAM,CAAC;IACf,uDAAuD;IACvD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,uEAAuE;IACvE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,0DAA0D;IAC1D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,gDAAgD;IAChD,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;CACjC;AAED,eAAO,MAAM,gBAAgB,yBAAyB,CAAC;AAEvD,UAAU,cAAc;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC,CAAC;IACpD,MAAM,CAAC,EAAE,WAAW,CAAC;CACtB;AA4BD,qBAAa,UAAU;IACrB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAS;IAChC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACpC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAS;IACjC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA0B;gBAEtC,OAAO,EAAE,aAAa;IAW5B,OAAO,CAAC,CAAC,EAAE,OAAO,EAAE,cAAc,GAAG,OAAO,CAAC,CAAC,CAAC;CAsEtD;AAED,eAAO,MAAM,UAAU,iBAAiB,CAAC"}
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { DeliverdError } from "./errors.js";
|
|
3
|
+
export const DEFAULT_BASE_URL = "https://deliverd.dev";
|
|
4
|
+
const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
5
|
+
if (signal?.aborted)
|
|
6
|
+
return reject(abortError(signal));
|
|
7
|
+
const timer = setTimeout(() => {
|
|
8
|
+
signal?.removeEventListener("abort", onAbort);
|
|
9
|
+
resolve();
|
|
10
|
+
}, ms);
|
|
11
|
+
const onAbort = () => {
|
|
12
|
+
clearTimeout(timer);
|
|
13
|
+
reject(abortError(signal));
|
|
14
|
+
};
|
|
15
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
16
|
+
});
|
|
17
|
+
function abortError(signal) {
|
|
18
|
+
return new DeliverdError(0, "aborted", "The request was aborted.", undefined, {
|
|
19
|
+
cause: signal.reason,
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
/** Exponential from 500ms with jitter, so a fleet of agents does not resonate. */
|
|
23
|
+
function backoffMs(attempt) {
|
|
24
|
+
const base = Math.min(8000, 500 * 2 ** (attempt - 1));
|
|
25
|
+
return base / 2 + Math.random() * (base / 2);
|
|
26
|
+
}
|
|
27
|
+
export class HttpClient {
|
|
28
|
+
baseUrl;
|
|
29
|
+
apiKey;
|
|
30
|
+
maxRetries;
|
|
31
|
+
timeout;
|
|
32
|
+
doFetch;
|
|
33
|
+
constructor(options) {
|
|
34
|
+
if (!options.apiKey) {
|
|
35
|
+
throw new DeliverdError(0, "no_api_key", "An apiKey is required.");
|
|
36
|
+
}
|
|
37
|
+
this.apiKey = options.apiKey;
|
|
38
|
+
this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
39
|
+
this.maxRetries = Math.max(1, options.maxRetries ?? 3);
|
|
40
|
+
this.timeout = options.timeout ?? 30_000;
|
|
41
|
+
this.doFetch = options.fetch ?? globalThis.fetch;
|
|
42
|
+
}
|
|
43
|
+
async request(options) {
|
|
44
|
+
const url = new URL(`${this.baseUrl}/api/v1${options.path}`);
|
|
45
|
+
for (const [key, value] of Object.entries(options.query ?? {})) {
|
|
46
|
+
if (value !== undefined)
|
|
47
|
+
url.searchParams.set(key, String(value));
|
|
48
|
+
}
|
|
49
|
+
const correlationId = randomUUID();
|
|
50
|
+
let lastError;
|
|
51
|
+
for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
|
|
52
|
+
if (attempt > 1)
|
|
53
|
+
await sleep(lastError ? retryDelay(lastError, attempt) : backoffMs(attempt), options.signal);
|
|
54
|
+
// The caller's signal and our own timeout, whichever fires first.
|
|
55
|
+
const timer = AbortSignal.timeout(this.timeout);
|
|
56
|
+
const signal = options.signal ? AbortSignal.any([options.signal, timer]) : timer;
|
|
57
|
+
let response;
|
|
58
|
+
try {
|
|
59
|
+
response = await this.doFetch(url, {
|
|
60
|
+
method: options.method,
|
|
61
|
+
headers: {
|
|
62
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
63
|
+
Accept: "application/json",
|
|
64
|
+
"User-Agent": USER_AGENT,
|
|
65
|
+
// One id per logical request, kept across retries: it is the
|
|
66
|
+
// thing to quote when something went wrong, and generating it
|
|
67
|
+
// here means nobody has to remember to.
|
|
68
|
+
"deliverd-correlation-id": correlationId,
|
|
69
|
+
...(options.body !== undefined ? { "Content-Type": "application/json" } : {}),
|
|
70
|
+
},
|
|
71
|
+
body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
|
|
72
|
+
signal,
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
catch (cause) {
|
|
76
|
+
if (options.signal?.aborted)
|
|
77
|
+
throw abortError(options.signal);
|
|
78
|
+
lastError = new DeliverdError(0, "network_error", describeNetworkError(cause), undefined, { cause });
|
|
79
|
+
if (attempt === this.maxRetries)
|
|
80
|
+
throw lastError;
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
if (response.status === 204)
|
|
84
|
+
return undefined;
|
|
85
|
+
const text = await response.text();
|
|
86
|
+
let json;
|
|
87
|
+
try {
|
|
88
|
+
json = text ? JSON.parse(text) : {};
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
lastError = new DeliverdError(response.status, "invalid_response", `Expected JSON from ${url.pathname} and got ${text.slice(0, 120)}`);
|
|
92
|
+
if (isRetryable(response.status) && attempt < this.maxRetries)
|
|
93
|
+
continue;
|
|
94
|
+
throw lastError;
|
|
95
|
+
}
|
|
96
|
+
if (response.ok)
|
|
97
|
+
return json;
|
|
98
|
+
const envelope = json.error;
|
|
99
|
+
lastError = new DeliverdError(response.status, envelope?.code ?? "error", envelope?.message ?? `Request failed (${response.status})`, envelope?.details);
|
|
100
|
+
lastError.retryAfter = parseRetryAfter(response.headers.get("retry-after"));
|
|
101
|
+
if (isRetryable(response.status) && attempt < this.maxRetries)
|
|
102
|
+
continue;
|
|
103
|
+
throw lastError;
|
|
104
|
+
}
|
|
105
|
+
throw lastError ?? new DeliverdError(0, "error", "Request failed.");
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
export const USER_AGENT = "deliverd-sdk";
|
|
109
|
+
/** 429 and 5xx only: a 4xx will be just as wrong on the next attempt. */
|
|
110
|
+
function isRetryable(status) {
|
|
111
|
+
return status === 429 || status >= 500;
|
|
112
|
+
}
|
|
113
|
+
function parseRetryAfter(header) {
|
|
114
|
+
if (!header)
|
|
115
|
+
return undefined;
|
|
116
|
+
const seconds = Number(header);
|
|
117
|
+
if (Number.isFinite(seconds))
|
|
118
|
+
return seconds * 1000;
|
|
119
|
+
const date = Date.parse(header);
|
|
120
|
+
return Number.isFinite(date) ? Math.max(0, date - Date.now()) : undefined;
|
|
121
|
+
}
|
|
122
|
+
function retryDelay(error, attempt) {
|
|
123
|
+
const after = error.retryAfter;
|
|
124
|
+
return after !== undefined ? after : backoffMs(attempt);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* A dropped connection says nothing useful on its own, and the first thing
|
|
128
|
+
* anyone wonders is whether they typed the host wrong.
|
|
129
|
+
*/
|
|
130
|
+
function describeNetworkError(cause) {
|
|
131
|
+
const message = cause instanceof Error ? cause.message : String(cause);
|
|
132
|
+
if (/timed? ?out|TimeoutError/i.test(message))
|
|
133
|
+
return `The request timed out: ${message}`;
|
|
134
|
+
return `Could not reach Deliverd: ${message}`;
|
|
135
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { HttpClient, type ClientOptions } from "./http.js";
|
|
2
|
+
import { Approvals, type WaitOptions } from "./approvals.js";
|
|
3
|
+
import { Comments, Reports } from "./reports.js";
|
|
4
|
+
import { Webhooks } from "./webhooks.js";
|
|
5
|
+
import { type DevelopmentOptions } from "./dev.js";
|
|
6
|
+
import { type Duration } from "./duration.js";
|
|
7
|
+
import type { CreateApprovalInput, Decision, PublishReportInput, PublishResult } from "./types.js";
|
|
8
|
+
export { Approval, Approvals, POLL_SCHEDULE, type WaitOptions } from "./approvals.js";
|
|
9
|
+
export { Comments, Reports } from "./reports.js";
|
|
10
|
+
export { constructEvent, DELIVERY_HEADER, EVENT_HEADER, SIGNATURE_HEADER, TOLERANCE_SECONDS, verifySignature, Webhooks, } from "./webhooks.js";
|
|
11
|
+
export { DeliverdError, DeliverdTimeoutError } from "./errors.js";
|
|
12
|
+
export { DEFAULT_BASE_URL, type ClientOptions } from "./http.js";
|
|
13
|
+
export { durationMs, type Duration } from "./duration.js";
|
|
14
|
+
export type { DevelopmentOptions, DevelopmentOutcome } from "./dev.js";
|
|
15
|
+
export type * from "./types.js";
|
|
16
|
+
/** How long a request waits for a person before it expires, unless you say. */
|
|
17
|
+
export declare const DEFAULT_EXPIRY: Duration;
|
|
18
|
+
export interface DeliverdOptions extends Partial<ClientOptions> {
|
|
19
|
+
/**
|
|
20
|
+
* `development` runs the whole loop on this machine: no key, no network,
|
|
21
|
+
* nobody interrupted. Defaults to `development` when `DELIVERD_MODE` says
|
|
22
|
+
* so, and to `live` otherwise.
|
|
23
|
+
*/
|
|
24
|
+
mode?: "live" | "development";
|
|
25
|
+
development?: DevelopmentOptions;
|
|
26
|
+
}
|
|
27
|
+
/** Everything `approve()` takes, plus the conveniences it adds on top. */
|
|
28
|
+
export interface ApproveOptions extends Omit<CreateApprovalInput, "expiresAt"> {
|
|
29
|
+
/** `"4h"`, `"30m"`, `"2d"`, or milliseconds. Default 24 hours. */
|
|
30
|
+
expiresIn?: Duration;
|
|
31
|
+
/** An exact moment instead, if you have one. */
|
|
32
|
+
expiresAt?: string;
|
|
33
|
+
/**
|
|
34
|
+
* Answer a question the approver asks, without leaving the wait. Return a
|
|
35
|
+
* string and it is posted; return null to leave it for a person.
|
|
36
|
+
*/
|
|
37
|
+
onQuestion?: WaitOptions["onQuestion"];
|
|
38
|
+
/** Called after each poll — a progress line in a CLI. */
|
|
39
|
+
onPoll?: WaitOptions["onPoll"];
|
|
40
|
+
/** Give up waiting after this. The request stays open until it expires. */
|
|
41
|
+
timeout?: Duration;
|
|
42
|
+
signal?: AbortSignal;
|
|
43
|
+
/**
|
|
44
|
+
* With an `externalId`, reuse an existing request rather than filing a
|
|
45
|
+
* second one. On by default, so restarting a crashed agent does not ask
|
|
46
|
+
* twice. See `approvals.findByExternalId` for exactly how far that goes.
|
|
47
|
+
*/
|
|
48
|
+
reuse?: boolean;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Deliverd: you build the action, Deliverd handles the human.
|
|
52
|
+
*
|
|
53
|
+
* ```ts
|
|
54
|
+
* import { deliverd } from "@deliverd/sdk";
|
|
55
|
+
*
|
|
56
|
+
* const decision = await deliverd.approve({ title: "Deploy to production" });
|
|
57
|
+
* if (decision.approved) await deploy();
|
|
58
|
+
* ```
|
|
59
|
+
*
|
|
60
|
+
* That is the whole integration. What it stands in for: an approval page, the
|
|
61
|
+
* emails and the reminders, identity and single sign-on, who is allowed to
|
|
62
|
+
* decide, a table to keep it in, an audit trail, and the dashboard somebody
|
|
63
|
+
* uses to do it. None of that is yours to build.
|
|
64
|
+
*
|
|
65
|
+
* With no arguments the key comes from `DELIVERD_API_KEY`. Before you have
|
|
66
|
+
* one, `new Deliverd({ mode: "development" })` runs the same code with an
|
|
67
|
+
* imaginary approver.
|
|
68
|
+
*/
|
|
69
|
+
export declare class Deliverd {
|
|
70
|
+
readonly approvals: Approvals;
|
|
71
|
+
readonly reports: Reports;
|
|
72
|
+
readonly comments: Comments;
|
|
73
|
+
readonly webhooks: Webhooks;
|
|
74
|
+
readonly http: HttpClient;
|
|
75
|
+
/** Whether an imaginary approver is deciding these. */
|
|
76
|
+
readonly development: boolean;
|
|
77
|
+
constructor(options?: DeliverdOptions);
|
|
78
|
+
/**
|
|
79
|
+
* Ask a person, and wait for the answer.
|
|
80
|
+
*
|
|
81
|
+
* Resolves when they decide — including when they say no, because a refusal
|
|
82
|
+
* is an answer and `if (decision.approved)` is the line that follows. It
|
|
83
|
+
* throws only when the wait itself failed: a timeout, an abort, or an API
|
|
84
|
+
* that could not be reached.
|
|
85
|
+
*
|
|
86
|
+
* Requests expire after a day unless you say otherwise, so a wait always
|
|
87
|
+
* ends.
|
|
88
|
+
*/
|
|
89
|
+
approve(options: ApproveOptions): Promise<Decision>;
|
|
90
|
+
/**
|
|
91
|
+
* A yes or no on something small: same mechanism, lower ceremony.
|
|
92
|
+
*
|
|
93
|
+
* Low risk and an hour to answer, because that is what "are you sure?"
|
|
94
|
+
* means — if it deserves a day and a paragraph of evidence, it deserves
|
|
95
|
+
* `approve()`.
|
|
96
|
+
*/
|
|
97
|
+
confirm(options: ApproveOptions): Promise<boolean>;
|
|
98
|
+
/** Publish HTML to a secure URL. The other half of the product, one call in. */
|
|
99
|
+
publish(input: PublishReportInput, signal?: AbortSignal): Promise<PublishResult>;
|
|
100
|
+
}
|
|
101
|
+
export declare const deliverd: Deliverd;
|
|
102
|
+
export default Deliverd;
|
|
103
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"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"}
|