@web-ts-toolkit/email-service 0.72.0 → 0.74.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/smtp.js CHANGED
@@ -272,6 +272,12 @@ function opaqueToken(value, maxBytes, code) {
272
272
  function identifier(value, code) {
273
273
  return opaqueToken(value, MESSAGE_LIMITS.identifierBytes, code);
274
274
  }
275
+ function uuidV4(value, code) {
276
+ if (typeof value !== "string" || value.length !== 36 || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value)) {
277
+ invalid(code);
278
+ }
279
+ return value;
280
+ }
275
281
  function hashToken(value, code) {
276
282
  if (typeof value !== "string" || value.length !== 64 || !/^[0-9a-f]{64}$/.test(value)) invalid(code);
277
283
  return value;
@@ -285,9 +291,9 @@ function jsonKey(key, code) {
285
291
 
286
292
  // src/internal/canonical-json.ts
287
293
  var treeLimits = { depth: MESSAGE_LIMITS.jsonDepth, values: MESSAGE_LIMITS.jsonValues };
288
- function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = treeLimits) {
294
+ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits2 = treeLimits) {
289
295
  let bytesLeft = maxBytes;
290
- let valuesLeft = limits.values;
296
+ let valuesLeft = limits2.values;
291
297
  const chunks = [];
292
298
  const ancestors = /* @__PURE__ */ new Set();
293
299
  function append(text, bytes = text.length) {
@@ -306,7 +312,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
306
312
  append(JSON.stringify(text), bytes);
307
313
  }
308
314
  function visit(value2, depth) {
309
- if (depth > limits.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
315
+ if (depth > limits2.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
310
316
  switch (typeof value2) {
311
317
  case "string":
312
318
  appendString(value2);
@@ -330,7 +336,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
330
336
  if (ancestors.has(value2)) invalid(code);
331
337
  ancestors.add(value2);
332
338
  try {
333
- const maxChildren = depth === limits.depth ? 0 : valuesLeft;
339
+ const maxChildren = depth === limits2.depth ? 0 : valuesLeft;
334
340
  if (isArray(value2, code)) {
335
341
  const length = denseArrayLength(value2, maxChildren, code);
336
342
  if (length && 2 * length + 1 > bytesLeft) invalid(code);
@@ -370,6 +376,71 @@ function copyJsonObject(input, maxBytes, code) {
370
376
  function sha256(input) {
371
377
  return (0, import_node_crypto.createHash)("sha256").update(input).digest("hex");
372
378
  }
379
+ function encodeEvidence(input, code, capacity) {
380
+ return canonicalJson(input, capacity?.limits.evidenceBytes ?? 8192, code, capacity?.limits.evidenceTree).encoded;
381
+ }
382
+
383
+ // src/internal/smtp-capacity.ts
384
+ var MIN_RECIPIENTS = MESSAGE_LIMITS.recipients + 1;
385
+ var MAX_SMTP_RECIPIENTS = 1e3;
386
+ var KIB = 1024;
387
+ var limits = Object.freeze({
388
+ snapshotBytes: 2 * KIB * KIB,
389
+ snapshotTree: Object.freeze({ depth: 4, values: 4096 }),
390
+ evidenceBytes: 64 * KIB,
391
+ evidenceTree: Object.freeze({ depth: 5, values: 4096 }),
392
+ jobBsonBytes: 4 * KIB * KIB,
393
+ activityBsonBytes: 128 * KIB,
394
+ registryCache: Object.freeze({ min: 0, default: 8, max: 16 }),
395
+ registryPending: Object.freeze({ min: 1, default: 2, max: 4 }),
396
+ servicePending: 4,
397
+ workerProfiles: 16,
398
+ workerConcurrency: Object.freeze({ min: 1, default: 1, max: 2 }),
399
+ runClaims: Object.freeze({ min: 1, default: 4, max: 16 }),
400
+ runMaintenance: Object.freeze({ min: 0, default: 4, max: 16 }),
401
+ adminMaintenance: Object.freeze({ min: 1, default: 4, max: 16 }),
402
+ page: Object.freeze({ min: 1, default: 8, max: 16 }),
403
+ memoryJobs: Object.freeze({ min: 1, default: 8, max: 16 }),
404
+ mongoInFlight: 4,
405
+ dueCandidates: 4
406
+ });
407
+ function readBinding(input, code) {
408
+ const { format, namespace, maxRecipients } = readRecord(input, ["format", "namespace", "maxRecipients"], [], code);
409
+ if (format !== "smtp-v2") invalid(code);
410
+ return Object.freeze({
411
+ format,
412
+ namespace: uuidV4(namespace, code),
413
+ maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_SMTP_RECIPIENTS, code)
414
+ });
415
+ }
416
+ function readCapacityOption(raw) {
417
+ if (!Object.hasOwn(raw, "smtpCapacity")) return;
418
+ return Object.freeze({ binding: readBinding(raw.smtpCapacity, "invalid_config"), limits });
419
+ }
420
+ function capacityTag(capacity) {
421
+ return capacity ? { smtpCapacity: capacity.binding } : {};
422
+ }
423
+ function recipientLimit(capacity) {
424
+ return capacity?.binding.maxRecipients ?? MESSAGE_LIMITS.recipients;
425
+ }
426
+ function matchesBinding(input, capacity, code) {
427
+ const binding = readBinding(input, code);
428
+ if (binding.namespace !== capacity.binding.namespace || binding.maxRecipients !== capacity.binding.maxRecipients) {
429
+ invalid(code);
430
+ }
431
+ }
432
+ function assertCapacityTag(raw, capacity, code) {
433
+ const tagged = Object.hasOwn(raw, "smtpCapacity");
434
+ if (capacity) {
435
+ if (!tagged) invalid(code);
436
+ matchesBinding(raw.smtpCapacity, capacity, code);
437
+ } else if (tagged) {
438
+ invalid(code);
439
+ }
440
+ }
441
+ function assertCapacityProvider(provider, capacity, code) {
442
+ if (capacity && provider.kind !== "smtp") invalid(code);
443
+ }
373
444
 
374
445
  // src/internal/attempt-codecs.ts
375
446
  var smtpStages = ["connect", "tls", "auth", "envelope", "data"];
@@ -416,6 +487,57 @@ function recipientCounts(envelope) {
416
487
  function smtpMessageId(attemptId) {
417
488
  return `<${attemptId}@email.invalid>`;
418
489
  }
490
+ function readRecipientResults(input, code, { limit, allowAccepted, ordered }) {
491
+ const seen = /* @__PURE__ */ new Set();
492
+ let previous = -1;
493
+ return readArray(input, limit, code, (value) => {
494
+ const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
495
+ if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
496
+ if (status !== "rejected" && (status !== "accepted" || !allowAccepted)) invalid(code);
497
+ const index = integer(rawIndex, 0, limit - 1, code);
498
+ if (ordered) {
499
+ const position = recipientGroups.indexOf(group) * limit + index;
500
+ if (position <= previous) invalid(code);
501
+ previous = position;
502
+ } else {
503
+ const key = `${group}:${index}`;
504
+ if (seen.has(key)) invalid(code);
505
+ seen.add(key);
506
+ }
507
+ return Object.freeze({ group, index, status });
508
+ });
509
+ }
510
+ function allAccepted(recipients) {
511
+ return recipients.length !== 0 && recipients.every(({ status }) => status === "accepted");
512
+ }
513
+ function createSmtpAcceptanceResult(recipients, messageId) {
514
+ const code = "invalid_command";
515
+ if (messageId !== void 0 && (typeof messageId !== "string" || messageId.length !== 52 || messageId !== smtpMessageId(uuidV4(messageId.slice(1, 37), code)))) {
516
+ invalid(code);
517
+ }
518
+ const checked = readRecipientResults(recipients, code, {
519
+ limit: MAX_SMTP_RECIPIENTS,
520
+ allowAccepted: true,
521
+ ordered: false
522
+ });
523
+ const data = { retry: "never", stage: "data", ...messageId === void 0 ? {} : { messageId } };
524
+ if (allAccepted(checked)) {
525
+ return Object.freeze({ ...data, reason: "smtp_accepted", outcome: "accepted", recipients: checked });
526
+ }
527
+ if (!checked.some(({ status }) => status === "accepted")) invalid(code);
528
+ return Object.freeze({
529
+ ...data,
530
+ reason: "smtp_partial",
531
+ outcome: "partially_accepted",
532
+ recipients: checked
533
+ });
534
+ }
535
+ function uncertainProviderResult(stage, reason) {
536
+ const base = { outcome: "unknown", retry: "never", stage };
537
+ if (reason === "provider_timeout") return { ...base, reason };
538
+ if (reason === "provider_aborted") return { ...base, reason };
539
+ return { ...base, reason };
540
+ }
419
541
  function readHint(input, reason, code) {
420
542
  if (reason !== "rate_deferred" && reason !== "sendgrid_throttled") invalid(code);
421
543
  const raw = readRecord(input, [], ["delayMs", "notBefore"], code);
@@ -429,7 +551,7 @@ function readHint(input, reason, code) {
429
551
  ...hasFloor ? { notBefore: unixMs(raw.notBefore, code) } : {}
430
552
  });
431
553
  }
432
- function readAttemptResult(input, code = "invalid_command", projected = false) {
554
+ function readAttemptResult(input, code = "invalid_command", projected = false, capacity) {
433
555
  const raw = readRecord(
434
556
  input,
435
557
  ["outcome", "retry", "stage", "reason"],
@@ -440,6 +562,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
440
562
  const [outcome, retry, stages, origin] = evidence[reason];
441
563
  const stage = stages.find((value) => value === raw.stage);
442
564
  if (raw.outcome !== outcome || raw.retry !== retry || !stage) invalid(code);
565
+ if (capacity && (origin === "sendgrid" || stage === "http")) invalid(code);
443
566
  const hasHint = Object.hasOwn(raw, "retryHint");
444
567
  if (projected && hasHint || !projected && reason === "rate_deferred" && !hasHint) invalid(code);
445
568
  const smtpSuccess = reason === "smtp_accepted" || reason === "smtp_partial";
@@ -448,16 +571,10 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
448
571
  let recipients;
449
572
  if (hasRecipients) {
450
573
  if (origin !== "smtp" && origin !== "provider" || stage !== "envelope" && stage !== "data") invalid(code);
451
- const seen = /* @__PURE__ */ new Set();
452
- recipients = readArray(raw.recipients, MESSAGE_LIMITS.recipients, code, (value) => {
453
- const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
454
- if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
455
- if (status !== "rejected" && (status !== "accepted" || !smtpSuccess)) invalid(code);
456
- const index = integer(rawIndex, 0, MESSAGE_LIMITS.recipients - 1, code);
457
- const key = `${group}:${index}`;
458
- if (seen.has(key)) invalid(code);
459
- seen.add(key);
460
- return Object.freeze({ group, index, status });
574
+ recipients = readRecipientResults(raw.recipients, code, {
575
+ limit: recipientLimit(capacity),
576
+ allowAccepted: smtpSuccess,
577
+ ordered: Boolean(capacity)
461
578
  });
462
579
  const accepted = recipients.filter(({ status }) => status === "accepted").length;
463
580
  if (reason === "smtp_accepted" && (!accepted || accepted !== recipients.length) || reason === "smtp_partial" && (!accepted || accepted === recipients.length)) {
@@ -471,7 +588,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
471
588
  if (hasProviderId && (reason !== "sendgrid_accepted" || typeof providerMessageId !== "string" || providerMessageId.length > 128 || !/^[A-Za-z0-9][A-Za-z0-9._=-]{0,127}$/.test(providerMessageId))) {
472
589
  invalid(code);
473
590
  }
474
- return Object.freeze({
591
+ const result = Object.freeze({
475
592
  outcome,
476
593
  retry,
477
594
  stage,
@@ -481,6 +598,8 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
481
598
  ...typeof messageId === "string" ? { messageId } : {},
482
599
  ...typeof providerMessageId === "string" ? { providerMessageId } : {}
483
600
  });
601
+ if (capacity && !projected) encodeEvidence(result, code, capacity);
602
+ return result;
484
603
  }
485
604
  function assertEvidenceContext(result, provider, attemptId, counts, code) {
486
605
  const { reason, stage, recipients, messageId } = result;
@@ -497,9 +616,9 @@ function assertEvidenceContext(result, provider, attemptId, counts, code) {
497
616
  }
498
617
  }
499
618
  }
500
- function readProviderResult(input, provider, attemptId, envelope) {
619
+ function readProviderResult(input, provider, attemptId, envelope, capacity) {
501
620
  const code = "invalid_command";
502
- const result = readAttemptResult(input, code);
621
+ const result = readAttemptResult(input, code, false, capacity);
503
622
  const origin = evidence[result.reason][3];
504
623
  if (origin !== "smtp" && origin !== "sendgrid" && origin !== "provider") invalid(code);
505
624
  assertEvidenceContext(result, provider, attemptId, recipientCounts(envelope), code);
@@ -649,7 +768,8 @@ function validateMailbox(input, code = SNAPSHOT) {
649
768
  ...Object.hasOwn(mailbox, "name") ? { name: headerString(mailbox.name, L.displayNameBytes, code) } : {}
650
769
  });
651
770
  }
652
- function validateEnvelope(input, kind, code = SNAPSHOT) {
771
+ function validateEnvelope(input, kind, code = SNAPSHOT, capacity) {
772
+ const limit = recipientLimit(capacity);
653
773
  const envelope = readRecord(input, ["from", "to", "cc", "bcc"], ["replyTo"], code);
654
774
  const seen = /* @__PURE__ */ new Set();
655
775
  const recipient = (raw) => {
@@ -660,9 +780,9 @@ function validateEnvelope(input, kind, code = SNAPSHOT) {
660
780
  return mailbox;
661
781
  };
662
782
  const from = validateMailbox(envelope.from, code);
663
- const to = readArray(envelope.to, L.recipients, code, recipient);
664
- const cc = readArray(envelope.cc, L.recipients - to.length, code, recipient);
665
- const bcc = readArray(envelope.bcc, L.recipients - to.length - cc.length, code, recipient);
783
+ const to = readArray(envelope.to, limit, code, recipient);
784
+ const cc = readArray(envelope.cc, limit - to.length, code, recipient);
785
+ const bcc = readArray(envelope.bcc, limit - to.length - cc.length, code, recipient);
666
786
  if (seen.size === 0 || kind === "sendgrid" && to.length === 0) invalid(code);
667
787
  return Object.freeze({
668
788
  from,
@@ -750,12 +870,17 @@ function validateExpiry(input, preparedAt, scheduleAt, code = SNAPSHOT) {
750
870
  }
751
871
  return expiresAt;
752
872
  }
753
- function hashSnapshot(snapshot) {
873
+ function hashSnapshot(snapshot, capacity) {
754
874
  return sha256(
755
- canonicalJson(snapshot, L.snapshotBytes, SNAPSHOT, { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }).encoded
875
+ canonicalJson(
876
+ snapshot,
877
+ capacity?.limits.snapshotBytes ?? L.snapshotBytes,
878
+ SNAPSHOT,
879
+ capacity?.limits.snapshotTree ?? { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }
880
+ ).encoded
756
881
  );
757
882
  }
758
- function readSnapshot(input) {
883
+ function readSnapshot(input, capacity) {
759
884
  const dto = readRecord(
760
885
  input,
761
886
  [
@@ -770,17 +895,19 @@ function readSnapshot(input) {
770
895
  "attachments",
771
896
  "correlation"
772
897
  ],
773
- ["subject", "html", "text", "templateId", "data"],
898
+ ["subject", "html", "text", "templateId", "data", "smtpCapacity"],
774
899
  SNAPSHOT
775
900
  );
776
901
  if (dto.version !== EMAIL_FORMAT_VERSION || dto.kind !== "smtp" && dto.kind !== "sendgrid") invalid(SNAPSHOT);
902
+ assertCapacityTag(dto, capacity, SNAPSHOT);
777
903
  const provider = validateProviderRef(dto.provider);
778
904
  if (provider.kind !== dto.kind) invalid("provider_mismatch");
905
+ assertCapacityProvider(provider, capacity, "provider_mismatch");
779
906
  const preparedAt = unixMs(dto.preparedAt, SNAPSHOT);
780
907
  const common = {
781
908
  version: EMAIL_FORMAT_VERSION,
782
909
  template: validateTemplateIdentity(dto.template),
783
- envelope: validateEnvelope(dto.envelope, provider.kind),
910
+ envelope: validateEnvelope(dto.envelope, provider.kind, SNAPSHOT, capacity),
784
911
  preparedAt,
785
912
  expiresAt: validateExpiry(dto.expiresAt, preparedAt, null),
786
913
  priority: integer(dto.priority, PRIORITY.min, PRIORITY.max, SNAPSHOT),
@@ -794,7 +921,7 @@ function readSnapshot(input) {
794
921
  ...Object.hasOwn(dto, "html") ? { html: dto.html } : {},
795
922
  ...Object.hasOwn(dto, "text") ? { text: dto.text } : {}
796
923
  });
797
- return Object.freeze({ ...common, kind: provider.kind, provider, ...content });
924
+ return Object.freeze({ ...common, kind: provider.kind, provider, ...capacityTag(capacity), ...content });
798
925
  }
799
926
  if (Object.hasOwn(dto, "subject") || Object.hasOwn(dto, "html") || Object.hasOwn(dto, "text")) invalid(SNAPSHOT);
800
927
  return Object.freeze({
@@ -805,31 +932,28 @@ function readSnapshot(input) {
805
932
  data: copyJsonObject(dto.data, L.dataBytes, SNAPSHOT)
806
933
  });
807
934
  }
808
- function validateSnapshot(input) {
809
- const snapshot = readSnapshot(input);
810
- return { snapshot, snapshotHash: hashSnapshot(snapshot) };
935
+ function validateSnapshot(input, capacity) {
936
+ const snapshot = readSnapshot(input, capacity);
937
+ return { snapshot, snapshotHash: hashSnapshot(snapshot, capacity) };
811
938
  }
812
939
 
813
940
  // src/internal/store-codecs.ts
814
941
  var REQUEST = "invalid_command";
815
942
  var LEASE = WORKER_LIMIT_BOUNDS.leaseMs;
816
943
  function readStoreId(value, code = REQUEST) {
817
- if (typeof value !== "string" || value.length !== 36 || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(value)) {
818
- invalid(code);
819
- }
820
- return value;
944
+ return uuidV4(value, code);
821
945
  }
822
946
 
823
947
  // src/internal/provider-preparation.ts
824
948
  function sameRef(a, b) {
825
949
  return a.resolverKey === b.resolverKey && a.id === b.id && a.version === b.version && a.filename === b.filename && a.contentType === b.contentType && a.byteLength === b.byteLength && a.sha256 === b.sha256;
826
950
  }
827
- function readProviderSubmission(input, ref) {
951
+ function readProviderSubmission(input, ref, capacity) {
828
952
  const code = "invalid_snapshot";
829
953
  const raw = readRecord(input, ["jobId", "attemptId", "snapshot", "attachments"], [], code);
830
954
  const jobId = readStoreId(raw.jobId, code);
831
955
  const attemptId = readStoreId(raw.attemptId, code);
832
- const { snapshot } = validateSnapshot(raw.snapshot);
956
+ const { snapshot } = validateSnapshot(raw.snapshot, capacity);
833
957
  if (ref.kind !== snapshot.kind || ref.key !== snapshot.provider.key || ref.mode !== snapshot.provider.mode) {
834
958
  invalid("provider_mismatch");
835
959
  }
@@ -860,6 +984,13 @@ function readProviderCall(input) {
860
984
  // src/providers/smtp/mime.ts
861
985
  var import_mail_composer = __toESM(require("nodemailer/lib/mail-composer"));
862
986
  var import_mime_funcs = require("nodemailer/lib/mime-funcs");
987
+
988
+ // src/internal/smtp-attachments.ts
989
+ function assertSmtpAttachmentTypes(refs) {
990
+ if (refs.some(({ contentType }) => /^(?:message|multipart)\//.test(contentType))) invalid("invalid_snapshot");
991
+ }
992
+
993
+ // src/providers/smtp/mime.ts
863
994
  function body(content) {
864
995
  if (content !== void 0) return { content: Buffer.from(content, "utf8"), contentTransferEncoding: "base64" };
865
996
  }
@@ -871,6 +1002,7 @@ function prepareSmtpMessage({
871
1002
  attemptId,
872
1003
  attachments
873
1004
  }) {
1005
+ assertSmtpAttachmentTypes(attachments.map(({ ref }) => ref));
874
1006
  const { from, to, cc, replyTo } = snapshot.envelope;
875
1007
  const destinations = recipientGroups.flatMap(
876
1008
  (group) => snapshot.envelope[group].map(({ address }, index) => Object.freeze({ address, group, index }))
@@ -888,16 +1020,13 @@ function prepareSmtpMessage({
888
1020
  html: body(snapshot.html),
889
1021
  date: new Date(snapshot.preparedAt),
890
1022
  messageId,
891
- attachments: attachments.map(({ ref, bytes }) => {
892
- if (/^(?:multipart|message)\//.test(ref.contentType)) invalid("invalid_snapshot");
893
- return {
894
- filename: ref.filename,
895
- contentType: ref.contentType,
896
- content: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength),
897
- contentDisposition: "attachment",
898
- contentTransferEncoding: "base64"
899
- };
900
- }),
1023
+ attachments: attachments.map(({ ref, bytes }) => ({
1024
+ filename: ref.filename,
1025
+ contentType: ref.contentType,
1026
+ content: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength),
1027
+ contentDisposition: "attachment",
1028
+ contentTransferEncoding: "base64"
1029
+ })),
901
1030
  disableFileAccess: true,
902
1031
  disableUrlAccess: true,
903
1032
  newline: "win"
@@ -957,7 +1086,8 @@ function readAuth(input) {
957
1086
  return Object.freeze({ user, pass });
958
1087
  }
959
1088
  function readSmtpConfig(input) {
960
- const raw = readRecord(input, ["key", "host", "tls"], ["port", "servername", "ca", "auth"], CONFIG);
1089
+ const raw = readRecord(input, ["key", "host", "tls"], ["port", "servername", "ca", "auth", "smtpCapacity"], CONFIG);
1090
+ const capacity = readCapacityOption(raw);
961
1091
  const ref = Object.freeze({ kind: "smtp", key: identifier(raw.key, CONFIG), mode: "live" });
962
1092
  const { tls } = raw;
963
1093
  if (tls !== "implicit" && tls !== "starttls") invalid(CONFIG);
@@ -972,7 +1102,17 @@ function readSmtpConfig(input) {
972
1102
  if (ca?.length === 0) invalid(CONFIG);
973
1103
  try {
974
1104
  const secureContext = (0, import_node_tls.createSecureContext)({ minVersion: SMTP_MIN_TLS_VERSION, ...ca ? { ca: [...ca] } : {} });
975
- return Object.freeze({ ref, host, port, tls, identity: servername ?? host, servername, secureContext, auth });
1105
+ return Object.freeze({
1106
+ ref,
1107
+ host,
1108
+ port,
1109
+ tls,
1110
+ identity: servername ?? host,
1111
+ servername,
1112
+ secureContext,
1113
+ auth,
1114
+ capacity
1115
+ });
976
1116
  } catch {
977
1117
  return invalid(CONFIG);
978
1118
  }
@@ -1293,18 +1433,12 @@ var SmtpConnection = class {
1293
1433
  function failed(stage, reason) {
1294
1434
  if (reason === "not_transmitted") return { outcome: "unsubmitted", retry: "safe_transient", stage, reason };
1295
1435
  if (reason === "provider_configuration") return { outcome: "unsubmitted", retry: "never", stage, reason };
1296
- return { outcome: "unknown", retry: "never", stage, reason };
1436
+ return uncertainProviderResult(stage, reason);
1297
1437
  }
1298
- function negative(stage, code, permanentRcptRefusal = false, recipients = []) {
1438
+ function negative(at, code, permanentRcptRefusal = false) {
1299
1439
  if (code < 400 || code > 599) throw new SmtpFailure("transport_uncertain");
1300
- const permanent = code >= 500 || permanentRcptRefusal;
1301
- return {
1302
- outcome: "rejected",
1303
- retry: permanent ? "never" : "safe_transient",
1304
- stage,
1305
- reason: permanent ? "smtp_permanent_reply" : "smtp_transient_reply",
1306
- ...recipients.length ? { recipients } : {}
1307
- };
1440
+ const details = at.recipients?.length ? at : { stage: at.stage };
1441
+ return code >= 500 || permanentRcptRefusal ? { ...details, outcome: "rejected", retry: "never", reason: "smtp_permanent_reply" } : { ...details, outcome: "rejected", retry: "safe_transient", reason: "smtp_transient_reply" };
1308
1442
  }
1309
1443
  function extensions({ lines }) {
1310
1444
  let starttls = false;
@@ -1325,34 +1459,34 @@ async function authenticate(connection, { user, pass }, mechanisms) {
1325
1459
  if (command.length <= 510) response = await connection.command(command);
1326
1460
  else {
1327
1461
  response = await connection.command("AUTH PLAIN");
1328
- if (response.code !== 334) return negative("auth", response.code);
1462
+ if (response.code !== 334) return negative({ stage: "auth" }, response.code);
1329
1463
  response = await connection.command(encoded);
1330
1464
  }
1331
1465
  } else if (mechanisms.has("LOGIN")) {
1332
1466
  response = await connection.command("AUTH LOGIN");
1333
- if (response.code !== 334) return negative("auth", response.code);
1467
+ if (response.code !== 334) return negative({ stage: "auth" }, response.code);
1334
1468
  response = await connection.command(Buffer.from(user, "utf8").toString("base64"));
1335
- if (response.code !== 334) return negative("auth", response.code);
1469
+ if (response.code !== 334) return negative({ stage: "auth" }, response.code);
1336
1470
  response = await connection.command(Buffer.from(pass, "utf8").toString("base64"));
1337
1471
  } else return failed("auth", "provider_configuration");
1338
- if (response.code !== 235) return negative("auth", response.code);
1472
+ if (response.code !== 235) return negative({ stage: "auth" }, response.code);
1339
1473
  }
1340
1474
  async function exchange(connection, config, message) {
1341
1475
  await connection.connect();
1342
1476
  if (config.tls === "implicit") await connection.startTls();
1343
1477
  connection.stage = "connect";
1344
1478
  const greeting = await connection.greeting();
1345
- if (greeting.code !== 220) return negative("connect", greeting.code);
1479
+ if (greeting.code !== 220) return negative({ stage: "connect" }, greeting.code);
1346
1480
  let ehlo = await connection.command("EHLO email.invalid");
1347
- if (ehlo.code !== 250) return negative("connect", ehlo.code);
1481
+ if (ehlo.code !== 250) return negative({ stage: "connect" }, ehlo.code);
1348
1482
  if (config.tls === "starttls") {
1349
1483
  connection.stage = "tls";
1350
1484
  if (!extensions(ehlo).starttls) return failed("tls", "provider_configuration");
1351
1485
  const upgrade = await connection.command("STARTTLS");
1352
- if (upgrade.code !== 220) return negative("tls", upgrade.code);
1486
+ if (upgrade.code !== 220) return negative({ stage: "tls" }, upgrade.code);
1353
1487
  await connection.startTls();
1354
1488
  ehlo = await connection.command("EHLO email.invalid");
1355
- if (ehlo.code !== 250) return negative("tls", ehlo.code);
1489
+ if (ehlo.code !== 250) return negative({ stage: "tls" }, ehlo.code);
1356
1490
  }
1357
1491
  if (config.auth) {
1358
1492
  const failure = await authenticate(connection, config.auth, extensions(ehlo).mechanisms);
@@ -1360,7 +1494,7 @@ async function exchange(connection, config, message) {
1360
1494
  }
1361
1495
  connection.stage = "envelope";
1362
1496
  let { code } = await connection.command(`MAIL FROM:<${message.from}>`);
1363
- if (code !== 250) return negative("envelope", code);
1497
+ if (code !== 250) return negative({ stage: "envelope" }, code);
1364
1498
  const recipients = [];
1365
1499
  let accepted = 0;
1366
1500
  for (const { address, group, index } of message.destinations) {
@@ -1374,26 +1508,20 @@ async function exchange(connection, config, message) {
1374
1508
  if (code === 421) break;
1375
1509
  } else throw new SmtpFailure("transport_uncertain");
1376
1510
  }
1377
- const rejected = recipients.filter(({ status }) => status === "rejected");
1511
+ const rejected = recipients.filter((recipient) => recipient.status === "rejected");
1378
1512
  if (accepted === 0 && recipients.length === message.destinations.length) {
1379
- return negative("envelope", code, connection.permanentRcptRefusal, rejected);
1513
+ return negative({ stage: "envelope", recipients: rejected }, code, connection.permanentRcptRefusal);
1380
1514
  }
1381
1515
  if (code === 421) {
1382
1516
  return failed("envelope", connection.permanentRcptRefusal ? "transport_uncertain" : "not_transmitted");
1383
1517
  }
1384
1518
  connection.stage = "data";
1519
+ const refusal = { stage: "data", recipients: rejected };
1385
1520
  ({ code } = await connection.command("DATA"));
1386
- if (code !== 354) return negative("data", code, connection.permanentRcptRefusal, rejected);
1521
+ if (code !== 354) return negative(refusal, code, connection.permanentRcptRefusal);
1387
1522
  ({ code } = await connection.data(message.openMimeStream));
1388
- if (code !== 250) return negative("data", code, connection.permanentRcptRefusal, rejected);
1389
- return {
1390
- outcome: rejected.length ? "partially_accepted" : "accepted",
1391
- retry: "never",
1392
- stage: "data",
1393
- reason: rejected.length ? "smtp_partial" : "smtp_accepted",
1394
- messageId: message.messageId,
1395
- recipients
1396
- };
1523
+ if (code !== 250) return negative(refusal, code, connection.permanentRcptRefusal);
1524
+ return createSmtpAcceptanceResult(recipients, message.messageId);
1397
1525
  }
1398
1526
  async function submitSmtp(config, message, call, resolverFactory) {
1399
1527
  const connection = new SmtpConnection(config, call, resolverFactory);
@@ -1410,11 +1538,12 @@ async function submitSmtp(config, message, call, resolverFactory) {
1410
1538
  // src/smtp.ts
1411
1539
  function createSmtpProvider(options) {
1412
1540
  const config = readSmtpConfig(options);
1413
- const { ref } = config;
1541
+ const { ref, capacity } = config;
1414
1542
  const provider = {
1415
1543
  ref,
1544
+ ...capacityTag(capacity),
1416
1545
  prepare(input) {
1417
- const prepared = readProviderSubmission(input, ref);
1546
+ const prepared = readProviderSubmission(input, ref, capacity);
1418
1547
  const {
1419
1548
  attemptId,
1420
1549
  snapshot: { envelope }
@@ -1428,13 +1557,14 @@ function createSmtpProvider(options) {
1428
1557
  message = void 0;
1429
1558
  const result = await submitSmtp(config, send, call);
1430
1559
  try {
1431
- return readProviderResult(result, ref, attemptId, envelope);
1560
+ return readProviderResult(result, ref, attemptId, envelope, capacity);
1432
1561
  } catch {
1433
1562
  return readProviderResult(
1434
1563
  { outcome: "unknown", retry: "never", stage: result.stage, reason: "transport_uncertain" },
1435
1564
  ref,
1436
1565
  attemptId,
1437
- envelope
1566
+ envelope,
1567
+ capacity
1438
1568
  );
1439
1569
  }
1440
1570
  }