@mailermine/node 1.0.0 → 1.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/dist/index.cjs CHANGED
@@ -3,9 +3,11 @@
3
3
  var crypto = require('crypto');
4
4
 
5
5
  // src/constants.ts
6
- var VERSION = "1.0.0";
6
+ var VERSION = "1.1.0";
7
7
  var DEFAULT_BASE_URL = "https://mailermine.com/api/v1";
8
8
  var DEFAULT_TIMEOUT_MS = 3e4;
9
+ var DEFAULT_MAX_RETRIES = 2;
10
+ var DEFAULT_MAX_RETRY_DELAY_MS = 3e4;
9
11
  var DEFAULT_USER_AGENT = `mailermine-node/${VERSION}`;
10
12
 
11
13
  // src/config/index.ts
@@ -14,12 +16,22 @@ var Configuration = class _Configuration {
14
16
  baseUrl;
15
17
  timeout;
16
18
  userAgent;
19
+ maxRetries;
20
+ maxRetryDelay;
17
21
  fetchApi;
18
22
  constructor(options) {
19
23
  this.apiKey = normalizeApiKey(options.apiKey);
20
24
  this.baseUrl = normalizeBaseUrl(options.baseUrl ?? DEFAULT_BASE_URL);
21
25
  this.timeout = normalizeTimeout(options.timeout ?? DEFAULT_TIMEOUT_MS);
22
26
  this.userAgent = normalizeUserAgent(options.userAgent ?? DEFAULT_USER_AGENT);
27
+ this.maxRetries = normalizeNonNegativeInteger(
28
+ options.maxRetries ?? DEFAULT_MAX_RETRIES,
29
+ "maxRetries"
30
+ );
31
+ this.maxRetryDelay = normalizeNonNegativeInteger(
32
+ options.maxRetryDelay ?? DEFAULT_MAX_RETRY_DELAY_MS,
33
+ "maxRetryDelay"
34
+ );
23
35
  if (options.fetchApi !== void 0) {
24
36
  this.fetchApi = options.fetchApi;
25
37
  }
@@ -41,7 +53,9 @@ var Configuration = class _Configuration {
41
53
  apiKey: this.apiKey,
42
54
  baseUrl: this.baseUrl,
43
55
  timeout: this.timeout,
44
- userAgent: this.userAgent
56
+ userAgent: this.userAgent,
57
+ maxRetries: this.maxRetries,
58
+ maxRetryDelay: this.maxRetryDelay
45
59
  };
46
60
  if (this.fetchApi !== void 0) {
47
61
  return { ...snapshot, fetchApi: this.fetchApi };
@@ -49,6 +63,12 @@ var Configuration = class _Configuration {
49
63
  return snapshot;
50
64
  }
51
65
  };
66
+ function normalizeNonNegativeInteger(value, name) {
67
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 0) {
68
+ throw new TypeError(`MailerMine Configuration ${name} must be a non-negative integer.`);
69
+ }
70
+ return value;
71
+ }
52
72
  function normalizeApiKey(apiKey) {
53
73
  if (typeof apiKey !== "string" || apiKey.trim() === "") {
54
74
  throw new TypeError("MailerMine Configuration requires a non-empty apiKey string.");
@@ -86,7 +106,7 @@ function normalizeUserAgent(userAgent) {
86
106
  }
87
107
 
88
108
  // generated/src/runtime.ts
89
- var BASE_PATH = "http://127.0.0.1:8000/api/v1".replace(/\/+$/, "");
109
+ var BASE_PATH = "https://mailermine.com/api/v1".replace(/\/+$/, "");
90
110
  var Configuration2 = class {
91
111
  constructor(configuration = {}) {
92
112
  this.configuration = configuration;
@@ -1017,6 +1037,9 @@ var EmailsApi = class extends BaseAPI {
1017
1037
  const queryParameters = {};
1018
1038
  const headerParameters = {};
1019
1039
  headerParameters["Content-Type"] = "application/json";
1040
+ if (requestParameters["idempotencyKey"] != null) {
1041
+ headerParameters["Idempotency-Key"] = String(requestParameters["idempotencyKey"]);
1042
+ }
1020
1043
  if (this.configuration && this.configuration.accessToken) {
1021
1044
  const token = this.configuration.accessToken;
1022
1045
  const tokenString = await token("bearerAuth", []);
@@ -1291,7 +1314,7 @@ var ProjectsApi = class extends BaseAPI {
1291
1314
  };
1292
1315
  }
1293
1316
  /**
1294
- * Soft-delete a project. Deletion is blocked while active domains, queued messages, or active campaigns remain. Required scope: `projects.write`.
1317
+ * Deactivate a project (status becomes inactive). Related data such as API keys, domains, and campaigns is kept. Deletion is blocked while queued messages or active campaigns remain. Required scope: `projects.write`.
1295
1318
  * Delete project
1296
1319
  */
1297
1320
  async deleteProjectRaw(requestParameters, initOverrides) {
@@ -1300,7 +1323,7 @@ var ProjectsApi = class extends BaseAPI {
1300
1323
  return new JSONApiResponse(response);
1301
1324
  }
1302
1325
  /**
1303
- * Soft-delete a project. Deletion is blocked while active domains, queued messages, or active campaigns remain. Required scope: `projects.write`.
1326
+ * Deactivate a project (status becomes inactive). Related data such as API keys, domains, and campaigns is kept. Deletion is blocked while queued messages or active campaigns remain. Required scope: `projects.write`.
1304
1327
  * Delete project
1305
1328
  */
1306
1329
  async deleteProject(requestParameters, initOverrides) {
@@ -3399,6 +3422,109 @@ var SuppressionsAdapter = class {
3399
3422
  }
3400
3423
  };
3401
3424
 
3425
+ // src/support/rate-limit.ts
3426
+ var RateLimitInfo = class _RateLimitInfo {
3427
+ constructor(limit, remaining, resetsAt) {
3428
+ this.limit = limit;
3429
+ this.remaining = remaining;
3430
+ this.resetsAt = resetsAt;
3431
+ }
3432
+ limit;
3433
+ remaining;
3434
+ resetsAt;
3435
+ /** Seconds until the window resets (0 when unknown or past). */
3436
+ get secondsUntilReset() {
3437
+ return this.resetsAt === null ? 0 : Math.max(0, Math.ceil((this.resetsAt.getTime() - Date.now()) / 1e3));
3438
+ }
3439
+ static fromHeaders(headers) {
3440
+ const limit = Number(headers.get("x-ratelimit-limit"));
3441
+ const remaining = Number(headers.get("x-ratelimit-remaining"));
3442
+ if (headers.get("x-ratelimit-limit") === null || headers.get("x-ratelimit-remaining") === null || !Number.isFinite(limit) || !Number.isFinite(remaining)) {
3443
+ return null;
3444
+ }
3445
+ const reset = Number(headers.get("x-ratelimit-reset"));
3446
+ return new _RateLimitInfo(
3447
+ limit,
3448
+ remaining,
3449
+ headers.get("x-ratelimit-reset") !== null && Number.isFinite(reset) ? new Date(reset * 1e3) : null
3450
+ );
3451
+ }
3452
+ };
3453
+
3454
+ // src/internal/http.ts
3455
+ var IDEMPOTENCY_HEADER = "Idempotency-Key";
3456
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]);
3457
+ var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([502, 503, 504]);
3458
+ function createResilientFetch(configuration, state) {
3459
+ const baseFetch = configuration.fetchApi ?? globalThis.fetch.bind(globalThis);
3460
+ return async (input, init) => {
3461
+ const method = (init?.method ?? "GET").toUpperCase();
3462
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
3463
+ const headers = new Headers(init?.headers);
3464
+ if (method === "POST" && !headers.has(IDEMPOTENCY_HEADER) && /\/emails\/?$/.test(new URL(url).pathname)) {
3465
+ headers.set(IDEMPOTENCY_HEADER, globalThis.crypto.randomUUID());
3466
+ }
3467
+ const replayable = SAFE_METHODS.has(method) || headers.has(IDEMPOTENCY_HEADER);
3468
+ const callerSignal = init?.signal ?? void 0;
3469
+ for (let attempt = 0; ; attempt++) {
3470
+ const timeoutSignal = AbortSignal.timeout(configuration.timeout);
3471
+ const signal = callerSignal ? AbortSignal.any([callerSignal, timeoutSignal]) : timeoutSignal;
3472
+ let response;
3473
+ try {
3474
+ response = await baseFetch(input, { ...init, headers, signal });
3475
+ } catch (error) {
3476
+ const callerAborted = callerSignal?.aborted === true;
3477
+ if (callerAborted || !replayable || attempt >= configuration.maxRetries) {
3478
+ throw error;
3479
+ }
3480
+ await sleep(backoff(attempt, configuration.maxRetryDelay), callerSignal);
3481
+ continue;
3482
+ }
3483
+ const rateLimit = RateLimitInfo.fromHeaders(response.headers);
3484
+ if (rateLimit) state.lastRateLimit = rateLimit;
3485
+ if (attempt >= configuration.maxRetries) return response;
3486
+ const status = response.status;
3487
+ let delay = null;
3488
+ if (status === 429) {
3489
+ const retryAfter = retryAfterMs(response.headers);
3490
+ if (retryAfter === null) delay = backoff(attempt, configuration.maxRetryDelay);
3491
+ else if (retryAfter <= configuration.maxRetryDelay) delay = retryAfter;
3492
+ } else if (RETRYABLE_STATUSES.has(status) && replayable) {
3493
+ delay = retryAfterMs(response.headers) ?? backoff(attempt, configuration.maxRetryDelay);
3494
+ delay = Math.min(delay, configuration.maxRetryDelay);
3495
+ }
3496
+ if (delay === null) return response;
3497
+ await response.body?.cancel().catch(() => void 0);
3498
+ await sleep(delay, callerSignal);
3499
+ }
3500
+ };
3501
+ }
3502
+ function backoff(attempt, max) {
3503
+ return Math.min(500 * 2 ** attempt + Math.floor(Math.random() * 250), max);
3504
+ }
3505
+ function retryAfterMs(headers) {
3506
+ const value = headers.get("retry-after");
3507
+ if (value === null || value.trim() === "") return null;
3508
+ const seconds = Number(value);
3509
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
3510
+ const date = Date.parse(value);
3511
+ return Number.isNaN(date) ? null : Math.max(0, date - Date.now());
3512
+ }
3513
+ function sleep(ms, signal) {
3514
+ if (ms <= 0) return Promise.resolve();
3515
+ return new Promise((resolve, reject) => {
3516
+ const timer = setTimeout(() => {
3517
+ signal?.removeEventListener("abort", onAbort);
3518
+ resolve();
3519
+ }, ms);
3520
+ const onAbort = () => {
3521
+ clearTimeout(timer);
3522
+ reject(signal?.reason ?? new Error("Aborted"));
3523
+ };
3524
+ signal?.addEventListener("abort", onAbort, { once: true });
3525
+ });
3526
+ }
3527
+
3402
3528
  // generated/src/apis/AudiencesApi.ts
3403
3529
  var AudiencesApi = class extends BaseAPI {
3404
3530
  /**
@@ -4648,7 +4774,7 @@ var CampaignsApi = class extends BaseAPI {
4648
4774
  };
4649
4775
  }
4650
4776
  /**
4651
- * Render the current campaign subject and bodies without sending. Required scope: `campaigns.read`.
4777
+ * Render the current campaign subject and bodies without sending. Requires an assigned template (`template_uuid` on create/update or via set-template). Returns HTTP 422 with `template` when no template is assigned. Required scope: `campaigns.read`.
4652
4778
  * Preview campaign
4653
4779
  */
4654
4780
  async previewCampaignRaw(requestParameters, initOverrides) {
@@ -4657,7 +4783,7 @@ var CampaignsApi = class extends BaseAPI {
4657
4783
  return new JSONApiResponse(response);
4658
4784
  }
4659
4785
  /**
4660
- * Render the current campaign subject and bodies without sending. Required scope: `campaigns.read`.
4786
+ * Render the current campaign subject and bodies without sending. Requires an assigned template (`template_uuid` on create/update or via set-template). Returns HTTP 422 with `template` when no template is assigned. Required scope: `campaigns.read`.
4661
4787
  * Preview campaign
4662
4788
  */
4663
4789
  async previewCampaign(requestParameters, initOverrides) {
@@ -7284,11 +7410,11 @@ function stripContentType(headers) {
7284
7410
  }
7285
7411
 
7286
7412
  // src/internal/generated-client.ts
7287
- function createInternalApis(configuration) {
7413
+ function createInternalApis(configuration, state = { lastRateLimit: null }) {
7288
7414
  const generated = new Configuration2({
7289
7415
  basePath: configuration.baseUrl,
7290
7416
  accessToken: configuration.apiKey,
7291
- fetchApi: createTimeoutFetch(configuration.timeout, configuration.fetchApi),
7417
+ fetchApi: createResilientFetch(configuration, state),
7292
7418
  headers: {
7293
7419
  Accept: "application/json",
7294
7420
  "User-Agent": configuration.userAgent
@@ -7311,8 +7437,11 @@ var EmailsAdapter = class {
7311
7437
  }
7312
7438
  sending;
7313
7439
  messages;
7314
- send(body) {
7315
- return this.sending.sendEmail({ sendEmailRequest: body });
7440
+ send(body, options = {}) {
7441
+ return this.sending.sendEmail({
7442
+ sendEmailRequest: body,
7443
+ ...options.idempotencyKey !== void 0 ? { idempotencyKey: options.idempotencyKey } : {}
7444
+ });
7316
7445
  }
7317
7446
  list(query) {
7318
7447
  return this.messages.listMessages(query);
@@ -7445,15 +7574,6 @@ var TemplatesAdapter = class {
7445
7574
  return this.api.deleteTemplate({ template: templateId });
7446
7575
  }
7447
7576
  };
7448
- function createTimeoutFetch(timeout, fetchApi) {
7449
- const baseFetch = fetchApi ?? globalThis.fetch.bind(globalThis);
7450
- return (input, init) => {
7451
- const timeoutSignal = AbortSignal.timeout(timeout);
7452
- const existingSignal = init?.signal;
7453
- const signal = existingSignal == null ? timeoutSignal : AbortSignal.any([existingSignal, timeoutSignal]);
7454
- return baseFetch(input, { ...init, signal });
7455
- };
7456
- }
7457
7577
 
7458
7578
  // src/support/responses.ts
7459
7579
  var Pagination = class {
@@ -7614,6 +7734,12 @@ var ApiError = class extends Error {
7614
7734
  status;
7615
7735
  body;
7616
7736
  name = "ApiError";
7737
+ /** Rate-limit state from the error response, when the API sent it. */
7738
+ rateLimit = null;
7739
+ /** Whether retrying the same request later may succeed (429 and 5xx). */
7740
+ get isRetryable() {
7741
+ return this.status === 429 || this.status >= 500;
7742
+ }
7617
7743
  };
7618
7744
  var AuthenticationError = class extends ApiError {
7619
7745
  name = "AuthenticationError";
@@ -7621,6 +7747,14 @@ var AuthenticationError = class extends ApiError {
7621
7747
  var PlanError = class extends ApiError {
7622
7748
  name = "PlanError";
7623
7749
  };
7750
+ var MissingScopeError = class extends PlanError {
7751
+ constructor(message, status, missingScopes, body, options) {
7752
+ super(message, status, body, options);
7753
+ this.missingScopes = missingScopes;
7754
+ }
7755
+ missingScopes;
7756
+ name = "MissingScopeError";
7757
+ };
7624
7758
  var NotFoundError = class extends ApiError {
7625
7759
  name = "NotFoundError";
7626
7760
  };
@@ -7653,51 +7787,61 @@ async function mapError(error) {
7653
7787
  if (error instanceof ResponseError) {
7654
7788
  const body = sanitizeValue(await readErrorBody(error.response));
7655
7789
  const record = toCamelRecord(body);
7656
- const message2 = getMessage(
7790
+ const message = getMessage(
7657
7791
  record,
7658
7792
  error.response.statusText || "MailerMine API request failed"
7659
7793
  );
7660
7794
  const status = error.response.status;
7795
+ const mapped = mapStatus(status, message, body, record, error.response.headers);
7796
+ mapped.rateLimit = RateLimitInfo.fromHeaders(error.response.headers);
7797
+ return mapped;
7798
+ }
7799
+ return mapTransportOrClientError(error);
7800
+ }
7801
+ function mapStatus(status, message, body, record, headers) {
7802
+ {
7661
7803
  switch (status) {
7662
7804
  case 401:
7663
- return new AuthenticationError(message2, status, body);
7664
- case 403:
7665
- return new PlanError(message2, status, body);
7805
+ return new AuthenticationError(message, status, body);
7806
+ case 403: {
7807
+ const missingScopes = getMissingScopes(record["errors"]);
7808
+ return missingScopes.length > 0 ? new MissingScopeError(message, status, missingScopes, body) : new PlanError(message, status, body);
7809
+ }
7666
7810
  case 404:
7667
- return new NotFoundError(message2, status, body);
7811
+ return new NotFoundError(message, status, body);
7668
7812
  case 422:
7669
- return new ValidationError(
7670
- message2,
7671
- status,
7672
- getValidationErrors(record["errors"]),
7673
- body
7674
- );
7813
+ return new ValidationError(message, status, getValidationErrors(record["errors"]), body);
7675
7814
  case 429:
7676
7815
  return new RateLimitError(
7677
- message2,
7816
+ message,
7678
7817
  status,
7679
- parseRetryAfter(error.response.headers.get("retry-after")),
7818
+ parseRetryAfter(headers.get("retry-after")),
7680
7819
  body
7681
7820
  );
7682
7821
  default:
7683
- return new ApiError(message2, status, body);
7822
+ return new ApiError(message, status, body);
7684
7823
  }
7685
7824
  }
7825
+ }
7826
+ function getMissingScopes(errors) {
7827
+ if (typeof errors !== "object" || errors === null || Array.isArray(errors)) return [];
7828
+ const scope = errors["scope"];
7829
+ const list = typeof scope === "string" ? [scope] : Array.isArray(scope) ? scope : [];
7830
+ return list.filter((value) => typeof value === "string" && value !== "");
7831
+ }
7832
+ function mapTransportOrClientError(error) {
7686
7833
  if (error instanceof RequiredError) {
7687
7834
  const field = sanitizeRequiredField(error.field);
7688
7835
  const message2 = field ? `The ${field} field is required.` : "A required field is missing.";
7689
- return new ValidationError(
7690
- message2,
7691
- 422,
7692
- field ? { [field]: [message2] } : {},
7693
- void 0
7694
- );
7836
+ return new ValidationError(message2, 422, field ? { [field]: [message2] } : {}, void 0);
7695
7837
  }
7696
7838
  if (error instanceof FetchError) {
7697
7839
  return new ApiError(getTransportMessage(error.cause), 0);
7698
7840
  }
7699
7841
  if (error instanceof ApiError) {
7700
- return cloneSdkError(error);
7842
+ const cloned = cloneSdkError(error);
7843
+ cloned.rateLimit = error.rateLimit;
7844
+ return cloned;
7701
7845
  }
7702
7846
  const message = error instanceof Error ? sanitizeText(error.message) : "Unknown MailerMine SDK error";
7703
7847
  return new ApiError(message, 0);
@@ -7716,9 +7860,7 @@ async function readErrorBody(response) {
7716
7860
  }
7717
7861
  function getMessage(record, fallback) {
7718
7862
  const value = record["message"] ?? record["error"];
7719
- return sanitizeText(
7720
- typeof value === "string" && value !== "" ? value : fallback
7721
- );
7863
+ return sanitizeText(typeof value === "string" && value !== "" ? value : fallback);
7722
7864
  }
7723
7865
  function getValidationErrors(value) {
7724
7866
  if (typeof value !== "object" || value === null || Array.isArray(value)) {
@@ -7746,24 +7888,17 @@ function cloneSdkError(error) {
7746
7888
  const message = sanitizeText(error.message);
7747
7889
  const body = sanitizeValue(error.body);
7748
7890
  if (error instanceof ValidationError) {
7749
- return new ValidationError(
7750
- message,
7751
- error.status,
7752
- getValidationErrors(error.errors),
7753
- body
7754
- );
7891
+ return new ValidationError(message, error.status, getValidationErrors(error.errors), body);
7755
7892
  }
7756
7893
  if (error instanceof RateLimitError) {
7757
- return new RateLimitError(
7758
- message,
7759
- error.status,
7760
- error.retryAfter,
7761
- body
7762
- );
7894
+ return new RateLimitError(message, error.status, error.retryAfter, body);
7763
7895
  }
7764
7896
  if (error instanceof AuthenticationError) {
7765
7897
  return new AuthenticationError(message, error.status, body);
7766
7898
  }
7899
+ if (error instanceof MissingScopeError) {
7900
+ return new MissingScopeError(message, error.status, [...error.missingScopes], body);
7901
+ }
7767
7902
  if (error instanceof PlanError) {
7768
7903
  return new PlanError(message, error.status, body);
7769
7904
  }
@@ -8885,14 +9020,23 @@ var Emails = class extends BaseResource {
8885
9020
  * text: 'Hello',
8886
9021
  * });
8887
9022
  * ```
9023
+ *
9024
+ * Pass `{ idempotencyKey }` to make retries from your own code safe:
9025
+ * the same key never sends twice.
8888
9026
  */
8889
- async send(input) {
9027
+ async send(input, options = {}) {
9028
+ const { idempotencyKey } = options;
9029
+ if (idempotencyKey !== void 0 && (typeof idempotencyKey !== "string" || idempotencyKey === "" || idempotencyKey.length > 255)) {
9030
+ throw new TypeError("idempotencyKey must be a non-empty string of at most 255 characters.");
9031
+ }
8890
9032
  return this.execute(async () => {
8891
9033
  const body = toGeneratedRequest({
8892
9034
  ...input,
8893
9035
  to: Array.isArray(input.to) ? [...input.to] : [input.to]
8894
9036
  });
8895
- return toResponse(await this.api.send(body));
9037
+ return toResponse(
9038
+ await this.api.send(body, idempotencyKey !== void 0 ? { idempotencyKey } : {})
9039
+ );
8896
9040
  });
8897
9041
  }
8898
9042
  /**
@@ -8905,17 +9049,13 @@ var Emails = class extends BaseResource {
8905
9049
  * Retrieve a single message by UUID.
8906
9050
  */
8907
9051
  async get(messageId) {
8908
- return this.execute(
8909
- async () => toResponse(await this.api.get(messageId))
8910
- );
9052
+ return this.execute(async () => toResponse(await this.api.get(messageId)));
8911
9053
  }
8912
9054
  /**
8913
9055
  * Retrieve lifecycle events for a single message.
8914
9056
  */
8915
9057
  async events(messageId) {
8916
- return this.execute(
8917
- async () => toCollection(await this.api.events(messageId))
8918
- );
9058
+ return this.execute(async () => toCollection(await this.api.events(messageId)));
8919
9059
  }
8920
9060
  };
8921
9061
 
@@ -9569,7 +9709,7 @@ var Suppressions = class extends BaseResource {
9569
9709
  );
9570
9710
  }
9571
9711
  };
9572
- var Webhooks = class extends BaseResource {
9712
+ var Webhooks = class _Webhooks extends BaseResource {
9573
9713
  /** @internal */
9574
9714
  constructor(api) {
9575
9715
  super();
@@ -9584,22 +9724,16 @@ var Webhooks = class extends BaseResource {
9584
9724
  }
9585
9725
  /** List webhook endpoints. */
9586
9726
  async list(options = {}) {
9587
- return this.execute(
9588
- async () => toCollection(await this.api.list(options))
9589
- );
9727
+ return this.execute(async () => toCollection(await this.api.list(options)));
9590
9728
  }
9591
9729
  /** Retrieve a webhook by UUID. */
9592
9730
  async get(webhookId) {
9593
- return this.execute(
9594
- async () => toResponse(await this.api.get(webhookId))
9595
- );
9731
+ return this.execute(async () => toResponse(await this.api.get(webhookId)));
9596
9732
  }
9597
9733
  /** Update a webhook endpoint. */
9598
9734
  async update(webhookId, input) {
9599
9735
  const body = Object.keys(input).length === 0 ? void 0 : toGeneratedRequest(input);
9600
- return this.execute(
9601
- async () => toResponse(await this.api.update(webhookId, body))
9602
- );
9736
+ return this.execute(async () => toResponse(await this.api.update(webhookId, body)));
9603
9737
  }
9604
9738
  /** Delete a webhook endpoint. */
9605
9739
  async delete(webhookId) {
@@ -9617,21 +9751,15 @@ var Webhooks = class extends BaseResource {
9617
9751
  }
9618
9752
  /** Rotate the signing secret. The new secret is returned only once. */
9619
9753
  async rotateSecret(webhookId) {
9620
- return this.execute(
9621
- async () => toResponse(await this.api.rotateSecret(webhookId))
9622
- );
9754
+ return this.execute(async () => toResponse(await this.api.rotateSecret(webhookId)));
9623
9755
  }
9624
9756
  /** Enable a webhook endpoint. */
9625
9757
  async enable(webhookId) {
9626
- return this.execute(
9627
- async () => toResponse(await this.api.enable(webhookId))
9628
- );
9758
+ return this.execute(async () => toResponse(await this.api.enable(webhookId)));
9629
9759
  }
9630
9760
  /** Disable a webhook endpoint. */
9631
9761
  async disable(webhookId) {
9632
- return this.execute(
9633
- async () => toResponse(await this.api.disable(webhookId))
9634
- );
9762
+ return this.execute(async () => toResponse(await this.api.disable(webhookId)));
9635
9763
  }
9636
9764
  /** List deliveries for a webhook. */
9637
9765
  async deliveries(webhookId, options = {}) {
@@ -9669,17 +9797,59 @@ var Webhooks = class extends BaseResource {
9669
9797
  }
9670
9798
  /** Retry one webhook delivery. */
9671
9799
  async retry(deliveryId) {
9672
- return this.execute(
9673
- async () => toResponse(await this.api.retry(deliveryId))
9674
- );
9800
+ return this.execute(async () => toResponse(await this.api.retry(deliveryId)));
9675
9801
  }
9676
- /** Verify a MailerMine HMAC-SHA256 webhook signature locally. */
9677
- static verify(payload, signature, secret) {
9678
- const expected = crypto.createHmac("sha256", secret).update(payload).digest("hex");
9679
- const normalized = signature.toLowerCase().startsWith("sha256=") ? signature.slice(7) : signature;
9802
+ /** Default maximum age, in seconds, of a signed webhook timestamp. */
9803
+ static DEFAULT_TOLERANCE_SECONDS = 300;
9804
+ /**
9805
+ * Verify a MailerMine webhook signature locally.
9806
+ *
9807
+ * MailerMine signs `{timestamp}.{rawBody}` with HMAC-SHA256 and sends the
9808
+ * timestamp in `X-MailerMine-Timestamp` and the signature in
9809
+ * `X-MailerMine-Signature` (`sha256=<hex>`). Pass the timestamp so the
9810
+ * signature matches and stale deliveries are rejected (replay protection).
9811
+ * Without a timestamp only a body-only signature is checked (legacy).
9812
+ * Prefer {@link Webhooks.verifyHeaders}.
9813
+ */
9814
+ static verify(payload, signature, secret, timestamp, toleranceSeconds = _Webhooks.DEFAULT_TOLERANCE_SECONDS) {
9815
+ if (!secret || !signature) return false;
9816
+ const normalized = signature.trim().toLowerCase().startsWith("sha256=") ? signature.trim().slice(7) : signature.trim();
9680
9817
  if (!/^[a-f\d]{64}$/i.test(normalized)) return false;
9818
+ let signed = payload;
9819
+ if (timestamp !== void 0 && timestamp !== null && timestamp !== "") {
9820
+ const seconds = Number(timestamp);
9821
+ if (!Number.isInteger(seconds)) return false;
9822
+ if (toleranceSeconds > 0 && Math.abs(Date.now() / 1e3 - seconds) > toleranceSeconds) {
9823
+ return false;
9824
+ }
9825
+ signed = `${seconds}.${payload}`;
9826
+ }
9827
+ const expected = crypto.createHmac("sha256", secret).update(signed).digest("hex");
9681
9828
  return crypto.timingSafeEqual(Buffer.from(expected, "hex"), Buffer.from(normalized, "hex"));
9682
9829
  }
9830
+ /**
9831
+ * Verify a webhook from its request headers (`X-MailerMine-Signature` and
9832
+ * `X-MailerMine-Timestamp`, falling back to legacy `X-Relay-*`).
9833
+ *
9834
+ * @example
9835
+ * ```ts
9836
+ * app.post('/hooks', express.raw({ type: 'application/json' }), (req, res) => {
9837
+ * if (!Webhooks.verifyHeaders(req.body.toString(), req.headers, secret)) return res.sendStatus(401);
9838
+ * });
9839
+ * ```
9840
+ */
9841
+ static verifyHeaders(payload, headers, secret, toleranceSeconds = _Webhooks.DEFAULT_TOLERANCE_SECONDS) {
9842
+ const read = (name) => {
9843
+ if (headers instanceof Headers) return headers.get(name);
9844
+ const key = Object.keys(headers).find((k) => k.toLowerCase() === name.toLowerCase());
9845
+ const value = key === void 0 ? void 0 : headers[key];
9846
+ return Array.isArray(value) ? value[0] ?? null : value ?? null;
9847
+ };
9848
+ const signature = read("x-mailermine-signature") ?? read("x-relay-signature");
9849
+ const timestamp = read("x-mailermine-timestamp") ?? read("x-relay-timestamp");
9850
+ if (!signature || !timestamp) return false;
9851
+ return _Webhooks.verify(payload, signature, secret, timestamp, toleranceSeconds);
9852
+ }
9683
9853
  };
9684
9854
  function normalizeDeliveryOptions(options) {
9685
9855
  return {
@@ -9701,6 +9871,7 @@ function normalizeNullableDate(value) {
9701
9871
  var MailerMine = class {
9702
9872
  configuration;
9703
9873
  apis;
9874
+ transport = { lastRateLimit: null };
9704
9875
  emailsResource;
9705
9876
  projectsResource;
9706
9877
  apiKeysResource;
@@ -9721,7 +9892,14 @@ var MailerMine = class {
9721
9892
  suppressionsResource;
9722
9893
  constructor(apiKeyOrOptions) {
9723
9894
  this.configuration = apiKeyOrOptions instanceof Configuration ? apiKeyOrOptions : Configuration.create(apiKeyOrOptions);
9724
- this.apis = createInternalApis(this.configuration);
9895
+ this.apis = createInternalApis(this.configuration, this.transport);
9896
+ }
9897
+ /**
9898
+ * Rate-limit state from the most recent API response (null until a
9899
+ * response carrying `X-RateLimit-*` headers has been received).
9900
+ */
9901
+ get rateLimit() {
9902
+ return this.transport.lastRateLimit;
9725
9903
  }
9726
9904
  /** Transactional email operations. */
9727
9905
  get emails() {
@@ -9806,6 +9984,47 @@ var MailerMine = class {
9806
9984
  }
9807
9985
  };
9808
9986
 
9987
+ // src/support/scopes.ts
9988
+ var Scopes = {
9989
+ EmailsSend: "emails.send",
9990
+ EmailsRead: "emails.read",
9991
+ TemplatesRead: "templates.read",
9992
+ TemplatesWrite: "templates.write",
9993
+ DomainsRead: "domains.read",
9994
+ DomainsWrite: "domains.write",
9995
+ ContactsRead: "contacts.read",
9996
+ ContactsWrite: "contacts.write",
9997
+ CampaignsRead: "campaigns.read",
9998
+ CampaignsWrite: "campaigns.write",
9999
+ AnalyticsRead: "analytics.read",
10000
+ BillingRead: "billing.read",
10001
+ ProjectsRead: "projects.read",
10002
+ ProjectsWrite: "projects.write",
10003
+ ApiKeysRead: "api_keys.read",
10004
+ ApiKeysWrite: "api_keys.write",
10005
+ WebhooksRead: "webhooks.read",
10006
+ WebhooksWrite: "webhooks.write",
10007
+ SuppressionsRead: "suppressions.read",
10008
+ SuppressionsWrite: "suppressions.write",
10009
+ EventsRead: "events.read",
10010
+ Admin: "admin"
10011
+ };
10012
+ var ScopePresets = {
10013
+ /** Send email only. */
10014
+ sendingOnly: [Scopes.EmailsSend],
10015
+ /** Send email and read delivery logs, events and analytics. */
10016
+ sendingAndLogs: [Scopes.EmailsSend, Scopes.EmailsRead, Scopes.EventsRead, Scopes.AnalyticsRead],
10017
+ /** Manage contacts and campaigns; read templates and analytics. */
10018
+ marketing: [
10019
+ Scopes.ContactsRead,
10020
+ Scopes.ContactsWrite,
10021
+ Scopes.CampaignsRead,
10022
+ Scopes.CampaignsWrite,
10023
+ Scopes.TemplatesRead,
10024
+ Scopes.AnalyticsRead
10025
+ ]
10026
+ };
10027
+
9809
10028
  exports.Analytics = Analytics;
9810
10029
  exports.ApiError = ApiError;
9811
10030
  exports.ApiKeys = ApiKeys;
@@ -9816,6 +10035,8 @@ exports.Collection = Collection;
9816
10035
  exports.Configuration = Configuration;
9817
10036
  exports.Contacts = Contacts;
9818
10037
  exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL;
10038
+ exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES;
10039
+ exports.DEFAULT_MAX_RETRY_DELAY_MS = DEFAULT_MAX_RETRY_DELAY_MS;
9819
10040
  exports.DEFAULT_TIMEOUT_MS = DEFAULT_TIMEOUT_MS;
9820
10041
  exports.DEFAULT_USER_AGENT = DEFAULT_USER_AGENT;
9821
10042
  exports.Domains = Domains;
@@ -9826,12 +10047,16 @@ exports.Imports = Imports;
9826
10047
  exports.Lists = Lists;
9827
10048
  exports.MailerMine = MailerMine;
9828
10049
  exports.Messages = Messages;
10050
+ exports.MissingScopeError = MissingScopeError;
9829
10051
  exports.NotFoundError = NotFoundError;
9830
10052
  exports.Pagination = Pagination;
9831
10053
  exports.PlanError = PlanError;
9832
10054
  exports.Projects = Projects;
9833
10055
  exports.RateLimitError = RateLimitError;
10056
+ exports.RateLimitInfo = RateLimitInfo;
9834
10057
  exports.Response = Response;
10058
+ exports.ScopePresets = ScopePresets;
10059
+ exports.Scopes = Scopes;
9835
10060
  exports.Segments = Segments;
9836
10061
  exports.Suppressions = Suppressions;
9837
10062
  exports.Tags = Tags;