@web-ts-toolkit/email-service 0.72.0 → 0.74.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.mts CHANGED
@@ -1,11 +1,14 @@
1
- import { J as JsonObject, E as EmailEnvelope, a as EmailScope, b as EmailAdmissionKey, P as ProviderRef, U as UnixMs, A as Awaitable, c as AttachmentRef, C as Correlation, d as JsonValue, e as CallOptions, f as PreparedEmailCommand, g as EmailClock } from './provider-HisBc6hk.mjs';
2
- export { h as AttachmentResolution, i as AttachmentResolver, j as AttemptReason, k as AttemptResult, l as ConfiguredEmailProvider, m as EmailAttemptId, n as EmailJobId, o as EmailProvider, p as EmailSnapshot, M as Mailbox, q as PreparedEmailSubmission, r as ProviderCall, s as ProviderReason, t as ProviderResult, u as ProviderSubmission, R as RecipientResult, v as ResolvedAttachment, w as RetryClass, x as RetryHint, S as SendGridSnapshot, y as SmtpSnapshot, z as SubmissionOutcome, B as SubmissionStage, T as TemplateIdentity } from './provider-HisBc6hk.mjs';
3
- import { E as EmailJobSummary, a as EmailRunOptions, b as EmailRunReport, c as EmailWorker, d as EmailStore, R as RetryPolicy, e as RetentionPolicy, f as EmailWorkerOptions, g as EmailAdminOptions, h as EmailAdmin, M as MemoryEmailStoreOptions } from './store-D4YAI6Rk.mjs';
4
- export { A as AttemptCommit, C as CancelResult, i as ClaimedEmail, j as CleanupReport, k as CleanupStep, l as EmailActivity, m as EmailActivityPage, n as EmailActivityQuery, o as EmailJobState, p as EmailRateLimiter, q as EmailRunEntry, r as EmailShutdownReport, s as EmailWorkerLimits, H as HandoffGrant, J as JobDisposition, L as LeaseGrant, t as LeaseToken, u as MaintenanceOptions, v as MaintenanceStop, O as OwnerFence, P as ProjectionPermit, w as ReconcileReport, x as ResolveUnknownCommand, y as ResolveUnknownResult, S as StoreAdmission, z as StoreCall, B as StoreNext, U as UnknownResolution } from './store-D4YAI6Rk.mjs';
1
+ import { J as JsonObject, E as EmailEnvelope, a as EmailScope, b as EmailAdmissionKey, P as ProviderRef, U as UnixMs, A as Awaitable, c as AttachmentRef, C as Correlation, d as JsonValue, S as SmtpCapacity, e as CallOptions, f as PreparedEmailCommand, g as EmailClock, R as RecipientResult, h as ProviderResult } from './provider-CeUryYAf.mjs';
2
+ export { i as AttachmentResolution, j as AttachmentResolver, k as AttemptReason, l as AttemptResult, m as ConfiguredEmailProvider, n as EmailAttemptId, o as EmailJobId, p as EmailProvider, q as EmailSnapshot, M as Mailbox, r as PreparedEmailSubmission, s as ProviderCall, t as ProviderReason, u as ProviderSubmission, v as ResolvedAttachment, w as RetryClass, x as RetryHint, y as SendGridSnapshot, z as SmtpSnapshot, B as SubmissionOutcome, D as SubmissionStage, T as TemplateIdentity } from './provider-CeUryYAf.mjs';
3
+ import { E as EmailJobSummary, a as EmailRunOptions, b as EmailRunReport, c as EmailWorker, d as EmailStore, R as RetryPolicy, e as RetentionPolicy, f as EmailWorkerOptions, g as EmailAdminOptions, h as EmailAdmin, M as MemoryEmailStoreOptions } from './store-DjCqXbPv.mjs';
4
+ export { A as AttemptCommit, C as CancelResult, i as ClaimedEmail, j as CleanupReport, k as CleanupStep, l as EmailActivity, m as EmailActivityPage, n as EmailActivityQuery, o as EmailJobState, p as EmailRateLimiter, q as EmailRunEntry, r as EmailShutdownReport, s as EmailWorkerLimits, H as HandoffGrant, J as JobDisposition, L as LeaseGrant, t as LeaseToken, u as MaintenanceOptions, v as MaintenanceStop, O as OwnerFence, P as ProjectionPermit, w as ReconcileReport, x as ResolveUnknownCommand, y as ResolveUnknownResult, S as StoreAdmission, z as StoreCall, B as StoreClaimNext, D as StoreNext, U as UnknownResolution } from './store-DjCqXbPv.mjs';
5
5
 
6
6
  /** Safe, stable diagnostics; no application data or transport-response text. */
7
7
  type EmailErrorCode = 'invalid_config' | 'invalid_command' | 'invalid_input' | 'invalid_data' | 'invalid_snapshot' | 'preparation_failed' | 'template_not_found' | 'template_source' | 'template_render' | 'provider_mismatch' | 'expired' | 'idempotency_conflict' | 'not_found' | 'resolution_conflict' | 'store_capacity' | 'store_unavailable' | 'store_incompatible' | 'write_unconfirmed' | 'invalid_cursor' | 'aborted' | 'deadline' | 'busy' | 'closed';
