@happyvertical/smrt-messages 0.62.13 → 0.63.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.
- package/AGENTS.md +7 -1
- package/agents/send-approval.md +101 -0
- package/dist/access.d.ts +33 -1
- package/dist/access.d.ts.map +1 -1
- package/dist/chunks/{AttachmentCollection-Dzz2iKjx.js → AttachmentCollection-CQaFv6FD.js} +4 -4
- package/dist/chunks/{AttachmentCollection-Dzz2iKjx.js.map → AttachmentCollection-CQaFv6FD.js.map} +1 -1
- package/dist/chunks/{Email-DDMgkm_l.js → Email-YfrfXXmh.js} +185 -9
- package/dist/chunks/Email-YfrfXXmh.js.map +1 -0
- package/dist/chunks/EmailAccountCollection-DzSW5043.js +2472 -0
- package/dist/chunks/EmailAccountCollection-DzSW5043.js.map +1 -0
- package/dist/chunks/{EmailCollection-lo8WePl-.js → EmailCollection-BGtIdMhg.js} +3 -3
- package/dist/chunks/{EmailCollection-lo8WePl-.js.map → EmailCollection-BGtIdMhg.js.map} +1 -1
- package/dist/chunks/{EmailFolder-Bu7y8-VX.js → EmailFolder-DADdGZC0.js} +6 -6
- package/dist/chunks/{EmailFolder-Bu7y8-VX.js.map → EmailFolder-DADdGZC0.js.map} +1 -1
- package/dist/chunks/{EmailFolderCollection-BpzzKBhM.js → EmailFolderCollection-DSnVCTIB.js} +2 -2
- package/dist/chunks/{EmailFolderCollection-BpzzKBhM.js.map → EmailFolderCollection-DSnVCTIB.js.map} +1 -1
- package/dist/chunks/{EmailSender-B-Rtq9du.js → EmailSender-0Y6Bo_OK.js} +8 -1
- package/dist/chunks/EmailSender-0Y6Bo_OK.js.map +1 -0
- package/dist/chunks/{Message-BwW51pgG.js → Message-CGQywP0F.js} +139 -11
- package/dist/chunks/Message-CGQywP0F.js.map +1 -0
- package/dist/chunks/{MessageCollection-JjZybSMu.js → MessageCollection-Cw1T8ZxA.js} +2 -2
- package/dist/chunks/{MessageCollection-JjZybSMu.js.map → MessageCollection-Cw1T8ZxA.js.map} +1 -1
- package/dist/chunks/{MessagingEndpointCollection-FmbtiFJy.js → MessagingEndpointCollection-CX2ygSoD.js} +2 -2
- package/dist/chunks/{MessagingEndpointCollection-FmbtiFJy.js.map → MessagingEndpointCollection-CX2ygSoD.js.map} +1 -1
- package/dist/connect.js +1 -1
- package/dist/html-to-text.d.ts +13 -0
- package/dist/html-to-text.d.ts.map +1 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +129 -14
- package/dist/index.js.map +1 -1
- package/dist/mail-drafts.d.ts +63 -0
- package/dist/mail-drafts.d.ts.map +1 -0
- package/dist/mail-triage.d.ts.map +1 -1
- package/dist/manifest.json +357 -33
- package/dist/models/Email.d.ts +5 -0
- package/dist/models/Email.d.ts.map +1 -1
- package/dist/models/EmailAccount.d.ts +8 -1
- package/dist/models/EmailAccount.d.ts.map +1 -1
- package/dist/models/Message.d.ts +11 -0
- package/dist/models/Message.d.ts.map +1 -1
- package/dist/models/SlackMessage.d.ts +10 -0
- package/dist/models/SlackMessage.d.ts.map +1 -1
- package/dist/send-approval.d.ts +275 -0
- package/dist/send-approval.d.ts.map +1 -0
- package/dist/senders/EmailSender.d.ts.map +1 -1
- package/dist/smrt-knowledge.json +216 -8
- package/dist/smrt-knowledge.okf.md +7 -2
- package/dist/types.d.ts +20 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +12 -11
- package/dist/chunks/Email-DDMgkm_l.js.map +0 -1
- package/dist/chunks/EmailAccountCollection-CgZE9YAM.js +0 -1992
- package/dist/chunks/EmailAccountCollection-CgZE9YAM.js.map +0 -1
- package/dist/chunks/EmailSender-B-Rtq9du.js.map +0 -1
- package/dist/chunks/Message-BwW51pgG.js.map +0 -1
package/AGENTS.md
CHANGED
|
@@ -68,7 +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
|
-
- `Message.send()` needs the `send` scope on an owned account.
|
|
71
|
+
- `Message.send()` needs the `send` scope on an owned account. Agent sends
|
|
72
|
+
(principal `kind` other than `person`/`human`) on a mail account are held
|
|
73
|
+
for a person's approval unless the owner opted in to `auto_send`;
|
|
74
|
+
approve / edit-then-approve / reject / release (as an approving person,
|
|
75
|
+
never the agent) through `MailSendApprovalService`,
|
|
76
|
+
drafts through `MailDraftService`, "handled by" on every message. Gate,
|
|
77
|
+
binding and bypass rules: [agents/send-approval.md](agents/send-approval.md). Account rows are
|
|
72
78
|
not filtered (senders, routes and the outbox read them without a principal).
|
|
73
79
|
- `MailAccessService` (`grant`, `revoke`, `list`, `setOwner`) needs tenant
|
|
74
80
|
`messages.manage-access` AND ownership (or delegation); an administrator
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# Agent send policy, held sends, drafts and "handled by" (#5141)
|
|
2
|
+
|
|
3
|
+
Epic I (happyvertical.com#585). Code: `src/send-approval.ts`,
|
|
4
|
+
`src/mail-drafts.ts`, the send path in `src/models/Message.ts`.
|
|
5
|
+
|
|
6
|
+
## Who is an agent
|
|
7
|
+
|
|
8
|
+
The host supplies the acting principal through `configureMailAccess`'s
|
|
9
|
+
`resolvePrincipal`. Only `kind: 'person'` (or `'human'`) is a person;
|
|
10
|
+
anything else, including no label, is an agent. A persona route
|
|
11
|
+
(`message.personaId`, `PersonaMessagingService`) is an agent send whoever
|
|
12
|
+
invoked it (requester `persona:<id>`). Trusted system work
|
|
13
|
+
(`runWithMailSystemAccess`: sync, the outbox) is never held. With no
|
|
14
|
+
principal: when a gate is configured, a persona send is held and any other
|
|
15
|
+
send is refused; without a gate, behaviour is unchanged.
|
|
16
|
+
|
|
17
|
+
## Policy
|
|
18
|
+
|
|
19
|
+
`EmailAccount.agentSendPolicy`: null or `require_approval` (default) holds an
|
|
20
|
+
agent's send; `auto_send` lets it leave. Only the account owner, as a person,
|
|
21
|
+
with tenant `messages.manage-access`, changes it
|
|
22
|
+
(`MailAccessService.setAgentSendPolicy`); raising to `auto_send` needs
|
|
23
|
+
`confirmAutoSend: true` (the smrt-social public-latch pattern), lowering is
|
|
24
|
+
instant, and a change of owner resets it to null. A host per-rule hook (`configureMailSendApprovals({
|
|
25
|
+
resolveAgentSendPolicy })`) may answer either way for one send; null falls
|
|
26
|
+
back to the account. Non-mail accounts have no policy and are not held.
|
|
27
|
+
|
|
28
|
+
## Held send
|
|
29
|
+
|
|
30
|
+
`Message.send()` checks `send` scope, then send-as (on an owned account a
|
|
31
|
+
principal sends only from the account's own address), then
|
|
32
|
+
`holdAgentSend()`. Send-as applies to every mail account (owned or not)
|
|
33
|
+
outside system access. For an agent under `require_approval` it:
|
|
34
|
+
|
|
35
|
+
1. refuses without a configured gate, without a tenant, for an unsaved draft
|
|
36
|
+
or a caller copy that differs from the stored row, and for send-time
|
|
37
|
+
attachment bytes;
|
|
38
|
+
2. hashes the stored draft (`mailSendBindingHash`: account, from, to/cc/bcc,
|
|
39
|
+
subject, bodies, threading headers, stored attachment rows and a SHA-256
|
|
40
|
+
of each attachment file's bytes);
|
|
41
|
+
3. calls the gate's `check`, which only reports: `pending` or `approved`
|
|
42
|
+
both return `pendingApproval` and send nothing. The agent never sends a
|
|
43
|
+
held draft itself; it goes out once, as the approving person.
|
|
44
|
+
|
|
45
|
+
A held message is set to `draft` (a persona route creates it `pending`), so
|
|
46
|
+
it leaves every pending/scheduled outbox and a person can decide it. A
|
|
47
|
+
persona message is held even under system access, so a system drain never
|
|
48
|
+
sends it around its approval. Send-time attachment bytes (for example
|
|
49
|
+
`PersonaMessagingService` `attachments`) are refused on a held send: they are
|
|
50
|
+
not stored, so no person could review them and nothing could bind them;
|
|
51
|
+
store them as `Attachment` rows on the message instead. A refused send of a
|
|
52
|
+
`pending`/`scheduled` message is marked `failed` (definite), never left
|
|
53
|
+
queued.
|
|
54
|
+
|
|
55
|
+
After the row is claimed, a send an approval released re-hashes the draft
|
|
56
|
+
(attachment rows included); a mismatch fails definitely and sends nothing.
|
|
57
|
+
The approval request carries a neutral summary, never mail content: request
|
|
58
|
+
and event rows are readable tenant-wide.
|
|
59
|
+
|
|
60
|
+
The gate is structural; smrt-approvals' `createApprovalMailSendGate`
|
|
61
|
+
implements it (kind `messages.mail.send`). smrt-messages has a dev dependency
|
|
62
|
+
on smrt-approvals for tests only.
|
|
63
|
+
|
|
64
|
+
## Deciding
|
|
65
|
+
|
|
66
|
+
`MailSendApprovalService` acts as the resolved principal, which must be a
|
|
67
|
+
person holding `read` and `send` on the draft's account in the same tenant.
|
|
68
|
+
Deciding also needs the tenant `messages.send` permission, checked through
|
|
69
|
+
smrt-users with no bypass (on an unowned account the per-account decision
|
|
70
|
+
checks none). `approve(id, { edits? })` refuses a draft that changed since
|
|
71
|
+
the request (`draft_changed`); with edits it approves the revised hash first
|
|
72
|
+
(edit-then-approve), then saves the edits; once the approval is complete it
|
|
73
|
+
consumes it and sends as the person. `release(id)` sends a request already
|
|
74
|
+
approved elsewhere (a generic inbox), only by one of its approvers. Before
|
|
75
|
+
any consume every counted approver is re-verified (tenant `messages.send`
|
|
76
|
+
and `send` on the account). `reject(id, reason)` keeps the draft.
|
|
77
|
+
Double release is prevented by the single-use consume and the send claim.
|
|
78
|
+
|
|
79
|
+
## Audit and "handled by"
|
|
80
|
+
|
|
81
|
+
Triage, draft saves and sends stamp `handledById` / `handledByKind` /
|
|
82
|
+
`handledAt` on the message (`getHandledBy()`, `threadHandledBy()` for a
|
|
83
|
+
thread). When the host runs the action inside smrt-core `withAuditContext()`,
|
|
84
|
+
`auditMailAction` writes `messages.draft.save`, `messages.send.held`,
|
|
85
|
+
`messages.send.approved[-with-edits]`, `messages.send.rejected`,
|
|
86
|
+
`messages.send` (before the provider call; a writer failure stops the send)
|
|
87
|
+
and `messages.triage.<action>`. Mail models are not `audit: true`: that makes
|
|
88
|
+
every sync and outbox write demand a writer.
|
|
89
|
+
|
|
90
|
+
Deciding needs an unsent draft or a definitely failed send (`not_a_draft`
|
|
91
|
+
otherwise; an outcome-unknown send is never re-approved). On an unowned
|
|
92
|
+
(tenant-wide) account the per-account checks pass for any tenant person, the
|
|
93
|
+
same authority as sending directly from it.
|
|
94
|
+
|
|
95
|
+
## Known gaps
|
|
96
|
+
|
|
97
|
+
- No approval-queue or handled-by Svelte component yet.
|
|
98
|
+
- Attachment bytes are re-read by the sender after the post-claim check, a
|
|
99
|
+
narrow window.
|
|
100
|
+
- A crash between consume and send leaves a consumed approval and an unsent
|
|
101
|
+
draft; the agent resubmits for a new approval.
|
package/dist/access.d.ts
CHANGED
|
@@ -29,6 +29,7 @@
|
|
|
29
29
|
*/
|
|
30
30
|
import type { SmrtClassOptions } from '@happyvertical/smrt-core';
|
|
31
31
|
import { MANAGE_MAIL_ACCESS_PERMISSION } from './permissions.js';
|
|
32
|
+
import type { AgentSendPolicy } from './types.js';
|
|
32
33
|
export declare const MAIL_SCOPES: readonly ["read", "triage", "draft", "send"];
|
|
33
34
|
export type MailScope = (typeof MAIL_SCOPES)[number];
|
|
34
35
|
/** `ResourceGrant.resourceType` for a mail account. */
|
|
@@ -48,7 +49,11 @@ export interface MailPrincipal {
|
|
|
48
49
|
* maps its credential to.
|
|
49
50
|
*/
|
|
50
51
|
userId: string;
|
|
51
|
-
/**
|
|
52
|
+
/**
|
|
53
|
+
* `'person'` (or `'human'`) for a person; anything else, including no
|
|
54
|
+
* label, is treated as an agent: its sends follow the account's agent send
|
|
55
|
+
* policy and it can never approve a held send.
|
|
56
|
+
*/
|
|
52
57
|
kind?: string;
|
|
53
58
|
/**
|
|
54
59
|
* Host ceiling on scopes (for example an agent credential's mail scopes).
|
|
@@ -124,6 +129,18 @@ export declare class MailAccessError extends Error {
|
|
|
124
129
|
readonly status = 403;
|
|
125
130
|
constructor(scope: MailScope, reason: MailAccessReason);
|
|
126
131
|
}
|
|
132
|
+
/**
|
|
133
|
+
* The acting principal for the current request or job, as the host's
|
|
134
|
+
* `resolvePrincipal` returns it, or null (nothing configured, no resolver, or
|
|
135
|
+
* a malformed principal).
|
|
136
|
+
*/
|
|
137
|
+
export declare function resolveMailPrincipal(): Promise<MailPrincipal | null>;
|
|
138
|
+
/**
|
|
139
|
+
* True only for a principal the host explicitly labels a person (`kind`
|
|
140
|
+
* `'person'` or `'human'`). Fail closed: a missing or unknown label is an
|
|
141
|
+
* agent, so it is held for approval and can never approve.
|
|
142
|
+
*/
|
|
143
|
+
export declare function isPersonMailPrincipal(principal: Pick<MailPrincipal, 'kind'> | null | undefined): boolean;
|
|
127
144
|
/**
|
|
128
145
|
* Decide whether the current principal holds `scope` on `account`. Never
|
|
129
146
|
* throws for a denial; a lookup failure denies.
|
|
@@ -153,6 +170,11 @@ export interface MailAccessAdmin {
|
|
|
153
170
|
/** The acting user (`MailPrincipal.userId`). */
|
|
154
171
|
userId: string;
|
|
155
172
|
tenantId: string;
|
|
173
|
+
/**
|
|
174
|
+
* The host's label for the actor (`MailPrincipal.kind`). Only a person may
|
|
175
|
+
* change an account's agent send policy; other operations ignore it.
|
|
176
|
+
*/
|
|
177
|
+
kind?: string;
|
|
156
178
|
}
|
|
157
179
|
export interface GrantMailAccessInput {
|
|
158
180
|
accountId: string;
|
|
@@ -186,6 +208,16 @@ export declare class MailAccessService {
|
|
|
186
208
|
revoke(grantId: string): Promise<void>;
|
|
187
209
|
list(accountId: string): Promise<import("@happyvertical/smrt-users").ResourceGrant[]>;
|
|
188
210
|
setOwner(accountId: string, ownerUserId: string): Promise<void>;
|
|
211
|
+
/**
|
|
212
|
+
* Set what happens when an agent sends from this mail account (smrt#5141).
|
|
213
|
+
* Owner only, person only, and the tenant `messages.manage-access` ceiling.
|
|
214
|
+
* Lowering to `require_approval` is instant (a kill switch); raising to
|
|
215
|
+
* `auto_send` needs `confirmAutoSend: true`, like smrt-social's public latch.
|
|
216
|
+
*/
|
|
217
|
+
setAgentSendPolicy(accountId: string, policy: AgentSendPolicy, options?: {
|
|
218
|
+
confirmAutoSend?: boolean;
|
|
219
|
+
}): Promise<void>;
|
|
220
|
+
private setAgentSendPolicyImpl;
|
|
189
221
|
private grantImpl;
|
|
190
222
|
/** Revoke a grant. Delegated children stop working with their ancestor. */
|
|
191
223
|
private revokeImpl;
|
package/dist/access.d.ts.map
CHANGED
|
@@ -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;
|
|
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;AAErD,uDAAuD;AACvD,eAAO,MAAM,0BAA0B,qBAAqB,CAAC;AAS7D,uEAAuE;AACvE,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,SAAS,GAAG,MAAM,CAE5D;AAED,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,SAAS,CAE9D;AAED,kDAAkD;AAClD,MAAM,WAAW,aAAa;IAC5B,4EAA4E;IAC5E,EAAE,EAAE,MAAM,CAAC;IACX,yEAAyE;IACzE,QAAQ,EAAE,MAAM,CAAC;IACjB;;;;OAIG;IACH,MAAM,EAAE,MAAM,CAAC;IAC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QL,SAAS;IAYvB,KAAK,CAAC,KAAK,EAAE,oBAAoB;IAIjC,MAAM,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAItC,IAAI,CAAC,SAAS,EAAE,MAAM;IAItB,QAAQ,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAI/D;;;;;OAKG;IACH,kBAAkB,CAChB,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,eAAe,EACvB,OAAO,GAAE;QAAE,eAAe,CAAC,EAAE,OAAO,CAAA;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"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
|
-
import {
|
|
2
|
+
import { B as runWithMailSystemAccess, T as assertHydratedMailAccess } from "./EmailAccountCollection-DzSW5043.js";
|
|
3
3
|
import { queryGlobal, queryWithGlobals } from "../host.js";
|
|
4
4
|
import { SmrtCollection, SmrtObject, foreignKey, importOptionalDependency, smrt } from "@happyvertical/smrt-core";
|
|
5
5
|
import { TenantScoped, tenantId } from "@happyvertical/smrt-tenancy/decorators";
|
|
@@ -72,7 +72,7 @@ var Attachment = class extends SmrtObject {
|
|
|
72
72
|
*/
|
|
73
73
|
async getMessage() {
|
|
74
74
|
if (!this.messageId) return null;
|
|
75
|
-
const { MessageCollection } = await import("./MessageCollection-
|
|
75
|
+
const { MessageCollection } = await import("./MessageCollection-Cw1T8ZxA.js").then((n) => n.n);
|
|
76
76
|
return await (await MessageCollection.create(this.options)).get({ id: this.messageId });
|
|
77
77
|
}
|
|
78
78
|
/**
|
|
@@ -178,7 +178,7 @@ var AttachmentCollection = class extends SmrtCollection {
|
|
|
178
178
|
*/
|
|
179
179
|
async backfillAccountIds() {
|
|
180
180
|
return runWithMailSystemAccess(async () => {
|
|
181
|
-
const { MessageCollection } = await import("./MessageCollection-
|
|
181
|
+
const { MessageCollection } = await import("./MessageCollection-Cw1T8ZxA.js").then((n) => n.n);
|
|
182
182
|
const messages = await MessageCollection.create(this.options);
|
|
183
183
|
let updated = 0;
|
|
184
184
|
for (const attachment of await this.list({ where: { accountId: null } })) {
|
|
@@ -305,4 +305,4 @@ var AttachmentCollection = class extends SmrtCollection {
|
|
|
305
305
|
//#endregion
|
|
306
306
|
export { AttachmentCollection_exports as n, Attachment as r, AttachmentCollection as t };
|
|
307
307
|
|
|
308
|
-
//# sourceMappingURL=AttachmentCollection-
|
|
308
|
+
//# sourceMappingURL=AttachmentCollection-CQaFv6FD.js.map
|
package/dist/chunks/{AttachmentCollection-Dzz2iKjx.js.map → AttachmentCollection-CQaFv6FD.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AttachmentCollection-Dzz2iKjx.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 importOptionalDependency,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport { assertHydratedMailAccess } from '../access.js';\nimport type { AttachmentOptions } from '../types';\n\n/**\n * Split an absolute path into its directory and file name, or return null for\n * a relative path. Plain string handling rather than `node:path`: the package\n * root must stay browser-reachable (the bundle-gate forbids `node:*` there).\n */\nfunction splitAbsolutePath(\n filePath: string,\n): { dir: string; base: string } | null {\n // A backslash separates segments only in a Windows path; in a POSIX path it\n // is an ordinary filename character.\n const windows = /^[A-Za-z]:[\\\\/]/.test(filePath);\n if (!windows && !filePath.startsWith('/')) return null;\n const cut = windows\n ? Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\\\'))\n : filePath.lastIndexOf('/');\n const dir = filePath.slice(0, cut) || filePath.slice(0, cut + 1);\n return { dir, base: filePath.slice(cut + 1) };\n}\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 * 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 file content (if stored externally)\n *\n * The files SDK is loaded through core's bundler-invisible optional-import\n * boundary so it never enters provider-neutral consumer bundles (#1979).\n * Absence of the SDK at runtime degrades to the existing null contract.\n *\n * The local provider joins every path onto its base path (the process cwd\n * by default), so an absolute `filePath` is rooted at its own directory, and\n * the bytes are read raw: decoding a PDF as UTF-8 corrupts it (#3808).\n */\n async readContent(): Promise<Buffer | null> {\n if (!this.filePath) return null;\n\n try {\n const { getFilesystem, initializeProviders } =\n (await importOptionalDependency(\n '@happyvertical/files',\n \"Import '@happyvertical/smrt-core/filesystem' (or '@happyvertical/smrt-assets/filesystem') during server startup to read externally-stored attachments in bundled builds.\",\n )) as typeof import('@happyvertical/files');\n // The SDK registers its providers asynchronously on import; make the\n // local one available before asking for it.\n await initializeProviders?.();\n const split = splitAbsolutePath(this.filePath);\n const files = await getFilesystem(\n split ? { type: 'local', basePath: split.dir } : { type: 'local' },\n );\n const data = await files.read(split ? split.base : this.filePath, {\n raw: true,\n });\n return data instanceof Buffer ? data : Buffer.from(data);\n } catch {\n return null;\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 attachment.accountId = message.accountId;\n await attachment.save();\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":";;;;;;;;;;;;;;;;;;;;;AAwBA,SAAS,kBACP,UACsC;CAGtC,MAAM,UAAU,kBAAkB,KAAK,QAAQ;CAC/C,IAAI,CAAC,WAAW,CAAC,SAAS,WAAW,GAAG,GAAG,OAAO;CAClD,MAAM,MAAM,UACR,KAAK,IAAI,SAAS,YAAY,GAAG,GAAG,SAAS,YAAY,IAAI,CAAC,IAC9D,SAAS,YAAY,GAAG;CAE5B,OAAO;EAAE,KADG,SAAS,MAAM,GAAG,GAAG,KAAK,SAAS,MAAM,GAAG,MAAM,CAAC;EACjD,MAAM,SAAS,MAAM,MAAM,CAAC;CAAE;AAC9C;AAQO,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,UAA6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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
|
+
{"version":3,"file":"AttachmentCollection-CQaFv6FD.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 importOptionalDependency,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy/decorators';\nimport { assertHydratedMailAccess } from '../access.js';\nimport type { AttachmentOptions } from '../types';\n\n/**\n * Split an absolute path into its directory and file name, or return null for\n * a relative path. Plain string handling rather than `node:path`: the package\n * root must stay browser-reachable (the bundle-gate forbids `node:*` there).\n */\nfunction splitAbsolutePath(\n filePath: string,\n): { dir: string; base: string } | null {\n // A backslash separates segments only in a Windows path; in a POSIX path it\n // is an ordinary filename character.\n const windows = /^[A-Za-z]:[\\\\/]/.test(filePath);\n if (!windows && !filePath.startsWith('/')) return null;\n const cut = windows\n ? Math.max(filePath.lastIndexOf('/'), filePath.lastIndexOf('\\\\'))\n : filePath.lastIndexOf('/');\n const dir = filePath.slice(0, cut) || filePath.slice(0, cut + 1);\n return { dir, base: filePath.slice(cut + 1) };\n}\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 * 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 file content (if stored externally)\n *\n * The files SDK is loaded through core's bundler-invisible optional-import\n * boundary so it never enters provider-neutral consumer bundles (#1979).\n * Absence of the SDK at runtime degrades to the existing null contract.\n *\n * The local provider joins every path onto its base path (the process cwd\n * by default), so an absolute `filePath` is rooted at its own directory, and\n * the bytes are read raw: decoding a PDF as UTF-8 corrupts it (#3808).\n */\n async readContent(): Promise<Buffer | null> {\n if (!this.filePath) return null;\n\n try {\n const { getFilesystem, initializeProviders } =\n (await importOptionalDependency(\n '@happyvertical/files',\n \"Import '@happyvertical/smrt-core/filesystem' (or '@happyvertical/smrt-assets/filesystem') during server startup to read externally-stored attachments in bundled builds.\",\n )) as typeof import('@happyvertical/files');\n // The SDK registers its providers asynchronously on import; make the\n // local one available before asking for it.\n await initializeProviders?.();\n const split = splitAbsolutePath(this.filePath);\n const files = await getFilesystem(\n split ? { type: 'local', basePath: split.dir } : { type: 'local' },\n );\n const data = await files.read(split ? split.base : this.filePath, {\n raw: true,\n });\n return data instanceof Buffer ? data : Buffer.from(data);\n } catch {\n return null;\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 attachment.accountId = message.accountId;\n await attachment.save();\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":";;;;;;;;;;;;;;;;;;;;;AAwBA,SAAS,kBACP,UACsC;CAGtC,MAAM,UAAU,kBAAkB,KAAK,QAAQ;CAC/C,IAAI,CAAC,WAAW,CAAC,SAAS,WAAW,GAAG,GAAG,OAAO;CAClD,MAAM,MAAM,UACR,KAAK,IAAI,SAAS,YAAY,GAAG,GAAG,SAAS,YAAY,IAAI,CAAC,IAC9D,SAAS,YAAY,GAAG;CAE5B,OAAO;EAAE,KADG,SAAS,MAAM,GAAG,GAAG,KAAK,SAAS,MAAM,GAAG,MAAM,CAAC;EACjD,MAAM,SAAS,MAAM,MAAM,CAAC;CAAE;AAC9C;AAQO,IAAM,aAAN,cAAyB,WAAW;CAEzC,WAA0B;CAG1B,YAAY;CAQZ,YAA2B;CAC3B,WAAW;CACX,cAAc;CACd,O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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,7 +1,161 @@
|
|
|
1
1
|
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
|
|
2
|
-
import "./EmailAccountCollection-
|
|
3
|
-
import { t as Message } from "./Message-
|
|
2
|
+
import "./EmailAccountCollection-DzSW5043.js";
|
|
3
|
+
import { t as Message } from "./Message-CGQywP0F.js";
|
|
4
4
|
import { ObjectRegistry, field, smrt } from "@happyvertical/smrt-core";
|
|
5
|
+
//#region src/html-to-text.ts
|
|
6
|
+
var HTML_TO_TEXT_MAX_INPUT = 256 * 1024;
|
|
7
|
+
var SKIP = /* @__PURE__ */ new Set([
|
|
8
|
+
"script",
|
|
9
|
+
"style",
|
|
10
|
+
"head",
|
|
11
|
+
"title",
|
|
12
|
+
"template",
|
|
13
|
+
"noscript"
|
|
14
|
+
]);
|
|
15
|
+
var BLOCK = /* @__PURE__ */ new Set([
|
|
16
|
+
"p",
|
|
17
|
+
"div",
|
|
18
|
+
"li",
|
|
19
|
+
"tr",
|
|
20
|
+
"br",
|
|
21
|
+
"h1",
|
|
22
|
+
"h2",
|
|
23
|
+
"h3",
|
|
24
|
+
"h4",
|
|
25
|
+
"h5",
|
|
26
|
+
"h6",
|
|
27
|
+
"blockquote",
|
|
28
|
+
"table",
|
|
29
|
+
"ul",
|
|
30
|
+
"ol",
|
|
31
|
+
"pre",
|
|
32
|
+
"hr"
|
|
33
|
+
]);
|
|
34
|
+
var NAMED = {
|
|
35
|
+
amp: "&",
|
|
36
|
+
lt: "<",
|
|
37
|
+
gt: ">",
|
|
38
|
+
quot: "\"",
|
|
39
|
+
apos: "'",
|
|
40
|
+
nbsp: " ",
|
|
41
|
+
mdash: "—",
|
|
42
|
+
ndash: "–",
|
|
43
|
+
hellip: "…",
|
|
44
|
+
lsquo: "‘",
|
|
45
|
+
rsquo: "’",
|
|
46
|
+
ldquo: "“",
|
|
47
|
+
rdquo: "”",
|
|
48
|
+
copy: "©",
|
|
49
|
+
reg: "®",
|
|
50
|
+
trade: "™",
|
|
51
|
+
bull: "•",
|
|
52
|
+
middot: "·"
|
|
53
|
+
};
|
|
54
|
+
function decodeEntities(text) {
|
|
55
|
+
if (!text.includes("&")) return text;
|
|
56
|
+
return text.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|[a-z]{2,8});/gi, (m, e) => {
|
|
57
|
+
if (e[0] === "#") {
|
|
58
|
+
const code = e[1] === "x" || e[1] === "X" ? Number.parseInt(e.slice(2), 16) : Number.parseInt(e.slice(1), 10);
|
|
59
|
+
if (code > 0 && code <= 1114111 && !(code >= 55296 && code <= 57343)) return String.fromCodePoint(code);
|
|
60
|
+
return "";
|
|
61
|
+
}
|
|
62
|
+
return NAMED[e.toLowerCase()] ?? m;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
var HTML_TO_TEXT_TRUNCATED = "[…truncated]";
|
|
66
|
+
function asciiLower(text) {
|
|
67
|
+
return text.replace(/[A-Z]/g, (c) => String.fromCharCode(c.charCodeAt(0) | 32));
|
|
68
|
+
}
|
|
69
|
+
function isUnsafe(code) {
|
|
70
|
+
return code <= 31 && code !== 10 && code !== 9 || code >= 127 && code <= 159 || code >= 8203 && code <= 8207 || code === 8232 || code === 8233 || code >= 8234 && code <= 8238 || code >= 8294 && code <= 8297 || code === 65279;
|
|
71
|
+
}
|
|
72
|
+
function stripUnsafe(text) {
|
|
73
|
+
let out = "";
|
|
74
|
+
let start = 0;
|
|
75
|
+
for (let i = 0; i < text.length; i++) if (isUnsafe(text.charCodeAt(i))) {
|
|
76
|
+
out += text.slice(start, i);
|
|
77
|
+
start = i + 1;
|
|
78
|
+
}
|
|
79
|
+
return start === 0 ? text : out + text.slice(start);
|
|
80
|
+
}
|
|
81
|
+
function htmlToText(html) {
|
|
82
|
+
let input = html;
|
|
83
|
+
let truncated = false;
|
|
84
|
+
if (input.length > 262144) {
|
|
85
|
+
let cut = HTML_TO_TEXT_MAX_INPUT;
|
|
86
|
+
const last = input.charCodeAt(cut - 1);
|
|
87
|
+
if (last >= 55296 && last <= 56319) cut -= 1;
|
|
88
|
+
input = input.slice(0, cut);
|
|
89
|
+
truncated = true;
|
|
90
|
+
}
|
|
91
|
+
const lower = asciiLower(input);
|
|
92
|
+
const out = [];
|
|
93
|
+
let i = 0;
|
|
94
|
+
const n = input.length;
|
|
95
|
+
while (i < n) {
|
|
96
|
+
const lt = input.indexOf("<", i);
|
|
97
|
+
if (lt === -1) {
|
|
98
|
+
out.push(input.slice(i));
|
|
99
|
+
break;
|
|
100
|
+
}
|
|
101
|
+
if (lt > i) out.push(input.slice(i, lt));
|
|
102
|
+
const next = lower[lt + 1];
|
|
103
|
+
if (next === void 0 || !/[a-z/!?]/.test(next)) {
|
|
104
|
+
out.push("<");
|
|
105
|
+
i = lt + 1;
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (input.startsWith("<!--", lt)) {
|
|
109
|
+
const end = input.indexOf("-->", lt + 4);
|
|
110
|
+
i = end === -1 ? n : end + 3;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const gt = input.indexOf(">", lt + 1);
|
|
114
|
+
if (gt === -1) break;
|
|
115
|
+
let j = lt + 1;
|
|
116
|
+
const closing = input[j] === "/";
|
|
117
|
+
if (closing) j++;
|
|
118
|
+
let k = j;
|
|
119
|
+
while (k < gt && /[a-z0-9]/.test(lower[k])) k++;
|
|
120
|
+
const name = lower.slice(j, k);
|
|
121
|
+
i = gt + 1;
|
|
122
|
+
if (!closing && SKIP.has(name)) {
|
|
123
|
+
let from = i;
|
|
124
|
+
let found = -1;
|
|
125
|
+
while (from < n) {
|
|
126
|
+
const c = lower.indexOf(`</${name}`, from);
|
|
127
|
+
if (c === -1) break;
|
|
128
|
+
const after = lower[c + 2 + name.length];
|
|
129
|
+
if (after === void 0 || !/[a-z0-9]/.test(after)) {
|
|
130
|
+
found = c;
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
133
|
+
from = c + 2;
|
|
134
|
+
}
|
|
135
|
+
if (found === -1) i = n;
|
|
136
|
+
else {
|
|
137
|
+
const close = input.indexOf(">", found);
|
|
138
|
+
i = close === -1 ? n : close + 1;
|
|
139
|
+
}
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
if (BLOCK.has(name)) out.push("\n");
|
|
143
|
+
}
|
|
144
|
+
const lines = stripUnsafe(decodeEntities(out.join(""))).split("\n").map((l) => l.trimEnd());
|
|
145
|
+
const kept = [];
|
|
146
|
+
let blanks = 0;
|
|
147
|
+
for (const line of lines) {
|
|
148
|
+
if (line === "") {
|
|
149
|
+
blanks++;
|
|
150
|
+
if (blanks > 1) continue;
|
|
151
|
+
} else blanks = 0;
|
|
152
|
+
kept.push(line);
|
|
153
|
+
}
|
|
154
|
+
const text = kept.join("\n").trim();
|
|
155
|
+
return truncated ? `${text}
|
|
156
|
+
${HTML_TO_TEXT_TRUNCATED}` : text;
|
|
157
|
+
}
|
|
158
|
+
//#endregion
|
|
5
159
|
//#region src/models/Email.ts
|
|
6
160
|
var Email_exports = /* @__PURE__ */ __exportAll({ Email: () => Email });
|
|
7
161
|
var __defProp = Object.defineProperty;
|
|
@@ -151,7 +305,7 @@ var Email = class extends Message {
|
|
|
151
305
|
*/
|
|
152
306
|
async getAccount() {
|
|
153
307
|
if (!this.accountId) return null;
|
|
154
|
-
const { EmailAccountCollection } = await import("./EmailAccountCollection-
|
|
308
|
+
const { EmailAccountCollection } = await import("./EmailAccountCollection-DzSW5043.js").then((n) => n.n);
|
|
155
309
|
return await (await EmailAccountCollection.create(this.options)).get({ id: this.accountId });
|
|
156
310
|
}
|
|
157
311
|
/**
|
|
@@ -159,7 +313,7 @@ var Email = class extends Message {
|
|
|
159
313
|
*/
|
|
160
314
|
async getFolder() {
|
|
161
315
|
if (!this.folderId) return null;
|
|
162
|
-
const { EmailFolderCollection } = await import("./EmailFolderCollection-
|
|
316
|
+
const { EmailFolderCollection } = await import("./EmailFolderCollection-DSnVCTIB.js").then((n) => n.n);
|
|
163
317
|
return await (await EmailFolderCollection.create(this.options)).get({ id: this.folderId });
|
|
164
318
|
}
|
|
165
319
|
/**
|
|
@@ -167,7 +321,7 @@ var Email = class extends Message {
|
|
|
167
321
|
*/
|
|
168
322
|
async getThreadEmails() {
|
|
169
323
|
if (!this.threadId) return [this];
|
|
170
|
-
const { EmailCollection } = await import("./EmailCollection-
|
|
324
|
+
const { EmailCollection } = await import("./EmailCollection-BGtIdMhg.js").then((n) => n.n);
|
|
171
325
|
return await (await EmailCollection.create(this.options)).getByThread(this.threadId);
|
|
172
326
|
}
|
|
173
327
|
/**
|
|
@@ -207,6 +361,14 @@ var Email = class extends Message {
|
|
|
207
361
|
createdAt: void 0,
|
|
208
362
|
updatedAt: void 0,
|
|
209
363
|
inReplyTo: this.messageId,
|
|
364
|
+
messageId: "",
|
|
365
|
+
providerMessageId: "",
|
|
366
|
+
htmlBody: "",
|
|
367
|
+
bccAddresses: "[]",
|
|
368
|
+
ccAddresses: "[]",
|
|
369
|
+
headers: "",
|
|
370
|
+
rawMessage: "",
|
|
371
|
+
hasAttachments: false,
|
|
210
372
|
toAddresses: JSON.stringify([{
|
|
211
373
|
address: this.fromAddress,
|
|
212
374
|
name: this.fromName
|
|
@@ -248,7 +410,12 @@ var Email = class extends Message {
|
|
|
248
410
|
fromName: "",
|
|
249
411
|
body: forwardBody,
|
|
250
412
|
textBody: forwardBody,
|
|
251
|
-
hasAttachments:
|
|
413
|
+
hasAttachments: false,
|
|
414
|
+
messageId: "",
|
|
415
|
+
providerMessageId: "",
|
|
416
|
+
htmlBody: "",
|
|
417
|
+
headers: "",
|
|
418
|
+
rawMessage: "",
|
|
252
419
|
inReplyToMessageId: "",
|
|
253
420
|
inReplyTo: "",
|
|
254
421
|
sendStatus: "draft",
|
|
@@ -266,7 +433,16 @@ var Email = class extends Message {
|
|
|
266
433
|
return `
|
|
267
434
|
|
|
268
435
|
On ${this.date ? this.date.toLocaleString() : "unknown date"}, ${this.fromName ? `${this.fromName} <${this.fromAddress}>` : this.fromAddress} wrote:
|
|
269
|
-
${
|
|
436
|
+
${this.plainBody().split("\n").map((line) => `> ${line}`).join("\n")}`;
|
|
437
|
+
}
|
|
438
|
+
/**
|
|
439
|
+
* Plain text of this email for quoting. HTML-only mail (no text alternative)
|
|
440
|
+
* is converted, because the HTML itself is never carried into a draft.
|
|
441
|
+
*/
|
|
442
|
+
plainBody() {
|
|
443
|
+
const text = this.textBody || this.body;
|
|
444
|
+
if (text) return text;
|
|
445
|
+
return htmlToText(this.htmlBody || "");
|
|
270
446
|
}
|
|
271
447
|
/**
|
|
272
448
|
* Build forwarded message body
|
|
@@ -275,7 +451,7 @@ ${(this.textBody || this.body || "").split("\n").map((line) => `> ${line}`).join
|
|
|
275
451
|
const dateStr = this.date ? this.date.toLocaleString() : "unknown date";
|
|
276
452
|
const from = this.fromName ? `${this.fromName} <${this.fromAddress}>` : this.fromAddress;
|
|
277
453
|
const toStr = this.getToAddresses().map((r) => r.name ? `${r.name} <${r.address}>` : r.address).join(", ");
|
|
278
|
-
const bodyText = this.
|
|
454
|
+
const bodyText = this.plainBody();
|
|
279
455
|
return [
|
|
280
456
|
"",
|
|
281
457
|
"",
|
|
@@ -357,4 +533,4 @@ Email = __decorateClass([smrt({
|
|
|
357
533
|
//#endregion
|
|
358
534
|
export { Email_exports as n, Email as t };
|
|
359
535
|
|
|
360
|
-
//# sourceMappingURL=Email-
|
|
536
|
+
//# sourceMappingURL=Email-YfrfXXmh.js.map
|