@web-ts-toolkit/email-service 0.0.0-stage → 0.72.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/LICENSE +201 -0
- package/README.md +446 -2
- package/index.d.mts +206 -0
- package/index.d.ts +206 -0
- package/index.js +4289 -0
- package/index.mjs +4244 -0
- package/mongoose.d.mts +24 -0
- package/mongoose.d.ts +24 -0
- package/mongoose.js +3045 -0
- package/mongoose.mjs +3020 -0
- package/package.json +89 -4
- package/provider-HisBc6hk.d.mts +183 -0
- package/provider-HisBc6hk.d.ts +183 -0
- package/sendgrid.d.mts +18 -0
- package/sendgrid.d.ts +18 -0
- package/sendgrid.js +1437 -0
- package/sendgrid.mjs +1410 -0
- package/smtp.d.mts +28 -0
- package/smtp.d.ts +28 -0
- package/smtp.js +1449 -0
- package/smtp.mjs +1412 -0
- package/store-D4YAI6Rk.d.mts +346 -0
- package/store-Vb63Gocz.d.ts +346 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright Junmin Ahn
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,447 @@
|
|
|
1
|
-
#
|
|
1
|
+
# `@web-ts-toolkit/email-service`
|
|
2
2
|
|
|
3
|
-
|
|
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 V1 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; do not prepare a replacement. Keep the relay within the
|
|
176
|
+
idempotency window. Restrict access to the staged payload; the returned job summary contains neither bodies nor addresses.
|
|
177
|
+
|
|
178
|
+
## Configure an SMTP profile
|
|
179
|
+
|
|
180
|
+
Install `nodemailer@">=10.6.0 <11"` to import the SMTP runtime entry. Its profile `key` must match the prepared snapshot.
|
|
181
|
+
|
|
182
|
+
<!-- example: smtp-profile -->
|
|
183
|
+
|
|
184
|
+
```typescript
|
|
185
|
+
import { createSmtpProvider } from '@web-ts-toolkit/email-service/smtp';
|
|
186
|
+
|
|
187
|
+
const smtp = createSmtpProvider({
|
|
188
|
+
key: 'standard-smtp',
|
|
189
|
+
host: 'smtp.example.invalid',
|
|
190
|
+
tls: 'starttls',
|
|
191
|
+
});
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
- `starttls` (default port 587) requires a successful TLS upgrade; `implicit` (465) starts with TLS. Both require TLS 1.2+
|
|
195
|
+
and verify the certificate against `servername` (if specified) or `host`, including IP SAN verification for literal
|
|
196
|
+
IPs. `ca` accepts one PEM CA certificate per array entry and replaces Node's default trust roots. `auth: { user, pass }`
|
|
197
|
+
uses advertised ESMTP PLAIN or LOGIN only over verified TLS; there is no plaintext fallback.
|
|
198
|
+
- Use an ASCII DNS host or a literal IP. The adapter uses a cancellable DNS resolver (not OS hosts-file aliases) and
|
|
199
|
+
dials one address. It does not pool, retry or select another server after a failure.
|
|
200
|
+
- `prepare` validates and copies the snapshot and attachment bytes without network I/O. SMTP sends visible To/Cc,
|
|
201
|
+
envelope-only Bcc and no implicit path or URL inputs. Attachments are ordinary MIME leaf parts, not nested message
|
|
202
|
+
or multipart MIME structures.
|
|
203
|
+
- `submit({ signal, timeoutMs })` consumes the prepared submission on a valid call. It closes its connection on abort
|
|
204
|
+
or timeout and never waits indefinitely for a peer. Neither closing the connection nor an `unknown` result means
|
|
205
|
+
the relay discarded the message. `accepted` and `partially_accepted` require a final DATA acknowledgement and mean
|
|
206
|
+
SMTP submission, not inbox delivery. Result diagnostics are fixed codes and recipient indexes, not addresses or raw
|
|
207
|
+
replies. Direct submission is unmanaged and does not provide durable queue or retry guarantees.
|
|
208
|
+
|
|
209
|
+
## Configure a SendGrid profile
|
|
210
|
+
|
|
211
|
+
No SendGrid SDK or peer is required. Supply an explicit Mail Send key from your host's secret configuration.
|
|
212
|
+
Use the profile's `ref` in a command for a template registered with `defineSendGridTemplate`.
|
|
213
|
+
|
|
214
|
+
<!-- example: sendgrid-profile -->
|
|
215
|
+
|
|
216
|
+
```typescript
|
|
217
|
+
import { createSendGridProvider } from '@web-ts-toolkit/email-service/sendgrid';
|
|
218
|
+
|
|
219
|
+
function validationProfile(apiKey: string) {
|
|
220
|
+
return createSendGridProvider({ key: 'validation', apiKey, mode: 'sandbox' });
|
|
221
|
+
}
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
- `mode` defaults to `'live'`. `'sandbox'` only validates a request; keep it distinct from a live profile. The
|
|
225
|
+
prepared snapshot's provider kind, key and mode must match. `prepare` does no network I/O and maps the
|
|
226
|
+
frozen envelope, dynamic data and verified attachment bytes to a single personalization with the requested
|
|
227
|
+
template ID. This entrypoint does not manage templates or pin their active SendGrid versions.
|
|
228
|
+
- `submit({ signal, timeoutMs })` makes at most one POST to `https://api.sendgrid.com/v3/mail/send` over
|
|
229
|
+
verified TLS 1.2+. No endpoint override, redirects, implicit retries or connection sharing. The JSON body is
|
|
230
|
+
capped at 8 MiB and the complete HTTP response at 64 KiB. Abort or deadline closes the connection; it cannot
|
|
231
|
+
recall a request SendGrid may already have accepted.
|
|
232
|
+
- Complete live `202` means `accepted` and may include one sanitized `providerMessageId`. Complete sandbox `200`
|
|
233
|
+
means `validated`, not `accepted`. Neither outcome reports inbox delivery or per-recipient status. A complete
|
|
234
|
+
`429` reports throttled rejection and may carry a retry floor; `400`, `401`, `403`, `404`, `405` and `413` are
|
|
235
|
+
permanent rejections. Other statuses (including `5xx`), incomplete or invalid HTTP, and uncertain transport
|
|
236
|
+
failures do not authorize a retry. The adapter never schedules a retry. Direct submissions are unmanaged and
|
|
237
|
+
provide no durable queue guarantees. Keep raw HTTP tracing off around credentials and message data.
|
|
238
|
+
|
|
239
|
+
## In-process store for tests and development
|
|
240
|
+
|
|
241
|
+
<!-- example: memory -->
|
|
242
|
+
|
|
243
|
+
```typescript
|
|
244
|
+
import { createMemoryEmailStore } from '@web-ts-toolkit/email-service';
|
|
245
|
+
|
|
246
|
+
const memoryStore = createMemoryEmailStore({ maxJobs: 32 });
|
|
247
|
+
await memoryStore.ready();
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
Share the same instance to exercise competing callers. Each instance loses its state on restart and does not share
|
|
251
|
+
state across processes. Capacity (default 256 jobs) is shared across scopes; a full store rejects new jobs instead of
|
|
252
|
+
evicting retained ones. This is not a fallback for durable persistence. The `EmailStore` methods are private lifecycle
|
|
253
|
+
primitives for adapters and tests, not application-facing routes. Claims include sensitive snapshots and ownership
|
|
254
|
+
tokens; do not log or expose them. Store operations alone never contact a provider.
|
|
255
|
+
|
|
256
|
+
## Run a worker
|
|
257
|
+
|
|
258
|
+
Bind a caller-ready store to the same scope as the admission service. Pass the configured provider instances, not
|
|
259
|
+
credentials in a queue payload. The profile's key, kind and mode must match the frozen snapshot.
|
|
260
|
+
|
|
261
|
+
<!-- example: worker -->
|
|
262
|
+
|
|
263
|
+
```typescript
|
|
264
|
+
import {
|
|
265
|
+
createEmailWorker,
|
|
266
|
+
type ConfiguredEmailProvider,
|
|
267
|
+
type EmailStore,
|
|
268
|
+
type EmailWorker,
|
|
269
|
+
} from '@web-ts-toolkit/email-service';
|
|
270
|
+
|
|
271
|
+
function makeWorker(store: EmailStore, profiles: readonly ConfiguredEmailProvider[]) {
|
|
272
|
+
return createEmailWorker({ scope: 'example-app', store, providers: profiles });
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function runDue(worker: EmailWorker, signal: AbortSignal) {
|
|
276
|
+
return worker.run({ limit: 20, concurrency: 4, maintenanceLimit: 10, signal });
|
|
277
|
+
}
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
- Your host calls `await runDue(worker, signal)` to do a bounded run.
|
|
281
|
+
Those are the default work limits; set lower limits when appropriate. `timeoutMs` defaults to 30 seconds for the
|
|
282
|
+
whole run, with a separate bounded finish grace. There is no polling or automatic connection management.
|
|
283
|
+
One run per instance is allowed. Different instances can share a queue. `idle` is not a whole-queue inventory.
|
|
284
|
+
- The worker prepares the provider payload, validates attachment bytes through your `attachmentResolvers`, and asks
|
|
285
|
+
the optional `rateLimiter` for one permit before making a durable handoff. A worker limiter should be instantiated
|
|
286
|
+
per worker; a shared limiter must enforce the actual shared quota outside the worker. The worker does not wait for
|
|
287
|
+
a deferred permit, refund permits, rerender snapshots, or choose an alternate profile.
|
|
288
|
+
- A missing or late handoff acknowledgement never permits a send. A finish write error is not evidence of rejection.
|
|
289
|
+
`unconfirmed` means the worker could not prove the stored attempt outcome; `unknown` is a stored result that is
|
|
290
|
+
never automatically retried. `submitted` counts full and partial acceptance, not sandbox validation or inbox
|
|
291
|
+
delivery. An application that explicitly redrives unknown work must accept possible duplicates.
|
|
292
|
+
- `await worker.shutdown({ timeoutMs: 15_000 })` permanently closes the worker, not the store. `stopped` means no
|
|
293
|
+
run or provider I/O is active; `pendingCallbacks` counts host promises still held after cancellation. Injected
|
|
294
|
+
stores and providers must honor call deadlines, abort actual I/O and wait for it to settle. A timed-out shutdown
|
|
295
|
+
can be awaited again, and it does not recall bytes already sent.
|
|
296
|
+
|
|
297
|
+
## Enqueue and resume a batch
|
|
298
|
+
|
|
299
|
+
Use `createEmailBatchService` with a service and worker bound to the **same scope and underlying store**.
|
|
300
|
+
Each item is a template command without a standalone `key`. Using `welcomeCommand`, `service`, `store`, `smtp`
|
|
301
|
+
and `makeWorker` from the preceding examples:
|
|
302
|
+
|
|
303
|
+
<!-- example: batch -->
|
|
304
|
+
|
|
305
|
+
```typescript
|
|
306
|
+
import { createEmailBatchService } from '@web-ts-toolkit/email-service';
|
|
307
|
+
|
|
308
|
+
const { key: _singleKey, ...command } = welcomeCommand;
|
|
309
|
+
const worker = makeWorker(store, [smtp]);
|
|
310
|
+
const batch = createEmailBatchService({ service, worker });
|
|
311
|
+
const request = { batchId: 'welcome-run-1', items: [{ itemId: 'notice-1', command }] };
|
|
312
|
+
const admission = await batch.enqueueBatch(request);
|
|
313
|
+
const resumed = await batch.enqueueBatch(request); // Same item identity; replays without preparing again.
|
|
314
|
+
// When the host is ready to process due jobs, call batch.run({ limit: 10, concurrency: 2 }).
|
|
315
|
+
```
|
|
316
|
+
|
|
317
|
+
- An enqueue call validates all 1–100 item envelopes and unique IDs before any lookup or preparation. It admits in
|
|
318
|
+
order under one `timeoutMs` (default 30 seconds, override 50–120,000 ms) and optional `signal`. Business input
|
|
319
|
+
is still parsed by the template on a miss; hold it stable until the call settles.
|
|
320
|
+
- Items can be `enqueued`, `replayed`, `failed` with a safe code, or `not_started` after abort or deadline. Earlier
|
|
321
|
+
writes aren't rolled back. Use the **same batch ID, item IDs and intents** to resume even in a different order;
|
|
322
|
+
`write_unconfirmed` may have committed. A committed match returns its current summary without preparing or
|
|
323
|
+
rendering again. Changing intent under the same ID reports `idempotency_conflict`; replay does not reopen
|
|
324
|
+
completed jobs. The counts distinguish failed items from the subset with a persistence error.
|
|
325
|
+
- With a wrapped service or one from another build (such as mixing ESM and CommonJS), the batch calls its public
|
|
326
|
+
`enqueue`. It passes the remaining time within that API's 50–60,000 ms range and a signal that can stop work
|
|
327
|
+
sooner. The batch waits for a started item to settle rather than assuming a write was cancelled. A custom
|
|
328
|
+
service must honor these limits and settle its I/O; one that does not cooperate can keep the batch pending.
|
|
329
|
+
- `batch.run` is the configured worker's **scope-wide** run, with the same bounds, limiter and report. It can
|
|
330
|
+
process unrelated due jobs in that scope. It neither filters by batch ID nor rewrites envelopes; the local
|
|
331
|
+
grouping ID is not SendGrid's `batch_id`.
|
|
332
|
+
- Call `worker.shutdown()` to stop delivery runs. This does not stop `enqueueBatch`; pass its own `signal` to
|
|
333
|
+
cancel admission. Supply a trusted worker: `batch.run` forwards its report and errors unchanged, so a custom
|
|
334
|
+
worker is responsible for redacting them and actually stopping its I/O.
|
|
335
|
+
|
|
336
|
+
## Inspect results and maintain history
|
|
337
|
+
|
|
338
|
+
Supply the caller-ready store and an admitted `jobId` (for example, `first.job.jobId`). Bind the admin to the same scope:
|
|
339
|
+
|
|
340
|
+
<!-- example: results -->
|
|
341
|
+
|
|
342
|
+
```typescript
|
|
343
|
+
import { createEmailAdmin, type EmailStore } from '@web-ts-toolkit/email-service';
|
|
344
|
+
|
|
345
|
+
async function inspectResults(store: EmailStore, jobId: string) {
|
|
346
|
+
const admin = createEmailAdmin({ scope: 'example-app', store });
|
|
347
|
+
const job = await admin.getJob(jobId); // Latest authoritative outcome, even before projection.
|
|
348
|
+
const projected = await admin.reconcile({ limit: 20 }); // Schedule this and cleanup separately from delivery.
|
|
349
|
+
const page = await admin.listActivities({ jobId, limit: 10 });
|
|
350
|
+
const next = page.nextCursor ? await admin.listActivities({ jobId, limit: 10, cursor: page.nextCursor }) : undefined;
|
|
351
|
+
const cleaned = await admin.cleanup({ limit: 20 });
|
|
352
|
+
return { job, projected, page, next, cleaned };
|
|
353
|
+
}
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
- Authorize requests in your application; a scope or cursor is not authentication. Results contain only redacted
|
|
357
|
+
metadata, fixed diagnostic codes, and reliably known recipient indexes, never queue snapshots, addresses, provider
|
|
358
|
+
responses or ownership tokens. Activities are submission history, not inbox delivery receipts or inputs to a resend.
|
|
359
|
+
- Lists contain complete committed projections, including those pending acknowledgement on the job. They order
|
|
360
|
+
newest finish first, then by job and attempt ID. `from` is inclusive; `before` is exclusive. Keep the same scope
|
|
361
|
+
and filters when passing `nextCursor`; page size can change (default 25, range 1–100). Pages are not snapshots.
|
|
362
|
+
- `reconcile` and `cleanup` do sequential work (default 20 steps, range 1–100); their counts describe only confirmed
|
|
363
|
+
progress in that call. All admin methods accept `signal` and one whole-call `timeoutMs` (default 10 seconds,
|
|
364
|
+
override 50–60,000 ms). A persistence failure can leave work committed; a later maintenance call safely resumes it.
|
|
365
|
+
An optional `onActivity` runs after a new confirmed projection ACK, without waiting for its returned promise.
|
|
366
|
+
If one callback is already pending, later notifications are skipped, not queued or retried.
|
|
367
|
+
- `cancel(jobId)` cannot recall mail after handoff. `resolveUnknown({ jobId, attemptId, action: 'dismiss' })` closes
|
|
368
|
+
the hold without changing the outcome. Explicit `'redrive'` with `acknowledgeDuplicateRisk: true` can requeue an
|
|
369
|
+
eligible unknown job once for a future worker run. Quiesce suspected old workers and review provider evidence
|
|
370
|
+
first: redrive can duplicate an accepted submission, and the admin never submits the message itself. After
|
|
371
|
+
`write_unconfirmed`, read the current job or repeat the exact same action; do not assume it rolled back.
|
|
372
|
+
- Retention is frozen at admission (default 7 days for payloads and 30 days each for history and idempotency).
|
|
373
|
+
Cleanup holds unresolved unknowns and unacknowledged history, prunes settled payloads when eligible, and only
|
|
374
|
+
removes the replay guard after all retention windows and the projection drain, once activities have been deleted.
|
|
375
|
+
|
|
376
|
+
## Durable store with Mongoose
|
|
377
|
+
|
|
378
|
+
Install `mongoose@">=9.12.2 <10"` alongside the package. Supply an open connection (not the global default)
|
|
379
|
+
to a writable MongoDB 8.x WiredTiger replica set with journaled majority enabled.
|
|
380
|
+
|
|
381
|
+
<!-- example: mongoose -->
|
|
382
|
+
|
|
383
|
+
```typescript
|
|
384
|
+
import { createConnection } from 'mongoose';
|
|
385
|
+
import { createMongooseEmailStore } from '@web-ts-toolkit/email-service/mongoose';
|
|
386
|
+
|
|
387
|
+
// The host supplies the replica-set URI and credentials; the store never logs either.
|
|
388
|
+
async function openStore(replicaSetUri: string) {
|
|
389
|
+
const connection = createConnection(replicaSetUri, { maxAdaptiveRetries: 0 });
|
|
390
|
+
try {
|
|
391
|
+
await connection.asPromise();
|
|
392
|
+
const store = createMongooseEmailStore(connection);
|
|
393
|
+
await store.ready();
|
|
394
|
+
return { store, close: () => connection.close() };
|
|
395
|
+
} catch (error) {
|
|
396
|
+
await connection.close();
|
|
397
|
+
throw error;
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
```
|
|
401
|
+
|
|
402
|
+
- `ready()` must succeed before any store call. It checks server status, replica-set config and startup
|
|
403
|
+
options, reads the collection/index catalog, and installs only missing V1 definitions. The principal needs
|
|
404
|
+
`serverStatus`, `replSetGetConfig`, `getCmdLineOpts`, collection/index inspection and creation as applicable,
|
|
405
|
+
and read/write access to the two private collections. Unsupported topology, validators, collations, model
|
|
406
|
+
aliases and conflicting or extra indexes are not adopted or repaired.
|
|
407
|
+
- `jobsCollection` and `activitiesCollection` default to `email_jobs` and `email_activities`.
|
|
408
|
+
`jobsModelName` and `activitiesModelName` reserve connection-local names (defaults `EmailJobV1` and
|
|
409
|
+
`EmailActivityV1`); no models are registered. Keep both collections private to this adapter: no manual
|
|
410
|
+
DML, host schemas/hooks, outside TTL, or live catalog changes. There is no migration.
|
|
411
|
+
- Do not use direct connections, mongos/load balancing, driver compression, SOCKS proxies, or automatic
|
|
412
|
+
encryption on this connection. Disable adaptive retries as shown (or disable driver read or write retries).
|
|
413
|
+
The store does not borrow caller sessions, change connection settings, or close the connection. Call
|
|
414
|
+
`ready()` again after an explicit reconnect or serving topology change.
|
|
415
|
+
- Writes use journaled majority. Exact point reads are primary and linearizable; indexed scans use primary
|
|
416
|
+
majority. Each instance limits in-flight calls and each data primitive to at most five seconds (`ready()`
|
|
417
|
+
has its own budget). Keep replica clocks in sync within one second. `write_unconfirmed` means the
|
|
418
|
+
write may have committed: **do not work an unconfirmed claim or launch after an unconfirmed handoff**.
|
|
419
|
+
- Snapshots and staged outboxes may contain addresses, rendered bodies and tokens. Restrict access, use
|
|
420
|
+
storage/backup encryption and secure credentials separately. The activity projection contains only redacted
|
|
421
|
+
result data; a provider accepting a submission would not establish inbox delivery. Host driver command
|
|
422
|
+
monitoring can see private BSON; don't enable raw command logging in production.
|
|
423
|
+
|
|
424
|
+
## Integration entrypoints
|
|
425
|
+
|
|
426
|
+
The integration types have their own entrypoints:
|
|
427
|
+
|
|
428
|
+
<!-- example: entry-types -->
|
|
429
|
+
|
|
430
|
+
```typescript
|
|
431
|
+
import type { SmtpProviderOptions } from '@web-ts-toolkit/email-service/smtp';
|
|
432
|
+
import type { SendGridProviderOptions } from '@web-ts-toolkit/email-service/sendgrid';
|
|
433
|
+
import type { MongooseEmailStoreOptions } from '@web-ts-toolkit/email-service/mongoose';
|
|
434
|
+
```
|
|
435
|
+
|
|
436
|
+
<!-- prettier-ignore -->
|
|
437
|
+
| Entry | Current surface | Optional peer |
|
|
438
|
+
| --- | --- | --- |
|
|
439
|
+
| `@web-ts-toolkit/email-service` | `EmailError`, `createEmailTemplateRegistry`, `defineLocalTemplate`, `defineSendGridTemplate`, `createEmailService`, `createEmailWorker`, `createEmailBatchService`, `createEmailAdmin`, `createMemoryEmailStore`, and shared contracts | None |
|
|
440
|
+
| `@web-ts-toolkit/email-service/smtp` | `createSmtpProvider`, `SmtpProviderOptions` | Nodemailer `>=10.6.0 <11` (runtime only) |
|
|
441
|
+
| `@web-ts-toolkit/email-service/sendgrid` | `createSendGridProvider`, `SendGridProviderOptions` | None (Node HTTPS) |
|
|
442
|
+
| `@web-ts-toolkit/email-service/mongoose` | `createMongooseEmailStore`, `MongooseEmailStoreOptions` | Mongoose `>=9.12.2 <10` (declarations and caller connection) |
|
|
443
|
+
|
|
444
|
+
The root has no runtime or declaration dependency on the optional peers. A type-only SMTP import does not require
|
|
445
|
+
Nodemailer. The Mongoose runtime module can load without Mongoose, but its declarations reference the peer and
|
|
446
|
+
the factory needs a caller-owned Mongoose connection. No entrypoint opens a connection, registers a model, starts
|
|
447
|
+
a timer, or submits mail when imported.
|