@happyvertical/smrt-messages 0.62.12 → 0.62.14

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.
Files changed (66) hide show
  1. package/AGENTS.md +13 -1
  2. package/agents/mail-search.md +40 -0
  3. package/agents/send-approval.md +101 -0
  4. package/dist/access.d.ts +33 -1
  5. package/dist/access.d.ts.map +1 -1
  6. package/dist/chunks/{AttachmentCollection-gv5YpGPo.js → AttachmentCollection-C0K7lITr.js} +4 -4
  7. package/dist/chunks/{AttachmentCollection-gv5YpGPo.js.map → AttachmentCollection-C0K7lITr.js.map} +1 -1
  8. package/dist/chunks/{Email---ifczUW.js → Email-DWF2VG_4.js} +11 -6
  9. package/dist/chunks/Email-DWF2VG_4.js.map +1 -0
  10. package/dist/chunks/EmailAccountCollection-OLTzu2T0.js +2472 -0
  11. package/dist/chunks/EmailAccountCollection-OLTzu2T0.js.map +1 -0
  12. package/dist/chunks/{EmailCollection-CHINTmyA.js → EmailCollection-8HeBXd0F.js} +18 -3
  13. package/dist/chunks/EmailCollection-8HeBXd0F.js.map +1 -0
  14. package/dist/chunks/{EmailFolder-C_H8u6bS.js → EmailFolder-Cl4sKRMB.js} +6 -6
  15. package/dist/chunks/{EmailFolder-C_H8u6bS.js.map → EmailFolder-Cl4sKRMB.js.map} +1 -1
  16. package/dist/chunks/{EmailFolderCollection-B83qLC-c.js → EmailFolderCollection-L0na2e1L.js} +2 -2
  17. package/dist/chunks/{EmailFolderCollection-B83qLC-c.js.map → EmailFolderCollection-L0na2e1L.js.map} +1 -1
  18. package/dist/chunks/{EmailSender-B-Rtq9du.js → EmailSender-BiAI0LWU.js} +8 -1
  19. package/dist/chunks/EmailSender-BiAI0LWU.js.map +1 -0
  20. package/dist/chunks/{Message-Ccqg6BLO.js → Message-CuvACyOv.js} +76 -9
  21. package/dist/chunks/Message-CuvACyOv.js.map +1 -0
  22. package/dist/chunks/{MessageCollection-BnHCLi1Q.js → MessageCollection-DOErodD3.js} +2 -2
  23. package/dist/chunks/{MessageCollection-BnHCLi1Q.js.map → MessageCollection-DOErodD3.js.map} +1 -1
  24. package/dist/chunks/{MessagingEndpointCollection-CHzGhkeL.js → MessagingEndpointCollection-CE3kQKQU.js} +2 -2
  25. package/dist/chunks/{MessagingEndpointCollection-CHzGhkeL.js.map → MessagingEndpointCollection-CE3kQKQU.js.map} +1 -1
  26. package/dist/collections/CorrespondentCollection.d.ts +6 -0
  27. package/dist/collections/CorrespondentCollection.d.ts.map +1 -0
  28. package/dist/collections/EmailCollection.d.ts +14 -0
  29. package/dist/collections/EmailCollection.d.ts.map +1 -1
  30. package/dist/connect.js +1 -1
  31. package/dist/index.d.ts +8 -2
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +940 -13
  34. package/dist/index.js.map +1 -1
  35. package/dist/mail-drafts.d.ts +63 -0
  36. package/dist/mail-drafts.d.ts.map +1 -0
  37. package/dist/mail-triage.d.ts.map +1 -1
  38. package/dist/manifest.json +919 -40
  39. package/dist/models/Correspondent.d.ts +63 -0
  40. package/dist/models/Correspondent.d.ts.map +1 -0
  41. package/dist/models/Email.d.ts.map +1 -1
  42. package/dist/models/EmailAccount.d.ts +8 -1
  43. package/dist/models/EmailAccount.d.ts.map +1 -1
  44. package/dist/models/Message.d.ts +9 -0
  45. package/dist/models/Message.d.ts.map +1 -1
  46. package/dist/send-approval.d.ts +275 -0
  47. package/dist/send-approval.d.ts.map +1 -0
  48. package/dist/senders/EmailSender.d.ts.map +1 -1
  49. package/dist/services/CorrespondentService.d.ts +113 -0
  50. package/dist/services/CorrespondentService.d.ts.map +1 -0
  51. package/dist/services/MailSearchService.d.ts +127 -0
  52. package/dist/services/MailSearchService.d.ts.map +1 -0
  53. package/dist/smrt-knowledge.json +392 -9
  54. package/dist/smrt-knowledge.okf.md +14 -3
  55. package/dist/svelte/components/RecipientInput.svelte +54 -0
  56. package/dist/svelte/components/RecipientInput.svelte.d.ts +6 -0
  57. package/dist/svelte/components/RecipientInput.svelte.d.ts.map +1 -1
  58. package/dist/types.d.ts +20 -0
  59. package/dist/types.d.ts.map +1 -1
  60. package/package.json +12 -11
  61. package/dist/chunks/Email---ifczUW.js.map +0 -1
  62. package/dist/chunks/EmailAccountCollection-DkvT4tdP.js +0 -1992
  63. package/dist/chunks/EmailAccountCollection-DkvT4tdP.js.map +0 -1
  64. package/dist/chunks/EmailCollection-CHINTmyA.js.map +0 -1
  65. package/dist/chunks/EmailSender-B-Rtq9du.js.map +0 -1
  66. package/dist/chunks/Message-Ccqg6BLO.js.map +0 -1
package/dist/index.js CHANGED
@@ -1,16 +1,16 @@
1
- import { A as MESSAGING_PERMISSION_DEFINITIONS, C as mailScopePermission, D as MANAGE_MESSAGE_CREDENTIALS_PERMISSION, E as withoutListBounds, F as seedMessagesRolePermissions, M as assertMessagingPermission, N as ensureMessagingPermissionsRegistered, O as MANAGE_MESSAGE_ROUTES_PERMISSION, P as messagingPrincipalFromPermissions, S as learnMailAccessOptions, T as runWithMailSystemAccess, _ as deniedMailAccountIds, b as inMailSystemAccess, c as MAIL_ACCOUNT_RESOURCE_TYPE, d as MailAccessService, f as assertHydratedMailAccess, g as decideMailAccess, h as configureMailAccess, i as AccountCollection, j as SEND_MESSAGES_PERMISSION, k as MESSAGES_ROLE_PERMISSION_MATRIX, l as MAIL_SCOPES, m as canAccessMailAccount, o as MailWriteBackUnsupportedError, p as assertMailAccess, r as EmailAccount, s as Account, t as EmailAccountCollection, u as MailAccessError, v as getEffectiveMailAccessConfigs, w as resetMailAccess, x as isMailScope, y as getMailAccessConfig } from "./chunks/EmailAccountCollection-DkvT4tdP.js";
1
+ import { A as deniedMailAccountIds, B as runWithMailSystemAccess, C as MailAccessError, D as canAccessMailAccount, E as assertMailAccess, F as isPersonMailPrincipal, G as MESSAGING_PERMISSION_DEFINITIONS, H as MANAGE_MESSAGE_CREDENTIALS_PERMISSION, I as learnMailAccessOptions, J as ensureMessagingPermissionsRegistered, K as SEND_MESSAGES_PERMISSION, L as mailScopePermission, M as getMailAccessConfig, N as inMailSystemAccess, O as configureMailAccess, P as isMailScope, R as resetMailAccess, S as MAIL_SCOPES, T as assertHydratedMailAccess, U as MANAGE_MESSAGE_ROUTES_PERMISSION, V as withoutListBounds, W as MESSAGES_ROLE_PERMISSION_MATRIX, X as seedMessagesRolePermissions, Y as messagingPrincipalFromPermissions, _ as resetMailSendApprovals, b as Account, c as HeldSendError, f as auditMailAction, g as mailSendBindingHash, i as AccountCollection, j as getEffectiveMailAccessConfigs, k as decideMailAccess, l as MailSendApprovalService, m as effectiveAgentSendPolicy, o as MailWriteBackUnsupportedError, p as configureMailSendApprovals, q as assertMessagingPermission, r as EmailAccount, s as APPROVE_HELD_SEND_PERMISSION, t as EmailAccountCollection, v as stampHandledBy, w as MailAccessService, x as MAIL_ACCOUNT_RESOURCE_TYPE, y as threadHandledBy, z as resolveMailPrincipal } from "./chunks/EmailAccountCollection-OLTzu2T0.js";
2
2
  import { buildSqliteRebuildStatements, isDeepStrictEqual, normalizeIdentityEmail, queryGlobal, queryWithGlobals, readNotificationProfile, withSystemContext, withTenant } from "./host.js";
