@happyvertical/smrt-messages 0.62.5 → 0.62.7

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 (63) hide show
  1. package/AGENTS.md +72 -0
  2. package/dist/access-enforcement.d.ts +20 -0
  3. package/dist/access-enforcement.d.ts.map +1 -0
  4. package/dist/access.d.ts +203 -0
  5. package/dist/access.d.ts.map +1 -0
  6. package/dist/chunks/AttachmentCollection-nTqD75n8.js +308 -0
  7. package/dist/chunks/AttachmentCollection-nTqD75n8.js.map +1 -0
  8. package/dist/chunks/{Email-rizVmZC9.js → Email-DKcIiMxB.js} +6 -6
  9. package/dist/chunks/{Email-rizVmZC9.js.map → Email-DKcIiMxB.js.map} +1 -1
  10. package/dist/chunks/EmailAccountCollection-DtCuHcB4.js +1224 -0
  11. package/dist/chunks/EmailAccountCollection-DtCuHcB4.js.map +1 -0
  12. package/dist/chunks/EmailCollection-BYeuWWsP.js +181 -0
  13. package/dist/chunks/EmailCollection-BYeuWWsP.js.map +1 -0
  14. package/dist/chunks/{EmailFolder-Dk9hx1HT.js → EmailFolder-UMGpXTQ7.js} +25 -6
  15. package/dist/chunks/EmailFolder-UMGpXTQ7.js.map +1 -0
  16. package/dist/chunks/EmailFolderCollection-DHZKwe1H.js +177 -0
  17. package/dist/chunks/EmailFolderCollection-DHZKwe1H.js.map +1 -0
  18. package/dist/chunks/EmailSender-B-Rtq9du.js +147 -0
  19. package/dist/chunks/EmailSender-B-Rtq9du.js.map +1 -0
  20. package/dist/chunks/{Message-QoL9DoTt.js → Message-M8INXZs5.js} +30 -6
  21. package/dist/chunks/Message-M8INXZs5.js.map +1 -0
  22. package/dist/chunks/{MessageCollection-B3YHj1hX.js → MessageCollection-CT0O_7wG.js} +2 -2
  23. package/dist/chunks/{MessageCollection-B3YHj1hX.js.map → MessageCollection-CT0O_7wG.js.map} +1 -1
  24. package/dist/chunks/MessagingEndpointCollection-DrNvP8GM.js +97 -0
  25. package/dist/chunks/MessagingEndpointCollection-DrNvP8GM.js.map +1 -0
  26. package/dist/collections/AttachmentCollection.d.ts +6 -0
  27. package/dist/collections/AttachmentCollection.d.ts.map +1 -1
  28. package/dist/connect.d.ts +82 -0
  29. package/dist/connect.d.ts.map +1 -0
  30. package/dist/connect.js +126 -0
  31. package/dist/connect.js.map +1 -0
  32. package/dist/index.d.ts +1 -0
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +458 -1399
  35. package/dist/index.js.map +1 -1
  36. package/dist/manifest.json +892 -32
  37. package/dist/models/Account.d.ts +23 -0
  38. package/dist/models/Account.d.ts.map +1 -1
  39. package/dist/models/Attachment.d.ts +14 -0
  40. package/dist/models/Attachment.d.ts.map +1 -1
  41. package/dist/models/EmailAccount.d.ts +3 -0
  42. package/dist/models/EmailAccount.d.ts.map +1 -1
  43. package/dist/models/EmailFolder.d.ts +7 -0
  44. package/dist/models/EmailFolder.d.ts.map +1 -1
  45. package/dist/models/Message.d.ts +7 -0
  46. package/dist/models/Message.d.ts.map +1 -1
  47. package/dist/permissions.d.ts +11 -0
  48. package/dist/permissions.d.ts.map +1 -1
  49. package/dist/services/MessagingSettingsService.d.ts +86 -0
  50. package/dist/services/MessagingSettingsService.d.ts.map +1 -1
  51. package/dist/services/NotificationOutboxService.d.ts +3 -0
  52. package/dist/services/NotificationOutboxService.d.ts.map +1 -1
  53. package/dist/smrt-knowledge.json +762 -21
  54. package/dist/smrt-knowledge.okf.md +3 -2
  55. package/dist/types.d.ts +5 -0
  56. package/dist/types.d.ts.map +1 -1
  57. package/package.json +20 -16
  58. package/dist/chunks/AccountCollection-C4vlT1ZY.js +0 -257
  59. package/dist/chunks/AccountCollection-C4vlT1ZY.js.map +0 -1
  60. package/dist/chunks/EmailFolder-Dk9hx1HT.js.map +0 -1
  61. package/dist/chunks/Message-QoL9DoTt.js.map +0 -1
  62. package/dist/chunks/__smrt-register__-B48BcESB.js +0 -6
  63. package/dist/chunks/__smrt-register__-B48BcESB.js.map +0 -1
