@repa/mail 0.1.0-alpha.20 → 0.1.0-alpha.22

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
@@ -5,12 +5,13 @@ Node 22 and Node 24. Root exports reject browsers/workers. `/contracts` is
5
5
  browser-safe. This package uses the repa evaluation licence; no public
6
6
  production SLA or stable production-use terms are promised.
7
7
 
8
- Published on npm: **0.1.0-alpha.19** on the `alpha` channel (first publication
9
- 0.1.0-alpha.18 on 2026-11-08, EMAIL-D226). Pin the exact version; a matching mail service
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.22** candidate, not yet published;
10
+ new-text reads below arrive in 0.1.0-alpha.21. Pin the exact version; a matching mail service
10
11
  deployment is qualified separately.
11
12
 
12
13
  ```sh
13
- npm install @repa/mail@0.1.0-alpha.19
14
+ npm install @repa/mail@0.1.0-alpha.20
14
15
  ```
15
16
 
16
17
  This package was named `@repa/email-server` until 0.1.0-alpha.17 (EMAIL-D226).
@@ -145,6 +146,77 @@ for integration subjects. Rotation preserves ownership, but queued first dispatc
145
146
  still checks the original key; keep it valid until its work drains. Revocation
146
147
  cannot recall provider-accepted mail.
147
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
+
148
220
  ## Limits and errors
149
221
 
150
222
  - 60 requests per minute per integration; workspace sending/storage allowances also apply.
@@ -1,4 +1,4 @@
1
- export { j as EmailAttachment, E 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, a as EmailRequestOptions, d as EmailSendOptions, b as EmailSender, e as EmailSubmission, n as EmailSubmissionState, g as EmailWebhookEvent } from './errors-B_W1C1Hu.js';
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
2
 
3
3
  declare function createEmailClient(): never;
4
4
  declare function createMailTransport(): never;
@@ -213,6 +213,48 @@ var MailError = class extends Error {
213
213
  this.name = "MailError";
214
214
  }
215
215
  };
216
+ var readContent = z.enum(["full", "new"]);
217
+ var newTextOutcome = z.enum(["cut", "whole", "unreadable"]);
218
+ var newTextConfidence = z.enum(["proven", "structural", "none"]);
219
+ var newTextSignatureReason = z.enum(["", "rfc3676_delimiter", "html_signature", "sender_learned"]);
220
+ var newTextRemovedKind = z.enum(["quote", "forward_header", "signature"]);
221
+ var newTextRemoved = z.object({
222
+ kind: newTextRemovedKind,
223
+ messageId: z.uuid().nullable(),
224
+ headerId: z.string().min(1).max(998).nullable(),
225
+ bytes: z.number().int().nonnegative()
226
+ }).strict();
227
+ var newTextReason = z.string().regex(/^[a-z0-9_]*$/).max(32);
228
+ var newTextInfo = z.object({
229
+ outcome: newTextOutcome,
230
+ confidence: newTextConfidence,
231
+ reason: newTextReason,
232
+ extractorVersion: z.number().int().min(1).max(65535),
233
+ fullTextBytes: z.number().int().nonnegative(),
234
+ signatureReason: newTextSignatureReason,
235
+ removed: z.array(newTextRemoved).max(8)
236
+ }).strict();
237
+ var unreadNewText = z.object({
238
+ outcome: z.literal(""),
239
+ confidence: z.literal(""),
240
+ reason: z.literal(""),
241
+ extractorVersion: z.literal(0),
242
+ fullTextBytes: z.literal(0),
243
+ signatureReason: z.literal(""),
244
+ removed: z.array(newTextRemoved).max(0)
245
+ }).strict();
246
+ var newTextMessage = z.object({
247
+ entry,
248
+ headers: message.shape.headers,
249
+ text: message.shape.text,
250
+ signature: z.string().max(1024),
251
+ attachments: message.shape.attachments,
252
+ warnings: message.shape.warnings,
253
+ incomplete: z.boolean(),
254
+ newText: newTextInfo
255
+ }).strict();
256
+
257
+ // src/contracts/conversations.ts
216
258
  var uuid3 = z.string().uuid();
