@repa/mail 0.0.0-stage → 0.1.0-alpha.21

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 ADDED
@@ -0,0 +1,36 @@
1
+ Repa SDK Pre-Release Evaluation License
2
+
3
+ Copyright (c) 2026 Repa. All rights reserved.
4
+
5
+ Subject to the restrictions below, Repa grants you a limited, revocable,
6
+ non-exclusive, non-transferable, non-sublicensable license to install and use
7
+ this pre-release SDK solely to evaluate Repa and to develop and test
8
+ integrations that communicate with Repa services using credentials you are
9
+ authorized to use.
10
+
11
+ You may not:
12
+
13
+ 1. use the SDK in production or provide it as part of a production service;
14
+ 2. copy, publish, redistribute, sublicense, sell, rent, lease, or otherwise
15
+ make the SDK available to another party;
16
+ 3. modify the SDK, create derivative works from it, or reverse engineer,
17
+ decompile, or disassemble it, except to the limited extent applicable law
18
+ expressly prohibits this restriction;
19
+ 4. use the SDK or information derived from it to create or improve a product
20
+ or service that competes with Repa; or
21
+ 5. remove or alter proprietary notices.
22
+
23
+ Repa and its licensors retain all ownership and intellectual-property rights
24
+ in the SDK. No rights are granted except those stated expressly in this
25
+ license. Access to Repa services remains subject to the applicable service
26
+ terms and may be suspended or terminated independently of this license.
27
+
28
+ This license terminates automatically if you breach it or when Repa replaces
29
+ this pre-release license for the SDK version you use. On termination, you must
30
+ stop using and delete the SDK.
31
+
32
+ THE SDK IS PRE-RELEASE SOFTWARE PROVIDED "AS IS" AND "AS AVAILABLE", WITHOUT
33
+ WARRANTIES OR CONDITIONS OF ANY KIND. TO THE MAXIMUM EXTENT PERMITTED BY LAW,
34
+ REPA WILL NOT BE LIABLE FOR ANY INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL,
35
+ OR EXEMPLARY DAMAGES, OR FOR LOSS OF DATA, PROFITS, REVENUE, OR BUSINESS,
36
+ ARISING FROM OR RELATED TO THE SDK.
package/README.md CHANGED
@@ -1,3 +1,245 @@
1
- # Temporary Holding Version
1
+ # @repa/mail
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
+ Server-only ESM TypeScript client for repa mail, on Node 22.12+ within
4
+ Node 22 and Node 24. Root exports reject browsers/workers. `/contracts` is
5
+ browser-safe. This package uses the repa evaluation licence; no public
6
+ production SLA or stable production-use terms are promised.
7
+
8
+ Published on npm: **0.1.0-alpha.20** on the `alpha` channel (first publication
9
+ under this name). This source is the **0.1.0-alpha.21** candidate, not yet published;
10
+ new-text reads below arrive with it. Pin the exact version; a matching mail service
11
+ deployment is qualified separately.
12
+
13
+ ```sh
14
+ npm install @repa/mail@0.1.0-alpha.20
15
+ ```
16
+
17
+ This package was named `@repa/email-server` until 0.1.0-alpha.17 (EMAIL-D226).
18
+ Only the package name changed: every export keeps its name, so an existing
19
+ integration changes only its import specifier.
20
+
21
+ ## Send a first message
22
+
23
+ Create an integration in mail Settings → Integrations and grant its sender.
24
+ Keep its key in a backend secret store; ordinary workspace API keys cannot send
25
+ mail. Verify the sender domain and use an owned recipient for a first test.
26
+
27
+ Save one durable job before sending: its UUID `idempotencyKey`, opaque host
28
+ `subject` and frozen `message`. A message contains `from` (one authorized address
29
+ string, optionally `Accounts <receipts@example.com>`), `to`/`cc`/`bcc`, `subject`,
30
+ `text` and/or `html`, and optional base64 attachments. `senderId` and
31
+ `sentAccountId` are not structured-send inputs. Then pass the saved job to:
32
+
33
+ ```ts
34
+ import { createEmailClient, type EmailMessage } from '@repa/mail';
35
+
36
+ export async function sendSavedMessage(job: {
37
+ subject: string; idempotencyKey: string; message: EmailMessage;
38
+ }, apiKey: string) {
39
+ const mail = createEmailClient({ apiKey, subject: job.subject });
40
+ return mail.send(job.message, { idempotencyKey: job.idempotencyKey });
41
+ }
42
+
43
+ ```
44
+
45
+ The SDK makes one HTTP attempt. Keep its `operationId`. After a timeout or lost
46
+ connection recover the same key with the same integration and subject:
47
+
48
+ ```ts
49
+ import { createEmailClient } from '@repa/mail';
50
+
51
+ export async function checkSavedMessage(apiKey: string, subject: string, key: string) {
52
+ const mail = createEmailClient({ apiKey, subject });
53
+ const receipt = await mail.findSubmissionByKey(key);
54
+ return mail.getSubmission(receipt.operationId);
55
+ }
56
+
57
+ ```
58
+
59
+ A definitive `NOT_FOUND`, or `preparing`, permits exact replay of the original
60
+ message and key. Changed input is `CONFLICT`. Never generate another UUID to
61
+ recover uncertain work. `queued` proves durable repa acceptance;
62
+ `provider_accepted` proves sending-service acceptance, not delivery;
63
+ `acceptance_unknown` needs reconciliation without resending.
64
+
65
+ The nine submission states are `preparing`, `pending`, `accepted`, `queued`,
66
+ `dispatching`, `acceptance_unknown`, `provider_accepted`, `failed`, `cancelled`.
67
+ `recipients` reports original envelope ordinals and independent feedback facts
68
+ (`Send`, `Delivery`, `Bounce`, `Complaint`, `Reject`, `Rendering Failure`,
69
+ `DeliveryDelay`), without recipient addresses. Delivery proves acceptance by the
70
+ recipient server, never inbox placement or reading. There is no open tracking.
71
+ The mail product's richer delivery display is not a public client method.
72
+
73
+ ## Verify and commit webhooks
74
+
75
+ Keep raw bytes. Resolve endpoint ID and versioned secrets from trusted
76
+ configuration. Enforce a 16,384-byte HTTP body limit and a request deadline in
77
+ your host before reading the body. Verify before parsing, and return success
78
+ only after committing:
79
+
80
+ ```ts
81
+ import { verifyEmailWebhook, type EmailWebhookEvent } from '@repa/mail';
82
+
83
+ export async function receiveMailEvent(request: Request, config: {
84
+ endpointId: string; secrets: Record<number, string>;
85
+ }, commitOnce: (event: EmailWebhookEvent) => Promise<void>) {
86
+ const event = verifyEmailWebhook({
87
+ body: new Uint8Array(await request.arrayBuffer()),
88
+ headers: request.headers, ...config,
89
+ });
90
+ await commitOnce(event);
91
+ return new Response(null, { status: 204 });
92
+ }
93
+
94
+ ```
95
+
96
+ `commitOnce` must save event ID and effect atomically and succeed for duplicates.
97
+ A failed signature/commit must not return success. Default timestamp tolerance is
98
+ 300 seconds. Keep old secrets until pinned deliveries drain during rotation;
99
+ remove revoked secrets. Deduplicate stable event IDs across history and webhooks.
100
+ `listEvents({after, limit})` returns at most 100 events and `next`; commit that
101
+ cursor with the page's durable effects. Arrival order is not guaranteed.
102
+ History and webhook payloads last 30 days. Retries: at most 12 over seven days;
103
+ explicit redelivery: at most three per event/endpoint within 30 days.
104
+
105
+ ## Headless mailboxes and rules
106
+
107
+ Your host backend authenticates users, derives the subject from its session,
108
+ and checks the mailbox/action on every request and download. Subjects grant no
109
+ additional authority. Keys never enter browser code, URLs, public env variables
110
+ or logs. Users do not need repa accounts.
111
+
112
+ ```ts
113
+ import { createEmailClient, createMailTransport } from '@repa/mail';
114
+
115
+ export async function openAllowedMailbox(apiKey: string, authenticatedSubject: string,
116
+ allowedAccountId: string, signal: AbortSignal) {
117
+ const mail = createEmailClient({ apiKey, subject: authenticatedSubject });
118
+ return createMailTransport(mail).open(allowedAccountId, signal);
119
+ }
120
+
121
+ ```
122
+
123
+ Exports include `createEmailClient`, `createMailTransport`, `verifyEmailWebhook`,
124
+ `EmailError`, the client/message/request types and browser-safe `/contracts`.
125
+ Client methods cover mailbox discovery/open, message/conversation list/read,
126
+ downloads, message changes, folder create/rename/delete, storage, raw submission,
127
+ drafts and rules. Sanitize read HTML and display safety warnings before content.
128
+
129
+ Rules require “Read and organize” or higher. `getRules`/`checkRules` are reads;
130
+ `saveRules` takes exactly one of `items` or `script`; `changeRules` performs one
131
+ `put`, `move`, `toggle` or `delete`. Both writes compare `expectedRevision`
132
+ without an operation UUID or Idempotency-Key. After response loss read again;
133
+ a stale revision is `CONFLICT`, while a refused change resolves
134
+ `{status: 'rejected', problems}`. Integrations cannot alter automatic replies,
135
+ forwarding or blocks that send mail. A script is at most 65,536 bytes.
136
+
137
+ The builder condition `{field: "tag", operator: "is", negate: false, value: "shop"}`
138
+ checks the original envelope recipient with Sieve `envelope :detail`. An exact
139
+ receiving address always wins over plus fallback. Tag reception grants no sender
140
+ authority.
141
+
142
+ Draft get/list/save/prepare/discard is private to integration + subject. Prepare
143
+ freezes the message; send reconciles the original draft ID. After a lost reply,
144
+ read the same draft and reuse that identity. Scheduling/unscheduling is refused
145
+ for integration subjects. Rotation preserves ownership, but queued first dispatch
146
+ still checks the original key; keep it valid until its work drains. Revocation
147
+ cannot recall provider-accepted mail.
148
+
149
+ ## Read a reply without the quoted chain
150
+
151
+ Each reply usually carries the earlier messages quoted below it. `readMessage`
152
+ with `content: 'new'` returns only what the sender wrote in this message:
153
+ `text` is the new text, `signature` the separated signature, and there is no
154
+ `html`. The default (`content: 'full'`, or no `content`) is the whole message;
155
+ the stored message never changes. `content: 'new'` cannot be combined with a
156
+ part download.
157
+
158
+ ```ts
159
+ import { createEmailClient } from '@repa/mail';
160
+
161
+ export async function readReplyOnly(apiKey: string, authenticatedSubject: string,
162
+ message: { accountId: string; folderId: string; uidValidity: number; uid: number }) {
163
+ const mail = createEmailClient({ apiKey, subject: authenticatedSubject });
164
+ const reply = await mail.readMessage({ ...message, content: 'new' });
165
+ // An unproven cut: say that earlier quoted text was removed; the full read still has it.
166
+ const note = reply.newText.confidence === 'structural' ? 'Earlier quoted text was removed.' : null;
167
+ return { text: reply.text, signature: reply.signature, note };
168
+ }
169
+ ```
170
+
171
+ `newText` says what happened:
172
+
173
+ - `outcome`: `cut` (quoted earlier text was removed), `whole` (nothing was
174
+ removed; the signature may still come separately) or `unreadable` (no
175
+ readable text; `text` is empty).
176
+ - `confidence`: `proven` (the removed text repeats an earlier message of the
177
+ same conversation in this mailbox), `structural` (the sender's mail program
178
+ marked it as a quote, but no earlier message proved it) or `none` (nothing
179
+ removed).
180
+ - `reason`: why, for example `gmail_quote`, `outlook_separator`,
181
+ `text_attribution` (an "On … wrote:" line) or `proven_repeat` for a cut, and
182
+ `no_quote`, `interleaved` (answers between quoted lines), `forward`,
183
+ `empty_remainder`, `too_large`, `invitation` or `encrypted` when the whole
184
+ text was kept. New reasons may appear; go by `outcome`.
185
+ - `signatureReason`: `rfc3676_delimiter` (the `-- ` line), `html_signature`
186
+ (the mail program's signature block), `sender_learned` (the same closing
187
+ lines end earlier messages from this sender) or empty.
188
+ - `removed[]`: each removed region with `kind` (`quote`, `forward_header`,
189
+ `signature`), `bytes`, `headerId` (the earlier message's Message-ID, null
190
+ when unproven) and `messageId`.
191
+ - `fullTextBytes` is the size of the whole text; `extractorVersion` names the
192
+ extractor that derived it.
193
+
194
+ No word the sender wrote is dropped: when a cut is not safe (answers between
195
+ quoted lines, several quoted regions, a forward), the whole text is kept.
196
+
197
+ ## Follow `removed[].messageId` to the earlier message
198
+
199
+ `messageId` is set only when you may read that earlier message in this
200
+ mailbox; it is the `id` of that message in `readConversation`, whose messages
201
+ also carry the same `newText` in `chat`.
202
+
203
+ ```ts
204
+ import { createEmailClient } from '@repa/mail';
205
+
206
+ export async function quotedEarlierMessages(apiKey: string, authenticatedSubject: string,
207
+ message: { accountId: string; folderId: string; uidValidity: number; uid: number }) {
208
+ const mail = createEmailClient({ apiKey, subject: authenticatedSubject });
209
+ const reply = await mail.readMessage({ ...message, content: 'new' });
210
+ const ids = new Set(reply.newText.removed.flatMap(region => region.messageId ? [region.messageId] : []));
211
+ if (ids.size === 0) return [];
212
+ const thread = await mail.readConversation({ ...message, cursor: '', limit: 50 });
213
+ return thread.messages.filter(earlier => ids.has(earlier.id)).map(earlier => ({ id: earlier.id, from: earlier.from, text: earlier.chat.text }));
214
+ }
215
+ ```
216
+
217
+ A conversation page holds its newest 50 messages; continue with `earlier` as
218
+ the cursor to reach older ones.
219
+
220
+ ## Limits and errors
221
+
222
+ - 60 requests per minute per integration; workspace sending/storage allowances also apply.
223
+ - 50 recipient entries before deduplication; at most 20 attachments.
224
+ - Encoded outgoing message: 26.2 MB (26,214,400 bytes); sending JSON: 35.0 MB
225
+ (34,968,920 bytes). No separate attachment-byte cap.
226
+ - Text/HTML each: 1.05 MB (1,048,576 bytes).
227
+ - Mailbox discovery: 100 per page; message/conversation lists: 20 per page.
228
+ - Public reads: 10 seconds; uploads: 40 seconds. SDK timeout: 45 seconds by
229
+ default, at most 120 seconds. Options accept `signal`, `timeoutMs`, `subject`.
230
+ - Initial lifetime journal: 10,000 distinct send keys per workspace; full returns
231
+ `LIMIT`, while exact retries keep their slot.
232
+
233
+ `EmailError` has closed `code` and optional `status`, `requestId`,
234
+ `retryAfterSeconds`, `idempotencyKey`, `operationId`. Size errors preserve
235
+ `limitBytes`, `attachmentBytes`, `attachmentCapacityBytes` when supplied.
236
+ `TIMEOUT`, `CONNECTION`, `ABORTED` never prove rollback. Mutations are never
237
+ retried automatically; redirects are refused. Inject `fetch` for your transport.
238
+
239
+ Full guide: [server SDK](../../solutions/email/docs/developer/mail-sdk.md) and
240
+ [mail HTTP API](../../solutions/email/docs/developer/mail-api.md). The source public route
241
+ manifest is `scripts/public-api-contract/mail-contract.mjs`; package exports
242
+ and current declarations define the available client. Historical
243
+ [send/webhook](https://github.com/devcited-labs/repa/blob/main/solutions/email/docs/public-api-acceptance-20261018.md)
244
+ and [own-IAM](https://github.com/devcited-labs/repa/blob/main/solutions/email/docs/headless-acceptance-20261018.md)
245
+ records qualify their dated contracts, not this unreleased source.
@@ -0,0 +1,7 @@
1
+ export { j as EmailAttachment, a as EmailClientOptions, m as EmailDomainSendScope, l as EmailDomainSender, h as EmailError, q as EmailEvent, f as EmailEventPage, p as EmailEventType, k as EmailExactSender, o as EmailFeedbackType, c as EmailMessage, E as EmailRequestOptions, d as EmailSendOptions, b as EmailSender, e as EmailSubmission, n as EmailSubmissionState, g as EmailWebhookEvent } from './errors-VxeL4C8r.js';
2
+
3
+ declare function createEmailClient(): never;
4
+ declare function createMailTransport(): never;
5
+ declare function verifyEmailWebhook(): never;
6
+
7
+ export { createEmailClient, createMailTransport, verifyEmailWebhook };
@@ -0,0 +1,14 @@
1
+ export { EmailError } from './chunk-XW4CRZRY.js';
2
+
3
+ // src/browser-denied.ts
4
+ function createEmailClient() {
5
+ throw new Error("@repa/mail is server-only. Keep integration keys in your backend.");
6
+ }
7
+ function createMailTransport() {
8
+ throw new Error("@repa/mail is server-only. Keep integration keys in your backend.");
9
+ }
10
+ function verifyEmailWebhook() {
11
+ throw new Error("Webhook verification belongs in your backend.");
12
+ }
13
+
14
+ export { createEmailClient, createMailTransport, verifyEmailWebhook };