@@ -0,0 +1,181 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
+ import { queryGlobal, queryWithGlobals } from "../host.js";
3
+ import { t as MessageCollection } from "./MessageCollection-CT0O_7wG.js";
4
+ import { t as Email } from "./Email-DKcIiMxB.js";
5
+ //#region src/collections/EmailCollection.ts
6
+ var EmailCollection_exports = /* @__PURE__ */ __exportAll({ EmailCollection: () => EmailCollection });
7
+ var EmailCollection = class extends MessageCollection {
8
+ static _itemClass = Email;
9
+ /**
10
+ * Get email by RFC 822 Message-ID
11
+ */
12
+ async getByMessageId(accountId, messageId) {
13
+ return (await this.list({
14
+ where: {
15
+ accountId,
16
+ messageId
17
+ },
18
+ limit: 1
19
+ }))[0] || null;
20
+ }
21
+ /**
22
+ * Get emails by account
23
+ */
24
+ async getByAccount(accountId) {
25
+ return await this.list({ where: { accountId } });
26
+ }
27
+ /**
28
+ * Get emails by folder
29
+ */
30
+ async getByFolder(folderId) {
31
+ return await this.list({ where: { folderId } });
32
+ }
33
+ /**
34
+ * Get emails by thread
35
+ */
36
+ async getByThread(threadId) {
37
+ return await this.list({ where: { threadId } });
38
+ }
39
+ /**
40
+ * Get unread emails
41
+ */
42
+ async getUnread(accountId) {
43
+ const where = { isRead: false };
44
+ if (accountId) where.accountId = accountId;
45
+ return await this.list({ where });
46
+ }
47
+ /**
48
+ * Get flagged emails
49
+ */
50
+ async getFlagged(accountId) {
51
+ const where = { isFlagged: true };
52
+ if (accountId) where.accountId = accountId;
53
+ return await this.list({ where });
54
+ }
55
+ /**
56
+ * Get emails with attachments
57
+ */
58
+ async getWithAttachments(accountId) {
59
+ const where = { hasAttachments: true };
60
+ if (accountId) where.accountId = accountId;
61
+ return await this.list({ where });
62
+ }
63
+ /**
64
+ * Get recent emails
65
+ */
66
+ async getRecent(limit = 20, accountId) {
67
+ return (await this.list({ where: accountId ? { accountId } : void 0 })).sort((a, b) => {
68
+ const dateA = a.date?.getTime() || 0;
69
+ return (b.date?.getTime() || 0) - dateA;
70
+ }).slice(0, limit);
71
+ }
72
+ /**
73
+ * Count emails in a folder
74
+ */
75
+ async countByFolder(folderId) {
76
+ return (await this.list({ where: { folderId } })).length;
77
+ }
78
+ /**
79
+ * Count unread emails in a folder
80
+ */
81
+ async countUnreadByFolder(folderId) {
82
+ return (await this.list({ where: {
83
+ folderId,
84
+ isRead: false
85
+ } })).length;
86
+ }
87
+ /**
88
+ * Count unread emails for an account
89
+ */
90
+ async countUnreadByAccount(accountId) {
91
+ return (await this.list({ where: {
92
+ accountId,
93
+ isRead: false
94
+ } })).length;
95
+ }
96
+ /**
97
+ * Search emails with email-specific filters.
98
+ * Alias: `search()` for backward compatibility.
99
+ */
100
+ async search(query, filters) {
101
+ return this.searchEmails(query, filters);
102
+ }
103
+ /**
104
+ * Search emails with email-specific filters
105
+ */
106
+ async searchEmails(query, filters) {
107
+ let emails = await this.list({});
108
+ if (query) {
109
+ const lowerQuery = query.toLowerCase();
110
+ emails = emails.filter((e) => e.subject?.toLowerCase().includes(lowerQuery) || e.textBody?.toLowerCase().includes(lowerQuery) || e.fromAddress?.toLowerCase().includes(lowerQuery) || e.fromName?.toLowerCase().includes(lowerQuery));
111
+ }
112
+ if (filters) {
113
+ if (filters.accountId) emails = emails.filter((e) => e.accountId === filters.accountId);
114
+ if (filters.folderId) emails = emails.filter((e) => e.folderId === filters.folderId);
115
+ if (filters.threadId) emails = emails.filter((e) => e.threadId === filters.threadId);
116
+ if (filters.from) {
117
+ const fromLower = filters.from.toLowerCase();
118
+ emails = emails.filter((e) => e.fromAddress?.toLowerCase().includes(fromLower) || e.fromName?.toLowerCase().includes(fromLower));
119
+ }
120
+ if (filters.to) {
121
+ const toLower = filters.to.toLowerCase();
122
+ emails = emails.filter((e) => e.toAddresses?.toLowerCase().includes(toLower));
123
+ }
124
+ if (filters.subject) {
125
+ const subjectLower = filters.subject.toLowerCase();
126
+ emails = emails.filter((e) => e.subject?.toLowerCase().includes(subjectLower));
127
+ }
128
+ if (filters.isRead !== void 0) emails = emails.filter((e) => e.isRead === filters.isRead);
129
+ if (filters.isFlagged !== void 0) emails = emails.filter((e) => e.isFlagged === filters.isFlagged);
130
+ if (filters.hasAttachments !== void 0) emails = emails.filter((e) => e.hasAttachments === filters.hasAttachments);
131
+ if (filters.sincDate) emails = emails.filter((e) => e.date && e.date >= filters.sincDate);
132
+ if (filters.beforeDate) emails = emails.filter((e) => e.date && e.date < filters.beforeDate);
133
+ }
134
+ return emails;
135
+ }
136
+ /**
137
+ * Mark all emails in a folder as read
138
+ */
139
+ async markFolderRead(folderId) {
140
+ const folderEmails = (await this.getUnread()).filter((e) => e.folderId === folderId);
141
+ for (const email of folderEmails) await email.markRead();
142
+ }
143
+ /**
144
+ * Delete emails by folder
145
+ */
146
+ async deleteByFolder(folderId) {
147
+ const emails = await this.getByFolder(folderId);
148
+ let count = 0;
149
+ for (const email of emails) {
150
+ await email.delete();
151
+ count++;
152
+ }
153
+ return count;
154
+ }
155
+ /**
156
+ * Get email statistics for an account
157
+ */
158
+ async getAccountStats(accountId) {
159
+ const emails = await this.getByAccount(accountId);
160
+ return {
161
+ total: emails.length,
162
+ unread: emails.filter((e) => !e.isRead).length,
163
+ flagged: emails.filter((e) => e.isFlagged).length,
164
+ withAttachments: emails.filter((e) => e.hasAttachments).length,
165
+ byType: { Email: emails.length }
166
+ };
167
+ }
168
+ async findByTenant(tenantId) {
169
+ return this.list({ where: { tenantId } });
170
+ }
171
+ async findGlobal() {
172
+ return queryGlobal(this);
173
+ }
174
+ async findWithGlobals(tenantId) {
175
+ return queryWithGlobals(this, tenantId, "Email.findWithGlobals");
176
+ }
177
+ };
178
+ //#endregion
179
+ export { EmailCollection_exports as n, EmailCollection as t };
180
+
181
+ //# sourceMappingURL=EmailCollection-BYeuWWsP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EmailCollection-BYeuWWsP.js","names":[],"sources":["../../src/collections/EmailCollection.ts"],"sourcesContent":["/**\n * EmailCollection - Collection manager for Email objects\n *\n * Extends MessageCollection with email-specific query methods.\n * STI framework auto-filters to Email instances.\n */\n\nimport { queryGlobal, queryWithGlobals } from '../host.js';\nimport { Email } from '../models/Email';\nimport type { EmailSearchFilters } from '../types';\nimport { MessageCollection } from './MessageCollection';\n\nexport class EmailCollection extends MessageCollection {\n static override readonly _itemClass = Email;\n\n /**\n * Get email by RFC 822 Message-ID\n */\n async getByMessageId(\n accountId: string,\n messageId: string,\n ): Promise<Email | null> {\n const emails = await this.list({\n where: { accountId, messageId },\n limit: 1,\n });\n return (emails[0] as Email) || null;\n }\n\n /**\n * Get emails by account\n */\n async getByAccount(accountId: string): Promise<Email[]> {\n return (await this.list({ where: { accountId } })) as Email[];\n }\n\n /**\n * Get emails by folder\n */\n async getByFolder(folderId: string): Promise<Email[]> {\n return (await this.list({ where: { folderId } })) as Email[];\n }\n\n /**\n * Get emails by thread\n */\n override async getByThread(threadId: string): Promise<Email[]> {\n return (await this.list({ where: { threadId } })) as Email[];\n }\n\n /**\n * Get unread emails\n */\n override async getUnread(accountId?: string): Promise<Email[]> {\n const where: Record<string, unknown> = { isRead: false };\n if (accountId) {\n where.accountId = accountId;\n }\n return (await this.list({ where })) as Email[];\n }\n\n /**\n * Get flagged emails\n */\n override async getFlagged(accountId?: string): Promise<Email[]> {\n const where: Record<string, unknown> = { isFlagged: true };\n if (accountId) {\n where.accountId = accountId;\n }\n return (await this.list({ where })) as Email[];\n }\n\n /**\n * Get emails with attachments\n */\n async getWithAttachments(accountId?: string): Promise<Email[]> {\n const where: Record<string, unknown> = { hasAttachments: true };\n if (accountId) {\n where.accountId = accountId;\n }\n return (await this.list({ where })) as Email[];\n }\n\n /**\n * Get recent emails\n */\n override async getRecent(limit = 20, accountId?: string): Promise<Email[]> {\n const allEmails = (await this.list({\n where: accountId ? { accountId } : undefined,\n })) as Email[];\n\n return allEmails\n .sort((a, b) => {\n const dateA = a.date?.getTime() || 0;\n const dateB = b.date?.getTime() || 0;\n return dateB - dateA;\n })\n .slice(0, limit);\n }\n\n /**\n * Count emails in a folder\n */\n async countByFolder(folderId: string): Promise<number> {\n const emails = await this.list({ where: { folderId } });\n return emails.length;\n }\n\n /**\n * Count unread emails in a folder\n */\n async countUnreadByFolder(folderId: string): Promise<number> {\n const emails = await this.list({ where: { folderId, isRead: false } });\n return emails.length;\n }\n\n /**\n * Count unread emails for an account\n */\n async countUnreadByAccount(accountId: string): Promise<number> {\n const emails = await this.list({ where: { accountId, isRead: false } });\n return emails.length;\n }\n\n /**\n * Search emails with email-specific filters.\n * Alias: `search()` for backward compatibility.\n */\n override async search(\n query: string,\n filters?: EmailSearchFilters,\n ): Promise<Email[]> {\n return this.searchEmails(query, filters);\n }\n\n /**\n * Search emails with email-specific filters\n */\n async searchEmails(\n query: string,\n filters?: EmailSearchFilters,\n ): Promise<Email[]> {\n let emails = (await this.list({})) as Email[];\n\n // Filter by query\n if (query) {\n const lowerQuery = query.toLowerCase();\n emails = emails.filter(\n (e) =>\n e.subject?.toLowerCase().includes(lowerQuery) ||\n e.textBody?.toLowerCase().includes(lowerQuery) ||\n e.fromAddress?.toLowerCase().includes(lowerQuery) ||\n e.fromName?.toLowerCase().includes(lowerQuery),\n );\n }\n\n // Apply filters\n if (filters) {\n if (filters.accountId) {\n emails = emails.filter((e) => e.accountId === filters.accountId);\n }\n if (filters.folderId) {\n emails = emails.filter((e) => e.folderId === filters.folderId);\n }\n if (filters.threadId) {\n emails = emails.filter((e) => e.threadId === filters.threadId);\n }\n if (filters.from) {\n const fromLower = filters.from.toLowerCase();\n emails = emails.filter(\n (e) =>\n e.fromAddress?.toLowerCase().includes(fromLower) ||\n e.fromName?.toLowerCase().includes(fromLower),\n );\n }\n if (filters.to) {\n const toLower = filters.to.toLowerCase();\n emails = emails.filter((e) =>\n e.toAddresses?.toLowerCase().includes(toLower),\n );\n }\n if (filters.subject) {\n const subjectLower = filters.subject.toLowerCase();\n emails = emails.filter((e) =>\n e.subject?.toLowerCase().includes(subjectLower),\n );\n }\n if (filters.isRead !== undefined) {\n emails = emails.filter((e) => e.isRead === filters.isRead);\n }\n if (filters.isFlagged !== undefined) {\n emails = emails.filter((e) => e.isFlagged === filters.isFlagged);\n }\n if (filters.hasAttachments !== undefined) {\n emails = emails.filter(\n (e) => e.hasAttachments === filters.hasAttachments,\n );\n }\n if (filters.sincDate) {\n emails = emails.filter(\n (e) => e.date && e.date >= (filters.sincDate as Date),\n );\n }\n if (filters.beforeDate) {\n emails = emails.filter(\n (e) => e.date && e.date < (filters.beforeDate as Date),\n );\n }\n }\n\n return emails;\n }\n\n /**\n * Mark all emails in a folder as read\n */\n async markFolderRead(folderId: string): Promise<void> {\n const emails = (await this.getUnread()) as Email[];\n const folderEmails = emails.filter((e) => e.folderId === folderId);\n\n for (const email of folderEmails) {\n await email.markRead();\n }\n }\n\n /**\n * Delete emails by folder\n */\n async deleteByFolder(folderId: string): Promise<number> {\n const emails = await this.getByFolder(folderId);\n let count = 0;\n\n for (const email of emails) {\n await email.delete();\n count++;\n }\n\n return count;\n }\n\n /**\n * Get email statistics for an account\n */\n override async getAccountStats(accountId: string): Promise<{\n total: number;\n unread: number;\n flagged: number;\n withAttachments: number;\n byType: Record<string, number>;\n }> {\n const emails = await this.getByAccount(accountId);\n\n return {\n total: emails.length,\n unread: emails.filter((e) => !e.isRead).length,\n flagged: emails.filter((e) => e.isFlagged).length,\n withAttachments: emails.filter((e) => e.hasAttachments).length,\n byType: { Email: emails.length },\n };\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Tenant Helper Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n override async findByTenant(tenantId: string): Promise<Email[]> {\n return this.list({ where: { tenantId } }) as Promise<Email[]>;\n }\n\n // Now that Email inherits Message's @TenantScoped recognition (#1596), an\n // explicit `tenant_id IS NULL` filter via list() throws and unflagged raw SQL\n // is blocked under an active tenant context — so route global / cross-global\n // lookups through the shared raw helpers. They auto-scope to the Email\n // `_meta_type` (via getStiChildMetaType) so the shared `messages` table never\n // returns sibling Message subtypes. (#1600)\n override async findGlobal(): Promise<Email[]> {\n return queryGlobal<Email>(this);\n }\n\n override async findWithGlobals(tenantId: string): Promise<Email[]> {\n return queryWithGlobals<Email>(this, tenantId, 'Email.findWithGlobals');\n }\n}\n"],"mappings":";;;;;;AAYO,IAAM,kBAAN,cAA8B,kBAAkB;CACrD,OAAyB,aAAa;;;;CAKtC,MAAM,eACJ,WACA,WACuB;EAKvB,QAAQ,MAJa,KAAK,KAAK;GAC7B,OAAO;IAAE;IAAW;GAAU;GAC9B,OAAO;EACT,CAAC,EAAA,CACc,MAAgB;CACjC;;;;CAKA,MAAM,aAAa,WAAqC;EACtD,OAAQ,MAAM,KAAK,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC;CAClD;;;;CAKA,MAAM,YAAY,UAAoC;EACpD,OAAQ,MAAM,KAAK,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;CACjD;;;;CAKA,MAAe,YAAY,UAAoC;EAC7D,OAAQ,MAAM,KAAK,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;CACjD;;;;CAKA,MAAe,UAAU,WAAsC;EAC7D,MAAM,QAAiC,EAAE,QAAQ,MAAM;EACvD,IAAI,WACF,MAAM,YAAY;EAEpB,OAAQ,MAAM,KAAK,KAAK,EAAE,MAAM,CAAC;CACnC;;;;CAKA,MAAe,WAAW,WAAsC;EAC9D,MAAM,QAAiC,EAAE,WAAW,KAAK;EACzD,IAAI,WACF,MAAM,YAAY;EAEpB,OAAQ,MAAM,KAAK,KAAK,EAAE,MAAM,CAAC;CACnC;;;;CAKA,MAAM,mBAAmB,WAAsC;EAC7D,MAAM,QAAiC,EAAE,gBAAgB,KAAK;EAC9D,IAAI,WACF,MAAM,YAAY;EAEpB,OAAQ,MAAM,KAAK,KAAK,EAAE,MAAM,CAAC;CACnC;;;;CAKA,MAAe,UAAU,QAAQ,IAAI,WAAsC;EAKzE,QAAO,MAJkB,KAAK,KAAK,EACjC,OAAO,YAAY,EAAE,U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AW,SAAS,QAAQ;GAC1B,MAAM,MAAM,OAAO;GACnB;EACF;EAEA,OAAO;CACT;;;;CAKA,MAAe,gBAAgB,WAM5B;EACD,MAAM,SAAS,MAAM,KAAK,aAAa,SAAS;EAEhD,OAAO;GACL,OAAO,OAAO;GACd,QAAQ,OAAO,QAAQ,MAAM,CAAC,EAAE,MAAM,CAAA,CAAE;GACxC,SAAS,OAAO,QAAQ,MAAM,EAAE,SAAS,CAAA,CAAE;GAC3C,iBAAiB,OAAO,QAAQ,MAAM,EAAE,cAAc,CAAA,CAAE;GACxD,QAAQ,EAAE,OAAO,OAAO,OAAO;EACjC;CACF;CAMA,MAAe,aAAa,UAAoC;EAC9D,OAAO,KAAK,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;CAC1C;CAQA,MAAe,aAA+B;EAC5C,OAAO,YAAmB,IAAI;CAChC;CAEA,MAAe,gBAAgB,UAAoC;EACjE,OAAO,iBAAwB,MAAM,UAAU,uBAAuB;CACxE;AACF"}
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import "./__smrt-register__-B48BcESB.js";
2
+ import { d as assertHydratedMailAccess } from "./EmailAccountCollection-DtCuHcB4.js";
3
3
  import { SmrtObject, foreignKey, smrt } from "@happyvertical/smrt-core";