217
259
  var uint2 = z.number().int().min(1).max(4294967295);
218
260
  var count = z.number().int().nonnegative();
@@ -245,7 +287,8 @@ var chatText = z.object({
245
287
  text: z.string().max(16384),
246
288
  quoted: z.boolean(),
247
289
  signature: z.string().max(1024),
248
- truncated: z.boolean()
290
+ truncated: z.boolean(),
291
+ newText: z.union([newTextInfo, unreadNewText])
249
292
  }).strict();
250
293
  var conversationMessage = z.object({
251
294
  id: uuid3,
@@ -449,7 +492,14 @@ var headlessOperations = {
449
492
  mailboxes: operation("mailboxes/discover", "mailboxes", z.object({ after: uuid5.optional(), limit: z.number().int().min(1).max(100) }).strict(), mailboxPage),
450
493
  open: operation("mailboxes/open", "open", account2, inbox, { responseBytes: 14 * MiB }),
451
494
  list: operation("messages/list", "list", location.extend({ before: z.number().int().min(0).max(4294967295), limit: z.number().int().min(1).max(20) }).strict(), entries, { responseBytes: 14 * MiB }),
452
- read: operation("messages/read", "read", messageLocation, message, { responseBytes: 14 * MiB }),
495
+ /** `content: 'new'` answers what the sender wrote without the quoted chain (EMAIL-D240); default `full`. */
496
+ read: operation(
497
+ "messages/read",
498
+ "read",
499
+ messageLocation.extend({ content: readContent.optional() }).strict(),
500
+ z.union([message, newTextMessage]),
501
+ { responseBytes: 14 * MiB }
502
+ ),
453
503
  conversations: operation("conversations/list", "conversations", location.extend({
454
504
  cursor: conversationCursor,
455
505
  limit: z.number().int().min(1).max(20)
@@ -506,7 +556,52 @@ var headlessOperations = {
506
556
  { requestBytes: RULES_REQUEST_BYTES, responseBytes: RULES_RESPONSE_BYTES, revision: true }
507
557
  )
508
558
  };
509
- var uuid6 = z.string().uuid();
559
+ var MiB2 = 1024 * 1024;
560
+ var NIL_UUID = "00000000-0000-0000-0000-000000000000";
561
+ var uuid6 = z.uuid().refine((value) => value !== NIL_UUID);
562
+ var MAXIMUM_RECEIVED_SUBSCRIPTIONS = 100;
563
+ var accountIds = z.array(uuid6).min(1).max(MAXIMUM_RECEIVED_SUBSCRIPTIONS).refine((ids) => new Set(ids.map((id) => id.toLowerCase())).size === ids.length, { message: "accountIds must be distinct" });
564
+ var receivedSubscriptions = z.object({ accountIds: z.array(z.uuid()).max(MAXIMUM_RECEIVED_SUBSCRIPTIONS) }).strict();
565
+ var receivedHeaders = message.shape.headers.extend({
566
+ date: z.string().max(512).optional(),
567
+ listId: z.string().max(2048).optional(),
568
+ autoSubmitted: z.string().max(512).optional(),
569
+ /** `X-Repa-Flow-Run`: the flow run that sent the message (FLOWS-D005 loop guard). */
570
+ repaFlowRun: z.string().max(512).optional()
571
+ }).strict();
572
+ var receivedMessage = message.extend({ headers: receivedHeaders, location: conversationLocation }).strict();
573
+ var receivedNewTextMessage = newTextMessage.extend({ headers: receivedHeaders, location: conversationLocation }).strict();
574
+ var actorId = z.string().min(1).max(256).regex(/^[^\u0000-\u001f\u007f]+$/);
575
+ var personMailboxAccess = z.object({ readable: z.array(uuid6).max(MAXIMUM_RECEIVED_SUBSCRIPTIONS) }).strict();
576
+ function platformOperation(internal, input, output, responseBytes = MiB2) {
577
+ return { internal, input, output, responseBytes };
578
+ }
579
+ var platformOperations = {
580
+ /**
581
+ * Adds mailboxes; each needs a current read grant, all or nothing. A mailbox without one, removed or unknown answers
582
+ * the same DENIED as a refused or unconfirmed admission (mail never says whether a mailbox exists). More than 100
583
+ * in all is LIMIT.
584
+ */
585
+ receivedSubscribe: platformOperation("received-subscribe", z.object({ accountIds }).strict(), receivedSubscriptions),
586
+ /** Lists the subscribed mailboxes; it needs admission only, so DENIED here is an admission answer. */
587
+ receivedSubscriptions: platformOperation("received-subscriptions", z.object({}).strict(), receivedSubscriptions),
588
+ /** Removes mailboxes; needs no grant, and removing an absent subscription changes nothing. */
589
+ receivedUnsubscribe: platformOperation("received-unsubscribe", z.object({ accountIds }).strict(), receivedSubscriptions),
590
+ /** Reads a message by `{accountId, messageId}` under the read grant; it never downloads a part. Default `full`. */
591
+ receivedRead: platformOperation(
592
+ "read",
593
+ z.object({ accountId: uuid6, messageId: uuid6, content: readContent.optional() }).strict(),
594
+ z.union([receivedMessage, receivedNewTextMessage]),
595
+ 14 * MiB2
596
+ ),
597
+ /**
598
+ * Which of 1–100 mailboxes a named person may read now (EMAIL-D250): their current Read right, answered only within
599
+ * mailboxes the integration itself may read, so any other mailbox, removed or unknown, reads as not readable. It
600
+ * answers a question about the person and never acts as them (EMAIL-D080 stands); DENIED is an admission answer.
601
+ */
602
+ personMailboxAccess: platformOperation("person-mailbox-access", z.object({ actorId, accountIds }).strict(), personMailboxAccess)
603
+ };
604
+ var uuid7 = z.string().uuid();
510
605
  var uint4 = z.number().int().min(1).max(4294967295);
511
606
  var count2 = z.number().int().nonnegative();
512
607
  var time = z.string();
@@ -619,24 +714,24 @@ var sentDeliveryStatus = z.object({
619
714
  timeline: z.array(deliveryEvent).max(50),
620
715
  timelineComplete: z.boolean()
621
716
  }).strict();
622
- var sentDeliveryLocation = z.object({ accountId: uuid6, folderId: uuid6, uidValidity: uint4, uid: uint4 }).strict();
717
+ var sentDeliveryLocation = z.object({ accountId: uuid7, folderId: uuid7, uidValidity: uint4, uid: uint4 }).strict();
623
718
  var sentDelivery = z.object({ status: sentDeliveryStatus.nullable() }).strict();
624
719
  var sentDeliveriesLocation = z.object({
625
- accountId: uuid6,
626
- folderId: uuid6,
720
+ accountId: uuid7,
721
+ folderId: uuid7,
627
722
  uidValidity: uint4,
628
723
  uids: z.array(uint4).min(1).max(MAXIMUM_DELIVERY_BATCH)
629
724
  }).strict();
630
725
  var sentDeliveries = z.object({
631
726
  messages: z.array(z.object({ uid: uint4, summary: deliverySummary.nullable() }).strict()).max(MAXIMUM_DELIVERY_BATCH)
632
727
  }).strict();
633
- var uuid7 = z.string().uuid();
728
+ var uuid8 = z.string().uuid();
634
729
  var MAXIMUM_SIGNATURES = 100;
635
730
  var MAXIMUM_SIGNATURE_BYTES = 2048;
636
731
  var MAXIMUM_SIGNATURE_LINES = 12;
637
732
  var signaturePlacement = z.enum(["above", "below"]);
638
733
  var signature = z.object({
639
- addressId: uuid7,
734
+ addressId: uuid8,
640
735
  address: z.string().max(320),
641
736
  text: z.string().max(MAXIMUM_SIGNATURE_BYTES),
642
737
  format: composeFormat.refine((value) => new TextEncoder().encode(JSON.stringify(value)).length <= 16384).optional(),
@@ -646,21 +741,21 @@ var signature = z.object({
646
741
  }).strict();
647
742
  var signaturePage = z.object({ signatures: z.array(signature).max(MAXIMUM_SIGNATURES), complete: z.boolean() }).strict();
648
743
  var signatureSave = z.object({
649
- operationId: uuid7,
650
- addressId: uuid7,
744
+ operationId: uuid8,
745
+ addressId: uuid8,
651
746
  text: z.string().max(MAXIMUM_SIGNATURE_BYTES),
652
747
  format: composeFormat.refine((value) => new TextEncoder().encode(JSON.stringify(value)).length <= 16384).optional(),
653
748
  placement: signaturePlacement,
654
749
  expectedRevision: z.number().int().nonnegative()
655
750
  }).strict();
656
751
  var signatureSaved = z.object({ signature }).strict();
657
- var uuid8 = z.string().uuid();
752
+ var uuid9 = z.string().uuid();
658
753
  var uint5 = z.number().int().min(1).max(4294967295);
659
754
  var address = z.string().min(1).max(320);
660
755
  var MAXIMUM_HEADER_SAMPLE = 400;
661
756
  var headerSampleInput = z.object({
662
- accountId: uuid8,
663
- folderId: uuid8.optional(),
757
+ accountId: uuid9,
758
+ folderId: uuid9.optional(),
664
759
  uidValidity: uint5.optional(),
665
760
  limit: z.number().int().min(1).max(MAXIMUM_HEADER_SAMPLE)
666
761
  }).strict().refine((input) => input.folderId === void 0 === (input.uidValidity === void 0), {
@@ -681,7 +776,7 @@ var headerSampleMessage = z.object({
681
776
  date: z.string().max(40).nullable()
682
777
  }).strict();
683
778
  var headerSample = z.object({ messages: z.array(headerSampleMessage).max(MAXIMUM_HEADER_SAMPLE), hasMore: z.boolean() }).strict();
684
- var uuid9 = z.uuid();
779
+ var uuid10 = z.uuid();
685
780
  var time2 = z.iso.datetime({ offset: true });
686
781
  var count3 = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
687
782
  var folderName2 = z.string().min(1).max(1024);
@@ -732,9 +827,9 @@ var importSourceInput = z.object({
732
827
  username: z.string().min(1).max(320),
733
828
  password: z.string().min(1).max(1024)
734
829
  }).strict();
735
- var importBegin = z.object({ operationId: uuid9, accountId: uuid9, source: importSourceInput }).strict();
736
- var importRef = z.object({ accountId: uuid9, importId: uuid9 }).strict();
737
- var importList = z.object({ accountId: uuid9 }).strict();
830
+ var importBegin = z.object({ operationId: uuid10, accountId: uuid10, source: importSourceInput }).strict();
831
+ var importRef = z.object({ accountId: uuid10, importId: uuid10 }).strict();
832
+ var importList = z.object({ accountId: uuid10 }).strict();
738
833
  var importFolderChoice = z.object({
739
834
  ordinal: z.number().int().min(0).max(MAXIMUM_IMPORT_FOLDERS - 1),
740
835
  include: z.boolean(),
@@ -744,9 +839,9 @@ var importConfirm = importRef.extend({
744
839
  folders: z.array(importFolderChoice).min(1).max(MAXIMUM_IMPORT_FOLDERS)
745
840
  }).strict();
746
841
  var importUploadBegin = z.object({
747
- operationId: uuid9,
748
- accountId: uuid9,
749
- folderId: uuid9,
842
+ operationId: uuid10,
843
+ accountId: uuid10,
844
+ folderId: uuid10,
750
845
  fileName: z.string().min(1).max(255),
751
846
  format: importFileFormat,
752
847
  bytes: z.number().int().min(1).max(MAXIMUM_IMPORT_UPLOAD_BYTES)
@@ -776,14 +871,14 @@ var importFile = z.object({
776
871
  receivedBytes: count3
777
872
  }).strict();
778
873
  var importSummary = z.object({
779
- id: uuid9,
780
- accountId: uuid9,
874
+ id: uuid10,
875
+ accountId: uuid10,
781
876
  kind: importKind,
782
877
  state: importState,
783
878
  source: importSource.nullable(),
784
879
  file: importFile.nullable(),
785
880
  /** The destination folder of an upload. */
786
- folderId: uuid9.nullable(),
881
+ folderId: uuid10.nullable(),
787
882
  createdAt: time2,
788
883
  startedAt: time2.nullable(),
789
884
  finishedAt: time2.nullable(),
@@ -830,15 +925,15 @@ var importErrorCode = z.enum([
830
925
  "UPLOAD_TOO_LARGE",
831
926
  "UPLOAD_DAY_LIMIT"
832
927
  ]);
833
- var uuid10 = z.uuid();
928
+ var uuid11 = z.uuid();
834
929
  var time3 = z.iso.datetime({ offset: true });
835
930
  var count4 = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
836
931
  var MAXIMUM_EXPORT_FOLDERS = 1024;
837
932
  var EXPORT_MANIFEST_NAME = "manifest.json";
838
933
  var exportStart = z.object({
839
- accountId: uuid10,
934
+ accountId: uuid11,
840
935
  /** null exports every folder the person may read. */
841
- folderIds: z.array(uuid10).min(1).max(MAXIMUM_EXPORT_FOLDERS).nullable()
936
+ folderIds: z.array(uuid11).min(1).max(MAXIMUM_EXPORT_FOLDERS).nullable()
842
937
  }).strict();
843
938
  var exportFlag = z.enum(["seen", "answered", "flagged", "draft", "deleted"]);
844
939
  var exportManifestMessage = z.object({
@@ -858,7 +953,7 @@ var exportManifestFolder = z.object({
858
953
  }).strict();
859
954
  var exportManifest = z.object({
860
955
  version: z.literal(1),
861
- mailbox: z.object({ accountId: uuid10, address: z.string().min(1).max(320).nullable() }).strict(),
956
+ mailbox: z.object({ accountId: uuid11, address: z.string().min(1).max(320).nullable() }).strict(),
862
957
  exportedAt: time3,
863
958
  folders: z.array(exportManifestFolder).max(MAXIMUM_EXPORT_FOLDERS)
864
959
  }).strict();
@@ -876,4 +971,64 @@ var inboxCountsInput = account3.extend({ folderIds: z.array(z.uuid()).min(1).max
876
971
  var inboxFolderCount = z.object({ folderId: z.uuid(), unseen: z.number().int().nonnegative(), total: z.number().int().nonnegative(), uidNext: z.number().int().min(1).max(4294967295), uidValidity: z.number().int().min(1).max(4294967295) }).strict();
877
972
  var inboxCounts = inboxPosition.extend({ folders: z.array(inboxFolderCount).max(200) }).strict();
878
973
 
879
- export { EXPORT_MANIFEST_NAME, IMPORT_UPLOAD_PART_BYTES, MAXIMUM_DELIVERY_BATCH, MAXIMUM_EXPORT_FOLDERS, MAXIMUM_HEADER_SAMPLE, MAXIMUM_IMPORTS_KEPT, MAXIMUM_IMPORT_FAILURES_SHOWN, MAXIMUM_IMPORT_FOLDERS, MAXIMUM_IMPORT_MESSAGE_BYTES, MAXIMUM_IMPORT_UPLOAD_BYTES, MAXIMUM_IMPORT_UPLOAD_DAY_BYTES, MAXIMUM_RULE_CONDITIONS, MAXIMUM_RULE_ITEMS, MAXIMUM_RULE_PROBLEMS, MAXIMUM_RULE_SCRIPT_BYTES, MAXIMUM_SEND_BASE64_BYTES, MAXIMUM_SEND_BODY_BYTES, MAXIMUM_SEND_BYTES, MAXIMUM_SIGNATURES, MAXIMUM_SIGNATURE_BYTES, MAXIMUM_SIGNATURE_LINES, MailError, RULES_REQUEST_BYTES, RULES_RESPONSE_BYTES, accountStorage, accountStorageMaximumBytes, attachment, changed, chatText, cleanupInput, cleanupResult, composeFormat, conversation, conversationCursor, conversationLocation, conversationMessage, conversationPage, conversationRow, deliveryEvent, deliveryEventName, deliveryMeaning, deliveryReason, deliveryState, deliveryStates, deliverySummary, download, draftContent, draftInputs, draftList, draftLocation, draftSchemas, entries, entry, exportFlag, exportManifest, exportManifestFolder, exportManifestMessage, exportStart, finishedImportStates, folder, headerSample, headerSampleInput, headerSampleMessage, headlessOperations, heldReason, importAnswer, importBegin, importConfirm, importDetail, importErrorCode, importFailureReason, importFile, importFileFormat, importFolderChoice, importKind, importList, importListAnswer, importMessageFailure, importPlanFolder, importProgress, importRef, importSecurity, importSource, importSourceInput, importSpecialUse, importState, importStates, importSummary, importUploadBegin, importUploadPart, importWaitReason, inbox, inboxCounts, inboxCountsInput, inboxFolderCount, inboxPosition, inboxWaitInput, mailbox, mailboxPage, mailboxRules, message, participant, receipt, recipientDelivery, renamedFolder, rule, ruleActions, ruleCondition, ruleForward, ruleItem, ruleItemInput, ruleVacation, rulesChecked, rulesInputs, rulesNotice, rulesProblem, rulesSaved, safeComposeLink, savedDraft, sender, sentDeliveries, sentDeliveriesLocation, sentDelivery, sentDeliveryLocation, sentDeliveryStatus, serviceAccountStorage, signature, signaturePage, signaturePlacement, signatureSave, signatureSaved, validComposeFormat };
974
+ // src/contracts/reply-recipients.ts
975
+ function addressList(header3) {
976
+ const text3 = typeof header3 === "string" ? header3 : header3.join(", ");
977
+ const items2 = [];
978
+ let current = "", quoted = false, angle = false, comment = 0;
979
+ for (let index2 = 0; index2 < text3.length; index2++) {
980
+ const char = text3[index2];
981
+ if (char === "\\" && quoted) {
982
+ current += char + (text3[++index2] ?? "");
983
+ continue;
984
+ }
985
+ if (char === '"' && !angle && !comment) quoted = !quoted;
986
+ else if (!quoted && char === "(") comment++;
987
+ else if (!quoted && char === ")" && comment) comment--;
988
+ else if (!quoted && !comment && char === "<") angle = true;
989
+ else if (!quoted && !comment && char === ">") angle = false;
990
+ if (!quoted && !angle && !comment && (char === "," || char === ";")) {
991
+ items2.push(current);
992
+ current = "";
993
+ continue;
994
+ }
995
+ if (!quoted && !angle && !comment && char === ":") {
996
+ current = "";
997
+ continue;
998
+ }
999
+ current += char;
1000
+ }
1001
+ items2.push(current);
1002
+ return items2.map((item) => (/<([^<>]*)>/.exec(item)?.[1] ?? item.replace(/\([^)]*\)/g, "")).trim()).filter((address2) => /^[^@\s]+@[^@\s]+$/.test(address2));
1003
+ }
1004
+ function replyRecipients(original, own, answer) {
1005
+ const mine = new Set(own.map((address2) => address2.toLowerCase()));
1006
+ const seen = /* @__PURE__ */ new Set();
1007
+ const removed = [];
1008
+ const keep = (addresses, reason) => addresses.flatMap((address2) => {
1009
+ const key = address2.toLowerCase();
1010
+ if (mine.has(key)) {
1011
+ removed.push({ address: address2, reason: "own", was: reason });
1012
+ return [];
1013
+ }
1014
+ if (seen.has(key)) {
1015
+ removed.push({ address: address2, reason: "duplicate", was: reason });
1016
+ return [];
1017
+ }
1018
+ seen.add(key);
1019
+ return [{ address: address2, reason }];
1020
+ });
1021
+ const fromHere = addressList(original.from).some((address2) => mine.has(address2.toLowerCase()));
1022
+ const replyTo = original.replyTo ? addressList(original.replyTo) : [];
1023
+ const answerTo = fromHere ? [] : replyTo.length ? keep(replyTo, "reply_to") : keep(addressList(original.from), "from");
1024
+ if (answer === "reply") return { to: fromHere ? keep(addressList(original.to), "to") : answerTo, cc: [], removed };
1025
+ let to = [...answerTo, ...keep(addressList(original.to), "to")];
1026
+ let cc = keep(addressList(original.cc), "cc");
1027
+ if (!to.length) [to, cc] = [cc, []];
1028
+ return { to, cc, removed };
1029
+ }
1030
+ function addressHeader(recipients) {
1031
+ return recipients.map((recipient) => recipient.address).join(", ");
1032
+ }
1033
+
1034
+ export { EXPORT_MANIFEST_NAME, IMPORT_UPLOAD_PART_BYTES, MAXIMUM_DELIVERY_BATCH, MAXIMUM_EXPORT_FOLDERS, MAXIMUM_HEADER_SAMPLE, MAXIMUM_IMPORTS_KEPT, MAXIMUM_IMPORT_FAILURES_SHOWN, MAXIMUM_IMPORT_FOLDERS, MAXIMUM_IMPORT_MESSAGE_BYTES, MAXIMUM_IMPORT_UPLOAD_BYTES, MAXIMUM_IMPORT_UPLOAD_DAY_BYTES, MAXIMUM_RECEIVED_SUBSCRIPTIONS, MAXIMUM_RULE_CONDITIONS, MAXIMUM_RULE_ITEMS, MAXIMUM_RULE_PROBLEMS, MAXIMUM_RULE_SCRIPT_BYTES, MAXIMUM_SEND_BASE64_BYTES, MAXIMUM_SEND_BODY_BYTES, MAXIMUM_SEND_BYTES, MAXIMUM_SIGNATURES, MAXIMUM_SIGNATURE_BYTES, MAXIMUM_SIGNATURE_LINES, MailError, RULES_REQUEST_BYTES, RULES_RESPONSE_BYTES, accountStorage, accountStorageMaximumBytes, addressHeader, addressList, attachment, changed, chatText, cleanupInput, cleanupResult, composeFormat, conversation, conversationCursor, conversationLocation, conversationMessage, conversationPage, conversationRow, deliveryEvent, deliveryEventName, deliveryMeaning, deliveryReason, deliveryState, deliveryStates, deliverySummary, download, draftContent, draftInputs, draftList, draftLocation, draftSchemas, entries, entry, exportFlag, exportManifest, exportManifestFolder, exportManifestMessage, exportStart, finishedImportStates, folder, headerSample, headerSampleInput, headerSampleMessage, headlessOperations, heldReason, importAnswer, importBegin, importConfirm, importDetail, importErrorCode, importFailureReason, importFile, importFileFormat, importFolderChoice, importKind, importList, importListAnswer, importMessageFailure, importPlanFolder, importProgress, importRef, importSecurity, importSource, importSourceInput, importSpecialUse, importState, importStates, importSummary, importUploadBegin, importUploadPart, importWaitReason, inbox, inboxCounts, inboxCountsInput, inboxFolderCount, inboxPosition, inboxWaitInput, mailbox, mailboxPage, mailboxRules, message, newTextConfidence, newTextInfo, newTextMessage, newTextOutcome, newTextReason, newTextRemoved, newTextRemovedKind, newTextSignatureReason, participant, personMailboxAccess, platformOperations, readContent, receipt, receivedHeaders, receivedMessage, receivedNewTextMessage, receivedSubscriptions, recipientDelivery, renamedFolder, replyRecipients, rule, ruleActions, ruleCondition, ruleForward, ruleItem, ruleItemInput, ruleVacation, rulesChecked, rulesInputs, rulesNotice, rulesProblem, rulesSaved, safeComposeLink, savedDraft, sender, sentDeliveries, sentDeliveriesLocation, sentDelivery, sentDeliveryLocation, sentDeliveryStatus, serviceAccountStorage, signature, signaturePage, signaturePlacement, signatureSave, signatureSaved, unreadNewText, validComposeFormat };