@happyvertical/smrt-messages 0.70.3 → 0.72.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 (59) hide show
  1. package/AGENTS.md +16 -6
  2. package/README.md +4 -2
  3. package/agents/attachment-storage.md +41 -0
  4. package/agents/send-approval.md +32 -12
  5. package/dist/access.d.ts +18 -1
  6. package/dist/access.d.ts.map +1 -1
  7. package/dist/attachment-storage.d.ts +50 -0
  8. package/dist/attachment-storage.d.ts.map +1 -0
  9. package/dist/chunks/{AttachmentCollection-Di2aRb2k.js → AttachmentCollection-CB5ssbOy.js} +40 -44
  10. package/dist/chunks/AttachmentCollection-CB5ssbOy.js.map +1 -0
  11. package/dist/chunks/{Email-tEYH6ZRw.js → Email--1mF4f-0.js} +6 -6
  12. package/dist/chunks/{Email-tEYH6ZRw.js.map → Email--1mF4f-0.js.map} +1 -1
  13. package/dist/chunks/{EmailAccountCollection-DWo_a-X5.js → EmailAccountCollection-BaWIVvI4.js} +136 -41
  14. package/dist/chunks/EmailAccountCollection-BaWIVvI4.js.map +1 -0
  15. package/dist/chunks/{EmailCollection-_Z2JY26I.js → EmailCollection-Cu7PTw8Y.js} +10 -4
  16. package/dist/chunks/{EmailCollection-_Z2JY26I.js.map → EmailCollection-Cu7PTw8Y.js.map} +1 -1
  17. package/dist/chunks/{EmailFolder-TyoFZVcC.js → EmailFolder-8CRSnmLs.js} +6 -6
  18. package/dist/chunks/{EmailFolder-TyoFZVcC.js.map → EmailFolder-8CRSnmLs.js.map} +1 -1
  19. package/dist/chunks/{EmailFolderCollection-CFtttkx6.js → EmailFolderCollection-e6QeSt5j.js} +2 -2
  20. package/dist/chunks/{EmailFolderCollection-CFtttkx6.js.map → EmailFolderCollection-e6QeSt5j.js.map} +1 -1
  21. package/dist/chunks/{EmailSender-bHwAYzBO.js → EmailSender-CQQMuVDg.js} +10 -4
  22. package/dist/chunks/EmailSender-CQQMuVDg.js.map +1 -0
  23. package/dist/chunks/{Message-DC877Gl7.js → Message-CHDqmhWf.js} +102 -43
  24. package/dist/chunks/Message-CHDqmhWf.js.map +1 -0
  25. package/dist/chunks/{MessageCollection-yZ6RyAtB.js → MessageCollection-B48ZrvCw.js} +7 -3
  26. package/dist/chunks/MessageCollection-B48ZrvCw.js.map +1 -0
  27. package/dist/chunks/{MessagingEndpointCollection-CNwpv_ZW.js → MessagingEndpointCollection-Z9eO6PSl.js} +2 -2
  28. package/dist/chunks/{MessagingEndpointCollection-CNwpv_ZW.js.map → MessagingEndpointCollection-Z9eO6PSl.js.map} +1 -1
  29. package/dist/collections/AttachmentCollection.d.ts.map +1 -1
  30. package/dist/collections/EmailCollection.d.ts.map +1 -1
  31. package/dist/collections/MessageCollection.d.ts.map +1 -1
  32. package/dist/connect.js +1 -1
  33. package/dist/host.browser.d.ts +2 -0
  34. package/dist/host.browser.d.ts.map +1 -1
  35. package/dist/host.browser.js +3 -1
  36. package/dist/host.browser.js.map +1 -1
  37. package/dist/host.d.ts +20 -0
  38. package/dist/host.d.ts.map +1 -1
  39. package/dist/host.js +39 -1
  40. package/dist/host.js.map +1 -1
  41. package/dist/index.d.ts +1 -0
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +18 -18
  44. package/dist/index.js.map +1 -1
  45. package/dist/manifest.json +1 -1
  46. package/dist/models/Attachment.d.ts +18 -11
  47. package/dist/models/Attachment.d.ts.map +1 -1
  48. package/dist/models/Message.d.ts +24 -12
  49. package/dist/models/Message.d.ts.map +1 -1
  50. package/dist/send-approval.d.ts.map +1 -1
  51. package/dist/senders/EmailSender.d.ts.map +1 -1
  52. package/dist/smrt-knowledge.json +13 -7
  53. package/dist/smrt-knowledge.okf.md +9 -5
  54. package/package.json +12 -12
  55. package/dist/chunks/AttachmentCollection-Di2aRb2k.js.map +0 -1
  56. package/dist/chunks/EmailAccountCollection-DWo_a-X5.js.map +0 -1
  57. package/dist/chunks/EmailSender-bHwAYzBO.js.map +0 -1
  58. package/dist/chunks/Message-DC877Gl7.js.map +0 -1
  59. package/dist/chunks/MessageCollection-yZ6RyAtB.js.map +0 -1