4
4
  import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy/decorators";
5
5
  //#region src/models/EmailFolder.ts
@@ -46,18 +46,37 @@ var EmailFolder = class extends SmrtObject {
46
46
  if (options.updatedAt) this.updatedAt = options.updatedAt;
47
47
  }
48
48
  /**
49
+ * Direct hydration (`new X({ id }).initialize()`, `loadRelated()`) bypasses
50
+ * the collection read hooks, so the per-account mail policy is applied here
51
+ * too: a row of an account closed to the principal never hydrates.
52
+ */
53
+ async loadFromId() {
54
+ await super.loadFromId();
55
+ await assertHydratedMailAccess({
56
+ accountId: this.accountId,
57
+ options: this.options
58
+ });
59
+ }
60
+ async loadFromSlug() {
61
+ await super.loadFromSlug();
62
+ await assertHydratedMailAccess({
63
+ accountId: this.accountId,
64
+ options: this.options
65
+ });
66
+ }
67
+ /**
49
68
  * Get the email account
50
69
  */
51
70
  async getAccount() {
52
71
  if (!this.accountId) return null;
53
- const { EmailAccountCollection } = await import("../index.js").then((n) => n.r);
72
+ const { EmailAccountCollection } = await import("./EmailAccountCollection-DtCuHcB4.js").then((n) => n.n);
54
73
  return await (await EmailAccountCollection.create(this.options)).get({ id: this.accountId });
55
74
  }
