@happyvertical/smrt-messages 0.70.3 → 0.71.0

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 (50) hide show
  1. package/AGENTS.md +9 -3
  2. package/README.md +4 -2
  3. package/agents/attachment-storage.md +41 -0
  4. package/dist/attachment-storage.d.ts +50 -0
  5. package/dist/attachment-storage.d.ts.map +1 -0
  6. package/dist/chunks/{AttachmentCollection-Di2aRb2k.js → AttachmentCollection-C14dERNK.js} +31 -37
  7. package/dist/chunks/AttachmentCollection-C14dERNK.js.map +1 -0
  8. package/dist/chunks/{Email-tEYH6ZRw.js → Email-Bd1lCLiC.js} +6 -6
  9. package/dist/chunks/{Email-tEYH6ZRw.js.map → Email-Bd1lCLiC.js.map} +1 -1
  10. package/dist/chunks/{EmailAccountCollection-DWo_a-X5.js → EmailAccountCollection-Clv4kruh.js} +108 -37
  11. package/dist/chunks/EmailAccountCollection-Clv4kruh.js.map +1 -0
  12. package/dist/chunks/{EmailCollection-_Z2JY26I.js → EmailCollection-CiZJ5I2l.js} +3 -3
  13. package/dist/chunks/{EmailCollection-_Z2JY26I.js.map → EmailCollection-CiZJ5I2l.js.map} +1 -1
  14. package/dist/chunks/{EmailFolder-TyoFZVcC.js → EmailFolder-Dvb6M-d_.js} +6 -6
  15. package/dist/chunks/{EmailFolder-TyoFZVcC.js.map → EmailFolder-Dvb6M-d_.js.map} +1 -1
  16. package/dist/chunks/{EmailFolderCollection-CFtttkx6.js → EmailFolderCollection-BR3yh7sp.js} +2 -2
  17. package/dist/chunks/{EmailFolderCollection-CFtttkx6.js.map → EmailFolderCollection-BR3yh7sp.js.map} +1 -1
  18. package/dist/chunks/{EmailSender-bHwAYzBO.js → EmailSender-B-c7mxbY.js} +10 -4
  19. package/dist/chunks/EmailSender-B-c7mxbY.js.map +1 -0
  20. package/dist/chunks/{Message-DC877Gl7.js → Message-CGyhd0kh.js} +6 -6
  21. package/dist/chunks/{Message-DC877Gl7.js.map → Message-CGyhd0kh.js.map} +1 -1
  22. package/dist/chunks/{MessageCollection-yZ6RyAtB.js → MessageCollection-DRCtm5z2.js} +2 -2
  23. package/dist/chunks/{MessageCollection-yZ6RyAtB.js.map → MessageCollection-DRCtm5z2.js.map} +1 -1
  24. package/dist/chunks/{MessagingEndpointCollection-CNwpv_ZW.js → MessagingEndpointCollection-Cju_NnJZ.js} +2 -2
  25. package/dist/chunks/{MessagingEndpointCollection-CNwpv_ZW.js.map → MessagingEndpointCollection-Cju_NnJZ.js.map} +1 -1
  26. package/dist/collections/AttachmentCollection.d.ts.map +1 -1
  27. package/dist/connect.js +1 -1
  28. package/dist/host.browser.d.ts +2 -0
  29. package/dist/host.browser.d.ts.map +1 -1
  30. package/dist/host.browser.js +3 -1
  31. package/dist/host.browser.js.map +1 -1
  32. package/dist/host.d.ts +20 -0
  33. package/dist/host.d.ts.map +1 -1
  34. package/dist/host.js +39 -1
  35. package/dist/host.js.map +1 -1
  36. package/dist/index.d.ts +1 -0
  37. package/dist/index.d.ts.map +1 -1
  38. package/dist/index.js +17 -17
  39. package/dist/index.js.map +1 -1
  40. package/dist/manifest.json +1 -1
  41. package/dist/models/Attachment.d.ts +13 -8
  42. package/dist/models/Attachment.d.ts.map +1 -1
  43. package/dist/send-approval.d.ts.map +1 -1
  44. package/dist/senders/EmailSender.d.ts.map +1 -1
  45. package/dist/smrt-knowledge.json +11 -5
  46. package/dist/smrt-knowledge.okf.md +9 -5
  47. package/package.json +12 -12
  48. package/dist/chunks/AttachmentCollection-Di2aRb2k.js.map +0 -1
  49. package/dist/chunks/EmailAccountCollection-DWo_a-X5.js.map +0 -1
  50. package/dist/chunks/EmailSender-bHwAYzBO.js.map +0 -1
package/AGENTS.md CHANGED
@@ -111,6 +111,13 @@ owners and call `configureMailAccess({ options, resolvePrincipal })` at startup
111
111
  `CorrespondentService` derives owner-private contacts (optional `Profile` link).
112
112
  Both fail closed. Details: [agents/mail-search.md](agents/mail-search.md).
113
113
 
114
+ ## Attachment storage root (#5645)
115
+
116
+ `Attachment.filePath` is `<accountId>/...` relative to the root set once at startup with
117
+ `configureAttachmentStorage({ root })` (beside `configureMailAccess`). Without
118
+ it stored files are never read (fail closed). Rules, send behaviour and the
119
+ upgrade step: [agents/attachment-storage.md](agents/attachment-storage.md).
120
+
114
121
  ## Mailbox connect (provider-neutral)
115
122
 
116
123
  Credentials reach smrt-secrets in two ways; neither writes the plaintext `settings` fallback.
@@ -221,9 +228,8 @@ import '@happyvertical/smrt-messages/providers/all'; // all of the above
221
228
  `createSender` hooks. Never import a provider SDK from any module reachable
222
229
  from `src/index.ts` — the consumer bundle gate (`packages/bundle-gate`)
223
230
  fails CI when one becomes reachable.
224
- - `Attachment.readContent()` loads `@happyvertical/files` through core's
225
- `importOptionalDependency` boundary and keeps its null-on-failure contract
226
- in builds where the SDK is absent.
231
+ - `Attachment.readContent()` reads with `node:fs` through `host.ts` (stubbed
232
+ in `host.browser.ts`), not `@happyvertical/files`; see Attachment storage.
227
233
 
228
234
  ## Gotchas
229
235
 
package/README.md CHANGED
@@ -50,7 +50,9 @@ if (!result.success) {
50
50
  }
51
51
 
52
52
  // Attach files: stored `Attachment` rows are read through
53
- // `Attachment.readContent()` at send time, and bytes rendered on demand go in
53
+ // `Attachment.readContent()` at send time from the directory you configure
54
+ // once at startup with `configureAttachmentStorage({ root: '/data/attachments' })`
55
+ // (required to read stored files; `filePath` is `<accountId>/...` below it), and bytes rendered on demand go in
54
56
  // `send({ attachments })`. Both reach the transport together; a stored file
55
57
  // that cannot be read fails the send (sendStatus 'failed', sendError set)
56
58
  // instead of being dropped.
@@ -67,7 +69,7 @@ await attachments.create({
67
69
  filename: 'PO-1042.pdf',
68
70
  contentType: 'application/pdf',
69
71
  size: pdfBytes.length,
70
- filePath: '/data/po/PO-1042.pdf',
72
+ filePath: `${account.id}/po/PO-1042.pdf`, // /data/attachments/<accountId>/po/PO-1042.pdf
71
73
  });
