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