3
- import { r as Attachment, t as AttachmentCollection } from "./chunks/AttachmentCollection-gv5YpGPo.js";
4
- import { t as EmailFolder } from "./chunks/EmailFolder-C_H8u6bS.js";
3
+ import { r as Attachment, t as AttachmentCollection } from "./chunks/AttachmentCollection-C0K7lITr.js";
4
+ import { t as EmailFolder } from "./chunks/EmailFolder-Cl4sKRMB.js";
5
5
  import { d as withProtectedNotificationHandoff, f as PROFILE_NOTIFICATION_POLICY_PREFIX, l as protectedNotificationMetadata, m as profileNotificationPolicy, p as assertNotificationRecipientIdentity, t as ProtectedNotificationHandoffError } from "./chunks/protected-notification-handoff-mvaEZVp7.js";
6
- import { t as Message } from "./chunks/Message-Ccqg6BLO.js";
6
+ import { t as Message } from "./chunks/Message-CuvACyOv.js";
7
7
  import { a as registerMessagingProvider, n as getMessagingProvider, o as ZulipSender, r as listMessagingProviders, s as TelegramSender, t as ensureBuiltinMessagingProvidersRegistered } from "./chunks/providers-Bz_F_ywF.js";
8
- import { t as MessageCollection } from "./chunks/MessageCollection-BnHCLi1Q.js";
9
- import { r as MessagingEndpoint, t as MessagingEndpointCollection } from "./chunks/MessagingEndpointCollection-CHzGhkeL.js";
10
- import { t as Email } from "./chunks/Email---ifczUW.js";
11
- import { t as EmailCollection } from "./chunks/EmailCollection-CHINTmyA.js";
12
- import { t as EmailFolderCollection } from "./chunks/EmailFolderCollection-B83qLC-c.js";
13
- import { t as EmailSender } from "./chunks/EmailSender-B-Rtq9du.js";
8
+ import { t as MessageCollection } from "./chunks/MessageCollection-DOErodD3.js";
9
+ import { r as MessagingEndpoint, t as MessagingEndpointCollection } from "./chunks/MessagingEndpointCollection-CE3kQKQU.js";
10
+ import { t as Email } from "./chunks/Email-DWF2VG_4.js";
11
+ import { t as EmailCollection } from "./chunks/EmailCollection-8HeBXd0F.js";
12
+ import { t as EmailFolderCollection } from "./chunks/EmailFolderCollection-L0na2e1L.js";
13
+ import { t as EmailSender } from "./chunks/EmailSender-BiAI0LWU.js";
14
14
  import { t as SlackSender } from "./chunks/SlackSender-CetlSe6D.js";
15
15
  import { t as TweetSender } from "./chunks/TweetSender-Dw-TDxIB.js";
16
16
  import { GlobalInterceptors, ObjectRegistry, SmrtCollection, SmrtObject, SmrtRecipe, crossPackageRef, detectEngine, field, foreignKey, isUniqueViolationError, smrt, usesEmbeddedRevisionFallback, withEmbeddedWriteQueue } from "@happyvertical/smrt-core";
@@ -98,7 +98,7 @@ function createMailAccessInterceptor() {
98
98
  const row = instance;
99
99
  row.accountId = null;
100
100
  if (!row.messageId || !row.options) return;
101
- const { MessageCollection } = await import("./chunks/MessageCollection-BnHCLi1Q.js").then((n) => n.n);
101
+ const { MessageCollection } = await import("./chunks/MessageCollection-DOErodD3.js").then((n) => n.n);
102
102
  row.accountId = (await runWithMailSystemAccess(async () => (await MessageCollection.create(row.options)).get({ id: row.messageId })))?.accountId || null;
103
103
  },