72
74
  await order.send({
73
75
  attachments: [
@@ -0,0 +1,41 @@
1
+ # Attachment storage root (#5645)
2
+
3
+ `Attachment.filePath` is a path relative to one root the host sets once at
4
+ startup with `configureAttachmentStorage({ root })` (`attachment-storage.ts`,
5
+ beside `configureMailAccess`; `resetAttachmentStorage()` for tests). The root
6
+ must be an absolute, existing directory; its real path is resolved once.
7
+
8
+ - **Layout**: a file lives at `<root>/<accountId>/<path>`, and `filePath` is
9
+ stored as `<accountId>/<path>`, where `accountId` is the account of the
10
+ message the attachment is on. Account ids are unique across tenants, so this
11
+ one prefix scopes both tenant and account (an attachment's own `tenantId` is
12
+ optional, but its message always has an account).
13
+ - **Write** (`Attachment.save()`, so also `AttachmentCollection.create` and the
14
+ generated `create` route): refuses an absolute path, a `..` segment, a
15
+ backslash, a control character (NUL included), `%2e`/`%2f`/`%5c` (any case,
16
+ any `%25` nesting) and an empty result, or a path not under `<accountId>/` of the message's current
17
+ account (read from the stored message, never the row's own `accountId`), with
18
+ `AttachmentStorageError`
19
+ (`status` 400); stores the normalised relative path. Needs no root.
20
+ - **Read** (`readContent()`, the only reader): no root configured throws
21
+ `AttachmentStorageError` naming `configureAttachmentStorage` (fail closed);
22
+ the stored path is re-checked against the message's current account, so an
23
+ attachment moved to another account's message loses its file (rows written earlier with an absolute or
24
+ escaping path are refused), the target's real path is resolved, and one
25
+ outside the account's own directory (or the root) throws. Missing or unreadable file stays `null`.
26
+ - **Send / held send**: `EmailSender` turns a refusal into the failed send
27
+ `Attachment "x" was not sent: ...` (recorded on `sendError`, nothing reaches
28
+ the transport); `mailSendBindingHash` binds a refused row as `unreadable`.
29
+ - **Upgrade**: a host that stored absolute paths must set the root, move each
30
+ file to `<root>/<accountId>/...` and rewrite its row as the relative path
31
+ `<accountId>/...`, using the account of the row's message; until then those sends fail.
32
+ `backfillAccountIds()` writes the column directly so such rows still fill.
33
+
34
+ ## Trust boundary
35
+
36
+ Reads check the real path just before opening it, so the root must not be
37
+ writable by untrusted parties (hard links or a symlink swap inside the root between the check and the
38
+ read is not defended). The per-account prefix stops one account naming another
39
+ account's file; it does not separate writers within one account.
40
+ The root's layout is the operator's: a symlinked account directory that points at
41
+ another account's directory inside the root is followed. Do not create one.
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Attachment storage root.
3
+ *
4
+ * A stored `Attachment.filePath` is a path relative to one configured root
5
+ * directory. The host calls {@link configureAttachmentStorage} once at startup;
6
+ * without it stored files are never read (fail closed). Writes are checked
7
+ * lexically ({@link normalizeAttachmentPath}); reads also resolve symlinks and
8
+ * refuse anything whose real path leaves the root's real path.
9
+ */
10
+ export interface AttachmentStorageConfig {
11
+ /** Absolute directory that holds every stored attachment file. */
12
+ root: string;
13
+ }
14
+ /** Thrown for a refused attachment path or an unconfigured storage root. */
15
+ export declare class AttachmentStorageError extends Error {
16
+ readonly status: number;
17
+ constructor(message: string, status?: number);
18
+ }
19
+ /** By name, so a copy of this module loaded twice still recognises it. */
20
+ export declare function isAttachmentStorageError(error: unknown): error is AttachmentStorageError;
21
+ /**
22
+ * Set the directory stored attachment files are read from. Call once at
23
+ * startup. The root must be an absolute path to an existing directory; its
24
+ * real path is resolved here, once. Calling again replaces it.
25
+ */
26
+ export declare function configureAttachmentStorage(config: AttachmentStorageConfig): void;
27
+ /** Remove the configuration (tests). Stored files are then unreadable. */
28
+ export declare function resetAttachmentStorage(): void;
29
+ /**
30
+ * The normalised relative form of a stored attachment path, or an
31
+ * {@link AttachmentStorageError}. Absolute paths, `..` segments, backslashes,
32
+ * control characters (NUL included) and percent-encoded dots or separators
33
+ * are refused; empty and `.` segments are dropped. Plain string handling: the
34
+ * package root must stay browser-reachable.
35
+ */
36
+ export declare function normalizeAttachmentPath(filePath: unknown): string;
37
+ /**
38
+ * The normalised path of an attachment owned by `accountId`: it must lie under
39
+ * `<accountId>/` (server-assigned ids contain no `/`, and are unique across tenants, so this scopes both
40
+ * tenant and account) and name a file below that directory.
41
+ */
42
+ export declare function scopeAttachmentPath(filePath: unknown, accountId: string | null | undefined): string;
43
+ /**
44
+ * Read a stored attachment file: `null` when it is missing or unreadable, an
45
+ * {@link AttachmentStorageError} when no root is configured, the path is not
46
+ * under `accountId`'s directory, or the path (or where a symlink leads) is
47
+ * outside the root.
48
+ */
49
+ export declare function readStoredAttachmentFile(filePath: string, accountId: string | null | undefined): Promise<Buffer | null>;
50
+ //# sourceMappingURL=attachment-storage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attachment-storage.d.ts","sourceRoot":"","sources":["../src/attachment-storage.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAOH,MAAM,WAAW,uBAAuB;IACtC,kEAAkE;IAClE,IAAI,EAAE,MAAM,CAAC;CACd;AAED,4EAA4E;AAC5E,qBAAa,sBAAuB,SAAQ,KAAK;IAC/C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;gBACZ,OAAO,EAAE,MAAM,EAAE,MAAM,SAAM;CAK1C;AAED,0EAA0E;AAC1E,wBAAgB,wBAAwB,CACtC,KAAK,EAAE,OAAO,GACb,KAAK,IAAI,sBAAsB,CAEjC;AAqBD;;;;GAIG;AACH,wBAAgB,0BAA0B,CACxC,MAAM,EAAE,uBAAuB,GAC9B,IAAI,CAQN;AAED,0EAA0E;AAC1E,wBAAgB,sBAAsB,IAAI,IAAI,CAE7C;AAMD;;;;;;GAMG;AACH,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,OAAO,GAAG,MAAM,CAmBjE;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,OAAO,EACjB,SAAS,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GACnC,MAAM,CAMR;AAED;;;;;GAKG;AACH,wBAAsB,wBAAwB,CAC5C,QAAQ,EAAE,MAAM,EAChB,SAAS,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GACnC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAiBxB"}
@@ -1,7 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import { D as assertMailDraftWrite, F as inMailSystemAccess, R as isUnsentDraft, T as assertHydratedMailAccess, W as runWithMailSystemAccess, z as learnMailAccessOptions } from "./EmailAccountCollection-DWo_a-X5.js";
2
+ import { C as readStoredAttachmentFile, G as learnMailAccessOptions, N as assertMailDraftWrite, T as scopeAttachmentPath, V as inMailSystemAccess, W as isUnsentDraft, X as runWithMailSystemAccess, j as assertHydratedMailAccess } from "./EmailAccountCollection-Clv4kruh.js";
3
3
  import { queryGlobal, queryWithGlobals } from "../host.js";
4
- import { ObjectRegistry, SmrtCollection, SmrtObject, foreignKey, importOptionalDependency, smrt } from "@happyvertical/smrt-core";
4
+ import { ObjectRegistry, SmrtCollection, SmrtObject, foreignKey, smrt } from "@happyvertical/smrt-core";
5
5
  import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy/decorators";
6
6
  //#region src/models/Attachment.ts
7
7
  var __defProp = Object.defineProperty;
@@ -19,15 +19,6 @@ var __decorateClass = (decorators, target, key, kind) => {
19
19
  return result;
20
20
  };
21
21
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
- function splitAbsolutePath(filePath) {
23
- const windows = /^[A-Za-z]:[\\/]/.test(filePath);
24
- if (!windows && !filePath.startsWith("/")) return null;
25
- const cut = windows ? Math.max(filePath.lastIndexOf("/"), filePath.lastIndexOf("\\")) : filePath.lastIndexOf("/");
26
- return {
27
- dir: filePath.slice(0, cut) || filePath.slice(0, cut + 1),
28
- base: filePath.slice(cut + 1)
29
- };
30
- }
31
22
  var Attachment = class extends SmrtObject {
32
23
  tenantId = null;
33
24
  messageId = "";
@@ -75,6 +66,7 @@ var Attachment = class extends SmrtObject {
75
66
  * an attachment cannot be moved on or off a draft without the scope.
76
67
  */
77
68
  async save(options) {
69
+ if (this.filePath) this.filePath = scopeAttachmentPath(this.filePath, await this.currentAccountId());
78
70
  await this.assertDraftParentWrite();
79
71
  return super.save(options);
80
72
  }
@@ -83,6 +75,20 @@ var Attachment = class extends SmrtObject {
83
75
  return super.delete(options);
84
76
  }
85
77
  /**
78
+ * The account of the message this row is stored on now, read from the
79
+ * stored message (never from the row's own `accountId`), or null.
80
+ */
81
+ async currentAccountId() {
82
+ if (!this.messageId) return null;
83
+ try {
84
+ const { MessageCollection } = await import("./MessageCollection-DRCtm5z2.js").then((n) => n.n);
85
+ const messages = await MessageCollection.create(this.options);
86
+ return (await this.db.get(messages.tableName, { id: this.messageId }))?.account_id || null;
87
+ } catch {
88
+ return null;
89
+ }
90
+ }
91
+ /**
86
92
  * Trusted system work and non-draft parents pass. Unlike the message check
87
93
  * this runs before the write, not inside its transaction: the attachment
88
94
  * save interceptor builds collections from the instance's options, and
@@ -105,7 +111,7 @@ var Attachment = class extends SmrtObject {
105
111
  }
106
112
  }
107
113
  if (!parentIds.size) return;
108
- const { MessageCollection } = await import("./MessageCollection-yZ6RyAtB.js").then((n) => n.n);
114
+ const { MessageCollection } = await import("./MessageCollection-DRCtm5z2.js").then((n) => n.n);
109
115
  const messages = await MessageCollection.create(this.options);
110
116
  const accountIds = [];
111
117
  for (const id of parentIds) {
@@ -119,7 +125,7 @@ var Attachment = class extends SmrtObject {
119
125
  */
120
126
  async getMessage() {
121
127
  if (!this.messageId) return null;
122
- const { MessageCollection } = await import("./MessageCollection-yZ6RyAtB.js").then((n) => n.n);
128
+ const { MessageCollection } = await import("./MessageCollection-DRCtm5z2.js").then((n) => n.n);
123
129
  return await (await MessageCollection.create(this.options)).get({ id: this.messageId });
124
130
  }
125
131
  /**
@@ -173,30 +179,19 @@ var Attachment = class extends SmrtObject {
173
179
  return !!this.filePath;
174
180
  }
175
181
  /**
176
- * Read file content (if stored externally)
182
+ * Read the stored file's bytes, or null when the row has no file or the
183
+ * file is missing or unreadable.
177
184
  *
178
- * The files SDK is loaded through core's bundler-invisible optional-import
179
- * boundary so it never enters provider-neutral consumer bundles (#1979).
180
- * Absence of the SDK at runtime degrades to the existing null contract.
181
- *
182
- * The local provider joins every path onto its base path (the process cwd
183
- * by default), so an absolute `filePath` is rooted at its own directory, and
184
- * the bytes are read raw: decoding a PDF as UTF-8 corrupts it (#3808).
185
+ * `filePath` is relative to the root set with `configureAttachmentStorage`
186
+ * and must lie under `<accountId>/` of the message's current account.
187
+ * Throws `AttachmentStorageError` when no root is configured, or when the
188
+ * stored path (or a symlink under it) leaves the root or the account's
189
+ * directory; this includes rows stored before the root existed. The bytes are read
190
+ * raw: decoding a PDF as UTF-8 corrupts it (#3808).
185
191
  */
186
192
  async readContent() {
187
193
  if (!this.filePath) return null;
188
- try {
189
- const { getFilesystem, initializeProviders } = await importOptionalDependency("@happyvertical/files", "Import '@happyvertical/smrt-core/filesystem' (or '@happyvertical/smrt-assets/filesystem') during server startup to read externally-stored attachments in bundled builds.");
190
- await initializeProviders?.();
191
- const split = splitAbsolutePath(this.filePath);
192
- const data = await (await getFilesystem(split ? {
193
- type: "local",
194
- basePath: split.dir
195
- } : { type: "local" })).read(split ? split.base : this.filePath, { raw: true });
196
- return data instanceof Buffer ? data : Buffer.from(data);
197
- } catch {
198
- return null;
199
- }
194
+ return readStoredAttachmentFile(this.filePath, await this.currentAccountId());
200
195
  }
201
196
  };
202
197
  __publicField(Attachment, "__smrtPackage__", "@happyvertical/smrt-messages");
@@ -225,15 +220,14 @@ var AttachmentCollection = class extends SmrtCollection {
225
220
  */
226
221
  async backfillAccountIds() {
227
222
  return runWithMailSystemAccess(async () => {
228
- const { MessageCollection } = await import("./MessageCollection-yZ6RyAtB.js").then((n) => n.n);
223
+ const { MessageCollection } = await import("./MessageCollection-DRCtm5z2.js").then((n) => n.n);
229
224
  const messages = await MessageCollection.create(this.options);
230
225
  let updated = 0;
231
226
  for (const attachment of await this.list({ where: { accountId: null } })) {
232
227
  if (!attachment.messageId) continue;
233
228
  const message = await messages.get({ id: attachment.messageId });
234
229
  if (!message?.accountId) continue;
235
- attachment.accountId = message.accountId;
236
- await attachment.save();
230
+ await this.db.update(this.tableName, { id: attachment.id }, { account_id: message.accountId });
237
231
  updated++;
238
232
  }
239
233
  return updated;
@@ -352,4 +346,4 @@ var AttachmentCollection = class extends SmrtCollection {
352
346
  //#endregion
353
347
  export { AttachmentCollection_exports as n, Attachment as r, AttachmentCollection as t };
354
348
 
355
- //# sourceMappingURL=AttachmentCollection-Di2aRb2k.js.map
349
+ //# sourceMappingURL=AttachmentCollection-C14dERNK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AttachmentCollection-C14dERNK.js","names":[],"sources":["../../src/models/Attachment.ts","../../src/collections/AttachmentCollection.ts"],"sourcesContent":["/**\n * Attachment model - Generalized attachment for any message type\n *\n * Uses messageId instead of emailId for cross-type support.\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 {\n foreignKey,\n ObjectRegistry,\n SmrtObject,\n type SmrtSaveOptions,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport {\n assertHydratedMailAccess,\n assertMailDraftWrite,\n inMailSystemAccess,\n isUnsentDraft,\n learnMailAccessOptions,\n} from '../access.js';\nimport {\n readStoredAttachmentFile,\n scopeAttachmentPath,\n} from '../attachment-storage.js';\nimport type { AttachmentOptions } from '../types';\n\n@TenantScoped({ mode: 'optional' })\n@smrt({\n api: { include: ['list', 'get', 'create', 'delete'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n})\nexport class Attachment extends SmrtObject { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n @tenantId({ nullable: true })\n tenantId: string | null = null;\n\n @foreignKey('Message')\n messageId = '';\n /**\n * The mail account this file belongs to. Copied from its message when the\n * attachment is saved, so per-account mail access can filter attachment\n * reads (lists, projections, counts) without a join. Null for rows saved\n * before the column existed: run `AttachmentCollection.backfillAccountIds()`.\n */\n @foreignKey('Account')\n accountId: string | null = null;\n filename = '';\n contentType = '';\n size = 0;\n contentId = ''; // For inline images (<img src=\"cid:...\">)\n contentDisposition: 'attachment' | 'inline' = 'attachment';\n filePath = ''; // External file storage path\n sourceUrl = ''; // For non-email attachments (media URLs, etc.)\n\n // Timestamps\n createdAt = new Date();\n\n constructor(options: AttachmentOptions = {}) {\n super(options);\n\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.messageId !== undefined) this.messageId = options.messageId;\n if (options.accountId !== undefined)\n this.accountId = options.accountId || null;\n if (options.filename !== undefined) this.filename = options.filename;\n if (options.contentType !== undefined)\n this.contentType = options.contentType;\n if (options.size !== undefined) this.size = options.size;\n if (options.contentId !== undefined) this.contentId = options.contentId;\n if (options.contentDisposition !== undefined)\n this.contentDisposition = options.contentDisposition;\n if (options.filePath !== undefined) this.filePath = options.filePath;\n if (options.sourceUrl !== undefined) this.sourceUrl = options.sourceUrl;\n if (options.createdAt) this.createdAt = options.createdAt;\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(this);\n }\n\n override async loadFromSlug() {\n await super.loadFromSlug();\n await assertHydratedMailAccess(this);\n }\n\n /**\n * An attachment is part of what its message will send, so writing one on an\n * unsent email draft of an owned account needs the same `draft` scope as\n * writing the draft (see `Message.save()`), whichever route the write takes.\n * Both the parent it is saved onto and the parent it is stored on count, so\n * an attachment cannot be moved on or off a draft without the scope.\n */\n override async save(options?: SmrtSaveOptions): Promise<this> {\n // A stored path is relative to the attachment storage root and under the\n // message account's directory: refuse anything else before it is written,\n // and keep the normalised form.\n if (this.filePath) {\n this.filePath = scopeAttachmentPath(\n this.filePath,\n await this.currentAccountId(),\n );\n }\n await this.assertDraftParentWrite();\n return super.save(options);\n }\n\n override async delete(\n options: { expectedUpdatedAt?: Date | string } = {},\n ): Promise<void> {\n await this.assertDraftParentWrite();\n return super.delete(options);\n }\n\n /**\n * The account of the message this row is stored on now, read from the\n * stored message (never from the row's own `accountId`), or null.\n */\n private async currentAccountId(): Promise<string | null> {\n if (!this.messageId) return null;\n try {\n const { MessageCollection } = await import(\n '../collections/MessageCollection.js'\n );\n const messages = await MessageCollection.create(this.options as never);\n const parent = (await this.db.get(messages.tableName, {\n id: this.messageId,\n })) as Record<string, unknown> | null;\n return (parent?.account_id as string | null) || null;\n } catch {\n return null;\n }\n }\n\n /**\n * Trusted system work and non-draft parents pass. Unlike the message check\n * this runs before the write, not inside its transaction: the attachment\n * save interceptor builds collections from the instance's options, and\n * inside a transaction those would register the transaction's handle as a\n * policy database.\n */\n private async assertDraftParentWrite(): Promise<void> {\n learnMailAccessOptions(this.options);\n if (inMailSystemAccess()) return;\n const parentIds = new Set<string>();\n if (this.messageId) parentIds.add(this.messageId);\n if (this.id) {\n const stored = await this.getCanonicalPersistedRow({ id: this.id });\n if (typeof stored?.message_id === 'string' && stored.message_id) {\n parentIds.add(stored.message_id);\n }\n }\n // A new attachment is written over the stored row that carries its slug\n // (its own, or the one the save derives from its id): that row's parent is\n // the one it changes.\n const slug = this.isPersisted ? '' : this.slug || (await this.getSlug());\n if (slug) {\n const columns = ObjectRegistry.getConflictColumns(\n this.getResolvedQualifiedName(),\n );\n if (columns.includes('slug')) {\n for (const keyed of await this.getCanonicalPersistedRows({\n slug,\n })) {\n if (typeof keyed.message_id === 'string' && keyed.message_id) {\n parentIds.add(keyed.message_id);\n }\n }\n }\n }\n if (!parentIds.size) return;\n const { MessageCollection } = await import(\n '../collections/MessageCollection.js'\n );\n const messages = await MessageCollection.create(this.options as never);\n const accountIds: Array<string | null> = [];\n for (const id of parentIds) {\n const parent = (await this.db.get(messages.tableName, { id })) as Record<\n string,\n unknown\n > | null;\n if (parent && isUnsentDraft(parent.send_status, parent.is_draft)) {\n accountIds.push((parent.account_id as string | null) ?? null);\n }\n }\n await assertMailDraftWrite(accountIds, this.options);\n }\n\n /**\n * Get the message this attachment belongs to\n */\n async getMessage() {\n if (!this.messageId) return null;\n\n const { MessageCollection } = await import(\n '../collections/MessageCollection'\n );\n const collection = await MessageCollection.create(this.options);\n\n return await collection.get({ id: this.messageId });\n }\n\n /**\n * Check if attachment is an image\n */\n isImage(): boolean {\n return this.contentType.startsWith('image/');\n }\n\n /**\n * Check if attachment is a PDF\n */\n isPdf(): boolean {\n return this.contentType === 'application/pdf';\n }\n\n /**\n * Check if attachment is inline (embedded in message body)\n */\n isInline(): boolean {\n return this.contentDisposition === 'inline';\n }\n\n /**\n * Get file extension from filename\n */\n getExtension(): string {\n if (!this.filename) return '';\n const parts = this.filename.split('.');\n return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : '';\n }\n\n /**\n * Get human-readable file size\n */\n getFormattedSize(): string {\n const units = ['B', 'KB', 'MB', 'GB'];\n let size = this.size;\n let unitIndex = 0;\n\n while (size >= 1024 && unitIndex < units.length - 1) {\n size /= 1024;\n unitIndex++;\n }\n\n return `${size.toFixed(1)} ${units[unitIndex]}`;\n }\n\n /**\n * Check if file is stored externally\n */\n hasExternalFile(): boolean {\n return !!this.filePath;\n }\n\n /**\n * Read the stored file's bytes, or null when the row has no file or the\n * file is missing or unreadable.\n *\n * `filePath` is relative to the root set with `configureAttachmentStorage`\n * and must lie under `<accountId>/` of the message's current account.\n * Throws `AttachmentStorageError` when no root is configured, or when the\n * stored path (or a symlink under it) leaves the root or the account's\n * directory; this includes rows stored before the root existed. The bytes are read\n * raw: decoding a PDF as UTF-8 corrupts it (#3808).\n */\n async readContent(): Promise<Buffer | null> {\n if (!this.filePath) return null;\n return readStoredAttachmentFile(\n this.filePath,\n await this.currentAccountId(),\n );\n }\n}\n","/**\n * AttachmentCollection - Generalized attachment collection using messageId\n */\n\nimport { SmrtCollection } from '@happyvertical/smrt-core';\nimport { runWithMailSystemAccess } from '../access.js';\nimport { queryGlobal, queryWithGlobals } from '../host.js';\nimport { Attachment } from '../models/Attachment';\n\nexport class AttachmentCollection extends SmrtCollection<Attachment> {\n static readonly _itemClass = Attachment;\n\n /**\n * Fill `accountId` on attachments saved before the column existed, from\n * their message. Run once per tenant after upgrading; safe to repeat.\n * Returns the number of rows updated.\n */\n async backfillAccountIds(): Promise<number> {\n return runWithMailSystemAccess(async () => {\n const { MessageCollection } = await import('./MessageCollection');\n const messages = await MessageCollection.create(this.options);\n let updated = 0;\n for (const attachment of await this.list({\n where: { accountId: null },\n })) {\n if (!attachment.messageId) continue;\n const message = await messages.get({ id: attachment.messageId });\n if (!message?.accountId) continue;\n // A direct column write: a row stored before the attachment storage\n // root existed may hold a path `save()` now refuses, and the backfill\n // must still make it visible.\n await this.db.update(\n this.tableName,\n { id: attachment.id },\n { account_id: message.accountId },\n );\n updated++;\n }\n return updated;\n });\n }\n\n /**\n * Get attachments for a message\n */\n async getByMessage(messageId: string): Promise<Attachment[]> {\n return await this.list({ where: { messageId } });\n }\n\n /**\n * Get attachments by content type\n */\n async getByContentType(contentType: string): Promise<Attachment[]> {\n return await this.list({ where: { contentType } });\n }\n\n /**\n * Get image attachments\n */\n async getImages(messageId?: string): Promise<Attachment[]> {\n const attachments = messageId\n ? await this.getByMessage(messageId)\n : await this.list({});\n\n return attachments.filter((a) => a.isImage());\n }\n\n /**\n * Get PDF attachments\n */\n async getPdfs(messageId?: string): Promise<Attachment[]> {\n const attachments = messageId\n ? await this.getByMessage(messageId)\n : await this.list({});\n\n return attachments.filter((a) => a.isPdf());\n }\n\n /**\n * Get inline attachments (embedded in message body)\n */\n async getInline(messageId: string): Promise<Attachment[]> {\n const attachments = await this.getByMessage(messageId);\n return attachments.filter((a) => a.isInline());\n }\n\n /**\n * Get regular attachments (not inline)\n */\n async getRegular(messageId: string): Promise<Attachment[]> {\n const attachments = await this.getByMessage(messageId);\n return attachments.filter((a) => !a.isInline());\n }\n\n /**\n * Get attachments with external files\n */\n async getWithExternalFiles(): Promise<Attachment[]> {\n const attachments = await this.list({});\n return attachments.filter((a) => a.hasExternalFile());\n }\n\n /**\n * Get total size of attachments for a message\n */\n async getTotalSize(messageId: string): Promise<number> {\n const attachments = await this.getByMessage(messageId);\n return attachments.reduce((sum, a) => sum + a.size, 0);\n }\n\n /**\n * Get largest attachments\n */\n async getLargest(limit = 10): Promise<Attachment[]> {\n const attachments = await this.list({});\n return attachments.sort((a, b) => b.size - a.size).slice(0, limit);\n }\n\n /**\n * Search attachments by filename\n */\n async searchByFilename(query: string): Promise<Attachment[]> {\n const attachments = await this.list({});\n const lowerQuery = query.toLowerCase();\n\n return attachments.filter((a) =>\n a.filename?.toLowerCase().includes(lowerQuery),\n );\n }\n\n /**\n * Get attachments by extension\n */\n async getByExtension(extension: string): Promise<Attachment[]> {\n const attachments = await this.list({});\n const lowerExt = extension.toLowerCase().replace(/^\\./, '');\n\n return attachments.filter((a) => a.getExtension() === lowerExt);\n }\n\n /**\n * Get attachment statistics\n */\n async getStats(): Promise<{\n total: number;\n totalSize: number;\n byType: Record<string, number>;\n inline: number;\n regular: number;\n }> {\n const attachments = await this.list({});\n\n const byType: Record<string, number> = {};\n for (const attachment of attachments) {\n const type = attachment.contentType.split('/')[0] || 'other';\n byType[type] = (byType[type] || 0) + 1;\n }\n\n return {\n total: attachments.length,\n totalSize: attachments.reduce((sum, a) => sum + a.size, 0),\n byType,\n inline: attachments.filter((a) => a.isInline()).length,\n regular: attachments.filter((a) => !a.isInline()).length,\n };\n }\n\n /**\n * Delete all attachments for a message\n */\n async deleteByMessage(messageId: string): Promise<number> {\n const attachments = await this.getByMessage(messageId);\n let count = 0;\n\n for (const attachment of attachments) {\n await attachment.delete();\n count++;\n }\n\n return count;\n }\n\n // ─────────────────────────────────────────────────────────────────────────\n // Tenant Helper Methods\n // ─────────────────────────────────────────────────────────────────────────\n\n async findByTenant(tenantId: string): Promise<Attachment[]> {\n return this.list({ where: { tenantId } });\n }\n\n // Attachment is @TenantScoped (CTI, own `attachments` table). Under an active\n // tenant context list({ tenantId: null }) throws and unflagged raw SQL is\n // blocked (#1596); route through the raw helpers.\n async findGlobal(): Promise<Attachment[]> {\n return queryGlobal<Attachment>(this);\n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1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
- import "./EmailAccountCollection-DWo_a-X5.js";
3
- import { t as Message } from "./Message-DC877Gl7.js";
2
+ import "./EmailAccountCollection-Clv4kruh.js";
3
+ import { t as Message } from "./Message-CGyhd0kh.js";
4
4
  import { ObjectRegistry, field, smrt } from "@happyvertical/smrt-core";
5
5
  //#region src/html-to-text.ts
6
6
  var HTML_TO_TEXT_MAX_INPUT = 256 * 1024;
@@ -305,7 +305,7 @@ var Email = class extends Message {
305
305
  */
306
306
  async getAccount() {
307
307
  if (!this.accountId) return null;
308
- const { EmailAccountCollection } = await import("./EmailAccountCollection-DWo_a-X5.js").then((n) => n.n);
308
+ const { EmailAccountCollection } = await import("./EmailAccountCollection-Clv4kruh.js").then((n) => n.n);
309
309
  return await (await EmailAccountCollection.create(this.options)).get({ id: this.accountId });
310
310
  }
311
311
  /**
@@ -313,7 +313,7 @@ var Email = class extends Message {
313
313
  */
314
314
  async getFolder() {
315
315
  if (!this.folderId) return null;
316
- const { EmailFolderCollection } = await import("./EmailFolderCollection-CFtttkx6.js").then((n) => n.n);
316
+ const { EmailFolderCollection } = await import("./EmailFolderCollection-BR3yh7sp.js").then((n) => n.n);
317
317
  return await (await EmailFolderCollection.create(this.options)).get({ id: this.folderId });
318
318
  }
319
319
  /**
@@ -321,7 +321,7 @@ var Email = class extends Message {
321
321
  */
322
322
  async getThreadEmails() {
323
323
  if (!this.threadId) return [this];
324
- const { EmailCollection } = await import("./EmailCollection-_Z2JY26I.js").then((n) => n.n);
324
+ const { EmailCollection } = await import("./EmailCollection-CiZJ5I2l.js").then((n) => n.n);
325
325
  return await (await EmailCollection.create(this.options)).getByThread(this.threadId);
326
326
  }
327
327
  /**
@@ -533,4 +533,4 @@ Email = __decorateClass([smrt({
533
533
  //#endregion
534
534
  export { Email_exports as n, Email as t };
535
535
 
536
- //# sourceMappingURL=Email-tEYH6ZRw.js.map
536
+ //# sourceMappingURL=Email-Bd1lCLiC.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"Email-tEYH6ZRw.js","names":[],"sources":["../../src/html-to-text.ts","../../src/models/Email.ts"],"sourcesContent":["/**\n * Linear-time HTML to plain text for quoting HTML-only mail in drafts.\n *\n * Single forward scan, no backtracking regexes, input capped at\n * HTML_TO_TEXT_MAX_INPUT. Markup is never passed through: tags are dropped,\n * and the content of script/style/head/title/template/noscript elements and\n * comments is dropped. Text hidden by CSS (display:none etc.) is NOT detected\n * and remains in the output.\n */\nexport const HTML_TO_TEXT_MAX_INPUT = 256 * 1024;\n\nconst SKIP = new Set([\n 'script',\n 'style',\n 'head',\n 'title',\n 'template',\n 'noscript',\n]);\nconst BLOCK = new Set([\n 'p',\n 'div',\n 'li',\n 'tr',\n 'br',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'blockquote',\n 'table',\n 'ul',\n 'ol',\n 'pre',\n 'hr',\n]);\nconst NAMED: Record<string, string> = {\n amp: '&',\n lt: '<',\n gt: '>',\n quot: '\"',\n apos: \"'\",\n nbsp: ' ',\n mdash: '—',\n ndash: '–',\n hellip: '…',\n lsquo: '‘',\n rsquo: '’',\n ldquo: '“',\n rdquo: '”',\n copy: '©',\n reg: '®',\n trade: '™',\n bull: '•',\n middot: '·',\n};\n\nfunction decodeEntities(text: string): string {\n if (!text.includes('&')) return text;\n return text.replace(/&(#x[0-9a-f]{1,6}|#\\d{1,7}|[a-z]{2,8});/gi, (m, e) => {\n if (e[0] === '#') {\n const code =\n e[1] === 'x' || e[1] === 'X'\n ? Number.parseInt(e.slice(2), 16)\n : Number.parseInt(e.slice(1), 10);\n if (code > 0 && code <= 0x10ffff && !(code >= 0xd800 && code <= 0xdfff)) {\n return String.fromCodePoint(code);\n }\n return '';\n }\n return NAMED[e.toLowerCase()] ?? m;\n });\n}\n\nexport const HTML_TO_TEXT_TRUNCATED = '[\\u2026truncated]';\n\n/** Length-preserving ASCII-only lowercase (String#toLowerCase can change length). */\nfunction asciiLower(text: string): string {\n return text.replace(/[A-Z]/g, (c) =>\n String.fromCharCode(c.charCodeAt(0) | 32),\n );\n}\n\n/** Bidi/format characters and C0/C1 controls (except \\n and \\t). */\nfunction isUnsafe(code: number): boolean {\n return (\n (code <= 0x1f && code !== 0x0a && code !== 0x09) ||\n (code >= 0x7f && code <= 0x9f) ||\n (code >= 0x200b && code <= 0x200f) ||\n code === 0x2028 ||\n code === 0x2029 ||\n (code >= 0x202a && code <= 0x202e) ||\n (code >= 0x2066 && code <= 0x2069) ||\n code === 0xfeff\n );\n}\n\nfunction stripUnsafe(text: string): string {\n let out = '';\n let start = 0;\n for (let i = 0; i < text.length; i++) {\n if (isUnsafe(text.charCodeAt(i))) {\n out += text.slice(start, i);\n start = i + 1;\n }\n }\n return start === 0 ? text : out + text.slice(start);\n}\n\nexport function htmlToText(html: string): string {\n let input = html;\n let truncated = false;\n if (input.length > HTML_TO_TEXT_MAX_INPUT) {\n let cut = HTML_TO_TEXT_MAX_INPUT;\n const last = input.charCodeAt(cut - 1);\n if (last >= 0xd800 && last <= 0xdbff) cut -= 1; // do not split a pair\n input = input.slice(0, cut);\n truncated = true;\n }\n const lower = asciiLower(input);\n const out: string[] = [];\n let i = 0;\n const n = input.length;\n while (i < n) {\n const lt = input.indexOf('<', i);\n if (lt === -1) {\n out.push(input.slice(i));\n break;\n }\n if (lt > i) out.push(input.slice(i, lt));\n const next = lower[lt + 1];\n if (next === undefined || !/[a-z/!?]/.test(next)) {\n // A bare `<` (e.g. \"a < b\") is literal text, not a tag.\n out.push('<');\n i = lt + 1;\n continue;\n }\n if (input.startsWith('<!--', lt)) {\n const end = input.indexOf('-->', lt + 4);\n i = end === -1 ? n : end + 3;\n continue;\n }\n const gt = input.indexOf('>', lt + 1);\n if (gt === -1) {\n // Unterminated tag: drop the rest rather than emit markup.\n break;\n }\n let j = lt + 1;\n const closing = input[j] === '/';\n if (closing) j++;\n let k = j;\n while (k < gt && /[a-z0-9]/.test(lower[k])) k++;\n const name = lower.slice(j, k);\n i = gt + 1;\n if (!closing && SKIP.has(name)) {\n // Drop through the matching close tag; unclosed drops the remainder.\n let from = i;\n let found = -1;\n while (from < n) {\n const c = lower.indexOf(`</${name}`, from);\n if (c === -1) break;\n const after = lower[c + 2 + name.length];\n if (after === undefined || !/[a-z0-9]/.test(after)) {\n found = c;\n break;\n }\n from = c + 2;\n }\n if (found === -1) {\n i = n;\n } else {\n const close = input.indexOf('>', found);\n i = close === -1 ? n : close + 1;\n }\n continue;\n }\n if (BLOCK.has(name)) out.push('\\n');\n }\n const lines = stripUnsafe(decodeEntities(out.join('')))\n\n .split('\\n')\n .map((l) => l.trimEnd());\n // Collapse runs of blank lines to at most one, linearly.\n const kept: string[] = [];\n let blanks = 0;\n for (const line of lines) {\n if (line === '') {\n blanks++;\n if (blanks > 1) continue;\n } else {\n blanks = 0;\n }\n kept.push(line);\n }\n const text = kept.join('\\n').trim();\n return truncated ? `${text}\\n${HTML_TO_TEXT_TRUNCATED}` : text;\n}\n","/**\n * Email model - Email message extending the Message STI base\n *\n * Retains all email-specific fields (RFC 822 compliance, folders, etc.)\n * while inheriting common message fields from Message.\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 { field, ObjectRegistry, smrt } from '@happyvertical/smrt-core';\nimport { htmlToText } from '../html-to-text.js';\nimport type { MailTriageAction, MailTriageResult } from '../mail-triage.js';\nimport type {\n EmailOptions,\n MessageSendResult,\n SendEmailOptions,\n} from '../types';\nimport type { EmailAccount } from './EmailAccount';\nimport { Message } from './Message';\n\n@smrt({\n tableStrategy: 'sti',\n // Opt-in semantic mail search (MailSearchService mode 'semantic'). No\n // automatic generation: sync must not call an embedding model per message.\n embeddings: {\n fields: ['subject', 'textBody'],\n provider: 'auto',\n autoGenerate: false,\n },\n api: { include: ['list', 'get', 'create', 'update', 'delete'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n // Message is read-only over REST; this provider type is writable there.\n widenParentExposure: { api: ['create', 'update', 'delete'] },\n})\nexport class Email extends Message { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n // RFC 822 fields\n @field({\n description:\n 'The email reference assigned by the sender for tracking replies.',\n })\n messageId = ''; // RFC 822 Message-ID header\n @field({\n description: 'The sender-assigned reference of the email being replied to.',\n })\n inReplyTo = '';\n @field({\n description:\n \"The mail server's own id for this email, used to keep mailbox sync from storing it twice.\",\n })\n providerMessageId = '';\n\n // Additional recipients\n @field({ description: 'Recipients receiving a visible copy of this email.' })\n ccAddresses = '';\n @field({\n description:\n 'Recipients receiving a copy without appearing in the visible recipient list.',\n })\n bccAddresses = '';\n @field({ description: 'The address replies should be sent to.' })\n replyToAddress = '';\n @field({ description: 'The name associated with the reply address.' })\n replyToName = '';\n\n // Email-specific content\n @field({ description: 'The plain-text version of the email.' })\n textBody = '';\n @field({ description: 'The formatted version of the email.' })\n htmlBody = '';\n\n // Location\n @field({\n description:\n 'The mailbox folder reference supplied by the email connection.',\n })\n folderId = '';\n @field({\n description: 'The location of this email within the mailbox folders.',\n })\n folderPath = '';\n @field({\n description: 'Labels applied to this email by the mailbox provider.',\n })\n labels = ''; // JSON array (Gmail)\n @field({ description: 'Mailbox markers such as read, answered, or flagged.' })\n flags = ''; // JSON array (IMAP)\n\n // Email-specific status flags\n @field({ description: 'Whether this email has been replied to.' })\n isAnswered = false;\n @field({ description: 'Whether this email is saved as an unfinished draft.' })\n isDraft = false;\n\n // Raw data\n @field({\n description: 'The original email content as received from the mail server.',\n })\n rawMessage = '';\n @field({\n description: 'Delivery and routing details included with the email.',\n })\n headers = ''; // JSON object\n\n constructor(options: EmailOptions = {}) {\n super(options);\n\n if (options.messageId !== undefined) this.messageId = options.messageId;\n if (options.inReplyTo !== undefined) this.inReplyTo = options.inReplyTo;\n if (options.providerMessageId !== undefined)\n this.providerMessageId = options.providerMessageId;\n if (options.ccAddresses !== undefined)\n this.ccAddresses = options.ccAddresses;\n if (options.bccAddresses !== undefined)\n this.bccAddresses = options.bccAddresses;\n if (options.replyToAddress !== undefined)\n this.replyToAddress = options.replyToAddress;\n if (options.replyToName !== undefined)\n this.replyToName = options.replyToName;\n if (options.textBody !== undefined) this.textBody = options.textBody;\n if (options.htmlBody !== undefined) this.htmlBody = options.htmlBody;\n if (options.folderId !== undefined) this.folderId = options.folderId;\n if (options.folderPath !== undefined) this.folderPath = options.folderPath;\n if (options.labels !== undefined) this.labels = options.labels;\n if (options.flags !== undefined) this.flags = options.flags;\n if (options.isAnswered !== undefined) this.isAnswered = options.isAnswered;\n if (options.isDraft !== undefined) this.isDraft = options.isDraft;\n if (options.rawMessage !== undefined) this.rawMessage = options.rawMessage;\n if (options.headers !== undefined) this.headers = options.headers;\n\n // Populate base body from textBody for unified access\n if (options.textBody && !options.body) {\n this.body = options.textBody;\n }\n }\n\n /**\n * Triage this message on the mail server and locally (see\n * `EmailAccount.triage`). The stored row is updated when the server accepts\n * the change (re-read it to see the new state; this instance is not\n * mutated). Throws when the server refuses it.\n */\n async triage(action: MailTriageAction): Promise<MailTriageResult> {\n if (!this.id) throw new Error('Email.triage requires a persisted email');\n const account = (await this.getAccount()) as EmailAccount | null;\n if (!account || typeof account.triage !== 'function') {\n throw new Error('Email.triage requires an email account');\n }\n const result = await account.triage(action, [this.id]);\n const failure = result.failed.find((f) => f.id === this.id);\n if (failure) {\n throw new Error(\n `Triage '${action.kind}' refused: ${failure.code}${failure.message ? ` (${failure.message})` : ''}`,\n );\n }\n return result;\n }\n\n /**\n * Get CC addresses as parsed array\n */\n getCcAddresses(): Array<{ address: string; name?: string }> {\n if (!this.ccAddresses) return [];\n try {\n return JSON.parse(this.ccAddresses);\n } catch {\n return [];\n }\n }\n\n /**\n * Get BCC addresses as parsed array\n */\n getBccAddresses(): Array<{ address: string; name?: string }> {\n if (!this.bccAddresses) return [];\n try {\n return JSON.parse(this.bccAddresses);\n } catch {\n return [];\n }\n }\n\n /**\n * Get labels as parsed array\n */\n getLabels(): string[] {\n if (!this.labels) return [];\n try {\n return JSON.parse(this.labels);\n } catch {\n return [];\n }\n }\n\n /**\n * Set labels from array\n */\n setLabels(labels: string[]): void {\n this.labels = JSON.stringify(labels);\n }\n\n /**\n * Get flags as parsed array\n */\n getFlags(): string[] {\n if (!this.flags) return [];\n try {\n return JSON.parse(this.flags);\n } catch {\n return [];\n }\n }\n\n /**\n * Set flags from array\n */\n setFlags(flags: string[]): void {\n this.flags = JSON.stringify(flags);\n }\n\n /**\n * Get headers as parsed object\n */\n getHeaders(): Record<string, string | string[]> {\n if (!this.headers) return {};\n try {\n return JSON.parse(this.headers);\n } catch {\n return {};\n }\n }\n\n /**\n * Set headers from object\n */\n setHeaders(headers: Record<string, string | string[]>): void {\n this.headers = JSON.stringify(headers);\n }\n\n /**\n * Get the email account (typed as EmailAccount)\n */\n override 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 the folder\n */\n async getFolder() {\n if (!this.folderId) return null;\n\n const { EmailFolderCollection } = await import(\n '../collections/EmailFolderCollection'\n );\n const collection = await EmailFolderCollection.create(this.options);\n\n return await collection.get({ id: this.folderId });\n }\n\n /**\n * Get emails in the same thread\n */\n async getThreadEmails(): Promise<Email[]> {\n if (!this.threadId) return [this];\n\n const { EmailCollection } = await import('../collections/EmailCollection');\n const collection = await EmailCollection.create(this.options);\n\n return await collection.getByThread(this.threadId);\n }\n\n /**\n * Get a short preview of the email body\n */\n override getPreview(maxLength = 200): string {\n const body = this.textBody || this.htmlBody?.replace(/<[^>]*>/g, '') || '';\n if (body.length <= maxLength) return body;\n return `${body.slice(0, maxLength)}...`;\n }\n\n /**\n * Get References header values as array\n */\n getReferences(): string[] {\n const headers = this.getHeaders();\n const refs = headers.references;\n if (!refs) return [];\n if (Array.isArray(refs)) return refs;\n return refs.split(/\\s+/).filter(Boolean);\n }\n\n /**\n * Create a reply to this email with RFC 822 threading\n */\n override createReply(options?: { replyAll?: boolean }): Email {\n const reply = new (ObjectRegistry.resolveEffectiveConstructor(Email))({\n ...this.draftOptions(),\n id: undefined,\n accountId: this.accountId,\n threadId: this.threadId || this.id || undefined,\n subject: this.subject.startsWith('Re:')\n ? this.subject\n : `Re: ${this.subject}`,\n fromAddress: '',\n fromName: '',\n inReplyToMessageId: this.id || undefined,\n sendStatus: 'draft',\n isRead: true,\n isDraft: true,\n date: null,\n createdAt: undefined,\n updatedAt: undefined,\n\n // RFC 822 threading\n inReplyTo: this.messageId,\n\n // Nothing of the inbound message's own content or identity carries\n // over: the reply is plain text, with no hidden recipients, no copied\n // Message-ID, headers, attachments, or provider/server state.\n messageId: '',\n providerMessageId: '',\n htmlBody: '',\n bccAddresses: '[]',\n ccAddresses: '[]',\n headers: '',\n rawMessage: '',\n hasAttachments: false,\n\n // To: original sender\n toAddresses: JSON.stringify([\n { address: this.fromAddress, name: this.fromName },\n ]),\n });\n\n // RFC 822 References: original references + original Message-ID\n const refs = [...this.getReferences()];\n if (this.messageId && !refs.includes(this.messageId)) {\n refs.push(this.messageId);\n }\n reply.setHeaders({ references: refs.join(' ') });\n\n // Reply-All: add original To/CC as CC (excluding self)\n if (options?.replyAll) {\n const allRecipients = [\n ...this.getToAddresses(),\n ...this.getCcAddresses(),\n ];\n // Remove original sender (already in To:) and any duplicates\n const seen = new Set([this.fromAddress.toLowerCase()]);\n const ccAddresses = allRecipients.filter((r) => {\n const addr = r.address.toLowerCase();\n if (seen.has(addr)) return false;\n seen.add(addr);\n return true;\n });\n reply.ccAddresses = JSON.stringify(ccAddresses);\n }\n\n reply.body = this.buildQuotedBody();\n reply.textBody = reply.body;\n\n return reply;\n }\n\n /**\n * Create a forward of this email\n */\n override createForward(): Email {\n const forwardBody = this.buildForwardBody();\n\n const forward = new (ObjectRegistry.resolveEffectiveConstructor(Email))({\n ...this.draftOptions(),\n id: undefined,\n accountId: this.accountId,\n threadId: '',\n subject: this.subject.startsWith('Fwd:')\n ? this.subject\n : `Fwd: ${this.subject}`,\n toAddresses: '[]',\n ccAddresses: '[]',\n bccAddresses: '[]',\n fromAddress: '',\n fromName: '',\n body: forwardBody,\n textBody: forwardBody,\n // Attachment rows are not copied, so the draft has none.\n hasAttachments: false,\n messageId: '',\n providerMessageId: '',\n htmlBody: '',\n headers: '',\n rawMessage: '',\n inReplyToMessageId: '',\n inReplyTo: '',\n sendStatus: 'draft',\n isDraft: true,\n isRead: true,\n date: null,\n createdAt: undefined,\n updatedAt: undefined,\n });\n\n return forward;\n }\n\n /**\n * Build email-specific quoted body for replies\n */\n protected override buildQuotedBody(): string {\n const dateStr = this.date ? this.date.toLocaleString() : 'unknown date';\n const from = this.fromName\n ? `${this.fromName} <${this.fromAddress}>`\n : this.fromAddress;\n\n const bodyText = this.plainBody();\n const quotedLines = bodyText\n .split('\\n')\n .map((line) => `> ${line}`)\n .join('\\n');\n\n return `\\n\\nOn ${dateStr}, ${from} wrote:\\n${quotedLines}`;\n }\n\n /**\n * Plain text of this email for quoting. HTML-only mail (no text alternative)\n * is converted, because the HTML itself is never carried into a draft.\n */\n private plainBody(): string {\n const text = this.textBody || this.body;\n if (text) return text;\n return htmlToText(this.htmlBody || '');\n }\n\n /**\n * Build forwarded message body\n */\n private buildForwardBody(): string {\n const dateStr = this.date ? this.date.toLocaleString() : 'unknown date';\n const from = this.fromName\n ? `${this.fromName} <${this.fromAddress}>`\n : this.fromAddress;\n\n const toStr = this.getToAddresses()\n .map((r) => (r.name ? `${r.name} <${r.address}>` : r.address))\n .join(', ');\n\n const bodyText = this.plainBody();\n\n return [\n '',\n '',\n '---------- Forwarded message ----------',\n `From: ${from}`,\n `Date: ${dateStr}`,\n `Subject: ${this.subject}`,\n `To: ${toStr}`,\n '',\n bodyText,\n ].join('\\n');\n }\n\n /**\n * Send this email. Accepts {@link SendEmailOptions}, including send-time\n * `attachments`, which `EmailSender` merges with the stored rows (#3808).\n */\n override async send(options?: SendEmailOptions): Promise<MessageSendResult> {\n const result = await super.send(options);\n await this.markHasAttachments(options, result);\n return result;\n }\n\n /** Retry a failed send; takes the same options as {@link Email.send}. */\n override async retrySend(\n options?: SendEmailOptions,\n ): Promise<MessageSendResult> {\n const result = await super.retrySend(options);\n await this.markHasAttachments(options, result);\n return result;\n }\n\n /**\n * Record `hasAttachments` once send-time bytes were actually delivered, so a\n * rejected or failed send never claims attachments that did not go out.\n */\n private async markHasAttachments(\n options: SendEmailOptions | undefined,\n result: MessageSendResult,\n ): Promise<void> {\n if (!result.success || !options?.attachments?.length) return;\n if (this.hasAttachments) return;\n this.hasAttachments = true;\n if (this.isPersisted) await this.save();\n }\n}\n"],"mappings":";;;;;AASO,IAAM,yBAAyB,MAAM;AAE5C,IAAM,uBAAO,IAAI,IAAI;CACnB;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,IAAM,wBAAQ,IAAI,IAAI;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,IAAM,QAAgC;CACpC,KAAK;CACL,IAAI;CACJ,IAAI;CACJ,MAAM;CACN,MAAM;CACN,MAAM;CACN,OAAO;CACP,OAAO;CACP,QAAQ;CACR,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACP,MAAM;CACN,KAAK;CACL,OAAO;CACP,MAAM;CACN,QAAQ;AACV;AAEA,SAAS,eAAe,MAAsB;CAC5C,IAAI,CAAC,KAAK,SAAS,GAAG,GAAG,OAAO;CAChC,OAAO,KAAK,QAAQ,8CAA8C,GAAG,MAAM;EACzE,IAAI,EAAE,OAAO,KAAK;GAChB,MAAM,OACJ,EAAE,OAAO,OAAO,EAAE,OAAO,MACrB,OAAO,SAAS,EAAE,MAAM,CAAC,GAAG,EAAE,IAC9B,OAAO,SAAS,EAAE,MAAM,CAAC,GAAG,EAAE;GACpC,IAAI,OAAO,KAAK,QAAQ,WAAY,EAAE,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A,CAAA;AAMA,gBAAA,CAHC,MAAM,EACL,aAAa,+DACf,CAAC,CAAA,GA9DU,MA+DX,WAAA,cAAA,CAAA;AAIA,gBAAA,CAHC,MAAM,EACL,aAAa,wDACf,CAAC,CAAA,GAlEU,MAmEX,WAAA,WAAA,CAAA;AAnEW,QAAN,gBAAA,CAfN,KAAK;CACJ,eAAe;CAGf,YAAY;EACV,QAAQ,CAAC,WAAW,UAAU;EAC9B,UAAU;EACV,cAAc;CAChB;CACA,KAAK,EAAE,SAAS;EAAC;EAAQ;EAAO;EAAU;EAAU;CAAQ,EAAE;CAC9D,KAAK,EAAE,SAAS,CAAC,QAAQ,KAAK,EAAE;CAChC,KAAK,EAAE,cAAc,KAAK;CAE1B,qBAAqB,EAAE,KAAK;EAAC;EAAU;EAAU;CAAQ,EAAE;AAC7D,CAAC,CAAA,GACY,KAAA"}
1
+ {"version":3,"file":"Email-Bd1lCLiC.js","names":[],"sources":["../../src/html-to-text.ts","../../src/models/Email.ts"],"sourcesContent":["/**\n * Linear-time HTML to plain text for quoting HTML-only mail in drafts.\n *\n * Single forward scan, no backtracking regexes, input capped at\n * HTML_TO_TEXT_MAX_INPUT. Markup is never passed through: tags are dropped,\n * and the content of script/style/head/title/template/noscript elements and\n * comments is dropped. Text hidden by CSS (display:none etc.) is NOT detected\n * and remains in the output.\n */\nexport const HTML_TO_TEXT_MAX_INPUT = 256 * 1024;\n\nconst SKIP = new Set([\n 'script',\n 'style',\n 'head',\n 'title',\n 'template',\n 'noscript',\n]);\nconst BLOCK = new Set([\n 'p',\n 'div',\n 'li',\n 'tr',\n 'br',\n 'h1',\n 'h2',\n 'h3',\n 'h4',\n 'h5',\n 'h6',\n 'blockquote',\n 'table',\n 'ul',\n 'ol',\n 'pre',\n 'hr',\n]);\nconst NAMED: Record<string, string> = {\n amp: '&',\n lt: '<',\n gt: '>',\n quot: '\"',\n apos: \"'\",\n nbsp: ' ',\n mdash: '—',\n ndash: '–',\n hellip: '…',\n lsquo: '‘',\n rsquo: '’',\n ldquo: '“',\n rdquo: '”',\n copy: '©',\n reg: '®',\n trade: '™',\n bull: '•',\n middot: '·',\n};\n\nfunction decodeEntities(text: string): string {\n if (!text.includes('&')) return text;\n return text.replace(/&(#x[0-9a-f]{1,6}|#\\d{1,7}|[a-z]{2,8});/gi, (m, e) => {\n if (e[0] === '#') {\n const code =\n e[1] === 'x' || e[1] === 'X'\n ? Number.parseInt(e.slice(2), 16)\n : Number.parseInt(e.slice(1), 10);\n if (code > 0 && code <= 0x10ffff && !(code >= 0xd800 && code <= 0xdfff)) {\n return String.fromCodePoint(code);\n }\n return '';\n }\n return NAMED[e.toLowerCase()] ?? m;\n });\n}\n\nexport const HTML_TO_TEXT_TRUNCATED = '[\\u2026truncated]';\n\n/** Length-preserving ASCII-only lowercase (String#toLowerCase can change length). */\nfunction asciiLower(text: string): string {\n return text.replace(/[A-Z]/g, (c) =>\n String.fromCharCode(c.charCodeAt(0) | 32),\n );\n}\n\n/** Bidi/format characters and C0/C1 controls (except \\n and \\t). */\nfunction isUnsafe(code: number): boolean {\n return (\n (code <= 0x1f && code !== 0x0a && code !== 0x09) ||\n (code >= 0x7f && code <= 0x9f) ||\n (code >= 0x200b && code <= 0x200f) ||\n code === 0x2028 ||\n code === 0x2029 ||\n (code >= 0x202a && code <= 0x202e) ||\n (code >= 0x2066 && code <= 0x2069) ||\n code === 0xfeff\n );\n}\n\nfunction stripUnsafe(text: string): string {\n let out = '';\n let start = 0;\n for (let i = 0; i < text.length; i++) {\n if (isUnsafe(text.charCodeAt(i))) {\n out += text.slice(start, i);\n start = i + 1;\n }\n }\n return start === 0 ? text : out + text.slice(start);\n}\n\nexport function htmlToText(html: string): string {\n let input = html;\n let truncated = false;\n if (input.length > HTML_TO_TEXT_MAX_INPUT) {\n let cut = HTML_TO_TEXT_MAX_INPUT;\n const last = input.charCodeAt(cut - 1);\n if (last >= 0xd800 && last <= 0xdbff) cut -= 1; // do not split a pair\n input = input.slice(0, cut);\n truncated = true;\n }\n const lower = asciiLower(input);\n const out: string[] = [];\n let i = 0;\n const n = input.length;\n while (i < n) {\n const lt = input.indexOf('<', i);\n if (lt === -1) {\n out.push(input.slice(i));\n break;\n }\n if (lt > i) out.push(input.slice(i, lt));\n const next = lower[lt + 1];\n if (next === undefined || !/[a-z/!?]/.test(next)) {\n // A bare `<` (e.g. \"a < b\") is literal text, not a tag.\n out.push('<');\n i = lt + 1;\n continue;\n }\n if (input.startsWith('<!--', lt)) {\n const end = input.indexOf('-->', lt + 4);\n i = end === -1 ? n : end + 3;\n continue;\n }\n const gt = input.indexOf('>', lt + 1);\n if (gt === -1) {\n // Unterminated tag: drop the rest rather than emit markup.\n break;\n }\n let j = lt + 1;\n const closing = input[j] === '/';\n if (closing) j++;\n let k = j;\n while (k < gt && /[a-z0-9]/.test(lower[k])) k++;\n const name = lower.slice(j, k);\n i = gt + 1;\n if (!closing && SKIP.has(name)) {\n // Drop through the matching close tag; unclosed drops the remainder.\n let from = i;\n let found = -1;\n while (from < n) {\n const c = lower.indexOf(`</${name}`, from);\n if (c === -1) break;\n const after = lower[c + 2 + name.length];\n if (after === undefined || !/[a-z0-9]/.test(after)) {\n found = c;\n break;\n }\n from = c + 2;\n }\n if (found === -1) {\n i = n;\n } else {\n const close = input.indexOf('>', found);\n i = close === -1 ? n : close + 1;\n }\n continue;\n }\n if (BLOCK.has(name)) out.push('\\n');\n }\n const lines = stripUnsafe(decodeEntities(out.join('')))\n\n .split('\\n')\n .map((l) => l.trimEnd());\n // Collapse runs of blank lines to at most one, linearly.\n const kept: string[] = [];\n let blanks = 0;\n for (const line of lines) {\n if (line === '') {\n blanks++;\n if (blanks > 1) continue;\n } else {\n blanks = 0;\n }\n kept.push(line);\n }\n const text = kept.join('\\n').trim();\n return truncated ? `${text}\\n${HTML_TO_TEXT_TRUNCATED}` : text;\n}\n","/**\n * Email model - Email message extending the Message STI base\n *\n * Retains all email-specific fields (RFC 822 compliance, folders, etc.)\n * while inheriting common message fields from Message.\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 { field, ObjectRegistry, smrt } from '@happyvertical/smrt-core';\nimport { htmlToText } from '../html-to-text.js';\nimport type { MailTriageAction, MailTriageResult } from '../mail-triage.js';\nimport type {\n EmailOptions,\n MessageSendResult,\n SendEmailOptions,\n} from '../types';\nimport type { EmailAccount } from './EmailAccount';\nimport { Message } from './Message';\n\n@smrt({\n tableStrategy: 'sti',\n // Opt-in semantic mail search (MailSearchService mode 'semantic'). No\n // automatic generation: sync must not call an embedding model per message.\n embeddings: {\n fields: ['subject', 'textBody'],\n provider: 'auto',\n autoGenerate: false,\n },\n api: { include: ['list', 'get', 'create', 'update', 'delete'] },\n mcp: { include: ['list', 'get'] },\n cli: { skipApiCheck: true },\n // Message is read-only over REST; this provider type is writable there.\n widenParentExposure: { api: ['create', 'update', 'delete'] },\n})\nexport class Email extends Message { static __smrtPackage__ = \"@happyvertical/smrt-messages\";\n // RFC 822 fields\n @field({\n description:\n 'The email reference assigned by the sender for tracking replies.',\n })\n messageId = ''; // RFC 822 Message-ID header\n @field({\n description: 'The sender-assigned reference of the email being replied to.',\n })\n inReplyTo = '';\n @field({\n description:\n \"The mail server's own id for this email, used to keep mailbox sync from storing it twice.\",\n })\n providerMessageId = '';\n\n // Additional recipients\n @field({ description: 'Recipients receiving a visible copy of this email.' })\n ccAddresses = '';\n @field({\n description:\n 'Recipients receiving a copy without appearing in the visible recipient list.',\n })\n bccAddresses = '';\n @field({ description: 'The address replies should be sent to.' })\n replyToAddress = '';\n @field({ description: 'The name associated with the reply address.' })\n replyToName = '';\n\n // Email-specific content\n @field({ description: 'The plain-text version of the email.' })\n textBody = '';\n @field({ description: 'The formatted version of the email.' })\n htmlBody = '';\n\n // Location\n @field({\n description:\n 'The mailbox folder reference supplied by the email connection.',\n })\n folderId = '';\n @field({\n description: 'The location of this email within the mailbox folders.',\n })\n folderPath = '';\n @field({\n description: 'Labels applied to this email by the mailbox provider.',\n })\n labels = ''; // JSON array (Gmail)\n @field({ description: 'Mailbox markers such as read, answered, or flagged.' })\n flags = ''; // JSON array (IMAP)\n\n // Email-specific status flags\n @field({ description: 'Whether this email has been replied to.' })\n isAnswered = false;\n @field({ description: 'Whether this email is saved as an unfinished draft.' })\n isDraft = false;\n\n // Raw data\n @field({\n description: 'The original email content as received from the mail server.',\n })\n rawMessage = '';\n @field({\n description: 'Delivery and routing details included with the email.',\n })\n headers = ''; // JSON object\n\n constructor(options: EmailOptions = {}) {\n super(options);\n\n if (options.messageId !== undefined) this.messageId = options.messageId;\n if (options.inReplyTo !== undefined) this.inReplyTo = options.inReplyTo;\n if (options.providerMessageId !== undefined)\n this.providerMessageId = options.providerMessageId;\n if (options.ccAddresses !== undefined)\n this.ccAddresses = options.ccAddresses;\n if (options.bccAddresses !== undefined)\n this.bccAddresses = options.bccAddresses;\n if (options.replyToAddress !== undefined)\n this.replyToAddress = options.replyToAddress;\n if (options.replyToName !== undefined)\n this.replyToName = options.replyToName;\n if (options.textBody !== undefined) this.textBody = options.textBody;\n if (options.htmlBody !== undefined) this.htmlBody = options.htmlBody;\n if (options.folderId !== undefined) this.folderId = options.folderId;\n if (options.folderPath !== undefined) this.folderPath = options.folderPath;\n if (options.labels !== undefined) this.labels = options.labels;\n if (options.flags !== undefined) this.flags = options.flags;\n if (options.isAnswered !== undefined) this.isAnswered = options.isAnswered;\n if (options.isDraft !== undefined) this.isDraft = options.isDraft;\n if (options.rawMessage !== undefined) this.rawMessage = options.rawMessage;\n if (options.headers !== undefined) this.headers = options.headers;\n\n // Populate base body from textBody for unified access\n if (options.textBody && !options.body) {\n this.body = options.textBody;\n }\n }\n\n /**\n * Triage this message on the mail server and locally (see\n * `EmailAccount.triage`). The stored row is updated when the server accepts\n * the change (re-read it to see the new state; this instance is not\n * mutated). Throws when the server refuses it.\n */\n async triage(action: MailTriageAction): Promise<MailTriageResult> {\n if (!this.id) throw new Error('Email.triage requires a persisted email');\n const account = (await this.getAccount()) as EmailAccount | null;\n if (!account || typeof account.triage !== 'function') {\n throw new Error('Email.triage requires an email account');\n }\n const result = await account.triage(action, [this.id]);\n const failure = result.failed.find((f) => f.id === this.id);\n if (failure) {\n throw new Error(\n `Triage '${action.kind}' refused: ${failure.code}${failure.message ? ` (${failure.message})` : ''}`,\n );\n }\n return result;\n }\n\n /**\n * Get CC addresses as parsed array\n */\n getCcAddresses(): Array<{ address: string; name?: string }> {\n if (!this.ccAddresses) return [];\n try {\n return JSON.parse(this.ccAddresses);\n } catch {\n return [];\n }\n }\n\n /**\n * Get BCC addresses as parsed array\n */\n getBccAddresses(): Array<{ address: string; name?: string }> {\n if (!this.bccAddresses) return [];\n try {\n return JSON.parse(this.bccAddresses);\n } catch {\n return [];\n }\n }\n\n /**\n * Get labels as parsed array\n */\n getLabels(): string[] {\n if (!this.labels) return [];\n try {\n return JSON.parse(this.labels);\n } catch {\n return [];\n }\n }\n\n /**\n * Set labels from array\n */\n setLabels(labels: string[]): void {\n this.labels = JSON.stringify(labels);\n }\n\n /**\n * Get flags as parsed array\n */\n getFlags(): string[] {\n if (!this.flags) return [];\n try {\n return JSON.parse(this.flags);\n } catch {\n return [];\n }\n }\n\n /**\n * Set flags from array\n */\n setFlags(flags: string[]): void {\n this.flags = JSON.stringify(flags);\n }\n\n /**\n * Get headers as parsed object\n */\n getHeaders(): Record<string, string | string[]> {\n if (!this.headers) return {};\n try {\n return JSON.parse(this.headers);\n } catch {\n return {};\n }\n }\n\n /**\n * Set headers from object\n */\n setHeaders(headers: Record<string, string | string[]>): void {\n this.headers = JSON.stringify(headers);\n }\n\n /**\n * Get the email account (typed as EmailAccount)\n */\n override 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 the folder\n */\n async getFolder() {\n if (!this.folderId) return null;\n\n const { EmailFolderCollection } = await import(\n '../collections/EmailFolderCollection'\n );\n const collection = await EmailFolderCollection.create(this.options);\n\n return await collection.get({ id: this.folderId });\n }\n\n /**\n * Get emails in the same thread\n */\n async getThreadEmails(): Promise<Email[]> {\n if (!this.threadId) return [this];\n\n const { EmailCollection } = await import('../collections/EmailCollection');\n const collection = await EmailCollection.create(this.options);\n\n return await collection.getByThread(this.threadId);\n }\n\n /**\n * Get a short preview of the email body\n */\n override getPreview(maxLength = 200): string {\n const body = this.textBody || this.htmlBody?.replace(/<[^>]*>/g, '') || '';\n if (body.length <= maxLength) return body;\n return `${body.slice(0, maxLength)}...`;\n }\n\n /**\n * Get References header values as array\n */\n getReferences(): string[] {\n const headers = this.getHeaders();\n const refs = headers.references;\n if (!refs) return [];\n if (Array.isArray(refs)) return refs;\n return refs.split(/\\s+/).filter(Boolean);\n }\n\n /**\n * Create a reply to this email with RFC 822 threading\n */\n override createReply(options?: { replyAll?: boolean }): Email {\n const reply = new (ObjectRegistry.resolveEffectiveConstructor(Email))({\n ...this.draftOptions(),\n id: undefined,\n accountId: this.accountId,\n threadId: this.threadId || this.id || undefined,\n subject: this.subject.startsWith('Re:')\n ? this.subject\n : `Re: ${this.subject}`,\n fromAddress: '',\n fromName: '',\n inReplyToMessageId: this.id || undefined,\n sendStatus: 'draft',\n isRead: true,\n isDraft: true,\n date: null,\n createdAt: undefined,\n updatedAt: undefined,\n\n // RFC 822 threading\n inReplyTo: this.messageId,\n\n // Nothing of the inbound message's own content or identity carries\n // over: the reply is plain text, with no hidden recipients, no copied\n // Message-ID, headers, attachments, or provider/server state.\n messageId: '',\n providerMessageId: '',\n htmlBody: '',\n bccAddresses: '[]',\n ccAddresses: '[]',\n headers: '',\n rawMessage: '',\n hasAttachments: false,\n\n // To: original sender\n toAddresses: JSON.stringify([\n { address: this.fromAddress, name: this.fromName },\n ]),\n });\n\n // RFC 822 References: original references + original Message-ID\n const refs = [...this.getReferences()];\n if (this.messageId && !refs.includes(this.messageId)) {\n refs.push(this.messageId);\n }\n reply.setHeaders({ references: refs.join(' ') });\n\n // Reply-All: add original To/CC as CC (excluding self)\n if (options?.replyAll) {\n const allRecipients = [\n ...this.getToAddresses(),\n ...this.getCcAddresses(),\n ];\n // Remove original sender (already in To:) and any duplicates\n const seen = new Set([this.fromAddress.toLowerCase()]);\n const ccAddresses = allRecipients.filter((r) => {\n const addr = r.address.toLowerCase();\n if (seen.has(addr)) return false;\n seen.add(addr);\n return true;\n });\n reply.ccAddresses = JSON.stringify(ccAddresses);\n }\n\n reply.body = this.buildQuotedBody();\n reply.textBody = reply.body;\n\n return reply;\n }\n\n /**\n * Create a forward of this email\n */\n override createForward(): Email {\n const forwardBody = this.buildForwardBody();\n\n const forward = new (ObjectRegistry.resolveEffectiveConstructor(Email))({\n ...this.draftOptions(),\n id: undefined,\n accountId: this.accountId,\n threadId: '',\n subject: this.subject.startsWith('Fwd:')\n ? this.subject\n : `Fwd: ${this.subject}`,\n toAddresses: '[]',\n ccAddresses: '[]',\n bccAddresses: '[]',\n fromAddress: '',\n fromName: '',\n body: forwardBody,\n textBody: forwardBody,\n // Attachment rows are not copied, so the draft has none.\n hasAttachments: false,\n messageId: '',\n providerMessageId: '',\n htmlBody: '',\n headers: '',\n rawMessage: '',\n inReplyToMessageId: '',\n inReplyTo: '',\n sendStatus: 'draft',\n isDraft: true,\n isRead: true,\n date: null,\n createdAt: undefined,\n updatedAt: undefined,\n });\n\n return forward;\n }\n\n /**\n * Build email-specific quoted body for replies\n */\n protected override buildQuotedBody(): string {\n const dateStr = this.date ? this.date.toLocaleString() : 'unknown date';\n const from = this.fromName\n ? `${this.fromName} <${this.fromAddress}>`\n : this.fromAddress;\n\n const bodyText = this.plainBody();\n const quotedLines = bodyText\n .split('\\n')\n .map((line) => `> ${line}`)\n .join('\\n');\n\n return `\\n\\nOn ${dateStr}, ${from} wrote:\\n${quotedLines}`;\n }\n\n /**\n * Plain text of this email for quoting. HTML-only mail (no text alternative)\n * is converted, because the HTML itself is never carried into a draft.\n */\n private plainBody(): string {\n const text = this.textBody || this.body;\n if (text) return text;\n return htmlToText(this.htmlBody || '');\n }\n\n /**\n * Build forwarded message body\n */\n private buildForwardBody(): string {\n const dateStr = this.date ? this.date.toLocaleString() : 'unknown date';\n const from = this.fromName\n ? `${this.fromName} <${this.fromAddress}>`\n : this.fromAddress;\n\n const toStr = this.getToAddresses()\n .map((r) => (r.name ? `${r.name} <${r.address}>` : r.address))\n .join(', ');\n\n const bodyText = this.plainBody();\n\n return [\n '',\n '',\n '---------- Forwarded message ----------',\n `From: ${from}`,\n `Date: ${dateStr}`,\n `Subject: ${this.subject}`,\n `To: ${toStr}`,\n '',\n bodyText,\n ].join('\\n');\n }\n\n /**\n * Send this email. Accepts {@link SendEmailOptions}, including send-time\n * `attachments`, which `EmailSender` merges with the stored rows (#3808).\n */\n override async send(options?: SendEmailOptions): Promise<MessageSendResult> {\n const result = await super.send(options);\n await this.markHasAttachments(options, result);\n return result;\n }\n\n /** Retry a failed send; takes the same options as {@link Email.send}. */\n override async retrySend(\n options?: SendEmailOptions,\n ): Promise<MessageSendResult> {\n const result = await super.retrySend(options);\n await this.markHasAttachments(options, result);\n return result;\n }\n\n /**\n * Record `hasAttachments` once send-time bytes were actually delivered, so a\n * rejected or failed send never claims attachments that did not go out.\n */\n private async markHasAttachments(\n options: SendEmailOptions | undefined,\n result: MessageSendResult,\n ): Promise<void> {\n if (!result.success || !options?.attachments?.length) return;\n if (this.hasAttachments) return;\n this.hasAttachments = true;\n if (this.isPersisted) await this.save();\n }\n}\n"],"mappings":";;;;;AASO,IAAM,yBAAyB,MAAM;AAE5C,IAAM,uBAAO,IAAI,IAAI;CACnB;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,IAAM,wBAAQ,IAAI,IAAI;CACpB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,IAAM,QAAgC;CACpC,KAAK;CACL,IAAI;CACJ,IAAI;CACJ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