@bernierllc/nevarmail 0.0.0 → 0.4.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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Bernier LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1 +1,212 @@
1
- placeholder
1
+ # @bernierllc/nevarmail
2
+
3
+ The official client for the NevarMail v1 API.
4
+
5
+ > **Where this lives.** This package is published from `bernierllc/tools`
6
+ > (`packages/core/nevarmail`) and is the single source of truth for the client.
7
+ > The NevarMail API it wraps is built in `bernierllc/email_demo`. **Any change to the
8
+ > NevarMail v1 API surface requires a matching change here, in the same unit of work** —
9
+ > see that repo's `CLAUDE.md` → "NevarMail SDK (`@bernierllc/nevarmail`)".
10
+
11
+
12
+ **One rule: every non-2xx throws.** If a call returns, the API accepted it. There is no
13
+ "success" object carrying a failure inside it, and no option to silence errors — the audit
14
+ that produced this package found a production integration that swallowed every error, so an
15
+ org may have been mailing into a `403` for months with nothing on either side noticing.
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install @bernierllc/nevarmail
21
+ ```
22
+
23
+ Requires Node 20+ (uses the global `fetch`). Zero dependencies.
24
+
25
+ ## Integration status
26
+
27
+ | Integration | Status | Why |
28
+ |-------------|--------|-----|
29
+ | Logger (`@bernierllc/logger`) | not-applicable | A zero-dependency API client stays zero-dependency. Every failure surfaces as a thrown `NevarMailError` carrying `status`, `code`, `requestId` and `cause` — log it in the consumer, with the consumer's logger. |
30
+ | NeverHub (`@bernierllc/neverhub-adapter`) | not-applicable | Core-tier package with no runtime lifecycle to register; NeverHub registration belongs to the service or suite that composes this client. Graceful degradation is therefore not required here. |
31
+
32
+ ## Usage
33
+
34
+ ```ts
35
+ import { NevarMail } from "@bernierllc/nevarmail";
36
+
37
+ const nevarmail = new NevarMail({ apiKey: process.env.NEVARMAIL_API_KEY! });
38
+
39
+ const result = await nevarmail.sendEmail({
40
+ to: "customer@example.com",
41
+ subject: "Your quote is ready",
42
+ html: "<p>Here it is.</p>",
43
+ use_case_id: process.env.NEVARMAIL_USE_CASE_TRANSACTIONAL,
44
+ });
45
+
46
+ console.log(result.id, result.status);
47
+ ```
48
+
49
+ ## Tenancy — one key is one org
50
+
51
+ A NevarMail API key **is** the organization. There is no org id in any request body; the
52
+ server resolves it from the key and ignores anything you send. Two consequences:
53
+
54
+ - One key per org. A key cannot be pointed at a second org, and a multi-tenant app that
55
+ sends on behalf of several NevarMail orgs holds several keys.
56
+ - Never accept an org identifier from an end user and pass it through. There is nowhere to
57
+ put it, and the attempt is a sign the integration is modeling tenancy wrong.
58
+
59
+ ## Keys, surfaces, and modes
60
+
61
+ Keys look like `nvm_api_live_…`, `nvm_api_test_…`, `nvm_mcp_live_…`, `nvm_mcp_test_…`.
62
+
63
+ - **Surface** (`api` vs `mcp`) — this package speaks REST, so it needs an `api` key. Pass an
64
+ `mcp` key and the constructor throws immediately rather than letting the server answer a
65
+ `403 KEY_TYPE_MISMATCH` at your first send, which reads like an auth bug.
66
+ - **Mode** (`live` vs `test`) — a test key sends only to addresses on the org's test
67
+ allow-list; anything else is a `422 TEST_MODE_RECIPIENT_NOT_ALLOWED`. The mode is a
68
+ property of the key, never a client option: `client.mode` reports what the key is.
69
+
70
+ ```ts
71
+ const nevarmail = new NevarMail({ apiKey: key });
72
+ if (nevarmail.mode === "test") console.warn("test key — sends are allow-list only");
73
+ ```
74
+
75
+ ## Errors
76
+
77
+ Every failure is a `NevarMailError`:
78
+
79
+ ```ts
80
+ import { NevarMail, NevarMailError } from "@bernierllc/nevarmail";
81
+
82
+ try {
83
+ await nevarmail.sendEmail({ to, subject, html });
84
+ } catch (err) {
85
+ if (err instanceof NevarMailError && err.code === "RECIPIENT_SUPPRESSED") {
86
+ // Expected: this person opted out. Not an outage.
87
+ return;
88
+ }
89
+ throw err; // everything else is worth waking someone for
90
+ }
91
+ ```
92
+
93
+ | Field | Meaning |
94
+ |---|---|
95
+ | `status` | HTTP status; `0` when the request never reached the API |
96
+ | `code` | Machine-readable code — branch on this, never on `message` |
97
+ | `requestId` | Quote it in support; it matches the API's `x-request-id` |
98
+ | `retryAfter` | Seconds, from `Retry-After` on a 429 |
99
+ | `body` | The parsed response, for codes newer than your installed version |
100
+
101
+ Codes worth handling explicitly:
102
+
103
+ | Code | Status | What it means |
104
+ |---|---|---|
105
+ | `RECIPIENT_SUPPRESSED` | 422 | Bounced, complained, or unsubscribed. Do not retry. |
106
+ | `MARKETING_NOT_ENABLED` | 422 | `emailType: "marketing"` before marketing is configured (Settings → Marketing, incl. a CAN-SPAM address). |
107
+ | `TEST_MODE_RECIPIENT_NOT_ALLOWED` | 422 | Test key, recipient not on the allow-list. |
108
+ | `CC_BCC_NOT_SUPPORTED_FOR_TEMPLATE` | 400 | Templated mail renders per recipient; send one request each. |
109
+ | `VALIDATION_ERROR` | 400 | The body is wrong. Retrying will not help. |
110
+ | `SCOPE_DENIED` | 403 | The key lacks the scope this route needs. |
111
+ | `KEY_TYPE_MISMATCH` | 403 | An MCP key on a REST route (this client refuses it at construction). |
112
+ | `RATE_LIMITED` | 429 | Retried automatically; surfaced if the budget runs out. |
113
+ | `SCHEDULE_NOT_CANCELLABLE` | 409 | The scheduled send already fired or was already cancelled. |
114
+ | `NETWORK_ERROR` | 0 | No response at all — DNS, TLS, or timeout. |
115
+
116
+ ## Retries
117
+
118
+ Retried: `429` (honoring `Retry-After`), `5xx`, and network failures — exponential backoff
119
+ with jitter, two extra attempts by default (`maxRetries`).
120
+
121
+ Never retried: any other `4xx`. It will fail the same way forever, so retrying turns one bad
122
+ request into three. Sends are not idempotent; a retry after a `5xx` may deliver twice.
123
+
124
+ ## Use cases and suppression scope
125
+
126
+ `use_case_id` names the message category a send belongs to. It is the difference between
127
+ "this person unsubscribed from your newsletter" and "this person can no longer be emailed":
128
+
129
+ - **Name it**, and an opt-out scoped to a *different* category does not block the send.
130
+ - **Omit it**, and every active suppression on that address applies — the strict reading.
131
+
132
+ Bounces and spam complaints block everything regardless. Only a `use_case_id` you passed
133
+ yourself can narrow a block; a default the server resolves cannot.
134
+
135
+ ## Methods
136
+
137
+ | Method | Route | Scope |
138
+ |---|---|---|
139
+ | `sendEmail` | `POST /api/v1/email/send` | `email:send` |
140
+ | `sendEmailToList` | `POST /api/v1/email/send-to-list` | `email:send` |
141
+ | `scheduleEmail` | `POST /api/v1/email/schedule` | `email:send` |
142
+ | `listScheduledEmails` | `GET /api/v1/email/schedule` | `email:send` |
143
+ | `cancelScheduledEmail` | `DELETE /api/v1/email/schedule/{id}` | `email:send` |
144
+ | `checkSuppression` | `GET /api/v1/suppressions/check` | `org:read` |
145
+ | `getPreferences` | `GET /api/v1/preferences` | `contacts:read` |
146
+ | `setPreferences` | `PUT /api/v1/preferences` | `contacts:write` |
147
+ | `listTemplates` / `createTemplate` / `getTemplate` / `updateTemplate` / `deleteTemplate` | `/api/v1/templates` | `templates:read` / `templates:write` |
148
+ | `renderTemplate` | `POST /api/v1/templates/{id}/render` | `templates:read` |
149
+ | `listLists` / `createList` / `getList` | `/api/v1/lists` | `contacts:read` / `contacts:write` |
150
+ | `addListContacts` | `POST /api/v1/lists/{id}/contacts` | `contacts:write` |
151
+ | `listContacts` / `upsertContacts` / `updateContact` / `deleteContact` | `/api/v1/contacts` | `contacts:read` / `contacts:write` |
152
+ | `listSenders` / `createSender` / `getSender` / `updateSender` / `deleteSender` | `/api/v1/senders` | `senders:read` / `senders:write` |
153
+ | `listDomains` / `createDomain(domain, { projectId })` / `getDomain` / `deleteDomain` | `/api/v1/domains` | `domains:read` / `domains:write` |
154
+ | `getDomainDnsRecords` / `verifyDomain` | `/api/v1/domains/{id}/…` | `domains:read` / `domains:write` |
155
+ | `listSuppressions` / `addSuppressions` | `/api/v1/suppressions` | `org:read` / `org:write` |
156
+
157
+ Application-level details worth knowing before you hit them:
158
+
159
+ - **List methods keep pagination.** `listTemplates` and friends return
160
+ `{ data, pagination: { page, perPage, total } }` — the envelope's pagination is the point of
161
+ calling a list route, so it is not unwrapped away. Single-resource methods return the payload
162
+ directly, same as the send methods.
163
+ - **Updates are `PATCH`, and partial.** Send only the fields you are changing.
164
+ - **`renderTemplate(id, variables)` sends the variables map as the whole body** — not wrapped in
165
+ a `variables` key.
166
+ - **`deleteTemplate` never 404s**: an unknown id resolves `{ deleted: false }` on a 200. Every
167
+ other delete throws on a missing resource.
168
+ - **Lists have no update or delete** — the API exposes none; the SDK does not invent them.
169
+ - **Suppression scope is cross-field**: `scope: "use_case"` requires `use_case_id`, and
170
+ `use_case_id` with `scope: "account"` is a `400`.
171
+ - **Managed accounts cannot delete domains** — `deleteDomain` throws `403 MANAGED_ACCOUNT`.
172
+
173
+ Anything still not covered — analytics, campaigns, webhook endpoints — goes through
174
+ `request()` (or `requestPaginated()` for list routes), which applies the same auth, envelope
175
+ unwrapping, throwing, and retries:
176
+
177
+ ```ts
178
+ const summary = await nevarmail.request<AnalyticsSummary>("GET", "/api/v1/analytics/summary");
179
+ ```
180
+
181
+ Reach for `request()` rather than writing a second HTTP client beside this one. That is how
182
+ the swallowed-error problem happened the first time.
183
+
184
+ ### `sendEmailToList` returns a rollup, not a verdict
185
+
186
+ A list send that reaches some recipients is a `200` with `status: "partial"` and a non-zero
187
+ `failedCount`. Check the fields; a 2xx does not mean everyone received it.
188
+
189
+ ```ts
190
+ const run = await nevarmail.sendEmailToList({ listId, subject, htmlContent });
191
+ if (run.status !== "sent") console.error(run.failedCount, run.failures);
192
+ ```
193
+
194
+ ### Scheduling needs a real instant
195
+
196
+ `scheduled_for` must carry an explicit offset — `2026-09-01T14:00:00Z` or
197
+ `2026-09-01T10:00:00-04:00`. A bare local time is four different moments depending on who
198
+ typed it, so the API rejects it rather than guessing. Convert on your side, where the zone is
199
+ actually known. Templated scheduled sends are refused: the processor does not render
200
+ templates, so accepting one would queue an empty body.
201
+
202
+ ## Options
203
+
204
+ ```ts
205
+ new NevarMail({
206
+ apiKey: process.env.NEVARMAIL_API_KEY!,
207
+ baseUrl: "https://app.nevarmail.com", // default
208
+ timeoutMs: 30_000, // default
209
+ maxRetries: 2, // default
210
+ fetch: undefined, // inject one for tests or a custom runtime
211
+ });
212
+ ```
@@ -0,0 +1,21 @@
1
+ /** Every failed call throws one of these. */
2
+ export declare class NevarMailError extends Error {
3
+ /** HTTP status, or 0 when the request never got a response. */
4
+ readonly status: number;
5
+ /** Machine-readable code from the v1 envelope, e.g. `RECIPIENT_SUPPRESSED`. */
6
+ readonly code: string;
7
+ /** `requestId` from the envelope (also the `x-request-id` header) — quote this in support. */
8
+ readonly requestId: string | null;
9
+ /** Seconds to wait, from the `Retry-After` header on a 429. */
10
+ readonly retryAfter: number | null;
11
+ /** The parsed response body, for codes this package predates. */
12
+ readonly body: unknown;
13
+ constructor(message: string, init: {
14
+ status: number;
15
+ code: string;
16
+ requestId?: string | null;
17
+ retryAfter?: number | null;
18
+ body?: unknown;
19
+ cause?: unknown;
20
+ });
21
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,29 @@
1
+ /*
2
+ Copyright (c) 2025 Bernier LLC
3
+
4
+ This file is licensed to the client under a limited-use license.
5
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
6
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
+ */
8
+ /** Every failed call throws one of these. */
9
+ export class NevarMailError extends Error {
10
+ /** HTTP status, or 0 when the request never got a response. */
11
+ status;
12
+ /** Machine-readable code from the v1 envelope, e.g. `RECIPIENT_SUPPRESSED`. */
13
+ code;
14
+ /** `requestId` from the envelope (also the `x-request-id` header) — quote this in support. */
15
+ requestId;
16
+ /** Seconds to wait, from the `Retry-After` header on a 429. */
17
+ retryAfter;
18
+ /** The parsed response body, for codes this package predates. */
19
+ body;
20
+ constructor(message, init) {
21
+ super(message, { cause: init.cause });
22
+ this.name = "NevarMailError";
23
+ this.status = init.status;
24
+ this.code = init.code;
25
+ this.requestId = init.requestId ?? null;
26
+ this.retryAfter = init.retryAfter ?? null;
27
+ this.body = init.body;
28
+ }
29
+ }
@@ -0,0 +1,504 @@
1
+ export { NevarMailError } from "./errors.js";
2
+ /** The v1 success envelope. `request()` unwraps `data` and returns it. */
3
+ export interface V1Pagination {
4
+ page: number;
5
+ perPage: number;
6
+ total: number;
7
+ }
8
+ export interface EmailResult {
9
+ id: string;
10
+ messageId: string | null;
11
+ status: string;
12
+ provider: string | null;
13
+ sentAt: string | null;
14
+ }
15
+ export interface SendEmailInput {
16
+ to: string;
17
+ subject?: string;
18
+ html?: string;
19
+ text?: string;
20
+ templateId?: string;
21
+ variables?: Record<string, unknown>;
22
+ from?: string;
23
+ fromName?: string;
24
+ replyTo?: string;
25
+ cc?: string | string[];
26
+ bcc?: string;
27
+ priority?: "low" | "normal" | "high";
28
+ metadata?: Record<string, unknown>;
29
+ emailType?: "transactional" | "marketing";
30
+ /**
31
+ * The message category this send belongs to. Naming it is what lets a
32
+ * recipient's opt-out from a DIFFERENT category stop blocking this one —
33
+ * omit it and every active suppression row applies. See the README.
34
+ */
35
+ use_case_id?: string;
36
+ }
37
+ export interface SendToListResult {
38
+ id: string;
39
+ /**
40
+ * `"partial"` and a non-zero `failedCount` are a 200 — a list send that got
41
+ * some mail out is not an HTTP failure. Check this field; do not read a 2xx
42
+ * as "everyone received it".
43
+ */
44
+ status: "sent" | "partial" | "failed";
45
+ sentCount: number;
46
+ skippedCount: number;
47
+ failedCount: number;
48
+ failures: {
49
+ email: string;
50
+ error: string;
51
+ }[];
52
+ listId: string;
53
+ }
54
+ export interface SendToListInput {
55
+ listId: string;
56
+ subject: string;
57
+ htmlContent: string;
58
+ textContent?: string;
59
+ fromEmail?: string;
60
+ fromName?: string;
61
+ replyTo?: string;
62
+ tags?: string[];
63
+ use_case_id?: string;
64
+ }
65
+ export interface ScheduleEmailInput extends Omit<SendEmailInput, "templateId" | "variables"> {
66
+ /**
67
+ * An instant, not a wall-clock guess: the offset is mandatory (`Z` or
68
+ * `±HH:MM`). The API rejects a bare local time rather than guessing a zone.
69
+ */
70
+ scheduled_for: string;
71
+ }
72
+ export interface ScheduledEmail {
73
+ id: string;
74
+ /** The queued send input, as submitted. */
75
+ emailData: unknown;
76
+ scheduledFor: string;
77
+ status: string;
78
+ retryCount: number;
79
+ maxRetries: number;
80
+ result: unknown;
81
+ error: string | null;
82
+ createdAt: string;
83
+ sentAt: string | null;
84
+ }
85
+ export type SuppressionReason = "hard_bounce" | "spam_complaint" | "unsubscribe" | "manual";
86
+ export interface SuppressionCheck {
87
+ suppressed: boolean;
88
+ canSend: boolean;
89
+ /** Absent when nothing is suppressed. */
90
+ reason?: SuppressionReason;
91
+ }
92
+ export interface UseCasePreference {
93
+ useCaseId: string;
94
+ name: string;
95
+ description: string | null;
96
+ category: string | null;
97
+ subscribed: boolean;
98
+ }
99
+ export interface RecipientPreferences {
100
+ email: string;
101
+ unsubscribedAll: boolean;
102
+ deliverable: boolean;
103
+ useCases: UseCasePreference[];
104
+ }
105
+ /** Accepted by every list method. The server clamps `perPage` to 1–100 (default 25). */
106
+ export interface PageOptions {
107
+ page?: number;
108
+ perPage?: number;
109
+ }
110
+ /** A list response with the envelope's `pagination` kept instead of discarded. */
111
+ export interface Paginated<T> {
112
+ data: T[];
113
+ pagination: V1Pagination;
114
+ }
115
+ export interface TemplateVariable {
116
+ name: string;
117
+ type: string;
118
+ required?: boolean;
119
+ default?: string;
120
+ }
121
+ export interface Template {
122
+ id: string;
123
+ projectId: string | null;
124
+ name: string;
125
+ subject: string;
126
+ htmlTemplate: string | null;
127
+ textTemplate: string | null;
128
+ variables: unknown;
129
+ category: string | null;
130
+ version: number | null;
131
+ isActive: boolean | null;
132
+ syncStatus: string | null;
133
+ providerTemplateRef: string | null;
134
+ createdAt: string;
135
+ updatedAt: string;
136
+ }
137
+ export interface CreateTemplateInput {
138
+ name: string;
139
+ subject: string;
140
+ htmlTemplate?: string;
141
+ textTemplate?: string;
142
+ variables?: TemplateVariable[];
143
+ category?: string;
144
+ }
145
+ export type UpdateTemplateInput = Partial<CreateTemplateInput>;
146
+ export interface RenderedTemplate {
147
+ html: string | null;
148
+ text: string | null;
149
+ subject: string;
150
+ }
151
+ export interface SubscriberList {
152
+ id: string;
153
+ orgId: string;
154
+ name: string;
155
+ description: string | null;
156
+ unsubScope: string;
157
+ unsubHandler: string;
158
+ customUnsubHtml: string | null;
159
+ hostedUnsubConfig: unknown;
160
+ storageTier: string;
161
+ primaryProviderId: string | null;
162
+ providerListIds: unknown;
163
+ campaignId: string | null;
164
+ syncStatus: string;
165
+ lastSyncedAt: string | null;
166
+ subscriberCount: number;
167
+ suppressedCount: number;
168
+ createdAt: string;
169
+ updatedAt: string;
170
+ }
171
+ export interface CreateListInput {
172
+ name: string;
173
+ description?: string;
174
+ unsubScope?: "list" | "global";
175
+ unsubHandler?: "provider" | "hosted" | "custom_html";
176
+ storageTier?: "provider" | "byo_database" | "local";
177
+ }
178
+ export interface NewContact {
179
+ email: string;
180
+ firstName?: string;
181
+ lastName?: string;
182
+ customFields?: Record<string, string>;
183
+ }
184
+ export interface NewContactWithLists extends NewContact {
185
+ listIds?: string[];
186
+ }
187
+ export interface AddListContactsResult {
188
+ listId: string;
189
+ tier: "local" | "provider";
190
+ provider: string;
191
+ submitted: number;
192
+ added: number;
193
+ alreadySubscribed: number;
194
+ status: "added" | "already_subscribed" | "processing";
195
+ }
196
+ export interface AggregatedContact {
197
+ email: string;
198
+ firstName?: string;
199
+ lastName?: string;
200
+ lists: string[];
201
+ providers: string[];
202
+ status: "subscribed" | "unsubscribed" | "pending";
203
+ }
204
+ export interface UpsertContactsResult {
205
+ submitted: number;
206
+ lists: AddListContactsResult[];
207
+ providerUpserted: number;
208
+ provider: string | null;
209
+ queued: boolean;
210
+ }
211
+ export interface UpdateContactInput {
212
+ email: string;
213
+ firstName?: string | null;
214
+ lastName?: string | null;
215
+ customFields?: Record<string, string>;
216
+ }
217
+ export interface UpdateContactResult {
218
+ email: string;
219
+ localMembershipsUpdated: number;
220
+ provider: string | null;
221
+ }
222
+ export interface Sender {
223
+ id: string;
224
+ name: string;
225
+ fromEmail: string;
226
+ fromName: string | null;
227
+ replyToEmail: string | null;
228
+ provider: string | null;
229
+ providerSenderId: string | null;
230
+ priority: number | null;
231
+ isDefault: boolean | null;
232
+ isActive: boolean | null;
233
+ isVerified: boolean | null;
234
+ verificationStatus: string | null;
235
+ createdAt: string;
236
+ updatedAt: string;
237
+ }
238
+ export interface CreateSenderInput {
239
+ name: string;
240
+ fromEmail: string;
241
+ fromName?: string;
242
+ replyToEmail?: string;
243
+ provider?: string;
244
+ providerSenderId?: string;
245
+ priority?: number;
246
+ isDefault?: boolean;
247
+ }
248
+ export type UpdateSenderInput = Partial<CreateSenderInput>;
249
+ export interface DnsRecord {
250
+ type: "TXT" | "CNAME" | "MX";
251
+ host: string;
252
+ value: string;
253
+ ttl?: number;
254
+ priority?: number;
255
+ }
256
+ export interface ProviderVerification {
257
+ id: string;
258
+ providerId: string;
259
+ providerType: string;
260
+ providerDisplayName: string;
261
+ verificationStatus: string;
262
+ dnsRecords: DnsRecord[];
263
+ dnsRecordStatuses: {
264
+ record: DnsRecord;
265
+ found: boolean;
266
+ actualValues: string[];
267
+ }[];
268
+ lastCheckedAt: string | null;
269
+ verifiedAt: string | null;
270
+ providerDomainId: string | null;
271
+ providerRegistrationStatus: string;
272
+ providerRegistrationResponse: unknown;
273
+ providerVerificationStatus: string;
274
+ }
275
+ export interface Domain {
276
+ id: string;
277
+ orgId: string;
278
+ /** Project the domain is attributed to — a domain is an org-level asset. */
279
+ projectId: string;
280
+ domain: string;
281
+ verificationStatus: string;
282
+ createdAt: string;
283
+ updatedAt: string;
284
+ providerVerifications: ProviderVerification[];
285
+ /** The four below only appear on the LIST response, not single-domain reads. */
286
+ inboxDomain?: boolean;
287
+ useCases?: {
288
+ id: string;
289
+ name: string;
290
+ slug: string | null;
291
+ projectSlug: string;
292
+ }[];
293
+ mxStatus?: string;
294
+ mxRecords?: DnsRecord[];
295
+ }
296
+ export interface DomainDnsRecords {
297
+ domainId: string;
298
+ domain: string;
299
+ providers: {
300
+ providerId: string;
301
+ providerType: string;
302
+ providerDisplayName: string;
303
+ records: DnsRecord[];
304
+ /** Keyed `"<type>:<host>"`, e.g. `"CNAME:em123.example.com"`. */
305
+ explanations: Record<string, string>;
306
+ }[];
307
+ }
308
+ export type SuppressionSource = "provider" | "user" | "system" | "import";
309
+ export interface Suppression {
310
+ id: string;
311
+ orgId: string;
312
+ email: string;
313
+ reason: SuppressionReason;
314
+ source: SuppressionSource;
315
+ providerId: string | null;
316
+ useCaseId: string | null;
317
+ providerSyncStatus: string | null;
318
+ isActive: boolean;
319
+ createdAt: string;
320
+ deactivatedAt: string | null;
321
+ deactivatedBy: string | null;
322
+ deactivatedByName: string | null;
323
+ deactivationReason: string | null;
324
+ }
325
+ export interface ListSuppressionsOptions extends PageOptions {
326
+ reason?: SuppressionReason;
327
+ source?: SuppressionSource;
328
+ isActive?: boolean;
329
+ /** Substring match on the email column. */
330
+ search?: string;
331
+ }
332
+ export interface AddSuppressionsInput {
333
+ /** 1–1000 addresses per request; the server rejects more. */
334
+ emails: string[];
335
+ /** Default `"account"`. `"use_case"` requires `use_case_id`; `use_case_id` with `"account"` is a 400. */
336
+ scope?: "account" | "use_case";
337
+ use_case_id?: string;
338
+ /** Default `"unsubscribe"` — the only reason that queues provider sync. */
339
+ reason?: SuppressionReason;
340
+ }
341
+ export interface AddSuppressionsResult {
342
+ inserted: number;
343
+ duplicates: number;
344
+ invalid: number;
345
+ provider_sync: "queued" | "skipped";
346
+ }
347
+ export interface NevarMailOptions {
348
+ /**
349
+ * A REST API key (`nvm_api_live_…` / `nvm_api_test_…`). An MCP key is
350
+ * rejected here rather than at first send: the surfaces are disjoint, and
351
+ * the server's answer is a 403 KEY_TYPE_MISMATCH that reads like an auth bug.
352
+ */
353
+ apiKey: string;
354
+ /** Defaults to the hosted API. */
355
+ baseUrl?: string;
356
+ /** Per-request timeout in ms. Default 30_000. */
357
+ timeoutMs?: number;
358
+ /** Extra attempts after the first, for transient failures only. Default 2. */
359
+ maxRetries?: number;
360
+ /** Injectable for tests and for runtimes with a non-global fetch. */
361
+ fetch?: typeof globalThis.fetch;
362
+ }
363
+ export interface RequestOptions {
364
+ query?: Record<string, string | number | boolean | undefined>;
365
+ body?: unknown;
366
+ signal?: AbortSignal;
367
+ }
368
+ export declare class NevarMail {
369
+ #private;
370
+ readonly baseUrl: string;
371
+ /** Derived from the key prefix, not configured — a mismatch is not possible. */
372
+ readonly mode: "live" | "test" | "unknown";
373
+ constructor(options: NevarMailOptions);
374
+ /**
375
+ * Every method below is one line over this. Public because the named methods
376
+ * do not cover all v1 routes — reach for this for the rest rather than
377
+ * hand-rolling a second client next to this one.
378
+ *
379
+ * Returns the unwrapped `data` from the v1 envelope. Throws on any non-2xx.
380
+ */
381
+ request<T>(method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE", path: string, options?: RequestOptions): Promise<T>;
382
+ /**
383
+ * Like `request`, but keeps the envelope's `pagination` — for the list
384
+ * routes, where dropping it would make `total` unknowable to the caller.
385
+ */
386
+ requestPaginated<T>(method: "GET" | "POST" | "PUT" | "PATCH" | "DELETE", path: string, options?: RequestOptions): Promise<Paginated<T>>;
387
+ /** POST /api/v1/email/send — one transactional message. */
388
+ sendEmail(input: SendEmailInput): Promise<EmailResult>;
389
+ /** POST /api/v1/email/send-to-list — one message to every contact on a list. */
390
+ sendEmailToList(input: SendToListInput): Promise<SendToListResult>;
391
+ /** POST /api/v1/email/schedule — queue a send for a future instant. */
392
+ scheduleEmail(input: ScheduleEmailInput): Promise<ScheduledEmail>;
393
+ /** GET /api/v1/email/schedule — the org's scheduled sends, newest first. */
394
+ listScheduledEmails(): Promise<ScheduledEmail[]>;
395
+ /** DELETE /api/v1/email/schedule/{id} — 409 SCHEDULE_NOT_CANCELLABLE once it has fired. */
396
+ cancelScheduledEmail(id: string): Promise<{
397
+ cancelled: boolean;
398
+ }>;
399
+ /**
400
+ * GET /api/v1/suppressions/check — would a send to this address be blocked?
401
+ * Omitting `useCaseId` is the strict answer: every active suppression counts.
402
+ */
403
+ checkSuppression(email: string, useCaseId?: string): Promise<SuppressionCheck>;
404
+ /** GET /api/v1/preferences — one recipient's per-category subscriptions. */
405
+ getPreferences(email: string): Promise<RecipientPreferences>;
406
+ /**
407
+ * PUT /api/v1/preferences — a COMPLETE set, not a delta: any suppressable
408
+ * category missing from `subscribedUseCaseIds` is treated as opted out.
409
+ */
410
+ setPreferences(email: string, subscribedUseCaseIds: string[]): Promise<RecipientPreferences>;
411
+ /** GET /api/v1/templates — paged; the route ignores search/category filters today. */
412
+ listTemplates(options?: PageOptions): Promise<Paginated<Template>>;
413
+ /** POST /api/v1/templates */
414
+ createTemplate(input: CreateTemplateInput): Promise<Template>;
415
+ /** GET /api/v1/templates/{id} — 404 NOT_FOUND. */
416
+ getTemplate(id: string): Promise<Template>;
417
+ /** PATCH /api/v1/templates/{id} — a partial update; the route has no PUT. */
418
+ updateTemplate(id: string, input: UpdateTemplateInput): Promise<Template>;
419
+ /**
420
+ * DELETE /api/v1/templates/{id} — an unknown id is NOT a 404: the route
421
+ * answers 200 `{ deleted: false }`. Check the flag, not just the resolution.
422
+ */
423
+ deleteTemplate(id: string): Promise<{
424
+ deleted: boolean;
425
+ }>;
426
+ /**
427
+ * POST /api/v1/templates/{id}/render — the body IS the variables map, with
428
+ * no wrapper key. Unknown template: 404 NOT_FOUND.
429
+ */
430
+ renderTemplate(id: string, variables?: Record<string, unknown>): Promise<RenderedTemplate>;
431
+ /** GET /api/v1/lists — paged. */
432
+ listLists(options?: PageOptions): Promise<Paginated<SubscriberList>>;
433
+ /** POST /api/v1/lists — 409 DUPLICATE_NAME on a name the org already uses. */
434
+ createList(input: CreateListInput): Promise<SubscriberList>;
435
+ /** GET /api/v1/lists/{id} — the v1 surface has no list update/delete routes. */
436
+ getList(id: string): Promise<SubscriberList>;
437
+ /**
438
+ * POST /api/v1/lists/{id}/contacts — one contact or a batch (max 1000).
439
+ * 404 LIST_NOT_FOUND; 422 LIST_NOT_SYNCED when the provider copy is behind.
440
+ */
441
+ addListContacts(listId: string, contacts: NewContact | NewContact[]): Promise<AddListContactsResult>;
442
+ /** GET /api/v1/contacts — paged; `q` is a substring search. */
443
+ listContacts(options?: PageOptions & {
444
+ q?: string;
445
+ }): Promise<Paginated<AggregatedContact>>;
446
+ /**
447
+ * POST /api/v1/contacts — upsert one contact or a batch (max 1000),
448
+ * optionally into lists via `listIds`. No `listIds` and no marketing
449
+ * provider configured: 404 NO_MARKETING_PROVIDER.
450
+ */
451
+ upsertContacts(contacts: NewContactWithLists | NewContactWithLists[]): Promise<UpsertContactsResult>;
452
+ /** PATCH /api/v1/contacts — needs at least one of firstName/lastName/customFields. */
453
+ updateContact(input: UpdateContactInput): Promise<UpdateContactResult>;
454
+ /** DELETE /api/v1/contacts?email=… */
455
+ deleteContact(email: string): Promise<{
456
+ deleted: true;
457
+ email: string;
458
+ localMembershipsRemoved: number;
459
+ }>;
460
+ /** GET /api/v1/senders — paged. */
461
+ listSenders(options?: PageOptions): Promise<Paginated<Sender>>;
462
+ /** POST /api/v1/senders */
463
+ createSender(input: CreateSenderInput): Promise<Sender>;
464
+ /** GET /api/v1/senders/{id} — 404 NOT_FOUND. */
465
+ getSender(id: string): Promise<Sender>;
466
+ /** PATCH /api/v1/senders/{id} — a partial update; the route has no PUT. */
467
+ updateSender(id: string, input: UpdateSenderInput): Promise<Sender>;
468
+ /** DELETE /api/v1/senders/{id} — 404 NOT_FOUND. */
469
+ deleteSender(id: string): Promise<{
470
+ deleted: boolean;
471
+ }>;
472
+ /** GET /api/v1/domains — paged; list rows carry extras single reads do not. */
473
+ listDomains(options?: PageOptions): Promise<Paginated<Domain>>;
474
+ /**
475
+ * POST /api/v1/domains — 409 DUPLICATE_DOMAIN if the org already has it.
476
+ * `projectId` is required when the org has more than one project
477
+ * (422 PROJECT_REQUIRED otherwise); 404 PROJECT_NOT_FOUND for a project
478
+ * outside the org.
479
+ */
480
+ createDomain(domain: string, options?: {
481
+ projectId?: string;
482
+ }): Promise<Domain>;
483
+ /** GET /api/v1/domains/{id} — 404 DOMAIN_NOT_FOUND. */
484
+ getDomain(id: string): Promise<Domain>;
485
+ /**
486
+ * DELETE /api/v1/domains/{id} — 403 MANAGED_ACCOUNT on NevarMail-managed
487
+ * orgs, whose provider config only NevarMail may change.
488
+ */
489
+ deleteDomain(id: string): Promise<{
490
+ deleted: true;
491
+ }>;
492
+ /** GET /api/v1/domains/{id}/dns-records — what to publish, with explanations. */
493
+ getDomainDnsRecords(id: string): Promise<DomainDnsRecords>;
494
+ /**
495
+ * POST /api/v1/domains/{id}/verify — triggers a DNS re-check and returns the
496
+ * domain with its updated verification state (a 200, not a 202).
497
+ */
498
+ verifyDomain(id: string): Promise<Domain>;
499
+ /** GET /api/v1/suppressions — paged, newest first. */
500
+ listSuppressions(options?: ListSuppressionsOptions): Promise<Paginated<Suppression>>;
501
+ /** POST /api/v1/suppressions — bulk add; see AddSuppressionsInput for the scope rules. */
502
+ addSuppressions(input: AddSuppressionsInput): Promise<AddSuppressionsResult>;
503
+ }
504
+ export default NevarMail;
package/dist/index.js ADDED
@@ -0,0 +1,379 @@
1
+ /*
2
+ Copyright (c) 2025 Bernier LLC
3
+
4
+ This file is licensed to the client under a limited-use license.
5
+ The client may use and modify this code *only within the scope of the project it was delivered for*.
6
+ Redistribution or use in other products or commercial offerings is not permitted without written consent from Bernier LLC.
7
+ */
8
+ /**
9
+ * @bernierllc/nevarmail — the official client for the NevarMail v1 API.
10
+ *
11
+ * The single design rule of this package: **every non-2xx throws.** The audit
12
+ * that produced it (GB-04) found three consumers with three hand-rolled
13
+ * clients, and the one in production swallowed every error — so an org may
14
+ * have been sending into a 403 for months with nobody noticing. A client that
15
+ * throws is the cheapest instrument against that whole class of failure.
16
+ *
17
+ * Zero dependencies: global `fetch` (Node 20+), no build-time codegen.
18
+ */
19
+ import { NevarMailError } from "./errors.js";
20
+ export { NevarMailError } from "./errors.js";
21
+ const DEFAULT_BASE_URL = "https://app.nevarmail.com";
22
+ const CANONICAL_KEY_RE = /^nvm_(api|mcp)_(live|test)_/;
23
+ const LEGACY_KEY_RE = /^nvm_(live|test)_/;
24
+ /**
25
+ * Transient means "the same request might work next time". A 4xx other than
26
+ * 429 is the caller's fault and will fail identically forever — retrying it
27
+ * turns one bad request into three.
28
+ */
29
+ function isRetryableStatus(status) {
30
+ return status === 429 || status >= 500;
31
+ }
32
+ function sleep(ms) {
33
+ return new Promise((resolve) => setTimeout(resolve, ms));
34
+ }
35
+ export class NevarMail {
36
+ baseUrl;
37
+ /** Derived from the key prefix, not configured — a mismatch is not possible. */
38
+ mode;
39
+ #apiKey;
40
+ #fetch;
41
+ #timeoutMs;
42
+ #maxRetries;
43
+ constructor(options) {
44
+ const key = options.apiKey?.trim();
45
+ if (!key) {
46
+ throw new NevarMailError("apiKey is required", {
47
+ status: 0,
48
+ code: "MISSING_API_KEY",
49
+ });
50
+ }
51
+ const canonical = CANONICAL_KEY_RE.exec(key);
52
+ if (canonical) {
53
+ if (canonical[1] === "mcp") {
54
+ throw new NevarMailError("This is an MCP key. The REST API needs an `nvm_api_…` key; MCP keys only work on the MCP endpoint.", { status: 0, code: "KEY_TYPE_MISMATCH" });
55
+ }
56
+ this.mode = canonical[2];
57
+ }
58
+ else if (LEGACY_KEY_RE.test(key)) {
59
+ // Pre-typed keys carry no surface segment; the server decides.
60
+ this.mode = key.startsWith("nvm_live_") ? "live" : "test";
61
+ }
62
+ else {
63
+ 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" });
64
+ }
65
+ this.#apiKey = key;
66
+ this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
67
+ this.#fetch = options.fetch ?? globalThis.fetch;
68
+ this.#timeoutMs = options.timeoutMs ?? 30_000;
69
+ this.#maxRetries = options.maxRetries ?? 2;
70
+ }
71
+ /**
72
+ * Every method below is one line over this. Public because the named methods
73
+ * do not cover all v1 routes — reach for this for the rest rather than
74
+ * hand-rolling a second client next to this one.
75
+ *
76
+ * Returns the unwrapped `data` from the v1 envelope. Throws on any non-2xx.
77
+ */
78
+ async request(method, path, options = {}) {
79
+ const parsed = await this.#send(method, path, options);
80
+ const envelope = parsed;
81
+ // 204s and any non-enveloped body pass through as-is.
82
+ return (envelope && typeof envelope === "object" && "data" in envelope
83
+ ? envelope.data
84
+ : parsed);
85
+ }
86
+ /**
87
+ * Like `request`, but keeps the envelope's `pagination` — for the list
88
+ * routes, where dropping it would make `total` unknowable to the caller.
89
+ */
90
+ async requestPaginated(method, path, options = {}) {
91
+ const parsed = (await this.#send(method, path, options));
92
+ const data = parsed?.data ?? [];
93
+ return {
94
+ data,
95
+ // Every wrapped list route sends pagination; synthesized only so a
96
+ // server that stops sending it degrades to a truthful single page.
97
+ pagination: parsed?.pagination ?? { page: 1, perPage: data.length, total: data.length },
98
+ };
99
+ }
100
+ /** The retry/throw/timeout policy, shared by both request forms. Returns the parsed body. */
101
+ async #send(method, path, options = {}) {
102
+ const url = new URL(`${this.baseUrl}${path}`);
103
+ for (const [k, v] of Object.entries(options.query ?? {})) {
104
+ if (v !== undefined)
105
+ url.searchParams.set(k, String(v));
106
+ }
107
+ let lastError;
108
+ for (let attempt = 0; attempt <= this.#maxRetries; attempt++) {
109
+ if (attempt > 0) {
110
+ // Retry-After wins over our backoff — the server knows its own window.
111
+ const backoff = lastError?.retryAfter
112
+ ? lastError.retryAfter * 1000
113
+ : 250 * 2 ** (attempt - 1) + Math.random() * 100;
114
+ await sleep(backoff);
115
+ }
116
+ let res;
117
+ try {
118
+ res = await this.#fetch(url, {
119
+ method,
120
+ headers: {
121
+ authorization: `Bearer ${this.#apiKey}`,
122
+ "content-type": "application/json",
123
+ accept: "application/json",
124
+ },
125
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
126
+ signal: options.signal ?? AbortSignal.timeout(this.#timeoutMs),
127
+ });
128
+ }
129
+ catch (cause) {
130
+ // No response at all: DNS, TCP, TLS, timeout. Transient unless the
131
+ // caller cancelled — see #abortedByCaller.
132
+ lastError = new NevarMailError(`Request to ${method} ${path} failed: ${cause?.message ?? "network error"}`, { status: 0, code: "NETWORK_ERROR", cause });
133
+ if (this.#abortedByCaller(options, cause))
134
+ throw lastError;
135
+ continue;
136
+ }
137
+ const requestId = res.headers.get("x-request-id");
138
+ // The body arrives after the headers, so it can still fail on its own:
139
+ // a dropped connection or a timeout mid-stream rejects here. Outside a
140
+ // try that would escape as a raw TypeError/AbortError and break the one
141
+ // guarantee this package makes — every failure is a NevarMailError.
142
+ let raw;
143
+ try {
144
+ raw = await res.text();
145
+ }
146
+ catch (cause) {
147
+ lastError = new NevarMailError(`Reading the response body of ${method} ${path} failed: ${cause?.message ?? "network error"}`, { status: res.status, code: "NETWORK_ERROR", requestId, cause });
148
+ if (this.#abortedByCaller(options, cause))
149
+ throw lastError;
150
+ continue;
151
+ }
152
+ let parsed = undefined;
153
+ if (raw) {
154
+ try {
155
+ parsed = JSON.parse(raw);
156
+ }
157
+ catch {
158
+ parsed = raw;
159
+ }
160
+ }
161
+ if (res.ok)
162
+ return parsed;
163
+ const envelope = (parsed ?? {});
164
+ const retryAfterHeader = res.headers.get("retry-after");
165
+ lastError = new NevarMailError(envelope.error ?? `${method} ${path} failed with ${res.status}`, {
166
+ status: res.status,
167
+ code: envelope.code ?? `HTTP_${res.status}`,
168
+ requestId: envelope.requestId ?? requestId,
169
+ retryAfter: retryAfterHeader ? Number(retryAfterHeader) : null,
170
+ body: parsed,
171
+ });
172
+ if (!isRetryableStatus(res.status))
173
+ throw lastError;
174
+ }
175
+ throw lastError;
176
+ }
177
+ /**
178
+ * A cancellation the caller asked for is not a transient failure: retrying
179
+ * re-uses the same already-aborted signal, so every attempt fails the same
180
+ * way and the only effect is delaying the rejection by the backoff. Our own
181
+ * timeout signal is a different matter — that one is worth another attempt.
182
+ */
183
+ #abortedByCaller(options, cause) {
184
+ if (options.signal?.aborted)
185
+ return true;
186
+ return options.signal !== undefined && cause?.name === "AbortError";
187
+ }
188
+ /** POST /api/v1/email/send — one transactional message. */
189
+ sendEmail(input) {
190
+ return this.request("POST", "/api/v1/email/send", { body: input });
191
+ }
192
+ /** POST /api/v1/email/send-to-list — one message to every contact on a list. */
193
+ sendEmailToList(input) {
194
+ return this.request("POST", "/api/v1/email/send-to-list", { body: input });
195
+ }
196
+ /** POST /api/v1/email/schedule — queue a send for a future instant. */
197
+ scheduleEmail(input) {
198
+ return this.request("POST", "/api/v1/email/schedule", { body: input });
199
+ }
200
+ /** GET /api/v1/email/schedule — the org's scheduled sends, newest first. */
201
+ listScheduledEmails() {
202
+ return this.request("GET", "/api/v1/email/schedule");
203
+ }
204
+ /** DELETE /api/v1/email/schedule/{id} — 409 SCHEDULE_NOT_CANCELLABLE once it has fired. */
205
+ cancelScheduledEmail(id) {
206
+ return this.request("DELETE", `/api/v1/email/schedule/${encodeURIComponent(id)}`);
207
+ }
208
+ /**
209
+ * GET /api/v1/suppressions/check — would a send to this address be blocked?
210
+ * Omitting `useCaseId` is the strict answer: every active suppression counts.
211
+ */
212
+ checkSuppression(email, useCaseId) {
213
+ return this.request("GET", "/api/v1/suppressions/check", {
214
+ query: { email, use_case_id: useCaseId },
215
+ });
216
+ }
217
+ /** GET /api/v1/preferences — one recipient's per-category subscriptions. */
218
+ getPreferences(email) {
219
+ return this.request("GET", "/api/v1/preferences", { query: { email } });
220
+ }
221
+ /**
222
+ * PUT /api/v1/preferences — a COMPLETE set, not a delta: any suppressable
223
+ * category missing from `subscribedUseCaseIds` is treated as opted out.
224
+ */
225
+ setPreferences(email, subscribedUseCaseIds) {
226
+ return this.request("PUT", "/api/v1/preferences", {
227
+ body: { email, subscribed_use_case_ids: subscribedUseCaseIds },
228
+ });
229
+ }
230
+ // ── Templates ──────────────────────────────────────────────────────────
231
+ /** GET /api/v1/templates — paged; the route ignores search/category filters today. */
232
+ listTemplates(options = {}) {
233
+ return this.requestPaginated("GET", "/api/v1/templates", { query: { ...options } });
234
+ }
235
+ /** POST /api/v1/templates */
236
+ createTemplate(input) {
237
+ return this.request("POST", "/api/v1/templates", { body: input });
238
+ }
239
+ /** GET /api/v1/templates/{id} — 404 NOT_FOUND. */
240
+ getTemplate(id) {
241
+ return this.request("GET", `/api/v1/templates/${encodeURIComponent(id)}`);
242
+ }
243
+ /** PATCH /api/v1/templates/{id} — a partial update; the route has no PUT. */
244
+ updateTemplate(id, input) {
245
+ return this.request("PATCH", `/api/v1/templates/${encodeURIComponent(id)}`, {
246
+ body: input,
247
+ });
248
+ }
249
+ /**
250
+ * DELETE /api/v1/templates/{id} — an unknown id is NOT a 404: the route
251
+ * answers 200 `{ deleted: false }`. Check the flag, not just the resolution.
252
+ */
253
+ deleteTemplate(id) {
254
+ return this.request("DELETE", `/api/v1/templates/${encodeURIComponent(id)}`);
255
+ }
256
+ /**
257
+ * POST /api/v1/templates/{id}/render — the body IS the variables map, with
258
+ * no wrapper key. Unknown template: 404 NOT_FOUND.
259
+ */
260
+ renderTemplate(id, variables = {}) {
261
+ return this.request("POST", `/api/v1/templates/${encodeURIComponent(id)}/render`, { body: variables });
262
+ }
263
+ // ── Lists & contacts ───────────────────────────────────────────────────
264
+ /** GET /api/v1/lists — paged. */
265
+ listLists(options = {}) {
266
+ return this.requestPaginated("GET", "/api/v1/lists", { query: { ...options } });
267
+ }
268
+ /** POST /api/v1/lists — 409 DUPLICATE_NAME on a name the org already uses. */
269
+ createList(input) {
270
+ return this.request("POST", "/api/v1/lists", { body: input });
271
+ }
272
+ /** GET /api/v1/lists/{id} — the v1 surface has no list update/delete routes. */
273
+ getList(id) {
274
+ return this.request("GET", `/api/v1/lists/${encodeURIComponent(id)}`);
275
+ }
276
+ /**
277
+ * POST /api/v1/lists/{id}/contacts — one contact or a batch (max 1000).
278
+ * 404 LIST_NOT_FOUND; 422 LIST_NOT_SYNCED when the provider copy is behind.
279
+ */
280
+ addListContacts(listId, contacts) {
281
+ return this.request("POST", `/api/v1/lists/${encodeURIComponent(listId)}/contacts`, { body: contacts });
282
+ }
283
+ /** GET /api/v1/contacts — paged; `q` is a substring search. */
284
+ listContacts(options = {}) {
285
+ return this.requestPaginated("GET", "/api/v1/contacts", {
286
+ query: { ...options },
287
+ });
288
+ }
289
+ /**
290
+ * POST /api/v1/contacts — upsert one contact or a batch (max 1000),
291
+ * optionally into lists via `listIds`. No `listIds` and no marketing
292
+ * provider configured: 404 NO_MARKETING_PROVIDER.
293
+ */
294
+ upsertContacts(contacts) {
295
+ return this.request("POST", "/api/v1/contacts", { body: contacts });
296
+ }
297
+ /** PATCH /api/v1/contacts — needs at least one of firstName/lastName/customFields. */
298
+ updateContact(input) {
299
+ return this.request("PATCH", "/api/v1/contacts", { body: input });
300
+ }
301
+ /** DELETE /api/v1/contacts?email=… */
302
+ deleteContact(email) {
303
+ return this.request("DELETE", "/api/v1/contacts", { query: { email } });
304
+ }
305
+ // ── Senders ────────────────────────────────────────────────────────────
306
+ /** GET /api/v1/senders — paged. */
307
+ listSenders(options = {}) {
308
+ return this.requestPaginated("GET", "/api/v1/senders", { query: { ...options } });
309
+ }
310
+ /** POST /api/v1/senders */
311
+ createSender(input) {
312
+ return this.request("POST", "/api/v1/senders", { body: input });
313
+ }
314
+ /** GET /api/v1/senders/{id} — 404 NOT_FOUND. */
315
+ getSender(id) {
316
+ return this.request("GET", `/api/v1/senders/${encodeURIComponent(id)}`);
317
+ }
318
+ /** PATCH /api/v1/senders/{id} — a partial update; the route has no PUT. */
319
+ updateSender(id, input) {
320
+ return this.request("PATCH", `/api/v1/senders/${encodeURIComponent(id)}`, {
321
+ body: input,
322
+ });
323
+ }
324
+ /** DELETE /api/v1/senders/{id} — 404 NOT_FOUND. */
325
+ deleteSender(id) {
326
+ return this.request("DELETE", `/api/v1/senders/${encodeURIComponent(id)}`);
327
+ }
328
+ // ── Domains ────────────────────────────────────────────────────────────
329
+ /** GET /api/v1/domains — paged; list rows carry extras single reads do not. */
330
+ listDomains(options = {}) {
331
+ return this.requestPaginated("GET", "/api/v1/domains", { query: { ...options } });
332
+ }
333
+ /**
334
+ * POST /api/v1/domains — 409 DUPLICATE_DOMAIN if the org already has it.
335
+ * `projectId` is required when the org has more than one project
336
+ * (422 PROJECT_REQUIRED otherwise); 404 PROJECT_NOT_FOUND for a project
337
+ * outside the org.
338
+ */
339
+ createDomain(domain, options = {}) {
340
+ return this.request("POST", "/api/v1/domains", {
341
+ body: options.projectId ? { domain, projectId: options.projectId } : { domain },
342
+ });
343
+ }
344
+ /** GET /api/v1/domains/{id} — 404 DOMAIN_NOT_FOUND. */
345
+ getDomain(id) {
346
+ return this.request("GET", `/api/v1/domains/${encodeURIComponent(id)}`);
347
+ }
348
+ /**
349
+ * DELETE /api/v1/domains/{id} — 403 MANAGED_ACCOUNT on NevarMail-managed
350
+ * orgs, whose provider config only NevarMail may change.
351
+ */
352
+ deleteDomain(id) {
353
+ return this.request("DELETE", `/api/v1/domains/${encodeURIComponent(id)}`);
354
+ }
355
+ /** GET /api/v1/domains/{id}/dns-records — what to publish, with explanations. */
356
+ getDomainDnsRecords(id) {
357
+ return this.request("GET", `/api/v1/domains/${encodeURIComponent(id)}/dns-records`);
358
+ }
359
+ /**
360
+ * POST /api/v1/domains/{id}/verify — triggers a DNS re-check and returns the
361
+ * domain with its updated verification state (a 200, not a 202).
362
+ */
363
+ verifyDomain(id) {
364
+ return this.request("POST", `/api/v1/domains/${encodeURIComponent(id)}/verify`);
365
+ }
366
+ // ── Suppressions ───────────────────────────────────────────────────────
367
+ /** GET /api/v1/suppressions — paged, newest first. */
368
+ listSuppressions(options = {}) {
369
+ const { isActive, ...rest } = options;
370
+ return this.requestPaginated("GET", "/api/v1/suppressions", {
371
+ query: { ...rest, is_active: isActive },
372
+ });
373
+ }
374
+ /** POST /api/v1/suppressions — bulk add; see AddSuppressionsInput for the scope rules. */
375
+ addSuppressions(input) {
376
+ return this.request("POST", "/api/v1/suppressions", { body: input });
377
+ }
378
+ }
379
+ export default NevarMail;
package/package.json CHANGED
@@ -1 +1,65 @@
1
- {"name":"@bernierllc/nevarmail","version":"0.0.0","description":"placeholder","license":"MIT","publishConfig":{"access":"public"}}
1
+ {
2
+ "name": "@bernierllc/nevarmail",
3
+ "version": "0.4.0",
4
+ "description": "Official client for the NevarMail v1 API. Typed, retries 429/5xx, throws NevarMailError on every non-2xx.",
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
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "engines": {
20
+ "node": ">=20.0.0"
21
+ },
22
+ "keywords": [
23
+ "nevarmail",
24
+ "email",
25
+ "esp",
26
+ "transactional-email",
27
+ "sdk",
28
+ "api-client",
29
+ "bernierllc"
30
+ ],
31
+ "author": "Bernier LLC",
32
+ "license": "MIT",
33
+ "repository": {
34
+ "type": "git",
35
+ "url": "https://github.com/bernierllc/tools",
36
+ "directory": "packages/core/nevarmail"
37
+ },
38
+ "publishConfig": {
39
+ "access": "public",
40
+ "registry": "https://registry.npmjs.org/"
41
+ },
42
+ "devDependencies": {
43
+ "@jest/globals": "^29.7.0",
44
+ "@types/jest": "^29.5.14",
45
+ "@types/node": "^20.0.0",
46
+ "@typescript-eslint/eslint-plugin": "^8.38.0",
47
+ "@typescript-eslint/parser": "^8.38.0",
48
+ "eslint": "^8.0.0",
49
+ "jest": "^29.5.0",
50
+ "rimraf": "^5.0.0",
51
+ "ts-jest": "^29.4.0",
52
+ "typescript": "^5.5.0"
53
+ },
54
+ "scripts": {
55
+ "build": "tsc -p tsconfig.json",
56
+ "dev": "tsc -p tsconfig.json --watch",
57
+ "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
58
+ "test:run": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
59
+ "test:watch": "node --experimental-vm-modules node_modules/jest/bin/jest.js --watch",
60
+ "test:coverage": "node --experimental-vm-modules node_modules/jest/bin/jest.js --coverage",
61
+ "lint": "eslint src --ext .ts",
62
+ "lint:fix": "eslint src --ext .ts --fix",
63
+ "clean": "rimraf dist"
64
+ }
65
+ }