104
104
  async afterList(className, results, context) {
@@ -153,6 +153,102 @@ function ensureMailAccessEnforcementRegistered() {
153
153
  GlobalInterceptors.register(createMailAccessInterceptor());
154
154
  }
155
155
  //#endregion
156
+ //#region src/mail-drafts.ts
157
+ var MailDraftError = class extends Error {
158
+ status;
159
+ constructor(message, status = 400) {
160
+ super(message);
161
+ this.name = "MailDraftError";
162
+ this.status = status;
163
+ }
164
+ };
165
+ function assertRecipients(value, label) {
166
+ if (value === void 0) return;
167
+ if (!Array.isArray(value) || value.some((entry) => !entry || typeof entry.address !== "string" || !entry.address.includes("@") || entry.name !== void 0 && typeof entry.name !== "string")) throw new MailDraftError(`${label} must be a list of { address, name? }.`);
168
+ }
169
+ var MailDraftService = class {
170
+ constructor(options) {
171
+ this.options = options;
172
+ }
173
+ options;
174
+ async account(accountId) {
175
+ const { EmailAccountCollection } = await import("./chunks/EmailAccountCollection-OLTzu2T0.js").then((n) => n.n);
176
+ const account = await runWithMailSystemAccess(async () => (await EmailAccountCollection.create(withoutListBounds(this.options))).get({ id: accountId }));
177
+ if (!account?.id) throw new MailDraftError("Mail account not found.", 404);
178
+ return account;
179
+ }
180
+ async stored(id) {
181
+ const { EmailCollection } = await import("./chunks/EmailCollection-8HeBXd0F.js").then((n) => n.n);
182
+ return await runWithMailSystemAccess(async () => (await EmailCollection.create(this.options)).get({ id }));
183
+ }
184
+ /** Create or update a draft. Returns the saved draft. */
185
+ async save(input) {
186
+ assertRecipients(input.toAddresses, "toAddresses");
187
+ assertRecipients(input.ccAddresses, "ccAddresses");
188
+ assertRecipients(input.bccAddresses, "bccAddresses");
189
+ const account = await this.account(input.accountId);
190
+ const principal = await resolveMailPrincipal();
191
+ if (principal && account.tenantId && principal.tenantId !== account.tenantId) throw new MailAccessError("draft", "tenant_mismatch");
192
+ await assertMailAccess(account, "draft");
193
+ let draft;
194
+ if (input.draftId) {
195
+ const existing = await this.stored(input.draftId);
196
+ if (!existing || existing.accountId !== account.id) throw new MailDraftError("Draft not found.", 404);
197
+ if (!existing.isDraft || existing.sendStatus !== "draft") throw new MailDraftError("Only an unsent draft can be changed.", 409);
198
+ draft = existing;
199
+ } else if (input.inReplyToMessageId) {
200
+ await assertMailAccess(account, "read");
201
+ const original = await this.stored(input.inReplyToMessageId);
202
+ if (!original || original.accountId !== account.id) throw new MailDraftError("Message not found.", 404);
203
+ draft = original.createReply({ replyAll: input.replyAll === true });
204
+ await draft.initialize();
205
+ } else {
206
+ const { Email: EmailClass } = await import("./chunks/Email-DWF2VG_4.js").then((n) => n.n);
207
+ draft = new (ObjectRegistry.resolveEffectiveConstructor(EmailClass))({
208
+ ...this.options,
209
+ tenantId: account.tenantId,
210
+ accountId: account.id,
211
+ isDraft: true,
212
+ sendStatus: "draft",
213
+ isRead: true,
214
+ toAddresses: "[]",
215
+ ccAddresses: "[]",
216
+ bccAddresses: "[]"
217
+ });
218
+ await draft.initialize();
219
+ }
220
+ if (input.subject !== void 0) draft.subject = input.subject;
221
+ if (input.textBody !== void 0) {
222
+ draft.textBody = input.textBody;
223
+ draft.body = input.textBody;
224
+ }
225
+ if (input.htmlBody !== void 0) draft.htmlBody = input.htmlBody;
226
+ if (input.toAddresses !== void 0) draft.toAddresses = JSON.stringify(input.toAddresses);
227
+ if (input.ccAddresses !== void 0) draft.ccAddresses = JSON.stringify(input.ccAddresses);
228
+ if (input.bccAddresses !== void 0) draft.bccAddresses = JSON.stringify(input.bccAddresses);
229
+ draft.fromAddress = account.email;
230
+ draft.tenantId = account.tenantId;
231
+ draft.accountId = account.id;
232
+ draft.isDraft = true;
233
+ draft.sendStatus = "draft";
234
+ draft.updatedAt = /* @__PURE__ */ new Date();
235
+ stampHandledBy(draft, principal);
236
+ await draft.save();
237
+ await auditMailAction("messages.draft.save", draft);
238
+ return draft;
239
+ }
240
+ /**
241
+ * Send a draft. The account's agent send policy applies: an agent's draft
242
+ * normally comes back with `pendingApproval` and waits for a person.
243
+ */
244
+ async submit(draftId, options) {
245
+ const draft = await this.stored(draftId);
246
+ if (!draft?.accountId || !draft.isDraft) throw new MailDraftError("Draft not found.", 404);
247
+ await assertMailAccess(await this.account(draft.accountId), "draft");
248
+ return await draft.send(options);
249
+ }
250
+ };
251
+ //#endregion
156
252
  //#region src/mail-sync-jobs.ts
157
253
  var MAIL_SYNC_QUEUE = "mail-sync";
158
254
  var CHANGE_FEED_PROVIDERS = ["jmap"];
@@ -199,6 +295,107 @@ async function enqueueDueMailSyncs(accounts, options = {}) {
199
295
  return queued;
200
296
  }
201
297
  //#endregion
298
+ //#region src/models/Correspondent.ts
299
+ var __defProp$12 = Object.defineProperty;
300
+ var __getOwnPropDesc$12 = Object.getOwnPropertyDescriptor;
301
+ var __defNormalProp$12 = (obj, key, value) => key in obj ? __defProp$12(obj, key, {
302
+ enumerable: true,
303
+ configurable: true,
304
+ writable: true,
305
+ value
306
+ }) : obj[key] = value;
307
+ var __decorateClass$12 = (decorators, target, key, kind) => {
308
+ var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc$12(target, key) : target;
309
+ for (var i = decorators.length - 1, decorator; i >= 0; i--) if (decorator = decorators[i]) result = (kind ? decorator(target, key, result) : decorator(result)) || result;
310
+ if (kind && result) __defProp$12(target, key, result);
311
+ return result;
312
+ };
313
+ var __publicField$12 = (obj, key, value) => __defNormalProp$12(obj, typeof key !== "symbol" ? key + "" : key, value);
314
+ var Correspondent = class extends SmrtObject {
315
+ tenantId = "";
316
+ ownerUserId = "";
317
+ address = "";
318
+ /** The most recent name mail used for this address; may be empty. */
319
+ displayName = "";
320
+ /** Messages the owner can read that mention this address. */
321
+ messageCount = 0;
322
+ /** Of those, messages sent by this address. */
323
+ sentCount = 0;
324
+ /** Of those, messages sent to or copied to this address. */
325
+ receivedCount = 0;
326
+ firstContactAt = null;
327
+ lastContactAt = null;
328
+ /** JSON array of mail account ids the address was seen in. */
329
+ accountIds = "[]";
330
+ /**
331
+ * JSON object keyed by mail account id with that account's own sent and
332
+ * received counts, first/last contact, and latest name. The service builds
333
+ * every view from the accounts the viewer can read only; the top-level
334
+ * counts above are totals kept for storage and are never shown on their own.
335
+ */
336
+ accountBreakdown = "{}";
337
+ profileId = null;
338
+ constructor(options = {}) {
339
+ super(options);
340
+ if (options.tenantId !== void 0) this.tenantId = options.tenantId;
341
+ if (options.ownerUserId !== void 0) this.ownerUserId = options.ownerUserId;
342
+ if (options.address !== void 0) this.address = options.address;
343
+ if (options.displayName !== void 0) this.displayName = options.displayName;
344
+ if (options.messageCount !== void 0) this.messageCount = options.messageCount;
345
+ if (options.sentCount !== void 0) this.sentCount = options.sentCount;
346
+ if (options.receivedCount !== void 0) this.receivedCount = options.receivedCount;
347
+ if (options.firstContactAt !== void 0) this.firstContactAt = options.firstContactAt;
348
+ if (options.lastContactAt !== void 0) this.lastContactAt = options.lastContactAt;
349
+ if (options.accountIds !== void 0) this.accountIds = options.accountIds;
350
+ if (options.accountBreakdown !== void 0) this.accountBreakdown = options.accountBreakdown;
351
+ if (options.profileId !== void 0) this.profileId = options.profileId;
352
+ }
353
+ /** Account ids this address was seen in (empty on unreadable JSON). */
354
+ get seenInAccountIds() {
355
+ try {
356
+ const parsed = JSON.parse(this.accountIds || "[]");
357
+ return Array.isArray(parsed) ? parsed.filter((id) => typeof id === "string") : [];
358
+ } catch {
359
+ return [];
360
+ }
361
+ }
362
+ };
363
+ __publicField$12(Correspondent, "__smrtPackage__", "@happyvertical/smrt-messages");
364
+ __decorateClass$12([tenantId()], Correspondent.prototype, "tenantId", 2);
365
+ __decorateClass$12([crossPackageRef("@happyvertical/smrt-users:User", {
366
+ required: true,
367
+ requiredFor: "identity"
368
+ })], Correspondent.prototype, "ownerUserId", 2);
369
+ __decorateClass$12([field({
370
+ required: true,
371
+ requiredFor: "identity"
372
+ })], Correspondent.prototype, "address", 2);
373
+ __decorateClass$12([crossPackageRef("@happyvertical/smrt-profiles:Profile", { nullable: true })], Correspondent.prototype, "profileId", 2);
374
+ Correspondent = __decorateClass$12([TenantScoped({ mode: "required" }), smrt({
375
+ tableName: "correspondents",
376
+ api: false,
377
+ mcp: false,
378
+ cli: false,
379
+ conflictColumns: [
380
+ "tenant_id",
381
+ "owner_user_id",
382
+ "address"
383
+ ],
384
+ indexes: [{
385
+ name: "correspondents_owner_last_contact_idx",
386
+ columns: [
387
+ "tenantId",
388
+ "ownerUserId",
389
+ "lastContactAt"
390
+ ]
391
+ }]
392
+ })], Correspondent);
393
+ //#endregion
394
+ //#region src/collections/CorrespondentCollection.ts
395
+ var CorrespondentCollection = class extends SmrtCollection {
396
+ static _itemClass = Correspondent;
397
+ };
398
+ //#endregion
202
399
  //#region src/models/NotificationDelivery.ts
203
400
  var __defProp$11 = Object.defineProperty;
204
401
  var __getOwnPropDesc$11 = Object.getOwnPropertyDescriptor;
@@ -786,7 +983,7 @@ var EmailAttachment = class extends Attachment {
786
983
  */
787
984
  async getEmail() {
788
985
  if (!this.messageId) return null;
789
- const { EmailCollection } = await import("./chunks/EmailCollection-CHINTmyA.js").then((n) => n.n);
986
+ const { EmailCollection } = await import("./chunks/EmailCollection-8HeBXd0F.js").then((n) => n.n);
790
987
  return await (await EmailCollection.create(this.options)).get({ id: this.messageId });
791
988
  }
792
989
  };
@@ -1869,6 +2066,736 @@ function isPrivateMailHost(host) {
1869
2066
  return false;
1870
2067
  }
1871
2068
  //#endregion
2069
+ //#region src/services/MailSearchService.ts
2070
+ var DEFAULT_LIMIT$3 = 25;
2071
+ var MAX_LIMIT$3 = 100;
2072
+ var SCAN_BATCH$1 = 200;
2073
+ var SCAN_LIMIT = 5e3;
2074
+ var SNIPPET_LENGTH = 200;
2075
+ function clampLimit$1(limit) {
2076
+ if (limit === void 0) return DEFAULT_LIMIT$3;
2077
+ if (!Number.isInteger(limit) || limit < 1) throw new Error("Mail search limit must be a positive integer.");
2078
+ return Math.min(limit, MAX_LIMIT$3);
2079
+ }
2080
+ function parseCursor(cursor) {
2081
+ if (!cursor) return 0;
2082
+ const n = Number(cursor);
2083
+ if (!Number.isInteger(n) || n < 0) throw new Error("Invalid mail search cursor.");
2084
+ return n;
2085
+ }
2086
+ var lower = (v) => (v ?? "").toLowerCase();
2087
+ function recipientHaystack(json) {
2088
+ if (!json) return "";
2089
+ try {
2090
+ const parsed = JSON.parse(json);
2091
+ if (!Array.isArray(parsed)) return lower(json);
2092
+ return parsed.map((p) => typeof p === "string" ? p : `${p?.address ?? ""} ${p?.name ?? ""}`).join(" ").toLowerCase();
2093
+ } catch {
2094
+ return lower(json);
2095
+ }
2096
+ }
2097
+ function labelsOf(email) {
2098
+ const out = /* @__PURE__ */ new Set();
2099
+ for (const raw of [email.labels]) try {
2100
+ const parsed = JSON.parse(raw || "[]");
2101
+ if (Array.isArray(parsed)) {
2102
+ for (const l of parsed) if (typeof l === "string") out.add(l);
2103
+ }
2104
+ } catch {}
2105
+ if (email.folderPath) out.add(email.folderPath);
2106
+ return [...out];
2107
+ }
2108
+ function toHit(email, similarity) {
2109
+ const body = (email.textBody || email.body || "").replace(/\s+/g, " ");
2110
+ return {
2111
+ accountId: email.accountId,
2112
+ emailId: email.id ?? null,
2113
+ providerMessageId: email.providerMessageId,
2114
+ threadId: email.threadId,
2115
+ subject: email.subject,
2116
+ fromAddress: email.fromAddress,
2117
+ fromName: email.fromName,
2118
+ date: email.date ?? null,
2119
+ snippet: body.slice(0, SNIPPET_LENGTH),
2120
+ isRead: email.isRead,
2121
+ isFlagged: email.isFlagged,
2122
+ hasAttachments: email.hasAttachments,
2123
+ labels: labelsOf(email),
2124
+ source: "local",
2125
+ ...similarity === void 0 ? {} : { similarity }
2126
+ };
2127
+ }
2128
+ function matches(email, q) {
2129
+ if (q.from) {
2130
+ const f = q.from.toLowerCase();
2131
+ if (!`${lower(email.fromAddress)} ${lower(email.fromName)}`.includes(f)) return false;
2132
+ }
2133
+ if (q.to) {
2134
+ const t = q.to.toLowerCase();
2135
+ if (!`${recipientHaystack(email.toAddresses)} ${recipientHaystack(email.ccAddresses)}`.includes(t)) return false;
2136
+ }
2137
+ if (q.subject && !lower(email.subject).includes(q.subject.toLowerCase())) return false;
2138
+ if (q.label) {
2139
+ const wanted = q.label.toLowerCase();
2140
+ if (!labelsOf(email).some((l) => l.toLowerCase() === wanted)) return false;
2141
+ }
2142
+ if (q.text) {
2143
+ const t = q.text.toLowerCase();
2144
+ const hay = `${lower(email.subject)} ${lower(email.textBody)} ${lower(email.body)} ${lower(email.fromAddress)} ${lower(email.fromName)}`;
2145
+ for (const word of t.split(/\s+/).filter(Boolean)) if (!hay.includes(word)) return false;
2146
+ }
2147
+ return true;
2148
+ }
2149
+ function structuredWhere(q, tenantId, accountIds) {
2150
+ const where = {
2151
+ tenantId,
2152
+ "accountId in": accountIds
2153
+ };
2154
+ if (q.hasAttachment !== void 0) where.hasAttachments = q.hasAttachment;
2155
+ if (q.isRead !== void 0) where.isRead = q.isRead;
2156
+ if (q.isFlagged !== void 0) where.isFlagged = q.isFlagged;
2157
+ if (q.since) where["date >="] = q.since;
2158
+ if (q.before) where["date <"] = q.before;
2159
+ return where;
2160
+ }
2161
+ var MailSearchService = class {
2162
+ constructor(options) {
2163
+ this.options = options;
2164
+ }
2165
+ options;
2166
+ /** Accounts the principal may search: owner or `read` grant, nothing else. */
2167
+ async searchableAccounts() {
2168
+ return readableMailAccounts(this.options);
2169
+ }
2170
+ async scope(requested) {
2171
+ const accounts = await this.searchableAccounts();
2172
+ const wanted = requested ? new Set(requested) : null;
2173
+ const chosen = accounts.filter((a) => !wanted || wanted.has(a.id));
2174
+ return {
2175
+ ids: chosen.map((a) => a.id),
2176
+ accounts: chosen
2177
+ };
2178
+ }
2179
+ /** Search the local index across every readable account. */
2180
+ async search(query = {}) {
2181
+ const limit = clampLimit$1(query.limit);
2182
+ const start = parseCursor(query.cursor);
2183
+ const { ids } = await this.scope(query.accountIds);
2184
+ const empty = {
2185
+ hits: [],
2186
+ nextCursor: null,
2187
+ accountIds: ids,
2188
+ truncated: false,
2189
+ semanticUsed: false
2190
+ };
2191
+ if (!ids.length) return empty;
2192
+ const { tenantId, db } = this.options;
2193
+ return withTenant({ tenantId }, () => runWithMailSystemAccess(async () => {
2194
+ const emails = await EmailCollection.create({ db });
2195
+ const where = structuredWhere(query, tenantId, ids);
2196
+ if (query.mode === "semantic" && query.text) {
2197
+ const ranked = await emails.semanticMatches(query.text, where);
2198
+ if (ranked?.length) {
2199
+ const hits2 = [];
2200
+ for (const match of ranked) {
2201
+ const email = (await emails.list({
2202
+ where: {
2203
+ ...where,
2204
+ id: match.id
2205
+ },
2206
+ limit: 1
2207
+ }))[0];
2208
+ if (email && matches(email, {
2209
+ ...query,
2210
+ text: void 0
2211
+ })) hits2.push(toHit(email, match.similarity));
2212
+ }
2213
+ return {
2214
+ hits: hits2.slice(start, start + limit),
2215
+ nextCursor: start + limit < hits2.length ? String(start + limit) : null,
2216
+ accountIds: ids,
2217
+ truncated: false,
2218
+ semanticUsed: true
2219
+ };
2220
+ }
2221
+ }
2222
+ const hits = [];
2223
+ let scanned = start;
2224
+ let exhausted = false;
2225
+ while (hits.length < limit + 1 && scanned - start < SCAN_LIMIT) {
2226
+ const batch = await emails.list({
2227
+ where,
2228
+ orderBy: ["date DESC", "id ASC"],
2229
+ limit: SCAN_BATCH$1,
2230
+ offset: scanned
2231
+ });
2232
+ for (const email of batch) {
2233
+ scanned += 1;
2234
+ if (matches(email, query)) hits.push(toHit(email));
2235
+ if (hits.length > limit) break;
2236
+ }
2237
+ if (batch.length < SCAN_BATCH$1) {
2238
+ exhausted = true;
2239
+ break;
2240
+ }
2241
+ if (hits.length > limit) break;
2242
+ }
2243
+ const more = hits.length > limit;
2244
+ const pageHits = hits.slice(0, limit);
2245
+ let nextCursor = null;
2246
+ let truncated = false;
2247
+ if (more) nextCursor = String(scanned - 1);
2248
+ else if (!exhausted) {
2249
+ truncated = true;
2250
+ nextCursor = String(scanned);
2251
+ }
2252
+ return {
2253
+ hits: pageHits,
2254
+ nextCursor,
2255
+ accountIds: ids,
2256
+ truncated,
2257
+ semanticUsed: false
2258
+ };
2259
+ }));
2260
+ }
2261
+ /**
2262
+ * Ask each readable account's own server (SDK `search()`), falling back to
2263
+ * the local index for accounts whose provider cannot search or fails. One
2264
+ * account's failure never blocks the others. Provider hits that are already
2265
+ * synced carry their local `emailId`.
2266
+ */
2267
+ async searchProvider(query = {}) {
2268
+ const limit = clampLimit$1(query.limit);
2269
+ const { ids, accounts } = await this.scope(query.accountIds);
2270
+ const result = {
2271
+ hits: [],
2272
+ providerAccountIds: [],
2273
+ fallbackAccounts: [],
2274
+ accountIds: ids,
2275
+ truncated: false
2276
+ };
2277
+ if (!ids.length) return result;
2278
+ const { tenantId, db } = this.options;
2279
+ const criteria = toSearchCriteria(query);
2280
+ for (const listing of accounts) {
2281
+ let answered = false;
2282
+ let reason = "provider search unavailable";
2283
+ try {
2284
+ const hits = await withTenant({ tenantId }, () => runWithMailSystemAccess(async () => {
2285
+ const account = await (await EmailAccountCollection.create({ db })).get({
2286
+ id: listing.id,
2287
+ tenantId
2288
+ });
2289
+ if (!account) throw new Error("account not found");
2290
+ const client = await account.createClient();
2291
+ try {
2292
+ await client.connect();
2293
+ if (!(await client.getCapabilities()).search) {
2294
+ reason = "provider does not support search";
2295
+ return null;
2296
+ }
2297
+ if (client.getAdapter() === "imap") {
2298
+ reason = "provider search needs a selected mailbox";
2299
+ return null;
2300
+ }
2301
+ const found = await client.search(criteria);
2302
+ const emails = await EmailCollection.create({ db });
2303
+ const out = [];
2304
+ for (const msg of found) {
2305
+ if (!matchesFlags(msg, query)) continue;
2306
+ if (out.length >= limit) {
2307
+ result.truncated = true;
2308
+ break;
2309
+ }
2310
+ const local = msg.id ? (await emails.list({
2311
+ where: {
2312
+ tenantId,
2313
+ accountId: listing.id,
2314
+ providerMessageId: msg.id
2315
+ },
2316
+ limit: 1
2317
+ }))[0] : void 0;
2318
+ out.push(local ? {
2319
+ ...toHit(local),
2320
+ source: "provider"
2321
+ } : {
2322
+ accountId: listing.id,
2323
+ emailId: null,
2324
+ providerMessageId: msg.id ?? "",
2325
+ threadId: msg.threadId ?? "",
2326
+ subject: msg.subject ?? "",
2327
+ fromAddress: msg.from?.address ?? "",
2328
+ fromName: msg.from?.name ?? "",
2329
+ date: msg.date ?? null,
2330
+ snippet: (msg.text ?? "").replace(/\s+/g, " ").slice(0, SNIPPET_LENGTH),
2331
+ isRead: (msg.flags ?? []).includes("\\Seen"),
2332
+ isFlagged: (msg.flags ?? []).includes("\\Flagged"),
2333
+ hasAttachments: (msg.attachments?.length ?? 0) > 0,
2334
+ labels: msg.labels ?? [],
2335
+ source: "provider"
2336
+ });
2337
+ }
2338
+ return out;
2339
+ } finally {
2340
+ await client.disconnect().catch(() => void 0);
2341
+ }
2342
+ }));
2343
+ if (hits) {
2344
+ result.hits.push(...hits);
2345
+ result.providerAccountIds.push(listing.id);
2346
+ answered = true;
2347
+ }
2348
+ } catch (error) {
2349
+ reason = "provider search failed";
2350
+ }
2351
+ if (!answered) {
2352
+ result.fallbackAccounts.push({
2353
+ accountId: listing.id,
2354
+ reason
2355
+ });
2356
+ const local = await this.search({
2357
+ ...query,
2358
+ accountIds: [listing.id],
2359
+ cursor: null,
2360
+ mode: "keyword"
2361
+ });
2362
+ result.hits.push(...local.hits);
2363
+ if (local.truncated) result.truncated = true;
2364
+ }
2365
+ }
2366
+ result.hits.sort((a, b) => (b.date?.getTime() ?? 0) - (a.date?.getTime() ?? 0));
2367
+ if (result.hits.length > limit) {
2368
+ result.hits = result.hits.slice(0, limit);
2369
+ result.truncated = true;
2370
+ }
2371
+ return result;
2372
+ }
2373
+ };
2374
+ function toSearchCriteria(q) {
2375
+ return {
2376
+ ...q.text ? { q: q.text } : {},
2377
+ ...q.from ? { from: q.from } : {},
2378
+ ...q.to ? { to: q.to } : {},
2379
+ ...q.subject ? { subject: q.subject } : {},
2380
+ ...q.since ? { since: q.since } : {},
2381
+ ...q.before ? { before: q.before } : {},
2382
+ ...q.isRead === false ? { unread: true } : {},
2383
+ ...q.isFlagged ? { flagged: true } : {}
2384
+ };
2385
+ }
2386
+ function matchesFlags(msg, q) {
2387
+ const flags = new Set((msg.flags ?? []).map((f) => String(f).toLowerCase()));
2388
+ if (q.hasAttachment !== void 0) {
2389
+ if ((msg.attachments?.length ?? 0) > 0 !== q.hasAttachment) return false;
2390
+ }
2391
+ if (q.isRead !== void 0 && flags.has("\\seen") !== q.isRead) return false;
2392
+ if (q.isFlagged !== void 0 && flags.has("\\flagged") !== q.isFlagged) return false;
2393
+ if (q.label) {
2394
+ const wanted = q.label.toLowerCase();
2395
+ if (![
2396
+ ...msg.labels ?? [],
2397
+ ...msg.folders ?? [],
2398
+ ...msg.folder ? [msg.folder] : []
2399
+ ].some((n) => n.toLowerCase() === wanted)) return false;
2400
+ }
2401
+ return true;
2402
+ }
2403
+ async function readableMailAccounts(options) {
2404
+ const settings = new MessagingSettingsService({
2405
+ db: options.db,
2406
+ tenantId: options.tenantId,
2407
+ principal: options.principal,
2408
+ resolvePersonaTenantId: async () => null
2409
+ });
2410
+ const out = [];
2411
+ let cursor = null;
2412
+ do {
2413
+ const page = await settings.listAccounts({
2414
+ limit: 200,
2415
+ cursor
2416
+ });
2417
+ for (const account of page.accounts) if (account.scopes.includes("read")) out.push(account);
2418
+ cursor = page.nextCursor;
2419
+ } while (cursor);
2420
+ return out;
2421
+ }
2422
+ //#endregion
2423
+ //#region src/services/CorrespondentService.ts
2424
+ var SCAN_BATCH = 500;
2425
+ var DEFAULT_LIMIT$2 = 50;
2426
+ var MAX_LIMIT$2 = 200;
2427
+ var SUGGEST_MAX = 20;
2428
+ var EMAIL_PATTERN = /^[^\s@<>]+@[^\s@<>]+$/;
2429
+ function parseParties(json) {
2430
+ if (!json) return [];
2431
+ try {
2432
+ const parsed = JSON.parse(json);
2433
+ if (!Array.isArray(parsed)) return [];
2434
+ const out = [];
2435
+ for (const p of parsed) {
2436
+ const address = normalizeCorrespondentAddress(typeof p === "string" ? p : p?.address);
2437
+ if (address) out.push({
2438
+ address,
2439
+ name: typeof p === "object" && p?.name ? String(p.name).trim() : ""
2440
+ });
2441
+ }
2442
+ return out;
2443
+ } catch {
2444
+ return [];
2445
+ }
2446
+ }
2447
+ function normalizeCorrespondentAddress(value) {
2448
+ if (typeof value !== "string") return null;
2449
+ const address = value.trim().toLowerCase();
2450
+ return EMAIL_PATTERN.test(address) ? address : null;
2451
+ }
2452
+ function parseBreakdown(row) {
2453
+ try {
2454
+ const parsed = JSON.parse(row.accountBreakdown || "{}");
2455
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
2456
+ } catch {
2457
+ return {};
2458
+ }
2459
+ }
2460
+ function viewOf(row, readable) {
2461
+ const all = parseBreakdown(row);
2462
+ const ids = Object.keys(all).filter((id) => readable.has(id));
2463
+ const reset = Object.keys(all).length === 0 && Boolean(row.profileId);
2464
+ if (!ids.length && !reset) return null;
2465
+ let sent = 0;
2466
+ let received = 0;
2467
+ let first = null;
2468
+ let last = null;
2469
+ let name = "";
2470
+ let nameAt = -1;
2471
+ for (const id of ids) {
2472
+ const e = all[id];
2473
+ sent += e.sent;
2474
+ received += e.received;
2475
+ if (e.first !== null) first = first === null ? e.first : Math.min(first, e.first);
2476
+ if (e.last !== null) last = last === null ? e.last : Math.max(last, e.last);
2477
+ if (e.name && e.nameAt >= nameAt) {
2478
+ name = e.name;
2479
+ nameAt = e.nameAt;
2480
+ }
2481
+ }
2482
+ return {
2483
+ id: row.id,
2484
+ address: row.address,
2485
+ displayName: name,
2486
+ messageCount: sent + received,
2487
+ sentCount: sent,
2488
+ receivedCount: received,
2489
+ firstContactAt: first === null ? null : new Date(first),
2490
+ lastContactAt: last === null ? null : new Date(last),
2491
+ accountIds: ids.sort(),
2492
+ profileId: row.profileId
2493
+ };
2494
+ }
2495
+ var CorrespondentService = class {
2496
+ constructor(options) {
2497
+ this.options = options;
2498
+ }
2499
+ options;
2500
+ get ownerUserId() {
2501
+ const { principal } = this.options;
2502
+ return principal.userId ?? principal.id ?? null;
2503
+ }
2504
+ /** Agent-style principal acting under ceilings or a credential id. */
2505
+ get delegated() {
2506
+ const { principal } = this.options;
2507
+ return Boolean(principal.scopes || principal.accountIds || principal.id && principal.userId && principal.id !== principal.userId);
2508
+ }
2509
+ /** The owner whose rows this principal may use, or null. */
2510
+ get actingOwner() {
2511
+ if (this.delegated && !this.options.allowDelegated) return null;
2512
+ return this.ownerUserId;
2513
+ }
2514
+ searchOptions() {
2515
+ return this.options;
2516
+ }
2517
+ async rows() {
2518
+ return CorrespondentCollection.create({ db: this.options.db });
2519
+ }
2520
+ async readableIds() {
2521
+ return new Set((await readableMailAccounts(this.searchOptions())).map((a) => a.id));
2522
+ }
2523
+ /**
2524
+ * Re-derive this owner's correspondents from readable mail. Idempotent.
2525
+ * Only the scanned (readable) accounts' entries are replaced; entries of
2526
+ * accounts outside the scan are kept as they are. Nothing changes when no
2527
+ * account is readable. Addresses of the scanned accounts are not
2528
+ * correspondents. A delegated principal is refused.
2529
+ */
2530
+ async refresh() {
2531
+ const result = {
2532
+ upserted: 0,
2533
+ removed: 0,
2534
+ scanned: 0
2535
+ };
2536
+ if (this.delegated && !this.options.allowDelegated) throw new Error("Correspondents are private to their owner.");
2537
+ const owner = this.actingOwner;
2538
+ const { tenantId, db } = this.options;
2539
+ if (!owner) return result;
2540
+ const ids = (await readableMailAccounts(this.searchOptions())).map((a) => a.id);
2541
+ if (!ids.length) return result;
2542
+ const scanned = new Set(ids);
2543
+ const own = new Set(await this.ownAddresses(ids));
2544
+ const aggs = /* @__PURE__ */ new Map();
2545
+ const touch = (party, kind, at, accountId) => {
2546
+ if (own.has(party.address)) return;
2547
+ let perAccount = aggs.get(party.address);
2548
+ if (!perAccount) {
2549
+ perAccount = {};
2550
+ aggs.set(party.address, perAccount);
2551
+ }
2552
+ let e = perAccount[accountId];
2553
+ if (!e) {
2554
+ e = {
2555
+ sent: 0,
2556
+ received: 0,
2557
+ first: null,
2558
+ last: null,
2559
+ name: "",
2560
+ nameAt: -1
2561
+ };
2562
+ perAccount[accountId] = e;
2563
+ }
2564
+ if (kind === "sent") e.sent += 1;
2565
+ else e.received += 1;
2566
+ if (at) {
2567
+ e.first = e.first === null ? at : Math.min(e.first, at);
2568
+ e.last = e.last === null ? at : Math.max(e.last, at);
2569
+ }
2570
+ if (party.name && at >= e.nameAt) {
2571
+ e.name = party.name;
2572
+ e.nameAt = at;
2573
+ }
2574
+ };
2575
+ await withTenant({ tenantId }, () => runWithMailSystemAccess(async () => {
2576
+ const emails = await EmailCollection.create({ db });
2577
+ for (let offset = 0;; offset += SCAN_BATCH) {
2578
+ const batch = await emails.list({
2579
+ where: {
2580
+ tenantId,
2581
+ "accountId in": ids
2582
+ },
2583
+ orderBy: ["id ASC"],
2584
+ limit: SCAN_BATCH,
2585
+ offset
2586
+ });
2587
+ for (const email of batch) {
2588
+ result.scanned += 1;
2589
+ const at = email.date?.getTime() ?? 0;
2590
+ const sender = normalizeCorrespondentAddress(email.fromAddress);
2591
+ if (sender) touch({
2592
+ address: sender,
2593
+ name: email.fromName?.trim() ?? ""
2594
+ }, "sent", at, email.accountId);
2595
+ for (const p of [...parseParties(email.toAddresses), ...parseParties(email.ccAddresses)]) touch(p, "received", at, email.accountId);
2596
+ }
2597
+ if (batch.length < SCAN_BATCH) break;
2598
+ }
2599
+ }));
2600
+ await withTenant({ tenantId }, async () => {
2601
+ const rows = await this.rows();
2602
+ const existing = await rows.list({
2603
+ where: {
2604
+ tenantId,
2605
+ ownerUserId: owner
2606
+ },
2607
+ limit: 1e5
2608
+ });
2609
+ const byAddress = new Map(existing.map((r) => [r.address, r]));
2610
+ const addresses = /* @__PURE__ */ new Set([...aggs.keys(), ...byAddress.keys()]);
2611
+ for (const address of addresses) {
2612
+ let row = byAddress.get(address);
2613
+ const merged = {};
2614
+ if (row) {
2615
+ for (const [id, e] of Object.entries(parseBreakdown(row))) if (!scanned.has(id)) merged[id] = e;
2616
+ }
2617
+ Object.assign(merged, aggs.get(address) ?? {});
2618
+ if (!Object.keys(merged).length && row && !row.profileId) {
2619
+ await row.delete();
2620
+ result.removed += 1;
2621
+ continue;
2622
+ }
2623
+ if (!row) try {
2624
+ row = await rows.create({
2625
+ _insertOnly: true,
2626
+ tenantId,
2627
+ ownerUserId: owner,
2628
+ address
2629
+ });
2630
+ } catch (error) {
2631
+ if (!isUniqueViolationError(error)) throw error;
2632
+ row = (await rows.list({
2633
+ where: {
2634
+ tenantId,
2635
+ ownerUserId: owner,
2636
+ address
2637
+ },
2638
+ limit: 1
2639
+ }))[0];
2640
+ if (!row) throw error;
2641
+ }
2642
+ let sent = 0;
2643
+ let received = 0;
2644
+ let first = null;
2645
+ let last = null;
2646
+ let name = "";
2647
+ let nameAt = -1;
2648
+ for (const e of Object.values(merged)) {
2649
+ sent += e.sent;
2650
+ received += e.received;
2651
+ if (e.first !== null) first = first === null ? e.first : Math.min(first, e.first);
2652
+ if (e.last !== null) last = last === null ? e.last : Math.max(last, e.last);
2653
+ if (e.name && e.nameAt >= nameAt) {
2654
+ name = e.name;
2655
+ nameAt = e.nameAt;
2656
+ }
2657
+ }
2658
+ row.accountBreakdown = JSON.stringify(merged);
2659
+ row.accountIds = JSON.stringify(Object.keys(merged).sort());
2660
+ row.sentCount = sent;
2661
+ row.receivedCount = received;
2662
+ row.messageCount = sent + received;
2663
+ row.firstContactAt = first === null ? null : new Date(first);
2664
+ row.lastContactAt = last === null ? null : new Date(last);
2665
+ row.displayName = name || row.displayName;
2666
+ await row.save();
2667
+ result.upserted += 1;
2668
+ }
2669
+ });
2670
+ return result;
2671
+ }
2672
+ async ownAddresses(accountIds) {
2673
+ const { EmailAccountCollection } = await import("./chunks/EmailAccountCollection-OLTzu2T0.js").then((n) => n.n);
2674
+ const accounts = await EmailAccountCollection.create({ db: this.options.db });
2675
+ const out = [];
2676
+ for (const id of accountIds) {
2677
+ const addr = normalizeCorrespondentAddress((await accounts.get({
2678
+ id,
2679
+ tenantId: this.options.tenantId
2680
+ }))?.email);
2681
+ if (addr) out.push(addr);
2682
+ }
2683
+ return out;
2684
+ }
2685
+ /** The owner's correspondents, as seen through the readable accounts. */
2686
+ async visible() {
2687
+ const owner = this.actingOwner;
2688
+ if (!owner) return [];
2689
+ const readable = await this.readableIds();
2690
+ if (!readable.size) return [];
2691
+ return withTenant({ tenantId: this.options.tenantId }, async () => {
2692
+ const rows = await (await this.rows()).list({
2693
+ where: {
2694
+ tenantId: this.options.tenantId,
2695
+ ownerUserId: owner
2696
+ },
2697
+ orderBy: ["lastContactAt DESC", "id ASC"],
2698
+ limit: 1e5
2699
+ });
2700
+ const views = [];
2701
+ for (const r of rows) {
2702
+ const v = viewOf(r, readable);
2703
+ if (v?.accountIds.length) views.push(v);
2704
+ }
2705
+ return views.sort((a, b) => (b.lastContactAt?.getTime() ?? 0) - (a.lastContactAt?.getTime() ?? 0) || a.address.localeCompare(b.address));
2706
+ });
2707
+ }
2708
+ async list(options = {}) {
2709
+ const requested = Number.isFinite(options.limit) ? Math.trunc(options.limit) : DEFAULT_LIMIT$2;
2710
+ const limit = Math.min(Math.max(requested, 1), MAX_LIMIT$2);
2711
+ const start = options.cursor ? Number(options.cursor) : 0;
2712
+ if (!Number.isInteger(start) || start < 0) throw new Error("Invalid correspondent cursor.");
2713
+ const q = options.query?.trim().toLowerCase();
2714
+ const all = (await this.visible()).filter((r) => !q || r.address.includes(q) || r.displayName.toLowerCase().includes(q));
2715
+ return {
2716
+ correspondents: all.slice(start, start + limit),
2717
+ nextCursor: start + limit < all.length ? String(start + limit) : null
2718
+ };
2719
+ }
2720
+ /**
2721
+ * Recipient autocomplete: correspondents whose address or name starts with
2722
+ * (or, for names, has a word starting with) `prefix`, best first.
2723
+ */
2724
+ async suggest(prefix, limit = 8) {
2725
+ const p = prefix.trim().toLowerCase();
2726
+ if (!p) return [];
2727
+ const cap = Math.min(Math.max(Math.trunc(limit) || 1, 1), SUGGEST_MAX);
2728
+ const scored = [];
2729
+ for (const view of await this.visible()) {
2730
+ const name = view.displayName.toLowerCase();
2731
+ let rank = -1;
2732
+ if (view.address.startsWith(p)) rank = 0;
2733
+ else if (name.startsWith(p)) rank = 1;
2734
+ else if (name.split(/\s+/).some((w) => w.startsWith(p))) rank = 2;
2735
+ else if (view.address.includes(p)) rank = 3;
2736
+ if (rank >= 0) scored.push({
2737
+ view,
2738
+ rank
2739
+ });
2740
+ }
2741
+ scored.sort((a, b) => a.rank - b.rank || b.view.messageCount - a.view.messageCount || a.view.address.localeCompare(b.view.address));
2742
+ return scored.slice(0, cap).map((s) => s.view);
2743
+ }
2744
+ async owned(id) {
2745
+ const owner = this.actingOwner;
2746
+ if (!owner) return null;
2747
+ const readable = await this.readableIds();
2748
+ if (!readable.size) return null;
2749
+ return withTenant({ tenantId: this.options.tenantId }, async () => {
2750
+ const found = (await (await this.rows()).list({
2751
+ where: {
2752
+ tenantId: this.options.tenantId,
2753
+ ownerUserId: owner,
2754
+ id
2755
+ },
2756
+ limit: 1
2757
+ }))[0];
2758
+ if (!found) return null;
2759
+ const view = viewOf(found, readable);
2760
+ return view ? {
2761
+ row: found,
2762
+ view
2763
+ } : null;
2764
+ });
2765
+ }
2766
+ async get(id) {
2767
+ return (await this.owned(id))?.view ?? null;
2768
+ }
2769
+ assertMayWrite() {
2770
+ if (this.delegated && !this.options.allowDelegated) throw new Error("Correspondents are private to their owner.");
2771
+ }
2772
+ /** Link a correspondent to a `Profile` of this tenant (owner's choice). */
2773
+ async linkProfile(id, profileId) {
2774
+ this.assertMayWrite();
2775
+ const hit = await this.owned(id);
2776
+ if (!hit) throw new Error("Correspondent not found.");
2777
+ const profile = await readNotificationProfile(this.options.db, this.options.tenantId, profileId);
2778
+ if (!profile || profile.tenantId && profile.tenantId !== this.options.tenantId) throw new Error("Profile not found.");
2779
+ hit.row.profileId = profileId;
2780
+ await withTenant({ tenantId: this.options.tenantId }, () => hit.row.save());
2781
+ return {
2782
+ ...hit.view,
2783
+ profileId
2784
+ };
2785
+ }
2786
+ async unlinkProfile(id) {
2787
+ this.assertMayWrite();
2788
+ const hit = await this.owned(id);
2789
+ if (!hit) throw new Error("Correspondent not found.");
2790
+ hit.row.profileId = null;
2791
+ await withTenant({ tenantId: this.options.tenantId }, () => hit.row.save());
2792
+ return {
2793
+ ...hit.view,
2794
+ profileId: null
2795
+ };
2796
+ }
2797
+ };
2798
+ //#endregion
1872
2799
  //#region src/services/NotificationOptOutService.ts
1873
2800
  var NotificationOptOutDeniedError = class extends Error {
1874
2801
  constructor(reason, message) {
@@ -3518,6 +4445,6 @@ ensureBuiltinMessagingProvidersRegistered();
3518
4445
  ensureMessagingPermissionsRegistered();
3519
4446
  ensureMailAccessEnforcementRegistered();
3520
4447
  //#endregion
3521
- export { Account, AccountCollection, Attachment, AttachmentCollection, Blacklist, BlacklistCollection, CHANGE_FEED_PROVIDERS, Email, EmailAccount, EmailAccountCollection, EmailAttachment, EmailAttachmentCollection, EmailCollection, EmailFolder, EmailFolderCollection, EmailSender, MAIL_ACCOUNT_RESOURCE_TYPE, MAIL_SCOPES, MAIL_SYNC_QUEUE, MANAGE_MESSAGE_CREDENTIALS_PERMISSION, MANAGE_MESSAGE_ROUTES_PERMISSION, MESSAGES_ROLE_PERMISSION_MATRIX, MESSAGING_PERMISSION_DEFINITIONS, MailAccessError, MailAccessService, MailWriteBackUnsupportedError, MailboxRecipe, Message, MessageCollection, MessagingEndpoint, MessagingEndpointCollection, MessagingSettingsService, NOTIFICATION_DELIVERY_CHANNELS, NOTIFICATION_OPT_OUT_ALL_SCOPE, NOTIFICATION_OPT_OUT_SCOPE_PATTERN, NotificationDelivery, NotificationDeliveryCollection, NotificationOptOut, NotificationOptOutCollection, NotificationOptOutDeniedError, NotificationOptOutService, NotificationOutboxDeniedError, NotificationOutboxService, NotificationsRecipe, PROFILE_NOTIFICATION_POLICY_PREFIX, PersonaMessageRoute, PersonaMessageRouteCollection, PersonaMessagingService, SEND_MESSAGES_PERMISSION, SlackAccount, SlackMessage, SlackRecipe, SlackSender, TelegramAccount, TelegramSender, Tweet, TweetSender, TwitterAccount, USER_NOTIFICATION_SEVERITIES, UserNotification, UserNotificationCollection, UserNotificationService, Whitelist, WhitelistCollection, ZulipAccount, ZulipSender, assertMailAccess, assertMessagingPermission, assertNotificationProfileRecipientSchema, buildNotificationLink, canAccessMailAccount, configureMailAccess, decideMailAccess, deniedMailAccountIds, enqueueDueMailSyncs, enqueueMailSync, ensureBuiltinMessagingProvidersRegistered, ensureMessagingPermissionsRegistered, getMessagingProvider, isMailScope, isValidNotificationOptOutScope, listMessagingProviders, mailScopePermission, mailSyncDedupeKey, messageSendTransport, messagingPrincipalFromPermissions, migrateNotificationProfileRecipients, notificationDeliveryCorrelationId, notificationDeliveryMessageId, optOutSuppression, planNotificationProfileRecipients, profileNotificationPolicy, registerMessagingProvider, resetMailAccess, runWithMailSystemAccess, seedMessagesRolePermissions };
4448
+ export { APPROVE_HELD_SEND_PERMISSION, Account, AccountCollection, Attachment, AttachmentCollection, Blacklist, BlacklistCollection, CHANGE_FEED_PROVIDERS, Correspondent, CorrespondentCollection, CorrespondentService, Email, EmailAccount, EmailAccountCollection, EmailAttachment, EmailAttachmentCollection, EmailCollection, EmailFolder, EmailFolderCollection, EmailSender, HeldSendError, MAIL_ACCOUNT_RESOURCE_TYPE, MAIL_SCOPES, MAIL_SYNC_QUEUE, MANAGE_MESSAGE_CREDENTIALS_PERMISSION, MANAGE_MESSAGE_ROUTES_PERMISSION, MESSAGES_ROLE_PERMISSION_MATRIX, MESSAGING_PERMISSION_DEFINITIONS, MailAccessError, MailAccessService, MailDraftError, MailDraftService, MailSearchService, MailSendApprovalService, MailWriteBackUnsupportedError, MailboxRecipe, Message, MessageCollection, MessagingEndpoint, MessagingEndpointCollection, MessagingSettingsService, NOTIFICATION_DELIVERY_CHANNELS, NOTIFICATION_OPT_OUT_ALL_SCOPE, NOTIFICATION_OPT_OUT_SCOPE_PATTERN, NotificationDelivery, NotificationDeliveryCollection, NotificationOptOut, NotificationOptOutCollection, NotificationOptOutDeniedError, NotificationOptOutService, NotificationOutboxDeniedError, NotificationOutboxService, NotificationsRecipe, PROFILE_NOTIFICATION_POLICY_PREFIX, PersonaMessageRoute, PersonaMessageRouteCollection, PersonaMessagingService, SEND_MESSAGES_PERMISSION, SlackAccount, SlackMessage, SlackRecipe, SlackSender, TelegramAccount, TelegramSender, Tweet, TweetSender, TwitterAccount, USER_NOTIFICATION_SEVERITIES, UserNotification, UserNotificationCollection, UserNotificationService, Whitelist, WhitelistCollection, ZulipAccount, ZulipSender, assertMailAccess, assertMessagingPermission, assertNotificationProfileRecipientSchema, auditMailAction, buildNotificationLink, canAccessMailAccount, configureMailAccess, configureMailSendApprovals, decideMailAccess, deniedMailAccountIds, effectiveAgentSendPolicy, enqueueDueMailSyncs, enqueueMailSync, ensureBuiltinMessagingProvidersRegistered, ensureMessagingPermissionsRegistered, getMessagingProvider, isMailScope, isPersonMailPrincipal, isValidNotificationOptOutScope, listMessagingProviders, mailScopePermission, mailSendBindingHash, mailSyncDedupeKey, messageSendTransport, messagingPrincipalFromPermissions, migrateNotificationProfileRecipients, normalizeCorrespondentAddress, notificationDeliveryCorrelationId, notificationDeliveryMessageId, optOutSuppression, planNotificationProfileRecipients, profileNotificationPolicy, readableMailAccounts, registerMessagingProvider, resetMailAccess, resetMailSendApprovals, resolveMailPrincipal, runWithMailSystemAccess, seedMessagesRolePermissions, stampHandledBy, threadHandledBy };
3522
4449
 
3523
4450
  //# sourceMappingURL=index.js.map