@octarq/plugin-mail 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jungley
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/api.ts ADDED
@@ -0,0 +1,302 @@
1
+ // Mail feature API surface — the slice of the JSON API owned by the mail plugin.
2
+ // Fully self-contained without relative host leaks.
3
+
4
+ export class ApiError extends Error {
5
+ status: number;
6
+ body?: any;
7
+ requestId?: string;
8
+ constructor(status: number, message: string, body?: any, requestId?: string) {
9
+ super(message);
10
+ this.status = status;
11
+ this.body = body;
12
+ this.requestId = requestId;
13
+ }
14
+ }
15
+
16
+ export function getAppLang(): string {
17
+ try {
18
+ const saved = localStorage.getItem("lang");
19
+ if (saved) return saved;
20
+ } catch {
21
+ /* ignore */
22
+ }
23
+ return typeof navigator !== "undefined" ? navigator.language || "en" : "en";
24
+ }
25
+
26
+ interface ErrorEnvelope {
27
+ message?: string;
28
+ error?: string;
29
+ detail?: string;
30
+ details?: Array<string | { location?: string; message?: string }>;
31
+ }
32
+
33
+ export async function req<T>(method: string, path: string, body?: unknown, lang?: string): Promise<T> {
34
+ const currentLang = lang || getAppLang();
35
+ const headers: Record<string, string> = {
36
+ "Accept-Language": currentLang,
37
+ };
38
+ if (body) {
39
+ headers["Content-Type"] = "application/json";
40
+ }
41
+ const res = await fetch(path, {
42
+ method,
43
+ headers,
44
+ body: body ? JSON.stringify(body) : undefined,
45
+ });
46
+ if (!res.ok) {
47
+ let msg = res.statusText;
48
+ let parsed: ErrorEnvelope | null = null;
49
+ try {
50
+ parsed = (await res.json()) as ErrorEnvelope;
51
+ if (parsed?.message) {
52
+ msg = parsed.message;
53
+ if (parsed.details && Array.isArray(parsed.details) && parsed.details.length > 0) {
54
+ const detailMsgs = parsed.details
55
+ .map((d) => {
56
+ if (typeof d === "string") return d;
57
+ if (d?.message) {
58
+ const loc = d.location ? `${d.location.replace(/^body\./, "")}: ` : "";
59
+ return `${loc}${d.message}`;
60
+ }
61
+ return "";
62
+ })
63
+ .filter(Boolean)
64
+ .join("; ");
65
+ if (detailMsgs) msg = `${msg} (${detailMsgs})`;
66
+ }
67
+ } else if (parsed?.error) {
68
+ msg = parsed.error;
69
+ } else if (parsed?.detail) {
70
+ msg = parsed.detail;
71
+ }
72
+ } catch {
73
+ // Non-JSON error body: fall through to statusText.
74
+ }
75
+ const requestId = res.headers.get("x-request-id") || undefined;
76
+ throw new ApiError(res.status, msg || `HTTP ${res.status}`, parsed, requestId);
77
+ }
78
+ if (res.status === 204) return undefined as unknown as T;
79
+ const contentType = res.headers.get("content-type");
80
+ if (contentType && contentType.includes("application/json")) {
81
+ return (await res.json()) as T;
82
+ }
83
+ return (await res.text()) as unknown as T;
84
+ }
85
+
86
+ export interface HostEntry {
87
+ host: string;
88
+ enabled: boolean;
89
+ }
90
+
91
+ export interface Domain {
92
+ id: number;
93
+ name: string;
94
+ providerAccountId?: number;
95
+ zoneId?: string;
96
+ note?: string;
97
+ forMail?: boolean;
98
+ forLink?: boolean;
99
+ linkHosts?: HostEntry[] | null;
100
+ mailHosts?: HostEntry[] | null;
101
+ createdAt?: string;
102
+ [key: string]: any;
103
+ }
104
+
105
+ export function effectiveMailHosts(d: Domain | { hosts?: string[]; mailHosts?: HostEntry[]; name?: string }): string[] {
106
+ if ("mailHosts" in d && Array.isArray(d.mailHosts)) {
107
+ return d.mailHosts.filter((h) => h.enabled).map((h) => h.host);
108
+ }
109
+ if ("hosts" in d && Array.isArray(d.hosts)) {
110
+ return d.hosts;
111
+ }
112
+ return [];
113
+ }
114
+
115
+ export interface SMTPSender {
116
+ id: number;
117
+ name: string;
118
+ host: string;
119
+ port: number;
120
+ user: string;
121
+ fromEmail: string;
122
+ passSet: boolean;
123
+ createdAt: string;
124
+ }
125
+
126
+ export interface SMTPSenderInput {
127
+ name: string;
128
+ host: string;
129
+ port: number;
130
+ user: string;
131
+ fromEmail: string;
132
+ pass?: string;
133
+ }
134
+
135
+ export interface MailSettingsData {
136
+ reservedMailboxes?: string;
137
+ catchAll?: boolean;
138
+ autoWrapLinks?: boolean;
139
+ inboundTokenSet?: boolean;
140
+ orgSlug?: string;
141
+ [key: string]: unknown;
142
+ }
143
+
144
+ export interface Mailbox {
145
+ id: number;
146
+ address: string;
147
+ note: string;
148
+ enabled: boolean;
149
+ unread: number;
150
+ }
151
+
152
+ export interface Attachment {
153
+ filename: string;
154
+ contentType: string;
155
+ size: number;
156
+ inline?: boolean;
157
+ contentId?: string;
158
+ truncated?: boolean;
159
+ }
160
+
161
+ export interface Email {
162
+ id: number;
163
+ mailboxId: number;
164
+ from: string;
165
+ to: string;
166
+ subject: string;
167
+ text: string;
168
+ html: string;
169
+ folder?: string;
170
+ unsubscribeUrl?: string;
171
+ read: boolean;
172
+ note: string;
173
+ attachments: string; // JSON string of Attachment[]
174
+ authSpf: string; // pass|fail|softfail|neutral|none|""
175
+ authDkim: string; // pass|fail|none|""
176
+ authDmarc: string; // pass|fail|none|""
177
+ receivedAt: string;
178
+ category?: "bill" | "otp" | "marketing" | "important" | "general" | string;
179
+ summary?: string;
180
+ importance?: number;
181
+ otp?: string;
182
+ }
183
+
184
+ export interface MailContact {
185
+ id: number;
186
+ address: string;
187
+ name: string;
188
+ interactionCount: number;
189
+ lastSeenAt: string;
190
+ createdAt?: string;
191
+ updatedAt?: string;
192
+ }
193
+
194
+ export interface MailSuppression {
195
+ id: number;
196
+ address: string;
197
+ reason: string;
198
+ source: string;
199
+ count: number;
200
+ createdAt: string;
201
+ updatedAt: string;
202
+ }
203
+
204
+ export const mailApi = {
205
+ // Mailbox CRUD
206
+ mailboxes: () => req<Mailbox[]>("GET", "/api/mailboxes"),
207
+ createMailbox: (m: Partial<Mailbox>) => req<Mailbox>("POST", "/api/mailboxes", m),
208
+ updateMailbox: (id: number, m: Partial<Mailbox>) => req<Mailbox>("PUT", `/api/mailboxes/${id}`, m),
209
+ deleteMailbox: (id: number) => req("DELETE", `/api/mailboxes/${id}`),
210
+
211
+ // Email read & mutation
212
+ emails: (mailboxId?: number, params?: { q?: string; folder?: string; limit?: number; offset?: number }) => {
213
+ const sp = new URLSearchParams();
214
+ if (mailboxId) sp.set("mailbox", mailboxId.toString());
215
+ if (params?.folder) sp.set("folder", params.folder);
216
+ if (params?.q) sp.set("q", params.q);
217
+ if (params?.limit) sp.set("limit", params.limit.toString());
218
+ if (params?.offset) sp.set("offset", params.offset.toString());
219
+ const qs = sp.toString();
220
+ return req<Email[]>("GET", `/api/emails${qs ? "?" + qs : ""}`);
221
+ },
222
+ email: (id: number) => req<Email>("GET", `/api/emails/${id}`),
223
+ updateEmail: (id: number, e: { read?: boolean; note?: string }) =>
224
+ req<Email>("PUT", `/api/emails/${id}`, e),
225
+ updateEmailFolder: (id: number, folder: string) =>
226
+ req<Email>("PUT", `/api/mail/emails/${id}/folder`, { folder }),
227
+ deleteEmail: (id: number) => req("DELETE", `/api/emails/${id}`),
228
+ readAllEmails: (mailbox?: number) =>
229
+ req<{ ok: boolean; updated: number }>(
230
+ "POST",
231
+ `/api/emails/read-all${mailbox ? `?mailbox=${mailbox}` : ""}`,
232
+ ),
233
+ rawEmailUrl: (id: number) => `/api/emails/${id}/raw`,
234
+ sendEmail: (m: {
235
+ from?: string;
236
+ to: string[];
237
+ subject: string;
238
+ text?: string;
239
+ html?: string;
240
+ smtpSenderId?: number;
241
+ smtpSenderSource?: "local" | "integration";
242
+ trackLinks?: boolean;
243
+ }) => req("POST", "/api/emails/send", m),
244
+
245
+ // Contacts
246
+ contacts: (params?: { query?: string; q?: string; limit?: number; offset?: number }) => {
247
+ const sp = new URLSearchParams();
248
+ const q = params?.query ?? params?.q;
249
+ if (q) sp.set("q", q);
250
+ if (params?.limit) sp.set("limit", params.limit.toString());
251
+ if (params?.offset) sp.set("offset", params.offset.toString());
252
+ const qs = sp.toString();
253
+ return req<MailContact[]>("GET", `/api/mail/contacts${qs ? "?" + qs : ""}`);
254
+ },
255
+
256
+ // Drafts
257
+ saveDraft: (d: { id?: number; mailboxId?: number; to: string; subject: string; text: string; html?: string }) =>
258
+ req<Email>("POST", "/api/mail/drafts", d),
259
+ deleteDraft: (id: number) => req<{ ok: boolean }>("DELETE", `/api/mail/drafts/${id}`),
260
+
261
+ // Suppressions
262
+ suppressions: () => req<MailSuppression[]>("GET", "/api/mail/suppressions"),
263
+ createSuppression: (address: string) => req<MailSuppression>("POST", "/api/mail/suppressions", { address }),
264
+ deleteSuppression: (id: number) => req("DELETE", `/api/mail/suppressions/${id}`),
265
+
266
+ // Domains (used for mailbox creation host selection)
267
+ domains: (params?: { q?: string; limit?: number; offset?: number }) => {
268
+ const sp = new URLSearchParams();
269
+ if (params?.q) sp.set("q", params.q);
270
+ if (params?.limit) sp.set("limit", params.limit.toString());
271
+ if (params?.offset) sp.set("offset", params.offset.toString());
272
+ const qs = sp.toString();
273
+ return req<Domain[]>("GET", `/api/domains${qs ? "?" + qs : ""}`);
274
+ },
275
+
276
+ // SMTP Senders
277
+ smtpSenders: () => req<SMTPSender[]>("GET", "/api/smtp-senders"),
278
+ createSMTPSender: (s: SMTPSenderInput) => req<SMTPSender>("POST", "/api/smtp-senders", s),
279
+ updateSMTPSender: (id: number, s: Partial<SMTPSenderInput>) =>
280
+ req<SMTPSender>("PUT", `/api/smtp-senders/${id}`, s),
281
+ deleteSMTPSender: (id: number) => req<void>("DELETE", `/api/smtp-senders/${id}`),
282
+ testSMTPSender: (id: number) => req<{ ok: boolean }>("POST", `/api/smtp-senders/${id}/test`),
283
+
284
+ // Settings & Inbound Token
285
+ settings: () => req<MailSettingsData>("GET", "/api/settings"),
286
+ updateSettings: (s: Partial<MailSettingsData> & { inboundToken?: string }) =>
287
+ req<any>("PUT", "/api/settings", s),
288
+ inboundToken: () => req<{ inboundToken: string }>("GET", "/api/settings/inbound-token"),
289
+
290
+ // AI Assist
291
+ aiAssistStatus: () => req<{ configured: boolean; provider: string }>("GET", "/api/ai/assist/status"),
292
+ aiSummarizeEmail: (id: number) =>
293
+ req<{ summary: string; category?: string; importance?: number; otp?: string }>(
294
+ "POST",
295
+ `/api/ai/assist/summarize-email/${id}`,
296
+ ),
297
+
298
+ // Overview
299
+ overview: (includeBot = false) => req<any>("GET", `/api/overview?include_bot=${includeBot}`),
300
+ };
301
+
302
+ export { mailApi as api };