@bernierllc/nevarmail 0.19.1 → 0.20.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 +53 -3
- package/dist/index.d.ts +116 -12
- package/dist/index.js +263 -120
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -95,7 +95,7 @@ try {
|
|
|
95
95
|
| `status` | HTTP status; `0` when the request never reached the API |
|
|
96
96
|
| `code` | Machine-readable code — branch on this, never on `message` |
|
|
97
97
|
| `requestId` | Quote it in support; it matches the API's `x-request-id` |
|
|
98
|
-
| `retryAfter` | Seconds, from `Retry-After` on a 429 |
|
|
98
|
+
| `retryAfter` | Seconds, from `Retry-After` on a 429. Waits of 30s or less are retried for you; a longer one (a daily cap) throws at once |
|
|
99
99
|
| `body` | The parsed response, for codes newer than your installed version |
|
|
100
100
|
|
|
101
101
|
Codes worth handling explicitly:
|
|
@@ -103,7 +103,7 @@ Codes worth handling explicitly:
|
|
|
103
103
|
| Code | Status | What it means |
|
|
104
104
|
|---|---|---|
|
|
105
105
|
| `RECIPIENT_SUPPRESSED` | 422 | Bounced, complained, or unsubscribed. Do not retry. |
|
|
106
|
-
| `
|
|
106
|
+
| `COMPLIANCE_ADDRESS_REQUIRED` | 422 | `emailType: "marketing"` (or a use case recipients can opt out of) from a project with no postal address. Set it with `setProjectAddress`. |
|
|
107
107
|
| `TEST_MODE_RECIPIENT_NOT_ALLOWED` | 422 | Test key, recipient not on the allow-list. |
|
|
108
108
|
| `CC_BCC_NOT_SUPPORTED_FOR_TEMPLATE` | 400 | Templated mail renders per recipient; send one request each. |
|
|
109
109
|
| `VALIDATION_ERROR` | 400 | The body is wrong. Retrying will not help. |
|
|
@@ -175,7 +175,6 @@ the two, not both). The slug must exist in exactly one project the key can open:
|
|
|
175
175
|
| `getDomainDnsRecords` / `verifyDomain` | `/api/v1/domains/{id}/…` | `domains:read` / `domains:write` |
|
|
176
176
|
| `listSuppressions` / `addSuppressions` | `/api/v1/suppressions` | `org:read` / `org:write` |
|
|
177
177
|
| `getProjectAddress(projectId)` / `setProjectAddress(projectId, { physicalAddress, addressComponents? })` | `GET` / `PUT /api/v1/projects/{id}/address` | `org:read` / `org:write` |
|
|
178
|
-
| `getProjectMarketing(projectId)` / `setProjectMarketing(projectId, { marketingEnabled })` | `GET` / `PUT /api/v1/projects/{id}/marketing` | `org:read` / `org:write` |
|
|
179
178
|
| `getInboxDbStatus` | `GET /api/v1/inbox-db/status` | `org:read` |
|
|
180
179
|
| `connectInboxDb({ connectionString, provider? })` (202, starts a background connect) / `testInboxDbConnection` | `POST /api/v1/inbox-db/connection` / `…/connection/test` | `org:write` |
|
|
181
180
|
| `getInboxDbConnectAttempt` (poll until `status` is not `running`) | `GET /api/v1/inbox-db/connection` | `org:read` |
|
|
@@ -233,6 +232,57 @@ typed it, so the API rejects it rather than guessing. Convert on your side, wher
|
|
|
233
232
|
actually known. Templated scheduled sends are refused: the processor does not render
|
|
234
233
|
templates, so accepting one would queue an empty body.
|
|
235
234
|
|
|
235
|
+
## Agent inboxes — `NevarMailInbox`
|
|
236
|
+
|
|
237
|
+
An agent inbox has its own API (`/api/v1/inbox/*`) and its own credential: a client id
|
|
238
|
+
(`nvm_inbox_…`) and secret from the inbox's Agents tab. API keys are refused there, and an
|
|
239
|
+
inbox credential reaches nothing outside its own inbox, so it is a separate client:
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
import { NevarMailInbox } from "@bernierllc/nevarmail";
|
|
243
|
+
|
|
244
|
+
const inbox = new NevarMailInbox({
|
|
245
|
+
clientId: process.env.NEVARMAIL_INBOX_CLIENT_ID!,
|
|
246
|
+
clientSecret: process.env.NEVARMAIL_INBOX_CLIENT_SECRET!,
|
|
247
|
+
// scopes: ["inbox:read"], // narrow the token; defaults to inbox:read + inbox:send
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
const { data } = await inbox.listEmails({ perPage: 10 });
|
|
251
|
+
for (const summary of data.filter((e) => !e.isRead)) {
|
|
252
|
+
const email = await inbox.getEmail(summary.id);
|
|
253
|
+
await inbox.send({
|
|
254
|
+
to: email.from,
|
|
255
|
+
subject: `Re: ${email.subject ?? ""}`,
|
|
256
|
+
text: "Got it.",
|
|
257
|
+
reply_to_email_id: email.id,
|
|
258
|
+
});
|
|
259
|
+
await inbox.markEmailRead(email.id);
|
|
260
|
+
}
|
|
261
|
+
```
|
|
262
|
+
|
|
263
|
+
| Method | Route | Scope |
|
|
264
|
+
|--------|-------|-------|
|
|
265
|
+
| `listEmails({ page, perPage, threadId })` | `GET /api/v1/inbox/emails` | `inbox:read` |
|
|
266
|
+
| `getEmail(id)` | `GET /api/v1/inbox/emails/{id}` | `inbox:read` |
|
|
267
|
+
| `markEmailRead(id)` | `POST /api/v1/inbox/emails/{id}/read` | `inbox:read` |
|
|
268
|
+
| `deleteEmail(id)` | `DELETE /api/v1/inbox/emails/{id}` | `inbox:read` |
|
|
269
|
+
| `send(input)` | `POST /api/v1/inbox/send` | `inbox:send` |
|
|
270
|
+
| `rotateCredentials()` | `POST /api/v1/inbox/credentials/rotate` | `inbox:read` |
|
|
271
|
+
|
|
272
|
+
- **Tokens are handled for you.** The client exchanges the credential for a short-lived
|
|
273
|
+
token (OAuth `client_credentials` at `/api/oauth/token`) on first use, renews it a minute
|
|
274
|
+
before expiry, and on a `401` gets one fresh token and retries once. A rejected credential
|
|
275
|
+
throws `code: "INVALID_CLIENT"`.
|
|
276
|
+
- **`send` is deliberately narrow.** From is always the inbox's address; at most 5
|
|
277
|
+
recipients across `to` and `cc`; no templates or lists. Hitting the daily limit is a
|
|
278
|
+
`429 inbox_daily_limit_reached` that throws at once, with `retryAfter` set to the
|
|
279
|
+
seconds until UTC midnight.
|
|
280
|
+
- **`rotateCredentials()` returns the new secret once** and switches the client to it.
|
|
281
|
+
Store it. The old secret stops working.
|
|
282
|
+
|
|
283
|
+
Same options (`baseUrl`, `timeoutMs`, `maxRetries`, `fetch`) and the same error contract as
|
|
284
|
+
`NevarMail`.
|
|
285
|
+
|
|
236
286
|
## Options
|
|
237
287
|
|
|
238
288
|
```ts
|
package/dist/index.d.ts
CHANGED
|
@@ -618,10 +618,6 @@ export interface SetProjectAddressInput {
|
|
|
618
618
|
/** Omitted or null clears any stored parts. Max 30. */
|
|
619
619
|
addressComponents?: AddressComponent[] | null;
|
|
620
620
|
}
|
|
621
|
-
/** A project's marketing switch: while off, every marketing send from the project is refused. */
|
|
622
|
-
export interface ProjectMarketing {
|
|
623
|
-
marketingEnabled: boolean;
|
|
624
|
-
}
|
|
625
621
|
export interface NevarMailOptions {
|
|
626
622
|
/**
|
|
627
623
|
* A REST API key (`nvm_api_live_…` / `nvm_api_test_…`). An MCP key is
|
|
@@ -867,14 +863,6 @@ export declare class NevarMail {
|
|
|
867
863
|
* marketing send is refused without one. Blank: 422 `PHYSICAL_ADDRESS_REQUIRED`.
|
|
868
864
|
*/
|
|
869
865
|
setProjectAddress(projectId: string, input: SetProjectAddressInput): Promise<ProjectAddress>;
|
|
870
|
-
/** GET /api/v1/projects/{id}/marketing — scope `org:read`; 404 NOT_FOUND for a project the key's user can't open. */
|
|
871
|
-
getProjectMarketing(projectId: string): Promise<ProjectMarketing>;
|
|
872
|
-
/**
|
|
873
|
-
* PUT /api/v1/projects/{id}/marketing — scope `org:write`. Turns marketing
|
|
874
|
-
* mail on or off for the project. Turning it on while the project's postal
|
|
875
|
-
* address is blank: 422 `PHYSICAL_ADDRESS_REQUIRED` (set it with `setProjectAddress`).
|
|
876
|
-
*/
|
|
877
|
-
setProjectMarketing(projectId: string, input: ProjectMarketing): Promise<ProjectMarketing>;
|
|
878
866
|
/** GET /api/v1/inbox-db/status — scope `org:read`; 404 when no connection is stored. */
|
|
879
867
|
getInboxDbStatus(): Promise<InboxDbStatus>;
|
|
880
868
|
/**
|
|
@@ -888,4 +876,120 @@ export declare class NevarMail {
|
|
|
888
876
|
/** POST /api/v1/inbox-db/connection/test — scope `org:write`; 404 when nothing is stored. */
|
|
889
877
|
testInboxDbConnection(): Promise<InboxDbStatus>;
|
|
890
878
|
}
|
|
879
|
+
/** The scopes an inbox credential can be granted (`INBOX_SCOPES` on the server). */
|
|
880
|
+
export type InboxScope = "inbox:read" | "inbox:send";
|
|
881
|
+
export interface NevarMailInboxOptions extends Omit<NevarMailOptions, "apiKey"> {
|
|
882
|
+
/** The inbox credential's client id (`nvm_inbox_…`), from the inbox's Agents tab. */
|
|
883
|
+
clientId: string;
|
|
884
|
+
/** Its client secret, shown once at creation or rotation. */
|
|
885
|
+
clientSecret: string;
|
|
886
|
+
/**
|
|
887
|
+
* Narrow the token, e.g. `["inbox:read"]` for a reader that must never send.
|
|
888
|
+
* Defaults to every inbox scope.
|
|
889
|
+
*/
|
|
890
|
+
scopes?: InboxScope[];
|
|
891
|
+
}
|
|
892
|
+
/** One message in an inbox listing. Timestamps are ISO strings. */
|
|
893
|
+
export interface InboxEmailSummary {
|
|
894
|
+
id: string;
|
|
895
|
+
from: string;
|
|
896
|
+
to: string[];
|
|
897
|
+
subject: string | null;
|
|
898
|
+
isRead: boolean;
|
|
899
|
+
direction: "inbound" | "outbound";
|
|
900
|
+
threadId: string;
|
|
901
|
+
receivedAt: string;
|
|
902
|
+
}
|
|
903
|
+
/** One message with its body. Attachments are metadata only. */
|
|
904
|
+
export interface InboxEmail extends InboxEmailSummary {
|
|
905
|
+
cc: string[];
|
|
906
|
+
text: string | null;
|
|
907
|
+
html: string | null;
|
|
908
|
+
headers: Record<string, unknown>;
|
|
909
|
+
messageId: string | null;
|
|
910
|
+
inReplyTo: string | null;
|
|
911
|
+
references: string[];
|
|
912
|
+
attachments: {
|
|
913
|
+
id: string;
|
|
914
|
+
filename: string;
|
|
915
|
+
contentType: string;
|
|
916
|
+
sizeBytes: number;
|
|
917
|
+
}[];
|
|
918
|
+
}
|
|
919
|
+
export interface ListInboxEmailsOptions extends PageOptions {
|
|
920
|
+
/** Only the messages of one thread. */
|
|
921
|
+
threadId?: string;
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* The From is always the inbox's own address, and the body is strict: no
|
|
925
|
+
* templates, lists or batch. At most 5 recipients across `to` and `cc`.
|
|
926
|
+
*/
|
|
927
|
+
export interface InboxSendInput {
|
|
928
|
+
to: string;
|
|
929
|
+
/** At most 4. */
|
|
930
|
+
cc?: string[];
|
|
931
|
+
subject: string;
|
|
932
|
+
/** `text`, `html` or both. */
|
|
933
|
+
text?: string;
|
|
934
|
+
html?: string;
|
|
935
|
+
/** Thread the reply under this received message. */
|
|
936
|
+
reply_to_email_id?: string;
|
|
937
|
+
}
|
|
938
|
+
export interface InboxSendResult {
|
|
939
|
+
id: string;
|
|
940
|
+
status: string;
|
|
941
|
+
}
|
|
942
|
+
export interface InboxCredentials {
|
|
943
|
+
client_id: string;
|
|
944
|
+
/** Returned exactly once. The client already uses it; store it before you drop the client. */
|
|
945
|
+
client_secret: string;
|
|
946
|
+
secret_hint: string;
|
|
947
|
+
}
|
|
948
|
+
/**
|
|
949
|
+
* The client for one agent inbox (`/api/v1/inbox/*`). The inbox surface takes
|
|
950
|
+
* an inbox credential, not an API key: the two are disjoint on the server, so
|
|
951
|
+
* they are two clients here, and an inbox credential cannot reach anything
|
|
952
|
+
* outside its own inbox.
|
|
953
|
+
*
|
|
954
|
+
* The credential is exchanged for a short-lived token (OAuth
|
|
955
|
+
* `client_credentials`) on first use and again shortly before it expires.
|
|
956
|
+
* Same error and retry policy as {@link NevarMail}: every non-2xx throws a
|
|
957
|
+
* `NevarMailError`.
|
|
958
|
+
*/
|
|
959
|
+
export declare class NevarMailInbox {
|
|
960
|
+
#private;
|
|
961
|
+
readonly baseUrl: string;
|
|
962
|
+
readonly clientId: string;
|
|
963
|
+
constructor(options: NevarMailInboxOptions);
|
|
964
|
+
/** Like {@link NevarMail.request}, authenticated as this inbox. Returns the unwrapped `data`. */
|
|
965
|
+
request<T>(method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE", path: string, options?: RequestOptions): Promise<T>;
|
|
966
|
+
/** Like {@link NevarMail.requestPaginated}, authenticated as this inbox. */
|
|
967
|
+
requestPaginated<T>(method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE", path: string, options?: RequestOptions): Promise<Paginated<T>>;
|
|
968
|
+
/** GET /api/v1/inbox/emails — scope `inbox:read`; newest first. */
|
|
969
|
+
listEmails(options?: ListInboxEmailsOptions): Promise<Paginated<InboxEmailSummary>>;
|
|
970
|
+
/** GET /api/v1/inbox/emails/{id} — scope `inbox:read`. */
|
|
971
|
+
getEmail(id: string): Promise<InboxEmail>;
|
|
972
|
+
/** POST /api/v1/inbox/emails/{id}/read — scope `inbox:read`. */
|
|
973
|
+
markEmailRead(id: string): Promise<{
|
|
974
|
+
id: string;
|
|
975
|
+
isRead: boolean;
|
|
976
|
+
}>;
|
|
977
|
+
/** DELETE /api/v1/inbox/emails/{id} — scope `inbox:read`; attachments go with it. */
|
|
978
|
+
deleteEmail(id: string): Promise<{
|
|
979
|
+
id: string;
|
|
980
|
+
deleted: true;
|
|
981
|
+
}>;
|
|
982
|
+
/**
|
|
983
|
+
* POST /api/v1/inbox/send — scope `inbox:send`. Hitting the daily cap throws
|
|
984
|
+
* at once with `code: "inbox_daily_limit_reached"` and `retryAfter` set to the
|
|
985
|
+
* seconds until UTC midnight.
|
|
986
|
+
*/
|
|
987
|
+
send(input: InboxSendInput): Promise<InboxSendResult>;
|
|
988
|
+
/**
|
|
989
|
+
* POST /api/v1/inbox/credentials/rotate — scope `inbox:read`. Issues a new
|
|
990
|
+
* secret and switches this client to it. Store `client_secret` from the
|
|
991
|
+
* result: it is shown once, and the old secret stops working.
|
|
992
|
+
*/
|
|
993
|
+
rotateCredentials(): Promise<InboxCredentials>;
|
|
994
|
+
}
|
|
891
995
|
export default NevarMail;
|
package/dist/index.js
CHANGED
|
@@ -29,6 +29,16 @@ const LEGACY_KEY_RE = /^nvm_(live|test)_/;
|
|
|
29
29
|
function isRetryableStatus(status) {
|
|
30
30
|
return status === 429 || status >= 500;
|
|
31
31
|
}
|
|
32
|
+
function transport(options) {
|
|
33
|
+
return {
|
|
34
|
+
baseUrl: (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, ""),
|
|
35
|
+
fetch: options.fetch ?? globalThis.fetch,
|
|
36
|
+
timeoutMs: options.timeoutMs ?? 30_000,
|
|
37
|
+
maxRetries: options.maxRetries ?? 2,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
/** The longest Retry-After the client waits out itself; longer ones throw. */
|
|
41
|
+
const MAX_RETRY_AFTER_SECONDS = 30;
|
|
32
42
|
function sleep(ms) {
|
|
33
43
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
34
44
|
}
|
|
@@ -44,14 +54,124 @@ function withListAliases(list) {
|
|
|
44
54
|
const useCaseId = list.useCaseId ?? list.campaignId ?? null;
|
|
45
55
|
return { ...list, useCaseId, campaignId: useCaseId, unsubScope: list.unsubScope ?? "list" };
|
|
46
56
|
}
|
|
57
|
+
/**
|
|
58
|
+
* The retry/throw/timeout policy every request of both clients goes through.
|
|
59
|
+
* Returns the parsed body. `authorization` is omitted only for the token grant.
|
|
60
|
+
*/
|
|
61
|
+
async function send(t, authorization, method, path, options = {}) {
|
|
62
|
+
const url = new URL(`${t.baseUrl}${path}`);
|
|
63
|
+
for (const [k, v] of Object.entries(options.query ?? {})) {
|
|
64
|
+
if (v !== undefined)
|
|
65
|
+
url.searchParams.set(k, String(v));
|
|
66
|
+
}
|
|
67
|
+
let lastError;
|
|
68
|
+
for (let attempt = 0; attempt <= t.maxRetries; attempt++) {
|
|
69
|
+
if (attempt > 0) {
|
|
70
|
+
// Retry-After wins over our backoff — the server knows its own window.
|
|
71
|
+
const backoff = lastError?.retryAfter
|
|
72
|
+
? lastError.retryAfter * 1000
|
|
73
|
+
: 250 * 2 ** (attempt - 1) + Math.random() * 100;
|
|
74
|
+
await sleep(backoff);
|
|
75
|
+
}
|
|
76
|
+
let res;
|
|
77
|
+
try {
|
|
78
|
+
res = await t.fetch(url, {
|
|
79
|
+
method,
|
|
80
|
+
headers: {
|
|
81
|
+
...(authorization ? { authorization } : {}),
|
|
82
|
+
"content-type": "application/json",
|
|
83
|
+
accept: "application/json",
|
|
84
|
+
},
|
|
85
|
+
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
|
86
|
+
signal: options.signal ?? AbortSignal.timeout(t.timeoutMs),
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
catch (cause) {
|
|
90
|
+
// No response at all: DNS, TCP, TLS, timeout. Transient unless the
|
|
91
|
+
// caller cancelled — see abortedByCaller.
|
|
92
|
+
lastError = new NevarMailError(`Request to ${method} ${path} failed: ${cause?.message ?? "network error"}`, { status: 0, code: "NETWORK_ERROR", cause });
|
|
93
|
+
if (abortedByCaller(options, cause))
|
|
94
|
+
throw lastError;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
const requestId = res.headers.get("x-request-id");
|
|
98
|
+
// The body arrives after the headers, so it can still fail on its own:
|
|
99
|
+
// a dropped connection or a timeout mid-stream rejects here. Outside a
|
|
100
|
+
// try that would escape as a raw TypeError/AbortError and break the one
|
|
101
|
+
// guarantee this package makes — every failure is a NevarMailError.
|
|
102
|
+
let raw;
|
|
103
|
+
try {
|
|
104
|
+
raw = await res.text();
|
|
105
|
+
}
|
|
106
|
+
catch (cause) {
|
|
107
|
+
lastError = new NevarMailError(`Reading the response body of ${method} ${path} failed: ${cause?.message ?? "network error"}`, { status: res.status, code: "NETWORK_ERROR", requestId, cause });
|
|
108
|
+
if (abortedByCaller(options, cause))
|
|
109
|
+
throw lastError;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
let parsed = undefined;
|
|
113
|
+
if (raw) {
|
|
114
|
+
try {
|
|
115
|
+
parsed = JSON.parse(raw);
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
parsed = raw;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
if (res.ok)
|
|
122
|
+
return parsed;
|
|
123
|
+
const envelope = (parsed ?? {});
|
|
124
|
+
const retryAfterHeader = res.headers.get("retry-after");
|
|
125
|
+
lastError = new NevarMailError(envelope.error ?? `${method} ${path} failed with ${res.status}`, {
|
|
126
|
+
status: res.status,
|
|
127
|
+
code: envelope.code ?? `HTTP_${res.status}`,
|
|
128
|
+
requestId: envelope.requestId ?? requestId,
|
|
129
|
+
retryAfter: retryAfterHeader ? Number(retryAfterHeader) : null,
|
|
130
|
+
body: parsed,
|
|
131
|
+
});
|
|
132
|
+
if (!isRetryableStatus(res.status))
|
|
133
|
+
throw lastError;
|
|
134
|
+
// A long Retry-After is a quota, not a blip — a daily cap answers with
|
|
135
|
+
// hours until UTC midnight. Sleeping that out would hang the caller and
|
|
136
|
+
// outlive any timeout, so hand it back with `retryAfter` set instead.
|
|
137
|
+
if ((lastError.retryAfter ?? 0) > MAX_RETRY_AFTER_SECONDS)
|
|
138
|
+
throw lastError;
|
|
139
|
+
}
|
|
140
|
+
throw lastError;
|
|
141
|
+
}
|
|
142
|
+
/**
|
|
143
|
+
* A cancellation the caller asked for is not a transient failure: retrying
|
|
144
|
+
* re-uses the same already-aborted signal, so every attempt fails the same
|
|
145
|
+
* way and the only effect is delaying the rejection by the backoff. Our own
|
|
146
|
+
* timeout signal is a different matter — that one is worth another attempt.
|
|
147
|
+
*/
|
|
148
|
+
function abortedByCaller(options, cause) {
|
|
149
|
+
if (options.signal?.aborted)
|
|
150
|
+
return true;
|
|
151
|
+
return options.signal !== undefined && cause?.name === "AbortError";
|
|
152
|
+
}
|
|
153
|
+
/** The v1 envelope's `data`. 204s and any non-enveloped body pass through as-is. */
|
|
154
|
+
function unwrap(parsed) {
|
|
155
|
+
const envelope = parsed;
|
|
156
|
+
return (envelope && typeof envelope === "object" && "data" in envelope ? envelope.data : parsed);
|
|
157
|
+
}
|
|
158
|
+
/** A list response with the envelope's `pagination` kept. */
|
|
159
|
+
function paginated(parsed) {
|
|
160
|
+
const body = parsed;
|
|
161
|
+
const data = body?.data ?? [];
|
|
162
|
+
return {
|
|
163
|
+
data,
|
|
164
|
+
// Every wrapped list route sends pagination; synthesized only so a
|
|
165
|
+
// server that stops sending it degrades to a truthful single page.
|
|
166
|
+
pagination: body?.pagination ?? { page: 1, perPage: data.length, total: data.length },
|
|
167
|
+
};
|
|
168
|
+
}
|
|
47
169
|
export class NevarMail {
|
|
48
170
|
baseUrl;
|
|
49
171
|
/** Derived from the key prefix, not configured — a mismatch is not possible. */
|
|
50
172
|
mode;
|
|
51
173
|
#apiKey;
|
|
52
|
-
#
|
|
53
|
-
#timeoutMs;
|
|
54
|
-
#maxRetries;
|
|
174
|
+
#transport;
|
|
55
175
|
constructor(options) {
|
|
56
176
|
const key = options.apiKey?.trim();
|
|
57
177
|
if (!key) {
|
|
@@ -75,10 +195,8 @@ export class NevarMail {
|
|
|
75
195
|
throw new NevarMailError("apiKey does not look like a NevarMail key (expected `nvm_api_live_…` or `nvm_api_test_…`).", { status: 0, code: "MALFORMED_API_KEY" });
|
|
76
196
|
}
|
|
77
197
|
this.#apiKey = key;
|
|
78
|
-
this
|
|
79
|
-
this
|
|
80
|
-
this.#timeoutMs = options.timeoutMs ?? 30_000;
|
|
81
|
-
this.#maxRetries = options.maxRetries ?? 2;
|
|
198
|
+
this.#transport = transport(options);
|
|
199
|
+
this.baseUrl = this.#transport.baseUrl;
|
|
82
200
|
}
|
|
83
201
|
/**
|
|
84
202
|
* Every method below is one line over this. Public because the named methods
|
|
@@ -88,114 +206,17 @@ export class NevarMail {
|
|
|
88
206
|
* Returns the unwrapped `data` from the v1 envelope. Throws on any non-2xx.
|
|
89
207
|
*/
|
|
90
208
|
async request(method, path, options = {}) {
|
|
91
|
-
|
|
92
|
-
const envelope = parsed;
|
|
93
|
-
// 204s and any non-enveloped body pass through as-is.
|
|
94
|
-
return (envelope && typeof envelope === "object" && "data" in envelope
|
|
95
|
-
? envelope.data
|
|
96
|
-
: parsed);
|
|
209
|
+
return unwrap(await this.#send(method, path, options));
|
|
97
210
|
}
|
|
98
211
|
/**
|
|
99
212
|
* Like `request`, but keeps the envelope's `pagination` — for the list
|
|
100
213
|
* routes, where dropping it would make `total` unknowable to the caller.
|
|
101
214
|
*/
|
|
102
215
|
async requestPaginated(method, path, options = {}) {
|
|
103
|
-
|
|
104
|
-
const data = parsed?.data ?? [];
|
|
105
|
-
return {
|
|
106
|
-
data,
|
|
107
|
-
// Every wrapped list route sends pagination; synthesized only so a
|
|
108
|
-
// server that stops sending it degrades to a truthful single page.
|
|
109
|
-
pagination: parsed?.pagination ?? { page: 1, perPage: data.length, total: data.length },
|
|
110
|
-
};
|
|
111
|
-
}
|
|
112
|
-
/** The retry/throw/timeout policy, shared by both request forms. Returns the parsed body. */
|
|
113
|
-
async #send(method, path, options = {}) {
|
|
114
|
-
const url = new URL(`${this.baseUrl}${path}`);
|
|
115
|
-
for (const [k, v] of Object.entries(options.query ?? {})) {
|
|
116
|
-
if (v !== undefined)
|
|
117
|
-
url.searchParams.set(k, String(v));
|
|
118
|
-
}
|
|
119
|
-
let lastError;
|
|
120
|
-
for (let attempt = 0; attempt <= this.#maxRetries; attempt++) {
|
|
121
|
-
if (attempt > 0) {
|
|
122
|
-
// Retry-After wins over our backoff — the server knows its own window.
|
|
123
|
-
const backoff = lastError?.retryAfter
|
|
124
|
-
? lastError.retryAfter * 1000
|
|
125
|
-
: 250 * 2 ** (attempt - 1) + Math.random() * 100;
|
|
126
|
-
await sleep(backoff);
|
|
127
|
-
}
|
|
128
|
-
let res;
|
|
129
|
-
try {
|
|
130
|
-
res = await this.#fetch(url, {
|
|
131
|
-
method,
|
|
132
|
-
headers: {
|
|
133
|
-
authorization: `Bearer ${this.#apiKey}`,
|
|
134
|
-
"content-type": "application/json",
|
|
135
|
-
accept: "application/json",
|
|
136
|
-
},
|
|
137
|
-
body: options.body === undefined ? undefined : JSON.stringify(options.body),
|
|
138
|
-
signal: options.signal ?? AbortSignal.timeout(this.#timeoutMs),
|
|
139
|
-
});
|
|
140
|
-
}
|
|
141
|
-
catch (cause) {
|
|
142
|
-
// No response at all: DNS, TCP, TLS, timeout. Transient unless the
|
|
143
|
-
// caller cancelled — see #abortedByCaller.
|
|
144
|
-
lastError = new NevarMailError(`Request to ${method} ${path} failed: ${cause?.message ?? "network error"}`, { status: 0, code: "NETWORK_ERROR", cause });
|
|
145
|
-
if (this.#abortedByCaller(options, cause))
|
|
146
|
-
throw lastError;
|
|
147
|
-
continue;
|
|
148
|
-
}
|
|
149
|
-
const requestId = res.headers.get("x-request-id");
|
|
150
|
-
// The body arrives after the headers, so it can still fail on its own:
|
|
151
|
-
// a dropped connection or a timeout mid-stream rejects here. Outside a
|
|
152
|
-
// try that would escape as a raw TypeError/AbortError and break the one
|
|
153
|
-
// guarantee this package makes — every failure is a NevarMailError.
|
|
154
|
-
let raw;
|
|
155
|
-
try {
|
|
156
|
-
raw = await res.text();
|
|
157
|
-
}
|
|
158
|
-
catch (cause) {
|
|
159
|
-
lastError = new NevarMailError(`Reading the response body of ${method} ${path} failed: ${cause?.message ?? "network error"}`, { status: res.status, code: "NETWORK_ERROR", requestId, cause });
|
|
160
|
-
if (this.#abortedByCaller(options, cause))
|
|
161
|
-
throw lastError;
|
|
162
|
-
continue;
|
|
163
|
-
}
|
|
164
|
-
let parsed = undefined;
|
|
165
|
-
if (raw) {
|
|
166
|
-
try {
|
|
167
|
-
parsed = JSON.parse(raw);
|
|
168
|
-
}
|
|
169
|
-
catch {
|
|
170
|
-
parsed = raw;
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
if (res.ok)
|
|
174
|
-
return parsed;
|
|
175
|
-
const envelope = (parsed ?? {});
|
|
176
|
-
const retryAfterHeader = res.headers.get("retry-after");
|
|
177
|
-
lastError = new NevarMailError(envelope.error ?? `${method} ${path} failed with ${res.status}`, {
|
|
178
|
-
status: res.status,
|
|
179
|
-
code: envelope.code ?? `HTTP_${res.status}`,
|
|
180
|
-
requestId: envelope.requestId ?? requestId,
|
|
181
|
-
retryAfter: retryAfterHeader ? Number(retryAfterHeader) : null,
|
|
182
|
-
body: parsed,
|
|
183
|
-
});
|
|
184
|
-
if (!isRetryableStatus(res.status))
|
|
185
|
-
throw lastError;
|
|
186
|
-
}
|
|
187
|
-
throw lastError;
|
|
216
|
+
return paginated(await this.#send(method, path, options));
|
|
188
217
|
}
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
* re-uses the same already-aborted signal, so every attempt fails the same
|
|
192
|
-
* way and the only effect is delaying the rejection by the backoff. Our own
|
|
193
|
-
* timeout signal is a different matter — that one is worth another attempt.
|
|
194
|
-
*/
|
|
195
|
-
#abortedByCaller(options, cause) {
|
|
196
|
-
if (options.signal?.aborted)
|
|
197
|
-
return true;
|
|
198
|
-
return options.signal !== undefined && cause?.name === "AbortError";
|
|
218
|
+
#send(method, path, options = {}) {
|
|
219
|
+
return send(this.#transport, `Bearer ${this.#apiKey}`, method, path, options);
|
|
199
220
|
}
|
|
200
221
|
/**
|
|
201
222
|
* POST /api/v1/email/send — one transactional message. A marketing send
|
|
@@ -530,18 +551,6 @@ export class NevarMail {
|
|
|
530
551
|
setProjectAddress(projectId, input) {
|
|
531
552
|
return this.request("PUT", `/api/v1/projects/${encodeURIComponent(projectId)}/address`, { body: input });
|
|
532
553
|
}
|
|
533
|
-
/** GET /api/v1/projects/{id}/marketing — scope `org:read`; 404 NOT_FOUND for a project the key's user can't open. */
|
|
534
|
-
getProjectMarketing(projectId) {
|
|
535
|
-
return this.request("GET", `/api/v1/projects/${encodeURIComponent(projectId)}/marketing`);
|
|
536
|
-
}
|
|
537
|
-
/**
|
|
538
|
-
* PUT /api/v1/projects/{id}/marketing — scope `org:write`. Turns marketing
|
|
539
|
-
* mail on or off for the project. Turning it on while the project's postal
|
|
540
|
-
* address is blank: 422 `PHYSICAL_ADDRESS_REQUIRED` (set it with `setProjectAddress`).
|
|
541
|
-
*/
|
|
542
|
-
setProjectMarketing(projectId, input) {
|
|
543
|
-
return this.request("PUT", `/api/v1/projects/${encodeURIComponent(projectId)}/marketing`, { body: input });
|
|
544
|
-
}
|
|
545
554
|
// ── Inbox database ─────────────────────────────────────────────────────
|
|
546
555
|
/** GET /api/v1/inbox-db/status — scope `org:read`; 404 when no connection is stored. */
|
|
547
556
|
getInboxDbStatus() {
|
|
@@ -564,4 +573,138 @@ export class NevarMail {
|
|
|
564
573
|
return this.request("POST", "/api/v1/inbox-db/connection/test");
|
|
565
574
|
}
|
|
566
575
|
}
|
|
576
|
+
/**
|
|
577
|
+
* The client for one agent inbox (`/api/v1/inbox/*`). The inbox surface takes
|
|
578
|
+
* an inbox credential, not an API key: the two are disjoint on the server, so
|
|
579
|
+
* they are two clients here, and an inbox credential cannot reach anything
|
|
580
|
+
* outside its own inbox.
|
|
581
|
+
*
|
|
582
|
+
* The credential is exchanged for a short-lived token (OAuth
|
|
583
|
+
* `client_credentials`) on first use and again shortly before it expires.
|
|
584
|
+
* Same error and retry policy as {@link NevarMail}: every non-2xx throws a
|
|
585
|
+
* `NevarMailError`.
|
|
586
|
+
*/
|
|
587
|
+
export class NevarMailInbox {
|
|
588
|
+
baseUrl;
|
|
589
|
+
clientId;
|
|
590
|
+
#clientSecret;
|
|
591
|
+
#scopes;
|
|
592
|
+
#transport;
|
|
593
|
+
#token;
|
|
594
|
+
#pendingToken;
|
|
595
|
+
constructor(options) {
|
|
596
|
+
const clientId = options.clientId?.trim();
|
|
597
|
+
if (!clientId?.startsWith("nvm_inbox_")) {
|
|
598
|
+
throw new NevarMailError("clientId must be an inbox credential (`nvm_inbox_…`). API keys do not work on the inbox API; use NevarMail for those.", { status: 0, code: "MALFORMED_CLIENT_ID" });
|
|
599
|
+
}
|
|
600
|
+
if (!options.clientSecret?.trim()) {
|
|
601
|
+
throw new NevarMailError("clientSecret is required", { status: 0, code: "MISSING_CLIENT_SECRET" });
|
|
602
|
+
}
|
|
603
|
+
this.clientId = clientId;
|
|
604
|
+
this.#clientSecret = options.clientSecret.trim();
|
|
605
|
+
this.#scopes = options.scopes;
|
|
606
|
+
this.#transport = transport(options);
|
|
607
|
+
this.baseUrl = this.#transport.baseUrl;
|
|
608
|
+
}
|
|
609
|
+
/** Like {@link NevarMail.request}, authenticated as this inbox. Returns the unwrapped `data`. */
|
|
610
|
+
async request(method, path, options = {}) {
|
|
611
|
+
return unwrap(await this.#send(method, path, options));
|
|
612
|
+
}
|
|
613
|
+
/** Like {@link NevarMail.requestPaginated}, authenticated as this inbox. */
|
|
614
|
+
async requestPaginated(method, path, options = {}) {
|
|
615
|
+
return paginated(await this.#send(method, path, options));
|
|
616
|
+
}
|
|
617
|
+
async #send(method, path, options) {
|
|
618
|
+
const token = await this.#accessToken();
|
|
619
|
+
try {
|
|
620
|
+
return await send(this.#transport, `Bearer ${token}`, method, path, options);
|
|
621
|
+
}
|
|
622
|
+
catch (err) {
|
|
623
|
+
// A 401 means the request was refused before it ran (nothing was sent),
|
|
624
|
+
// so one retry on a fresh token is safe: the token was revoked, or
|
|
625
|
+
// expired earlier than our clock thought. A second 401 is real.
|
|
626
|
+
if (!(err instanceof NevarMailError) || err.status !== 401)
|
|
627
|
+
throw err;
|
|
628
|
+
if (this.#token?.value === token)
|
|
629
|
+
this.#token = undefined;
|
|
630
|
+
return send(this.#transport, `Bearer ${await this.#accessToken()}`, method, path, options);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
/** The cached token, or one fresh exchange shared by every caller waiting on it. */
|
|
634
|
+
#accessToken() {
|
|
635
|
+
if (this.#token && Date.now() < this.#token.renewAt)
|
|
636
|
+
return Promise.resolve(this.#token.value);
|
|
637
|
+
this.#pendingToken ??= this.#exchange().finally(() => {
|
|
638
|
+
this.#pendingToken = undefined;
|
|
639
|
+
});
|
|
640
|
+
return this.#pendingToken;
|
|
641
|
+
}
|
|
642
|
+
async #exchange() {
|
|
643
|
+
let res;
|
|
644
|
+
try {
|
|
645
|
+
res = (await send(this.#transport, undefined, "POST", "/api/oauth/token", {
|
|
646
|
+
body: {
|
|
647
|
+
grant_type: "client_credentials",
|
|
648
|
+
client_id: this.clientId,
|
|
649
|
+
client_secret: this.#clientSecret,
|
|
650
|
+
...(this.#scopes ? { scope: this.#scopes.join(" ") } : {}),
|
|
651
|
+
},
|
|
652
|
+
}));
|
|
653
|
+
}
|
|
654
|
+
catch (err) {
|
|
655
|
+
// The token endpoint answers in OAuth's shape (`{ error: "invalid_client" }`),
|
|
656
|
+
// not the v1 envelope, so lift its error into `code`.
|
|
657
|
+
const oauthError = err instanceof NevarMailError && err.body?.error;
|
|
658
|
+
if (typeof oauthError !== "string")
|
|
659
|
+
throw err;
|
|
660
|
+
const e = err;
|
|
661
|
+
throw new NevarMailError(oauthError === "invalid_client"
|
|
662
|
+
? "The inbox credential was rejected: wrong id or secret, revoked, or the inbox is no longer active."
|
|
663
|
+
: `Getting an inbox token failed: ${oauthError}`, { status: e.status, code: oauthError.toUpperCase(), requestId: e.requestId, body: e.body, cause: err });
|
|
664
|
+
}
|
|
665
|
+
// Renew a minute early so a token never expires mid-request.
|
|
666
|
+
this.#token = {
|
|
667
|
+
value: res.access_token,
|
|
668
|
+
renewAt: Date.now() + Math.max(0, res.expires_in - 60) * 1000,
|
|
669
|
+
};
|
|
670
|
+
return res.access_token;
|
|
671
|
+
}
|
|
672
|
+
/** GET /api/v1/inbox/emails — scope `inbox:read`; newest first. */
|
|
673
|
+
listEmails(options = {}) {
|
|
674
|
+
const { threadId, ...page } = options;
|
|
675
|
+
return this.requestPaginated("GET", "/api/v1/inbox/emails", {
|
|
676
|
+
query: { ...page, thread_id: threadId },
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
/** GET /api/v1/inbox/emails/{id} — scope `inbox:read`. */
|
|
680
|
+
getEmail(id) {
|
|
681
|
+
return this.request("GET", `/api/v1/inbox/emails/${encodeURIComponent(id)}`);
|
|
682
|
+
}
|
|
683
|
+
/** POST /api/v1/inbox/emails/{id}/read — scope `inbox:read`. */
|
|
684
|
+
markEmailRead(id) {
|
|
685
|
+
return this.request("POST", `/api/v1/inbox/emails/${encodeURIComponent(id)}/read`);
|
|
686
|
+
}
|
|
687
|
+
/** DELETE /api/v1/inbox/emails/{id} — scope `inbox:read`; attachments go with it. */
|
|
688
|
+
deleteEmail(id) {
|
|
689
|
+
return this.request("DELETE", `/api/v1/inbox/emails/${encodeURIComponent(id)}`);
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* POST /api/v1/inbox/send — scope `inbox:send`. Hitting the daily cap throws
|
|
693
|
+
* at once with `code: "inbox_daily_limit_reached"` and `retryAfter` set to the
|
|
694
|
+
* seconds until UTC midnight.
|
|
695
|
+
*/
|
|
696
|
+
send(input) {
|
|
697
|
+
return this.request("POST", "/api/v1/inbox/send", { body: input });
|
|
698
|
+
}
|
|
699
|
+
/**
|
|
700
|
+
* POST /api/v1/inbox/credentials/rotate — scope `inbox:read`. Issues a new
|
|
701
|
+
* secret and switches this client to it. Store `client_secret` from the
|
|
702
|
+
* result: it is shown once, and the old secret stops working.
|
|
703
|
+
*/
|
|
704
|
+
async rotateCredentials() {
|
|
705
|
+
const creds = await this.request("POST", "/api/v1/inbox/credentials/rotate");
|
|
706
|
+
this.#clientSecret = creds.client_secret;
|
|
707
|
+
return creds;
|
|
708
|
+
}
|
|
709
|
+
}
|
|
567
710
|
export default NevarMail;
|
package/package.json
CHANGED