@happyvertical/smrt-messages 0.70.1 → 0.70.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +4 -0
- package/agents/send-approval.md +28 -0
- package/dist/access.d.ts +22 -0
- package/dist/access.d.ts.map +1 -1
- package/dist/chunks/{AttachmentCollection-Cs6dC7vz.js → AttachmentCollection-Di2aRb2k.js} +52 -5
- package/dist/chunks/AttachmentCollection-Di2aRb2k.js.map +1 -0
- package/dist/chunks/{Email-C5PO3e6c.js → Email-tEYH6ZRw.js} +6 -6
- package/dist/chunks/{Email-C5PO3e6c.js.map → Email-tEYH6ZRw.js.map} +1 -1
- package/dist/chunks/{EmailAccountCollection-BJH0rOH2.js → EmailAccountCollection-DWo_a-X5.js} +55 -20
- package/dist/chunks/EmailAccountCollection-DWo_a-X5.js.map +1 -0
- package/dist/chunks/{EmailCollection-3iN8bLk4.js → EmailCollection-_Z2JY26I.js} +3 -3
- package/dist/chunks/{EmailCollection-3iN8bLk4.js.map → EmailCollection-_Z2JY26I.js.map} +1 -1
- package/dist/chunks/{EmailFolder-DR6Rz6n9.js → EmailFolder-TyoFZVcC.js} +6 -6
- package/dist/chunks/{EmailFolder-DR6Rz6n9.js.map → EmailFolder-TyoFZVcC.js.map} +1 -1
- package/dist/chunks/{EmailFolderCollection-BByXjljN.js → EmailFolderCollection-CFtttkx6.js} +2 -2
- package/dist/chunks/{EmailFolderCollection-BByXjljN.js.map → EmailFolderCollection-CFtttkx6.js.map} +1 -1
- package/dist/chunks/{EmailSender-DJ899ng7.js → EmailSender-bHwAYzBO.js} +2 -2
- package/dist/chunks/{EmailSender-DJ899ng7.js.map → EmailSender-bHwAYzBO.js.map} +1 -1
- package/dist/chunks/{Message-DuyeDIeW.js → Message-DC877Gl7.js} +145 -10
- package/dist/chunks/Message-DC877Gl7.js.map +1 -0
- package/dist/chunks/{MessageCollection-CrL6570U.js → MessageCollection-yZ6RyAtB.js} +2 -2
- package/dist/chunks/{MessageCollection-CrL6570U.js.map → MessageCollection-yZ6RyAtB.js.map} +1 -1
- package/dist/chunks/{MessagingEndpointCollection-5jqgi9mo.js → MessagingEndpointCollection-CNwpv_ZW.js} +2 -2
- package/dist/chunks/{MessagingEndpointCollection-5jqgi9mo.js.map → MessagingEndpointCollection-CNwpv_ZW.js.map} +1 -1
- package/dist/connect.js +1 -1
- package/dist/index.js +16 -16
- package/dist/manifest.json +63 -1
- package/dist/models/Attachment.d.ts +20 -1
- package/dist/models/Attachment.d.ts.map +1 -1
- package/dist/models/Message.d.ts +32 -0
- package/dist/models/Message.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +59 -9
- package/dist/smrt-knowledge.okf.md +2 -2
- package/package.json +12 -12
- package/dist/chunks/AttachmentCollection-Cs6dC7vz.js.map +0 -1
- package/dist/chunks/EmailAccountCollection-BJH0rOH2.js.map +0 -1
- package/dist/chunks/Message-DuyeDIeW.js.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
2
|
import { queryGlobal, queryWithGlobals } from "../host.js";
|
|
3
|
-
import { t as MessageCollection } from "./MessageCollection-
|
|
4
|
-
import { t as Email } from "./Email-
|
|
3
|
+
import { t as MessageCollection } from "./MessageCollection-yZ6RyAtB.js";
|
|
4
|
+
import { t as Email } from "./Email-tEYH6ZRw.js";
|
|
5
5
|
//#region src/collections/EmailCollection.ts
|
|
6
6
|
var EmailCollection_exports = /* @__PURE__ */ __exportAll({ EmailCollection: () => EmailCollection });
|
|
7
7
|
var EmailCollection = class extends MessageCollection {
|
|
@@ -193,4 +193,4 @@ var EmailCollection = class extends MessageCollection {
|
|
|
193
193
|
//#endregion
|
|
194
194
|
export { EmailCollection_exports as n, EmailCollection as t };
|
|
195
195
|
|
|
196
|
-
//# sourceMappingURL=EmailCollection-
|
|
196
|
+
//# sourceMappingURL=EmailCollection-_Z2JY26I.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EmailCollection-3iN8bLk4.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 * Rank emails by meaning (core `semanticSearchIds`), with `where` applied\n * BEFORE ranking so a hit can never come from outside the caller's scope.\n * Returns null when embeddings are not available (not configured, or the\n * embedding provider failed) so callers fall back to keyword search;\n * authorization and database failures still throw.\n */\n async semanticMatches(\n query: string,\n where: Record<string, unknown>,\n options: { limit?: number; minSimilarity?: number } = {},\n ): Promise<Array<{ id: string; similarity: number }> | null> {\n const result = await this.semanticSearchIdsWithAvailability(query, {\n limit: options.limit ?? 200,\n minSimilarity: options.minSimilarity ?? 0.2,\n where,\n });\n return result.available ? result.matches : null;\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,IA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AI;CAChC;CAEA,MAAe,gBAAgB,UAAoC;EACjE,OAAO,iBAAwB,MAAM,UAAU,uBAAuB;CACxE;AACF"}
|
|
1
|
+
{"version":3,"file":"EmailCollection-_Z2JY26I.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 * Rank emails by meaning (core `semanticSearchIds`), with `where` applied\n * BEFORE ranking so a hit can never come from outside the caller's scope.\n * Returns null when embeddings are not available (not configured, or the\n * embedding provider failed) so callers fall back to keyword search;\n * authorization and database failures still throw.\n */\n async semanticMatches(\n query: string,\n where: Record<string, unknown>,\n options: { limit?: number; minSimilarity?: number } = {},\n ): Promise<Array<{ id: string; similarity: number }> | null> {\n const result = await this.semanticSearchIdsWithAvailability(query, {\n limit: options.limit ?? 200,\n minSimilarity: options.minSimilarity ?? 0.2,\n where,\n });\n return result.available ? result.matches : null;\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;CAC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,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 { T as assertHydratedMailAccess } from "./EmailAccountCollection-
|
|
2
|
+
import { T as assertHydratedMailAccess } from "./EmailAccountCollection-DWo_a-X5.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
|
|
@@ -69,14 +69,14 @@ var EmailFolder = class extends SmrtObject {
|
|
|
69
69
|
*/
|
|
70
70
|
async getAccount() {
|
|
71
71
|
if (!this.accountId) return null;
|
|
72
|
-
const { EmailAccountCollection } = await import("./EmailAccountCollection-
|
|
72
|
+
const { EmailAccountCollection } = await import("./EmailAccountCollection-DWo_a-X5.js").then((n) => n.n);
|
|
73
73
|
return await (await EmailAccountCollection.create(this.options)).get({ id: this.accountId });
|
|
74
74
|
}
|
|
75
75
|
/**
|
|
76
76
|
* Get all emails in this folder
|
|
77
77
|
*/
|
|
78
78
|
async getEmails(limit) {
|
|
79
|
-
const { EmailCollection } = await import("./EmailCollection-
|
|
79
|
+
const { EmailCollection } = await import("./EmailCollection-_Z2JY26I.js").then((n) => n.n);
|
|
80
80
|
const collection = await EmailCollection.create(this.options);
|
|
81
81
|
const options = { where: { folderId: this.id } };
|
|
82
82
|
if (limit) options.limit = limit;
|
|
@@ -86,7 +86,7 @@ var EmailFolder = class extends SmrtObject {
|
|
|
86
86
|
* Get unread emails in this folder
|
|
87
87
|
*/
|
|
88
88
|
async getUnreadEmails(limit) {
|
|
89
|
-
const { EmailCollection } = await import("./EmailCollection-
|
|
89
|
+
const { EmailCollection } = await import("./EmailCollection-_Z2JY26I.js").then((n) => n.n);
|
|
90
90
|
const collection = await EmailCollection.create(this.options);
|
|
91
91
|
const options = { where: {
|
|
92
92
|
folderId: this.id,
|
|
@@ -101,7 +101,7 @@ var EmailFolder = class extends SmrtObject {
|
|
|
101
101
|
async refreshCounts() {
|
|
102
102
|
if (!this.id) throw new Error("EmailFolder.refreshCounts requires a persisted folder (missing id)");
|
|
103
103
|
const folderId = this.id;
|
|
104
|
-
const { EmailCollection } = await import("./EmailCollection-
|
|
104
|
+
const { EmailCollection } = await import("./EmailCollection-_Z2JY26I.js").then((n) => n.n);
|
|
105
105
|
const collection = await EmailCollection.create(this.options);
|
|
106
106
|
this.messageCount = await collection.countByFolder(folderId);
|
|
107
107
|
this.unreadCount = await collection.countUnreadByFolder(folderId);
|
|
@@ -178,4 +178,4 @@ EmailFolder = __decorateClass([TenantScoped({ mode: "optional" }), smrt({
|
|
|
178
178
|
//#endregion
|
|
179
179
|
export { EmailFolder_exports as n, EmailFolder as t };
|
|
180
180
|
|
|
181
|
-
//# sourceMappingURL=EmailFolder-
|
|
181
|
+
//# sourceMappingURL=EmailFolder-TyoFZVcC.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EmailFolder-
|
|
1
|
+
{"version":3,"file":"EmailFolder-TyoFZVcC.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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|
-
import { t as EmailFolder } from "./EmailFolder-
|
|
3
|
+
import { t as EmailFolder } from "./EmailFolder-TyoFZVcC.js";
|
|
4
4
|
import { SmrtCollection } from "@happyvertical/smrt-core";
|
|
5
5
|
//#region src/collections/EmailFolderCollection.ts
|
|
6
6
|
var EmailFolderCollection_exports = /* @__PURE__ */ __exportAll({ EmailFolderCollection: () => EmailFolderCollection });
|
|
@@ -174,4 +174,4 @@ var EmailFolderCollection = class extends SmrtCollection {
|
|
|
174
174
|
//#endregion
|
|
175
175
|
export { EmailFolderCollection_exports as n, EmailFolderCollection as t };
|
|
176
176
|
|
|
177
|
-
//# sourceMappingURL=EmailFolderCollection-
|
|
177
|
+
//# sourceMappingURL=EmailFolderCollection-CFtttkx6.js.map
|
package/dist/chunks/{EmailFolderCollection-BByXjljN.js.map → EmailFolderCollection-CFtttkx6.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EmailFolderCollection-
|
|
1
|
+
{"version":3,"file":"EmailFolderCollection-CFtttkx6.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;;;;CAKA,MAAM,aAAa,WAA2C;EAC5D,OAAO,MAAM,KAAK,KAAK,EAAE,OAAO,EAAE,UAAU,EAAE,CAAC;CACjD;;;;CAKA,MAAM,SAAS,WAAgD;EAE7D,QAAO,MADe,KAAK,aAAa,SAAS,EAAA,CAClC,MAAM,MAAM,EAAE,QAAQ,CAAC,KAAK;CAC7C;;;;CAKA,MAAM,QAAQ,WAAgD;EAE5D,QAAO,MADe,KAAK,aAAa,SAAS,EAAA,CAClC,MAAM,MAAM,EAAE,OAAO,CAAC,KAAK;CAC5C;;;;CAKA,MAAM,UAAU,WAAgD;EAE9D,QAAO,MADe,KAAK,aAAa,SAAS,EAAA,CAClC,MAAM,MAAM,EAAE,SAAS,CAAC,KAAK;CAC9C;;;;CAKA,MAAM,SAAS,WAAgD;EAE7D,QAAO,MADe,KAAK,aAAa,SAAS,EAAA,CAClC,MAAM,MAAM,EAAE,QAAQ,CAAC,KAAK;CAC7C;;;;CAKA,MAAM,QAAQ,WAAgD;EAE5D,QAAO,MADe,KAAK,aAAa,SAAS,EAAA,CAClC,MAAM,MAAM,E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OAAO,cAAc;CAE/B;;;;CAKA,MAAM,gBAAgB,WAMnB;EACD,MAAM,UAAU,MAAM,KAAK,aAAa,SAAS;EAEjD,OAAO;GACL,cAAc,QAAQ;GACtB,eAAe,QAAQ,QAAQ,KAAK,MAAM,MAAM,EAAE,cAAc,CAAC;GACjE,aAAa,QAAQ,QAAQ,KAAK,MAAM,MAAM,EAAE,aAAa,CAAC;GAC9D,eAAe,QAAQ,QAAQ,MAAM,EAAE,eAAe,CAAC,CAAA,CAAE;GACzD,aAAa,QAAQ,QAAQ,MAAM,CAAC,EAAE,eAAe,CAAC,CAAA,CAAE;EAC1D;CACF;;;;CAKA,MAAM,oBAAoB,WAAkC;EAS1D,KAAA,MAAW,cAAc;GAPvB;IAAE,MAAM;IAAS,MAAM;IAAS,YAAY;GAAU;GACtD;IAAE,MAAM;IAAQ,MAAM;IAAQ,YAAY;GAAS;GACnD;IAAE,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"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
|
-
import { d as assertApprovedAttachments } from "./EmailAccountCollection-
|
|
2
|
+
import { d as assertApprovedAttachments } from "./EmailAccountCollection-DWo_a-X5.js";
|
|
3
3
|
import { n as assertProtectedEmailAdmission, r as assertProtectedEmailHandoff, t as ProtectedNotificationHandoffError } from "./protected-notification-handoff-mvaEZVp7.js";
|
|
4
4
|
//#region src/senders/EmailSender.ts
|
|
5
5
|
var EmailSender_exports = /* @__PURE__ */ __exportAll({
|
|
@@ -151,4 +151,4 @@ function isDefiniteSendRejection(error) {
|
|
|
151
151
|
//#endregion
|
|
152
152
|
export { EmailSender_exports as n, EmailSender as t };
|
|
153
153
|
|
|
154
|
-
//# sourceMappingURL=EmailSender-
|
|
154
|
+
//# sourceMappingURL=EmailSender-bHwAYzBO.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"EmailSender-DJ899ng7.js","names":[],"sources":["../../src/senders/EmailSender.ts"],"sourcesContent":["import {\n assertProtectedEmailAdmission,\n assertProtectedEmailHandoff,\n ProtectedNotificationHandoffError,\n} from '../protected-notification-handoff.js';\n/**\n * EmailSender — sends email messages via the SDK EmailClient\n */\n\nimport type { Attachment, EmailClient } from '@happyvertical/email';\nimport type { Email } from '../models/Email';\nimport type { EmailAccount } from '../models/EmailAccount';\nimport { assertApprovedAttachments } from '../send-approval.js';\nimport type {\n MessageSenderInterface,\n MessageSendResult,\n SendEmailOptions,\n} from '../types';\n\nexport class EmailSender implements MessageSenderInterface {\n readonly providerType = 'email';\n private client: EmailClient;\n private account: EmailAccount;\n\n constructor(client: EmailClient, account: EmailAccount) {\n this.client = client;\n this.account = account;\n }\n\n isReady(): boolean {\n return this.client.isConnected();\n }\n\n async send(\n message: Email,\n options?: SendEmailOptions,\n ): Promise<MessageSendResult> {\n const toAddresses = message.getToAddresses();\n const ccAddresses = message.getCcAddresses();\n const bccAddresses = message.getBccAddresses();\n\n // Resolve every attachment before anything reaches the transport: a file\n // that cannot be read fails the send instead of leaving silently (#3808).\n let attachments: Attachment[];\n try {\n await assertProtectedEmailAdmission(message, options);\n attachments = await this.collectAttachments(message, options);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n sentAt: new Date(),\n };\n }\n\n const emailMessage = {\n from: {\n name: message.fromName || this.account.name,\n address: message.fromAddress || this.account.email,\n },\n to: toAddresses.map((r) => ({\n name: r.name,\n address: r.address,\n })),\n cc:\n ccAddresses.length > 0\n ? ccAddresses.map((r) => ({ name: r.name, address: r.address }))\n : undefined,\n bcc:\n bccAddresses.length > 0\n ? bccAddresses.map((r) => ({ name: r.name, address: r.address }))\n : undefined,\n subject: message.subject,\n text: message.textBody || message.body,\n html: message.htmlBody || undefined,\n inReplyTo: message.inReplyTo || undefined,\n attachments: attachments.length > 0 ? attachments : undefined,\n };\n\n try {\n await assertProtectedEmailHandoff(\n message,\n attachments as unknown as NonNullable<SendEmailOptions['attachments']>,\n options,\n emailMessage,\n );\n const result = await this.client.send(emailMessage);\n\n return {\n success: true,\n providerMessageId: result.messageId,\n accepted: result.accepted,\n rejected: result.rejected,\n providerResponse: { response: result.response },\n sentAt: new Date(),\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n ...(error instanceof ProtectedNotificationHandoffError ||\n isDefiniteSendRejection(error)\n ? {}\n : { outcomeUnknown: true }),\n sentAt: new Date(),\n };\n }\n }\n\n /**\n * The message's stored `Attachment` rows followed by the send-time bytes.\n *\n * Stored rows are listed through the message's own options, so the lookup\n * runs under the same tenant context as the message. A row's file is read\n * through `Attachment.readContent()`, the package's one attachment-reading\n * seam, so the bytes are handed to the transport rather than a path it\n * would have to resolve itself.\n */\n private async collectAttachments(\n message: Email,\n options?: SendEmailOptions,\n ): Promise<Attachment[]> {\n const resolved: Attachment[] = [];\n const handed: Parameters<typeof assertApprovedAttachments>[1] = [];\n\n // Only a message backed by a row can own attachment rows; an unsaved\n // draft sent directly through the sender has none to look up.\n const stored = message.isPersisted ? await message.getAttachments() : [];\n for (const attachment of stored) {\n if (\n message.tenantId &&\n attachment.tenantId &&\n attachment.tenantId !== message.tenantId\n ) {\n throw new Error(\n `Attachment \"${attachment.filename}\" belongs to another tenant than its message.`,\n );\n }\n if (!attachment.filePath) {\n throw new Error(\n `Attachment \"${attachment.filename}\" has no stored file to send` +\n (attachment.sourceUrl\n ? ' (a sourceUrl is not fetched at send time).'\n : '.'),\n );\n }\n const content = await attachment.readContent();\n if (!content) {\n throw new Error(\n `Attachment \"${attachment.filename}\" could not be read from \"${attachment.filePath}\": ` +\n 'the file is missing or unreadable, or the files SDK is not loaded ' +\n '(see Attachment.readContent()).',\n );\n }\n handed.push({ row: attachment, content });\n resolved.push({\n filename: attachment.filename,\n contentType: attachment.contentType || 'application/octet-stream',\n size: content.length,\n content: Buffer.from(content),\n contentId: attachment.contentId || undefined,\n contentDisposition: attachment.contentDisposition,\n });\n }\n\n // A send an approval released carries exactly the approved files.\n assertApprovedAttachments(message, handed);\n\n for (const attachment of options?.attachments ?? []) {\n if (!attachment.filename) {\n throw new Error('A send-time attachment needs a filename.');\n }\n if (!attachment.content) {\n throw new Error(\n `Send-time attachment \"${attachment.filename}\" has no content.`,\n );\n }\n // Own the bytes handed to the SDK so callers cannot mutate the approved\n // document while an asynchronous provider send is in flight.\n const content = Buffer.from(attachment.content);\n resolved.push({\n filename: attachment.filename,\n contentType: attachment.contentType || 'application/octet-stream',\n size: content.length,\n content,\n contentId: attachment.contentId,\n contentDisposition: attachment.contentDisposition ?? 'attachment',\n });\n }\n\n return resolved;\n }\n}\n\n/** Error codes the SDK email clients use for a send that was refused. */\nconst DEFINITE_EMAIL_ERROR_CODES = new Set([\n 'AUTHENTICATION_ERROR',\n 'AUTHORIZATION_ERROR',\n 'INVALID_MESSAGE',\n 'ATTACHMENT_ERROR',\n]);\n\n/** Socket errors raised before any connection to the server existed. */\nconst NEVER_CONNECTED_CODES = new Set([\n 'ECONNREFUSED',\n 'ENOTFOUND',\n 'EHOSTUNREACH',\n 'EAI_AGAIN',\n]);\n\n/**\n * Whether a provider send error proves the message was not accepted: the\n * server answered with an SMTP reply code, the SDK classified it as an\n * authentication/validation failure, a send error accepted no recipient, or\n * the connection was never made. Anything else (a timeout, a reset\n * connection, an unclassified error) may have happened after the server took\n * the message, so its outcome is unknown.\n */\nexport function isDefiniteSendRejection(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false;\n const candidates = [error, (error as { cause?: unknown }).cause].filter(\n (value): value is Record<string, unknown> =>\n !!value && typeof value === 'object',\n );\n for (const candidate of candidates) {\n if (typeof candidate.responseCode === 'number') return true;\n if (typeof candidate.code === 'string') {\n if (DEFINITE_EMAIL_ERROR_CODES.has(candidate.code)) return true;\n if (NEVER_CONNECTED_CODES.has(candidate.code)) return true;\n }\n }\n const sendError = error as { code?: unknown; accepted?: unknown };\n return (\n sendError.code === 'SEND_ERROR' &&\n Array.isArray(sendError.accepted) &&\n sendError.accepted.length === 0\n );\n}\n"],"mappings":";;;;;;;;AAmBO,IAAM,cAAN,MAAoD;CAChD,eAAe;CAChB;CACA;CAER,YAAY,QAAqB,SAAuB;EACtD,KAAK,SAAS;EACd,KAAK,UAAU;CACjB;CAEA,UAAmB;EACjB,OAAO,KAAK,OAAO,YAAY;CACjC;CAEA,MAAM,KACJ,SACA,SAC4B;EAC5B,MAAM,cAAc,QAAQ,eAAe;EAC3C,MAAM,cAAc,QAAQ,eAAe;EAC3C,MAAM,eAAe,QAAQ,gBAAgB;EAI7C,IAAI;EACJ,IAAI;GACF,MAAM,8BAA8B,SAAS,OAAO;GACpD,cAAc,MAAM,KAAK,mBAAmB,SAAS,OAAO;EAC9D,SAAS,OAAO;GACd,OAAO;IACL,SAAS;IACT,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IAC5D,wBAAQ,IAAI,KAAK;GACnB;EACF;EAEA,MAAM,eAAe;GACnB,MAAM;IACJ,MAAM,QAAQ,YAAY,KAAK,QAAQ;IACvC,SAAS,QAAQ,eAAe,KAAK,QAAQ;GAC/C;GACA,IAAI,YAAY,KAAK,OAAO;IAC1B,MAAM,EAAE;IACR,SAAS,EAAE;GAC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GAAG,OAAO;GAC3D,IAAI,sBAAsB,IAAI,UAAU,IAAI,GAAG,OAAO;EACxD;CACF;CACA,MAAM,YAAY;CAClB,OACE,UAAU,SAAS,gBACnB,MAAM,QAAQ,UAAU,QAAQ,KAChC,UAAU,SAAS,WAAW;AAElC"}
|
|
1
|
+
{"version":3,"file":"EmailSender-bHwAYzBO.js","names":[],"sources":["../../src/senders/EmailSender.ts"],"sourcesContent":["import {\n assertProtectedEmailAdmission,\n assertProtectedEmailHandoff,\n ProtectedNotificationHandoffError,\n} from '../protected-notification-handoff.js';\n/**\n * EmailSender — sends email messages via the SDK EmailClient\n */\n\nimport type { Attachment, EmailClient } from '@happyvertical/email';\nimport type { Email } from '../models/Email';\nimport type { EmailAccount } from '../models/EmailAccount';\nimport { assertApprovedAttachments } from '../send-approval.js';\nimport type {\n MessageSenderInterface,\n MessageSendResult,\n SendEmailOptions,\n} from '../types';\n\nexport class EmailSender implements MessageSenderInterface {\n readonly providerType = 'email';\n private client: EmailClient;\n private account: EmailAccount;\n\n constructor(client: EmailClient, account: EmailAccount) {\n this.client = client;\n this.account = account;\n }\n\n isReady(): boolean {\n return this.client.isConnected();\n }\n\n async send(\n message: Email,\n options?: SendEmailOptions,\n ): Promise<MessageSendResult> {\n const toAddresses = message.getToAddresses();\n const ccAddresses = message.getCcAddresses();\n const bccAddresses = message.getBccAddresses();\n\n // Resolve every attachment before anything reaches the transport: a file\n // that cannot be read fails the send instead of leaving silently (#3808).\n let attachments: Attachment[];\n try {\n await assertProtectedEmailAdmission(message, options);\n attachments = await this.collectAttachments(message, options);\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n sentAt: new Date(),\n };\n }\n\n const emailMessage = {\n from: {\n name: message.fromName || this.account.name,\n address: message.fromAddress || this.account.email,\n },\n to: toAddresses.map((r) => ({\n name: r.name,\n address: r.address,\n })),\n cc:\n ccAddresses.length > 0\n ? ccAddresses.map((r) => ({ name: r.name, address: r.address }))\n : undefined,\n bcc:\n bccAddresses.length > 0\n ? bccAddresses.map((r) => ({ name: r.name, address: r.address }))\n : undefined,\n subject: message.subject,\n text: message.textBody || message.body,\n html: message.htmlBody || undefined,\n inReplyTo: message.inReplyTo || undefined,\n attachments: attachments.length > 0 ? attachments : undefined,\n };\n\n try {\n await assertProtectedEmailHandoff(\n message,\n attachments as unknown as NonNullable<SendEmailOptions['attachments']>,\n options,\n emailMessage,\n );\n const result = await this.client.send(emailMessage);\n\n return {\n success: true,\n providerMessageId: result.messageId,\n accepted: result.accepted,\n rejected: result.rejected,\n providerResponse: { response: result.response },\n sentAt: new Date(),\n };\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n ...(error instanceof ProtectedNotificationHandoffError ||\n isDefiniteSendRejection(error)\n ? {}\n : { outcomeUnknown: true }),\n sentAt: new Date(),\n };\n }\n }\n\n /**\n * The message's stored `Attachment` rows followed by the send-time bytes.\n *\n * Stored rows are listed through the message's own options, so the lookup\n * runs under the same tenant context as the message. A row's file is read\n * through `Attachment.readContent()`, the package's one attachment-reading\n * seam, so the bytes are handed to the transport rather than a path it\n * would have to resolve itself.\n */\n private async collectAttachments(\n message: Email,\n options?: SendEmailOptions,\n ): Promise<Attachment[]> {\n const resolved: Attachment[] = [];\n const handed: Parameters<typeof assertApprovedAttachments>[1] = [];\n\n // Only a message backed by a row can own attachment rows; an unsaved\n // draft sent directly through the sender has none to look up.\n const stored = message.isPersisted ? await message.getAttachments() : [];\n for (const attachment of stored) {\n if (\n message.tenantId &&\n attachment.tenantId &&\n attachment.tenantId !== message.tenantId\n ) {\n throw new Error(\n `Attachment \"${attachment.filename}\" belongs to another tenant than its message.`,\n );\n }\n if (!attachment.filePath) {\n throw new Error(\n `Attachment \"${attachment.filename}\" has no stored file to send` +\n (attachment.sourceUrl\n ? ' (a sourceUrl is not fetched at send time).'\n : '.'),\n );\n }\n const content = await attachment.readContent();\n if (!content) {\n throw new Error(\n `Attachment \"${attachment.filename}\" could not be read from \"${attachment.filePath}\": ` +\n 'the file is missing or unreadable, or the files SDK is not loaded ' +\n '(see Attachment.readContent()).',\n );\n }\n handed.push({ row: attachment, content });\n resolved.push({\n filename: attachment.filename,\n contentType: attachment.contentType || 'application/octet-stream',\n size: content.length,\n content: Buffer.from(content),\n contentId: attachment.contentId || undefined,\n contentDisposition: attachment.contentDisposition,\n });\n }\n\n // A send an approval released carries exactly the approved files.\n assertApprovedAttachments(message, handed);\n\n for (const attachment of options?.attachments ?? []) {\n if (!attachment.filename) {\n throw new Error('A send-time attachment needs a filename.');\n }\n if (!attachment.content) {\n throw new Error(\n `Send-time attachment \"${attachment.filename}\" has no content.`,\n );\n }\n // Own the bytes handed to the SDK so callers cannot mutate the approved\n // document while an asynchronous provider send is in flight.\n const content = Buffer.from(attachment.content);\n resolved.push({\n filename: attachment.filename,\n contentType: attachment.contentType || 'application/octet-stream',\n size: content.length,\n content,\n contentId: attachment.contentId,\n contentDisposition: attachment.contentDisposition ?? 'attachment',\n });\n }\n\n return resolved;\n }\n}\n\n/** Error codes the SDK email clients use for a send that was refused. */\nconst DEFINITE_EMAIL_ERROR_CODES = new Set([\n 'AUTHENTICATION_ERROR',\n 'AUTHORIZATION_ERROR',\n 'INVALID_MESSAGE',\n 'ATTACHMENT_ERROR',\n]);\n\n/** Socket errors raised before any connection to the server existed. */\nconst NEVER_CONNECTED_CODES = new Set([\n 'ECONNREFUSED',\n 'ENOTFOUND',\n 'EHOSTUNREACH',\n 'EAI_AGAIN',\n]);\n\n/**\n * Whether a provider send error proves the message was not accepted: the\n * server answered with an SMTP reply code, the SDK classified it as an\n * authentication/validation failure, a send error accepted no recipient, or\n * the connection was never made. Anything else (a timeout, a reset\n * connection, an unclassified error) may have happened after the server took\n * the message, so its outcome is unknown.\n */\nexport function isDefiniteSendRejection(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false;\n const candidates = [error, (error as { cause?: unknown }).cause].filter(\n (value): value is Record<string, unknown> =>\n !!value && typeof value === 'object',\n );\n for (const candidate of candidates) {\n if (typeof candidate.responseCode === 'number') return true;\n if (typeof candidate.code === 'string') {\n if (DEFINITE_EMAIL_ERROR_CODES.has(candidate.code)) return true;\n if (NEVER_CONNECTED_CODES.has(candidate.code)) return true;\n }\n }\n const sendError = error as { code?: unknown; accepted?: unknown };\n return (\n sendError.code === 'SEND_ERROR' &&\n Array.isArray(sendError.accepted) &&\n sendError.accepted.length === 0\n );\n}\n"],"mappings":";;;;;;;;AAmBO,IAAM,cAAN,MAAoD;CAChD,eAAe;CAChB;CACA;CAER,YAAY,QAAqB,SAAuB;EACtD,KAAK,SAAS;EACd,KAAK,UAAU;CACjB;CAEA,UAAmB;EACjB,OAAO,KAAK,OAAO,YAAY;CACjC;CAEA,MAAM,KACJ,SACA,SAC4B;EAC5B,MAAM,cAAc,QAAQ,eAAe;EAC3C,MAAM,cAAc,QAAQ,eAAe;EAC3C,MAAM,eAAe,QAAQ,gBAAgB;EAI7C,IAAI;EACJ,IAAI;GACF,MAAM,8BAA8B,SAAS,OAAO;GACpD,cAAc,MAAM,KAAK,mBAAmB,SAAS,OAAO;EAC9D,SAAS,OAAO;GACd,OAAO;IACL,SAAS;IACT,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IAC5D,wBAAQ,IAAI,KAAK;GACnB;EACF;EAEA,MAAM,eAAe;GACnB,MAAM;IACJ,MAAM,QAAQ,YAAY,KAAK,QAAQ;IACvC,SAAS,QAAQ,eAAe,KAAK,QAAQ;GAC/C;GACA,IAAI,YAAY,KAAK,OAAO;IAC1B,MAAM,EAAE;IACR,SAAS,EAAE;GACb,EAAE;GACF,IACE,YAAY,SAAS,IACjB,YAAY,KAAK,OAAO;IAAE,MAAM,EAAE;IAAM,SAAS,EAAE;GAAQ,EAAE,IAC7D,KAAA;GACN,KACE,aAAa,SAAS,IAClB,aAAa,KAAK,OAAO;IAAE,MAAM,EAAE;IAAM,SAAS,EAAE;GAAQ,EAAE,IAC9D,KAAA;GACN,SAAS,QAAQ;GACjB,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MailAccessError, F as inMailSystemAccess, O as assertMailScopeOn, R as isUnsentDraft, T as assertHydratedMailAccess, U as resolveMailPrincipal, f as auditMailAction, h as holdAgentSend, j as decideMailAccess, u as approvedDraftChanged, v as stampHandledBy, z as learnMailAccessOptions } from "./EmailAccountCollection-DWo_a-X5.js";
|
|
2
2
|
import { a as assertProtectedNotificationRetry, c as beginProtectedNotificationSend, i as assertProtectedNotificationDelete, o as assertProtectedNotificationSave, s as assertProtectedSenderHandoff, t as ProtectedNotificationHandoffError, u as rememberNotificationOrigin } from "./protected-notification-handoff-mvaEZVp7.js";
|
|
3
3
|
import { ObjectRegistry, SmrtObject, crossPackageRef, field, foreignKey, smrt, usesEmbeddedRevisionFallback, withEmbeddedWriteQueue } from "@happyvertical/smrt-core";
|
|
4
4
|
import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy/decorators";
|
|
@@ -53,6 +53,43 @@ async function saveSendLifecycle(message) {
|
|
|
53
53
|
lifecycleSaves.delete(message);
|
|
54
54
|
}
|
|
55
55
|
}
|
|
56
|
+
var heldSaves = /* @__PURE__ */ new WeakSet();
|
|
57
|
+
async function saveHeld(message) {
|
|
58
|
+
heldSaves.add(message);
|
|
59
|
+
try {
|
|
60
|
+
await message.save();
|
|
61
|
+
} finally {
|
|
62
|
+
heldSaves.delete(message);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
var SEND_PATH_MAY_CHANGE = /* @__PURE__ */ new Set([
|
|
66
|
+
"sendStatus",
|
|
67
|
+
"sentAt",
|
|
68
|
+
"sendError",
|
|
69
|
+
"retryCount",
|
|
70
|
+
"handledById",
|
|
71
|
+
"handledByKind",
|
|
72
|
+
"handledAt",
|
|
73
|
+
"updatedAt"
|
|
74
|
+
]);
|
|
75
|
+
var DATE_LIKE = /^\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?$/;
|
|
76
|
+
function canonValue(value) {
|
|
77
|
+
if (value === void 0 || value === null) return "";
|
|
78
|
+
if (value instanceof Date) return Number.isNaN(value.getTime()) ? "" : value.toISOString();
|
|
79
|
+
if (typeof value === "object") return JSON.stringify(value);
|
|
80
|
+
if (typeof value === "string") {
|
|
81
|
+
if (DATE_LIKE.test(value)) {
|
|
82
|
+
const time = Date.parse(value);
|
|
83
|
+
if (!Number.isNaN(time)) return new Date(time).toISOString();
|
|
84
|
+
}
|
|
85
|
+
if (value.startsWith("[") || value.startsWith("{")) try {
|
|
86
|
+
return JSON.stringify(JSON.parse(value));
|
|
87
|
+
} catch {
|
|
88
|
+
return value;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return String(value);
|
|
92
|
+
}
|
|
56
93
|
var DRAFT_CARRIED_FIELDS = /* @__PURE__ */ new Set([
|
|
57
94
|
"tenantId",
|
|
58
95
|
"metadata",
|
|
@@ -172,8 +209,11 @@ var Message = class extends SmrtObject {
|
|
|
172
209
|
async save(options) {
|
|
173
210
|
const signature = lifecycleSaves.get(this);
|
|
174
211
|
lifecycleSaves.delete(this);
|
|
212
|
+
const authorized = signature !== void 0 && signature === lifecycleSignature(this);
|
|
213
|
+
const lifecycle = authorized || heldSaves.has(this);
|
|
214
|
+
const required = await this.enforceDraftScope(lifecycle);
|
|
175
215
|
return this.withTransaction(async () => {
|
|
176
|
-
|
|
216
|
+
await this.assertDraftScopeStillHolds(lifecycle, required);
|
|
177
217
|
await assertProtectedNotificationSave(this, options, authorized);
|
|
178
218
|
if (signature !== void 0 && signature !== lifecycleSignature(this)) throw new Error("Message lifecycle changed during its guarded save.");
|
|
179
219
|
const result = await super.save(options);
|
|
@@ -185,8 +225,103 @@ var Message = class extends SmrtObject {
|
|
|
185
225
|
}
|
|
186
226
|
/** Protected outbound evidence is retained; ordinary message deletion remains unchanged. */
|
|
187
227
|
async delete(options = {}) {
|
|
188
|
-
await
|
|
189
|
-
return
|
|
228
|
+
const required = await this.enforceDraftScope(false);
|
|
229
|
+
return this.withTransaction(async () => {
|
|
230
|
+
await this.assertDraftScopeStillHolds(false, required);
|
|
231
|
+
await assertProtectedNotificationDelete(this);
|
|
232
|
+
return super.delete(options);
|
|
233
|
+
});
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Creating, changing or deleting a draft on an owned account needs the
|
|
237
|
+
* `draft` scope, whichever route the write takes. A draft is an email
|
|
238
|
+
* flagged `isDraft` that has not been sent (any send status but `sent`), in
|
|
239
|
+
* whatever form the flag is stored; received mail is not flagged. The stored
|
|
240
|
+
* row decides, whatever class this instance is, so a base `Message` handle
|
|
241
|
+
* on a stored draft is covered. Both the new and the stored state count, so
|
|
242
|
+
* a draft cannot be edited by first relabelling it, and both accounts count
|
|
243
|
+
* when a draft moves. Trusted system work, unowned accounts and rows that
|
|
244
|
+
* are not drafts are unaffected.
|
|
245
|
+
*
|
|
246
|
+
* `lifecycle` is the send path's own save (status changes, a held send moved
|
|
247
|
+
* back to draft): it needs the `send` scope instead, and passes only while
|
|
248
|
+
* every field outside {@link SEND_PATH_MAY_CHANGE} still equals the stored
|
|
249
|
+
* row, so it cannot carry an edit. A row the send path itself creates (an
|
|
250
|
+
* unsaved message being sent) needs `send` too.
|
|
251
|
+
*
|
|
252
|
+
* Returns the requirements it enforced (empty for system work).
|
|
253
|
+
*/
|
|
254
|
+
async enforceDraftScope(lifecycle) {
|
|
255
|
+
if (inMailSystemAccess()) return /* @__PURE__ */ new Set();
|
|
256
|
+
const rootOptions = { ...this.options };
|
|
257
|
+
learnMailAccessOptions(rootOptions);
|
|
258
|
+
const required = await this.draftScopeRequirements(lifecycle);
|
|
259
|
+
for (const key of required) {
|
|
260
|
+
const at = key.indexOf(":");
|
|
261
|
+
await assertMailScopeOn([key.slice(at + 1)], key.slice(0, at), rootOptions);
|
|
262
|
+
}
|
|
263
|
+
return required;
|
|
264
|
+
}
|
|
265
|
+
/**
|
|
266
|
+
* The same decision re-read inside the write transaction. The policy lookups
|
|
267
|
+
* (grants, account owner) use the configured database handle, which a
|
|
268
|
+
* single-connection engine cannot serve while a transaction is open, so they
|
|
269
|
+
* stay outside; what the write re-checks is the stored row. A row that now
|
|
270
|
+
* needs more than was enforced is refused, and the caller retries.
|
|
271
|
+
*/
|
|
272
|
+
async assertDraftScopeStillHolds(lifecycle, enforced) {
|
|
273
|
+
if (inMailSystemAccess()) return;
|
|
274
|
+
for (const key of await this.draftScopeRequirements(lifecycle)) if (!enforced.has(key)) throw new MailAccessError(key.slice(0, key.indexOf(":")), "denied");
|
|
275
|
+
}
|
|
276
|
+
/** The `scope:accountId` pairs this write needs, read through `this.db`. */
|
|
277
|
+
async draftScopeRequirements(lifecycle) {
|
|
278
|
+
const needed = /* @__PURE__ */ new Set();
|
|
279
|
+
const row = this;
|
|
280
|
+
const draftNow = "isDraft" in this && isUnsentDraft(row.sendStatus, row.isDraft);
|
|
281
|
+
const priorAccountIds = [];
|
|
282
|
+
let stored = null;
|
|
283
|
+
let unchanged = false;
|
|
284
|
+
if (this.id) {
|
|
285
|
+
stored = await this.getCanonicalPersistedRow({ id: this.id });
|
|
286
|
+
if (stored) {
|
|
287
|
+
if (isUnsentDraft(stored.send_status, stored.is_draft)) priorAccountIds.push(String(stored.account_id ?? ""));
|
|
288
|
+
unchanged = this.matchesStoredBeyondSendPath(stored);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
let takesOver = false;
|
|
292
|
+
if (!this.isPersisted) {
|
|
293
|
+
if (ObjectRegistry.getConflictColumns(this.getResolvedQualifiedName()).includes("slug")) {
|
|
294
|
+
const slug = typeof row.slug === "string" && row.slug ? row.slug : await this.getSlug();
|
|
295
|
+
if (typeof slug === "string" && slug) for (const keyed of await this.getCanonicalPersistedRows({ slug })) {
|
|
296
|
+
if (keyed.id === this.id) continue;
|
|
297
|
+
takesOver = true;
|
|
298
|
+
unchanged = false;
|
|
299
|
+
if (isUnsentDraft(keyed.send_status, keyed.is_draft)) priorAccountIds.push(String(keyed.account_id ?? ""));
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
if (!draftNow && !priorAccountIds.length) return needed;
|
|
304
|
+
const scope = lifecycle && (stored && unchanged || !stored && !takesOver) ? "send" : "draft";
|
|
305
|
+
for (const id of [draftNow ? this.accountId : "", ...priorAccountIds]) if (id) needed.add(`${scope}:${id}`);
|
|
306
|
+
return needed;
|
|
307
|
+
}
|
|
308
|
+
/** Whether every field outside {@link SEND_PATH_MAY_CHANGE} equals `stored`. */
|
|
309
|
+
matchesStoredBeyondSendPath(stored) {
|
|
310
|
+
const row = this;
|
|
311
|
+
const names = /* @__PURE__ */ new Set([
|
|
312
|
+
...this.draftFieldNames(),
|
|
313
|
+
"tenantId",
|
|
314
|
+
"slug",
|
|
315
|
+
"context"
|
|
316
|
+
]);
|
|
317
|
+
for (const name of names) {
|
|
318
|
+
if (SEND_PATH_MAY_CHANGE.has(name)) continue;
|
|
319
|
+
const column = name.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`);
|
|
320
|
+
if (!(column in stored)) continue;
|
|
321
|
+
const mine = row[name];
|
|
322
|
+
if (!(typeof mine === "boolean" ? mine === mailFlag(stored[column]) : canonValue(mine) === canonValue(stored[column]))) return false;
|
|
323
|
+
}
|
|
324
|
+
return true;
|
|
190
325
|
}
|
|
191
326
|
async finalizeSendLifecycle(result, actor = null) {
|
|
192
327
|
if (!this.id) throw new Error("Cannot finalize an unsaved message send");
|
|
@@ -333,12 +468,12 @@ var Message = class extends SmrtObject {
|
|
|
333
468
|
*/
|
|
334
469
|
async getAccount() {
|
|
335
470
|
if (!this.accountId) return null;
|
|
336
|
-
const { AccountCollection } = await import("./EmailAccountCollection-
|
|
471
|
+
const { AccountCollection } = await import("./EmailAccountCollection-DWo_a-X5.js").then((n) => n.a);
|
|
337
472
|
return await (await AccountCollection.create(this.options)).get({ id: this.accountId });
|
|
338
473
|
}
|
|
339
474
|
async getEndpoint() {
|
|
340
475
|
if (!this.endpointId) return null;
|
|
341
|
-
const { MessagingEndpointCollection } = await import("./MessagingEndpointCollection-
|
|
476
|
+
const { MessagingEndpointCollection } = await import("./MessagingEndpointCollection-CNwpv_ZW.js").then((n) => n.n);
|
|
342
477
|
return (await MessagingEndpointCollection.create(this.options)).get({ id: this.endpointId });
|
|
343
478
|
}
|
|
344
479
|
/**
|
|
@@ -346,14 +481,14 @@ var Message = class extends SmrtObject {
|
|
|
346
481
|
*/
|
|
347
482
|
async getThreadMessages() {
|
|
348
483
|
if (!this.threadId) return [this];
|
|
349
|
-
const { MessageCollection } = await import("./MessageCollection-
|
|
484
|
+
const { MessageCollection } = await import("./MessageCollection-yZ6RyAtB.js").then((n) => n.n);
|
|
350
485
|
return await (await MessageCollection.create(this.options)).list({ where: { threadId: this.threadId } });
|
|
351
486
|
}
|
|
352
487
|
/**
|
|
353
488
|
* Get attachments for this message
|
|
354
489
|
*/
|
|
355
490
|
async getAttachments() {
|
|
356
|
-
const { AttachmentCollection } = await import("./AttachmentCollection-
|
|
491
|
+
const { AttachmentCollection } = await import("./AttachmentCollection-Di2aRb2k.js").then((n) => n.n);
|
|
357
492
|
return await (await AttachmentCollection.create(this.options)).list({ where: { messageId: this.id } });
|
|
358
493
|
}
|
|
359
494
|
/**
|
|
@@ -419,7 +554,7 @@ var Message = class extends SmrtObject {
|
|
|
419
554
|
const toDraft = held.pendingApproval !== void 0 && this.sendStatus !== "draft";
|
|
420
555
|
if (toDraft) this.sendStatus = "draft";
|
|
421
556
|
if (held.pendingApproval?.created) stampHandledBy(this, actor);
|
|
422
|
-
if (toDraft || held.pendingApproval?.created) await this
|
|
557
|
+
if (toDraft || held.pendingApproval?.created) await saveHeld(this);
|
|
423
558
|
if (held.pendingApproval === void 0 && (this.sendStatus === "pending" || this.sendStatus === "scheduled") && this.isPersisted) {
|
|
424
559
|
this.sendStatus = "failed";
|
|
425
560
|
this.sendError = held.error ?? "Send refused";
|
|
@@ -713,4 +848,4 @@ Message = __decorateClass([TenantScoped({ mode: "optional" }), smrt({
|
|
|
713
848
|
//#endregion
|
|
714
849
|
export { Message as t };
|
|
715
850
|
|
|
716
|
-
//# sourceMappingURL=Message-
|
|
851
|
+
//# sourceMappingURL=Message-DC877Gl7.js.map
|