@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/mongoose.js CHANGED
@@ -275,6 +275,12 @@ function scopeToken(value, code = "invalid_command") {
275
275
  function identifier(value, code) {
276
276
  return opaqueToken(value, MESSAGE_LIMITS.identifierBytes, code);
277
277
  }
278
+ function uuidV4(value, code) {
279
+ 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)) {
280
+ invalid(code);
281
+ }
282
+ return value;
283
+ }
278
284
  function hashToken(value, code) {
279
285
  if (typeof value !== "string" || value.length !== 64 || !/^[0-9a-f]{64}$/.test(value)) invalid(code);
280
286
  return value;
@@ -288,9 +294,9 @@ function jsonKey(key, code) {
288
294
 
289
295
  // src/internal/canonical-json.ts
290
296
  var treeLimits = { depth: MESSAGE_LIMITS.jsonDepth, values: MESSAGE_LIMITS.jsonValues };
291
- function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = treeLimits) {
297
+ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits2 = treeLimits) {
292
298
  let bytesLeft = maxBytes;
293
- let valuesLeft = limits.values;
299
+ let valuesLeft = limits2.values;
294
300
  const chunks = [];
295
301
  const ancestors = /* @__PURE__ */ new Set();
296
302
  function append(text, bytes = text.length) {
@@ -309,7 +315,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
309
315
  append(JSON.stringify(text), bytes);
310
316
  }
311
317
  function visit(value2, depth) {
312
- if (depth > limits.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
318
+ if (depth > limits2.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
313
319
  switch (typeof value2) {
314
320
  case "string":
315
321
  appendString(value2);
@@ -333,7 +339,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
333
339
  if (ancestors.has(value2)) invalid(code);
334
340
  ancestors.add(value2);
335
341
  try {
336
- const maxChildren = depth === limits.depth ? 0 : valuesLeft;
342
+ const maxChildren = depth === limits2.depth ? 0 : valuesLeft;
337
343
  if (isArray(value2, code)) {
338
344
  const length = denseArrayLength(value2, maxChildren, code);
339
345
  if (length && 2 * length + 1 > bytesLeft) invalid(code);
@@ -376,6 +382,71 @@ function sha256(input) {
376
382
  function hashJson(input, maxBytes, code = "invalid_snapshot") {
377
383
  return sha256(canonicalJson(input, maxBytes, code).encoded);
378
384
  }
385
+ function encodeEvidence(input, code, capacity) {
386
+ return canonicalJson(input, capacity?.limits.evidenceBytes ?? 8192, code, capacity?.limits.evidenceTree).encoded;
387
+ }
388
+
389
+ // src/internal/smtp-capacity.ts
390
+ var MIN_RECIPIENTS = MESSAGE_LIMITS.recipients + 1;
391
+ var MAX_SMTP_RECIPIENTS = 1e3;
392
+ var KIB = 1024;
393
+ var limits = Object.freeze({
394
+ snapshotBytes: 2 * KIB * KIB,
395
+ snapshotTree: Object.freeze({ depth: 4, values: 4096 }),
396
+ evidenceBytes: 64 * KIB,
397
+ evidenceTree: Object.freeze({ depth: 5, values: 4096 }),
398
+ jobBsonBytes: 4 * KIB * KIB,
399
+ activityBsonBytes: 128 * KIB,
400
+ registryCache: Object.freeze({ min: 0, default: 8, max: 16 }),
401
+ registryPending: Object.freeze({ min: 1, default: 2, max: 4 }),
402
+ servicePending: 4,
403
+ workerProfiles: 16,
404
+ workerConcurrency: Object.freeze({ min: 1, default: 1, max: 2 }),
405
+ runClaims: Object.freeze({ min: 1, default: 4, max: 16 }),
406
+ runMaintenance: Object.freeze({ min: 0, default: 4, max: 16 }),
407
+ adminMaintenance: Object.freeze({ min: 1, default: 4, max: 16 }),
408
+ page: Object.freeze({ min: 1, default: 8, max: 16 }),
409
+ memoryJobs: Object.freeze({ min: 1, default: 8, max: 16 }),
410
+ mongoInFlight: 4,
411
+ dueCandidates: 4
412
+ });
413
+ function readBinding(input, code) {
414
+ const { format, namespace, maxRecipients } = readRecord(input, ["format", "namespace", "maxRecipients"], [], code);
415
+ if (format !== "smtp-v2") invalid(code);
416
+ return Object.freeze({
417
+ format,
418
+ namespace: uuidV4(namespace, code),
419
+ maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_SMTP_RECIPIENTS, code)
420
+ });
421
+ }
422
+ function readCapacityOption(raw) {
423
+ if (!Object.hasOwn(raw, "smtpCapacity")) return;
424
+ return Object.freeze({ binding: readBinding(raw.smtpCapacity, "invalid_config"), limits });
425
+ }
426
+ function capacityTag(capacity) {
427
+ return capacity ? { smtpCapacity: capacity.binding } : {};
428
+ }
429
+ function recipientLimit(capacity) {
430
+ return capacity?.binding.maxRecipients ?? MESSAGE_LIMITS.recipients;
431
+ }
432
+ function matchesBinding(input, capacity, code) {
433
+ const binding = readBinding(input, code);
434
+ if (binding.namespace !== capacity.binding.namespace || binding.maxRecipients !== capacity.binding.maxRecipients) {
435
+ invalid(code);
436
+ }
437
+ }
438
+ function assertCapacityTag(raw, capacity, code) {
439
+ const tagged = Object.hasOwn(raw, "smtpCapacity");
440
+ if (capacity) {
441
+ if (!tagged) invalid(code);
442
+ matchesBinding(raw.smtpCapacity, capacity, code);
443
+ } else if (tagged) {
444
+ invalid(code);
445
+ }
446
+ }
447
+ function assertCapacityProvider(provider2, capacity, code) {
448
+ if (capacity && provider2.kind !== "smtp") invalid(code);
449
+ }
379
450
 
380
451
  // src/internal/attempt-codecs.ts
381
452
  var smtpStages = ["connect", "tls", "auth", "envelope", "data"];
@@ -415,12 +486,42 @@ function readAttemptReason(value, code) {
415
486
  if (typeof value !== "string" || !Object.hasOwn(evidence, value)) invalid(code);
416
487
  return value;
417
488
  }
489
+ var recipientGroups = ["to", "cc", "bcc"];
418
490
  function recipientCounts(envelope) {
419
491
  return Object.freeze({ to: envelope.to.length, cc: envelope.cc.length, bcc: envelope.bcc.length });
420
492
  }
493
+ function readRecipientCounts(input, code, capacity) {
494
+ const limit = recipientLimit(capacity);
495
+ const counts = readRecord(input, recipientGroups, [], code);
496
+ const to = integer(counts.to, 0, limit, code);
497
+ const cc = integer(counts.cc, 0, limit - to, code);
498
+ const bcc = integer(counts.bcc, 0, limit - to - cc, code);
499
+ if (to + cc + bcc === 0) invalid(code);
500
+ return Object.freeze({ to, cc, bcc });
501
+ }
421
502
  function smtpMessageId(attemptId) {
422
503
  return `<${attemptId}@email.invalid>`;
423
504
  }
505
+ function readRecipientResults(input, code, { limit, allowAccepted, ordered }) {
506
+ const seen = /* @__PURE__ */ new Set();
507
+ let previous = -1;
508
+ return readArray(input, limit, code, (value) => {
509
+ const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
510
+ if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
511
+ if (status !== "rejected" && (status !== "accepted" || !allowAccepted)) invalid(code);
512
+ const index = integer(rawIndex, 0, limit - 1, code);
513
+ if (ordered) {
514
+ const position = recipientGroups.indexOf(group) * limit + index;
515
+ if (position <= previous) invalid(code);
516
+ previous = position;
517
+ } else {
518
+ const key = `${group}:${index}`;
519
+ if (seen.has(key)) invalid(code);
520
+ seen.add(key);
521
+ }
522
+ return Object.freeze({ group, index, status });
523
+ });
524
+ }
424
525
  function readHint(input, reason, code) {
425
526
  if (reason !== "rate_deferred" && reason !== "sendgrid_throttled") invalid(code);
426
527
  const raw = readRecord(input, [], ["delayMs", "notBefore"], code);
@@ -434,7 +535,7 @@ function readHint(input, reason, code) {
434
535
  ...hasFloor ? { notBefore: unixMs(raw.notBefore, code) } : {}
435
536
  });
436
537
  }
437
- function readAttemptResult(input, code = "invalid_command", projected = false) {
538
+ function readAttemptResult(input, code = "invalid_command", projected = false, capacity) {
438
539
  const raw = readRecord(
439
540
  input,
440
541
  ["outcome", "retry", "stage", "reason"],
@@ -445,6 +546,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
445
546
  const [outcome, retry, stages, origin] = evidence[reason];
446
547
  const stage = stages.find((value) => value === raw.stage);
447
548
  if (raw.outcome !== outcome || raw.retry !== retry || !stage) invalid(code);
549
+ if (capacity && (origin === "sendgrid" || stage === "http")) invalid(code);
448
550
  const hasHint = Object.hasOwn(raw, "retryHint");
449
551
  if (projected && hasHint || !projected && reason === "rate_deferred" && !hasHint) invalid(code);
450
552
  const smtpSuccess = reason === "smtp_accepted" || reason === "smtp_partial";
@@ -453,16 +555,10 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
453
555
  let recipients;
454
556
  if (hasRecipients) {
455
557
  if (origin !== "smtp" && origin !== "provider" || stage !== "envelope" && stage !== "data") invalid(code);
456
- const seen = /* @__PURE__ */ new Set();
457
- recipients = readArray(raw.recipients, MESSAGE_LIMITS.recipients, code, (value) => {
458
- const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
459
- if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
460
- if (status !== "rejected" && (status !== "accepted" || !smtpSuccess)) invalid(code);
461
- const index = integer(rawIndex, 0, MESSAGE_LIMITS.recipients - 1, code);
462
- const key = `${group}:${index}`;
463
- if (seen.has(key)) invalid(code);
464
- seen.add(key);
465
- return Object.freeze({ group, index, status });
558
+ recipients = readRecipientResults(raw.recipients, code, {
559
+ limit: recipientLimit(capacity),
560
+ allowAccepted: smtpSuccess,
561
+ ordered: Boolean(capacity)
466
562
  });
467
563
  const accepted = recipients.filter(({ status }) => status === "accepted").length;
468
564
  if (reason === "smtp_accepted" && (!accepted || accepted !== recipients.length) || reason === "smtp_partial" && (!accepted || accepted === recipients.length)) {
@@ -476,7 +572,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
476
572
  if (hasProviderId && (reason !== "sendgrid_accepted" || typeof providerMessageId !== "string" || providerMessageId.length > 128 || !/^[A-Za-z0-9][A-Za-z0-9._=-]{0,127}$/.test(providerMessageId))) {
477
573
  invalid(code);
478
574
  }
479
- return Object.freeze({
575
+ const result = Object.freeze({
480
576
  outcome,
481
577
  retry,
482
578
  stage,
@@ -486,6 +582,8 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
486
582
  ...typeof messageId === "string" ? { messageId } : {},
487
583
  ...typeof providerMessageId === "string" ? { providerMessageId } : {}
488
584
  });
585
+ if (capacity && !projected) encodeEvidence(result, code, capacity);
586
+ return result;
489
587
  }
490
588
  function assertEvidencePhase(reason, phase, source, code) {
491
589
  const origin = evidence[reason][3];
@@ -496,8 +594,8 @@ function assertEvidencePhase(reason, phase, source, code) {
496
594
  const allowed = phase === "pre_handoff" ? origin === "pre" : origin === "smtp" || origin === "sendgrid" || origin === "provider" || origin === "launch";
497
595
  if (!allowed) invalid(code);
498
596
  }
499
- function assertEvidenceContext(result2, provider2, attemptId, counts, code) {
500
- const { reason, stage, recipients, messageId } = result2;
597
+ function assertEvidenceContext(result, provider2, attemptId, counts, code) {
598
+ const { reason, stage, recipients, messageId } = result;
501
599
  const origin = evidence[reason][3];
502
600
  if (origin === "smtp" && provider2.kind !== "smtp" || origin === "sendgrid" && provider2.kind !== "sendgrid" || origin === "provider" && (provider2.kind === "smtp" ? stage === "http" : stage !== "http" && stage !== "connect" && stage !== "tls") || reason === "sendgrid_accepted" && provider2.mode !== "live" || reason === "sendgrid_validated" && provider2.mode !== "sandbox" || messageId !== void 0 && messageId !== smtpMessageId(attemptId)) {
503
601
  invalid(code);
@@ -515,19 +613,19 @@ function lifecycleEvidence(reason) {
515
613
  const [outcome, retry] = evidence[reason];
516
614
  return Object.freeze({ outcome, retry, reason, stage: "pre_handoff" });
517
615
  }
518
- function attemptEffect(result2, attemptId, ordinal2, manual, policy, expiresAt, now) {
519
- const { outcome, reason } = result2;
616
+ function attemptEffect(result, attemptId, ordinal2, manual, policy, expiresAt, now) {
617
+ const { outcome, reason } = result;
520
618
  if (outcome !== "unsubmitted" && outcome !== "rejected") return { disposition: outcome, reason };
521
619
  if (reason === "cancelled" || reason === "expired") return { disposition: reason, reason };
522
620
  const disposition = outcome === "unsubmitted" ? "failed" : "rejected";
523
- if (result2.retry === "never") return { disposition, reason };
621
+ if (result.retry === "never") return { disposition, reason };
524
622
  if (now >= expiresAt) return { disposition: "expired", reason: "expired" };
525
623
  if (manual || ordinal2 >= policy.maxAttempts) return { disposition, reason: "attempts_exhausted" };
526
624
  const cap = Math.min(policy.maxDelayMs, policy.baseDelayMs * 2 ** (ordinal2 - 1));
527
625
  const half = Math.floor(cap / 2);
528
626
  const jitter = half + Number.parseInt(sha256(attemptId).slice(0, 8), 16) % (cap - half + 1);
529
- const delay = Math.max(jitter, result2.retryHint?.delayMs ?? 0);
530
- const retryAt = Math.max(now + Math.min(delay, MAX_UNIX_MS - now), result2.retryHint?.notBefore ?? 0);
627
+ const delay = Math.max(jitter, result.retryHint?.delayMs ?? 0);
628
+ const retryAt = Math.max(now + Math.min(delay, MAX_UNIX_MS - now), result.retryHint?.notBefore ?? 0);
531
629
  if (retryAt >= expiresAt) return { disposition: "expired", reason: "expired" };
532
630
  return { disposition: "retry_scheduled", reason, retryAt };
533
631
  }
@@ -571,10 +669,11 @@ function validateMailbox(input, code = SNAPSHOT) {
571
669
  ...Object.hasOwn(mailbox, "name") ? { name: headerString(mailbox.name, L.displayNameBytes, code) } : {}
572
670
  });
573
671
  }
574
- function validateEnvelope(input, kind, code = SNAPSHOT) {
672
+ function validateEnvelope(input, kind, code = SNAPSHOT, capacity) {
673
+ const limit = recipientLimit(capacity);
575
674
  const envelope = readRecord(input, ["from", "to", "cc", "bcc"], ["replyTo"], code);
576
675
  const seen = /* @__PURE__ */ new Set();
577
- const recipient2 = (raw) => {
676
+ const recipient = (raw) => {
578
677
  const mailbox = validateMailbox(raw, code);
579
678
  const address = mailbox.address.toLowerCase();
580
679
  if (seen.has(address)) invalid(code);
@@ -582,9 +681,9 @@ function validateEnvelope(input, kind, code = SNAPSHOT) {
582
681
  return mailbox;
583
682
  };
584
683
  const from = validateMailbox(envelope.from, code);
585
- const to = readArray(envelope.to, L.recipients, code, recipient2);
586
- const cc = readArray(envelope.cc, L.recipients - to.length, code, recipient2);
587
- const bcc = readArray(envelope.bcc, L.recipients - to.length - cc.length, code, recipient2);
684
+ const to = readArray(envelope.to, limit, code, recipient);
685
+ const cc = readArray(envelope.cc, limit - to.length, code, recipient);
686
+ const bcc = readArray(envelope.bcc, limit - to.length - cc.length, code, recipient);
588
687
  if (seen.size === 0 || kind === "sendgrid" && to.length === 0) invalid(code);
589
688
  return Object.freeze({
590
689
  from,
@@ -659,12 +758,17 @@ function validateExpiry(input, preparedAt, scheduleAt, code = SNAPSHOT) {
659
758
  }
660
759
  return expiresAt;
661
760
  }
662
- function hashSnapshot(snapshot) {
761
+ function hashSnapshot(snapshot, capacity) {
663
762
  return sha256(
664
- canonicalJson(snapshot, L.snapshotBytes, SNAPSHOT, { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }).encoded
763
+ canonicalJson(
764
+ snapshot,
765
+ capacity?.limits.snapshotBytes ?? L.snapshotBytes,
766
+ SNAPSHOT,
767
+ capacity?.limits.snapshotTree ?? { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }
768
+ ).encoded
665
769
  );
666
770
  }
667
- function readSnapshot(input) {
771
+ function readSnapshot(input, capacity) {
668
772
  const dto = readRecord(
669
773
  input,
670
774
  [
@@ -679,17 +783,19 @@ function readSnapshot(input) {
679
783
  "attachments",
680
784
  "correlation"
681
785
  ],
682
- ["subject", "html", "text", "templateId", "data"],
786
+ ["subject", "html", "text", "templateId", "data", "smtpCapacity"],
683
787
  SNAPSHOT
684
788
  );
685
789
  if (dto.version !== EMAIL_FORMAT_VERSION || dto.kind !== "smtp" && dto.kind !== "sendgrid") invalid(SNAPSHOT);
790
+ assertCapacityTag(dto, capacity, SNAPSHOT);
686
791
  const provider2 = validateProviderRef(dto.provider);
687
792
  if (provider2.kind !== dto.kind) invalid("provider_mismatch");
793
+ assertCapacityProvider(provider2, capacity, "provider_mismatch");
688
794
  const preparedAt = unixMs(dto.preparedAt, SNAPSHOT);
689
795
  const common = {
690
796
  version: EMAIL_FORMAT_VERSION,
691
797
  template: validateTemplateIdentity(dto.template),
692
- envelope: validateEnvelope(dto.envelope, provider2.kind),
798
+ envelope: validateEnvelope(dto.envelope, provider2.kind, SNAPSHOT, capacity),
693
799
  preparedAt,
694
800
  expiresAt: validateExpiry(dto.expiresAt, preparedAt, null),
695
801
  priority: integer(dto.priority, PRIORITY.min, PRIORITY.max, SNAPSHOT),
@@ -703,7 +809,7 @@ function readSnapshot(input) {
703
809
  ...Object.hasOwn(dto, "html") ? { html: dto.html } : {},
704
810
  ...Object.hasOwn(dto, "text") ? { text: dto.text } : {}
705
811
  });
706
- return Object.freeze({ ...common, kind: provider2.kind, provider: provider2, ...content });
812
+ return Object.freeze({ ...common, kind: provider2.kind, provider: provider2, ...capacityTag(capacity), ...content });
707
813
  }
708
814
  if (Object.hasOwn(dto, "subject") || Object.hasOwn(dto, "html") || Object.hasOwn(dto, "text")) invalid(SNAPSHOT);
709
815
  return Object.freeze({
@@ -714,9 +820,9 @@ function readSnapshot(input) {
714
820
  data: copyJsonObject(dto.data, L.dataBytes, SNAPSHOT)
715
821
  });
716
822
  }
717
- function validateSnapshot(input) {
718
- const snapshot = readSnapshot(input);
719
- return { snapshot, snapshotHash: hashSnapshot(snapshot) };
823
+ function validateSnapshot(input, capacity) {
824
+ const snapshot = readSnapshot(input, capacity);
825
+ return { snapshot, snapshotHash: hashSnapshot(snapshot, capacity) };
720
826
  }
721
827
 
722
828
  // src/internal/budget.ts
@@ -841,42 +947,56 @@ function validateAdmissionKey(input, code = "invalid_command") {
841
947
  function encodeAdmissionKey(key) {
842
948
  return key.kind === "single" ? `s:${key.idempotencyKey}` : `b:${key.batchId}:${key.itemId}`;
843
949
  }
844
- function fingerprintFor(identity) {
950
+ function fingerprintFor(identity, capacity) {
845
951
  const { scope: scope2, key, templateKey, provider: provider2, scheduleAt, intentHash } = identity;
846
952
  return hashJson(
847
- [EMAIL_FORMAT_VERSION, scope2, key, templateKey, provider2, scheduleAt, intentHash],
953
+ [
954
+ ...capacity ? ["smtp-v2-admission", capacity.binding] : [],
955
+ EMAIL_FORMAT_VERSION,
956
+ scope2,
957
+ key,
958
+ templateKey,
959
+ provider2,
960
+ scheduleAt,
961
+ intentHash
962
+ ],
848
963
  MESSAGE_LIMITS.intentBytes
849
964
  );
850
965
  }
851
- function validatePreparedCommand(scope2, input) {
966
+ function validatePreparedCommand(scope2, input, capacity) {
852
967
  const expectedScope = scopeToken(scope2);
853
968
  const code = "invalid_snapshot";
854
969
  const dto = readRecord(
855
970
  input,
856
971
  ["version", "scope", "key", "scheduleAt", "intentHash", "fingerprint", "snapshotHash", "snapshot"],
857
- [],
972
+ ["smtpCapacity"],
858
973
  code
859
974
  );
860
975
  if (dto.version !== EMAIL_FORMAT_VERSION || scopeToken(dto.scope, code) !== expectedScope) invalid(code);
976
+ assertCapacityTag(dto, capacity, code);
861
977
  const key = validateAdmissionKey(dto.key, code);
862
978
  const scheduleAt = dto.scheduleAt === null ? null : unixMs(dto.scheduleAt, code);
863
979
  const intentHash = hashToken(dto.intentHash, code);
864
980
  const fingerprint = hashToken(dto.fingerprint, code);
865
981
  const storedSnapshotHash = hashToken(dto.snapshotHash, code);
866
- const { snapshot, snapshotHash } = validateSnapshot(dto.snapshot);
982
+ const { snapshot, snapshotHash } = validateSnapshot(dto.snapshot, capacity);
867
983
  validateExpiry(snapshot.expiresAt, snapshot.preparedAt, scheduleAt);
868
- if (snapshotHash !== storedSnapshotHash || fingerprint !== fingerprintFor({
869
- scope: expectedScope,
870
- key,
871
- templateKey: snapshot.template.key,
872
- provider: snapshot.provider,
873
- scheduleAt,
874
- intentHash
875
- })) {
984
+ if (snapshotHash !== storedSnapshotHash || fingerprint !== fingerprintFor(
985
+ {
986
+ scope: expectedScope,
987
+ key,
988
+ templateKey: snapshot.template.key,
989
+ provider: snapshot.provider,
990
+ scheduleAt,
991
+ intentHash
992
+ },
993
+ capacity
994
+ )) {
876
995
  invalid(code);
877
996
  }
878
997
  return Object.freeze({
879
998
  version: EMAIL_FORMAT_VERSION,
999
+ ...capacityTag(capacity),
880
1000
  scope: expectedScope,
881
1001
  key,
882
1002
  scheduleAt,
@@ -891,10 +1011,7 @@ function validatePreparedCommand(scope2, input) {
891
1011
  var REQUEST = "invalid_command";
892
1012
  var LEASE = WORKER_LIMIT_BOUNDS.leaseMs;
893
1013
  function readStoreId(value, code = REQUEST) {
894
- 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)) {
895
- invalid(code);
896
- }
897
- return value;
1014
+ return uuidV4(value, code);
898
1015
  }
899
1016
  function readLeaseToken(value, code = REQUEST) {
900
1017
  if (typeof value !== "string" || value.length < 22 || value.length > 128 || !/^[A-Za-z0-9_-]+$/.test(value) || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value)) {
@@ -908,14 +1025,18 @@ function readLeaseMs(value) {
908
1025
  function timeAfter(start, delayMs) {
909
1026
  return delayMs <= MAX_UNIX_MS - start ? start + delayMs : void 0;
910
1027
  }
911
- function readStoreCall(input, worker = false) {
1028
+ function readStoreCall(input, worker = false, capacity) {
912
1029
  const code = "invalid_config";
913
- const raw = readRecord(input, ["signal", "timeoutMs"], [], code);
1030
+ const { smtpCapacity, ...raw } = readRecord(input, ["signal", "timeoutMs"], capacity ? ["smtpCapacity"] : [], code);
1031
+ if (capacity) assertCapacityTag({ smtpCapacity }, capacity, "store_incompatible");
914
1032
  const max = worker ? WORKER_LIMIT_BOUNDS.storeTimeoutMs.max : CALL_BUDGETS.admissionOrAdmin.max;
915
1033
  const timeoutMs = integer(raw.timeoutMs, 1, max, code);
916
1034
  const call = readCallOptions(raw, { default: STORE_PRIMITIVE_TIMEOUT_MS, min: 1, max });
917
1035
  if (!call.signal) invalid(code);
918
- return { signal: call.signal, timeoutMs: worker ? timeoutMs : Math.min(timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS) };
1036
+ return {
1037
+ signal: call.signal,
1038
+ timeoutMs: worker && !capacity ? timeoutMs : Math.min(timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS)
1039
+ };
919
1040
  }
920
1041
  function readRetryPolicy(input, code = REQUEST) {
921
1042
  const raw = readRecord(input, ["maxAttempts", "baseDelayMs", "maxDelayMs"], [], code);
@@ -941,9 +1062,9 @@ function readRetentionPolicy(input, code = REQUEST) {
941
1062
  idempotencyMs: integer(idempotencyMs, bounds.idempotencyMs.min, bounds.idempotencyMs.max, code)
942
1063
  });
943
1064
  }
944
- function readStoreAdmission(scope2, input) {
1065
+ function readStoreAdmission(scope2, input, capacity) {
945
1066
  const raw = readRecord(input, ["command", "jobId", "retry", "retention"], [], REQUEST);
946
- const command = validatePreparedCommand(scope2, raw.command);
1067
+ const command = validatePreparedCommand(scope2, raw.command, capacity);
947
1068
  return Object.freeze({
948
1069
  command,
949
1070
  admissionKey: encodeAdmissionKey(command.key),
@@ -964,15 +1085,15 @@ function readClaim(input) {
964
1085
  leaseMs: readLeaseMs(leaseMs)
965
1086
  });
966
1087
  }
967
- function readFinish(input) {
968
- const { fence, phase, operationId, result: result2 } = readRecord(
1088
+ function readFinish(input, capacity) {
1089
+ const { fence, phase, operationId, result } = readRecord(
969
1090
  input,
970
1091
  ["fence", "phase", "operationId", "result"],
971
1092
  [],
972
1093
  REQUEST
973
1094
  );
974
1095
  if (phase !== "pre_handoff" && phase !== "handed_off") invalid(REQUEST);
975
- const evidence2 = readAttemptResult(result2);
1096
+ const evidence2 = readAttemptResult(result, REQUEST, false, capacity);
976
1097
  assertEvidencePhase(evidence2.reason, phase, "owner", REQUEST);
977
1098
  return Object.freeze({ fence: readFence(fence), phase, operationId: readStoreId(operationId), result: evidence2 });
978
1099
  }
@@ -989,7 +1110,6 @@ function readResolution(input) {
989
1110
  }
990
1111
 
991
1112
  // src/internal/activity-codecs.ts
992
- var ACTIVITY_BYTES = 8192;
993
1113
  var dispositions = [
994
1114
  "accepted",
995
1115
  "partially_accepted",
@@ -1006,17 +1126,17 @@ function readDisposition(input, code) {
1006
1126
  if (input === "retry_scheduled") return input;
1007
1127
  return invalid(code);
1008
1128
  }
1009
- function assertActivityDisposition(result2, disposition, code) {
1010
- const { outcome, reason } = result2;
1129
+ function assertActivityDisposition(result, disposition, code) {
1130
+ const { outcome, reason } = result;
1011
1131
  if (outcome !== "rejected" && outcome !== "unsubmitted") {
1012
1132
  if (disposition !== outcome) invalid(code);
1013
1133
  } else if (reason === "expired" || reason === "cancelled") {
1014
1134
  if (disposition !== reason) invalid(code);
1015
- } else if (disposition !== (outcome === "rejected" ? "rejected" : "failed") && !(result2.retry === "safe_transient" && (disposition === "expired" || disposition === "retry_scheduled"))) {
1135
+ } else if (disposition !== (outcome === "rejected" ? "rejected" : "failed") && !(result.retry === "safe_transient" && (disposition === "expired" || disposition === "retry_scheduled"))) {
1016
1136
  invalid(code);
1017
1137
  }
1018
1138
  }
1019
- function readActivity(scope2, input, code = "store_incompatible") {
1139
+ function captureActivity(scope2, input, code, capacity) {
1020
1140
  const raw = readRecord(
1021
1141
  input,
1022
1142
  [
@@ -1033,26 +1153,32 @@ function readActivity(scope2, input, code = "store_incompatible") {
1033
1153
  "result",
1034
1154
  "disposition"
1035
1155
  ],
1036
- ["handedOffAt"],
1156
+ ["handedOffAt", "smtpCapacity", "recipientCounts"],
1037
1157
  code
1038
1158
  );
1039
1159
  if (raw.version !== EMAIL_FORMAT_VERSION || scopeToken(raw.scope, code) !== scope2) invalid(code);
1160
+ assertCapacityTag(raw, capacity, code);
1161
+ if (!capacity && Object.hasOwn(raw, "recipientCounts")) invalid(code);
1162
+ const counts = capacity ? readRecipientCounts(raw.recipientCounts, code, capacity) : void 0;
1040
1163
  const jobId = readStoreId(raw.jobId, code);
1041
1164
  const attemptId = readStoreId(raw.attemptId, code);
1042
1165
  const provider2 = validateProviderRef(raw.provider, code);
1166
+ assertCapacityProvider(provider2, capacity, code);
1043
1167
  const startedAt = unixMs(raw.startedAt, code);
1044
1168
  const finishedAt = unixMs(raw.finishedAt, code);
1045
1169
  const handedOffAt = Object.hasOwn(raw, "handedOffAt") ? unixMs(raw.handedOffAt, code) : void 0;
1046
1170
  if (finishedAt < startedAt || handedOffAt !== void 0 && (handedOffAt < startedAt || handedOffAt > finishedAt)) {
1047
1171
  invalid(code);
1048
1172
  }
1049
- const result2 = readAttemptResult(raw.result, code, true);
1050
- assertEvidencePhase(result2.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", code);
1051
- assertEvidenceContext(result2, provider2, attemptId, void 0, code);
1173
+ const result = readAttemptResult(raw.result, code, true, capacity);
1174
+ assertEvidencePhase(result.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", code);
1175
+ assertEvidenceContext(result, provider2, attemptId, counts, code);
1052
1176
  const disposition = readDisposition(raw.disposition, code);
1053
- assertActivityDisposition(result2, disposition, code);
1177
+ assertActivityDisposition(result, disposition, code);
1054
1178
  return Object.freeze({
1055
1179
  version: EMAIL_FORMAT_VERSION,
1180
+ ...capacityTag(capacity),
1181
+ ...counts ? { recipientCounts: counts } : {},
1056
1182
  scope: scope2,
1057
1183
  jobId,
1058
1184
  attemptId,
@@ -1063,54 +1189,66 @@ function readActivity(scope2, input, code = "store_incompatible") {
1063
1189
  startedAt,
1064
1190
  ...handedOffAt === void 0 ? {} : { handedOffAt },
1065
1191
  finishedAt,
1066
- result: result2,
1192
+ result,
1067
1193
  disposition
1068
1194
  });
1069
1195
  }
1070
- function activityFor(job, commit) {
1196
+ function readActivity(scope2, input, code = "store_incompatible", capacity) {
1197
+ const activity = captureActivity(scope2, input, code, capacity);
1198
+ if (capacity) encodeEvidence(activity, code, capacity);
1199
+ return activity;
1200
+ }
1201
+ function activityFor(job, commit, capacity) {
1071
1202
  const { outcome, retry, stage, reason, recipients, messageId, providerMessageId } = commit.result;
1072
- return readActivity(job.scope, {
1073
- version: EMAIL_FORMAT_VERSION,
1074
- scope: job.scope,
1075
- jobId: job.jobId,
1076
- attemptId: commit.attemptId,
1077
- ordinal: commit.ordinal,
1078
- provider: job.provider,
1079
- template: job.template,
1080
- correlation: job.correlation,
1081
- startedAt: commit.startedAt,
1082
- ...commit.handedOffAt === void 0 ? {} : { handedOffAt: commit.handedOffAt },
1083
- finishedAt: commit.finishedAt,
1084
- disposition: commit.disposition,
1085
- result: {
1086
- outcome,
1087
- retry,
1088
- stage,
1089
- reason,
1090
- ...recipients === void 0 ? {} : { recipients },
1091
- ...messageId === void 0 ? {} : { messageId },
1092
- ...providerMessageId === void 0 ? {} : { providerMessageId }
1093
- }
1094
- });
1203
+ return captureActivity(
1204
+ job.scope,
1205
+ {
1206
+ version: EMAIL_FORMAT_VERSION,
1207
+ ...capacityTag(capacity),
1208
+ ...capacity ? { recipientCounts: job.recipientCounts } : {},
1209
+ scope: job.scope,
1210
+ jobId: job.jobId,
1211
+ attemptId: commit.attemptId,
1212
+ ordinal: commit.ordinal,
1213
+ provider: job.provider,
1214
+ template: job.template,
1215
+ correlation: job.correlation,
1216
+ startedAt: commit.startedAt,
1217
+ ...commit.handedOffAt === void 0 ? {} : { handedOffAt: commit.handedOffAt },
1218
+ finishedAt: commit.finishedAt,
1219
+ disposition: commit.disposition,
1220
+ result: {
1221
+ outcome,
1222
+ retry,
1223
+ stage,
1224
+ reason,
1225
+ ...recipients === void 0 ? {} : { recipients },
1226
+ ...messageId === void 0 ? {} : { messageId },
1227
+ ...providerMessageId === void 0 ? {} : { providerMessageId }
1228
+ }
1229
+ },
1230
+ "store_incompatible",
1231
+ capacity
1232
+ );
1095
1233
  }
1096
- function activityDigest(activity) {
1097
- return hashJson(activity, ACTIVITY_BYTES, "store_incompatible");
1234
+ function activityDigest(activity, capacity) {
1235
+ return sha256(encodeEvidence(activity, "store_incompatible", capacity));
1098
1236
  }
1099
- function readStoredActivity(scope2, input, code = "store_incompatible") {
1237
+ function readStoredActivity(scope2, input, code = "store_incompatible", capacity) {
1100
1238
  const raw = readRecord(input, ["activity", "digest"], [], code);
1101
- const activity = readActivity(scope2, raw.activity, code);
1239
+ const activity = captureActivity(scope2, raw.activity, code, capacity);
1102
1240
  const digest2 = hashToken(raw.digest, code);
1103
- if (activityDigest(activity) !== digest2) invalid(code);
1241
+ if (activityDigest(activity, capacity) !== digest2) invalid(code);
1104
1242
  return Object.freeze({ activity, digest: digest2 });
1105
1243
  }
1106
- function readProjectionPermit(scope2, input) {
1244
+ function readProjectionPermit(scope2, input, capacity) {
1107
1245
  const code = "invalid_command";
1108
1246
  const {
1109
1247
  activity,
1110
1248
  digest: digest2,
1111
1249
  permitUntil: rawUntil
1112
1250
  } = readRecord(input, ["activity", "digest", "permitUntil"], [], code);
1113
- const stored = readStoredActivity(scope2, { activity, digest: digest2 }, code);
1251
+ const stored = readStoredActivity(scope2, { activity, digest: digest2 }, code, capacity);
1114
1252
  const permitUntil = unixMs(rawUntil, code);
1115
1253
  if (permitUntil - stored.activity.finishedAt < PROJECTION_PERMIT_MS) invalid(code);
1116
1254
  return Object.freeze({ ...stored, permitUntil });
@@ -1122,13 +1260,15 @@ function compareActivity(a, b) {
1122
1260
  return b.finishedAt - a.finishedAt || compareAscii(a.jobId, b.jobId) || compareAscii(a.attemptId, b.attemptId);
1123
1261
  }
1124
1262
  function cursorPayload(criteria, position) {
1263
+ const binding = criteria.capacity?.binding;
1125
1264
  return {
1126
1265
  v: EMAIL_FORMAT_VERSION,
1127
1266
  s: criteria.scope,
1128
1267
  j: criteria.jobId,
1129
1268
  f: criteria.from,
1130
1269
  b: criteria.before,
1131
- p: [position.finishedAt, position.jobId, position.attemptId]
1270
+ p: [position.finishedAt, position.jobId, position.attemptId],
1271
+ ...binding ? { c: [binding.format, binding.namespace, binding.maxRecipients] } : {}
1132
1272
  };
1133
1273
  }
1134
1274
  function encodeCursor(criteria, position) {
@@ -1149,7 +1289,7 @@ function decodeCursor(criteria, cursor) {
1149
1289
  } catch {
1150
1290
  invalid(code);
1151
1291
  }
1152
- const { p } = readRecord(input, ["v", "s", "j", "f", "b", "p"], [], code);
1292
+ const { p } = readRecord(input, ["v", "s", "j", "f", "b", "p"], criteria.capacity ? ["c"] : [], code);
1153
1293
  const tuple = readArray(p, 3, code, (entry) => entry);
1154
1294
  const position = Object.freeze({
1155
1295
  finishedAt: unixMs(tuple[0], code),
@@ -1161,15 +1301,16 @@ function decodeCursor(criteria, cursor) {
1161
1301
  }
1162
1302
  return position;
1163
1303
  }
1164
- function readActivityCriteria(scope2, input) {
1304
+ function readActivityCriteria(scope2, input, capacity) {
1165
1305
  const code = "invalid_command";
1166
1306
  const raw = readRecord(input, [], ["jobId", "from", "before", "limit", "cursor"], code);
1167
1307
  const jobId = Object.hasOwn(raw, "jobId") ? readStoreId(raw.jobId, code) : null;
1168
1308
  const from = Object.hasOwn(raw, "from") ? unixMs(raw.from, code) : null;
1169
1309
  const before = Object.hasOwn(raw, "before") ? unixMs(raw.before, code) : null;
1170
1310
  if (from !== null && before !== null && from > before) invalid(code);
1171
- const limit = Object.hasOwn(raw, "limit") ? integer(raw.limit, ACTIVITY_PAGE_LIMIT.min, ACTIVITY_PAGE_LIMIT.max, code) : ACTIVITY_PAGE_LIMIT.default;
1172
- const criteria = { scope: scope2, jobId, from, before, limit };
1311
+ const page = capacity?.limits.page ?? ACTIVITY_PAGE_LIMIT;
1312
+ const limit = Object.hasOwn(raw, "limit") ? integer(raw.limit, page.min, page.max, code) : page.default;
1313
+ const criteria = { scope: scope2, jobId, from, before, limit, ...capacity ? { capacity } : {} };
1173
1314
  return Object.freeze({
1174
1315
  ...criteria,
1175
1316
  ...Object.hasOwn(raw, "cursor") ? { after: decodeCursor(criteria, raw.cursor) } : {}
@@ -1179,7 +1320,7 @@ function readOrderedActivities(criteria, input, maxRows) {
1179
1320
  const code = "store_incompatible";
1180
1321
  let previous = criteria.after;
1181
1322
  return readArray(input, maxRows, code, (row) => {
1182
- const activity = readActivity(criteria.scope, row);
1323
+ const activity = readActivity(criteria.scope, row, code, criteria.capacity);
1183
1324
  if (previous && compareActivity(previous, activity) >= 0 || criteria.jobId !== null && criteria.jobId !== activity.jobId || criteria.from !== null && activity.finishedAt < criteria.from || criteria.before !== null && activity.finishedAt >= criteria.before) {
1184
1325
  invalid(code);
1185
1326
  }
@@ -1270,6 +1411,7 @@ function jobSummary(job) {
1270
1411
  const latest = job.attempts.at(-1)?.commit;
1271
1412
  return Object.freeze({
1272
1413
  version: EMAIL_FORMAT_VERSION,
1414
+ ...job.smtpCapacity ? { smtpCapacity: job.smtpCapacity } : {},
1273
1415
  scope: job.scope,
1274
1416
  jobId: job.jobId,
1275
1417
  key: Object.freeze({ ...job.key }),
@@ -1294,13 +1436,13 @@ function jobSummary(job) {
1294
1436
  ...summaryState
1295
1437
  });
1296
1438
  }
1297
- function copyCommit(commit) {
1298
- return Object.freeze({ ...commit, result: readAttemptResult(commit.result, STORED2) });
1439
+ function copyCommit(commit, capacity) {
1440
+ return Object.freeze({ ...commit, result: readAttemptResult(commit.result, STORED2, false, capacity) });
1299
1441
  }
1300
- function readStoredSnapshot(job, input) {
1442
+ function readStoredSnapshot(job, input, capacity) {
1301
1443
  let validated;
1302
1444
  try {
1303
- validated = validateSnapshot(input);
1445
+ validated = validateSnapshot(input, capacity);
1304
1446
  } catch {
1305
1447
  return invalid(STORED2);
1306
1448
  }
@@ -1367,7 +1509,7 @@ function readState(input) {
1367
1509
  }
1368
1510
  return invalid(STORED2);
1369
1511
  }
1370
- function readLedgerAttempt(input, job) {
1512
+ function readLedgerAttempt(input, job, capacity) {
1371
1513
  const entry = readRecord(input, ["commit", "digest"], ["ownerDigest", "permitUntil", "projectionAckAt"], STORED2);
1372
1514
  const raw = readRecord(
1373
1515
  entry.commit,
@@ -1380,14 +1522,14 @@ function readLedgerAttempt(input, job) {
1380
1522
  const handedOffAt = optionalTime(raw, "handedOffAt");
1381
1523
  const finishedAt = unixMs(raw.finishedAt, STORED2);
1382
1524
  const retryAt = optionalTime(raw, "retryAt");
1383
- const result2 = readAttemptResult(raw.result, STORED2);
1525
+ const result = readAttemptResult(raw.result, STORED2, false, capacity);
1384
1526
  const ownerDigest = Object.hasOwn(entry, "ownerDigest") ? hashToken(entry.ownerDigest, STORED2) : void 0;
1385
- const internal = result2.reason === "pre_handoff_lease_expired" || result2.reason === "post_handoff_lease_expired" || result2.reason === "cancelled";
1386
- if (raw.jobId !== job.jobId || startedAt >= job.expiresAt || finishedAt < startedAt || finishedAt > job.updatedAt || handedOffAt !== void 0 && (handedOffAt < startedAt || handedOffAt >= job.expiresAt || handedOffAt > finishedAt) || result2.reason === "cancelled" && finishedAt >= job.expiresAt || result2.reason === "expired" && finishedAt < job.expiresAt || result2.reason === "pre_handoff_lease_expired" && finishedAt - startedAt < WORKER_LIMIT_BOUNDS.leaseMs.min || result2.reason === "post_handoff_lease_expired" && (handedOffAt === void 0 || finishedAt - handedOffAt < WORKER_LIMIT_BOUNDS.leaseMs.min) || ownerDigest === void 0 !== internal) {
1527
+ const internal = result.reason === "pre_handoff_lease_expired" || result.reason === "post_handoff_lease_expired" || result.reason === "cancelled";
1528
+ if (raw.jobId !== job.jobId || startedAt >= job.expiresAt || finishedAt < startedAt || finishedAt > job.updatedAt || handedOffAt !== void 0 && (handedOffAt < startedAt || handedOffAt >= job.expiresAt || handedOffAt > finishedAt) || result.reason === "cancelled" && finishedAt >= job.expiresAt || result.reason === "expired" && finishedAt < job.expiresAt || result.reason === "pre_handoff_lease_expired" && finishedAt - startedAt < WORKER_LIMIT_BOUNDS.leaseMs.min || result.reason === "post_handoff_lease_expired" && (handedOffAt === void 0 || finishedAt - handedOffAt < WORKER_LIMIT_BOUNDS.leaseMs.min) || ownerDigest === void 0 !== internal) {
1387
1529
  invalid(STORED2);
1388
1530
  }
1389
- assertEvidencePhase(result2.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", STORED2);
1390
- assertEvidenceContext(result2, job.provider, attemptId, job.recipientCounts, STORED2);
1531
+ assertEvidencePhase(result.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", STORED2);
1532
+ assertEvidenceContext(result, job.provider, attemptId, job.recipientCounts, STORED2);
1391
1533
  const commit = Object.freeze({
1392
1534
  jobId: job.jobId,
1393
1535
  attemptId,
@@ -1396,7 +1538,7 @@ function readLedgerAttempt(input, job) {
1396
1538
  startedAt,
1397
1539
  ...handedOffAt === void 0 ? {} : { handedOffAt },
1398
1540
  finishedAt,
1399
- result: result2,
1541
+ result,
1400
1542
  disposition: readDisposition(raw.disposition, STORED2),
1401
1543
  reason: raw.reason === "attempts_exhausted" ? raw.reason : readAttemptReason(raw.reason, STORED2),
1402
1544
  ...retryAt === void 0 ? {} : { retryAt }
@@ -1407,7 +1549,7 @@ function readLedgerAttempt(input, job) {
1407
1549
  invalid(STORED2);
1408
1550
  }
1409
1551
  const digest2 = hashToken(entry.digest, STORED2);
1410
- if (digest2 !== activityDigest(activityFor(job, commit))) invalid(STORED2);
1552
+ if (digest2 !== activityDigest(activityFor(job, commit, capacity), capacity)) invalid(STORED2);
1411
1553
  return Object.freeze({
1412
1554
  commit,
1413
1555
  digest: digest2,
@@ -1428,12 +1570,12 @@ function assertHistory(job) {
1428
1570
  let pending = false;
1429
1571
  let lastAck = 0;
1430
1572
  for (const { commit, permitUntil, projectionAckAt } of job.attempts) {
1431
- const { attemptId, ordinal: ordinal2, startedAt, finishedAt, result: result2, disposition, reason, retryAt } = commit;
1573
+ const { attemptId, ordinal: ordinal2, startedAt, finishedAt, result, disposition, reason, retryAt } = commit;
1432
1574
  if (nextAt === void 0 || startedAt < nextAt || seen.has(attemptId) || ordinal2 !== seen.size + 1 || !manual && ordinal2 > retry.maxAttempts) {
1433
1575
  invalid(STORED2);
1434
1576
  }
1435
1577
  seen.add(attemptId);
1436
- const expected = attemptEffect(result2, attemptId, ordinal2, manual, retry, expiresAt, finishedAt);
1578
+ const expected = attemptEffect(result, attemptId, ordinal2, manual, retry, expiresAt, finishedAt);
1437
1579
  if (disposition !== expected.disposition || reason !== expected.reason || retryAt !== expected.retryAt)
1438
1580
  invalid(STORED2);
1439
1581
  if (permitUntil !== void 0) {
@@ -1491,7 +1633,7 @@ function assertHistory(job) {
1491
1633
  if (job.snapshot || retireAt === void 0 || retireAt > job.updatedAt) invalid(STORED2);
1492
1634
  }
1493
1635
  }
1494
- function readJobRecord(scope2, input) {
1636
+ function readJobRecord(scope2, input, capacity) {
1495
1637
  const raw = readRecord(
1496
1638
  input,
1497
1639
  [
@@ -1518,27 +1660,26 @@ function readJobRecord(scope2, input) {
1518
1660
  "attempts",
1519
1661
  "resolutions"
1520
1662
  ],
1521
- ["snapshot", "projectionPermitUntil", "retiring"],
1663
+ ["snapshot", "projectionPermitUntil", "retiring", "smtpCapacity", "intentHash"],
1522
1664
  STORED2
1523
1665
  );
1524
1666
  if (raw.version !== EMAIL_FORMAT_VERSION || scopeToken(raw.scope, STORED2) !== scope2) invalid(STORED2);
1525
- const counts = readRecord(raw.recipientCounts, ["to", "cc", "bcc"], [], STORED2);
1526
- const recipients = Object.freeze({
1527
- to: integer(counts.to, 0, MESSAGE_LIMITS.recipients, STORED2),
1528
- cc: integer(counts.cc, 0, MESSAGE_LIMITS.recipients, STORED2),
1529
- bcc: integer(counts.bcc, 0, MESSAGE_LIMITS.recipients, STORED2)
1530
- });
1531
- integer(recipients.to + recipients.cc + recipients.bcc, 1, MESSAGE_LIMITS.recipients, STORED2);
1667
+ assertCapacityTag(raw, capacity, STORED2);
1668
+ const recipients = readRecipientCounts(raw.recipientCounts, STORED2, capacity);
1532
1669
  const key = validateAdmissionKey(raw.key, STORED2);
1533
1670
  const admissionKey = encodeAdmissionKey(key);
1534
1671
  if (raw.admissionKey !== admissionKey) invalid(STORED2);
1672
+ if (!capacity && Object.hasOwn(raw, "intentHash")) invalid(STORED2);
1673
+ const intentHash = capacity ? hashToken(raw.intentHash, STORED2) : void 0;
1535
1674
  const base = {
1536
1675
  version: EMAIL_FORMAT_VERSION,
1676
+ ...capacityTag(capacity),
1537
1677
  scope: scope2,
1538
1678
  jobId: readStoreId(raw.jobId, STORED2),
1539
1679
  key,
1540
1680
  admissionKey,
1541
1681
  fingerprint: hashToken(raw.fingerprint, STORED2),
1682
+ ...intentHash === void 0 ? {} : { intentHash },
1542
1683
  snapshotHash: hashToken(raw.snapshotHash, STORED2),
1543
1684
  retry: readRetryPolicy(raw.retry, STORED2),
1544
1685
  retention: readRetentionPolicy(raw.retention, STORED2),
@@ -1554,6 +1695,10 @@ function readJobRecord(scope2, input) {
1554
1695
  revision: readStoreId(raw.revision, STORED2),
1555
1696
  state: readState(raw.state)
1556
1697
  };
1698
+ assertCapacityProvider(base.provider, capacity, STORED2);
1699
+ if (intentHash !== void 0 && base.fingerprint !== fingerprintFor({ ...base, templateKey: base.template.key, intentHash }, capacity)) {
1700
+ invalid(STORED2);
1701
+ }
1557
1702
  if (base.createdAt > base.updatedAt || Math.max(base.createdAt, base.scheduleAt ?? 0) >= base.expiresAt || base.provider.kind === "sendgrid" && !recipients.to) {
1558
1703
  invalid(STORED2);
1559
1704
  }
@@ -1562,8 +1707,8 @@ function readJobRecord(scope2, input) {
1562
1707
  if (retiring && raw.retiring !== true) invalid(STORED2);
1563
1708
  const job = Object.freeze({
1564
1709
  ...base,
1565
- ...Object.hasOwn(raw, "snapshot") ? { snapshot: readStoredSnapshot(base, raw.snapshot) } : {},
1566
- attempts: readArray(raw.attempts, MAX_ATTEMPT_LEDGER, STORED2, (entry) => readLedgerAttempt(entry, base)),
1710
+ ...Object.hasOwn(raw, "snapshot") ? { snapshot: readStoredSnapshot(base, raw.snapshot, capacity) } : {},
1711
+ attempts: readArray(raw.attempts, MAX_ATTEMPT_LEDGER, STORED2, (entry) => readLedgerAttempt(entry, base, capacity)),
1567
1712
  resolutions: readArray(raw.resolutions, 2, STORED2, readUnknownResolution),
1568
1713
  ...projectionPermitUntil === void 0 ? {} : { projectionPermitUntil },
1569
1714
  ...retiring ? { retiring: true } : {}
@@ -1572,6 +1717,11 @@ function readJobRecord(scope2, input) {
1572
1717
  return job;
1573
1718
  }
1574
1719
 
1720
+ // src/internal/smtp-attachments.ts
1721
+ function assertSmtpAttachmentTypes(refs) {
1722
+ if (refs.some(({ contentType }) => /^(?:message|multipart)\//.test(contentType))) invalid("invalid_snapshot");
1723
+ }
1724
+
1575
1725
  // src/internal/job-transitions.ts
1576
1726
  function guard(job, { now }, before) {
1577
1727
  if (unixMs(now, "store_unavailable") < job.updatedAt || before !== void 0 && now >= before) {
@@ -1595,15 +1745,18 @@ function replace(job, time2, patch, value, before, pendingAck) {
1595
1745
  write: { kind: "replace", guard: pendingAck ? { ...expect, pendingAck } : expect, next }
1596
1746
  };
1597
1747
  }
1598
- function newJob(admission, time2) {
1748
+ function newJob(admission, time2, capacity) {
1599
1749
  const { command, jobId, retry, retention, admissionKey } = admission;
1600
1750
  const { scope: scope2, key, scheduleAt, fingerprint, snapshotHash, snapshot } = command;
1601
1751
  const now = unixMs(time2.now, "store_unavailable");
1602
1752
  if (snapshot.preparedAt - now > MAX_PREPARED_AT_SKEW_MS) invalid("invalid_snapshot");
1603
1753
  const nextAt = Math.max(now, scheduleAt ?? now);
1604
1754
  if (nextAt >= snapshot.expiresAt) invalid("expired");
1755
+ if (snapshot.kind === "smtp") assertSmtpAttachmentTypes(snapshot.attachments);
1605
1756
  return Object.freeze({
1606
1757
  version: EMAIL_FORMAT_VERSION,
1758
+ ...capacityTag(capacity),
1759
+ ...capacity ? { intentHash: command.intentHash } : {},
1607
1760
  scope: scope2,
1608
1761
  jobId,
1609
1762
  key,
@@ -1642,14 +1795,18 @@ function liveLease(job, fence, phase, now) {
1642
1795
  }
1643
1796
  return lease;
1644
1797
  }
1645
- function claimJob(job, claim, time2) {
1798
+ function claimEligibility(job, now) {
1799
+ if (job.state.state !== "queued" || job.state.nextAt > now) return "not_due";
1800
+ return now >= job.expiresAt ? "expired" : "eligible";
1801
+ }
1802
+ function claimJob(job, claim, time2, capacity) {
1646
1803
  const { now } = time2;
1647
- if (job.state.state !== "queued" || job.state.nextAt > now || now >= job.expiresAt) return null;
1804
+ if (claimEligibility(job, now) !== "eligible") return null;
1648
1805
  const manual = hasRedrive(job);
1649
1806
  const ordinal2 = job.attempts.length + 1;
1650
1807
  if (ordinal2 > MAX_ATTEMPT_LEDGER || !manual && ordinal2 > job.retry.maxAttempts) invalid("store_incompatible");
1651
1808
  if (job.attempts.some(({ commit }) => commit.attemptId === claim.attemptId)) invalid("invalid_command");
1652
- const snapshot = readStoredSnapshot(job, job.snapshot);
1809
+ const snapshot = readStoredSnapshot(job, job.snapshot, capacity);
1653
1810
  const lease = Object.freeze({
1654
1811
  attemptId: claim.attemptId,
1655
1812
  token: claim.token,
@@ -1672,6 +1829,20 @@ function claimJob(job, claim, time2) {
1672
1829
  Math.min(job.expiresAt, lease.leaseEndsAt)
1673
1830
  );
1674
1831
  }
1832
+ var EXPIRY_MAINTENANCE_REQUIRED = Object.freeze({ status: "expiry_maintenance_required" });
1833
+ function claimWindow(claim, candidateLimit, capacity) {
1834
+ let expired = 0;
1835
+ return {
1836
+ decide(job, time2) {
1837
+ const decision = claimJob(job, claim, time2, capacity);
1838
+ if (decision === null && claimEligibility(job, time2.now) === "expired") expired++;
1839
+ return decision;
1840
+ },
1841
+ result(next) {
1842
+ return next.status !== "applied" && expired === candidateLimit ? EXPIRY_MAINTENANCE_REQUIRED : next;
1843
+ }
1844
+ };
1845
+ }
1675
1846
  function renewJob(job, fence, leaseMs, time2) {
1676
1847
  const lease = liveLease(job, fence, "pre_handoff", time2.now);
1677
1848
  if (!lease || time2.now >= job.expiresAt) return null;
@@ -1709,11 +1880,11 @@ function markJob(job, fence, leaseMs, time2) {
1709
1880
  Math.min(job.expiresAt, lease.leaseEndsAt, grant.leaseEndsAt)
1710
1881
  );
1711
1882
  }
1712
- function finalize(job, lease, operationId, result2, time2, owner) {
1883
+ function finalize(job, lease, operationId, result, time2, owner, capacity) {
1713
1884
  const { now } = time2;
1714
1885
  const { attemptId, startedAt, handedOffAt } = lease;
1715
1886
  const ordinal2 = job.attempts.length + 1;
1716
- const effect = attemptEffect(result2, attemptId, ordinal2, hasRedrive(job), job.retry, job.expiresAt, now);
1887
+ const effect = attemptEffect(result, attemptId, ordinal2, hasRedrive(job), job.retry, job.expiresAt, now);
1717
1888
  const commit = Object.freeze({
1718
1889
  jobId: job.jobId,
1719
1890
  attemptId,
@@ -1722,31 +1893,31 @@ function finalize(job, lease, operationId, result2, time2, owner) {
1722
1893
  startedAt,
1723
1894
  ...handedOffAt === void 0 ? {} : { handedOffAt },
1724
1895
  finishedAt: now,
1725
- result: result2,
1896
+ result,
1726
1897
  ...effect
1727
1898
  });
1728
1899
  const entry = Object.freeze({
1729
1900
  commit,
1730
- digest: activityDigest(activityFor(job, commit)),
1901
+ digest: activityDigest(activityFor(job, commit, capacity), capacity),
1731
1902
  ...owner ? { ownerDigest: sha256(lease.token) } : {}
1732
1903
  });
1733
1904
  const state = effect.disposition === "retry_scheduled" ? Object.freeze({ state: "queued", nextAt: effect.retryAt }) : terminalState(effect.disposition, effect.reason, now);
1734
1905
  let before = owner ? lease.leaseEndsAt : void 0;
1735
- if (result2.reason === "cancelled" || result2.retry === "safe_transient" && effect.disposition !== "expired") {
1906
+ if (result.reason === "cancelled" || result.retry === "safe_transient" && effect.disposition !== "expired") {
1736
1907
  before = Math.min(before ?? job.expiresAt, job.expiresAt);
1737
1908
  }
1738
1909
  return replace(
1739
1910
  job,
1740
1911
  time2,
1741
1912
  { ...job, state, attempts: Object.freeze([...job.attempts, entry]) },
1742
- () => copyCommit(commit),
1913
+ () => copyCommit(commit, capacity),
1743
1914
  before
1744
1915
  );
1745
1916
  }
1746
- function finishJob(job, request, time2) {
1747
- const { fence, phase, operationId, result: result2 } = request;
1917
+ function finishJob(job, request, time2, capacity) {
1918
+ const { fence, phase, operationId, result } = request;
1748
1919
  if (job.jobId !== fence.jobId) return null;
1749
- assertEvidencePhase(result2.reason, phase, "owner", "invalid_command");
1920
+ assertEvidencePhase(result.reason, phase, "owner", "invalid_command");
1750
1921
  const previous = job.attempts.find(({ commit }) => commit.attemptId === fence.attemptId);
1751
1922
  if (previous) {
1752
1923
  const { commit } = previous;
@@ -1754,28 +1925,28 @@ function finishJob(job, request, time2) {
1754
1925
  if (previous.ownerDigest !== sha256(fence.token) || commit.operationId !== operationId || previousPhase !== phase) {
1755
1926
  return null;
1756
1927
  }
1757
- if (hashJson(result2, 8192, "invalid_command") !== hashJson(commit.result, 8192, "store_incompatible")) {
1928
+ if (sha256(encodeEvidence(result, "invalid_command", capacity)) !== sha256(encodeEvidence(commit.result, "store_incompatible", capacity))) {
1758
1929
  invalid("invalid_command");
1759
1930
  }
1760
- return { value: copyCommit(commit) };
1931
+ return { value: copyCommit(commit, capacity) };
1761
1932
  }
1762
1933
  const lease = liveLease(job, fence, phase, time2.now);
1763
1934
  if (!lease) return null;
1764
- if (result2.reason === "expired" && time2.now < job.expiresAt) invalid("invalid_command");
1765
- assertEvidenceContext(result2, job.provider, fence.attemptId, job.recipientCounts, "invalid_command");
1766
- return finalize(job, lease, operationId, result2, time2, true);
1935
+ if (result.reason === "expired" && time2.now < job.expiresAt) invalid("invalid_command");
1936
+ assertEvidenceContext(result, job.provider, fence.attemptId, job.recipientCounts, "invalid_command");
1937
+ return finalize(job, lease, operationId, result, time2, true, capacity);
1767
1938
  }
1768
- function recoverJob(job, operationId, time2) {
1939
+ function recoverJob(job, operationId, time2, capacity) {
1769
1940
  if (job.state.state !== "leased" || time2.now < job.state.lease.leaseEndsAt) return null;
1770
1941
  const { lease } = job.state;
1771
1942
  const reason = lease.handedOffAt === void 0 ? "pre_handoff_lease_expired" : "post_handoff_lease_expired";
1772
- return finalize(job, lease, operationId, lifecycleEvidence(reason), time2, false);
1943
+ return finalize(job, lease, operationId, lifecycleEvidence(reason), time2, false, capacity);
1773
1944
  }
1774
1945
  function expireJob(job, time2) {
1775
1946
  if (job.state.state !== "queued" || time2.now < job.expiresAt) return null;
1776
1947
  return replace(job, time2, { ...job, state: terminalState("expired", "expired", time2.now) }, jobSummary);
1777
1948
  }
1778
- function cancelJob(job, operationId, time2) {
1949
+ function cancelJob(job, operationId, time2, capacity) {
1779
1950
  const { state } = job;
1780
1951
  if (state.state === "terminal") {
1781
1952
  return {
@@ -1789,7 +1960,7 @@ function cancelJob(job, operationId, time2) {
1789
1960
  return { value: Object.freeze({ status: "too_late", job: jobSummary(job) }) };
1790
1961
  }
1791
1962
  if (state.state === "leased") {
1792
- const decision = finalize(job, state.lease, operationId, lifecycleEvidence("cancelled"), time2, false);
1963
+ const decision = finalize(job, state.lease, operationId, lifecycleEvidence("cancelled"), time2, false, capacity);
1793
1964
  const { write } = decision;
1794
1965
  if (write?.kind !== "replace") invalid("store_incompatible");
1795
1966
  return { write, value: Object.freeze({ status: "cancelled", job: jobSummary(write.next) }) };
@@ -1834,11 +2005,11 @@ function resolveJob(job, request, time2) {
1834
2005
  function replaceAttempt(job, previous, entry) {
1835
2006
  return Object.freeze(job.attempts.map((attempt) => attempt === previous ? Object.freeze(entry) : attempt));
1836
2007
  }
1837
- function reserveJobProjection(job, time2) {
2008
+ function reserveJobProjection(job, time2, capacity) {
1838
2009
  const entry = pendingAttempt(job);
1839
2010
  if (job.retiring || !entry || entry.commit.finishedAt > time2.now) return null;
1840
2011
  const permitUntil = timeAfter(time2.now, PROJECTION_PERMIT_MS) ?? invalid("store_unavailable");
1841
- const activity = activityFor(job, entry.commit);
2012
+ const activity = activityFor(job, entry.commit, capacity);
1842
2013
  const permit = Object.freeze({ activity, digest: entry.digest, permitUntil });
1843
2014
  const attempts = replaceAttempt(job, entry, { ...entry, permitUntil });
1844
2015
  return replace(
@@ -2007,9 +2178,9 @@ var MongoConnection = class {
2007
2178
  return { kind: "ack", reply };
2008
2179
  }
2009
2180
  async read(binding, budget, command, target) {
2010
- const result2 = await this.exec(binding, budget, command, target);
2011
- if (result2.kind !== "ack") return invalid("store_unavailable");
2012
- return result2.reply;
2181
+ const result = await this.exec(binding, budget, command, target);
2182
+ if (result.kind !== "ack") return invalid("store_unavailable");
2183
+ return result.reply;
2013
2184
  }
2014
2185
  async write(binding, budget, command, definite) {
2015
2186
  return this.exec(binding, budget, command, "store", true, definite);
@@ -2119,9 +2290,9 @@ var jobOptional = [
2119
2290
  "pendingAt",
2120
2291
  "nextCleanupAt"
2121
2292
  ];
2122
- function readJobBson(scope2, raw) {
2123
- const { _id, lifecycle: lifecycle2, messageExpiresAt, state, nextAt, expiresAt, leaseEndsAt, pendingAt, nextCleanupAt, ...rest } = readRecord(raw, jobRequired, jobOptional, STORED3);
2124
- const job = readJobRecord(scope2, { ...rest, state: lifecycle2, expiresAt: messageExpiresAt });
2293
+ function readJobBson(scope2, raw, capacity) {
2294
+ const { _id, lifecycle: lifecycle2, messageExpiresAt, state, nextAt, expiresAt, leaseEndsAt, pendingAt, nextCleanupAt, ...rest } = readRecord(raw, jobRequired, capacity ? [...jobOptional, "smtpCapacity", "intentHash"] : jobOptional, STORED3);
2295
+ const job = readJobRecord(scope2, { ...rest, state: lifecycle2, expiresAt: messageExpiresAt }, capacity);
2125
2296
  const selectors = jobSelectors(job);
2126
2297
  for (const [key, value, expected] of [
2127
2298
  ["state", state, selectors.state],
@@ -2152,14 +2323,15 @@ var activityRequired = [
2152
2323
  "disposition"
2153
2324
  ];
2154
2325
  var activityOptional = ["handedOffAt"];
2155
- function readActivityBson(expectedScope, row) {
2326
+ function readActivityBson(expectedScope, row, capacity) {
2156
2327
  if (!Object.hasOwn(row, "complete")) {
2157
- const { _id: _id2, scope: scope2, jobId, attemptId, stubDeleteAt } = readRecord(
2328
+ const { _id: _id2, scope: scope2, jobId, attemptId, stubDeleteAt, ...tag } = readRecord(
2158
2329
  row,
2159
2330
  [...activityIdentity, "stubDeleteAt"],
2160
- [],
2331
+ capacity ? ["smtpCapacity"] : [],
2161
2332
  STORED3
2162
2333
  );
2334
+ assertCapacityTag(tag, capacity, STORED3);
2163
2335
  readStoreId(_id2, STORED3);
2164
2336
  readStoreId(jobId, STORED3);
2165
2337
  readStoreId(attemptId, STORED3);
@@ -2167,9 +2339,14 @@ function readActivityBson(expectedScope, row) {
2167
2339
  unixMs(stubDeleteAt.getTime(), STORED3);
2168
2340
  return;
2169
2341
  }
2170
- const { _id, complete, digest: digest2, ...activity } = readRecord(row, activityRequired, activityOptional, STORED3);
2342
+ const { _id, complete, digest: digest2, ...activity } = readRecord(
2343
+ row,
2344
+ activityRequired,
2345
+ capacity ? [...activityOptional, "smtpCapacity", "recipientCounts"] : activityOptional,
2346
+ STORED3
2347
+ );
2171
2348
  readStoreId(_id, STORED3);
2172
- const stored = readStoredActivity(expectedScope, { activity, digest: digest2 });
2349
+ const stored = readStoredActivity(expectedScope, { activity, digest: digest2 }, STORED3, capacity);
2173
2350
  if (complete !== true) invalid(STORED3);
2174
2351
  return stored;
2175
2352
  }
@@ -2199,49 +2376,58 @@ var provider = objectSchema({
2199
2376
  });
2200
2377
  var template = objectSchema({ key: string, revision: string });
2201
2378
  var correlation = { ...bsonObject, maxProperties: MESSAGE_LIMITS.correlationEntries, additionalProperties: string };
2202
- var recipient = objectSchema({
2203
- group: { enum: ["to", "cc", "bcc"] },
2204
- index: { ...numeric, minimum: 0, maximum: MESSAGE_LIMITS.recipients - 1 },
2205
- status: { enum: ["accepted", "rejected"] }
2206
- });
2207
- var result = {
2208
- outcome: string,
2209
- retry: { enum: ["never", "safe_transient"] },
2210
- stage: string,
2211
- reason: string,
2212
- recipients: { bsonType: "array", maxItems: MESSAGE_LIMITS.recipients, items: recipient },
2213
- messageId: { ...string, maxLength: "<00000000-0000-4000-8000-000000000000@email.invalid>".length },
2214
- providerMessageId: { ...string, maxLength: 128 }
2215
- };
2379
+ var smtpProvider = objectSchema({ kind: { enum: ["smtp"] }, key: string, mode: { enum: ["live"] } });
2380
+ function resultFields(capacity) {
2381
+ const max = recipientLimit(capacity);
2382
+ const recipient = objectSchema({
2383
+ group: { enum: ["to", "cc", "bcc"] },
2384
+ index: { ...numeric, minimum: 0, maximum: max - 1 },
2385
+ status: { enum: ["accepted", "rejected"] }
2386
+ });
2387
+ return {
2388
+ outcome: string,
2389
+ retry: { enum: ["never", "safe_transient"] },
2390
+ stage: string,
2391
+ reason: string,
2392
+ recipients: { bsonType: "array", maxItems: max, items: recipient },
2393
+ messageId: { ...string, maxLength: "<00000000-0000-4000-8000-000000000000@email.invalid>".length },
2394
+ ...capacity ? {} : { providerMessageId: { ...string, maxLength: 128 } }
2395
+ };
2396
+ }
2216
2397
  var resultOptional = ["recipients", "messageId", "providerMessageId"];
2217
- var ledgerAttempt = objectSchema(
2218
- {
2219
- commit: objectSchema(
2220
- {
2221
- jobId: uuid,
2222
- attemptId: uuid,
2223
- ordinal,
2224
- operationId: uuid,
2225
- startedAt: time,
2226
- handedOffAt: time,
2227
- finishedAt: time,
2228
- result: objectSchema(
2229
- { ...result, retryHint: objectSchema({ delayMs: numeric, notBefore: time }, ["delayMs", "notBefore"]) },
2230
- [...resultOptional, "retryHint"]
2231
- ),
2232
- disposition: string,
2233
- reason: string,
2234
- retryAt: time
2235
- },
2236
- ["handedOffAt", "retryAt"]
2237
- ),
2238
- digest,
2239
- ownerDigest: digest,
2240
- permitUntil: time,
2241
- projectionAckAt: time
2242
- },
2243
- ["ownerDigest", "permitUntil", "projectionAckAt"]
2244
- );
2398
+ function ledgerAttempt(capacity) {
2399
+ return objectSchema(
2400
+ {
2401
+ commit: objectSchema(
2402
+ {
2403
+ jobId: uuid,
2404
+ attemptId: uuid,
2405
+ ordinal,
2406
+ operationId: uuid,
2407
+ startedAt: time,
2408
+ handedOffAt: time,
2409
+ finishedAt: time,
2410
+ result: objectSchema(
2411
+ {
2412
+ ...resultFields(capacity),
2413
+ retryHint: objectSchema({ delayMs: numeric, notBefore: time }, ["delayMs", "notBefore"])
2414
+ },
2415
+ [...resultOptional, "retryHint"]
2416
+ ),
2417
+ disposition: string,
2418
+ reason: string,
2419
+ retryAt: time
2420
+ },
2421
+ ["handedOffAt", "retryAt"]
2422
+ ),
2423
+ digest,
2424
+ ownerDigest: digest,
2425
+ permitUntil: time,
2426
+ projectionAckAt: time
2427
+ },
2428
+ ["ownerDigest", "permitUntil", "projectionAckAt"]
2429
+ );
2430
+ }
2245
2431
  var lifecycle = {
2246
2432
  oneOf: [
2247
2433
  objectSchema({ state: { enum: ["queued"] }, nextAt: time }),
@@ -2271,13 +2457,57 @@ var lifecycle = {
2271
2457
  )
2272
2458
  ]
2273
2459
  };
2274
- function jobValidator() {
2460
+ function capacityField({ binding }) {
2275
2461
  return {
2462
+ smtpCapacity: objectSchema({
2463
+ format: { enum: [binding.format] },
2464
+ namespace: { enum: [binding.namespace] },
2465
+ maxRecipients: { ...numeric, enum: [binding.maxRecipients] }
2466
+ })
2467
+ };
2468
+ }
2469
+ function countsSchema(capacity) {
2470
+ const count = capacity ? { ...numeric, minimum: 0, maximum: recipientLimit(capacity) } : numeric;
2471
+ return objectSchema({ to: count, cc: count, bcc: count });
2472
+ }
2473
+ function smtpSnapshot(capacity) {
2474
+ const mailbox = objectSchema({ address: string, name: string }, ["name"]);
2475
+ const recipients = { bsonType: "array", maxItems: recipientLimit(capacity), items: mailbox };
2476
+ return objectSchema(
2477
+ {
2478
+ version,
2479
+ ...capacityField(capacity),
2480
+ kind: { enum: ["smtp"] },
2481
+ provider: smtpProvider,
2482
+ template,
2483
+ envelope: objectSchema({ from: mailbox, to: recipients, cc: recipients, bcc: recipients, replyTo: mailbox }, [
2484
+ "replyTo"
2485
+ ]),
2486
+ preparedAt: time,
2487
+ expiresAt: time,
2488
+ priority: { ...numeric, minimum: PRIORITY.min, maximum: PRIORITY.max },
2489
+ attachments: { bsonType: "array", maxItems: MESSAGE_LIMITS.attachments, items: bsonObject },
2490
+ correlation,
2491
+ subject: string,
2492
+ html: string,
2493
+ text: string
2494
+ },
2495
+ ["html", "text"]
2496
+ );
2497
+ }
2498
+ function withBsonLimit(validator, maxBytes) {
2499
+ return maxBytes === void 0 ? validator : {
2500
+ $and: [validator, { $expr: { $lte: [{ $bsonSize: "$$ROOT" }, maxBytes] } }]
2501
+ };
2502
+ }
2503
+ function jobValidator(capacity) {
2504
+ const validator = {
2276
2505
  $jsonSchema: {
2277
2506
  ...objectSchema(
2278
2507
  {
2279
2508
  _id: string,
2280
2509
  version,
2510
+ ...capacity ? { ...capacityField(capacity), intentHash: digest } : {},
2281
2511
  scope,
2282
2512
  jobId: uuid,
2283
2513
  key: {
@@ -2289,13 +2519,13 @@ function jobValidator() {
2289
2519
  admissionKey: string,
2290
2520
  fingerprint: digest,
2291
2521
  snapshotHash: digest,
2292
- snapshot: bsonObject,
2522
+ snapshot: capacity ? smtpSnapshot(capacity) : bsonObject,
2293
2523
  retry: objectSchema({ maxAttempts: numeric, baseDelayMs: numeric, maxDelayMs: numeric }),
2294
2524
  retention: objectSchema({ payloadMs: numeric, historyMs: numeric, idempotencyMs: numeric }),
2295
- provider,
2525
+ provider: capacity ? smtpProvider : provider,
2296
2526
  template,
2297
2527
  correlation,
2298
- recipientCounts: objectSchema({ to: numeric, cc: numeric, bcc: numeric }),
2528
+ recipientCounts: countsSchema(capacity),
2299
2529
  scheduleAt: { anyOf: [time, { bsonType: "null" }] },
2300
2530
  createdAt: time,
2301
2531
  updatedAt: time,
@@ -2304,7 +2534,7 @@ function jobValidator() {
2304
2534
  revision: uuid,
2305
2535
  lifecycle,
2306
2536
  state: { enum: ["queued", "leased", "terminal"] },
2307
- attempts: { bsonType: "array", items: ledgerAttempt, maxItems: MAX_ATTEMPT_LEDGER },
2537
+ attempts: { bsonType: "array", items: ledgerAttempt(capacity), maxItems: MAX_ATTEMPT_LEDGER },
2308
2538
  resolutions: {
2309
2539
  bsonType: "array",
2310
2540
  maxItems: 2,
@@ -2338,10 +2568,11 @@ function jobValidator() {
2338
2568
  ]
2339
2569
  }
2340
2570
  };
2571
+ return withBsonLimit(validator, capacity?.limits.jobBsonBytes);
2341
2572
  }
2342
- function activityValidator() {
2343
- const identity = { _id: uuid, scope, jobId: uuid, attemptId: uuid };
2344
- return {
2573
+ function activityValidator(capacity) {
2574
+ const identity = { _id: uuid, scope, jobId: uuid, attemptId: uuid, ...capacity ? capacityField(capacity) : {} };
2575
+ const validator = {
2345
2576
  $jsonSchema: {
2346
2577
  oneOf: [
2347
2578
  objectSchema(
@@ -2351,13 +2582,14 @@ function activityValidator() {
2351
2582
  complete: { enum: [true] },
2352
2583
  digest,
2353
2584
  ordinal,
2354
- provider,
2585
+ provider: capacity ? smtpProvider : provider,
2586
+ ...capacity ? { recipientCounts: countsSchema(capacity) } : {},
2355
2587
  template,
2356
2588
  correlation,
2357
2589
  startedAt: time,
2358
2590
  handedOffAt: time,
2359
2591
  finishedAt: time,
2360
- result: objectSchema(result, resultOptional),
2592
+ result: objectSchema(resultFields(capacity), resultOptional),
2361
2593
  disposition: string
2362
2594
  },
2363
2595
  activityOptional
@@ -2366,6 +2598,7 @@ function activityValidator() {
2366
2598
  ]
2367
2599
  }
2368
2600
  };
2601
+ return withBsonLimit(validator, capacity?.limits.activityBsonBytes);
2369
2602
  }
2370
2603
 
2371
2604
  // src/stores/mongoose/schema.ts
@@ -2405,18 +2638,24 @@ var activityIndexes = [
2405
2638
  },
2406
2639
  { name: "v1_activity_stub_ttl", key: { stubDeleteAt: 1 }, expireAfterSeconds: 0 }
2407
2640
  ];
2408
- function jobSchema(name) {
2409
- return { name, validator: jobValidator(), indexes: jobIndexes };
2641
+ function indexName(v1Name, capacity) {
2642
+ return capacity ? `v2_${v1Name.slice(3)}` : v1Name;
2643
+ }
2644
+ function laneIndexes(indexes, capacity) {
2645
+ return capacity ? indexes.map((index) => ({ ...index, name: indexName(index.name, capacity) })) : indexes;
2410
2646
  }
2411
- function activitySchema(name) {
2412
- return { name, validator: activityValidator(), indexes: activityIndexes };
2647
+ function jobSchema(name, capacity) {
2648
+ return { name, validator: jobValidator(capacity), indexes: laneIndexes(jobIndexes, capacity) };
2649
+ }
2650
+ function activitySchema(name, capacity) {
2651
+ return { name, validator: activityValidator(capacity), indexes: laneIndexes(activityIndexes, capacity) };
2413
2652
  }
2414
2653
  function simple(collation) {
2415
2654
  return collation === void 0 || (0, import_node_util5.isDeepStrictEqual)(collation, SIMPLE);
2416
2655
  }
2417
2656
  async function getCollection(io, binding, budget, name) {
2418
- const result2 = await io.read(binding, budget, { listCollections: 1, filter: { name }, cursor: { batchSize: 2 } });
2419
- const rows = batch(result2, 1, `${binding.db.databaseName}.$cmd.listCollections`);
2657
+ const result = await io.read(binding, budget, { listCollections: 1, filter: { name }, cursor: { batchSize: 2 } });
2658
+ const rows = batch(result, 1, `${binding.db.databaseName}.$cmd.listCollections`);
2420
2659
  return rows[0] === void 0 ? void 0 : doc(rows[0], "store_incompatible");
2421
2660
  }
2422
2661
  function checkCollection(row, schema) {
@@ -2433,8 +2672,8 @@ function matchesIndex(raw, index) {
2433
2672
  }
2434
2673
  async function missingIndexes(io, binding, budget, { name, indexes }) {
2435
2674
  const max = 64;
2436
- const result2 = await io.read(binding, budget, { listIndexes: name, cursor: { batchSize: max + 1 } });
2437
- const defs = batch(result2, max, `${binding.db.databaseName}.${name}`);
2675
+ const result = await io.read(binding, budget, { listIndexes: name, cursor: { batchSize: max + 1 } });
2676
+ const defs = batch(result, max, `${binding.db.databaseName}.${name}`);
2438
2677
  const required = [{ name: "_id_", key: { _id: 1 } }, ...indexes];
2439
2678
  const seen = /* @__PURE__ */ new Set();
2440
2679
  for (const def of defs) {
@@ -2446,9 +2685,15 @@ async function missingIndexes(io, binding, budget, { name, indexes }) {
2446
2685
  if (!seen.has("_id_")) invalid("store_incompatible");
2447
2686
  return indexes.filter((index) => !seen.has(index.name));
2448
2687
  }
2688
+ async function checkExistingCollection(io, binding, budget, schema) {
2689
+ const row = await getCollection(io, binding, budget, schema.name);
2690
+ if (!row) return;
2691
+ checkCollection(row, schema);
2692
+ await missingIndexes(io, binding, budget, schema);
2693
+ }
2449
2694
  async function prepareCollection(io, binding, budget, schema) {
2450
2695
  if (!await getCollection(io, binding, budget, schema.name)) {
2451
- const result2 = await io.write(
2696
+ const result = await io.write(
2452
2697
  binding,
2453
2698
  budget,
2454
2699
  {
@@ -2460,12 +2705,12 @@ async function prepareCollection(io, binding, budget, schema) {
2460
2705
  },
2461
2706
  [48, 2, 9, 72, 115]
2462
2707
  );
2463
- if (result2.kind === "definite_error" && result2.code !== 48) invalid("store_incompatible");
2708
+ if (result.kind === "definite_error" && result.code !== 48) invalid("store_incompatible");
2464
2709
  }
2465
2710
  checkCollection(await getCollection(io, binding, budget, schema.name), schema);
2466
2711
  const missing = await missingIndexes(io, binding, budget, schema);
2467
2712
  if (missing.length) {
2468
- const result2 = await io.write(
2713
+ const result = await io.write(
2469
2714
  binding,
2470
2715
  budget,
2471
2716
  {
@@ -2474,7 +2719,7 @@ async function prepareCollection(io, binding, budget, schema) {
2474
2719
  },
2475
2720
  [2, 67, 68, 72, 85, 86, 11e3]
2476
2721
  );
2477
- if (result2.kind === "definite_error") invalid("store_incompatible");
2722
+ if (result.kind === "definite_error") invalid("store_incompatible");
2478
2723
  if ((await missingIndexes(io, binding, budget, schema)).length) invalid("store_incompatible");
2479
2724
  }
2480
2725
  }
@@ -2495,13 +2740,22 @@ function modifiedValue(reply) {
2495
2740
  if (n !== (reply.value === null ? 0 : 1) || reply.value === void 0) invalid("write_unconfirmed");
2496
2741
  return reply.value;
2497
2742
  }
2498
- function casFilter({ scope: scope2, jobId, revision, state, retiring, pendingAck, atOrAfter, before }) {
2743
+ function capacityFilter(capacity) {
2744
+ const binding = capacity?.binding;
2745
+ return binding ? {
2746
+ "smtpCapacity.format": binding.format,
2747
+ "smtpCapacity.namespace": binding.namespace,
2748
+ "smtpCapacity.maxRecipients": binding.maxRecipients
2749
+ } : {};
2750
+ }
2751
+ function casFilter({ scope: scope2, jobId, revision, state, retiring, pendingAck, atOrAfter, before }, capacity) {
2499
2752
  const lease = state.state === "leased" ? state.lease : void 0;
2500
2753
  return {
2501
2754
  _id: jobIdKey(scope2, jobId),
2502
2755
  scope: scope2,
2503
2756
  jobId,
2504
2757
  version: EMAIL_FORMAT_VERSION,
2758
+ ...capacityFilter(capacity),
2505
2759
  revision,
2506
2760
  state: state.state,
2507
2761
  "lifecycle.state": state.state,
@@ -2528,16 +2782,18 @@ function casFilter({ scope: scope2, jobId, revision, state, retiring, pendingAck
2528
2782
  };
2529
2783
  }
2530
2784
  var MongoOperations = class {
2531
- constructor(io, binding, budget, names) {
2785
+ constructor(io, binding, budget, names, capacity) {
2532
2786
  this.io = io;
2533
2787
  this.binding = binding;
2534
2788
  this.budget = budget;
2535
2789
  this.names = names;
2790
+ this.capacity = capacity;
2536
2791
  }
2537
2792
  io;
2538
2793
  binding;
2539
2794
  budget;
2540
2795
  names;
2796
+ capacity;
2541
2797
  check() {
2542
2798
  this.budget.check();
2543
2799
  }
@@ -2551,7 +2807,7 @@ var MongoOperations = class {
2551
2807
  const reply = await this.io.read(this.binding, this.budget, {
2552
2808
  find,
2553
2809
  filter,
2554
- hint,
2810
+ hint: indexName(hint, this.capacity),
2555
2811
  collation: SIMPLE,
2556
2812
  readConcern: { level },
2557
2813
  limit,
@@ -2565,7 +2821,7 @@ var MongoOperations = class {
2565
2821
  async byJob(scope2, jobId) {
2566
2822
  const [raw] = await this.find(this.names.jobsCollection, { scope: scope2, jobId }, JOB_ID, 1, "linearizable");
2567
2823
  if (!raw) return;
2568
- const job = readJobBson(scope2, raw);
2824
+ const job = readJobBson(scope2, raw, this.capacity);
2569
2825
  if (job.jobId !== jobId) invalid("store_incompatible");
2570
2826
  this.check();
2571
2827
  return job;
@@ -2573,7 +2829,7 @@ var MongoOperations = class {
2573
2829
  async byAdmission(scope2, admissionKey) {
2574
2830
  const [raw] = await this.find(this.names.jobsCollection, { scope: scope2, admissionKey }, ADMISSION_ID, 1, "linearizable");
2575
2831
  if (!raw) return;
2576
- const job = readJobBson(scope2, raw);
2832
+ const job = readJobBson(scope2, raw, this.capacity);
2577
2833
  if (job.admissionKey !== admissionKey) invalid("store_incompatible");
2578
2834
  this.check();
2579
2835
  return job;
@@ -2583,18 +2839,18 @@ var MongoOperations = class {
2583
2839
  if (!raw) return;
2584
2840
  const { jobId, attemptId } = doc(raw, "store_incompatible");
2585
2841
  if (jobId !== identity.jobId || attemptId !== identity.attemptId) invalid("store_incompatible");
2586
- const row = readActivityBson(identity.scope, raw);
2842
+ const row = readActivityBson(identity.scope, raw, this.capacity);
2587
2843
  this.check();
2588
2844
  return row;
2589
2845
  }
2590
2846
  async insert(job) {
2591
- const result2 = await this.io.write(this.binding, this.budget, {
2847
+ const result = await this.io.write(this.binding, this.budget, {
2592
2848
  insert: this.names.jobsCollection,
2593
2849
  documents: [jobBson(job)]
2594
2850
  });
2595
- if (result2.kind !== "ack") invalid("write_unconfirmed");
2596
- const { n, writeErrors } = result2.reply;
2597
- if (n === 1 && !Object.hasOwn(result2.reply, "writeErrors")) return "inserted";
2851
+ if (result.kind !== "ack") invalid("write_unconfirmed");
2852
+ const { n, writeErrors } = result.reply;
2853
+ if (n === 1 && !Object.hasOwn(result.reply, "writeErrors")) return "inserted";
2598
2854
  if (n === 0 && Array.isArray(writeErrors) && writeErrors.length === 1) {
2599
2855
  const { code } = doc(writeErrors[0], "write_unconfirmed");
2600
2856
  if (code === 121) invalid("store_incompatible");
@@ -2613,23 +2869,23 @@ var MongoOperations = class {
2613
2869
  }
2614
2870
  async replace(write) {
2615
2871
  const { guard: guard2, next } = write;
2616
- const result2 = await this.io.write(
2872
+ const result = await this.io.write(
2617
2873
  this.binding,
2618
2874
  this.budget,
2619
2875
  {
2620
2876
  findAndModify: this.names.jobsCollection,
2621
- query: casFilter(guard2),
2877
+ query: casFilter(guard2, this.capacity),
2622
2878
  // Treat the whole replacement as literal, including rendered strings beginning with '$'.
2623
2879
  update: [{ $replaceWith: { $literal: jobBson(next) } }],
2624
2880
  fields: { _id: 1, revision: 1 },
2625
2881
  new: true,
2626
- hint: JOB_ID,
2882
+ hint: indexName(JOB_ID, this.capacity),
2627
2883
  collation: SIMPLE
2628
2884
  },
2629
2885
  [121]
2630
2886
  );
2631
- if (result2.kind === "definite_error") invalid("store_incompatible");
2632
- const value = modifiedValue(result2.reply);
2887
+ if (result.kind === "definite_error") invalid("store_incompatible");
2888
+ const value = modifiedValue(result.reply);
2633
2889
  if (value === null) return false;
2634
2890
  const { _id, revision } = doc(value, "write_unconfirmed");
2635
2891
  if (_id !== jobIdKey(next.scope, next.jobId) || revision !== next.revision) invalid("write_unconfirmed");
@@ -2644,7 +2900,7 @@ var MongoOperations = class {
2644
2900
  const identity = { scope: scope2, jobId, attemptId };
2645
2901
  const [raw] = await this.find(this.names.activitiesCollection, identity, ACTIVITY_ID, 1, "linearizable");
2646
2902
  if (raw) {
2647
- readActivityBson(scope2, raw);
2903
+ readActivityBson(scope2, raw, this.capacity);
2648
2904
  exact.push({ ...identity, _id: readStoreId(doc(raw, "store_incompatible")._id, "store_incompatible") });
2649
2905
  }
2650
2906
  }
@@ -2655,9 +2911,9 @@ var MongoOperations = class {
2655
2911
  delete: this.names.activitiesCollection,
2656
2912
  // An exact indexed delete per attempt in one ordered command.
2657
2913
  deletes: exact.map((identity) => ({
2658
- q: { ...identity, $expr: serverWindow(guard2.atOrAfter) },
2914
+ q: { ...identity, ...capacityFilter(this.capacity), $expr: serverWindow(guard2.atOrAfter) },
2659
2915
  limit: 1,
2660
- hint: ACTIVITY_ID,
2916
+ hint: indexName(ACTIVITY_ID, this.capacity),
2661
2917
  collation: SIMPLE
2662
2918
  }))
2663
2919
  });
@@ -2670,7 +2926,14 @@ var MongoOperations = class {
2670
2926
  }
2671
2927
  const outcome = await this.io.write(this.binding, this.budget, {
2672
2928
  delete: this.names.jobsCollection,
2673
- deletes: [{ q: casFilter(guard2), limit: 1, hint: JOB_ID, collation: SIMPLE }]
2929
+ deletes: [
2930
+ {
2931
+ q: casFilter(guard2, this.capacity),
2932
+ limit: 1,
2933
+ hint: indexName(JOB_ID, this.capacity),
2934
+ collation: SIMPLE
2935
+ }
2936
+ ]
2674
2937
  });
2675
2938
  if (outcome.kind !== "ack") invalid("write_unconfirmed");
2676
2939
  return writeCount(outcome.reply, 1) === 1;
@@ -2693,6 +2956,13 @@ var MongoOperations = class {
2693
2956
  }
2694
2957
  return invalid("busy");
2695
2958
  }
2959
+ get dueCandidateLimit() {
2960
+ return this.capacity?.limits.dueCandidates ?? MAX_STORE_CANDIDATES;
2961
+ }
2962
+ async claimNext(scope2, claim) {
2963
+ const window = claimWindow(claim, this.dueCandidateLimit, this.capacity);
2964
+ return window.result(await this.next(scope2, "nextAt", window.decide));
2965
+ }
2696
2966
  async next(scope2, due, decide) {
2697
2967
  const selectionAt = await this.now();
2698
2968
  const { name, state, sort } = dueIndexes[due];
@@ -2704,7 +2974,7 @@ var MongoOperations = class {
2704
2974
  [due]: { $exists: true, $lte: selectionAt }
2705
2975
  },
2706
2976
  name,
2707
- MAX_STORE_CANDIDATES,
2977
+ this.dueCandidateLimit,
2708
2978
  "majority",
2709
2979
  sort,
2710
2980
  { _id: 0, jobId: 1 }
@@ -2739,15 +3009,15 @@ var MongoOperations = class {
2739
3009
  const identity = activityKey(permit.activity);
2740
3010
  const activity = activityBson(permit);
2741
3011
  const candidateId = (0, import_node_crypto2.randomUUID)();
2742
- const result2 = await this.io.write(
3012
+ const result = await this.io.write(
2743
3013
  this.binding,
2744
3014
  this.budget,
2745
3015
  {
2746
3016
  findAndModify: this.names.activitiesCollection,
2747
- query: identity,
3017
+ query: { ...identity, ...capacityFilter(this.capacity) },
2748
3018
  new: true,
2749
3019
  upsert: true,
2750
- hint: ACTIVITY_ID,
3020
+ hint: indexName(ACTIVITY_ID, this.capacity),
2751
3021
  collation: SIMPLE,
2752
3022
  update: [
2753
3023
  {
@@ -2768,7 +3038,7 @@ var MongoOperations = class {
2768
3038
  ],
2769
3039
  default: {
2770
3040
  $mergeObjects: [
2771
- { $literal: identity },
3041
+ { $literal: { ...identity, ...capacityTag(this.capacity) } },
2772
3042
  { _id: { $literal: candidateId }, stubDeleteAt: { $add: ["$$NOW", ACTIVITY_STUB_TTL_MS] } }
2773
3043
  ]
2774
3044
  }
@@ -2779,10 +3049,14 @@ var MongoOperations = class {
2779
3049
  },
2780
3050
  [11e3, 121]
2781
3051
  );
2782
- if (result2.kind === "definite_error" && result2.code === 121) invalid("store_incompatible");
3052
+ if (result.kind === "definite_error" && result.code === 121) invalid("store_incompatible");
2783
3053
  let confirmedComplete = false;
2784
- if (result2.kind === "ack") {
2785
- const row = readActivityBson(identity.scope, doc(modifiedValue(result2.reply), "write_unconfirmed"));
3054
+ if (result.kind === "ack") {
3055
+ const row = readActivityBson(
3056
+ identity.scope,
3057
+ doc(modifiedValue(result.reply), "write_unconfirmed"),
3058
+ this.capacity
3059
+ );
2786
3060
  if (row && row.digest !== permit.digest) invalid("store_incompatible");
2787
3061
  confirmedComplete = row !== void 0;
2788
3062
  }
@@ -2840,7 +3114,7 @@ var MongoOperations = class {
2840
3114
  await readRange(Object.keys(range).length ? { finishedAt: range } : {});
2841
3115
  const page = activityPage(
2842
3116
  criteria,
2843
- rows.map((row) => readActivityBson(scope2, row)?.activity ?? invalid("store_incompatible"))
3117
+ rows.map((row) => readActivityBson(scope2, row, this.capacity)?.activity ?? invalid("store_incompatible"))
2844
3118
  );
2845
3119
  this.check();
2846
3120
  return page;
@@ -2849,11 +3123,25 @@ var MongoOperations = class {
2849
3123
 
2850
3124
  // src/mongoose.ts
2851
3125
  var MAX_IN_FLIGHT = 32;
2852
- function readNames(options) {
2853
- const keys = ["jobsCollection", "activitiesCollection", "jobsModelName", "activitiesModelName"];
2854
- const input = readRecord(options, [], keys, "invalid_config");
3126
+ var NAME_KEYS = ["jobsCollection", "activitiesCollection", "jobsModelName", "activitiesModelName"];
3127
+ function readStoreConfig(options) {
3128
+ const input = readRecord(options, [], [...NAME_KEYS, "smtpCapacity"], "invalid_config");
3129
+ const capacity = readCapacityOption(input);
3130
+ if (capacity) {
3131
+ if (NAME_KEYS.some((key) => Object.hasOwn(input, key))) invalid("invalid_config");
3132
+ const { namespace } = capacity.binding;
3133
+ const prefix = `email_smtp_v2.${namespace}`;
3134
+ const modelId = namespace.replaceAll("-", "_");
3135
+ const names2 = Object.freeze({
3136
+ jobsCollection: `${prefix}.jobs`,
3137
+ activitiesCollection: `${prefix}.activities`,
3138
+ jobsModelName: `EmailSmtpV2Job_${modelId}`,
3139
+ activitiesModelName: `EmailSmtpV2Activity_${modelId}`
3140
+ });
3141
+ return { names: names2, capacity };
3142
+ }
2855
3143
  const names = { ...MONGOOSE_DEFAULT_NAMES };
2856
- for (const key of keys) {
3144
+ for (const key of NAME_KEYS) {
2857
3145
  const value = input[key];
2858
3146
  if (value === void 0) continue;
2859
3147
  if (typeof value !== "string" || !/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(value)) invalid("invalid_config");
@@ -2861,18 +3149,18 @@ function readNames(options) {
2861
3149
  }
2862
3150
  if (names.jobsCollection === names.activitiesCollection || names.jobsModelName === names.activitiesModelName)
2863
3151
  invalid("invalid_config");
2864
- return Object.freeze(names);
3152
+ return { names: Object.freeze(names), capacity };
2865
3153
  }
2866
3154
  function createMongooseEmailStore(connection, options = {}) {
2867
3155
  checkConnectionType(connection);
2868
- const names = readNames(options);
3156
+ const { names, capacity } = readStoreConfig(options);
2869
3157
  const io = new MongoConnection(connection, names);
2870
3158
  let readyBinding;
2871
3159
  let preparing = false;
2872
3160
  let inFlight = 0;
2873
3161
  async function run(call, worker, fn) {
2874
- const { signal, timeoutMs } = readStoreCall(call, worker);
2875
- if (inFlight >= MAX_IN_FLIGHT) invalid("busy");
3162
+ const { signal, timeoutMs } = readStoreCall(call, worker, capacity);
3163
+ if (inFlight >= (capacity?.limits.mongoInFlight ?? MAX_IN_FLIGHT)) invalid("busy");
2876
3164
  const budget = createBudget(systemEmailClock, Math.min(timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS), signal);
2877
3165
  inFlight++;
2878
3166
  try {
@@ -2880,13 +3168,14 @@ function createMongooseEmailStore(connection, options = {}) {
2880
3168
  if (!readyBinding) invalid("store_unavailable");
2881
3169
  const binding = io.bind();
2882
3170
  if (binding.client !== readyBinding.client || binding.db !== readyBinding.db) invalid("store_unavailable");
2883
- return await fn(new MongoOperations(io, binding, budget, names));
3171
+ return await fn(new MongoOperations(io, binding, budget, names, capacity));
2884
3172
  } finally {
2885
3173
  inFlight--;
2886
3174
  budget.close();
2887
3175
  }
2888
3176
  }
2889
3177
  const store = {
3178
+ ...capacityTag(capacity),
2890
3179
  async ready(options2 = {}) {
2891
3180
  const { timeoutMs, signal } = readCallOptions(options2, CALL_BUDGETS.admissionOrAdmin);
2892
3181
  if (preparing || inFlight) invalid("busy");
@@ -2897,8 +3186,14 @@ function createMongooseEmailStore(connection, options = {}) {
2897
3186
  budget.check();
2898
3187
  const binding = io.bind();
2899
3188
  await io.verifyTopology(binding, budget);
2900
- await prepareCollection(io, binding, budget, jobSchema(names.jobsCollection));
2901
- await prepareCollection(io, binding, budget, activitySchema(names.activitiesCollection));
3189
+ const jobs = jobSchema(names.jobsCollection, capacity);
3190
+ const activities = activitySchema(names.activitiesCollection, capacity);
3191
+ if (capacity) {
3192
+ await checkExistingCollection(io, binding, budget, jobs);
3193
+ await checkExistingCollection(io, binding, budget, activities);
3194
+ }
3195
+ await prepareCollection(io, binding, budget, jobs);
3196
+ await prepareCollection(io, binding, budget, activities);
2902
3197
  const jobId = (0, import_node_crypto3.randomUUID)();
2903
3198
  const probe = { scope: "!readiness", jobId };
2904
3199
  for (const [find, filter, hint] of [
@@ -2909,7 +3204,7 @@ function createMongooseEmailStore(connection, options = {}) {
2909
3204
  await io.read(binding, budget, {
2910
3205
  find,
2911
3206
  filter,
2912
- hint,
3207
+ hint: indexName(hint, capacity),
2913
3208
  collation: SIMPLE,
2914
3209
  readConcern: { level: "linearizable" },
2915
3210
  singleBatch: true,
@@ -2935,10 +3230,10 @@ function createMongooseEmailStore(connection, options = {}) {
2935
3230
  },
2936
3231
  insert(scope2, input, call) {
2937
3232
  return run(call, false, async (ops) => {
2938
- const safe = readStoreAdmission(scopeToken(scope2), input);
3233
+ const safe = readStoreAdmission(scopeToken(scope2), input, capacity);
2939
3234
  if (await ops.byAdmission(scope2, safe.admissionKey)) return Object.freeze({ status: "duplicate" });
2940
3235
  if (await ops.byJob(scope2, safe.jobId)) invalid("invalid_command");
2941
- const job = newJob(safe, { now: await ops.now(), revision: (0, import_node_crypto3.randomUUID)() });
3236
+ const job = newJob(safe, { now: await ops.now(), revision: (0, import_node_crypto3.randomUUID)() }, capacity);
2942
3237
  const summary = jobSummary(job);
2943
3238
  return await ops.insert(job) === "inserted" ? Object.freeze({ status: "inserted", job: summary }) : Object.freeze({ status: "duplicate" });
2944
3239
  });
@@ -2954,13 +3249,13 @@ function createMongooseEmailStore(connection, options = {}) {
2954
3249
  const id = readStoreId(attemptId);
2955
3250
  const job = await ops.byJob(scopeToken(scope2), readStoreId(jobId));
2956
3251
  const commit = job?.attempts.find((entry) => entry.commit.attemptId === id)?.commit;
2957
- return commit ? copyCommit(commit) : null;
3252
+ return commit ? copyCommit(commit, capacity) : null;
2958
3253
  });
2959
3254
  },
2960
3255
  claimNext(scope2, input, call) {
2961
3256
  return run(call, true, (ops) => {
2962
3257
  const safe = readClaim(input);
2963
- return ops.next(scopeToken(scope2), "nextAt", (job, time2) => claimJob(job, safe, time2));
3258
+ return ops.claimNext(scopeToken(scope2), safe);
2964
3259
  });
2965
3260
  },
2966
3261
  renew(scope2, fence, leaseMs, call) {
@@ -2979,14 +3274,14 @@ function createMongooseEmailStore(connection, options = {}) {
2979
3274
  },
2980
3275
  finish(scope2, input, call) {
2981
3276
  return run(call, true, (ops) => {
2982
- const safe = readFinish(input);
2983
- return ops.point(scopeToken(scope2), safe.fence.jobId, (job, time2) => finishJob(job, safe, time2));
3277
+ const safe = readFinish(input, capacity);
3278
+ return ops.point(scopeToken(scope2), safe.fence.jobId, (job, time2) => finishJob(job, safe, time2, capacity));
2984
3279
  });
2985
3280
  },
2986
3281
  recoverNext(scope2, call) {
2987
3282
  return run(call, true, (ops) => {
2988
3283
  const operationId = (0, import_node_crypto3.randomUUID)();
2989
- return ops.next(scopeToken(scope2), "leaseEndsAt", (job, time2) => recoverJob(job, operationId, time2));
3284
+ return ops.next(scopeToken(scope2), "leaseEndsAt", (job, time2) => recoverJob(job, operationId, time2, capacity));
2990
3285
  });
2991
3286
  },
2992
3287
  expireNext(scope2, call) {
@@ -2995,7 +3290,11 @@ function createMongooseEmailStore(connection, options = {}) {
2995
3290
  cancel(scope2, jobId, call) {
2996
3291
  return run(call, false, async (ops) => {
2997
3292
  const operationId = (0, import_node_crypto3.randomUUID)();
2998
- return await ops.point(scopeToken(scope2), readStoreId(jobId), (job, time2) => cancelJob(job, operationId, time2)) ?? Object.freeze({ status: "not_found" });
3293
+ return await ops.point(
3294
+ scopeToken(scope2),
3295
+ readStoreId(jobId),
3296
+ (job, time2) => cancelJob(job, operationId, time2, capacity)
3297
+ ) ?? Object.freeze({ status: "not_found" });
2999
3298
  });
3000
3299
  },
3001
3300
  resolveUnknown(scope2, input, call) {
@@ -3005,11 +3304,15 @@ function createMongooseEmailStore(connection, options = {}) {
3005
3304
  });
3006
3305
  },
3007
3306
  reserveProjection(scope2, call) {
3008
- return run(call, false, (ops) => ops.next(scopeToken(scope2), "pendingAt", reserveJobProjection));
3307
+ return run(
3308
+ call,
3309
+ false,
3310
+ (ops) => ops.next(scopeToken(scope2), "pendingAt", (job, time2) => reserveJobProjection(job, time2, capacity))
3311
+ );
3009
3312
  },
3010
3313
  putActivity(scope2, input, call) {
3011
3314
  return run(call, false, async (ops) => {
3012
- const permit = readProjectionPermit(scopeToken(scope2), input);
3315
+ const permit = readProjectionPermit(scopeToken(scope2), input, capacity);
3013
3316
  const identity = activityKey(permit.activity);
3014
3317
  const job = await ops.byJob(scope2, identity.jobId);
3015
3318
  const activity = await ops.byActivity(identity);
@@ -3021,7 +3324,7 @@ function createMongooseEmailStore(connection, options = {}) {
3021
3324
  },
3022
3325
  ackProjection(scope2, input, call) {
3023
3326
  return run(call, false, async (ops) => {
3024
- const permit = readProjectionPermit(scopeToken(scope2), input);
3327
+ const permit = readProjectionPermit(scopeToken(scope2), input, capacity);
3025
3328
  const identity = activityKey(permit.activity);
3026
3329
  return await ops.point(
3027
3330
  scope2,
@@ -3031,7 +3334,7 @@ function createMongooseEmailStore(connection, options = {}) {
3031
3334
  });
3032
3335
  },
3033
3336
  listActivities(scope2, query, call) {
3034
- return run(call, false, (ops) => ops.list(readActivityCriteria(scopeToken(scope2), query)));
3337
+ return run(call, false, (ops) => ops.list(readActivityCriteria(scopeToken(scope2), query, capacity)));
3035
3338
  },
3036
3339
  cleanupNext(scope2, call) {
3037
3340
  return run(call, false, (ops) => ops.next(scopeToken(scope2), "nextCleanupAt", cleanupJob));