package/AGENTS.md CHANGED
@@ -68,9 +68,13 @@ owners and call `configureMailAccess({ options, resolvePrincipal })` at startup
68
68
  on purpose (`available` means outbound transport; JMAP is receive and sync
69
69
  only), and `connectMailbox` still connects it. Policy lookups use the
70
70
  configured db handle, not a caller's transaction.
71
- - Draft writes (and their attachments) need the `draft` scope on an owned
72
- account, checked in `Message.save()`/`delete()` and
73
- `Attachment.save()`/`delete()`; rules and bypasses:
71
+ - Writes to anything a later send would transmit (every row that is not
72
+ `sent`: drafts, `pending`, `scheduled`, `sending`, `failed`, received mail
73
+ saved, and any fresh row), attachments included, need the `draft` scope on
74
+ an owned account, checked in `Message.save()`/`delete()` and
75
+ `Attachment.save()`/`delete()`. Received mail (provider id, unflagged, plain
76
+ `draft`) is never sent and may be deleted; a stored `sent` row cannot leave
77
+ `sent`; read/flag changes alone need only `triage`. Rules and bypasses:
74
78
  [agents/send-approval.md](agents/send-approval.md#draft-writes).
75
79
  - `Message.send()` needs the `send` scope on an owned account. Agent sends
76
80
  (principal `kind` other than `person`/`human`) on a mail account are held
@@ -111,6 +115,13 @@ owners and call `configureMailAccess({ options, resolvePrincipal })` at startup
111
115
  `CorrespondentService` derives owner-private contacts (optional `Profile` link).
112
116
  Both fail closed. Details: [agents/mail-search.md](agents/mail-search.md).
113
117
 
118
+ ## Attachment storage root (#5645)
119
+
120
+ `Attachment.filePath` is `<accountId>/...` relative to the root set once at startup with
121
+ `configureAttachmentStorage({ root })` (beside `configureMailAccess`). Without
122
+ it stored files are never read (fail closed). Rules, send behaviour and the
123
+ upgrade step: [agents/attachment-storage.md](agents/attachment-storage.md).
124
+
114
125
  ## Mailbox connect (provider-neutral)
115
126
 
116
127
  Credentials reach smrt-secrets in two ways; neither writes the plaintext `settings` fallback.
@@ -221,9 +232,8 @@ import '@happyvertical/smrt-messages/providers/all'; // all of the above
221
232
  `createSender` hooks. Never import a provider SDK from any module reachable
222
233
  from `src/index.ts` — the consumer bundle gate (`packages/bundle-gate`)
223
234
  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.
235
+ - `Attachment.readContent()` reads with `node:fs` through `host.ts` (stubbed
236
+ in `host.browser.ts`), not `@happyvertical/files`; see Attachment storage.
227
237
 
228
238
  ## Gotchas
229
239
 
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.
@@ -42,7 +42,7 @@ outside system access. For an agent under `require_approval` it:
42
42
  both return `pendingApproval` and send nothing. The agent never sends a
43
43
  held draft itself; it goes out once, as the approving person.
44
44
 
45
- A held message is set to `draft` (a persona route creates it `pending`), so
45
+ A held message is set to `draft` and flagged `isDraft` (a persona route creates it `pending`), so
46
46
  it leaves every pending/scheduled outbox and a person can decide it. A
47
47
  persona message is held even under system access, so a system drain never
48
48
  sends it around its approval. Send-time attachment bytes (for example
@@ -103,19 +103,38 @@ same authority as sending directly from it.
103
103
  ## Draft writes
104
104
 
105
105
  The `draft` scope is needed: `Message.save()` and `Message.delete()`
106
- check it (`assertMailScopeOn`, `access.ts`) for an email that is draft
107
- content now or was when stored, by id or by the slug a new object would take
108
- over (its own or the one derived from its id), and for both accounts when a
109
- draft moves. Draft content is an email flagged `isDraft` (any stored form:
110
- `true`, `1`, `'1'`, `'true'`) whose `sendStatus` is not `sent`, so `failed`,
111
- `pending`, `scheduled` and `sending` rows are covered too. The stored row
112
- decides, whatever class the handle is. Received mail is not flagged. The
106
+ check it (`assertMailScopeOn`, `access.ts`) for unsent outgoing mail (below)
107
+ now or when stored, by id or by the slug a new object would take over (its own
108
+ or the one derived from its id), and for both accounts when a row moves. A
109
+ draft flag is `isDraft` in any stored form (`true`, `1`, `'1'`, `'true'`). The
110
+ stored row decides, whatever class the handle is. The
113
111
  grants and account owner are read before the write (a single-connection
114
112
  engine cannot serve the policy handle inside a transaction); the write then
115
113
  re-reads the stored row and refuses a save that now needs more.
116
114
  `Attachment.save()`/`delete()` need the same scope when the message they
117
- belong to (or are moved from) is draft content on an owned account; that
118
- check runs just before the write, not inside it.
115
+ belong to (or are moved from) is gated (`isMailWriteGated`). A write is gated
116
+ for every row that is not `sent`, because a later send would transmit it. That
117
+ includes received mail when it is saved, so content cannot be written without
118
+ the scope and then flipped into a draft; deleting received mail (and its
119
+ attachments) stays open. Received mail is a provider-tagged row (`messageId`,
120
+ `providerMessageId`, `folderId`, `tweetId` or `slackTs` set) that is unflagged
121
+ and still `draft`; `Message.send()` refuses it, stored row included. A `draft`
122
+ row with no provider id, a flagged draft, and `pending`, `scheduled`,
123
+ `sending`, `failed` or an unknown status are gated like any other.
124
+ `Message.save()`/`delete()` apply the same test to the stored row and to the
125
+ state a row is moved into, so a row cannot be relabelled or stripped of its
126
+ provider id around the check. A stored `sent` row cannot be moved out of
127
+ `sent` by a principal (sent mail is a record); an instance loaded before the
128
+ row was sent is refused the same way, so a stale save cannot make it sendable
129
+ again. A fresh row needs `draft` too, except a row the send path itself creates
130
+ (an unsaved message being sent) or the persona route queues, which needs
131
+ `send` (the route saves through a module-private helper, `saveQueuedForSend`,
132
+ valid only for a fresh row). A save that changes only `isRead` and `isFlagged`
133
+ of a stored row needs the `triage` scope instead of `draft`, so triage marks work on queued rows, and
134
+ `markAllRead` / `markFolderRead` try every row before raising the first error.
135
+ Sync stores received mail under `runWithMailSystemAccess`; a host that stores received mail itself does the same. A held
136
+ send's binding hash still covers its attachment rows. The attachment check
137
+ runs just before the write, not inside it.
119
138
  That covers generated routes, collection `delete`/`getOrUpsert`,
120
139
  `createReply`/`createForward` + `save()` and `MailDraftService`. Trusted work
121
140
  (`runWithMailSystemAccess`: sync, outbox, triage write-back, approval edits)
@@ -124,6 +143,7 @@ need `send` instead, and only while every stored field outside the lifecycle
124
143
  fields (`sendStatus`, `sentAt`, `sendError`, `retryCount`, handled-by,
125
144
  `updatedAt`) is unchanged, tenant, slug, context and subclass fields included.
126
145
  A row the send path itself creates (an unsaved message being sent) needs
127
- `send` too. As for read, triage and send, a principal's scope and account
128
- ceilings apply to unowned accounts too; with no principal an owned account is
146
+ `send` too (a queued row whose account no longer exists is marked `failed`
147
+ with nothing else changed, without a scope). As for read, triage and send, a
148
+ principal's scope and account ceilings apply to unowned accounts too; with no principal an owned account is
129
149
  closed and an unowned one is open.
package/dist/access.d.ts CHANGED
@@ -169,6 +169,21 @@ export declare function mailFlag(value: unknown): boolean;
169
169
  * Received mail is not flagged, whatever status it carries.
170
170
  */
171
171
  export declare function isUnsentDraft(sendStatus: unknown, isDraft: unknown): boolean;
172
+ /** Whether a row (instance or stored, any naming) carries a provider id. */
173
+ export declare function hasMailProvenance(row: Record<string, unknown>): boolean;
174
+ /**
175
+ * Received mail: a provider-tagged row that is neither flagged as a draft nor
176
+ * in an outgoing status. A record of what arrived, so it is never sent.
177
+ */
178
+ export declare function isReceivedMail(row: Record<string, unknown>): boolean;
179
+ /**
180
+ * Whether a write to this row (instance or stored) needs the `draft` scope.
181
+ * Every row that is not `sent` is, because a later send would transmit it.
182
+ * Saving counts received mail ({@link isReceivedMail}) too, so its content
183
+ * cannot be written without the scope and then flipped into a draft; deleting
184
+ * received mail removes nothing a send would transmit, so it stays open.
185
+ */
186
+ export declare function isMailWriteGated(row: Record<string, unknown>, write: 'save' | 'delete'): boolean;
172
187
  /**
173
188
  * Gate for writes that create, change or delete a draft: the principal needs
174
189
  * the `draft` scope on every listed account. Trusted system work
@@ -177,7 +192,9 @@ export declare function isUnsentDraft(sendStatus: unknown, isDraft: unknown): bo
177
192
  */
178
193
  export declare function assertMailDraftWrite(accountIds: ReadonlyArray<string | null | undefined>, options: SmrtClassOptions | undefined): Promise<void>;
179
194
  /** {@link assertMailDraftWrite} for any scope. */
180
- export declare function assertMailScopeOn(accountIds: ReadonlyArray<string | null | undefined>, scope: MailScope, options: SmrtClassOptions | undefined): Promise<void>;
195
+ export declare function assertMailScopeOn(accountIds: ReadonlyArray<string | null | undefined>, scope: MailScope, options: SmrtClassOptions | undefined, { allowMissing }?: {
196
+ allowMissing?: boolean;
197
+ }): Promise<void>;
181
198
  /**
182
199
  * Gate for direct hydration (`new Email({ id }).initialize()`,
183
200
  * `loadRelated('messageId')`), which bypasses collection read hooks: throws
@@ -1 +1 @@
1
- {"version":3,"file":"access.d.ts","sourceRoot":"","sources":["../src/access.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAEjE,OAAO,EAEL,6BAA6B,EAG9B,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAElD,eAAO,MAAM,WAAW,8CAA+C,CAAC;AACxE,MAAM,MAAM,SAAS,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC;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;KAAO,GAC1C,OAAO,CAAC,IAAI,CAAC;YAMF,sBAAsB;YAkCtB,SAAS;IAwDvB,2EAA2E;YAC7D,UAAU;IA8BxB,2DAA2D;YAC7C,QAAQ;IAoBtB;;;;;OAKG;YACW,YAAY;CAmC3B;AAED,OAAO,EAAE,6BAA6B,EAAE,CAAC"}
@@ -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, K as learnMailAccessOptions, N as assertMailDraftWrite, T as scopeAttachmentPath, U as isMailWriteGated, V as inMailSystemAccess, Z as runWithMailSystemAccess, j as assertHydratedMailAccess } from "./EmailAccountCollection-BaWIVvI4.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 = "";
@@ -68,28 +59,45 @@ var Attachment = class extends SmrtObject {
68
59
  await assertHydratedMailAccess(this);
69
60
  }
70
61
  /**
71
- * An attachment is part of what its message will send, so writing one on an
72
- * unsent email draft of an owned account needs the same `draft` scope as
73
- * writing the draft (see `Message.save()`), whichever route the write takes.
62
+ * An attachment is part of what its message will send, so writing one on
63
+ * a message of an owned account that is not `sent` needs the same `draft`
64
+ * scope as writing the message (see `Message.save()`), whichever route the
65
+ * write takes. Deleting one on received mail stays open.
66
+ *
74
67
  * Both the parent it is saved onto and the parent it is stored on count, so
75
68
  * an attachment cannot be moved on or off a draft without the scope.
76
69
  */
77
70
  async save(options) {
78
- await this.assertDraftParentWrite();
71
+ if (this.filePath) this.filePath = scopeAttachmentPath(this.filePath, await this.currentAccountId());
72
+ await this.assertDraftParentWrite("save");
79
73
  return super.save(options);
80
74
  }
81
75
  async delete(options = {}) {
82
- await this.assertDraftParentWrite();
76
+ await this.assertDraftParentWrite("delete");
83
77
  return super.delete(options);
84
78
  }
85
79
  /**
80
+ * The account of the message this row is stored on now, read from the
81
+ * stored message (never from the row's own `accountId`), or null.
82
+ */
83
+ async currentAccountId() {
84
+ if (!this.messageId) return null;
85
+ try {
86
+ const { MessageCollection } = await import("./MessageCollection-B48ZrvCw.js").then((n) => n.n);
87
+ const messages = await MessageCollection.create(this.options);
88
+ return (await this.db.get(messages.tableName, { id: this.messageId }))?.account_id || null;
89
+ } catch {
90
+ return null;
91
+ }
92
+ }
93
+ /**
86
94
  * Trusted system work and non-draft parents pass. Unlike the message check
87
95
  * this runs before the write, not inside its transaction: the attachment
88
96
  * save interceptor builds collections from the instance's options, and
89
97
  * inside a transaction those would register the transaction's handle as a
90
98
  * policy database.
91
99
  */
92
- async assertDraftParentWrite() {
100
+ async assertDraftParentWrite(write) {
93
101
  learnMailAccessOptions(this.options);
94
102
  if (inMailSystemAccess()) return;
95
103
  const parentIds = /* @__PURE__ */ new Set();
@@ -105,12 +113,12 @@ var Attachment = class extends SmrtObject {
105
113
  }
106
114
  }
107
115
  if (!parentIds.size) return;
108
- const { MessageCollection } = await import("./MessageCollection-yZ6RyAtB.js").then((n) => n.n);
116
+ const { MessageCollection } = await import("./MessageCollection-B48ZrvCw.js").then((n) => n.n);
109
117
  const messages = await MessageCollection.create(this.options);
110
118
  const accountIds = [];
111
119
  for (const id of parentIds) {
112
120
  const parent = await this.db.get(messages.tableName, { id });
113
- if (parent && isUnsentDraft(parent.send_status, parent.is_draft)) accountIds.push(parent.account_id ?? null);
121
+ if (parent && isMailWriteGated(parent, write)) accountIds.push(parent.account_id ?? null);
114
122
  }
115
123
  await assertMailDraftWrite(accountIds, this.options);
116
124
  }
@@ -119,7 +127,7 @@ var Attachment = class extends SmrtObject {
119
127
  */
120
128
  async getMessage() {
121
129
  if (!this.messageId) return null;
122
- const { MessageCollection } = await import("./MessageCollection-yZ6RyAtB.js").then((n) => n.n);
130
+ const { MessageCollection } = await import("./MessageCollection-B48ZrvCw.js").then((n) => n.n);
123
131
  return await (await MessageCollection.create(this.options)).get({ id: this.messageId });
124
132
  }
125
133
  /**
@@ -173,30 +181,19 @@ var Attachment = class extends SmrtObject {
173
181
  return !!this.filePath;
174
182
  }
175
183
  /**
176
- * Read file content (if stored externally)
184
+ * Read the stored file's bytes, or null when the row has no file or the
185
+ * file is missing or unreadable.
177
186
  *
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).
187
+ * `filePath` is relative to the root set with `configureAttachmentStorage`
188
+ * and must lie under `<accountId>/` of the message's current account.
189
+ * Throws `AttachmentStorageError` when no root is configured, or when the
190
+ * stored path (or a symlink under it) leaves the root or the account's
191
+ * directory; this includes rows stored before the root existed. The bytes are read
192
+ * raw: decoding a PDF as UTF-8 corrupts it (#3808).
185
193
  */
186
194
  async readContent() {
187
195
  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
- }
196
+ return readStoredAttachmentFile(this.filePath, await this.currentAccountId());
200
197
  }
201
198
  };
202
199
  __publicField(Attachment, "__smrtPackage__", "@happyvertical/smrt-messages");
@@ -225,15 +222,14 @@ var AttachmentCollection = class extends SmrtCollection {
225
222
  */
226
223
  async backfillAccountIds() {
227
224
  return runWithMailSystemAccess(async () => {
228
- const { MessageCollection } = await import("./MessageCollection-yZ6RyAtB.js").then((n) => n.n);
225
+ const { MessageCollection } = await import("./MessageCollection-B48ZrvCw.js").then((n) => n.n);
229
226
  const messages = await MessageCollection.create(this.options);
230
227
  let updated = 0;
231
228
  for (const attachment of await this.list({ where: { accountId: null } })) {
232
229
  if (!attachment.messageId) continue;
233
230
  const message = await messages.get({ id: attachment.messageId });
234
231
  if (!message?.accountId) continue;
235
- attachment.accountId = message.accountId;
236
- await attachment.save();
232
+ await this.db.update(this.tableName, { id: attachment.id }, { account_id: message.accountId });
237
233
  updated++;
238
234
  }
239
235
  return updated;
@@ -352,4 +348,4 @@ var AttachmentCollection = class extends SmrtCollection {
352
348
  //#endregion
353
349
  export { AttachmentCollection_exports as n, Attachment as r, AttachmentCollection as t };
354
350
 
355
- //# sourceMappingURL=AttachmentCollection-Di2aRb2k.js.map
351
+ //# sourceMappingURL=AttachmentCollection-CB5ssbOy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AttachmentCollection-CB5ssbOy.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 isMailWriteGated,\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\n * a message of an owned account that is not `sent` needs the same `draft`\n * scope as writing the message (see `Message.save()`), whichever route the\n * write takes. Deleting one on received mail stays open.\n *\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('save');\n return super.save(options);\n }\n\n override async delete(\n options: { expectedUpdatedAt?: Date | string } = {},\n ): Promise<void> {\n await this.assertDraftParentWrite('delete');\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(\n write: 'save' | 'delete',\n ): 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 && isMailWriteGated(parent, write)) {\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 }\n\n async findWithGlobals(tenantId: string): Promise<Attachment[]> {\n return queryWithGlobals<Attachment>(\n this,\n tenantId,\n 'Attachment.findWithGlobals',\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoCO,IAAM,aAAN,cAAyB,WAAW;CAEzC,WAA0B;CAG1B,YAAY;CAQZ,YAA2B;CAC3B,WAAW;CACX,cAAc;CACd,OAAO;CACP,YAAY;CACZ,qBAA8C;CAC9C,WAAW;CACX,YAAY;CAGZ,4BAAY,IAAI,KAAK;CAErB,YAAY,UAA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MAAM,EAAE,aAAa,MAAM,QAAQ;CAChE;;;;CAKA,MAAM,WAMH;EACD,MAAM,cAAc,MAAM,KAAK,KAAK,CAAC,CAAC;EAEtC,MAAM,SAAiC,CAAC;EACxC,KAAA,MAAW,cAAc,aAAa;GACpC,MAAM,OAAO,WAAW,YAAY,MAAM,GAAG,CAAA,CAAE,MAAM;GACrD,OAAO,SAAS,OAAO,SAAS,KAAK;EACvC;EAEA,OAAO;GACL,OAAO,YAAY;GACnB,WAAW,YAAY,QAAQ,KAAK,MAAM,MAAM,EAAE,MAAM,CAAC;GACzD;GACA,QAAQ,YAAY,QAAQ,MAAM,EAAE,SAAS,CAAC,CAAA,CAAE;GAChD,SAAS,YAAY,QAAQ,MAAM,CAAC,EAAE,SAAS,CAAC,CAAA,CAAE;EACpD;CACF;;;;CAKA,MAAM,gBAAgB,WAAoC;EACxD,MAAM,cAAc,MAAM,KAAK,aAAa,SAAS;EACrD,IAAI,QAAQ;EAEZ,KAAA,MAAW,cAAc,aAAa;GACpC,MAAM,WAAW,OAAO;GACxB;EACF;EAEA,OAAO;CACT;CAMA,MAAM,aAAa,UAAyC;EAC1D,OAAO,KAAK,KAAK,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC;CAC1C;CAKA,MAAM,aAAoC;EACxC,OAAO,YAAwB,IAAI;CACrC;CAEA,MAAM,gBAAgB,UAAyC;EAC7D,OAAO,iBACL,MACA,UACA,4BACF;CACF;AACF"}
@@ -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-BaWIVvI4.js";
3
+ import { t as Message } from "./Message-CHDqmhWf.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-BaWIVvI4.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-e6QeSt5j.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-Cu7PTw8Y.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--1mF4f-0.js.map