8
- /** Compare `.code`, not class identity, across separately loaded ESM and CommonJS builds. */
8
+ /**
9
+ * Narrow a caught `unknown` to a known `.code`, not class identity. Independently bundled
10
+ * entrypoints can throw different classes even within one format (all ESM or all CommonJS).
11
+ */
9
12
  declare class EmailError extends Error {
10
13
  /** `write_unconfirmed` does not mean that a dispatched mutation failed to commit. */
11
14
  readonly code: EmailErrorCode;
@@ -23,6 +26,10 @@ type PrepareContext = {
23
26
  /** Host-generated fields. Only From and Reply-To can come from template defaults. */
24
27
  type PreparedFields<D extends JsonObject> = Partial<EmailEnvelope> & {
25
28
  values: D;
29
+ /**
30
+ * Unix ms; defaults to 24 hours from preparation. Must be strictly after preparation and
31
+ * `scheduleAt` (if given), and at most 30 days from preparation. Frozen in the snapshot.
32
+ */
26
33
  expiresAt?: UnixMs;
27
34
  priority?: number;
28
35
  attachments?: readonly AttachmentRef[];
@@ -44,7 +51,10 @@ type LocalSource = {
44
51
  type TemplateDefinition<I, D extends JsonObject> = {
45
52
  revision: string;
46
53
  defaults?: Pick<Partial<EmailEnvelope>, 'from' | 'replyTo'>;
47
- /** Synchronously validate the host's opaque business input. */
54
+ /**
55
+ * Validate the command's declared input shape synchronously at runtime.
56
+ * The return type defines what callers supply as `command.input`; normalize message values in `prepare`.
57
+ */
48
58
  parseInput: (input: unknown) => I;
49
59
  /** Synchronously validate or normalize a detached JSON object. Return a new object to change it. */
50
60
  parseData: (data: unknown) => D;
@@ -73,15 +83,26 @@ type TemplateMap = Readonly<Record<string, Omit<TemplateDefinition<never, JsonOb
73
83
  type TemplateDefinitions<T extends TemplateMap> = T & {
74
84
  [K in keyof T]: TemplateDefinition<ReturnType<T[K]['parseInput']>, ReturnType<T[K]['parseData']>>;
75
85
  };
76
- /** The key determines the input and provider kind. `intent` describes stable business meaning, not rendered data. */
86
+ type ProviderByTemplateKind = {
87
+ handlebars: Extract<ProviderRef, {
88
+ kind: 'smtp';
89
+ }>;
90
+ sendgrid: Extract<ProviderRef, {
91
+ kind: 'sendgrid';
92
+ }>;
93
+ };
94
+ /**
95
+ * The template key determines input and provider kind. A widened `TemplateMap` allows either provider.
96
+ * `intent` describes stable business meaning, not rendered data.
97
+ * Keep `scheduleAt` stable on replay; schedules past the default 24-hour expiry need explicit `expiresAt` in `prepare`.
98
+ */
77
99
  type TemplateCommand<T extends TemplateMap> = {
78
100
  [K in keyof T & string]: {
79
101
  templateKey: K;
80
102
  input: ReturnType<T[K]['parseInput']>;
81
- provider: Extract<ProviderRef, {
82
- kind: T[K]['kind'] extends 'handlebars' ? 'smtp' : 'sendgrid';
83
- }>;
103
+ provider: ProviderByTemplateKind[T[K]['kind']];
84
104
  intent: JsonValue;
105
+ /** Earliest eligible time (Unix ms), not a timer. Must precede the snapshot expiry. */
85
106
  scheduleAt?: UnixMs;
86
107
  };
87
108
  }[keyof T & string];
@@ -90,6 +111,8 @@ type EmailCommand<T extends TemplateMap> = TemplateCommand<T> & {
90
111
  key: EmailAdmissionKey;
91
112
  };
92
113
  type TemplateRegistryOptions = {
114
+ /** Prepare only local SMTP messages under this binding. Use the same tuple for their admission. */
115
+ smtpCapacity?: SmtpCapacity;
93
116
  clock?: EmailClock;
94
117
  cacheEntries?: number;
95
118
  maxPending?: number;
@@ -97,7 +120,11 @@ type TemplateRegistryOptions = {
97
120
  helpers?: Readonly<Record<string, (...args: unknown[]) => unknown>>;
98
121
  };
99
122
  interface EmailTemplateRegistry<T extends TemplateMap> {
100
- /** Prepare a detached snapshot without using a queue or contacting a provider. */
123
+ readonly smtpCapacity?: SmtpCapacity;
124
+ /**
125
+ * Prepare a detached snapshot without using a queue or contacting a provider.
126
+ * SMTP `message/*` and `multipart/*` attachment refs fail with `invalid_snapshot`.
127
+ */
101
128
  prepare(scope: EmailScope, command: EmailCommand<T>, options?: CallOptions): Promise<PreparedEmailCommand>;
102
129
  /** Evict one or all compilation cache entries and fence their prior in-flight loads. */
103
130
  invalidate(templateKey?: keyof T & string): void;
@@ -114,15 +141,34 @@ type AdmissionResult = {
114
141
  readonly status: 'enqueued' | 'replayed';
115
142
  readonly job: EmailJobSummary;
116
143
  };
117
- interface EmailService<T extends TemplateMap> {
144
+ /** Prepared-only admission. The relay does not need a template registry or delivery configuration. */
145
+ interface EmailRelay {
146
+ /**
147
+ * Relay the same scoped outbox snapshot unchanged. Does not join a host transaction, rerender, or extend expiry.
148
+ * A retained match replays; on a new admission SMTP `message/*` and `multipart/*` refs fail with `invalid_snapshot`.
149
+ */
150
+ enqueuePrepared(command: PreparedEmailCommand, options?: CallOptions): Promise<AdmissionResult>;
151
+ }
152
+ type EmailRelayOptions = {
153
+ /** The original scope of the staged command. */
154
+ scope: EmailScope;
155
+ /** Pass the exact store binding explicitly when relaying to an opted-in queue. */
156
+ smtpCapacity?: SmtpCapacity;
157
+ /** Admission primitives only. Ready the underlying store before use. */
158
+ store: Pick<EmailStore, 'smtpCapacity' | 'findAdmission' | 'insert'>;
159
+ retry?: Partial<RetryPolicy>;
160
+ retention?: Partial<RetentionPolicy>;
161
+ };
162
+ interface EmailService<T extends TemplateMap> extends EmailRelay {
118
163
  readonly scope: EmailScope;
164
+ readonly smtpCapacity?: SmtpCapacity;
119
165
  /** Admit or replay by scoped stable intent; a committed replay does not prepare again. */
120
166
  enqueue(command: EmailCommand<T>, options?: CallOptions): Promise<AdmissionResult>;
121
- /** Relay the same scoped outbox snapshot unchanged. Does not join a host transaction, rerender, or extend expiry. */
122
- enqueuePrepared(command: PreparedEmailCommand, options?: CallOptions): Promise<AdmissionResult>;
123
167
  }
124
168
  type EmailServiceOptions<T extends TemplateMap> = {
125
169
  scope: EmailScope;
170
+ /** Must match the registry and store. Relay staged commands only through their original binding. */
171
+ smtpCapacity?: SmtpCapacity;
126
172
  store: EmailStore;
127
173
  registry: EmailTemplateRegistry<T>;
128
174
  retry?: Partial<RetryPolicy>;
@@ -152,7 +198,8 @@ type EmailBatchResult = {
152
198
  readonly persistenceFailures: number;
153
199
  };
154
200
  };
155
- interface EmailBatchService<T extends TemplateMap> {
201
+ /** Producer-only batch admission; no worker or delivery methods. */
202
+ interface EmailBatchAdmission<T extends TemplateMap> {
156
203
  /**
157
204
  * Validate 1–100 items up front, then admit them in input order under one timeout (default 30 seconds).
158
205
  * Replay the same batch/item IDs and intent to resume; earlier writes aren't rolled back on a failure.
@@ -161,15 +208,30 @@ interface EmailBatchService<T extends TemplateMap> {
161
208
  batchId: string;
162
209
  items: readonly EmailBatchItem<T>[];
163
210
  }, options?: CallOptions): Promise<EmailBatchResult>;
211
+ }
212
+ type EmailBatchAdmissionOptions<T extends TemplateMap> = {
213
+ /** Bound admission service or wrapper. A wrapper must honor the call's signal and timeout. */
214
+ service: Pick<EmailService<T>, 'scope' | 'smtpCapacity' | 'enqueue'>;
215
+ /** Pass the exact tuple explicitly when the service is opted in. */
216
+ smtpCapacity?: SmtpCapacity;
217
+ };
218
+ interface EmailBatchService<T extends TemplateMap> extends EmailBatchAdmission<T> {
164
219
  /** Run the same scope-wide worker, not a second delivery loop or a batch filter. */
165
220
  run(options?: EmailRunOptions): Promise<EmailRunReport>;
166
221
  }
167
222
  type EmailBatchServiceOptions<T extends TemplateMap> = {
168
- /** Must share the worker's scope and underlying store. */
223
+ /** Must share the worker's scope, underlying store and SMTP capacity binding, if enabled. */
169
224
  service: EmailService<T>;
170
225
  worker: EmailWorker;
226
+ /** Pass the exact tuple explicitly when the service and worker are opted in. */
227
+ smtpCapacity?: SmtpCapacity;
171
228
  };
172
229
 
230
+ /**
231
+ * Admit a staged outbox snapshot without a registry. Ready the underlying queue store first.
232
+ * After `write_unconfirmed`, relay the same staged command under its original scope and binding.
233
+ */
234
+ declare function createEmailRelay(options: EmailRelayOptions): EmailRelay;
173
235
  /**
174
236
  * Scope-bound admission only. Call `store.ready()` yourself; neither method contacts a mail provider.
175
237
  * After `write_unconfirmed`, retry the same scoped key and intent: the original insert may have committed.
@@ -180,9 +242,16 @@ declare function createEmailService<T extends TemplateMap>(options: EmailService
180
242
  * Create a scope-bound worker for a caller-ready store and exact provider profiles. The host schedules
181
243
  * bounded `run` calls; nothing polls on construction. `shutdown` is permanent and never closes the store.
182
244
  * A one-shot provider call requires a timely durable handoff acknowledgement, not a later read of a marker.
245
+ * An empty provider array throws `invalid_config` before any work. For enqueue-only batches,
246
+ * use `createEmailBatchAdmission({ service })` instead of constructing a worker.
183
247
  */
184
248
  declare function createEmailWorker(options: EmailWorkerOptions): EmailWorker;
185
249
 
250
+ /**
251
+ * Enqueue or resume a batch through a bound service without configuring a worker.
252
+ * Replay the same batch/item IDs and intent after `write_unconfirmed`: an item may already have committed.
253
+ */
254
+ declare function createEmailBatchAdmission<T extends TemplateMap>(options: EmailBatchAdmissionOptions<T>): EmailBatchAdmission<T>;
186
255
  /**
187
256
  * Compose a same-scope admission service and worker. Wire both to the same underlying store.
188
257
  * Enqueue is sequential and resumable by batch/item ID, not atomic. `run` serves the whole scope.
@@ -197,10 +266,20 @@ declare function createEmailBatchService<T extends TemplateMap>(options: EmailBa
197
266
  declare function createEmailAdmin(options: EmailAdminOptions): EmailAdmin;
198
267
 
199
268
  /**
200
- * Single-process V1 store for tests and development. State is lost on restart and is not shared across
269
+ * Single-process store for tests and development. State is lost on restart and is not shared across
201
270
  * instances or processes. Capacity is global across scopes; it never evicts a protected job or acts as
202
271
  * a fallback for another store. Uses the injected clock's wall time for store guards.
203
272
  */
204
273
  declare function createMemoryEmailStore(options?: MemoryEmailStoreOptions): EmailStore;
205
274
 
206
- export { type AdmissionResult, AttachmentRef, Awaitable, CallOptions, Correlation, EmailAdmin, EmailAdminOptions, EmailAdmissionKey, type EmailBatchItem, type EmailBatchResult, type EmailBatchService, type EmailBatchServiceOptions, EmailClock, type EmailCommand, EmailEnvelope, EmailError, type EmailErrorCode, EmailJobSummary, EmailRunOptions, EmailRunReport, EmailScope, type EmailService, type EmailServiceOptions, EmailStore, type EmailTemplateRegistry, EmailWorker, EmailWorkerOptions, JsonObject, JsonValue, type LocalSource, type LocalTemplate, type LocalTemplateConfig, MemoryEmailStoreOptions, type PrepareContext, PreparedEmailCommand, type PreparedFields, ProviderRef, RetentionPolicy, RetryPolicy, type SendGridTemplate, type SendGridTemplateConfig, type TemplateCommand, type TemplateDefinition, type TemplateDefinitions, type TemplateMap, type TemplateRegistryOptions, UnixMs, createEmailAdmin, createEmailBatchService, createEmailService, createEmailTemplateRegistry, createEmailWorker, createMemoryEmailStore, defineLocalTemplate, defineSendGridTemplate };
275
+ /**
276
+ * After SMTP's final DATA acknowledgement, build full or partial acceptance from recipient results.
277
+ * Copies and freezes the result, preserving input order. Throws `invalid_command` for an empty,
278
+ * all-rejected or malformed list, or a malformed optional `<${attemptId}@email.invalid>` message ID.
279
+ * The worker still checks coverage, queue bounds, any required order, and the actual attempt ID.
280
+ */
281
+ declare function createSmtpAcceptanceResult(recipients: readonly RecipientResult[], messageId?: string): Extract<ProviderResult, {
282
+ reason: 'smtp_accepted' | 'smtp_partial';
283
+ }>;
284
+
285
+ export { type AdmissionResult, AttachmentRef, Awaitable, CallOptions, Correlation, EmailAdmin, EmailAdminOptions, EmailAdmissionKey, type EmailBatchAdmission, type EmailBatchAdmissionOptions, type EmailBatchItem, type EmailBatchResult, type EmailBatchService, type EmailBatchServiceOptions, EmailClock, type EmailCommand, EmailEnvelope, EmailError, type EmailErrorCode, EmailJobSummary, type EmailRelay, type EmailRelayOptions, EmailRunOptions, EmailRunReport, EmailScope, type EmailService, type EmailServiceOptions, EmailStore, type EmailTemplateRegistry, EmailWorker, EmailWorkerOptions, JsonObject, JsonValue, type LocalSource, type LocalTemplate, type LocalTemplateConfig, MemoryEmailStoreOptions, type PrepareContext, PreparedEmailCommand, type PreparedFields, ProviderRef, ProviderResult, RecipientResult, RetentionPolicy, RetryPolicy, type SendGridTemplate, type SendGridTemplateConfig, SmtpCapacity, type TemplateCommand, type TemplateDefinition, type TemplateDefinitions, type TemplateMap, type TemplateRegistryOptions, UnixMs, createEmailAdmin, createEmailBatchAdmission, createEmailBatchService, createEmailRelay, createEmailService, createEmailTemplateRegistry, createEmailWorker, createMemoryEmailStore, createSmtpAcceptanceResult, defineLocalTemplate, defineSendGridTemplate };
package/index.d.ts CHANGED
@@ -1,11 +1,14 @@
1
- import { J as JsonObject, E as EmailEnvelope, a as EmailScope, b as EmailAdmissionKey, P as ProviderRef, U as UnixMs, A as Awaitable, c as AttachmentRef, C as Correlation, d as JsonValue, e as CallOptions, f as PreparedEmailCommand, g as EmailClock } from './provider-HisBc6hk.js';
2
- export { h as AttachmentResolution, i as AttachmentResolver, j as AttemptReason, k as AttemptResult, l as ConfiguredEmailProvider, m as EmailAttemptId, n as EmailJobId, o as EmailProvider, p as EmailSnapshot, M as Mailbox, q as PreparedEmailSubmission, r as ProviderCall, s as ProviderReason, t as ProviderResult, u as ProviderSubmission, R as RecipientResult, v as ResolvedAttachment, w as RetryClass, x as RetryHint, S as SendGridSnapshot, y as SmtpSnapshot, z as SubmissionOutcome, B as SubmissionStage, T as TemplateIdentity } from './provider-HisBc6hk.js';
3
- import { E as EmailJobSummary, a as EmailRunOptions, b as EmailRunReport, c as EmailWorker, d as EmailStore, R as RetryPolicy, e as RetentionPolicy, f as EmailWorkerOptions, g as EmailAdminOptions, h as EmailAdmin, M as MemoryEmailStoreOptions } from './store-Vb63Gocz.js';
4
- export { A as AttemptCommit, C as CancelResult, i as ClaimedEmail, j as CleanupReport, k as CleanupStep, l as EmailActivity, m as EmailActivityPage, n as EmailActivityQuery, o as EmailJobState, p as EmailRateLimiter, q as EmailRunEntry, r as EmailShutdownReport, s as EmailWorkerLimits, H as HandoffGrant, J as JobDisposition, L as LeaseGrant, t as LeaseToken, u as MaintenanceOptions, v as MaintenanceStop, O as OwnerFence, P as ProjectionPermit, w as ReconcileReport, x as ResolveUnknownCommand, y as ResolveUnknownResult, S as StoreAdmission, z as StoreCall, B as StoreNext, U as UnknownResolution } from './store-Vb63Gocz.js';
1
+ import { J as JsonObject, E as EmailEnvelope, a as EmailScope, b as EmailAdmissionKey, P as ProviderRef, U as UnixMs, A as Awaitable, c as AttachmentRef, C as Correlation, d as JsonValue, S as SmtpCapacity, e as CallOptions, f as PreparedEmailCommand, g as EmailClock, R as RecipientResult, h as ProviderResult } from './provider-CeUryYAf.js';
2
+ export { i as AttachmentResolution, j as AttachmentResolver, k as AttemptReason, l as AttemptResult, m as ConfiguredEmailProvider, n as EmailAttemptId, o as EmailJobId, p as EmailProvider, q as EmailSnapshot, M as Mailbox, r as PreparedEmailSubmission, s as ProviderCall, t as ProviderReason, u as ProviderSubmission, v as ResolvedAttachment, w as RetryClass, x as RetryHint, y as SendGridSnapshot, z as SmtpSnapshot, B as SubmissionOutcome, D as SubmissionStage, T as TemplateIdentity } from './provider-CeUryYAf.js';
3
+ import { E as EmailJobSummary, a as EmailRunOptions, b as EmailRunReport, c as EmailWorker, d as EmailStore, R as RetryPolicy, e as RetentionPolicy, f as EmailWorkerOptions, g as EmailAdminOptions, h as EmailAdmin, M as MemoryEmailStoreOptions } from './store-CFasgH3C.js';
4
+ export { A as AttemptCommit, C as CancelResult, i as ClaimedEmail, j as CleanupReport, k as CleanupStep, l as EmailActivity, m as EmailActivityPage, n as EmailActivityQuery, o as EmailJobState, p as EmailRateLimiter, q as EmailRunEntry, r as EmailShutdownReport, s as EmailWorkerLimits, H as HandoffGrant, J as JobDisposition, L as LeaseGrant, t as LeaseToken, u as MaintenanceOptions, v as MaintenanceStop, O as OwnerFence, P as ProjectionPermit, w as ReconcileReport, x as ResolveUnknownCommand, y as ResolveUnknownResult, S as StoreAdmission, z as StoreCall, B as StoreClaimNext, D as StoreNext, U as UnknownResolution } from './store-CFasgH3C.js';
5
5
 
6
6
  /** Safe, stable diagnostics; no application data or transport-response text. */
7
7
  type EmailErrorCode = 'invalid_config' | 'invalid_command' | 'invalid_input' | 'invalid_data' | 'invalid_snapshot' | 'preparation_failed' | 'template_not_found' | 'template_source' | 'template_render' | 'provider_mismatch' | 'expired' | 'idempotency_conflict' | 'not_found' | 'resolution_conflict' | 'store_capacity' | 'store_unavailable' | 'store_incompatible' | 'write_unconfirmed' | 'invalid_cursor' | 'aborted' | 'deadline' | 'busy' | 'closed';
8
- /** Compare `.code`, not class identity, across separately loaded ESM and CommonJS builds. */
8
+ /**
9
+ * Narrow a caught `unknown` to a known `.code`, not class identity. Independently bundled
10
+ * entrypoints can throw different classes even within one format (all ESM or all CommonJS).
11
+ */
9
12
  declare class EmailError extends Error {
10
13
  /** `write_unconfirmed` does not mean that a dispatched mutation failed to commit. */
11
14
  readonly code: EmailErrorCode;
@@ -23,6 +26,10 @@ type PrepareContext = {
23
26
  /** Host-generated fields. Only From and Reply-To can come from template defaults. */
24
27
  type PreparedFields<D extends JsonObject> = Partial<EmailEnvelope> & {
25
28
  values: D;
29
+ /**
30
+ * Unix ms; defaults to 24 hours from preparation. Must be strictly after preparation and
31
+ * `scheduleAt` (if given), and at most 30 days from preparation. Frozen in the snapshot.
32
+ */
26
33
  expiresAt?: UnixMs;
27
34
  priority?: number;
28
35
  attachments?: readonly AttachmentRef[];
@@ -44,7 +51,10 @@ type LocalSource = {
44
51
  type TemplateDefinition<I, D extends JsonObject> = {
45
52
  revision: string;
46
53
  defaults?: Pick<Partial<EmailEnvelope>, 'from' | 'replyTo'>;
47
- /** Synchronously validate the host's opaque business input. */
54
+ /**
55
+ * Validate the command's declared input shape synchronously at runtime.
56
+ * The return type defines what callers supply as `command.input`; normalize message values in `prepare`.
57
+ */
48
58
  parseInput: (input: unknown) => I;
49
59
  /** Synchronously validate or normalize a detached JSON object. Return a new object to change it. */
50
60
  parseData: (data: unknown) => D;
@@ -73,15 +83,26 @@ type TemplateMap = Readonly<Record<string, Omit<TemplateDefinition<never, JsonOb
73
83
  type TemplateDefinitions<T extends TemplateMap> = T & {
74
84
  [K in keyof T]: TemplateDefinition<ReturnType<T[K]['parseInput']>, ReturnType<T[K]['parseData']>>;
75
85
  };
76
- /** The key determines the input and provider kind. `intent` describes stable business meaning, not rendered data. */
86
+ type ProviderByTemplateKind = {
87
+ handlebars: Extract<ProviderRef, {
88
+ kind: 'smtp';
89
+ }>;
90
+ sendgrid: Extract<ProviderRef, {
91
+ kind: 'sendgrid';
92
+ }>;
93
+ };
94
+ /**
95
+ * The template key determines input and provider kind. A widened `TemplateMap` allows either provider.
96
+ * `intent` describes stable business meaning, not rendered data.
97
+ * Keep `scheduleAt` stable on replay; schedules past the default 24-hour expiry need explicit `expiresAt` in `prepare`.
98
+ */
77
99
  type TemplateCommand<T extends TemplateMap> = {
78
100
  [K in keyof T & string]: {
79
101
  templateKey: K;
80
102
  input: ReturnType<T[K]['parseInput']>;
81
- provider: Extract<ProviderRef, {
82
- kind: T[K]['kind'] extends 'handlebars' ? 'smtp' : 'sendgrid';
83
- }>;
103
+ provider: ProviderByTemplateKind[T[K]['kind']];
84
104
  intent: JsonValue;
105
+ /** Earliest eligible time (Unix ms), not a timer. Must precede the snapshot expiry. */
85
106
  scheduleAt?: UnixMs;
86
107
  };
87
108
  }[keyof T & string];
@@ -90,6 +111,8 @@ type EmailCommand<T extends TemplateMap> = TemplateCommand<T> & {
90
111
  key: EmailAdmissionKey;
91
112
  };
92
113
  type TemplateRegistryOptions = {
114
+ /** Prepare only local SMTP messages under this binding. Use the same tuple for their admission. */
115
+ smtpCapacity?: SmtpCapacity;
93
116
  clock?: EmailClock;
94
117
  cacheEntries?: number;
95
118
  maxPending?: number;
@@ -97,7 +120,11 @@ type TemplateRegistryOptions = {
97
120
  helpers?: Readonly<Record<string, (...args: unknown[]) => unknown>>;
98
121
  };
99
122
  interface EmailTemplateRegistry<T extends TemplateMap> {
100
- /** Prepare a detached snapshot without using a queue or contacting a provider. */
123
+ readonly smtpCapacity?: SmtpCapacity;
124
+ /**
125
+ * Prepare a detached snapshot without using a queue or contacting a provider.
126
+ * SMTP `message/*` and `multipart/*` attachment refs fail with `invalid_snapshot`.
127
+ */
101
128
  prepare(scope: EmailScope, command: EmailCommand<T>, options?: CallOptions): Promise<PreparedEmailCommand>;
102
129
  /** Evict one or all compilation cache entries and fence their prior in-flight loads. */
103
130
  invalidate(templateKey?: keyof T & string): void;
@@ -114,15 +141,34 @@ type AdmissionResult = {
114
141
  readonly status: 'enqueued' | 'replayed';
115
142
  readonly job: EmailJobSummary;
116
143
  };
117
- interface EmailService<T extends TemplateMap> {
144
+ /** Prepared-only admission. The relay does not need a template registry or delivery configuration. */
145
+ interface EmailRelay {
146
+ /**
147
+ * Relay the same scoped outbox snapshot unchanged. Does not join a host transaction, rerender, or extend expiry.
148
+ * A retained match replays; on a new admission SMTP `message/*` and `multipart/*` refs fail with `invalid_snapshot`.
149
+ */
150
+ enqueuePrepared(command: PreparedEmailCommand, options?: CallOptions): Promise<AdmissionResult>;
151
+ }
152
+ type EmailRelayOptions = {
153
+ /** The original scope of the staged command. */
154
+ scope: EmailScope;
155
+ /** Pass the exact store binding explicitly when relaying to an opted-in queue. */
156
+ smtpCapacity?: SmtpCapacity;
157
+ /** Admission primitives only. Ready the underlying store before use. */
158
+ store: Pick<EmailStore, 'smtpCapacity' | 'findAdmission' | 'insert'>;
159
+ retry?: Partial<RetryPolicy>;
160
+ retention?: Partial<RetentionPolicy>;
161
+ };
162
+ interface EmailService<T extends TemplateMap> extends EmailRelay {
118
163
  readonly scope: EmailScope;
164
+ readonly smtpCapacity?: SmtpCapacity;
119
165
  /** Admit or replay by scoped stable intent; a committed replay does not prepare again. */
120
166
  enqueue(command: EmailCommand<T>, options?: CallOptions): Promise<AdmissionResult>;
121
- /** Relay the same scoped outbox snapshot unchanged. Does not join a host transaction, rerender, or extend expiry. */
122
- enqueuePrepared(command: PreparedEmailCommand, options?: CallOptions): Promise<AdmissionResult>;
123
167
  }
124
168
  type EmailServiceOptions<T extends TemplateMap> = {
125
169
  scope: EmailScope;
170
+ /** Must match the registry and store. Relay staged commands only through their original binding. */
171
+ smtpCapacity?: SmtpCapacity;
126
172
  store: EmailStore;
127
173
  registry: EmailTemplateRegistry<T>;
128
174
  retry?: Partial<RetryPolicy>;
@@ -152,7 +198,8 @@ type EmailBatchResult = {
152
198
  readonly persistenceFailures: number;
153
199
  };
154
200
  };
155
- interface EmailBatchService<T extends TemplateMap> {
201
+ /** Producer-only batch admission; no worker or delivery methods. */
202
+ interface EmailBatchAdmission<T extends TemplateMap> {
156
203
  /**
157
204
  * Validate 1–100 items up front, then admit them in input order under one timeout (default 30 seconds).
158
205
  * Replay the same batch/item IDs and intent to resume; earlier writes aren't rolled back on a failure.
@@ -161,15 +208,30 @@ interface EmailBatchService<T extends TemplateMap> {
161
208
  batchId: string;
162
209
  items: readonly EmailBatchItem<T>[];
163
210
  }, options?: CallOptions): Promise<EmailBatchResult>;
211
+ }
212
+ type EmailBatchAdmissionOptions<T extends TemplateMap> = {
213
+ /** Bound admission service or wrapper. A wrapper must honor the call's signal and timeout. */
214
+ service: Pick<EmailService<T>, 'scope' | 'smtpCapacity' | 'enqueue'>;
215
+ /** Pass the exact tuple explicitly when the service is opted in. */
216
+ smtpCapacity?: SmtpCapacity;
217
+ };
218
+ interface EmailBatchService<T extends TemplateMap> extends EmailBatchAdmission<T> {
164
219
  /** Run the same scope-wide worker, not a second delivery loop or a batch filter. */
165
220
  run(options?: EmailRunOptions): Promise<EmailRunReport>;
166
221
  }
167
222
  type EmailBatchServiceOptions<T extends TemplateMap> = {
168
- /** Must share the worker's scope and underlying store. */
223
+ /** Must share the worker's scope, underlying store and SMTP capacity binding, if enabled. */
169
224
  service: EmailService<T>;
170
225
  worker: EmailWorker;
226
+ /** Pass the exact tuple explicitly when the service and worker are opted in. */
227
+ smtpCapacity?: SmtpCapacity;
171
228
  };
172
229
 
230
+ /**
231
+ * Admit a staged outbox snapshot without a registry. Ready the underlying queue store first.
232
+ * After `write_unconfirmed`, relay the same staged command under its original scope and binding.
233
+ */
234
+ declare function createEmailRelay(options: EmailRelayOptions): EmailRelay;
173
235
  /**
174
236
  * Scope-bound admission only. Call `store.ready()` yourself; neither method contacts a mail provider.
175
237
  * After `write_unconfirmed`, retry the same scoped key and intent: the original insert may have committed.
@@ -180,9 +242,16 @@ declare function createEmailService<T extends TemplateMap>(options: EmailService
180
242
  * Create a scope-bound worker for a caller-ready store and exact provider profiles. The host schedules
181
243
  * bounded `run` calls; nothing polls on construction. `shutdown` is permanent and never closes the store.
182
244
  * A one-shot provider call requires a timely durable handoff acknowledgement, not a later read of a marker.
245
+ * An empty provider array throws `invalid_config` before any work. For enqueue-only batches,
246
+ * use `createEmailBatchAdmission({ service })` instead of constructing a worker.
183
247
  */
184
248
  declare function createEmailWorker(options: EmailWorkerOptions): EmailWorker;
185
249
 
250
+ /**
251
+ * Enqueue or resume a batch through a bound service without configuring a worker.
252
+ * Replay the same batch/item IDs and intent after `write_unconfirmed`: an item may already have committed.
253
+ */
254
+ declare function createEmailBatchAdmission<T extends TemplateMap>(options: EmailBatchAdmissionOptions<T>): EmailBatchAdmission<T>;
186
255
  /**
187
256
  * Compose a same-scope admission service and worker. Wire both to the same underlying store.
188
257
  * Enqueue is sequential and resumable by batch/item ID, not atomic. `run` serves the whole scope.
@@ -197,10 +266,20 @@ declare function createEmailBatchService<T extends TemplateMap>(options: EmailBa
197
266
  declare function createEmailAdmin(options: EmailAdminOptions): EmailAdmin;
198
267
 
199
268
  /**
200
- * Single-process V1 store for tests and development. State is lost on restart and is not shared across
269
+ * Single-process store for tests and development. State is lost on restart and is not shared across
201
270
  * instances or processes. Capacity is global across scopes; it never evicts a protected job or acts as
202
271
  * a fallback for another store. Uses the injected clock's wall time for store guards.
203
272
  */
204
273
  declare function createMemoryEmailStore(options?: MemoryEmailStoreOptions): EmailStore;
205
274
 
206
- export { type AdmissionResult, AttachmentRef, Awaitable, CallOptions, Correlation, EmailAdmin, EmailAdminOptions, EmailAdmissionKey, type EmailBatchItem, type EmailBatchResult, type EmailBatchService, type EmailBatchServiceOptions, EmailClock, type EmailCommand, EmailEnvelope, EmailError, type EmailErrorCode, EmailJobSummary, EmailRunOptions, EmailRunReport, EmailScope, type EmailService, type EmailServiceOptions, EmailStore, type EmailTemplateRegistry, EmailWorker, EmailWorkerOptions, JsonObject, JsonValue, type LocalSource, type LocalTemplate, type LocalTemplateConfig, MemoryEmailStoreOptions, type PrepareContext, PreparedEmailCommand, type PreparedFields, ProviderRef, RetentionPolicy, RetryPolicy, type SendGridTemplate, type SendGridTemplateConfig, type TemplateCommand, type TemplateDefinition, type TemplateDefinitions, type TemplateMap, type TemplateRegistryOptions, UnixMs, createEmailAdmin, createEmailBatchService, createEmailService, createEmailTemplateRegistry, createEmailWorker, createMemoryEmailStore, defineLocalTemplate, defineSendGridTemplate };
275
+ /**
276
+ * After SMTP's final DATA acknowledgement, build full or partial acceptance from recipient results.
277
+ * Copies and freezes the result, preserving input order. Throws `invalid_command` for an empty,
278
+ * all-rejected or malformed list, or a malformed optional `<${attemptId}@email.invalid>` message ID.
279
+ * The worker still checks coverage, queue bounds, any required order, and the actual attempt ID.
280
+ */
281
+ declare function createSmtpAcceptanceResult(recipients: readonly RecipientResult[], messageId?: string): Extract<ProviderResult, {
282
+ reason: 'smtp_accepted' | 'smtp_partial';
283
+ }>;
284
+
285
+ export { type AdmissionResult, AttachmentRef, Awaitable, CallOptions, Correlation, EmailAdmin, EmailAdminOptions, EmailAdmissionKey, type EmailBatchAdmission, type EmailBatchAdmissionOptions, type EmailBatchItem, type EmailBatchResult, type EmailBatchService, type EmailBatchServiceOptions, EmailClock, type EmailCommand, EmailEnvelope, EmailError, type EmailErrorCode, EmailJobSummary, type EmailRelay, type EmailRelayOptions, EmailRunOptions, EmailRunReport, EmailScope, type EmailService, type EmailServiceOptions, EmailStore, type EmailTemplateRegistry, EmailWorker, EmailWorkerOptions, JsonObject, JsonValue, type LocalSource, type LocalTemplate, type LocalTemplateConfig, MemoryEmailStoreOptions, type PrepareContext, PreparedEmailCommand, type PreparedFields, ProviderRef, ProviderResult, RecipientResult, RetentionPolicy, RetryPolicy, type SendGridTemplate, type SendGridTemplateConfig, SmtpCapacity, type TemplateCommand, type TemplateDefinition, type TemplateDefinitions, type TemplateMap, type TemplateRegistryOptions, UnixMs, createEmailAdmin, createEmailBatchAdmission, createEmailBatchService, createEmailRelay, createEmailService, createEmailTemplateRegistry, createEmailWorker, createMemoryEmailStore, createSmtpAcceptanceResult, defineLocalTemplate, defineSendGridTemplate };