56
75
  /**
57
76
  * Get all emails in this folder
58
77
  */
59
78
  async getEmails(limit) {
60
- const { EmailCollection } = await import("../index.js").then((n) => n.n);
79
+ const { EmailCollection } = await import("./EmailCollection-BYeuWWsP.js").then((n) => n.n);
61
80
  const collection = await EmailCollection.create(this.options);
62
81
  const options = { where: { folderId: this.id } };
63
82
  if (limit) options.limit = limit;
@@ -67,7 +86,7 @@ var EmailFolder = class extends SmrtObject {
67
86
  * Get unread emails in this folder
68
87
  */
69
88
  async getUnreadEmails(limit) {
70
- const { EmailCollection } = await import("../index.js").then((n) => n.n);
89
+ const { EmailCollection } = await import("./EmailCollection-BYeuWWsP.js").then((n) => n.n);
71
90
  const collection = await EmailCollection.create(this.options);
72
91
  const options = { where: {
73
92
  folderId: this.id,
@@ -82,7 +101,7 @@ var EmailFolder = class extends SmrtObject {
82
101
  async refreshCounts() {
83
102
  if (!this.id) throw new Error("EmailFolder.refreshCounts requires a persisted folder (missing id)");
84
103
  const folderId = this.id;
85
- const { EmailCollection } = await import("../index.js").then((n) => n.n);
104
+ const { EmailCollection } = await import("./EmailCollection-BYeuWWsP.js").then((n) => n.n);
86
105
  const collection = await EmailCollection.create(this.options);
87
106
  this.messageCount = await collection.countByFolder(folderId);
88
107
  this.unreadCount = await collection.countUnreadByFolder(folderId);
@@ -159,4 +178,4 @@ EmailFolder = __decorateClass([TenantScoped({ mode: "optional" }), smrt({
159
178
  //#endregion
160
179
  export { EmailFolder_exports as n, EmailFolder as t };
161
180
 
162
- //# sourceMappingURL=EmailFolder-Dk9hx1HT.js.map
181
+ //# sourceMappingURL=EmailFolder-UMGpXTQ7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EmailFolder-UMGpXTQ7.js","names":[],"sources":["../../src/models/EmailFolder.ts"],"sourcesContent":["/**\n * EmailFolder model - Folder/label tracking\n */\n\n// Register the package manifest before this module's @smrt() decorator\n// runs, whichever chunk the library build places it in (#3098).\nimport '../__smrt-register__.js';\nimport { foreignKey, SmrtObject, smrt } from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport { assertHydratedMailAccess } from '../access.js';\nimport type { EmailFolderOptions } from '../types';\n\n@TenantScoped({ mode: 'optional' })\n@smrt({\n api: { include: ['list', 'get', 'create', 'update', 'delete'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n})\nexport class EmailFolder extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n @foreignKey('Account')\n accountId = '';\n name = '';\n path = '';\n delimiter = '/';\n specialUse = ''; // '\\\\Inbox', '\\\\Sent', '\\\\Drafts', etc.\n messageCount = 0;\n unreadCount = 0;\n subscribed = true;\n\n // Timestamps\n createdAt = new Date();\n updatedAt = new Date();\n\n constructor(options: EmailFolderOptions = {}) {\n super(options);\n\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.accountId !== undefined) this.accountId = options.accountId;\n if (options.name !== undefined) this.name = options.name;\n if (options.path !== undefined) this.path = options.path;\n if (options.delimiter !== undefined) this.delimiter = options.delimiter;\n if (options.specialUse !== undefined) this.specialUse = options.specialUse;\n if (options.messageCount !== undefined)\n this.messageCount = options.messageCount;\n if (options.unreadCount !== undefined)\n this.unreadCount = options.unreadCount;\n if (options.subscribed !== undefined) this.subscribed = options.subscribed;\n if (options.createdAt) this.createdAt = options.createdAt;\n if (options.updatedAt) this.updatedAt = options.updatedAt;\n }\n\n /**\n * Direct hydration (`new X({ id }).initialize()`, `loadRelated()`) bypasses\n * the collection read hooks, so the per-account mail policy is applied here\n * too: a row of an account closed to the principal never hydrates.\n */\n override async loadFromId() {\n await super.loadFromId();\n await assertHydratedMailAccess({\n accountId: this.accountId,\n options: this.options,\n });\n }\n\n override async loadFromSlug() {\n await super.loadFromSlug();\n await assertHydratedMailAccess({\n accountId: this.accountId,\n options: this.options,\n });\n }\n\n /**\n * Get the email account\n */\n async getAccount() {\n if (!this.accountId) return null;\n\n const { EmailAccountCollection } = await import(\n '../collections/EmailAccountCollection'\n );\n const collection = await EmailAccountCollection.create(this.options);\n\n return await collection.get({ id: this.accountId });\n }\n\n /**\n * Get all emails in this folder\n */\n async getEmails(limit?: number) {\n const { EmailCollection } = await import('../collections/EmailCollection');\n const collection = await EmailCollection.create(this.options);\n\n const options: { where: Record<string, unknown>; limit?: number } = {\n where: { folderId: this.id },\n };\n if (limit) {\n options.limit = limit;\n }\n\n return await collection.list(options);\n }\n\n /**\n * Get unread emails in this folder\n */\n async getUnreadEmails(limit?: number) {\n const { EmailCollection } = await import('../collections/EmailCollection');\n const collection = await EmailCollection.create(this.options);\n\n const options: { where: Record<string, unknown>; limit?: number } = {\n where: { folderId: this.id, isRead: false },\n };\n if (limit) {\n options.limit = limit;\n }\n\n return await collection.list(options);\n }\n\n /**\n * Update message counts from database\n */\n async refreshCounts(): Promise<void> {\n if (!this.id) {\n throw new Error(\n 'EmailFolder.refreshCounts requires a persisted folder (missing id)',\n );\n }\n const folderId = this.id;\n const { EmailCollection } = await import('../collections/EmailCollection');\n const collection = await EmailCollection.create(this.options);\n\n this.messageCount = await collection.countByFolder(folderId);\n this.unreadCount = await collection.countUnreadByFolder(folderId);\n this.updatedAt = new Date();\n await this.save();\n }\n\n /**\n * Check if this is the inbox folder\n */\n isInbox(): boolean {\n return this.specialUse === '\\\\Inbox' || this.path.toLowerCase() === 'inbox';\n }\n\n /**\n * Check if this is the sent folder\n */\n isSent(): boolean {\n return this.specialUse === '\\\\Sent' || this.path.toLowerCase() === 'sent';\n }\n\n /**\n * Check if this is the drafts folder\n */\n isDrafts(): boolean {\n return (\n this.specialUse === '\\\\Drafts' || this.path.toLowerCase() === 'drafts'\n );\n }\n\n /**\n * Check if this is the trash folder\n */\n isTrash(): boolean {\n return this.specialUse === '\\\\Trash' || this.path.toLowerCase() === 'trash';\n }\n\n /**\n * Check if this is the spam/junk folder\n */\n isSpam(): boolean {\n return (\n this.specialUse === '\\\\Junk' ||\n this.path.toLowerCase() === 'spam' ||\n this.path.toLowerCase() === 'junk'\n );\n }\n\n /**\n * Check if this is a system folder\n */\n isSystemFolder(): boolean {\n return !!this.specialUse;\n }\n\n /**\n * Subscribe to folder\n */\n async subscribe(): Promise<void> {\n this.subscribed = true;\n this.updatedAt = new Date();\n await this.save();\n }\n\n /**\n * Unsubscribe from folder\n */\n async unsubscribe(): Promise<void> {\n this.subscribed = false;\n this.updatedAt = new Date();\n await this.save();\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAkBO,IAAM,cAAN,cAA0B,WAAW;CAE1C,WAA0B;CAG1B,YAAY;CACZ,OAAO;CACP,OAAO;CACP,YAAY;CACZ,aAAa;CACb,eAAe;CACf,cAAc;CACd,aAAa;CAGb,4BAAY,IAAI,KAAK;CACrB,4BAAY,IAAI,KAAK;CAErB,YAAY,UAA8B,CAAC,GAAG;EAC5C,MAAM,OAAO;EAEb,IAAI,QAAQ,aAAa,KAAA,GAAW,KAAK,WAAW,QAAQ;EAC5D,IAAI,QAAQ,cAAc,KAAA,GAAW,KAAK,YAAY,QAAQ;EAC9D,IAAI,QAAQ,SAAS,KAAA,GAAW,KAAK,OAAO,QAAQ;EACpD,IAAI,QAAQ,SAAS,KAAA,GAAW,KAAK,OAAO,QAAQ;EACpD,IAAI,QAAQ,cAAc,KAAA,GAAW,KAAK,YAAY,QAAQ;EAC9D,IAAI,QAAQ,eAAe,KAAA,GAAW,KAAK,aAAa,QAAQ;EACh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AAA,CADC,SAAS,EAAE,UAAU,KAAK,CAAC,CAAA,GADjB,YAEX,WAAA,YAAA,CAAA;AAGA,gBAAA,CADC,WAAW,SAAS,CAAA,GAJV,YAKX,WAAA,aAAA,CAAA;AALW,cAAN,gBAAA,CANN,aAAa,EAAE,MAAM,WAAW,CAAC,GACjC,KAAK;CACJ,KAAK,EAAE,SAAS;EAAC;EAAQ;EAAO;EAAU;EAAU;CAAQ,EAAE;CAC9D,KAAK,EAAE,SAAS,CAAC,QAAQ,KAAK,EAAE;CAChC,KAAK,EAAE,cAAc,KAAK;AAC5B,CAAC,CAAA,GACY,WAAA"}
@@ -0,0 +1,177 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
+ import { queryGlobal, queryWithGlobals } from "../host.js";
3
+ import { t as EmailFolder } from "./EmailFolder-UMGpXTQ7.js";
4
+ import { SmrtCollection } from "@happyvertical/smrt-core";
5
+ //#region src/collections/EmailFolderCollection.ts
6
+ var EmailFolderCollection_exports = /* @__PURE__ */ __exportAll({ EmailFolderCollection: () => EmailFolderCollection });
7
+ var EmailFolderCollection = class extends SmrtCollection {
8
+ static _itemClass = EmailFolder;
9
+ /**
10
+ * Get folder by path for an account
11
+ */
12
+ async getByPath(accountId, path) {
13
+ return (await this.list({ where: {
14
+ accountId,
15
+ path
16
+ } }))[0] || null;
17
+ }
18
+ /**
19
+ * Get folders by account
20
+ */
21
+ async getByAccount(accountId) {
22
+ return await this.list({ where: { accountId } });
23
+ }
24
+ /**
25
+ * Get inbox folder for an account
26
+ */
27
+ async getInbox(accountId) {
28
+ return (await this.getByAccount(accountId)).find((f) => f.isInbox()) || null;
29
+ }
30
+ /**
31
+ * Get sent folder for an account
32
+ */
33
+ async getSent(accountId) {
34
+ return (await this.getByAccount(accountId)).find((f) => f.isSent()) || null;
35
+ }
36
+ /**
37
+ * Get drafts folder for an account
38
+ */
39
+ async getDrafts(accountId) {
40
+ return (await this.getByAccount(accountId)).find((f) => f.isDrafts()) || null;
41
+ }
42
+ /**
43
+ * Get trash folder for an account
44
+ */
45
+ async getTrash(accountId) {
46
+ return (await this.getByAccount(accountId)).find((f) => f.isTrash()) || null;
47
+ }
48
+ /**
49
+ * Get spam folder for an account
50
+ */
51
+ async getSpam(accountId) {
52
+ return (await this.getByAccount(accountId)).find((f) => f.isSpam()) || null;
53
+ }
54
+ /**
55
+ * Get system folders for an account
56
+ */
57
+ async getSystemFolders(accountId) {
58
+ return (await this.getByAccount(accountId)).filter((f) => f.isSystemFolder());
59
+ }
60
+ /**
61
+ * Get user-created folders for an account
62
+ */
63
+ async getUserFolders(accountId) {
64
+ return (await this.getByAccount(accountId)).filter((f) => !f.isSystemFolder());
65
+ }
66
+ /**
67
+ * Get subscribed folders
68
+ */
69
+ async getSubscribed(accountId) {
70
+ const where = { subscribed: true };
71
+ if (accountId) where.accountId = accountId;
72
+ return await this.list({ where });
73
+ }
74
+ /**
75
+ * Get folders with unread messages
76
+ */
77
+ async getWithUnread(accountId) {
78
+ return (accountId ? await this.getByAccount(accountId) : await this.list({})).filter((f) => f.unreadCount > 0);
79
+ }
80
+ /**
81
+ * Search folders with filters
82
+ */
83
+ async search(query, filters) {
84
+ let folders = await this.list({});
85
+ if (query) {
86
+ const lowerQuery = query.toLowerCase();
87
+ folders = folders.filter((f) => f.name?.toLowerCase().includes(lowerQuery) || f.path?.toLowerCase().includes(lowerQuery));
88
+ }
89
+ if (filters) {
90
+ if (filters.accountId) folders = folders.filter((f) => f.accountId === filters.accountId);
91
+ if (filters.specialUse) folders = folders.filter((f) => f.specialUse === filters.specialUse);
92
+ if (filters.subscribed !== void 0) folders = folders.filter((f) => f.subscribed === filters.subscribed);
93
+ }
94
+ return folders;
95
+ }
96
+ /**
97
+ * Refresh counts for all folders in an account
98
+ */
99
+ async refreshAllCounts(accountId) {
100
+ const folders = await this.getByAccount(accountId);
101
+ for (const folder of folders) await folder.refreshCounts();
102
+ }
103
+ /**
104
+ * Get folder statistics for an account
105
+ */
106
+ async getAccountStats(accountId) {
107
+ const folders = await this.getByAccount(accountId);
108
+ return {
109
+ totalFolders: folders.length,
110
+ totalMessages: folders.reduce((sum, f) => sum + f.messageCount, 0),
111
+ totalUnread: folders.reduce((sum, f) => sum + f.unreadCount, 0),
112
+ systemFolders: folders.filter((f) => f.isSystemFolder()).length,
113
+ userFolders: folders.filter((f) => !f.isSystemFolder()).length
114
+ };
115
+ }
116
+ /**
117
+ * Create standard system folders for an account
118
+ */
119
+ async createSystemFolders(accountId) {
120
+ for (const folderData of [
121
+ {
122
+ name: "INBOX",
123
+ path: "INBOX",
124
+ specialUse: "\\Inbox"
125
+ },
126
+ {
127
+ name: "Sent",
128
+ path: "Sent",
129
+ specialUse: "\\Sent"
130
+ },
131
+ {
132
+ name: "Drafts",
133
+ path: "Drafts",
134
+ specialUse: "\\Drafts"
135
+ },
136
+ {
137
+ name: "Trash",
138
+ path: "Trash",
139
+ specialUse: "\\Trash"
140
+ },
141
+ {
142
+ name: "Spam",
143
+ path: "Spam",
144
+ specialUse: "\\Junk"
145
+ }
146
+ ]) if (!await this.getByPath(accountId, folderData.path)) await (await this.create({
147
+ accountId,
148
+ ...folderData
149
+ })).save();
150
+ }
151
+ /**
152
+ * Find all email folders belonging to a specific tenant
153
+ */
154
+ async findByTenant(tenantId) {
155
+ return this.list({ where: { tenantId } });
156
+ }
157
+ /**
158
+ * Find all global email folders (no tenant).
159
+ *
160
+ * EmailFolder is @TenantScoped (CTI, own `email_folders` table). Under an
161
+ * active tenant context list({ tenantId: null }) throws and unflagged raw SQL
162
+ * is blocked (#1596); route through the raw helpers.
163
+ */
164
+ async findGlobal() {
165
+ return queryGlobal(this);
166
+ }
167
+ /**
168
+ * Find email folders for a tenant including global folders.
169
+ */
170
+ async findWithGlobals(tenantId) {
171
+ return queryWithGlobals(this, tenantId, "EmailFolder.findWithGlobals");
172
+ }
173
+ };
174
+ //#endregion
175
+ export { EmailFolderCollection_exports as n, EmailFolderCollection as t };
176
+
177
+ //# sourceMappingURL=EmailFolderCollection-DHZKwe1H.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EmailFolderCollection-DHZKwe1H.js","names":[],"sources":["../../src/collections/EmailFolderCollection.ts"],"sourcesContent":["/**\n * EmailFolderCollection - Collection manager for EmailFolder objects\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { queryGlobal, queryWithGlobals } from '../host.js';\nimport { EmailFolder } from '../models/EmailFolder';\nimport type { EmailFolderSearchFilters } from '../types';\n\nexport class EmailFolderCollection extends SmrtCollection<EmailFolder> {\n static readonly _itemClass = EmailFolder;\n\n /**\n * Get folder by path for an account\n */\n async getByPath(\n accountId: string,\n path: string,\n ): Promise<EmailFolder | null> {\n const folders = await this.list({ where: { accountId, path } });\n return folders[0] || null;\n }\n\n /**\n * Get folders by account\n */\n async getByAccount(accountId: string): Promise<EmailFolder[]> {\n return await this.list({ where: { accountId } });\n }\n\n /**\n * Get inbox folder for an account\n */\n async getInbox(accountId: string): Promise<EmailFolder | null> {\n const folders = await this.getByAccount(accountId);\n return folders.find((f) => f.isInbox()) || null;\n }\n\n /**\n * Get sent folder for an account\n */\n async getSent(accountId: string): Promise<EmailFolder | null> {\n const folders = await this.getByAccount(accountId);\n return folders.find((f) => f.isSent()) || null;\n }\n\n /**\n * Get drafts folder for an account\n */\n async getDrafts(accountId: string): Promise<EmailFolder | null> {\n const folders = await this.getByAccount(accountId);\n return folders.find((f) => f.isDrafts()) || null;\n }\n\n /**\n * Get trash folder for an account\n */\n async getTrash(accountId: string): Promise<EmailFolder | null> {\n const folders = await this.getByAccount(accountId);\n return folders.find((f) => f.isTrash()) || null;\n }\n\n /**\n * Get spam folder for an account\n */\n async getSpam(accountId: string): Promise<EmailFolder | null> {\n const folders = await this.getByAccount(accountId);\n return folders.find((f) => f.isSpam()) || null;\n }\n\n /**\n * Get system folders for an account\n */\n async getSystemFolders(accountId: string): Promise<EmailFolder[]> {\n const folders = await this.getByAccount(accountId);\n return folders.filter((f) => f.isSystemFolder());\n }\n\n /**\n * Get user-created folders for an account\n */\n async getUserFolders(accountId: string): Promise<EmailFolder[]> {\n const folders = await this.getByAccount(accountId);\n return folders.filter((f) => !f.isSystemFolder());\n }\n\n /**\n * Get subscribed folders\n */\n async getSubscribed(accountId?: string): Promise<EmailFolder[]> {\n const where: Record<string, unknown> = { subscribed: true };\n if (accountId) {\n where.accountId = accountId;\n }\n return await this.list({ where });\n }\n\n /**\n * Get folders with unread messages\n */\n async getWithUnread(accountId?: string): Promise<EmailFolder[]> {\n const folders = accountId\n ? await this.getByAccount(accountId)\n : await this.list({});\n\n return folders.filter((f) => f.unreadCount > 0);\n }\n\n /**\n * Search folders with filters\n */\n async search(\n query: string,\n filters?: EmailFolderSearchFilters,\n ): Promise<EmailFolder[]> {\n let folders = await this.list({});\n\n // Filter by query\n if (query) {\n const lowerQuery = query.toLowerCase();\n folders = folders.filter(\n (f) =>\n f.name?.toLowerCase().includes(lowerQuery) ||\n f.path?.toLowerCase().includes(lowerQuery),\n );\n }\n\n // Apply filters\n if (filters) {\n if (filters.accountId) {\n folders = folders.filter((f) => f.accountId === filters.accountId);\n }\n if (filters.specialUse) {\n folders = folders.filter((f) => f.specialUse === filters.specialUse);\n }\n if (filters.subscribed !== undefined) {\n folders = folders.filter((f) => f.subscribed === filters.subscribed);\n }\n }\n\n return folders;\n }\n\n /**\n * Refresh counts for all folders in an account\n */\n async refreshAllCounts(accountId: string): Promise<void> {\n const folders = await this.getByAccount(accountId);\n\n for (const folder of folders) {\n await folder.refreshCounts();\n }\n }\n\n /**\n * Get folder statistics for an account\n */\n async getAccountStats(accountId: string): Promise<{\n totalFolders: number;\n totalMessages: number;\n totalUnread: number;\n systemFolders: number;\n userFolders: number;\n }> {\n const folders = await this.getByAccount(accountId);\n\n return {\n totalFolders: folders.length,\n totalMessages: folders.reduce((sum, f) => sum + f.messageCount, 0),\n totalUnread: folders.reduce((sum, f) => sum + f.unreadCount, 0),\n systemFolders: folders.filter((f) => f.isSystemFolder()).length,\n userFolders: folders.filter((f) => !f.isSystemFolder()).length,\n };\n }\n\n /**\n * Create standard system folders for an account\n */\n async createSystemFolders(accountId: string): Promise<void> {\n const standardFolders = [\n { name: 'INBOX', path: 'INBOX', specialUse: '\\\\Inbox' },\n { name: 'Sent', path: 'Sent', specialUse: '\\\\Sent' },\n { name: 'Drafts', path: 'Drafts', specialUse: '\\\\Drafts' },\n { name: 'Trash', path: 'Trash', specialUse: '\\\\Trash' },\n { name: 'Spam', path: 'Spam', specialUse: '\\\\Junk' },\n ];\n\n for (const folderData of standardFolders) {\n const existing = await this.getByPath(accountId, folderData.path);\n if (!existing) {\n // Create through the collection so the DB connection is bound; a bare\n // `new EmailFolder(...)` + save() throws \"Database accessed before\n // initialization\" under per-instance DB injection.\n const folder = await this.create({\n accountId,\n ...folderData,\n });\n await folder.save();\n }\n }\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Tenant Helper Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n /**\n * Find all email folders belonging to a specific tenant\n */\n async findByTenant(tenantId: string): Promise<EmailFolder[]> {\n return this.list({ where: { tenantId } });\n }\n\n /**\n * Find all global email folders (no tenant).\n *\n * EmailFolder is @TenantScoped (CTI, own `email_folders` table). Under an\n * active tenant context list({ tenantId: null }) throws and unflagged raw SQL\n * is blocked (#1596); route through the raw helpers.\n */\n async findGlobal(): Promise<EmailFolder[]> {\n return queryGlobal<EmailFolder>(this);\n }\n\n /**\n * Find email folders for a tenant including global folders.\n */\n async findWithGlobals(tenantId: string): Promise<EmailFolder[]> {\n return queryWithGlobals<EmailFolder>(\n this,\n tenantId,\n 'EmailFolder.findWithGlobals',\n );\n }\n}\n"],"mappings":";;;;;;AASO,IAAM,wBAAN,cAAoC,eAA4B;CACrE,OAAgB,aAAa;;;;CAK7B,MAAM,UACJ,WACA,MAC6B;EAE7B,QAAO,MADe,KAAK,KAAK,EAAE,OAAO;GAAE;GAAW;EAAK,EAAE,CAAC,EAAA,CAC/C,MAAM;CACvB;;;;CA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,MAAM;IAAU,MAAM;IAAU,YAAY;GAAW;GACzD;IAAE,MAAM;IAAS,MAAM;IAAS,YAAY;GAAU;GACtD;IAAE,MAAM;IAAQ,MAAM;IAAQ,YAAY;GAAS;EAG5B,GAEvB,IAAI,CAAC,MADkB,KAAK,UAAU,WAAW,WAAW,IAAI,GAS9D,OAAM,MAJe,KAAK,OAAO;GAC/B;GACA,GAAG;EACL,CAAC,EAAA,CACY,KAAK;CAGxB;;;;CASA,MAAM,aAAa,UAA0C;EAC3D,OAAO,KAAK,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;CAC1C;;;;;;;;CASA,MAAM,aAAqC;EACzC,OAAO,YAAyB,IAAI;CACtC;;;;CAKA,MAAM,gBAAgB,UAA0C;EAC9D,OAAO,iBACL,MACA,UACA,6BACF;CACF;AACF"}
@@ -0,0 +1,147 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
+ import { n as assertProtectedEmailAdmission, r as assertProtectedEmailHandoff, t as ProtectedNotificationHandoffError } from "./protected-notification-handoff-mvaEZVp7.js";
3
+ //#region src/senders/EmailSender.ts
4
+ var EmailSender_exports = /* @__PURE__ */ __exportAll({
5
+ EmailSender: () => EmailSender,
6
+ isDefiniteSendRejection: () => isDefiniteSendRejection
7
+ });
8
+ var EmailSender = class {
9
+ providerType = "email";
10
+ client;
11
+ account;
12
+ constructor(client, account) {
13
+ this.client = client;
14
+ this.account = account;
15
+ }
16
+ isReady() {
17
+ return this.client.isConnected();
18
+ }
19
+ async send(message, options) {
20
+ const toAddresses = message.getToAddresses();
21
+ const ccAddresses = message.getCcAddresses();
22
+ const bccAddresses = message.getBccAddresses();
23
+ let attachments;
24
+ try {
25
+ await assertProtectedEmailAdmission(message, options);
26
+ attachments = await this.collectAttachments(message, options);
27
+ } catch (error) {
28
+ return {
29
+ success: false,
30
+ error: error instanceof Error ? error.message : String(error),
31
+ sentAt: /* @__PURE__ */ new Date()
32
+ };
33
+ }
34
+ const emailMessage = {
35
+ from: {
36
+ name: message.fromName || this.account.name,
37
+ address: message.fromAddress || this.account.email
38
+ },
39
+ to: toAddresses.map((r) => ({
40
+ name: r.name,
41
+ address: r.address
42
+ })),
43
+ cc: ccAddresses.length > 0 ? ccAddresses.map((r) => ({
44
+ name: r.name,
45
+ address: r.address
46
+ })) : void 0,
47
+ bcc: bccAddresses.length > 0 ? bccAddresses.map((r) => ({
48
+ name: r.name,
49
+ address: r.address
50
+ })) : void 0,
51
+ subject: message.subject,
52
+ text: message.textBody || message.body,
53
+ html: message.htmlBody || void 0,
54
+ inReplyTo: message.inReplyTo || void 0,
55
+ attachments: attachments.length > 0 ? attachments : void 0
56
+ };
57
+ try {
58
+ await assertProtectedEmailHandoff(message, attachments, options, emailMessage);
59
+ const result = await this.client.send(emailMessage);
60
+ return {
61
+ success: true,
62
+ providerMessageId: result.messageId,
63
+ accepted: result.accepted,
64
+ rejected: result.rejected,
65
+ providerResponse: { response: result.response },
66
+ sentAt: /* @__PURE__ */ new Date()
67
+ };
68
+ } catch (error) {
69
+ return {
70
+ success: false,
71
+ error: error instanceof Error ? error.message : String(error),
72
+ ...error instanceof ProtectedNotificationHandoffError || isDefiniteSendRejection(error) ? {} : { outcomeUnknown: true },
73
+ sentAt: /* @__PURE__ */ new Date()
74
+ };
75
+ }
76
+ }
77
+ /**
78
+ * The message's stored `Attachment` rows followed by the send-time bytes.
79
+ *
80
+ * Stored rows are listed through the message's own options, so the lookup
81
+ * runs under the same tenant context as the message. A row's file is read
82
+ * through `Attachment.readContent()`, the package's one attachment-reading
83
+ * seam, so the bytes are handed to the transport rather than a path it
84
+ * would have to resolve itself.
85
+ */
86
+ async collectAttachments(message, options) {
87
+ const resolved = [];
88
+ const stored = message.isPersisted ? await message.getAttachments() : [];
89
+ for (const attachment of stored) {
90
+ if (message.tenantId && attachment.tenantId && attachment.tenantId !== message.tenantId) throw new Error(`Attachment "${attachment.filename}" belongs to another tenant than its message.`);
91
+ if (!attachment.filePath) throw new Error(`Attachment "${attachment.filename}" has no stored file to send` + (attachment.sourceUrl ? " (a sourceUrl is not fetched at send time)." : "."));
92
+ const content = await attachment.readContent();
93
+ if (!content) throw new Error(`Attachment "${attachment.filename}" could not be read from "${attachment.filePath}": the file is missing or unreadable, or the files SDK is not loaded (see Attachment.readContent()).`);
94
+ resolved.push({
95
+ filename: attachment.filename,
96
+ contentType: attachment.contentType || "application/octet-stream",
97
+ size: content.length,
98
+ content: Buffer.from(content),
99
+ contentId: attachment.contentId || void 0,
100
+ contentDisposition: attachment.contentDisposition
101
+ });
102
+ }
103
+ for (const attachment of options?.attachments ?? []) {
104
+ if (!attachment.filename) throw new Error("A send-time attachment needs a filename.");
105
+ if (!attachment.content) throw new Error(`Send-time attachment "${attachment.filename}" has no content.`);
106
+ const content = Buffer.from(attachment.content);
107
+ resolved.push({
108
+ filename: attachment.filename,
109
+ contentType: attachment.contentType || "application/octet-stream",
110
+ size: content.length,
111
+ content,
112
+ contentId: attachment.contentId,
113
+ contentDisposition: attachment.contentDisposition ?? "attachment"
114
+ });
115
+ }
116
+ return resolved;
117
+ }
118
+ };
119
+ var DEFINITE_EMAIL_ERROR_CODES = /* @__PURE__ */ new Set([
120
+ "AUTHENTICATION_ERROR",
121
+ "AUTHORIZATION_ERROR",
122
+ "INVALID_MESSAGE",
123
+ "ATTACHMENT_ERROR"
124
+ ]);
125
+ var NEVER_CONNECTED_CODES = /* @__PURE__ */ new Set([
126
+ "ECONNREFUSED",
127
+ "ENOTFOUND",
128
+ "EHOSTUNREACH",
129
+ "EAI_AGAIN"
130
+ ]);
131
+ function isDefiniteSendRejection(error) {
132
+ if (!error || typeof error !== "object") return false;
133
+ const candidates = [error, error.cause].filter((value) => !!value && typeof value === "object");
134
+ for (const candidate of candidates) {
135
+ if (typeof candidate.responseCode === "number") return true;
136
+ if (typeof candidate.code === "string") {
137
+ if (DEFINITE_EMAIL_ERROR_CODES.has(candidate.code)) return true;
138
+ if (NEVER_CONNECTED_CODES.has(candidate.code)) return true;
139
+ }
140
+ }
141
+ const sendError = error;
142
+ return sendError.code === "SEND_ERROR" && Array.isArray(sendError.accepted) && sendError.accepted.length === 0;
143
+ }
144
+ //#endregion
145
+ export { EmailSender_exports as n, EmailSender as t };
146
+
147
+ //# sourceMappingURL=EmailSender-B-Rtq9du.js.map