@web-ts-toolkit/email-service 0.72.0 → 0.73.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/index.js CHANGED
@@ -301,6 +301,12 @@ function scopeToken(value, code = "invalid_command") {
301
301
  function identifier(value, code) {
302
302
  return opaqueToken(value, MESSAGE_LIMITS.identifierBytes, code);
303
303
  }
304
+ function uuidV4(value, code) {
305
+ 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)) {
306
+ invalid(code);
307
+ }
308
+ return value;
309
+ }
304
310
  function hashToken(value, code) {
305
311
  if (typeof value !== "string" || value.length !== 64 || !/^[0-9a-f]{64}$/.test(value)) invalid(code);
306
312
  return value;
@@ -622,9 +628,9 @@ function syncStage(budget, code, run) {
622
628
  // src/internal/canonical-json.ts
623
629
  var import_node_crypto = require("crypto");
624
630
  var treeLimits = { depth: MESSAGE_LIMITS.jsonDepth, values: MESSAGE_LIMITS.jsonValues };
625
- function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = treeLimits) {
631
+ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits2 = treeLimits) {
626
632
  let bytesLeft = maxBytes;
627
- let valuesLeft = limits.values;
633
+ let valuesLeft = limits2.values;
628
634
  const chunks = [];
629
635
  const ancestors = /* @__PURE__ */ new Set();
630
636
  function append(text, bytes = text.length) {
@@ -643,7 +649,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
643
649
  append(JSON.stringify(text), bytes);
644
650
  }
645
651
  function visit(value2, depth) {
646
- if (depth > limits.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
652
+ if (depth > limits2.depth || --valuesLeft < 0 || bytesLeft < 1) invalid(code);
647
653
  switch (typeof value2) {
648
654
  case "string":
649
655
  appendString(value2);
@@ -667,7 +673,7 @@ function canonicalJson(input, maxBytes, code = "invalid_snapshot", limits = tree
667
673
  if (ancestors.has(value2)) invalid(code);
668
674
  ancestors.add(value2);
669
675
  try {
670
- const maxChildren = depth === limits.depth ? 0 : valuesLeft;
676
+ const maxChildren = depth === limits2.depth ? 0 : valuesLeft;
671
677
  if (isArray(value2, code)) {
672
678
  const length = denseArrayLength(value2, maxChildren, code);
673
679
  if (length && 2 * length + 1 > bytesLeft) invalid(code);
@@ -710,10 +716,83 @@ function sha256(input) {
710
716
  function hashJson(input, maxBytes, code = "invalid_snapshot") {
711
717
  return sha256(canonicalJson(input, maxBytes, code).encoded);
712
718
  }
719
+ function encodeEvidence(input, code, capacity) {
720
+ return canonicalJson(input, capacity?.limits.evidenceBytes ?? 8192, code, capacity?.limits.evidenceTree).encoded;
721
+ }
713
722
 
714
723
  // src/internal/message-codecs.ts
715
724
  var import_node_net = require("net");
716
725
  var import_node_util4 = require("util");
726
+
727
+ // src/internal/smtp-capacity.ts
728
+ var MIN_RECIPIENTS = MESSAGE_LIMITS.recipients + 1;
729
+ var MAX_RECIPIENTS = 1e3;
730
+ var KIB = 1024;
731
+ var limits = Object.freeze({
732
+ snapshotBytes: 2 * KIB * KIB,
733
+ snapshotTree: Object.freeze({ depth: 4, values: 4096 }),
734
+ evidenceBytes: 64 * KIB,
735
+ evidenceTree: Object.freeze({ depth: 5, values: 4096 }),
736
+ jobBsonBytes: 4 * KIB * KIB,
737
+ activityBsonBytes: 128 * KIB,
738
+ registryCache: Object.freeze({ min: 0, default: 8, max: 16 }),
739
+ registryPending: Object.freeze({ min: 1, default: 2, max: 4 }),
740
+ servicePending: 4,
741
+ workerProfiles: 16,
742
+ workerConcurrency: Object.freeze({ min: 1, default: 1, max: 2 }),
743
+ runClaims: Object.freeze({ min: 1, default: 4, max: 16 }),
744
+ runMaintenance: Object.freeze({ min: 0, default: 4, max: 16 }),
745
+ adminMaintenance: Object.freeze({ min: 1, default: 4, max: 16 }),
746
+ page: Object.freeze({ min: 1, default: 8, max: 16 }),
747
+ memoryJobs: Object.freeze({ min: 1, default: 8, max: 16 }),
748
+ mongoInFlight: 4,
749
+ dueCandidates: 4
750
+ });
751
+ function readBinding(input, code) {
752
+ const { format, namespace, maxRecipients } = readRecord(input, ["format", "namespace", "maxRecipients"], [], code);
753
+ if (format !== "smtp-v2") invalid(code);
754
+ return Object.freeze({
755
+ format,
756
+ namespace: uuidV4(namespace, code),
757
+ maxRecipients: integer(maxRecipients, MIN_RECIPIENTS, MAX_RECIPIENTS, code)
758
+ });
759
+ }
760
+ function readCapacityOption(raw) {
761
+ if (!Object.hasOwn(raw, "smtpCapacity")) return;
762
+ return Object.freeze({ binding: readBinding(raw.smtpCapacity, "invalid_config"), limits });
763
+ }
764
+ function capacityTag(capacity) {
765
+ return capacity ? { smtpCapacity: capacity.binding } : {};
766
+ }
767
+ function recipientLimit(capacity) {
768
+ return capacity?.binding.maxRecipients ?? MESSAGE_LIMITS.recipients;
769
+ }
770
+ function matchesBinding(input, capacity, code) {
771
+ const binding = readBinding(input, code);
772
+ if (binding.namespace !== capacity.binding.namespace || binding.maxRecipients !== capacity.binding.maxRecipients) {
773
+ invalid(code);
774
+ }
775
+ }
776
+ function assertCapacityTag(raw, capacity, code) {
777
+ const tagged = Object.hasOwn(raw, "smtpCapacity");
778
+ if (capacity) {
779
+ if (!tagged) invalid(code);
780
+ matchesBinding(raw.smtpCapacity, capacity, code);
781
+ } else if (tagged) {
782
+ invalid(code);
783
+ }
784
+ }
785
+ function assertPortCapacity(port, capacity) {
786
+ const code = "invalid_config";
787
+ const binding = readPortMember(port, "smtpCapacity");
788
+ if (capacity) matchesBinding(binding, capacity, code);
789
+ else if (binding !== void 0) invalid(code);
790
+ }
791
+ function assertCapacityProvider(provider, capacity, code) {
792
+ if (capacity && provider.kind !== "smtp") invalid(code);
793
+ }
794
+
795
+ // src/internal/message-codecs.ts
717
796
  var L = MESSAGE_LIMITS;
718
797
  var SNAPSHOT = "invalid_snapshot";
719
798
  var DOT_ATOM = /^[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[A-Za-z0-9!#$%&'*+/=?^_`{|}~-]+)*$/;
@@ -750,7 +829,8 @@ function validateMailbox(input, code = SNAPSHOT) {
750
829
  ...Object.hasOwn(mailbox, "name") ? { name: headerString(mailbox.name, L.displayNameBytes, code) } : {}
751
830
  });
752
831
  }
753
- function validateEnvelope(input, kind, code = SNAPSHOT) {
832
+ function validateEnvelope(input, kind, code = SNAPSHOT, capacity) {
833
+ const limit = recipientLimit(capacity);
754
834
  const envelope = readRecord(input, ["from", "to", "cc", "bcc"], ["replyTo"], code);
755
835
  const seen = /* @__PURE__ */ new Set();
756
836
  const recipient = (raw) => {
@@ -761,9 +841,9 @@ function validateEnvelope(input, kind, code = SNAPSHOT) {
761
841
  return mailbox;
762
842
  };
763
843
  const from = validateMailbox(envelope.from, code);
764
- const to = readArray(envelope.to, L.recipients, code, recipient);
765
- const cc = readArray(envelope.cc, L.recipients - to.length, code, recipient);
766
- const bcc = readArray(envelope.bcc, L.recipients - to.length - cc.length, code, recipient);
844
+ const to = readArray(envelope.to, limit, code, recipient);
845
+ const cc = readArray(envelope.cc, limit - to.length, code, recipient);
846
+ const bcc = readArray(envelope.bcc, limit - to.length - cc.length, code, recipient);
767
847
  if (seen.size === 0 || kind === "sendgrid" && to.length === 0) invalid(code);
768
848
  return Object.freeze({
769
849
  from,
@@ -851,12 +931,17 @@ function validateExpiry(input, preparedAt, scheduleAt, code = SNAPSHOT) {
851
931
  }
852
932
  return expiresAt;
853
933
  }
854
- function hashSnapshot(snapshot) {
934
+ function hashSnapshot(snapshot, capacity) {
855
935
  return sha256(
856
- canonicalJson(snapshot, L.snapshotBytes, SNAPSHOT, { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }).encoded
936
+ canonicalJson(
937
+ snapshot,
938
+ capacity?.limits.snapshotBytes ?? L.snapshotBytes,
939
+ SNAPSHOT,
940
+ capacity?.limits.snapshotTree ?? { depth: L.jsonDepth + 1, values: L.jsonValues + 256 }
941
+ ).encoded
857
942
  );
858
943
  }
859
- function readSnapshot(input) {
944
+ function readSnapshot(input, capacity) {
860
945
  const dto = readRecord(
861
946
  input,
862
947
  [
@@ -871,17 +956,19 @@ function readSnapshot(input) {
871
956
  "attachments",
872
957
  "correlation"
873
958
  ],
874
- ["subject", "html", "text", "templateId", "data"],
959
+ ["subject", "html", "text", "templateId", "data", "smtpCapacity"],
875
960
  SNAPSHOT
876
961
  );
877
962
  if (dto.version !== EMAIL_FORMAT_VERSION || dto.kind !== "smtp" && dto.kind !== "sendgrid") invalid(SNAPSHOT);
963
+ assertCapacityTag(dto, capacity, SNAPSHOT);
878
964
  const provider = validateProviderRef(dto.provider);
879
965
  if (provider.kind !== dto.kind) invalid("provider_mismatch");
966
+ assertCapacityProvider(provider, capacity, "provider_mismatch");
880
967
  const preparedAt = unixMs(dto.preparedAt, SNAPSHOT);
881
968
  const common = {
882
969
  version: EMAIL_FORMAT_VERSION,
883
970
  template: validateTemplateIdentity(dto.template),
884
- envelope: validateEnvelope(dto.envelope, provider.kind),
971
+ envelope: validateEnvelope(dto.envelope, provider.kind, SNAPSHOT, capacity),
885
972
  preparedAt,
886
973
  expiresAt: validateExpiry(dto.expiresAt, preparedAt, null),
887
974
  priority: integer(dto.priority, PRIORITY.min, PRIORITY.max, SNAPSHOT),
@@ -895,7 +982,7 @@ function readSnapshot(input) {
895
982
  ...Object.hasOwn(dto, "html") ? { html: dto.html } : {},
896
983
  ...Object.hasOwn(dto, "text") ? { text: dto.text } : {}
897
984
  });
898
- return Object.freeze({ ...common, kind: provider.kind, provider, ...content });
985
+ return Object.freeze({ ...common, kind: provider.kind, provider, ...capacityTag(capacity), ...content });
899
986
  }
900
987
  if (Object.hasOwn(dto, "subject") || Object.hasOwn(dto, "html") || Object.hasOwn(dto, "text")) invalid(SNAPSHOT);
901
988
  return Object.freeze({
@@ -906,9 +993,9 @@ function readSnapshot(input) {
906
993
  data: copyJsonObject(dto.data, L.dataBytes, SNAPSHOT)
907
994
  });
908
995
  }
909
- function validateSnapshot(input) {
910
- const snapshot = readSnapshot(input);
911
- return { snapshot, snapshotHash: hashSnapshot(snapshot) };
996
+ function validateSnapshot(input, capacity) {
997
+ const snapshot = readSnapshot(input, capacity);
998
+ return { snapshot, snapshotHash: hashSnapshot(snapshot, capacity) };
912
999
  }
913
1000
 
914
1001
  // src/internal/command-codecs.ts
@@ -932,25 +1019,35 @@ function encodeAdmissionKey(key) {
932
1019
  function sameCommandMetadata(key, templateKey, provider, scheduleAt, expected) {
933
1020
  return encodeAdmissionKey(key) === encodeAdmissionKey(expected.key) && templateKey === expected.templateKey && provider.kind === expected.provider.kind && provider.key === expected.provider.key && provider.mode === expected.provider.mode && scheduleAt === expected.scheduleAt;
934
1021
  }
935
- function fingerprintFor(identity) {
1022
+ function fingerprintFor(identity, capacity) {
936
1023
  const { scope, key, templateKey, provider, scheduleAt, intentHash } = identity;
937
1024
  return hashJson(
938
- [EMAIL_FORMAT_VERSION, scope, key, templateKey, provider, scheduleAt, intentHash],
1025
+ [
1026
+ ...capacity ? ["smtp-v2-admission", capacity.binding] : [],
1027
+ EMAIL_FORMAT_VERSION,
1028
+ scope,
1029
+ key,
1030
+ templateKey,
1031
+ provider,
1032
+ scheduleAt,
1033
+ intentHash
1034
+ ],
939
1035
  MESSAGE_LIMITS.intentBytes
940
1036
  );
941
1037
  }
942
- function parseCommandIdentity(scope, command) {
1038
+ function parseCommandIdentity(scope, command, capacity) {
943
1039
  const code = "invalid_command";
944
1040
  const parsedScope = scopeToken(scope, code);
945
1041
  const raw = readRecord(command, ["key", "templateKey", "input", "provider", "intent"], ["scheduleAt"], code);
946
1042
  const key = validateAdmissionKey(raw.key, code);
947
1043
  const templateKey = identifier(raw.templateKey, code);
948
1044
  const provider = validateProviderRef(raw.provider, code);
1045
+ assertCapacityProvider(provider, capacity, "provider_mismatch");
949
1046
  const scheduleAt = raw.scheduleAt === void 0 ? null : unixMs(raw.scheduleAt, code);
950
1047
  const intent = canonicalJson(raw.intent, MESSAGE_LIMITS.intentBytes, code);
951
1048
  const identity = { scope: parsedScope, key, templateKey, provider, scheduleAt, intentHash: sha256(intent.encoded) };
952
1049
  return Object.freeze({
953
- identity: Object.freeze({ ...identity, fingerprint: fingerprintFor(identity) }),
1050
+ identity: Object.freeze({ ...identity, fingerprint: fingerprintFor(identity, capacity) }),
954
1051
  command: Object.freeze({
955
1052
  key,
956
1053
  templateKey,
@@ -961,35 +1058,40 @@ function parseCommandIdentity(scope, command) {
961
1058
  })
962
1059
  });
963
1060
  }
964
- function validatePreparedCommand(scope, input) {
1061
+ function validatePreparedCommand(scope, input, capacity) {
965
1062
  const expectedScope = scopeToken(scope);
966
1063
  const code = "invalid_snapshot";
967
1064
  const dto = readRecord(
968
1065
  input,
969
1066
  ["version", "scope", "key", "scheduleAt", "intentHash", "fingerprint", "snapshotHash", "snapshot"],
970
- [],
1067
+ ["smtpCapacity"],
971
1068
  code
972
1069
  );
973
1070
  if (dto.version !== EMAIL_FORMAT_VERSION || scopeToken(dto.scope, code) !== expectedScope) invalid(code);
1071
+ assertCapacityTag(dto, capacity, code);
974
1072
  const key = validateAdmissionKey(dto.key, code);
975
1073
  const scheduleAt = dto.scheduleAt === null ? null : unixMs(dto.scheduleAt, code);
976
1074
  const intentHash = hashToken(dto.intentHash, code);
977
1075
  const fingerprint = hashToken(dto.fingerprint, code);
978
1076
  const storedSnapshotHash = hashToken(dto.snapshotHash, code);
979
- const { snapshot, snapshotHash } = validateSnapshot(dto.snapshot);
1077
+ const { snapshot, snapshotHash } = validateSnapshot(dto.snapshot, capacity);
980
1078
  validateExpiry(snapshot.expiresAt, snapshot.preparedAt, scheduleAt);
981
- if (snapshotHash !== storedSnapshotHash || fingerprint !== fingerprintFor({
982
- scope: expectedScope,
983
- key,
984
- templateKey: snapshot.template.key,
985
- provider: snapshot.provider,
986
- scheduleAt,
987
- intentHash
988
- })) {
1079
+ if (snapshotHash !== storedSnapshotHash || fingerprint !== fingerprintFor(
1080
+ {
1081
+ scope: expectedScope,
1082
+ key,
1083
+ templateKey: snapshot.template.key,
1084
+ provider: snapshot.provider,
1085
+ scheduleAt,
1086
+ intentHash
1087
+ },
1088
+ capacity
1089
+ )) {
989
1090
  invalid(code);
990
1091
  }
991
1092
  return Object.freeze({
992
1093
  version: EMAIL_FORMAT_VERSION,
1094
+ ...capacityTag(capacity),
993
1095
  scope: expectedScope,
994
1096
  key,
995
1097
  scheduleAt,
@@ -1223,7 +1325,7 @@ function readDefinition(value) {
1223
1325
  }
1224
1326
  return invalid(code);
1225
1327
  }
1226
- function captureFields(raw, definition, context, scheduleAt, budget, slot) {
1328
+ function captureFields(raw, definition, context, scheduleAt, budget, slot, capacity) {
1227
1329
  const code = "invalid_snapshot";
1228
1330
  const fields = readRecord(
1229
1331
  raw,
@@ -1241,7 +1343,9 @@ function captureFields(raw, definition, context, scheduleAt, budget, slot) {
1241
1343
  bcc: fields.bcc === void 0 ? [] : fields.bcc,
1242
1344
  ...replyTo === void 0 ? {} : { replyTo }
1243
1345
  },
1244
- context.provider.kind
1346
+ context.provider.kind,
1347
+ code,
1348
+ capacity
1245
1349
  );
1246
1350
  const expiresAt = validateExpiry(
1247
1351
  fields.expiresAt === void 0 ? context.now + DEFAULT_EXPIRY_MS : fields.expiresAt,
@@ -1264,18 +1368,25 @@ function findRegistryPreparation(registry) {
1264
1368
  }
1265
1369
  function createEmailTemplateRegistry(definitions, options = {}) {
1266
1370
  const code = "invalid_config";
1267
- const config = readRecord(options, [], ["clock", "cacheEntries", "maxPending", "helpers"], code);
1371
+ const config = readRecord(options, [], ["clock", "cacheEntries", "maxPending", "helpers", "smtpCapacity"], code);
1372
+ const capacity = readCapacityOption(config);
1268
1373
  const clock = readClock(config.clock);
1269
- const maxPending = boundedOption(config.maxPending, TEMPLATE_MAX_PENDING);
1270
- const renderer = createLocalRenderer(boundedOption(config.cacheEntries, TEMPLATE_CACHE_ENTRIES), config.helpers);
1374
+ const maxPending = boundedOption(config.maxPending, capacity?.limits.registryPending ?? TEMPLATE_MAX_PENDING);
1375
+ const renderer = createLocalRenderer(
1376
+ boundedOption(config.cacheEntries, capacity?.limits.registryCache ?? TEMPLATE_CACHE_ENTRIES),
1377
+ config.helpers
1378
+ );
1271
1379
  const registered = /* @__PURE__ */ new Map();
1272
1380
  for (const key of plainKeys(definitions, Infinity, code)) {
1273
- registered.set(identifier(key, code), readDefinition(ownData(definitions, key, code)));
1381
+ const definition = readDefinition(ownData(definitions, key, code));
1382
+ if (capacity && definition.kind !== "handlebars") invalid(code);
1383
+ registered.set(identifier(key, code), definition);
1274
1384
  }
1275
1385
  let pending = 0;
1276
1386
  async function prepareParsed({ identity, command: safe }, budget) {
1277
1387
  budget.check();
1278
1388
  const { templateKey, provider, key, scheduleAt } = identity;
1389
+ assertCapacityProvider(provider, capacity, "provider_mismatch");
1279
1390
  const definition = registered.get(templateKey);
1280
1391
  if (!definition) invalid("template_not_found");
1281
1392
  if ((definition.kind === "handlebars" ? "smtp" : "sendgrid") !== provider.kind) invalid("provider_mismatch");
@@ -1299,7 +1410,7 @@ function createEmailTemplateRegistry(definitions, options = {}) {
1299
1410
  slot,
1300
1411
  "preparation_failed",
1301
1412
  () => prepare(input, context),
1302
- (raw) => captureFields(raw, definition, context, scheduleAt, budget, slot)
1413
+ (raw) => captureFields(raw, definition, context, scheduleAt, budget, slot, capacity)
1303
1414
  );
1304
1415
  budget.check();
1305
1416
  const base = {
@@ -1311,17 +1422,18 @@ function createEmailTemplateRegistry(definitions, options = {}) {
1311
1422
  let snapshot;
1312
1423
  if (provider.kind === "smtp" && definition.kind === "handlebars") {
1313
1424
  const content = await renderer.render(templateKey, definition, data, budget, slot);
1314
- snapshot = Object.freeze({ ...base, kind: provider.kind, provider, ...content });
1425
+ snapshot = Object.freeze({ ...base, kind: provider.kind, provider, ...capacityTag(capacity), ...content });
1315
1426
  } else if (provider.kind === "sendgrid" && definition.kind === "sendgrid") {
1316
1427
  snapshot = Object.freeze({ ...base, kind: provider.kind, provider, templateId: definition.templateId, data });
1317
1428
  } else {
1318
1429
  return invalid("provider_mismatch");
1319
1430
  }
1320
1431
  budget.check();
1321
- const snapshotHash = hashSnapshot(snapshot);
1432
+ const snapshotHash = hashSnapshot(snapshot, capacity);
1322
1433
  budget.check();
1323
1434
  return Object.freeze({
1324
1435
  version: EMAIL_FORMAT_VERSION,
1436
+ ...capacityTag(capacity),
1325
1437
  scope: identity.scope,
1326
1438
  key,
1327
1439
  scheduleAt,
@@ -1335,6 +1447,7 @@ function createEmailTemplateRegistry(definitions, options = {}) {
1335
1447
  }
1336
1448
  }
1337
1449
  const registry = Object.freeze({
1450
+ ...capacityTag(capacity),
1338
1451
  invalidate(key) {
1339
1452
  if (key !== void 0) identifier(key, code);
1340
1453
  renderer.invalidate(key);
@@ -1344,7 +1457,7 @@ function createEmailTemplateRegistry(definitions, options = {}) {
1344
1457
  const budget = createBudget(clock, call.timeoutMs, call.signal);
1345
1458
  try {
1346
1459
  budget.check();
1347
- return await prepareParsed(parseCommandIdentity(scope, command), budget);
1460
+ return await prepareParsed(parseCommandIdentity(scope, command, capacity), budget);
1348
1461
  } finally {
1349
1462
  budget.close();
1350
1463
  }
@@ -1412,9 +1525,19 @@ function attemptOutcome(reason) {
1412
1525
  function isSafeTransient(reason) {
1413
1526
  return evidence[reason][1] === "safe_transient";
1414
1527
  }
1528
+ var recipientGroups = ["to", "cc", "bcc"];
1415
1529
  function recipientCounts(envelope) {
1416
1530
  return Object.freeze({ to: envelope.to.length, cc: envelope.cc.length, bcc: envelope.bcc.length });
1417
1531
  }
1532
+ function readRecipientCounts(input, code, capacity) {
1533
+ const limit = recipientLimit(capacity);
1534
+ const counts = readRecord(input, recipientGroups, [], code);
1535
+ const to = integer(counts.to, 0, limit, code);
1536
+ const cc = integer(counts.cc, 0, limit - to, code);
1537
+ const bcc = integer(counts.bcc, 0, limit - to - cc, code);
1538
+ if (to + cc + bcc === 0) invalid(code);
1539
+ return Object.freeze({ to, cc, bcc });
1540
+ }
1418
1541
  function smtpMessageId(attemptId) {
1419
1542
  return `<${attemptId}@email.invalid>`;
1420
1543
  }
@@ -1431,7 +1554,7 @@ function readHint(input, reason, code) {
1431
1554
  ...hasFloor ? { notBefore: unixMs(raw.notBefore, code) } : {}
1432
1555
  });
1433
1556
  }
1434
- function readAttemptResult(input, code = "invalid_command", projected = false) {
1557
+ function readAttemptResult(input, code = "invalid_command", projected = false, capacity) {
1435
1558
  const raw = readRecord(
1436
1559
  input,
1437
1560
  ["outcome", "retry", "stage", "reason"],
@@ -1442,6 +1565,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
1442
1565
  const [outcome, retry, stages2, origin] = evidence[reason];
1443
1566
  const stage = stages2.find((value) => value === raw.stage);
1444
1567
  if (raw.outcome !== outcome || raw.retry !== retry || !stage) invalid(code);
1568
+ if (capacity && (origin === "sendgrid" || stage === "http")) invalid(code);
1445
1569
  const hasHint = Object.hasOwn(raw, "retryHint");
1446
1570
  if (projected && hasHint || !projected && reason === "rate_deferred" && !hasHint) invalid(code);
1447
1571
  const smtpSuccess = reason === "smtp_accepted" || reason === "smtp_partial";
@@ -1451,14 +1575,22 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
1451
1575
  if (hasRecipients) {
1452
1576
  if (origin !== "smtp" && origin !== "provider" || stage !== "envelope" && stage !== "data") invalid(code);
1453
1577
  const seen = /* @__PURE__ */ new Set();
1454
- recipients = readArray(raw.recipients, MESSAGE_LIMITS.recipients, code, (value) => {
1578
+ const limit = recipientLimit(capacity);
1579
+ let previous = -1;
1580
+ recipients = readArray(raw.recipients, limit, code, (value) => {
1455
1581
  const { group, index: rawIndex, status } = readRecord(value, ["group", "index", "status"], [], code);
1456
1582
  if (group !== "to" && group !== "cc" && group !== "bcc") invalid(code);
1457
1583
  if (status !== "rejected" && (status !== "accepted" || !smtpSuccess)) invalid(code);
1458
- const index = integer(rawIndex, 0, MESSAGE_LIMITS.recipients - 1, code);
1459
- const key = `${group}:${index}`;
1460
- if (seen.has(key)) invalid(code);
1461
- seen.add(key);
1584
+ const index = integer(rawIndex, 0, limit - 1, code);
1585
+ if (capacity) {
1586
+ const position = recipientGroups.indexOf(group) * limit + index;
1587
+ if (position <= previous) invalid(code);
1588
+ previous = position;
1589
+ } else {
1590
+ const key = `${group}:${index}`;
1591
+ if (seen.has(key)) invalid(code);
1592
+ seen.add(key);
1593
+ }
1462
1594
  return Object.freeze({ group, index, status });
1463
1595
  });
1464
1596
  const accepted = recipients.filter(({ status }) => status === "accepted").length;
@@ -1473,7 +1605,7 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
1473
1605
  if (hasProviderId && (reason !== "sendgrid_accepted" || typeof providerMessageId !== "string" || providerMessageId.length > 128 || !/^[A-Za-z0-9][A-Za-z0-9._=-]{0,127}$/.test(providerMessageId))) {
1474
1606
  invalid(code);
1475
1607
  }
1476
- return Object.freeze({
1608
+ const result = Object.freeze({
1477
1609
  outcome,
1478
1610
  retry,
1479
1611
  stage,
@@ -1483,6 +1615,8 @@ function readAttemptResult(input, code = "invalid_command", projected = false) {
1483
1615
  ...typeof messageId === "string" ? { messageId } : {},
1484
1616
  ...typeof providerMessageId === "string" ? { providerMessageId } : {}
1485
1617
  });
1618
+ if (capacity && !projected) encodeEvidence(result, code, capacity);
1619
+ return result;
1486
1620
  }
1487
1621
  function assertEvidencePhase(reason, phase, source, code) {
1488
1622
  const origin = evidence[reason][3];
@@ -1508,9 +1642,9 @@ function assertEvidenceContext(result, provider, attemptId, counts, code) {
1508
1642
  }
1509
1643
  }
1510
1644
  }
1511
- function readProviderResult(input, provider, attemptId, envelope) {
1645
+ function readProviderResult(input, provider, attemptId, envelope, capacity) {
1512
1646
  const code = "invalid_command";
1513
- const result = readAttemptResult(input, code);
1647
+ const result = readAttemptResult(input, code, false, capacity);
1514
1648
  const origin = evidence[result.reason][3];
1515
1649
  if (origin !== "smtp" && origin !== "sendgrid" && origin !== "provider") invalid(code);
1516
1650
  assertEvidenceContext(result, provider, attemptId, recipientCounts(envelope), code);
@@ -1541,10 +1675,7 @@ function attemptEffect(result, attemptId, ordinal, manual, policy, expiresAt, no
1541
1675
  var REQUEST = "invalid_command";
1542
1676
  var LEASE = WORKER_LIMIT_BOUNDS.leaseMs;
1543
1677
  function readStoreId(value, code = REQUEST) {
1544
- 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)) {
1545
- invalid(code);
1546
- }
1547
- return value;
1678
+ return uuidV4(value, code);
1548
1679
  }
1549
1680
  function readLeaseToken(value, code = REQUEST) {
1550
1681
  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)) {
@@ -1558,14 +1689,18 @@ function readLeaseMs(value) {
1558
1689
  function timeAfter(start, delayMs) {
1559
1690
  return delayMs <= MAX_UNIX_MS - start ? start + delayMs : void 0;
1560
1691
  }
1561
- function readStoreCall(input, worker = false) {
1692
+ function readStoreCall(input, worker = false, capacity) {
1562
1693
  const code = "invalid_config";
1563
- const raw = readRecord(input, ["signal", "timeoutMs"], [], code);
1694
+ const { smtpCapacity, ...raw } = readRecord(input, ["signal", "timeoutMs"], capacity ? ["smtpCapacity"] : [], code);
1695
+ if (capacity) assertCapacityTag({ smtpCapacity }, capacity, "store_incompatible");
1564
1696
  const max = worker ? WORKER_LIMIT_BOUNDS.storeTimeoutMs.max : CALL_BUDGETS.admissionOrAdmin.max;
1565
1697
  const timeoutMs = integer(raw.timeoutMs, 1, max, code);
1566
1698
  const call = readCallOptions(raw, { default: STORE_PRIMITIVE_TIMEOUT_MS, min: 1, max });
1567
1699
  if (!call.signal) invalid(code);
1568
- return { signal: call.signal, timeoutMs: worker ? timeoutMs : Math.min(timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS) };
1700
+ return {
1701
+ signal: call.signal,
1702
+ timeoutMs: worker && !capacity ? timeoutMs : Math.min(timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS)
1703
+ };
1569
1704
  }
1570
1705
  function readStoreNext(value, read) {
1571
1706
  const code = "store_incompatible";
@@ -1602,9 +1737,9 @@ function readRetentionPolicy(input, code = REQUEST) {
1602
1737
  idempotencyMs: integer(idempotencyMs, bounds.idempotencyMs.min, bounds.idempotencyMs.max, code)
1603
1738
  });
1604
1739
  }
1605
- function readStoreAdmission(scope, input) {
1740
+ function readStoreAdmission(scope, input, capacity) {
1606
1741
  const raw = readRecord(input, ["command", "jobId", "retry", "retention"], [], REQUEST);
1607
- const command = validatePreparedCommand(scope, raw.command);
1742
+ const command = validatePreparedCommand(scope, raw.command, capacity);
1608
1743
  return Object.freeze({
1609
1744
  command,
1610
1745
  admissionKey: encodeAdmissionKey(command.key),
@@ -1625,7 +1760,7 @@ function readClaim(input) {
1625
1760
  leaseMs: readLeaseMs(leaseMs)
1626
1761
  });
1627
1762
  }
1628
- function readFinish(input) {
1763
+ function readFinish(input, capacity) {
1629
1764
  const { fence, phase, operationId, result } = readRecord(
1630
1765
  input,
1631
1766
  ["fence", "phase", "operationId", "result"],
@@ -1633,7 +1768,7 @@ function readFinish(input) {
1633
1768
  REQUEST
1634
1769
  );
1635
1770
  if (phase !== "pre_handoff" && phase !== "handed_off") invalid(REQUEST);
1636
- const evidence2 = readAttemptResult(result);
1771
+ const evidence2 = readAttemptResult(result, REQUEST, false, capacity);
1637
1772
  assertEvidencePhase(evidence2.reason, phase, "owner", REQUEST);
1638
1773
  return Object.freeze({ fence: readFence(fence), phase, operationId: readStoreId(operationId), result: evidence2 });
1639
1774
  }
@@ -1650,7 +1785,6 @@ function readResolution(input) {
1650
1785
  }
1651
1786
 
1652
1787
  // src/internal/activity-codecs.ts
1653
- var ACTIVITY_BYTES = 8192;
1654
1788
  var dispositions = [
1655
1789
  "accepted",
1656
1790
  "partially_accepted",
@@ -1677,7 +1811,7 @@ function assertActivityDisposition(result, disposition, code) {
1677
1811
  invalid(code);
1678
1812
  }
1679
1813
  }
1680
- function readActivity(scope, input, code = "store_incompatible") {
1814
+ function captureActivity(scope, input, code, capacity) {
1681
1815
  const raw = readRecord(
1682
1816
  input,
1683
1817
  [
@@ -1694,26 +1828,32 @@ function readActivity(scope, input, code = "store_incompatible") {
1694
1828
  "result",
1695
1829
  "disposition"
1696
1830
  ],
1697
- ["handedOffAt"],
1831
+ ["handedOffAt", "smtpCapacity", "recipientCounts"],
1698
1832
  code
1699
1833
  );
1700
1834
  if (raw.version !== EMAIL_FORMAT_VERSION || scopeToken(raw.scope, code) !== scope) invalid(code);
1835
+ assertCapacityTag(raw, capacity, code);
1836
+ if (!capacity && Object.hasOwn(raw, "recipientCounts")) invalid(code);
1837
+ const counts = capacity ? readRecipientCounts(raw.recipientCounts, code, capacity) : void 0;
1701
1838
  const jobId = readStoreId(raw.jobId, code);
1702
1839
  const attemptId = readStoreId(raw.attemptId, code);
1703
1840
  const provider = validateProviderRef(raw.provider, code);
1841
+ assertCapacityProvider(provider, capacity, code);
1704
1842
  const startedAt = unixMs(raw.startedAt, code);
1705
1843
  const finishedAt = unixMs(raw.finishedAt, code);
1706
1844
  const handedOffAt = Object.hasOwn(raw, "handedOffAt") ? unixMs(raw.handedOffAt, code) : void 0;
1707
1845
  if (finishedAt < startedAt || handedOffAt !== void 0 && (handedOffAt < startedAt || handedOffAt > finishedAt)) {
1708
1846
  invalid(code);
1709
1847
  }
1710
- const result = readAttemptResult(raw.result, code, true);
1848
+ const result = readAttemptResult(raw.result, code, true, capacity);
1711
1849
  assertEvidencePhase(result.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", code);
1712
- assertEvidenceContext(result, provider, attemptId, void 0, code);
1850
+ assertEvidenceContext(result, provider, attemptId, counts, code);
1713
1851
  const disposition = readDisposition(raw.disposition, code);
1714
1852
  assertActivityDisposition(result, disposition, code);
1715
1853
  return Object.freeze({
1716
1854
  version: EMAIL_FORMAT_VERSION,
1855
+ ...capacityTag(capacity),
1856
+ ...counts ? { recipientCounts: counts } : {},
1717
1857
  scope,
1718
1858
  jobId,
1719
1859
  attemptId,
@@ -1728,50 +1868,62 @@ function readActivity(scope, input, code = "store_incompatible") {
1728
1868
  disposition
1729
1869
  });
1730
1870
  }
1731
- function activityFor(job, commit) {
1871
+ function readActivity(scope, input, code = "store_incompatible", capacity) {
1872
+ const activity = captureActivity(scope, input, code, capacity);
1873
+ if (capacity) encodeEvidence(activity, code, capacity);
1874
+ return activity;
1875
+ }
1876
+ function activityFor(job, commit, capacity) {
1732
1877
  const { outcome, retry, stage, reason, recipients, messageId, providerMessageId } = commit.result;
1733
- return readActivity(job.scope, {
1734
- version: EMAIL_FORMAT_VERSION,
1735
- scope: job.scope,
1736
- jobId: job.jobId,
1737
- attemptId: commit.attemptId,
1738
- ordinal: commit.ordinal,
1739
- provider: job.provider,
1740
- template: job.template,
1741
- correlation: job.correlation,
1742
- startedAt: commit.startedAt,
1743
- ...commit.handedOffAt === void 0 ? {} : { handedOffAt: commit.handedOffAt },
1744
- finishedAt: commit.finishedAt,
1745
- disposition: commit.disposition,
1746
- result: {
1747
- outcome,
1748
- retry,
1749
- stage,
1750
- reason,
1751
- ...recipients === void 0 ? {} : { recipients },
1752
- ...messageId === void 0 ? {} : { messageId },
1753
- ...providerMessageId === void 0 ? {} : { providerMessageId }
1754
- }
1755
- });
1878
+ return captureActivity(
1879
+ job.scope,
1880
+ {
1881
+ version: EMAIL_FORMAT_VERSION,
1882
+ ...capacityTag(capacity),
1883
+ ...capacity ? { recipientCounts: job.recipientCounts } : {},
1884
+ scope: job.scope,
1885
+ jobId: job.jobId,
1886
+ attemptId: commit.attemptId,
1887
+ ordinal: commit.ordinal,
1888
+ provider: job.provider,
1889
+ template: job.template,
1890
+ correlation: job.correlation,
1891
+ startedAt: commit.startedAt,
1892
+ ...commit.handedOffAt === void 0 ? {} : { handedOffAt: commit.handedOffAt },
1893
+ finishedAt: commit.finishedAt,
1894
+ disposition: commit.disposition,
1895
+ result: {
1896
+ outcome,
1897
+ retry,
1898
+ stage,
1899
+ reason,
1900
+ ...recipients === void 0 ? {} : { recipients },
1901
+ ...messageId === void 0 ? {} : { messageId },
1902
+ ...providerMessageId === void 0 ? {} : { providerMessageId }
1903
+ }
1904
+ },
1905
+ "store_incompatible",
1906
+ capacity
1907
+ );
1756
1908
  }
1757
- function activityDigest(activity) {
1758
- return hashJson(activity, ACTIVITY_BYTES, "store_incompatible");
1909
+ function activityDigest(activity, capacity) {
1910
+ return sha256(encodeEvidence(activity, "store_incompatible", capacity));
1759
1911
  }
1760
- function readStoredActivity(scope, input, code = "store_incompatible") {
1912
+ function readStoredActivity(scope, input, code = "store_incompatible", capacity) {
1761
1913
  const raw = readRecord(input, ["activity", "digest"], [], code);
1762
- const activity = readActivity(scope, raw.activity, code);
1914
+ const activity = captureActivity(scope, raw.activity, code, capacity);
1763
1915
  const digest = hashToken(raw.digest, code);
1764
- if (activityDigest(activity) !== digest) invalid(code);
1916
+ if (activityDigest(activity, capacity) !== digest) invalid(code);
1765
1917
  return Object.freeze({ activity, digest });
1766
1918
  }
1767
- function readProjectionPermit(scope, input) {
1919
+ function readProjectionPermit(scope, input, capacity) {
1768
1920
  const code = "invalid_command";
1769
1921
  const {
1770
1922
  activity,
1771
1923
  digest,
1772
1924
  permitUntil: rawUntil
1773
1925
  } = readRecord(input, ["activity", "digest", "permitUntil"], [], code);
1774
- const stored = readStoredActivity(scope, { activity, digest }, code);
1926
+ const stored = readStoredActivity(scope, { activity, digest }, code, capacity);
1775
1927
  const permitUntil = unixMs(rawUntil, code);
1776
1928
  if (permitUntil - stored.activity.finishedAt < PROJECTION_PERMIT_MS) invalid(code);
1777
1929
  return Object.freeze({ ...stored, permitUntil });
@@ -1783,13 +1935,15 @@ function compareActivity(a, b) {
1783
1935
  return b.finishedAt - a.finishedAt || compareAscii(a.jobId, b.jobId) || compareAscii(a.attemptId, b.attemptId);
1784
1936
  }
1785
1937
  function cursorPayload(criteria, position) {
1938
+ const binding = criteria.capacity?.binding;
1786
1939
  return {
1787
1940
  v: EMAIL_FORMAT_VERSION,
1788
1941
  s: criteria.scope,
1789
1942
  j: criteria.jobId,
1790
1943
  f: criteria.from,
1791
1944
  b: criteria.before,
1792
- p: [position.finishedAt, position.jobId, position.attemptId]
1945
+ p: [position.finishedAt, position.jobId, position.attemptId],
1946
+ ...binding ? { c: [binding.format, binding.namespace, binding.maxRecipients] } : {}
1793
1947
  };
1794
1948
  }
1795
1949
  function encodeCursor(criteria, position) {
@@ -1810,7 +1964,7 @@ function decodeCursor(criteria, cursor) {
1810
1964
  } catch {
1811
1965
  invalid(code);
1812
1966
  }
1813
- const { p } = readRecord(input, ["v", "s", "j", "f", "b", "p"], [], code);
1967
+ const { p } = readRecord(input, ["v", "s", "j", "f", "b", "p"], criteria.capacity ? ["c"] : [], code);
1814
1968
  const tuple = readArray(p, 3, code, (entry) => entry);
1815
1969
  const position = Object.freeze({
1816
1970
  finishedAt: unixMs(tuple[0], code),
@@ -1822,15 +1976,16 @@ function decodeCursor(criteria, cursor) {
1822
1976
  }
1823
1977
  return position;
1824
1978
  }
1825
- function readActivityCriteria(scope, input) {
1979
+ function readActivityCriteria(scope, input, capacity) {
1826
1980
  const code = "invalid_command";
1827
1981
  const raw = readRecord(input, [], ["jobId", "from", "before", "limit", "cursor"], code);
1828
1982
  const jobId = Object.hasOwn(raw, "jobId") ? readStoreId(raw.jobId, code) : null;
1829
1983
  const from = Object.hasOwn(raw, "from") ? unixMs(raw.from, code) : null;
1830
1984
  const before = Object.hasOwn(raw, "before") ? unixMs(raw.before, code) : null;
1831
1985
  if (from !== null && before !== null && from > before) invalid(code);
1832
- const limit = Object.hasOwn(raw, "limit") ? integer(raw.limit, ACTIVITY_PAGE_LIMIT.min, ACTIVITY_PAGE_LIMIT.max, code) : ACTIVITY_PAGE_LIMIT.default;
1833
- const criteria = { scope, jobId, from, before, limit };
1986
+ const page = capacity?.limits.page ?? ACTIVITY_PAGE_LIMIT;
1987
+ const limit = Object.hasOwn(raw, "limit") ? integer(raw.limit, page.min, page.max, code) : page.default;
1988
+ const criteria = { scope, jobId, from, before, limit, ...capacity ? { capacity } : {} };
1834
1989
  return Object.freeze({
1835
1990
  ...criteria,
1836
1991
  ...Object.hasOwn(raw, "cursor") ? { after: decodeCursor(criteria, raw.cursor) } : {}
@@ -1850,7 +2005,7 @@ function readOrderedActivities(criteria, input, maxRows) {
1850
2005
  const code = "store_incompatible";
1851
2006
  let previous = criteria.after;
1852
2007
  return readArray(input, maxRows, code, (row) => {
1853
- const activity = readActivity(criteria.scope, row);
2008
+ const activity = readActivity(criteria.scope, row, code, criteria.capacity);
1854
2009
  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) {
1855
2010
  invalid(code);
1856
2011
  }
@@ -1900,14 +2055,18 @@ function readUnknownResolution(input) {
1900
2055
  if (action !== "dismiss" && action !== "redrive") invalid(STORED);
1901
2056
  return Object.freeze({ attemptId: readStoreId(attemptId, STORED), at: unixMs(at, STORED), action });
1902
2057
  }
1903
- function readJobSummary(scope, input) {
2058
+ function readJobSummary(scope, input, capacity) {
1904
2059
  const raw = readRecord(
1905
2060
  input,
1906
2061
  COMMON,
1907
- ["latestAttempt", "nextAt", "phase", "disposition", "terminalReason", "terminalAt"],
2062
+ ["latestAttempt", "nextAt", "phase", "disposition", "terminalReason", "terminalAt", "smtpCapacity"],
1908
2063
  STORED
1909
2064
  );
1910
2065
  if (raw.version !== EMAIL_FORMAT_VERSION || scopeToken(raw.scope, STORED) !== scope) invalid(STORED);
2066
+ assertCapacityTag(raw, capacity, STORED);
2067
+ const optional = capacity ? ["latestAttempt", "smtpCapacity"] : ["latestAttempt"];
2068
+ const provider = validateProviderRef(raw.provider, STORED);
2069
+ assertCapacityProvider(provider, capacity, STORED);
1911
2070
  const createdAt = unixMs(raw.createdAt, STORED);
1912
2071
  const updatedAt = unixMs(raw.updatedAt, STORED);
1913
2072
  const expiresAt = unixMs(raw.expiresAt, STORED);
@@ -1916,16 +2075,16 @@ function readJobSummary(scope, input) {
1916
2075
  if (updatedAt < createdAt || firstDue >= expiresAt) invalid(STORED);
1917
2076
  let state;
1918
2077
  if (raw.state === "queued") {
1919
- readRecord(raw, [...COMMON, "nextAt"], ["latestAttempt"], STORED);
2078
+ readRecord(raw, [...COMMON, "nextAt"], optional, STORED);
1920
2079
  const nextAt = unixMs(raw.nextAt, STORED);
1921
2080
  if (nextAt < firstDue || nextAt >= expiresAt) invalid(STORED);
1922
2081
  state = { state: raw.state, nextAt };
1923
2082
  } else if (raw.state === "leased") {
1924
- readRecord(raw, [...COMMON, "phase"], ["latestAttempt"], STORED);
2083
+ readRecord(raw, [...COMMON, "phase"], optional, STORED);
1925
2084
  if (raw.phase !== "pre_handoff" && raw.phase !== "handed_off") invalid(STORED);
1926
2085
  state = { state: raw.state, phase: raw.phase };
1927
2086
  } else if (raw.state === "terminal") {
1928
- readRecord(raw, [...COMMON, "disposition", "terminalAt", "terminalReason"], ["latestAttempt"], STORED);
2087
+ readRecord(raw, [...COMMON, "disposition", "terminalAt", "terminalReason"], optional, STORED);
1929
2088
  const terminalAt = unixMs(raw.terminalAt, STORED);
1930
2089
  const disposition = readDisposition(raw.disposition, STORED);
1931
2090
  if (terminalAt < createdAt || terminalAt > updatedAt || disposition === "retry_scheduled") invalid(STORED);
@@ -1950,10 +2109,11 @@ function readJobSummary(scope, input) {
1950
2109
  const resolutions = readArray(raw.resolutions, Math.min(2, attemptCount - active), STORED, readUnknownResolution);
1951
2110
  return Object.freeze({
1952
2111
  version: EMAIL_FORMAT_VERSION,
2112
+ ...capacityTag(capacity),
1953
2113
  scope,
1954
2114
  jobId: readStoreId(raw.jobId, STORED),
1955
2115
  key: validateAdmissionKey(raw.key, STORED),
1956
- provider: validateProviderRef(raw.provider, STORED),
2116
+ provider,
1957
2117
  template: validateTemplateIdentity(raw.template, STORED),
1958
2118
  correlation: validateCorrelation(raw.correlation, STORED),
1959
2119
  scheduleAt,
@@ -2005,7 +2165,7 @@ async function runStoreCall(clock, parent, options) {
2005
2165
  budget.check();
2006
2166
  invalid("deadline");
2007
2167
  }
2008
- const call = Object.freeze({ timeoutMs, signal: budget.signal });
2168
+ const call = Object.freeze({ timeoutMs, signal: budget.signal, ...capacityTag(options.capacity) });
2009
2169
  let raw;
2010
2170
  try {
2011
2171
  const pending = options.invoke(call, dispatchedAt);
@@ -2071,7 +2231,10 @@ function createEmailService(options) {
2071
2231
  return createEmailServiceWithClock(options, systemEmailClock);
2072
2232
  }
2073
2233
  function createEmailServiceWithClock(options, clock) {
2074
- const raw = readRecord(options, ["scope", "store", "registry"], ["retry", "retention"], CONFIG);
2234
+ const raw = readRecord(options, ["scope", "store", "registry"], ["retry", "retention", "smtpCapacity"], CONFIG);
2235
+ const capacity = readCapacityOption(raw);
2236
+ assertPortCapacity(raw.store, capacity);
2237
+ assertPortCapacity(raw.registry, capacity);
2075
2238
  const scope = scopeToken(raw.scope, CONFIG);
2076
2239
  const retry = readRetryPolicy(readPolicy(raw.retry, DEFAULT_RETRY_POLICY), CONFIG);
2077
2240
  const retention = readRetentionPolicy(readPolicy(raw.retention, DEFAULT_RETENTION_POLICY), CONFIG);
@@ -2081,10 +2244,11 @@ function createEmailServiceWithClock(options, clock) {
2081
2244
  const registry = raw.registry;
2082
2245
  const prepare = bindMethod(registry, "prepare");
2083
2246
  const internalPrepare = findRegistryPreparation(registry);
2247
+ let admissions = 0;
2084
2248
  async function prepareMiss(parsed, parent) {
2085
2249
  const { identity, command } = parsed;
2086
2250
  const accept = (value) => {
2087
- const staged = validatePreparedCommand(scope, value);
2251
+ const staged = validatePreparedCommand(scope, value, capacity);
2088
2252
  if (!sameCommandMetadata(
2089
2253
  staged.key,
2090
2254
  staged.snapshot.template.key,
@@ -2113,7 +2277,7 @@ function createEmailServiceWithClock(options, clock) {
2113
2277
  slots = { pending: 0 };
2114
2278
  injectedRegistrySlots.set(registry, slots);
2115
2279
  }
2116
- if (slots.pending >= TEMPLATE_MAX_PENDING.default) invalid("busy");
2280
+ if (slots.pending >= (capacity?.limits.registryPending.default ?? TEMPLATE_MAX_PENDING.default)) invalid("busy");
2117
2281
  const budget = createChildBudget(clock, parent, CALL_BUDGETS.prepare.default);
2118
2282
  const occupied = slots;
2119
2283
  slots.pending++;
@@ -2143,12 +2307,13 @@ function createEmailServiceWithClock(options, clock) {
2143
2307
  function findWinner(key, budget) {
2144
2308
  return runStoreCall(clock, budget, {
2145
2309
  maxMs: STORE_PRIMITIVE_TIMEOUT_MS,
2310
+ capacity,
2146
2311
  effect: "read",
2147
2312
  invoke: (call) => find(scope, key, call),
2148
2313
  accept(value) {
2149
2314
  if (value === null) return null;
2150
2315
  const raw2 = readRecord(value, ["job", "fingerprint"], [], STORED2);
2151
- const job = readJobSummary(scope, raw2.job);
2316
+ const job = readJobSummary(scope, raw2.job, capacity);
2152
2317
  if (encodeAdmissionKey(job.key) !== encodeAdmissionKey(key)) invalid(STORED2);
2153
2318
  return { job, fingerprint: hashToken(raw2.fingerprint, STORED2) };
2154
2319
  }
@@ -2166,6 +2331,7 @@ function createEmailServiceWithClock(options, clock) {
2166
2331
  try {
2167
2332
  const job = await runStoreCall(clock, budget, {
2168
2333
  maxMs: STORE_PRIMITIVE_TIMEOUT_MS,
2334
+ capacity,
2169
2335
  effect: "mutation",
2170
2336
  definite: INSERT_REJECTIONS,
2171
2337
  invoke: (call) => insert(scope, admission, call),
@@ -2173,7 +2339,7 @@ function createEmailServiceWithClock(options, clock) {
2173
2339
  const raw2 = readRecord(value, ["status"], ["job"], STORED2);
2174
2340
  if (raw2.status === "duplicate" && !Object.hasOwn(raw2, "job")) return null;
2175
2341
  if (raw2.status !== "inserted") invalid(STORED2);
2176
- const job2 = readJobSummary(scope, raw2.job);
2342
+ const job2 = readJobSummary(scope, raw2.job, capacity);
2177
2343
  const { snapshot } = command;
2178
2344
  if (job2.jobId !== admission.jobId || !matchesAdmissionJob(job2, identity, "enqueued") || job2.template.revision !== snapshot.template.revision || snapshot.preparedAt - job2.createdAt > MAX_PREPARED_AT_SKEW_MS || job2.expiresAt !== snapshot.expiresAt || job2.priority !== snapshot.priority || !sameCorrelation(job2.correlation, snapshot.correlation)) {
2179
2345
  invalid(STORED2);
@@ -2199,24 +2365,37 @@ function createEmailServiceWithClock(options, clock) {
2199
2365
  if (winner) return replay(winner, parsed.identity);
2200
2366
  return insertOrConfirm(await prepareMiss(parsed, budget), parsed.identity, budget);
2201
2367
  }
2202
- async function inOperation(call, run) {
2203
- const { timeoutMs, signal } = readCallOptions(call, CALL_BUDGETS.admissionOrAdmin);
2204
- const budget = createBudget(clock, timeoutMs, signal);
2368
+ async function withAdmission(run) {
2369
+ if (!capacity) return run();
2370
+ if (admissions >= capacity.limits.servicePending) invalid("busy");
2371
+ admissions++;
2205
2372
  try {
2206
- budget.check();
2207
- return await run(budget);
2373
+ return await run();
2208
2374
  } finally {
2209
- budget.close();
2375
+ admissions--;
2210
2376
  }
2211
2377
  }
2378
+ function inOperation(call, run) {
2379
+ return withAdmission(async () => {
2380
+ const { timeoutMs, signal } = readCallOptions(call, CALL_BUDGETS.admissionOrAdmin);
2381
+ const budget = createBudget(clock, timeoutMs, signal);
2382
+ try {
2383
+ budget.check();
2384
+ return await run(budget);
2385
+ } finally {
2386
+ budget.close();
2387
+ }
2388
+ });
2389
+ }
2212
2390
  const service = Object.freeze({
2213
2391
  scope,
2392
+ ...capacityTag(capacity),
2214
2393
  enqueue(command, call = {}) {
2215
- return inOperation(call, (budget) => enqueueParsed(parseCommandIdentity(scope, command), budget));
2394
+ return inOperation(call, (budget) => enqueueParsed(parseCommandIdentity(scope, command, capacity), budget));
2216
2395
  },
2217
2396
  enqueuePrepared(input, call = {}) {
2218
2397
  return inOperation(call, async (budget) => {
2219
- const command = validatePreparedCommand(scope, input);
2398
+ const command = validatePreparedCommand(scope, input, capacity);
2220
2399
  const identity = {
2221
2400
  scope,
2222
2401
  key: command.key,
@@ -2231,7 +2410,7 @@ function createEmailServiceWithClock(options, clock) {
2231
2410
  });
2232
2411
  }
2233
2412
  });
2234
- serviceAdmissions.set(service, enqueueParsed);
2413
+ serviceAdmissions.set(service, (parsed, budget) => withAdmission(() => enqueueParsed(parsed, budget)));
2235
2414
  return service;
2236
2415
  }
2237
2416
  function readPolicy(input, defaults) {
@@ -2256,30 +2435,36 @@ var import_node_util8 = require("util");
2256
2435
 
2257
2436
  // src/internal/worker-config.ts
2258
2437
  var CONFIG2 = "invalid_config";
2259
- function readLimits(input) {
2438
+ function readLimits(input, capacity) {
2260
2439
  const keys = Object.keys(WORKER_LIMIT_BOUNDS);
2261
2440
  const raw = readRecord(input === void 0 ? {} : input, [], keys, CONFIG2);
2262
- const limits = {};
2263
- for (const key of keys) limits[key] = boundedOption(raw[key], WORKER_LIMIT_BOUNDS[key]);
2264
- const { leaseMs, storeTimeoutMs, providerTimeoutMs, finalizeGraceMs } = limits;
2441
+ const limits2 = {};
2442
+ for (const key of keys) {
2443
+ const bounds = key === "maxConcurrency" ? capacity?.limits.workerConcurrency : void 0;
2444
+ limits2[key] = boundedOption(raw[key], bounds ?? WORKER_LIMIT_BOUNDS[key]);
2445
+ }
2446
+ const { leaseMs, storeTimeoutMs, providerTimeoutMs, finalizeGraceMs } = limits2;
2265
2447
  if (leaseMs < Math.max(
2266
2448
  3 * storeTimeoutMs + CLOCK_MARGIN_MS,
2267
2449
  storeTimeoutMs + providerTimeoutMs + finalizeGraceMs + CLOCK_MARGIN_MS
2268
2450
  )) {
2269
2451
  invalid(CONFIG2);
2270
2452
  }
2271
- return Object.freeze(limits);
2453
+ return Object.freeze(limits2);
2272
2454
  }
2273
2455
  function sameProvider(a, b) {
2274
2456
  return a.kind === b.kind && a.key === b.key && a.mode === b.mode;
2275
2457
  }
2276
- function readProfiles(input) {
2458
+ function readProfiles(input, capacity) {
2277
2459
  const profiles = /* @__PURE__ */ new Map();
2278
- readArray(input, Number.MAX_SAFE_INTEGER, CONFIG2, (provider) => {
2460
+ readArray(input, capacity?.limits.workerProfiles ?? Number.MAX_SAFE_INTEGER, CONFIG2, (provider) => {
2279
2461
  const ref = validateProviderRef(readPortMember(provider, "ref"), CONFIG2);
2462
+ assertPortCapacity(provider, capacity);
2463
+ assertCapacityProvider(ref, capacity, CONFIG2);
2280
2464
  if (profiles.has(ref.key)) invalid(CONFIG2);
2281
2465
  profiles.set(ref.key, Object.freeze({ ref, prepare: bindMethod(provider, "prepare") }));
2282
2466
  });
2467
+ if (capacity && profiles.size === 0) invalid(CONFIG2);
2283
2468
  return profiles;
2284
2469
  }
2285
2470
  function readResolvers(input) {
@@ -2317,15 +2502,18 @@ function readWorkerConfig(input) {
2317
2502
  const raw = readRecord(
2318
2503
  input,
2319
2504
  ["scope", "store", "providers"],
2320
- ["attachmentResolvers", "rateLimiter", "clock", "limits"],
2505
+ ["attachmentResolvers", "rateLimiter", "clock", "limits", "smtpCapacity"],
2321
2506
  CONFIG2
2322
2507
  );
2323
2508
  const { store } = raw;
2509
+ const capacity = readCapacityOption(raw);
2510
+ assertPortCapacity(store, capacity);
2324
2511
  return Object.freeze({
2512
+ capacity,
2325
2513
  scope: scopeToken(raw.scope, CONFIG2),
2326
- limits: readLimits(raw.limits),
2514
+ limits: readLimits(raw.limits, capacity),
2327
2515
  clock: readWorkerClock(raw.clock),
2328
- profiles: readProfiles(raw.providers),
2516
+ profiles: readProfiles(raw.providers, capacity),
2329
2517
  resolvers: readResolvers(raw.attachmentResolvers),
2330
2518
  limiter: readLimiter(raw.rateLimiter),
2331
2519
  store: Object.freeze({
@@ -2339,7 +2527,7 @@ function readWorkerConfig(input) {
2339
2527
  })
2340
2528
  });
2341
2529
  }
2342
- function readRunOptions(input, limits) {
2530
+ function readRunOptions(input, limits2, capacity) {
2343
2531
  const { limit, concurrency, maintenanceLimit, ...call } = readRecord(
2344
2532
  input,
2345
2533
  [],
@@ -2348,9 +2536,9 @@ function readRunOptions(input, limits) {
2348
2536
  );
2349
2537
  return Object.freeze({
2350
2538
  ...readCallOptions(call, CALL_BUDGETS.batchOrRun),
2351
- limit: boundedOption(limit, RUN_CLAIM_LIMIT),
2352
- concurrency: boundedOption(concurrency, { min: 1, max: limits.maxConcurrency, default: limits.maxConcurrency }),
2353
- maintenanceLimit: boundedOption(maintenanceLimit, RUN_MAINTENANCE_LIMIT)
2539
+ limit: boundedOption(limit, capacity?.limits.runClaims ?? RUN_CLAIM_LIMIT),
2540
+ concurrency: boundedOption(concurrency, { min: 1, max: limits2.maxConcurrency, default: limits2.maxConcurrency }),
2541
+ maintenanceLimit: boundedOption(maintenanceLimit, capacity?.limits.runMaintenance ?? RUN_MAINTENANCE_LIMIT)
2354
2542
  });
2355
2543
  }
2356
2544
  function readShutdownOptions(input) {
@@ -2366,10 +2554,10 @@ function readGrant(times, leaseMs) {
2366
2554
  if (leaseEndsAt - grantedAt !== leaseMs) invalid(STORED3);
2367
2555
  return Object.freeze({ grantedAt, leaseEndsAt });
2368
2556
  }
2369
- function readClaimed(value, scope, expected) {
2557
+ function readClaimed(value, scope, expected, capacity) {
2370
2558
  const raw = readRecord(value, ["job", "snapshot", "fence", "lease", "ordinal", "manual"], [], STORED3);
2371
- const job = readJobSummary(scope, raw.job);
2372
- const { snapshot } = validateSnapshot(raw.snapshot);
2559
+ const job = readJobSummary(scope, raw.job, capacity);
2560
+ const { snapshot } = validateSnapshot(raw.snapshot, capacity);
2373
2561
  const fence = readFence(raw.fence);
2374
2562
  const lease = readGrant(readRecord(raw.lease, ["grantedAt", "leaseEndsAt"], [], STORED3), expected.leaseMs);
2375
2563
  const ordinal = integer(raw.ordinal, 1, MAX_ATTEMPT_LEDGER, STORED3);
@@ -2404,7 +2592,7 @@ function readHandoff(value, last, claim, leaseMs, times) {
2404
2592
  assertLaterGrant(grant, last, claim.job.expiresAt, times);
2405
2593
  return Object.freeze({ ...grant, handoffAt });
2406
2594
  }
2407
- function readCommit(value) {
2595
+ function readCommit(value, capacity) {
2408
2596
  const raw = readRecord(
2409
2597
  value,
2410
2598
  ["jobId", "attemptId", "ordinal", "operationId", "startedAt", "finishedAt", "result", "disposition", "reason"],
@@ -2415,7 +2603,7 @@ function readCommit(value) {
2415
2603
  const finishedAt = unixMs(raw.finishedAt, STORED3);
2416
2604
  const handedOffAt = Object.hasOwn(raw, "handedOffAt") ? unixMs(raw.handedOffAt, STORED3) : void 0;
2417
2605
  const retryAt = Object.hasOwn(raw, "retryAt") ? unixMs(raw.retryAt, STORED3) : void 0;
2418
- const result = readAttemptResult(raw.result, STORED3);
2606
+ const result = readAttemptResult(raw.result, STORED3, false, capacity);
2419
2607
  const disposition = readDisposition(raw.disposition, STORED3);
2420
2608
  const reason = raw.reason === "attempts_exhausted" ? raw.reason : readAttemptReason(raw.reason, STORED3);
2421
2609
  assertEvidencePhase(result.reason, handedOffAt === void 0 ? "pre_handoff" : "handed_off", "ledger", STORED3);
@@ -2438,23 +2626,23 @@ function readCommit(value) {
2438
2626
  ...retryAt === void 0 ? {} : { retryAt }
2439
2627
  });
2440
2628
  }
2441
- function readRecovery(value) {
2442
- const commit = readCommit(value);
2629
+ function readRecovery(value, capacity) {
2630
+ const commit = readCommit(value, capacity);
2443
2631
  const { result, startedAt, handedOffAt, finishedAt } = commit;
2444
2632
  if (result.reason !== "pre_handoff_lease_expired" && result.reason !== "post_handoff_lease_expired" || finishedAt - (handedOffAt ?? startedAt) < WORKER_LIMIT_BOUNDS.leaseMs.min) {
2445
2633
  invalid(STORED3);
2446
2634
  }
2447
2635
  return commit;
2448
2636
  }
2449
- function readQueuedExpiry(value, scope) {
2450
- const job = readJobSummary(scope, value);
2637
+ function readQueuedExpiry(value, scope, capacity) {
2638
+ const job = readJobSummary(scope, value, capacity);
2451
2639
  if (job.state !== "terminal" || job.disposition !== "expired" || job.terminalReason !== "expired" || job.terminalAt < job.expiresAt || job.updatedAt !== job.terminalAt) {
2452
2640
  invalid(STORED3);
2453
2641
  }
2454
2642
  return job;
2455
2643
  }
2456
- function readOwnedCommit(value, { claim, lease, handoff }, request, providerInvoked, direct) {
2457
- const commit = readCommit(value);
2644
+ function readOwnedCommit(value, { claim, lease, handoff }, request, providerInvoked, direct, capacity) {
2645
+ const commit = readCommit(value, capacity);
2458
2646
  const { attemptId, startedAt, handedOffAt, finishedAt, result, disposition, retryAt } = commit;
2459
2647
  const { job, snapshot, fence, ordinal, manual } = claim;
2460
2648
  const { expiresAt } = job;
@@ -2467,7 +2655,7 @@ function readOwnedCommit(value, { claim, lease, handoff }, request, providerInvo
2467
2655
  assertEvidenceContext(result, snapshot.provider, attemptId, recipientCounts(snapshot.envelope), STORED3);
2468
2656
  if (request && commit.operationId === request.operationId) {
2469
2657
  const phase = handedOffAt === void 0 ? "pre_handoff" : "handed_off";
2470
- if (phase !== request.phase || finishedAt >= last.leaseEndsAt || canonicalJson(result, 8192, STORED3).encoded !== canonicalJson(request.result, 8192, STORED3).encoded) {
2658
+ if (phase !== request.phase || finishedAt >= last.leaseEndsAt || encodeEvidence(result, STORED3, capacity) !== encodeEvidence(request.result, STORED3, capacity)) {
2471
2659
  invalid(STORED3);
2472
2660
  }
2473
2661
  } else if (direct) {
@@ -2479,7 +2667,7 @@ function readOwnedCommit(value, { claim, lease, handoff }, request, providerInvo
2479
2667
  // src/internal/worker-finish.ts
2480
2668
  var import_node_crypto3 = require("crypto");
2481
2669
  async function finishAttempt(run, evidence2, providerInvoked, result) {
2482
- const { clock, store, scope, limits } = run.config;
2670
+ const { clock, store, scope, limits: limits2, capacity } = run.config;
2483
2671
  const {
2484
2672
  claim: { fence },
2485
2673
  handoff,
@@ -2488,13 +2676,13 @@ async function finishAttempt(run, evidence2, providerInvoked, result) {
2488
2676
  const now = monotonicNow(clock);
2489
2677
  const request = result && handoff !== "unconfirmed" ? Object.freeze({ fence, phase: handoff ? "handed_off" : "pre_handoff", operationId: (0, import_node_crypto3.randomUUID)(), result }) : void 0;
2490
2678
  const leaseEnd = safeLeaseEnd(handoff && handoff !== "unconfirmed" ? handoff : lease);
2491
- const grace = createBudgetUntil(clock, Math.min(now, run.budget.deadline) + limits.finalizeGraceMs);
2679
+ const grace = createBudgetUntil(clock, Math.min(now, run.budget.deadline) + limits2.finalizeGraceMs);
2492
2680
  async function confirm() {
2493
2681
  try {
2494
2682
  return await run.callStore(grace, {
2495
2683
  effect: "read",
2496
2684
  invoke: (call) => store.findAttempt(scope, fence.jobId, fence.attemptId, call),
2497
- accept: (value) => value === null ? null : readOwnedCommit(value, evidence2, request, providerInvoked, false)
2685
+ accept: (value) => value === null ? null : readOwnedCommit(value, evidence2, request, providerInvoked, false, capacity)
2498
2686
  });
2499
2687
  } catch {
2500
2688
  return null;
@@ -2505,7 +2693,7 @@ async function finishAttempt(run, evidence2, providerInvoked, result) {
2505
2693
  effect: "mutation",
2506
2694
  deadline: leaseEnd,
2507
2695
  invoke: (call) => store.finish(scope, exact, call),
2508
- accept: (value) => value === null ? null : readOwnedCommit(value, evidence2, exact, providerInvoked, true)
2696
+ accept: (value) => value === null ? null : readOwnedCommit(value, evidence2, exact, providerInvoked, true, capacity)
2509
2697
  });
2510
2698
  }
2511
2699
  try {
@@ -2682,8 +2870,8 @@ var AttemptOwner = class {
2682
2870
  }
2683
2871
  }
2684
2872
  async renewWhile(budget, stopped) {
2685
- const { clock, limits } = this.run.config;
2686
- const cadence = Math.floor(limits.leaseMs / 3);
2873
+ const { clock, limits: limits2 } = this.run.config;
2874
+ const cadence = Math.floor(limits2.leaseMs / 3);
2687
2875
  const waitSignal = AbortSignal.any([stopped, this.run.noLaunch]);
2688
2876
  while (!waitSignal.aborted) {
2689
2877
  try {
@@ -2753,7 +2941,7 @@ var AttemptOwner = class {
2753
2941
  }
2754
2942
  };
2755
2943
  async function launch(run, owner, mark, submit, preflight) {
2756
- const { clock, limits } = run.config;
2944
+ const { clock, limits: limits2, capacity } = run.config;
2757
2945
  const { provider, envelope, expiresAt } = owner.claim.snapshot;
2758
2946
  const { attemptId } = owner.claim.fence;
2759
2947
  const launchEnd = Math.min(
@@ -2771,7 +2959,7 @@ async function launch(run, owner, mark, submit, preflight) {
2771
2959
  io = createChildBudgetUntil(
2772
2960
  clock,
2773
2961
  run.budget,
2774
- Math.min(now + limits.providerTimeoutMs, safeLeaseEnd(mark) - limits.finalizeGraceMs)
2962
+ Math.min(now + limits2.providerTimeoutMs, safeLeaseEnd(mark) - limits2.finalizeGraceMs)
2775
2963
  );
2776
2964
  run.checkLaunch();
2777
2965
  io.check();
@@ -2787,7 +2975,7 @@ async function launch(run, owner, mark, submit, preflight) {
2787
2975
  if (!import_node_util8.types.isPromise(returned)) return unknown("transport_uncertain");
2788
2976
  let result;
2789
2977
  try {
2790
- result = readProviderResult(raw, provider, attemptId, envelope);
2978
+ result = readProviderResult(raw, provider, attemptId, envelope, capacity);
2791
2979
  } catch {
2792
2980
  return unknown("transport_uncertain");
2793
2981
  }
@@ -2811,8 +2999,8 @@ async function launch(run, owner, mark, submit, preflight) {
2811
2999
  }
2812
3000
  async function processOwned(owner, slot) {
2813
3001
  const { run, claim, lease } = owner;
2814
- const { clock, limits } = run.config;
2815
- const deadline = lease.dispatchedAt + limits.preHandoffTimeoutMs;
3002
+ const { clock, limits: limits2 } = run.config;
3003
+ const deadline = lease.dispatchedAt + limits2.preHandoffTimeoutMs;
2816
3004
  let budget;
2817
3005
  try {
2818
3006
  budget = createChildBudgetUntil(clock, run.budget, deadline);
@@ -2891,11 +3079,16 @@ var WorkerRun = class {
2891
3079
  if (this.noLaunch.aborted) invalid("aborted");
2892
3080
  }
2893
3081
  callStore(budget, operation) {
2894
- const { clock, limits } = this.config;
3082
+ const { clock, limits: limits2, capacity } = this.config;
2895
3083
  let invoked = false;
2896
3084
  return runStoreCall(clock, budget, {
2897
3085
  ...operation,
2898
- maxMs: Math.min(operation.maxMs ?? limits.storeTimeoutMs, limits.storeTimeoutMs),
3086
+ capacity,
3087
+ maxMs: Math.min(
3088
+ operation.maxMs ?? limits2.storeTimeoutMs,
3089
+ limits2.storeTimeoutMs,
3090
+ capacity ? STORE_PRIMITIVE_TIMEOUT_MS : Infinity
3091
+ ),
2899
3092
  beforeInvoke: () => {
2900
3093
  if (operation.authorize) this.checkLaunch();
2901
3094
  operation.beforeInvoke?.();
@@ -2973,23 +3166,23 @@ async function sweep(run, limit, items, invoke, read, entry) {
2973
3166
  return false;
2974
3167
  }
2975
3168
  function claimNext(run) {
2976
- const { clock, scope, store, limits } = run.config;
3169
+ const { clock, scope, store, limits: limits2, capacity } = run.config;
2977
3170
  const request = Object.freeze({
2978
3171
  attemptId: (0, import_node_crypto4.randomUUID)(),
2979
3172
  token: (0, import_node_crypto4.randomBytes)(16).toString("base64url"),
2980
- leaseMs: limits.leaseMs
3173
+ leaseMs: limits2.leaseMs
2981
3174
  });
2982
3175
  let dispatchedAt;
2983
3176
  return run.callStore(run.budget, {
2984
3177
  effect: "mutation",
2985
3178
  authorize: true,
2986
- maxMs: limits.preHandoffTimeoutMs,
3179
+ maxMs: limits2.preHandoffTimeoutMs,
2987
3180
  invoke(call, start) {
2988
3181
  dispatchedAt = start;
2989
3182
  return store.claimNext(scope, request, call);
2990
3183
  },
2991
3184
  accept: (value) => readStoreNext(value, (raw) => {
2992
- const claim = readClaimed(raw, scope, request);
3185
+ const claim = readClaimed(raw, scope, request, capacity);
2993
3186
  return { claim, dispatchedAt, confirmedAt: monotonicNow(clock) };
2994
3187
  })
2995
3188
  });
@@ -3067,13 +3260,13 @@ async function drainClaims(run, options, items, slots) {
3067
3260
  }
3068
3261
  async function runQueue(run, options, slots, shutdown) {
3069
3262
  const items = [];
3070
- const { scope, store } = run.config;
3263
+ const { scope, store, capacity } = run.config;
3071
3264
  const contended = await sweep(
3072
3265
  run,
3073
3266
  options.maintenanceLimit,
3074
3267
  items,
3075
3268
  (call) => store.recoverNext(scope, call),
3076
- readRecovery,
3269
+ (value) => readRecovery(value, capacity),
3077
3270
  (commit) => ({
3078
3271
  operation: "recover",
3079
3272
  jobId: commit.jobId,
@@ -3087,7 +3280,7 @@ async function runQueue(run, options, slots, shutdown) {
3087
3280
  options.maintenanceLimit,
3088
3281
  items,
3089
3282
  (call) => store.expireNext(scope, call),
3090
- (value) => readQueuedExpiry(value, scope),
3283
+ (value) => readQueuedExpiry(value, scope, capacity),
3091
3284
  (job) => ({
3092
3285
  operation: "expire",
3093
3286
  jobId: job.jobId,
@@ -3112,16 +3305,17 @@ async function runQueue(run, options, slots, shutdown) {
3112
3305
  }
3113
3306
  function createEmailWorker(options) {
3114
3307
  const config = readWorkerConfig(options);
3115
- const { clock, scope, limits } = config;
3308
+ const { clock, scope, limits: limits2, capacity } = config;
3116
3309
  const shutdown = new AbortController();
3117
3310
  const slots = /* @__PURE__ */ new Set();
3118
3311
  let active;
3119
3312
  const worker = {
3120
3313
  scope,
3314
+ ...capacityTag(capacity),
3121
3315
  async run(options2 = {}) {
3122
3316
  if (shutdown.signal.aborted) invalid("closed");
3123
3317
  if (active) invalid("busy");
3124
- const settings = readRunOptions(options2, limits);
3318
+ const settings = readRunOptions(options2, limits2, capacity);
3125
3319
  const done = new AbortController();
3126
3320
  active = done;
3127
3321
  try {
@@ -3188,7 +3382,7 @@ var ADMISSION_ERRORS = [
3188
3382
  function boundScope(port) {
3189
3383
  return scopeToken(readPortMember(port, "scope"), "invalid_config");
3190
3384
  }
3191
- function readBatch(scope, input) {
3385
+ function readBatch(scope, input, capacity) {
3192
3386
  const code = "invalid_command";
3193
3387
  const raw = readRecord(input, ["batchId", "items"], [], code);
3194
3388
  const batchId = identifier(raw.batchId, code);
@@ -3199,7 +3393,10 @@ function readBatch(scope, input) {
3199
3393
  if (seen.has(itemId)) invalid(code);
3200
3394
  seen.add(itemId);
3201
3395
  const command = readRecord(item.command, ["templateKey", "input", "provider", "intent"], ["scheduleAt"], code);
3202
- return { itemId, parsed: parseCommandIdentity(scope, { ...command, key: { kind: "batch", batchId, itemId } }) };
3396
+ return {
3397
+ itemId,
3398
+ parsed: parseCommandIdentity(scope, { ...command, key: { kind: "batch", batchId, itemId } }, capacity)
3399
+ };
3203
3400
  });
3204
3401
  if (!items.length) invalid(code);
3205
3402
  return { batchId, items };
@@ -3208,11 +3405,11 @@ function stopReason(budget) {
3208
3405
  if (budget.remainingMs() > 0) return;
3209
3406
  return allowedErrorCode(budget.signal.reason, STOP_ERRORS2) ?? invalid("invalid_config");
3210
3407
  }
3211
- function readAdmissionResult(input, identity) {
3408
+ function readAdmissionResult(input, identity, capacity) {
3212
3409
  const code = "write_unconfirmed";
3213
3410
  const { status, job: raw } = readRecord(input, ["status", "job"], [], code);
3214
3411
  if (status !== "enqueued" && status !== "replayed") invalid(code);
3215
- const job = readJobSummary(identity.scope, raw);
3412
+ const job = readJobSummary(identity.scope, raw, capacity);
3216
3413
  if (!matchesAdmissionJob(job, identity, status)) invalid(code);
3217
3414
  return { status, job };
3218
3415
  }
@@ -3220,20 +3417,25 @@ function createEmailBatchService(options) {
3220
3417
  return createEmailBatchServiceWithClock(options, systemEmailClock);
3221
3418
  }
3222
3419
  function createEmailBatchServiceWithClock(options, clock) {
3223
- const { service, worker } = readRecord(options, ["service", "worker"], [], "invalid_config");
3420
+ const raw = readRecord(options, ["service", "worker"], ["smtpCapacity"], "invalid_config");
3421
+ const { service, worker } = raw;
3422
+ const capacity = readCapacityOption(raw);
3423
+ assertPortCapacity(service, capacity);
3424
+ assertPortCapacity(worker, capacity);
3224
3425
  const scope = boundScope(service);
3225
3426
  if (scope !== boundScope(worker)) invalid("invalid_config");
3226
3427
  const run = bindMethod(worker, "run");
3227
3428
  const enqueue = bindMethod(service, "enqueue");
3228
3429
  const admit = findServiceAdmission(service) ?? (async ({ command, identity }, budget) => {
3229
3430
  if (boundScope(service) !== scope) invalid("invalid_config");
3431
+ assertPortCapacity(service, capacity);
3230
3432
  const bounds = CALL_BUDGETS.admissionOrAdmin;
3231
3433
  const timeoutMs = Math.max(bounds.min, Math.min(bounds.max, Math.floor(budget.remainingMs())));
3232
3434
  budget.check();
3233
- let raw;
3435
+ let raw2;
3234
3436
  try {
3235
3437
  const pending = enqueue(command, Object.freeze({ signal: budget.signal, timeoutMs }));
3236
- raw = import_node_util9.types.isPromise(pending) ? await pending : pending;
3438
+ raw2 = import_node_util9.types.isPromise(pending) ? await pending : pending;
3237
3439
  } catch (error) {
3238
3440
  if (allowedErrorCode(error, ["aborted"]) && allowedErrorCode(budget.signal.reason, ["deadline"])) {
3239
3441
  invalid("deadline");
@@ -3241,17 +3443,20 @@ function createEmailBatchServiceWithClock(options, clock) {
3241
3443
  throw error;
3242
3444
  }
3243
3445
  try {
3244
- return readAdmissionResult(raw, identity);
3446
+ return readAdmissionResult(raw2, identity, capacity);
3245
3447
  } catch {
3246
3448
  return invalid("write_unconfirmed");
3247
3449
  }
3248
3450
  });
3451
+ let admitting = false;
3249
3452
  const batch = {
3250
3453
  async enqueueBatch(input, call = {}) {
3454
+ if (capacity && admitting) invalid("busy");
3251
3455
  const { signal, timeoutMs } = readCallOptions(call, CALL_BUDGETS.batchOrRun);
3252
3456
  const budget = createBudget(clock, timeoutMs, signal);
3457
+ admitting = true;
3253
3458
  try {
3254
- const { batchId, items: commands } = readBatch(scope, input);
3459
+ const { batchId, items: commands } = readBatch(scope, input, capacity);
3255
3460
  const items = [];
3256
3461
  const counts = { enqueued: 0, replayed: 0, failed: 0, notStarted: 0, persistenceFailures: 0 };
3257
3462
  for (const { itemId, parsed } of commands) {
@@ -3273,11 +3478,13 @@ function createEmailBatchServiceWithClock(options, clock) {
3273
3478
  }
3274
3479
  return Object.freeze({ batchId, items: Object.freeze(items), counts: Object.freeze(counts) });
3275
3480
  } finally {
3481
+ admitting = false;
3276
3482
  budget.close();
3277
3483
  }
3278
3484
  },
3279
3485
  async run(options2) {
3280
3486
  if (boundScope(worker) !== scope) invalid("invalid_config");
3487
+ assertPortCapacity(worker, capacity);
3281
3488
  return run(options2);
3282
3489
  }
3283
3490
  };
@@ -3298,7 +3505,10 @@ function createEmailAdmin(options) {
3298
3505
  return createEmailAdminWithClock(options, systemEmailClock);
3299
3506
  }
3300
3507
  function createEmailAdminWithClock(options, clock) {
3301
- const { scope: input, store, onActivity: callback } = readRecord(options, ["scope", "store"], ["onActivity"], CONFIG3);
3508
+ const raw = readRecord(options, ["scope", "store"], ["onActivity", "smtpCapacity"], CONFIG3);
3509
+ const { scope: input, store, onActivity: callback } = raw;
3510
+ const capacity = readCapacityOption(raw);
3511
+ assertPortCapacity(store, capacity);
3302
3512
  const scope = scopeToken(input, CONFIG3);
3303
3513
  const findJob = bindMethod(store, "findJob");
3304
3514
  const cancel = bindMethod(store, "cancel");
@@ -3310,6 +3520,7 @@ function createEmailAdminWithClock(options, clock) {
3310
3520
  const cleanupNext = bindMethod(store, "cleanupNext");
3311
3521
  const onActivity = callback === void 0 ? void 0 : requireCallback(callback);
3312
3522
  let observers = 0;
3523
+ let active = false;
3313
3524
  function observe(activity, counts) {
3314
3525
  if (!onActivity) return;
3315
3526
  if (observers >= MAX_OBSERVER_PENDING) {
@@ -3328,29 +3539,35 @@ function createEmailAdminWithClock(options, clock) {
3328
3539
  }
3329
3540
  }
3330
3541
  function readJob(jobId, value) {
3331
- const job = readJobSummary(scope, value);
3542
+ const job = readJobSummary(scope, value, capacity);
3332
3543
  if (job.jobId !== jobId) invalid(STORED4);
3333
3544
  return job;
3334
3545
  }
3335
3546
  function callStore(budget, operation) {
3336
- return runStoreCall(clock, budget, { ...operation, maxMs: STORE_PRIMITIVE_TIMEOUT_MS });
3547
+ return runStoreCall(clock, budget, { ...operation, maxMs: STORE_PRIMITIVE_TIMEOUT_MS, capacity });
3337
3548
  }
3338
3549
  function write(budget, invoke, accept) {
3339
3550
  return callStore(budget, { effect: "mutation", invoke, accept });
3340
3551
  }
3341
3552
  async function inOperation(options2, run) {
3342
- const { timeoutMs, signal: source } = readCallOptions(options2, CALL_BUDGETS.admissionOrAdmin);
3343
- const signal = source && AbortSignal.any([source]);
3344
- const budget = createBudget(clock, timeoutMs, signal);
3553
+ if (capacity && active) invalid("busy");
3554
+ active = true;
3345
3555
  try {
3346
- return await run(budget, signal);
3556
+ const { timeoutMs, signal: source } = readCallOptions(options2, CALL_BUDGETS.admissionOrAdmin);
3557
+ const signal = source && AbortSignal.any([source]);
3558
+ const budget = createBudget(clock, timeoutMs, signal);
3559
+ try {
3560
+ return await run(budget, signal);
3561
+ } finally {
3562
+ budget.close();
3563
+ }
3347
3564
  } finally {
3348
- budget.close();
3565
+ active = false;
3349
3566
  }
3350
3567
  }
3351
3568
  async function maintain(options2, step) {
3352
3569
  const { limit: input2, ...call } = readRecord(options2, [], ["limit", "signal", "timeoutMs"], CONFIG3);
3353
- const limit = boundedOption(input2, ADMIN_MAINTENANCE_LIMIT);
3570
+ const limit = boundedOption(input2, capacity?.limits.adminMaintenance ?? ADMIN_MAINTENANCE_LIMIT);
3354
3571
  return inOperation(call, async (budget, signal) => {
3355
3572
  let stop = "limit";
3356
3573
  for (let i = 0; i < limit; i++) {
@@ -3393,11 +3610,11 @@ function createEmailAdminWithClock(options, clock) {
3393
3610
  budget,
3394
3611
  (call) => cancel(scope, id, call),
3395
3612
  (value) => {
3396
- const raw = readRecord(value, ["status"], ["job"], STORED4);
3397
- const { status } = raw;
3398
- if (status === "not_found" && !Object.hasOwn(raw, "job")) return Object.freeze({ status });
3613
+ const raw2 = readRecord(value, ["status"], ["job"], STORED4);
3614
+ const { status } = raw2;
3615
+ if (status === "not_found" && !Object.hasOwn(raw2, "job")) return Object.freeze({ status });
3399
3616
  if (status !== "cancelled" && status !== "too_late") invalid(STORED4);
3400
- const job = readJob(id, raw.job);
3617
+ const job = readJob(id, raw2.job);
3401
3618
  if (status === "cancelled" !== (job.state === "terminal" && job.disposition === "cancelled")) {
3402
3619
  invalid(STORED4);
3403
3620
  }
@@ -3414,8 +3631,8 @@ function createEmailAdminWithClock(options, clock) {
3414
3631
  definite: RESOLUTION_REJECTIONS,
3415
3632
  invoke: (call) => resolveUnknown(scope, request, call),
3416
3633
  accept(value) {
3417
- const { status, job: raw } = readRecord(value, ["status", "job"], [], STORED4);
3418
- const job = readJob(request.jobId, raw);
3634
+ const { status, job: raw2 } = readRecord(value, ["status", "job"], [], STORED4);
3635
+ const job = readJob(request.jobId, raw2);
3419
3636
  const decision = job.resolutions.find(({ attemptId }) => attemptId === request.attemptId);
3420
3637
  if (decision?.action !== request.action || status !== "resolved" && status !== "replayed") {
3421
3638
  invalid(STORED4);
@@ -3430,7 +3647,7 @@ function createEmailAdminWithClock(options, clock) {
3430
3647
  },
3431
3648
  listActivities(query = {}, options2 = {}) {
3432
3649
  return inOperation(options2, (budget) => {
3433
- const criteria = readActivityCriteria(scope, query);
3650
+ const criteria = readActivityCriteria(scope, query, capacity);
3434
3651
  const request = activityQuery(criteria);
3435
3652
  return callStore(budget, {
3436
3653
  effect: "read",
@@ -3445,7 +3662,7 @@ function createEmailAdminWithClock(options, clock) {
3445
3662
  const next = await write(
3446
3663
  budget,
3447
3664
  (call) => reserve(scope, call),
3448
- (value) => readStoreNext(value, (permit2) => readProjectionPermit(scope, permit2))
3665
+ (value) => readStoreNext(value, (permit2) => readProjectionPermit(scope, permit2, capacity))
3449
3666
  );
3450
3667
  if (next.status !== "applied") return next.status === "none" ? "idle" : "contended";
3451
3668
  counts.reserved++;
@@ -3560,6 +3777,7 @@ function jobSummary(job) {
3560
3777
  const latest = job.attempts.at(-1)?.commit;
3561
3778
  return Object.freeze({
3562
3779
  version: EMAIL_FORMAT_VERSION,
3780
+ ...job.smtpCapacity ? { smtpCapacity: job.smtpCapacity } : {},
3563
3781
  scope: job.scope,
3564
3782
  jobId: job.jobId,
3565
3783
  key: Object.freeze({ ...job.key }),
@@ -3584,13 +3802,13 @@ function jobSummary(job) {
3584
3802
  ...summaryState
3585
3803
  });
3586
3804
  }
3587
- function copyCommit(commit) {
3588
- return Object.freeze({ ...commit, result: readAttemptResult(commit.result, STORED5) });
3805
+ function copyCommit(commit, capacity) {
3806
+ return Object.freeze({ ...commit, result: readAttemptResult(commit.result, STORED5, false, capacity) });
3589
3807
  }
3590
- function readStoredSnapshot(job, input) {
3808
+ function readStoredSnapshot(job, input, capacity) {
3591
3809
  let validated;
3592
3810
  try {
3593
- validated = validateSnapshot(input);
3811
+ validated = validateSnapshot(input, capacity);
3594
3812
  } catch {
3595
3813
  return invalid(STORED5);
3596
3814
  }
@@ -3625,7 +3843,7 @@ function replace(job, time, patch, value, before, pendingAck) {
3625
3843
  write: { kind: "replace", guard: pendingAck ? { ...expect, pendingAck } : expect, next }
3626
3844
  };
3627
3845
  }
3628
- function newJob(admission, time) {
3846
+ function newJob(admission, time, capacity) {
3629
3847
  const { command, jobId, retry, retention, admissionKey } = admission;
3630
3848
  const { scope, key, scheduleAt, fingerprint, snapshotHash, snapshot } = command;
3631
3849
  const now = unixMs(time.now, "store_unavailable");
@@ -3634,6 +3852,8 @@ function newJob(admission, time) {
3634
3852
  if (nextAt >= snapshot.expiresAt) invalid("expired");
3635
3853
  return Object.freeze({
3636
3854
  version: EMAIL_FORMAT_VERSION,
3855
+ ...capacityTag(capacity),
3856
+ ...capacity ? { intentHash: command.intentHash } : {},
3637
3857
  scope,
3638
3858
  jobId,
3639
3859
  key,
@@ -3672,14 +3892,14 @@ function liveLease(job, fence, phase, now) {
3672
3892
  }
3673
3893
  return lease;
3674
3894
  }
3675
- function claimJob(job, claim, time) {
3895
+ function claimJob(job, claim, time, capacity) {
3676
3896
  const { now } = time;
3677
3897
  if (job.state.state !== "queued" || job.state.nextAt > now || now >= job.expiresAt) return null;
3678
3898
  const manual = hasRedrive(job);
3679
3899
  const ordinal = job.attempts.length + 1;
3680
3900
  if (ordinal > MAX_ATTEMPT_LEDGER || !manual && ordinal > job.retry.maxAttempts) invalid("store_incompatible");
3681
3901
  if (job.attempts.some(({ commit }) => commit.attemptId === claim.attemptId)) invalid("invalid_command");
3682
- const snapshot = readStoredSnapshot(job, job.snapshot);
3902
+ const snapshot = readStoredSnapshot(job, job.snapshot, capacity);
3683
3903
  const lease = Object.freeze({
3684
3904
  attemptId: claim.attemptId,
3685
3905
  token: claim.token,
@@ -3739,7 +3959,7 @@ function markJob(job, fence, leaseMs, time) {
3739
3959
  Math.min(job.expiresAt, lease.leaseEndsAt, grant.leaseEndsAt)
3740
3960
  );
3741
3961
  }
3742
- function finalize(job, lease, operationId, result, time, owner) {
3962
+ function finalize(job, lease, operationId, result, time, owner, capacity) {
3743
3963
  const { now } = time;
3744
3964
  const { attemptId, startedAt, handedOffAt } = lease;
3745
3965
  const ordinal = job.attempts.length + 1;
@@ -3757,7 +3977,7 @@ function finalize(job, lease, operationId, result, time, owner) {
3757
3977
  });
3758
3978
  const entry = Object.freeze({
3759
3979
  commit,
3760
- digest: activityDigest(activityFor(job, commit)),
3980
+ digest: activityDigest(activityFor(job, commit, capacity), capacity),
3761
3981
  ...owner ? { ownerDigest: sha256(lease.token) } : {}
3762
3982
  });
3763
3983
  const state = effect.disposition === "retry_scheduled" ? Object.freeze({ state: "queued", nextAt: effect.retryAt }) : terminalState(effect.disposition, effect.reason, now);
@@ -3769,11 +3989,11 @@ function finalize(job, lease, operationId, result, time, owner) {
3769
3989
  job,
3770
3990
  time,
3771
3991
  { ...job, state, attempts: Object.freeze([...job.attempts, entry]) },
3772
- () => copyCommit(commit),
3992
+ () => copyCommit(commit, capacity),
3773
3993
  before
3774
3994
  );
3775
3995
  }
3776
- function finishJob(job, request, time) {
3996
+ function finishJob(job, request, time, capacity) {
3777
3997
  const { fence, phase, operationId, result } = request;
3778
3998
  if (job.jobId !== fence.jobId) return null;
3779
3999
  assertEvidencePhase(result.reason, phase, "owner", "invalid_command");
@@ -3784,28 +4004,28 @@ function finishJob(job, request, time) {
3784
4004
  if (previous.ownerDigest !== sha256(fence.token) || commit.operationId !== operationId || previousPhase !== phase) {
3785
4005
  return null;
3786
4006
  }
3787
- if (hashJson(result, 8192, "invalid_command") !== hashJson(commit.result, 8192, "store_incompatible")) {
4007
+ if (sha256(encodeEvidence(result, "invalid_command", capacity)) !== sha256(encodeEvidence(commit.result, "store_incompatible", capacity))) {
3788
4008
  invalid("invalid_command");
3789
4009
  }
3790
- return { value: copyCommit(commit) };
4010
+ return { value: copyCommit(commit, capacity) };
3791
4011
  }
3792
4012
  const lease = liveLease(job, fence, phase, time.now);
3793
4013
  if (!lease) return null;
3794
4014
  if (result.reason === "expired" && time.now < job.expiresAt) invalid("invalid_command");
3795
4015
  assertEvidenceContext(result, job.provider, fence.attemptId, job.recipientCounts, "invalid_command");
3796
- return finalize(job, lease, operationId, result, time, true);
4016
+ return finalize(job, lease, operationId, result, time, true, capacity);
3797
4017
  }
3798
- function recoverJob(job, operationId, time) {
4018
+ function recoverJob(job, operationId, time, capacity) {
3799
4019
  if (job.state.state !== "leased" || time.now < job.state.lease.leaseEndsAt) return null;
3800
4020
  const { lease } = job.state;
3801
4021
  const reason = lease.handedOffAt === void 0 ? "pre_handoff_lease_expired" : "post_handoff_lease_expired";
3802
- return finalize(job, lease, operationId, lifecycleEvidence(reason), time, false);
4022
+ return finalize(job, lease, operationId, lifecycleEvidence(reason), time, false, capacity);
3803
4023
  }
3804
4024
  function expireJob(job, time) {
3805
4025
  if (job.state.state !== "queued" || time.now < job.expiresAt) return null;
3806
4026
  return replace(job, time, { ...job, state: terminalState("expired", "expired", time.now) }, jobSummary);
3807
4027
  }
3808
- function cancelJob(job, operationId, time) {
4028
+ function cancelJob(job, operationId, time, capacity) {
3809
4029
  const { state } = job;
3810
4030
  if (state.state === "terminal") {
3811
4031
  return {
@@ -3819,7 +4039,7 @@ function cancelJob(job, operationId, time) {
3819
4039
  return { value: Object.freeze({ status: "too_late", job: jobSummary(job) }) };
3820
4040
  }
3821
4041
  if (state.state === "leased") {
3822
- const decision = finalize(job, state.lease, operationId, lifecycleEvidence("cancelled"), time, false);
4042
+ const decision = finalize(job, state.lease, operationId, lifecycleEvidence("cancelled"), time, false, capacity);
3823
4043
  const { write } = decision;
3824
4044
  if (write?.kind !== "replace") invalid("store_incompatible");
3825
4045
  return { write, value: Object.freeze({ status: "cancelled", job: jobSummary(write.next) }) };
@@ -3864,11 +4084,11 @@ function resolveJob(job, request, time) {
3864
4084
  function replaceAttempt(job, previous, entry) {
3865
4085
  return Object.freeze(job.attempts.map((attempt) => attempt === previous ? Object.freeze(entry) : attempt));
3866
4086
  }
3867
- function reserveJobProjection(job, time) {
4087
+ function reserveJobProjection(job, time, capacity) {
3868
4088
  const entry = pendingAttempt(job);
3869
4089
  if (job.retiring || !entry || entry.commit.finishedAt > time.now) return null;
3870
4090
  const permitUntil = timeAfter(time.now, PROJECTION_PERMIT_MS) ?? invalid("store_unavailable");
3871
- const activity = activityFor(job, entry.commit);
4091
+ const activity = activityFor(job, entry.commit, capacity);
3872
4092
  const permit = Object.freeze({ activity, digest: entry.digest, permitUntil });
3873
4093
  const attempts = replaceAttempt(job, entry, { ...entry, permitUntil });
3874
4094
  return replace(
@@ -4012,12 +4232,14 @@ var TIME_MISS = /* @__PURE__ */ Symbol("time_miss");
4012
4232
  var NONE = Object.freeze({ status: "none" });
4013
4233
  var CONTENDED = Object.freeze({ status: "contended" });
4014
4234
  function createMemoryEmailStore(options = {}) {
4015
- const config = readRecord(options, [], ["clock", "maxJobs"], "invalid_config");
4235
+ const config = readRecord(options, [], ["clock", "maxJobs", "smtpCapacity"], "invalid_config");
4236
+ const capacity = readCapacityOption(config);
4016
4237
  const clock = readClock(config.clock);
4017
- const maxJobs = boundedOption(config.maxJobs, MEMORY_MAX_JOBS);
4238
+ const maxJobs = boundedOption(config.maxJobs, capacity?.limits.memoryJobs ?? MEMORY_MAX_JOBS);
4018
4239
  const scopes = /* @__PURE__ */ new Map();
4019
4240
  let count = 0;
4020
4241
  let active = false;
4242
+ let ready = false;
4021
4243
  let lastWall = 0;
4022
4244
  function wallNow() {
4023
4245
  let now;
@@ -4058,8 +4280,13 @@ function createMemoryEmailStore(options = {}) {
4058
4280
  active = false;
4059
4281
  }
4060
4282
  }
4283
+ function primitive(call, worker, run) {
4284
+ const safe = readStoreCall(call, worker, capacity);
4285
+ if (capacity && !ready) invalid("store_unavailable");
4286
+ return atomic(safe, run);
4287
+ }
4061
4288
  function read(call, worker, get) {
4062
- return atomic(readStoreCall(call, worker), (check) => {
4289
+ return primitive(call, worker, (check) => {
4063
4290
  const value = get();
4064
4291
  check();
4065
4292
  return value;
@@ -4124,12 +4351,14 @@ function createMemoryEmailStore(options = {}) {
4124
4351
  return misses ? CONTENDED : NONE;
4125
4352
  }
4126
4353
  const store = {
4354
+ ...capacityTag(capacity),
4127
4355
  async ready(options2 = {}) {
4128
4356
  const call = readCallOptions(options2, CALL_BUDGETS.admissionOrAdmin);
4129
4357
  atomic({ ...call, timeoutMs: Math.min(call.timeoutMs, STORE_PRIMITIVE_TIMEOUT_MS) }, (check) => {
4130
4358
  wallNow();
4131
4359
  check();
4132
4360
  });
4361
+ ready = true;
4133
4362
  },
4134
4363
  async findAdmission(scope, key, call) {
4135
4364
  return read(call, false, () => {
@@ -4141,15 +4370,15 @@ function createMemoryEmailStore(options = {}) {
4141
4370
  });
4142
4371
  },
4143
4372
  async insert(scope, admission, call) {
4144
- return atomic(readStoreCall(call), (check) => {
4145
- const parsed = readStoreAdmission(scope, admission);
4373
+ return primitive(call, false, (check) => {
4374
+ const parsed = readStoreAdmission(scope, admission, capacity);
4146
4375
  const rows = scopes.get(parsed.command.scope);
4147
4376
  if (rows?.identities.has(parsed.admissionKey)) {
4148
4377
  check();
4149
4378
  return Object.freeze({ status: "duplicate" });
4150
4379
  }
4151
4380
  if (rows?.jobs.has(parsed.jobId)) invalid("invalid_command");
4152
- const row = newJob(parsed, { now: wallNow(), revision: (0, import_node_crypto5.randomUUID)() });
4381
+ const row = newJob(parsed, { now: wallNow(), revision: (0, import_node_crypto5.randomUUID)() }, capacity);
4153
4382
  if (count >= maxJobs) invalid("store_capacity");
4154
4383
  const result = Object.freeze({ status: "inserted", job: jobSummary(row) });
4155
4384
  check();
@@ -4176,62 +4405,66 @@ function createMemoryEmailStore(options = {}) {
4176
4405
  const job = readStoreId(jobId);
4177
4406
  const id = readStoreId(attemptId);
4178
4407
  const entry = rows?.jobs.get(job)?.attempts.find(({ commit }) => commit.attemptId === id);
4179
- return entry ? copyCommit(entry.commit) : null;
4408
+ return entry ? copyCommit(entry.commit, capacity) : null;
4180
4409
  });
4181
4410
  },
4182
4411
  async claimNext(scope, claim, call) {
4183
- return atomic(readStoreCall(call, true), (check) => {
4412
+ return primitive(call, true, (check) => {
4184
4413
  const safe = readClaim(claim);
4185
- return next(scope, "nextAt", check, (row, time) => claimJob(row, safe, time));
4414
+ return next(scope, "nextAt", check, (row, time) => claimJob(row, safe, time, capacity));
4186
4415
  });
4187
4416
  },
4188
4417
  async renew(scope, fence, leaseMs, call) {
4189
- return atomic(readStoreCall(call, true), (check) => {
4418
+ return primitive(call, true, (check) => {
4190
4419
  const safe = readFence(fence);
4191
4420
  const duration = readLeaseMs(leaseMs);
4192
4421
  return point(scope, safe.jobId, check, (row, time) => renewJob(row, safe, duration, time));
4193
4422
  });
4194
4423
  },
4195
4424
  async markHandoff(scope, fence, leaseMs, call) {
4196
- return atomic(readStoreCall(call, true), (check) => {
4425
+ return primitive(call, true, (check) => {
4197
4426
  const safe = readFence(fence);
4198
4427
  const duration = readLeaseMs(leaseMs);
4199
4428
  return point(scope, safe.jobId, check, (row, time) => markJob(row, safe, duration, time));
4200
4429
  });
4201
4430
  },
4202
4431
  async finish(scope, finish, call) {
4203
- return atomic(readStoreCall(call, true), (check) => {
4204
- const safe = readFinish(finish);
4205
- return point(scope, safe.fence.jobId, check, (row, time) => finishJob(row, safe, time));
4432
+ return primitive(call, true, (check) => {
4433
+ const safe = readFinish(finish, capacity);
4434
+ return point(scope, safe.fence.jobId, check, (row, time) => finishJob(row, safe, time, capacity));
4206
4435
  });
4207
4436
  },
4208
4437
  async recoverNext(scope, call) {
4209
- return atomic(readStoreCall(call, true), (check) => {
4438
+ return primitive(call, true, (check) => {
4210
4439
  const operationId = (0, import_node_crypto5.randomUUID)();
4211
- return next(scope, "leaseEndsAt", check, (row, time) => recoverJob(row, operationId, time));
4440
+ return next(scope, "leaseEndsAt", check, (row, time) => recoverJob(row, operationId, time, capacity));
4212
4441
  });
4213
4442
  },
4214
4443
  async expireNext(scope, call) {
4215
- return atomic(readStoreCall(call, true), (check) => next(scope, "queuedExpiresAt", check, expireJob));
4444
+ return primitive(call, true, (check) => next(scope, "queuedExpiresAt", check, expireJob));
4216
4445
  },
4217
4446
  async cancel(scope, jobId, call) {
4218
- return atomic(readStoreCall(call), (check) => {
4447
+ return primitive(call, false, (check) => {
4219
4448
  const operationId = (0, import_node_crypto5.randomUUID)();
4220
- return point(scope, readStoreId(jobId), check, (row, time) => cancelJob(row, operationId, time)) ?? Object.freeze({ status: "not_found" });
4449
+ return point(scope, readStoreId(jobId), check, (row, time) => cancelJob(row, operationId, time, capacity)) ?? Object.freeze({ status: "not_found" });
4221
4450
  });
4222
4451
  },
4223
4452
  async resolveUnknown(scope, command, call) {
4224
- return atomic(readStoreCall(call), (check) => {
4453
+ return primitive(call, false, (check) => {
4225
4454
  const safe = readResolution(command);
4226
4455
  return point(scope, safe.jobId, check, (row, time) => resolveJob(row, safe, time)) ?? invalid("not_found");
4227
4456
  });
4228
4457
  },
4229
4458
  async reserveProjection(scope, call) {
4230
- return atomic(readStoreCall(call), (check) => next(scope, "pendingAt", check, reserveJobProjection));
4459
+ return primitive(
4460
+ call,
4461
+ false,
4462
+ (check) => next(scope, "pendingAt", check, (row, time) => reserveJobProjection(row, time, capacity))
4463
+ );
4231
4464
  },
4232
4465
  async putActivity(scope, permit, call) {
4233
- return atomic(readStoreCall(call), (check) => {
4234
- const safe = readProjectionPermit(scopeToken(scope), permit);
4466
+ return primitive(call, false, (check) => {
4467
+ const safe = readProjectionPermit(scopeToken(scope), permit, capacity);
4235
4468
  const rows = scopes.get(scope);
4236
4469
  const { jobId, attemptId } = safe.activity;
4237
4470
  const existing = rows?.byJob.get(jobId)?.byId.get(attemptId);
@@ -4247,8 +4480,8 @@ function createMemoryEmailStore(options = {}) {
4247
4480
  });
4248
4481
  },
4249
4482
  async ackProjection(scope, permit, call) {
4250
- return atomic(readStoreCall(call), (check) => {
4251
- const safe = readProjectionPermit(scopeToken(scope), permit);
4483
+ return primitive(call, false, (check) => {
4484
+ const safe = readProjectionPermit(scopeToken(scope), permit, capacity);
4252
4485
  const { jobId, attemptId } = safe.activity;
4253
4486
  const proof = scopes.get(scope)?.byJob.get(jobId)?.byId.get(attemptId);
4254
4487
  return point(scope, jobId, check, (row, time) => acknowledgeJobProjection(row, safe, proof, time)) ?? "stale";
@@ -4256,7 +4489,7 @@ function createMemoryEmailStore(options = {}) {
4256
4489
  },
4257
4490
  async listActivities(scope, query, call) {
4258
4491
  return read(call, false, () => {
4259
- const criteria = readActivityCriteria(scopeToken(scope), query);
4492
+ const criteria = readActivityCriteria(scopeToken(scope), query, capacity);
4260
4493
  const rows = scopes.get(scope);
4261
4494
  const { jobId, before, from, after, limit } = criteria;
4262
4495
  const index = (jobId === null ? rows?.activities : rows?.byJob.get(jobId)?.ordered) ?? [];
@@ -4270,7 +4503,7 @@ function createMemoryEmailStore(options = {}) {
4270
4503
  });
4271
4504
  },
4272
4505
  async cleanupNext(scope, call) {
4273
- return atomic(readStoreCall(call), (check) => next(scope, "nextCleanupAt", check, cleanupJob));
4506
+ return primitive(call, false, (check) => next(scope, "nextCleanupAt", check, cleanupJob));
4274
4507
  }
4275
4508
  };
4276
4509
  return Object.freeze(store);