@web-ts-toolkit/email-service 0.0.0-stage → 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/README.md CHANGED
@@ -1,3 +1,585 @@
1
- # Temporary Holding Version
1
+ # `@web-ts-toolkit/email-service`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Typed email preparation, queue admission and bounded submission for Node.js 24 or later. Prepare local Handlebars
4
+ content for SMTP or validate SendGrid dynamic-template data. Preparation alone does not enqueue, and admission never
5
+ sends mail.
6
+
7
+ ## Imports
8
+
9
+ Install with `pnpm add @web-ts-toolkit/email-service`. Use named imports (or destructure `require()` in CommonJS).
10
+ There is no default export. Preparation, admission, and the memory store need neither optional peer.
11
+
12
+ <!-- example: errors -->
13
+
14
+ ```typescript
15
+ import { EmailError, type EmailErrorCode } from '@web-ts-toolkit/email-service';
16
+
17
+ const error = new EmailError('write_unconfirmed');
18
+ const code: EmailErrorCode = error.code;
19
+ // An unconfirmed write may have committed. Do not treat it as a definite failure.
20
+ console.log(code);
21
+ ```
22
+
23
+ Compare `.code`, not class identity, if your application loads both builds.
24
+ `PreparedEmailCommand` describes the sensitive, versioned outbox payload. Treat it like queue data, not a log record.
25
+
26
+ ## Prepare a local template
27
+
28
+ Render an SMTP snapshot without Nodemailer, a store, or a network connection:
29
+
30
+ <!-- example: local -->
31
+
32
+ ```typescript
33
+ import { createEmailTemplateRegistry, defineLocalTemplate } from '@web-ts-toolkit/email-service';
34
+
35
+ const welcome = defineLocalTemplate({
36
+ kind: 'handlebars',
37
+ revision: 'v1',
38
+ defaults: { from: { address: 'sender@example.invalid' } },
39
+ subject: { kind: 'inline', content: 'Welcome, {{name}}' },
40
+ html: { kind: 'inline', content: '<p>Welcome, {{name}}.</p>' },
41
+ parseInput(input) {
42
+ if (typeof input !== 'string' || !input.trim()) throw new Error('Expected a name');
43
+ return input;
44
+ },
45
+ prepare(name) {
46
+ return { to: [{ address: 'recipient@example.invalid' }], values: { name } };
47
+ },
48
+ parseData(data) {
49
+ if (!data || typeof data !== 'object' || !('name' in data) || typeof data.name !== 'string') {
50
+ throw new Error('Expected a name');
51
+ }
52
+ return { name: data.name };
53
+ },
54
+ });
55
+
56
+ const registry = createEmailTemplateRegistry({ welcome });
57
+ const welcomeCommand = {
58
+ templateKey: 'welcome',
59
+ input: '<Example>',
60
+ intent: { name: '<Example>' },
61
+ key: { kind: 'single', idempotencyKey: 'welcome-1' },
62
+ provider: { kind: 'smtp', key: 'standard-smtp', mode: 'live' },
63
+ } as const;
64
+ const prepared = await registry.prepare('example-app', welcomeCommand);
65
+ ```
66
+
67
+ The snapshot has a plain-text subject and escaped HTML. `prepare` does not admit a job.
68
+
69
+ Keep `parseInput` and `parseData` synchronous. Preparation can be async and may run again after a crash; keep
70
+ side effects idempotent. `intent` is explicit, stable business meaning, not the generated message. Configure only
71
+ trusted sources and helpers. HTML values escape by default; this is not sanitization. To update advertised local
72
+ content, change its revision and create a new registry; `registry.invalidate(key?)` only refreshes the local cache.
73
+
74
+ ## Prepare a SendGrid dynamic template
75
+
76
+ Register a template you already manage in SendGrid. For this example the input is a positive integer and the
77
+ template expects `{ hours: number }`. Neither registration nor preparation requires credentials.
78
+
79
+ <!-- example: sendgrid-template -->
80
+
81
+ ```typescript
82
+ import { createEmailTemplateRegistry, defineSendGridTemplate } from '@web-ts-toolkit/email-service';
83
+
84
+ function requireHours(value: unknown): number {
85
+ if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 1) throw new Error('Expected hours');
86
+ return value;
87
+ }
88
+
89
+ const reminder = defineSendGridTemplate<number, { hours: number }>({
90
+ kind: 'sendgrid',
91
+ revision: 'v1',
92
+ templateId: 'd-0123456789abcdeffedcba9876543210', // Synthetic ID; replace for your application.
93
+ defaults: { from: { address: 'sender@example.invalid' } },
94
+ parseInput: requireHours,
95
+ prepare(hours) {
96
+ return { to: [{ address: 'recipient@example.invalid' }], values: { hours } };
97
+ },
98
+ parseData(data) {
99
+ if (!data || typeof data !== 'object' || !('hours' in data)) throw new Error('Expected hours');
100
+ return { hours: requireHours(data.hours) };
101
+ },
102
+ });
103
+
104
+ const sendGridRegistry = createEmailTemplateRegistry({ reminder });
105
+ const stagedReminder = await sendGridRegistry.prepare('example-app', {
106
+ templateKey: 'reminder',
107
+ input: 2,
108
+ intent: { hours: 2 },
109
+ key: { kind: 'single', idempotencyKey: 'reminder-1' },
110
+ provider: { kind: 'sendgrid', key: 'validation', mode: 'sandbox' },
111
+ });
112
+ ```
113
+
114
+ The command needs a `sendgrid` provider ref (`live` or `sandbox`) and the prepared envelope needs at least one To
115
+ recipient. Preparation freezes the template ID and dynamic data, not SendGrid's active remote version.
116
+
117
+ ## Enqueue or relay a job
118
+
119
+ Using `registry` and `welcomeCommand` from the local-template example:
120
+
121
+ <!-- example: admission -->
122
+
123
+ ```typescript
124
+ import { createEmailService, createMemoryEmailStore } from '@web-ts-toolkit/email-service';
125
+
126
+ const store = createMemoryEmailStore(); // Non-durable; use the Mongoose store for persistence.
127
+ await store.ready();
128
+ const service = createEmailService({ scope: 'example-app', store, registry });
129
+ const first = await service.enqueue(welcomeCommand); // enqueued; nothing sent
130
+ const again = await service.enqueue(welcomeCommand); // replayed; no preparation
131
+ console.log(first.job.jobId === again.job.jobId); // true
132
+ ```
133
+
134
+ - The service is bound to one scope; your application must authorize access. `intent` must describe every stable
135
+ business difference that matters. A committed job with the same key and fingerprint returns its current summary
136
+ without looking up the template, even after completion or payload expiry/pruning. Reusing the key for different
137
+ intent fails with `idempotency_conflict`. Deduplication ends when the stored identity guard is purged.
138
+ - Simultaneous first calls can both prepare, but only the unique committed job wins. If admission returns
139
+ `write_unconfirmed`, retry with the **same scope, key and intent** (or the same staged snapshot). The job may already
140
+ exist; a missing acknowledgement does not prove rollback. Do not generate a new key to retry the same command.
141
+ - Both methods accept `{ signal?, timeoutMs? }` (default 10 seconds, override 50–60,000 ms). Lookup, preparation,
142
+ insert and any confirmation share that budget. `retry` and `retention` are optional policy overrides frozen on the
143
+ first insert; replay does not change them. Never put personal data or secrets into IDs or correlation tokens.
144
+
145
+ ### Stage a host-owned outbox
146
+
147
+ Prepare before the business write. Pass `stagedReminder` from the SendGrid example as `email`. Your `commit`
148
+ implementation saves the business change and the versioned, sensitive `email` value in **one host transaction**.
149
+ Only after commit does your relay read that value and enqueue it on the caller-ready queue store:
150
+
151
+ <!-- example: outbox -->
152
+
153
+ ```typescript
154
+ import {
155
+ createEmailService,
156
+ createEmailTemplateRegistry,
157
+ type EmailStore,
158
+ type PreparedEmailCommand,
159
+ } from '@web-ts-toolkit/email-service';
160
+
161
+ type CommitReminder = (row: { reminderId: string; email: PreparedEmailCommand }) => Promise<void>;
162
+
163
+ async function writeReminder(reminderId: string, email: PreparedEmailCommand, commit: CommitReminder) {
164
+ await commit({ reminderId, email });
165
+ }
166
+
167
+ function relayReminder(store: EmailStore, email: PreparedEmailCommand) {
168
+ const relay = createEmailService({ scope: 'example-app', store, registry: createEmailTemplateRegistry({}) });
169
+ return relay.enqueuePrepared(email);
170
+ }
171
+ ```
172
+
173
+ Relay validates the staged DTO, its hashes, and its scope. It does not join your transaction, rerender, refresh expiry,
174
+ or send. Mark your outbox row relayed only after `enqueued` or `replayed`. If an acknowledgement is lost, relay the
175
+ same persisted snapshot under the same scoped key and queue configuration; do not prepare a replacement. Keep the
176
+ relay within the idempotency window. Restrict access to the staged payload; the returned job summary contains
177
+ neither bodies nor addresses.
178
+
179
+ ## Configure an SMTP profile
180
+
181
+ Install `nodemailer@">=10.6.0 <11"` to import the SMTP runtime entry. Its profile `key` must match the prepared snapshot.
182
+ The default is 50 total To/Cc/Bcc recipients; see [SMTP capacity opt-in](#opt-in-to-larger-smtp-envelopes) for a separate
183
+ queue that can admit larger envelopes.
184
+
185
+ <!-- example: smtp-profile -->
186
+
187
+ ```typescript
188
+ import { createSmtpProvider } from '@web-ts-toolkit/email-service/smtp';
189
+
190
+ const smtp = createSmtpProvider({
191
+ key: 'standard-smtp',
192
+ host: 'smtp.example.invalid',
193
+ tls: 'starttls',
194
+ });
195
+ ```
196
+
197
+ - `starttls` (default port 587) requires a successful TLS upgrade; `implicit` (465) starts with TLS. Both require TLS 1.2+
198
+ and verify the certificate against `servername` (if specified) or `host`, including IP SAN verification for literal
199
+ IPs. `ca` accepts one PEM CA certificate per array entry and replaces Node's default trust roots. `auth: { user, pass }`
200
+ uses advertised ESMTP PLAIN or LOGIN only over verified TLS; there is no plaintext fallback.
201
+ - Use an ASCII DNS host or a literal IP. The adapter uses a cancellable DNS resolver (not OS hosts-file aliases) and
202
+ dials one address. It does not pool, retry or select another server after a failure.
203
+ - `prepare` validates and copies the snapshot and attachment bytes without network I/O. SMTP sends visible To/Cc,
204
+ envelope-only Bcc and no implicit path or URL inputs. Attachments are ordinary MIME leaf parts, not nested message
205
+ or multipart MIME structures.
206
+ - `submit({ signal, timeoutMs })` consumes the prepared submission on a valid call. It closes its connection on abort
207
+ or timeout and never waits indefinitely for a peer. Neither closing the connection nor an `unknown` result means
208
+ the relay discarded the message. `accepted` and `partially_accepted` require a final DATA acknowledgement and mean
209
+ SMTP submission, not inbox delivery. Result diagnostics are fixed codes and recipient indexes, not addresses or raw
210
+ replies. Direct submission is unmanaged and does not provide durable queue or retry guarantees.
211
+
212
+ ## Configure a SendGrid profile
213
+
214
+ No SendGrid SDK or peer is required. Supply an explicit Mail Send key from your host's secret configuration.
215
+ Use the profile's `ref` in a command for a template registered with `defineSendGridTemplate`.
216
+
217
+ <!-- example: sendgrid-profile -->
218
+
219
+ ```typescript
220
+ import { createSendGridProvider } from '@web-ts-toolkit/email-service/sendgrid';
221
+
222
+ function validationProfile(apiKey: string) {
223
+ return createSendGridProvider({ key: 'validation', apiKey, mode: 'sandbox' });
224
+ }
225
+ ```
226
+
227
+ - `mode` defaults to `'live'`. `'sandbox'` only validates a request; keep it distinct from a live profile. The
228
+ prepared snapshot's provider kind, key and mode must match. `prepare` does no network I/O and maps the
229
+ frozen envelope, dynamic data and verified attachment bytes to a single personalization with the requested
230
+ template ID. This entrypoint does not manage templates or pin their active SendGrid versions.
231
+ - `submit({ signal, timeoutMs })` makes at most one POST to `https://api.sendgrid.com/v3/mail/send` over
232
+ verified TLS 1.2+. No endpoint override, redirects, implicit retries or connection sharing. The JSON body is
233
+ capped at 8 MiB and the complete HTTP response at 64 KiB. Abort or deadline closes the connection; it cannot
234
+ recall a request SendGrid may already have accepted.
235
+ - Complete live `202` means `accepted` and may include one sanitized `providerMessageId`. Complete sandbox `200`
236
+ means `validated`, not `accepted`. Neither outcome reports inbox delivery or per-recipient status. A complete
237
+ `429` reports throttled rejection and may carry a retry floor; `400`, `401`, `403`, `404`, `405` and `413` are
238
+ permanent rejections. Other statuses (including `5xx`), incomplete or invalid HTTP, and uncertain transport
239
+ failures do not authorize a retry. The adapter never schedules a retry. Direct submissions are unmanaged and
240
+ provide no durable queue guarantees. Keep raw HTTP tracing off around credentials and message data.
241
+
242
+ ## In-process store for tests and development
243
+
244
+ <!-- example: memory -->
245
+
246
+ ```typescript
247
+ import { createMemoryEmailStore } from '@web-ts-toolkit/email-service';
248
+
249
+ const memoryStore = createMemoryEmailStore({ maxJobs: 32 });
250
+ await memoryStore.ready();
251
+ ```
252
+
253
+ Share the same instance to exercise competing callers. Each instance loses its state on restart and does not share
254
+ state across processes. The V1 job limit (default 256) is shared across scopes; a full store rejects new jobs instead of
255
+ evicting retained ones. This is not a fallback for durable persistence. The `EmailStore` methods are private lifecycle
256
+ primitives for adapters and tests, not application-facing routes. Claims include sensitive snapshots and ownership
257
+ tokens; do not log or expose them. Store operations alone never contact a provider.
258
+
259
+ ## Run a worker
260
+
261
+ Bind a caller-ready store to the same scope as the admission service. Pass the configured provider instances, not
262
+ credentials in a queue payload. The profile's key, kind and mode must match the frozen snapshot.
263
+
264
+ <!-- example: worker -->
265
+
266
+ ```typescript
267
+ import {
268
+ createEmailWorker,
269
+ type ConfiguredEmailProvider,
270
+ type EmailStore,
271
+ type EmailWorker,
272
+ } from '@web-ts-toolkit/email-service';
273
+
274
+ function makeWorker(store: EmailStore, profiles: readonly ConfiguredEmailProvider[]) {
275
+ return createEmailWorker({ scope: 'example-app', store, providers: profiles });
276
+ }
277
+
278
+ function runDue(worker: EmailWorker, signal: AbortSignal) {
279
+ return worker.run({ limit: 20, concurrency: 4, maintenanceLimit: 10, signal });
280
+ }
281
+ ```
282
+
283
+ - Your host calls `await runDue(worker, signal)` to do a bounded run.
284
+ Those are the V1 default work limits; set lower limits when appropriate. `timeoutMs` defaults to 30 seconds for the
285
+ whole run, with a separate bounded finish grace. There is no polling or automatic connection management.
286
+ One run per instance is allowed. Different instances can share a queue. `idle` is not a whole-queue inventory.
287
+ - The worker prepares the provider payload, validates attachment bytes through your `attachmentResolvers`, and asks
288
+ the optional `rateLimiter` for one permit before making a durable handoff. A worker limiter should be instantiated
289
+ per worker; a shared limiter must enforce the actual shared quota outside the worker. The worker does not wait for
290
+ a deferred permit, refund permits, rerender snapshots, or choose an alternate profile.
291
+ - A missing or late handoff acknowledgement never permits a send. A finish write error is not evidence of rejection.
292
+ `unconfirmed` means the worker could not prove the stored attempt outcome; `unknown` is a stored result that is
293
+ never automatically retried. `submitted` counts full and partial acceptance, not sandbox validation or inbox
294
+ delivery. An application that explicitly redrives unknown work must accept possible duplicates.
295
+ - `await worker.shutdown({ timeoutMs: 15_000 })` permanently closes the worker, not the store. `stopped` means no
296
+ run or provider I/O is active; `pendingCallbacks` counts host promises still held after cancellation. Injected
297
+ stores and providers must honor call deadlines, abort actual I/O and wait for it to settle. A timed-out shutdown
298
+ can be awaited again, and it does not recall bytes already sent.
299
+
300
+ ## Enqueue and resume a batch
301
+
302
+ Use `createEmailBatchService` with a service and worker bound to the **same scope and underlying store**.
303
+ Each item is a template command without a standalone `key`. Using `welcomeCommand`, `service`, `store`, `smtp`
304
+ and `makeWorker` from the preceding examples:
305
+
306
+ <!-- example: batch -->
307
+
308
+ ```typescript
309
+ import { createEmailBatchService } from '@web-ts-toolkit/email-service';
310
+
311
+ const { key: _singleKey, ...command } = welcomeCommand;
312
+ const worker = makeWorker(store, [smtp]);
313
+ const batch = createEmailBatchService({ service, worker });
314
+ const request = { batchId: 'welcome-run-1', items: [{ itemId: 'notice-1', command }] };
315
+ const admission = await batch.enqueueBatch(request);
316
+ const resumed = await batch.enqueueBatch(request); // Same item identity; replays without preparing again.
317
+ // When the host is ready to process due jobs, call batch.run({ limit: 10, concurrency: 2 }).
318
+ ```
319
+
320
+ - An enqueue call validates all 1–100 item envelopes and unique IDs before any lookup or preparation. It admits in
321
+ order under one `timeoutMs` (default 30 seconds, override 50–120,000 ms) and optional `signal`. Business input
322
+ is still parsed by the template on a miss; hold it stable until the call settles.
323
+ - Items can be `enqueued`, `replayed`, `failed` with a safe code, or `not_started` after abort or deadline. Earlier
324
+ writes aren't rolled back. Use the **same batch ID, item IDs and intents** to resume even in a different order;
325
+ `write_unconfirmed` may have committed. A committed match returns its current summary without preparing or
326
+ rendering again. Changing intent under the same ID reports `idempotency_conflict`; replay does not reopen
327
+ completed jobs. The counts distinguish failed items from the subset with a persistence error.
328
+ - With a wrapped service or one from another build (such as mixing ESM and CommonJS), the batch calls its public
329
+ `enqueue`. It passes the remaining time within that API's 50–60,000 ms range and a signal that can stop work
330
+ sooner. The batch waits for a started item to settle rather than assuming a write was cancelled. A custom
331
+ service must honor these limits and settle its I/O; one that does not cooperate can keep the batch pending.
332
+ - `batch.run` is the configured worker's **scope-wide** run, with the same bounds, limiter and report. It can
333
+ process unrelated due jobs in that scope. It neither filters by batch ID nor rewrites envelopes; the local
334
+ grouping ID is not SendGrid's `batch_id`.
335
+ - Call `worker.shutdown()` to stop delivery runs. This does not stop `enqueueBatch`; pass its own `signal` to
336
+ cancel admission. Supply a trusted worker: `batch.run` forwards its report and errors unchanged, so a custom
337
+ worker is responsible for redacting them and actually stopping its I/O.
338
+
339
+ ## Inspect results and maintain history
340
+
341
+ Supply the caller-ready store and an admitted `jobId` (for example, `first.job.jobId`). Bind the admin to the same scope:
342
+
343
+ <!-- example: results -->
344
+
345
+ ```typescript
346
+ import { createEmailAdmin, type EmailStore } from '@web-ts-toolkit/email-service';
347
+
348
+ async function inspectResults(store: EmailStore, jobId: string) {
349
+ const admin = createEmailAdmin({ scope: 'example-app', store });
350
+ const job = await admin.getJob(jobId); // Latest authoritative outcome, even before projection.
351
+ const projected = await admin.reconcile({ limit: 20 }); // Schedule this and cleanup separately from delivery.
352
+ const page = await admin.listActivities({ jobId, limit: 10 });
353
+ const next = page.nextCursor ? await admin.listActivities({ jobId, limit: 10, cursor: page.nextCursor }) : undefined;
354
+ const cleaned = await admin.cleanup({ limit: 20 });
355
+ return { job, projected, page, next, cleaned };
356
+ }
357
+ ```
358
+
359
+ - Authorize requests in your application; a scope or cursor is not authentication. Results contain only redacted
360
+ metadata, fixed diagnostic codes, and reliably known recipient indexes, never queue snapshots, addresses, provider
361
+ responses or ownership tokens. Activities are submission history, not inbox delivery receipts or inputs to a resend.
362
+ - Lists contain complete committed projections, including those pending acknowledgement on the job. They order
363
+ newest finish first, then by job and attempt ID. `from` is inclusive; `before` is exclusive. Keep the same scope
364
+ and filters when passing `nextCursor`; page size can change (V1 default 25, range 1–100). Pages are not snapshots.
365
+ - `reconcile` and `cleanup` do sequential work (V1 default 20 steps, range 1–100); their counts describe only
366
+ confirmed progress in that call. All admin methods accept `signal` and one whole-call `timeoutMs` (default 10 seconds,
367
+ override 50–60,000 ms). A persistence failure can leave work committed; a later maintenance call safely resumes it.
368
+ An optional `onActivity` runs after a new confirmed projection ACK, without waiting for its returned promise.
369
+ If one callback is already pending, later notifications are skipped, not queued or retried.
370
+ - `cancel(jobId)` cannot recall mail after handoff. `resolveUnknown({ jobId, attemptId, action: 'dismiss' })` closes
371
+ the hold without changing the outcome. Explicit `'redrive'` with `acknowledgeDuplicateRisk: true` can requeue an
372
+ eligible unknown job once for a future worker run. Quiesce suspected old workers and review provider evidence
373
+ first: redrive can duplicate an accepted submission, and the admin never submits the message itself. After
374
+ `write_unconfirmed`, read the current job or repeat the exact same action; do not assume it rolled back.
375
+ - Retention is frozen at admission (default 7 days for payloads and 30 days each for history and idempotency).
376
+ Cleanup holds unresolved unknowns and unacknowledged history, prunes settled payloads when eligible, and only
377
+ removes the replay guard after all retention windows and the projection drain, once activities have been deleted.
378
+
379
+ ## Durable store with Mongoose
380
+
381
+ Install `mongoose@">=9.12.2 <10"` alongside the package. Supply an open connection (not the global default)
382
+ to a writable MongoDB 8.x WiredTiger replica set with journaled majority enabled.
383
+
384
+ <!-- example: mongoose -->
385
+
386
+ ```typescript
387
+ import { createConnection } from 'mongoose';
388
+ import { createMongooseEmailStore } from '@web-ts-toolkit/email-service/mongoose';
389
+
390
+ // The host supplies the replica-set URI and credentials; the store never logs either.
391
+ async function openStore(replicaSetUri: string) {
392
+ const connection = createConnection(replicaSetUri, { maxAdaptiveRetries: 0 });
393
+ try {
394
+ await connection.asPromise();
395
+ const store = createMongooseEmailStore(connection);
396
+ await store.ready();
397
+ return { connection, store, close: () => connection.close() };
398
+ } catch (error) {
399
+ await connection.close();
400
+ throw error;
401
+ }
402
+ }
403
+ ```
404
+
405
+ - `ready()` must succeed before any store call. It checks server status, replica-set config and startup
406
+ options, reads the collection/index catalog, and installs only missing V1 definitions. The principal needs
407
+ `serverStatus`, `replSetGetConfig`, `getCmdLineOpts`, collection/index inspection and creation as applicable,
408
+ and read/write access to the two private collections. Unsupported topology, validators, collations, model
409
+ aliases and conflicting or extra indexes are not adopted or repaired.
410
+ - `jobsCollection` and `activitiesCollection` default to `email_jobs` and `email_activities`.
411
+ `jobsModelName` and `activitiesModelName` reserve connection-local names (defaults `EmailJobV1` and
412
+ `EmailActivityV1`); no models are registered. Keep both collections private to this adapter: no manual
413
+ DML, host schemas/hooks, outside TTL, or live catalog changes. There is no migration.
414
+ - Do not use direct connections, mongos/load balancing, driver compression, SOCKS proxies, or automatic
415
+ encryption on this connection. Disable adaptive retries as shown (or disable driver read or write retries).
416
+ The store does not borrow caller sessions, change connection settings, or close the connection. Call
417
+ `ready()` again after an explicit reconnect or serving topology change.
418
+ - Writes use journaled majority. Exact point reads are primary and linearizable; indexed scans use primary
419
+ majority. Each instance limits in-flight calls and each data primitive to at most five seconds (`ready()`
420
+ has its own budget). Keep replica clocks in sync within one second. `write_unconfirmed` means the
421
+ write may have committed: **do not work an unconfirmed claim or launch after an unconfirmed handoff**.
422
+ - Snapshots and staged outboxes may contain addresses, rendered bodies and tokens. Restrict access, use
423
+ storage/backup encryption and secure credentials separately. The activity projection contains only redacted
424
+ result data; a provider accepting a submission would not establish inbox delivery. Host driver command
425
+ monitoring can see private BSON; don't enable raw command logging in production.
426
+
427
+ ## Opt in to larger SMTP envelopes
428
+
429
+ Omit `smtpCapacity` for V1: **50 total To/Cc/Bcc recipients**, unchanged default SMTP and SendGrid live/sandbox
430
+ behavior, and the existing store definitions. The opt-in is for live SMTP only. It accepts one complete envelope
431
+ per message; it never splits or truncates the envelope. To/Cc stay visible; Bcc stays envelope-only.
432
+
433
+ Choose one **canonical lowercase UUIDv4** for the logical store and an integer `maxRecipients` from **51 to 1,000**.
434
+ Keep that binding in trusted host configuration and pass it as `smtpCapacity` to every factory in that queue:
435
+ registry, store, admission service, each SMTP profile, worker, batch facade and admin. They compare the tuple by
436
+ value and take frozen copies. Do not read it from request data or infer it from a snapshot or a worker setting.
437
+ Factory mismatches fail with `invalid_config`. There is no new environment setting; the host still supplies relay
438
+ credentials separately.
439
+
440
+ This example uses both optional peers and an already open [Mongoose connection](#durable-store-with-mongoose).
441
+ It queues 51 synthetic addresses and does not run the worker. Replace the example UUID with one assigned to your
442
+ store; do not generate a new UUID on startup.
443
+
444
+ <!-- example: smtp-capacity -->
445
+
446
+ ```typescript
447
+ import type { Connection } from 'mongoose';
448
+ import {
449
+ createEmailAdmin,
450
+ createEmailBatchService,
451
+ createEmailService,
452
+ createEmailTemplateRegistry,
453
+ createEmailWorker,
454
+ defineLocalTemplate,
455
+ type SmtpCapacity,
456
+ } from '@web-ts-toolkit/email-service';
457
+ import { createMongooseEmailStore } from '@web-ts-toolkit/email-service/mongoose';
458
+ import { createSmtpProvider, type SmtpProviderOptions } from '@web-ts-toolkit/email-service/smtp';
459
+
460
+ const smtpCapacity: SmtpCapacity = {
461
+ format: 'smtp-v2',
462
+ namespace: '6d36e018-b27f-4f3d-88d1-9b10ad86aaff',
463
+ maxRecipients: 51,
464
+ };
465
+
466
+ async function configureCapacityLane(connection: Connection, relay: Omit<SmtpProviderOptions, 'smtpCapacity'>) {
467
+ const scope = 'example-app';
468
+ const store = createMongooseEmailStore(connection, { smtpCapacity });
469
+ await store.ready();
470
+ const notice = defineLocalTemplate({
471
+ kind: 'handlebars',
472
+ revision: 'v1',
473
+ defaults: { from: { address: 'sender@example.invalid' } },
474
+ subject: { kind: 'inline', content: 'Example notice' },
475
+ text: { kind: 'inline', content: 'Synthetic message' },
476
+ parseInput: () => null,
477
+ parseData: () => ({}),
478
+ prepare: () => ({
479
+ to: Array.from({ length: 51 }, (_, i) => ({ address: `recipient-${i}@example.invalid` })),
480
+ values: {},
481
+ }),
482
+ });
483
+ const registry = createEmailTemplateRegistry({ notice }, { smtpCapacity });
484
+ const service = createEmailService({ scope, store, registry, smtpCapacity });
485
+ const smtp = createSmtpProvider({ ...relay, smtpCapacity });
486
+ const worker = createEmailWorker({ scope, store, providers: [smtp], smtpCapacity });
487
+ const batch = createEmailBatchService({ service, worker, smtpCapacity });
488
+ const admin = createEmailAdmin({ scope, store, smtpCapacity });
489
+ const admission = await service.enqueue({
490
+ templateKey: 'notice',
491
+ input: null,
492
+ intent: 'synthetic-notice',
493
+ key: { kind: 'single', idempotencyKey: 'notice-1' },
494
+ provider: smtp.ref,
495
+ });
496
+ return { admission, admin, batch, worker };
497
+ }
498
+ ```
499
+
500
+ For development, use `createMemoryEmailStore({ smtpCapacity })` and still await `store.ready()`. Separate backings
501
+ (including independent memory stores) need different UUIDs, even in one process. For local SMTP tests, run a TLS relay
502
+ with a fixture certificate signed by a test CA. For example, supply `host: '127.0.0.1'`, the fixture `port`,
503
+ `tls: 'implicit'`, `servername: 'smtp.loopback.invalid'` (matching the certificate's DNS SAN) and `ca: [fixtureCaPem]`.
504
+ `ca` explicitly trusts the fixture CA instead of the default roots; it does not bypass hostname verification.
505
+ Both implicit TLS and required STARTTLS verify the peer; plaintext mail and plaintext authentication are not supported.
506
+
507
+ ### Envelope, queue and relay limits
508
+
509
+ - Count and size checks both apply. The canonical snapshot is capped at **2 MiB and 4,096 JSON values** in the
510
+ opted-in queue (V1 uses a 1 MiB snapshot limit). Envelope fields, metadata, attachment references, and rendered
511
+ bodies share the snapshot budget, including JSON escaping. The individual **512 KiB HTML** and **256 KiB text**
512
+ allowances do not increase. Up to five attachments may supply separate bytes (2 MiB each, 5 MiB total).
513
+ An over-limit snapshot fails with `invalid_snapshot` before insert or provider preflight. On-wire MIME is a
514
+ different size from the snapshot: allow for headers, encoding and attachments when checking the relay's limits.
515
+ - Opted-in workers default to one concurrent job (max two). `run()` defaults to four claims and four maintenance
516
+ steps (each max 16). Admin history pages default to eight activities (max 16); reconciliation and cleanup default
517
+ to four steps (max 16). A bound memory store defaults to eight jobs (max 16); a bound Mongo handle permits at
518
+ most four in-flight primitives. Do not copy larger V1 settings into a capacity queue.
519
+ - Relay recipient limits, reply latency, message size limits and throughput may require choosing a lower cap.
520
+ The adapter waits for each `RCPT TO` reply, even if the relay advertises PIPELINING. For planning, multiply the
521
+ recipient count by a conservative per-reply latency and add time for DNS, connection, TLS, other commands,
522
+ MIME transfer and the final acknowledgement. Leave reserve for jitter and worker/store operations too. At
523
+ 60 ms per reply, 1,000 RCPT replies alone use the entire 60-second provider maximum.
524
+
525
+ On verified-TLS loopback, a single 1,000-recipient transaction with 8.18 MiB of synthetic MIME took **5.851 s**
526
+ with 5 ms added per RCPT (15 s provider budget), **26.004 s** with 25 ms, and **50.980 s** with 50 ms (60 s budget).
527
+ These are single samples, not production latency estimates or a guarantee for another relay. The worker's
528
+ `limits.providerTimeoutMs` defaults to 15,000 ms and cannot exceed 60,000 ms; the effective call is further
529
+ clipped by the remaining run and lease windows, including finalization grace and clock margin. Defaults are
530
+ a 30 s run, 60 s lease and 10 s finalization grace. The two extended samples used
531
+ `limits: { providerTimeoutMs: 60_000, leaseMs: 90_000 }` and a 75,000 ms `run({ timeoutMs })` budget, not just a
532
+ higher provider timeout. Measure with representative envelopes and keep headroom; timeouts are not a flow-control
533
+ strategy.
534
+
535
+ After a partial acceptance there is no automatic resend, including to the rejected subset. Only definitive safe
536
+ transient nonacceptance authorizes a submission retry. Timeout or missing acknowledgement can leave an `unknown`
537
+ result; closing a socket does not prove that the relay discarded the message. `write_unconfirmed` is not a rollback.
538
+ Job and activity reads remain redacted. Opted-in activities include group counts and, when known, group/index
539
+ outcomes, not recipient addresses, message content, attachment references, credentials or raw SMTP replies.
540
+
541
+ ### Storage, rollout and rollback
542
+
543
+ - `format: 'smtp-v2'` selects a separate **storage** format; the public DTOs still have `version: 1`.
544
+ Every opted-in prepared command, SMTP snapshot, job summary and activity carries its `smtpCapacity` metadata,
545
+ even below 51 recipients. The field is optional in TypeScript so the types still describe V1 data, where it
546
+ must be absent. Neither queue will accept the other's staged values.
547
+ - On MongoDB the binding owns exactly `email_smtp_v2.<namespace>.jobs` and
548
+ `email_smtp_v2.<namespace>.activities`; V1 collection/model name overrides cannot be supplied with this option.
549
+ Call `ready()` before use. It checks both definitions and installs missing collections/indexes; it does not
550
+ alter existing validators, rewrite rows or touch V1 collections. A conflicting cap for an existing namespace
551
+ fails readiness. Keep the pair private and restore it together, offline, under its original binding.
552
+ - Keep the namespace and cap fixed for the lifetime of the backing queue. To change the cap, provision a fresh
553
+ namespace, verify readiness, and change routing for **new** work. Keep older and newer queues separate, each
554
+ with its own matched worker and admin. Third-party stores stay V1 unless they implement the bound storage and
555
+ limits, including checking the exact `StoreCall.smtpCapacity` before each primitive.
556
+ - To roll back, stop routing new work to the opt-in queue. Keep already staged outbox values and jobs on their
557
+ original route. Drain (or park) that lane with matching code and binding for recovery, inspection and retention;
558
+ keep V1 traffic on its existing queue. Do not point an older, V1-only runtime at the opted-in store. Do not retag,
559
+ copy or replay jobs across queues or automatically redrive uncertain work. The original lane's idempotency and
560
+ retention still apply.
561
+
562
+ ## Integration entrypoints
563
+
564
+ The integration types have their own entrypoints:
565
+
566
+ <!-- example: entry-types -->
567
+
568
+ ```typescript
569
+ import type { SmtpProviderOptions } from '@web-ts-toolkit/email-service/smtp';
570
+ import type { SendGridProviderOptions } from '@web-ts-toolkit/email-service/sendgrid';
571
+ import type { MongooseEmailStoreOptions } from '@web-ts-toolkit/email-service/mongoose';
572
+ ```
573
+
574
+ <!-- prettier-ignore -->
575
+ | Entry | Current surface | Optional peer |
576
+ | --- | --- | --- |
577
+ | `@web-ts-toolkit/email-service` | `EmailError`, `createEmailTemplateRegistry`, `defineLocalTemplate`, `defineSendGridTemplate`, `createEmailService`, `createEmailWorker`, `createEmailBatchService`, `createEmailAdmin`, `createMemoryEmailStore`, and shared contracts including `SmtpCapacity` | None |
578
+ | `@web-ts-toolkit/email-service/smtp` | `createSmtpProvider`, `SmtpProviderOptions` | Nodemailer `>=10.6.0 <11` (runtime only) |
579
+ | `@web-ts-toolkit/email-service/sendgrid` | `createSendGridProvider`, `SendGridProviderOptions` | None (Node HTTPS) |
580
+ | `@web-ts-toolkit/email-service/mongoose` | `createMongooseEmailStore`, `MongooseEmailStoreOptions` | Mongoose `>=9.12.2 <10` (declarations and caller connection) |
581
+
582
+ The root has no runtime or declaration dependency on the optional peers. A type-only SMTP import does not require
583
+ Nodemailer. The Mongoose runtime module can load without Mongoose, but its declarations reference the peer and
584
+ the factory needs a caller-owned Mongoose connection. No entrypoint opens a connection, registers a model, starts
585
+ a timer, or submits mail when imported.