@tenonhq/dovetail-gmail 0.0.7

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/README.md ADDED
@@ -0,0 +1,67 @@
1
+ # @tenonhq/dovetail-gmail
2
+
3
+ Gmail API client for Dovetail. Provides inbox operations and LLM-optimized formatting for the CTO morning digest (`context/email-digest.md`).
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm i -D @tenonhq/dovetail-gmail @tenonhq/dovetail-google-auth
9
+ ```
10
+
11
+ ## Setup
12
+
13
+ Gmail auth is handled by [`@tenonhq/dovetail-google-auth`](../google-auth). Follow the setup in that package's README to obtain `GOOGLE_CLIENT_ID`, `GOOGLE_CLIENT_SECRET`, and `GOOGLE_REFRESH_TOKEN`. The OAuth consent screen must enable the **Gmail API** with the `gmail.modify` scope.
14
+
15
+ ```bash
16
+ # .env
17
+ GOOGLE_CLIENT_ID=...
18
+ GOOGLE_CLIENT_SECRET=...
19
+ GOOGLE_REFRESH_TOKEN=...
20
+ ```
21
+
22
+ ## Usage
23
+
24
+ ```typescript
25
+ import { createGoogleAuth, configFromEnv } from "@tenonhq/dovetail-google-auth";
26
+ import {
27
+ createGmailClient,
28
+ getUnread,
29
+ getStarred,
30
+ getVipEmails,
31
+ getActionRequired,
32
+ formatDigest,
33
+ } from "@tenonhq/dovetail-gmail";
34
+
35
+ var { auth } = createGoogleAuth({ config: configFromEnv() });
36
+ var client = createGmailClient({ auth: auth });
37
+
38
+ var unread = await getUnread({ client: client, maxResults: 25 });
39
+ var starred = await getStarred({ client: client });
40
+ var vip = await getVipEmails({
41
+ client: client,
42
+ config: { senders: ["daniel@tenonhq.com"] },
43
+ });
44
+ var action = await getActionRequired({ client: client });
45
+
46
+ var digest = formatDigest({
47
+ unread: unread,
48
+ starred: starred,
49
+ vip: vip,
50
+ actionRequired: action,
51
+ });
52
+ ```
53
+
54
+ ## API Surface
55
+
56
+ - **Client:** `createGmailClient`
57
+ - **Read:** `getUnread`, `getStarred`, `searchEmails`, `getThread`, `getVipEmails`, `getActionRequired`
58
+ - **Write:** `archiveEmail`, `labelEmail`, `markAsRead`, `markAsUnread`, `moveToTrash`, `starEmail`, `unstarEmail`
59
+ - **Formatting:** `formatDigest`, `formatThread`, `formatEmailSummary`
60
+ - **Parsing:** `parseGmailIdentifier` — extracts message/thread IDs from Gmail URLs
61
+
62
+ See `src/types.ts` for the full type surface including `VipConfig` and `ActionRequiredConfig`.
63
+
64
+ ## Related
65
+
66
+ - [`@tenonhq/dovetail-google-auth`](../google-auth) — shared OAuth2 layer
67
+ - [`@tenonhq/dovetail-google-calendar`](../google-calendar) — sibling Google integration
@@ -0,0 +1,107 @@
1
+ import { OAuth2Client } from "google-auth-library";
2
+ import { GmailThread, GmailSearchResult, GmailClient, GetUnreadParams, GetStarredParams, SearchEmailsParams, GetThreadParams, GetVipEmailsParams, GetActionRequiredParams, ArchiveEmailParams, LabelEmailParams, MarkAsReadParams, MarkAsUnreadParams, MoveToTrashParams, StarEmailParams, UnstarEmailParams } from "./types";
3
+ /**
4
+ * @description Creates a Gmail API client from an authenticated OAuth2 client.
5
+ * @param params - Object with the OAuth2Client auth instance.
6
+ * @returns The Gmail API client.
7
+ */
8
+ export declare function createGmailClient(params: {
9
+ auth: OAuth2Client;
10
+ }): GmailClient;
11
+ /**
12
+ * @description Fetches unread emails from the inbox.
13
+ * @param params - Object with client and optional maxResults.
14
+ * @returns Search result with unread emails.
15
+ */
16
+ export declare function getUnread(params: {
17
+ client: GmailClient;
18
+ } & GetUnreadParams): Promise<GmailSearchResult>;
19
+ /**
20
+ * @description Fetches starred emails.
21
+ * @param params - Object with client and optional maxResults.
22
+ * @returns Search result with starred emails.
23
+ */
24
+ export declare function getStarred(params: {
25
+ client: GmailClient;
26
+ } & GetStarredParams): Promise<GmailSearchResult>;
27
+ /**
28
+ * @description Searches emails using Gmail query syntax.
29
+ * @param params - Object with client, query string, optional maxResults and pageToken.
30
+ * @returns Search result with matching emails.
31
+ */
32
+ export declare function searchEmails(params: {
33
+ client: GmailClient;
34
+ } & SearchEmailsParams): Promise<GmailSearchResult>;
35
+ /**
36
+ * @description Fetches a full email thread with all messages.
37
+ * @param params - Object with client and threadId.
38
+ * @returns The email thread with all messages.
39
+ */
40
+ export declare function getThread(params: {
41
+ client: GmailClient;
42
+ } & GetThreadParams): Promise<GmailThread>;
43
+ /**
44
+ * @description Fetches unread emails from VIP senders.
45
+ * @param params - Object with client, senders list, and optional maxResults.
46
+ * @returns Search result with VIP emails.
47
+ */
48
+ export declare function getVipEmails(params: {
49
+ client: GmailClient;
50
+ } & GetVipEmailsParams): Promise<GmailSearchResult>;
51
+ /**
52
+ * @description Fetches action-required emails based on subject patterns and labels.
53
+ * @param params - Object with client, optional labels, subjectPatterns, and maxResults.
54
+ * @returns Search result with action-required emails.
55
+ */
56
+ export declare function getActionRequired(params: {
57
+ client: GmailClient;
58
+ } & GetActionRequiredParams): Promise<GmailSearchResult>;
59
+ /**
60
+ * @description Archives an email by removing the INBOX label.
61
+ * @param params - Object with client and messageId.
62
+ */
63
+ export declare function archiveEmail(params: {
64
+ client: GmailClient;
65
+ } & ArchiveEmailParams): Promise<void>;
66
+ /**
67
+ * @description Adds or removes labels from an email.
68
+ * @param params - Object with client, messageId, and labels to add/remove.
69
+ */
70
+ export declare function labelEmail(params: {
71
+ client: GmailClient;
72
+ } & LabelEmailParams): Promise<void>;
73
+ /**
74
+ * @description Marks an email as read by removing the UNREAD label.
75
+ * @param params - Object with client and messageId.
76
+ */
77
+ export declare function markAsRead(params: {
78
+ client: GmailClient;
79
+ } & MarkAsReadParams): Promise<void>;
80
+ /**
81
+ * @description Marks an email as unread by adding the UNREAD label.
82
+ * @param params - Object with client and messageId.
83
+ */
84
+ export declare function markAsUnread(params: {
85
+ client: GmailClient;
86
+ } & MarkAsUnreadParams): Promise<void>;
87
+ /**
88
+ * @description Moves an email to trash.
89
+ * @param params - Object with client and messageId.
90
+ */
91
+ export declare function moveToTrash(params: {
92
+ client: GmailClient;
93
+ } & MoveToTrashParams): Promise<void>;
94
+ /**
95
+ * @description Stars an email by adding the STARRED label.
96
+ * @param params - Object with client and messageId.
97
+ */
98
+ export declare function starEmail(params: {
99
+ client: GmailClient;
100
+ } & StarEmailParams): Promise<void>;
101
+ /**
102
+ * @description Unstars an email by removing the STARRED label.
103
+ * @param params - Object with client and messageId.
104
+ */
105
+ export declare function unstarEmail(params: {
106
+ client: GmailClient;
107
+ } & UnstarEmailParams): Promise<void>;
package/dist/client.js ADDED
@@ -0,0 +1,418 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.createGmailClient = createGmailClient;
7
+ exports.getUnread = getUnread;
8
+ exports.getStarred = getStarred;
9
+ exports.searchEmails = searchEmails;
10
+ exports.getThread = getThread;
11
+ exports.getVipEmails = getVipEmails;
12
+ exports.getActionRequired = getActionRequired;
13
+ exports.archiveEmail = archiveEmail;
14
+ exports.labelEmail = labelEmail;
15
+ exports.markAsRead = markAsRead;
16
+ exports.markAsUnread = markAsUnread;
17
+ exports.moveToTrash = moveToTrash;
18
+ exports.starEmail = starEmail;
19
+ exports.unstarEmail = unstarEmail;
20
+ const gmail_1 = require("@googleapis/gmail");
21
+ const dovetail_google_auth_1 = require("@tenonhq/dovetail-google-auth");
22
+ const sanitize_html_1 = __importDefault(require("sanitize-html"));
23
+ var USER_ID = "me";
24
+ // --- Client Factory ---
25
+ /**
26
+ * @description Creates a Gmail API client from an authenticated OAuth2 client.
27
+ * @param params - Object with the OAuth2Client auth instance.
28
+ * @returns The Gmail API client.
29
+ */
30
+ function createGmailClient(params) {
31
+ return (0, gmail_1.gmail)({ version: "v1", auth: params.auth });
32
+ }
33
+ // --- Read Operations ---
34
+ /**
35
+ * @description Fetches unread emails from the inbox.
36
+ * @param params - Object with client and optional maxResults.
37
+ * @returns Search result with unread emails.
38
+ */
39
+ async function getUnread(params) {
40
+ return searchEmails({
41
+ client: params.client,
42
+ query: "is:unread in:inbox",
43
+ maxResults: params.maxResults || 20,
44
+ pageToken: params.pageToken,
45
+ });
46
+ }
47
+ /**
48
+ * @description Fetches starred emails.
49
+ * @param params - Object with client and optional maxResults.
50
+ * @returns Search result with starred emails.
51
+ */
52
+ async function getStarred(params) {
53
+ return searchEmails({
54
+ client: params.client,
55
+ query: "is:starred",
56
+ maxResults: params.maxResults || 10,
57
+ pageToken: params.pageToken,
58
+ });
59
+ }
60
+ /**
61
+ * @description Searches emails using Gmail query syntax.
62
+ * @param params - Object with client, query string, optional maxResults and pageToken.
63
+ * @returns Search result with matching emails.
64
+ */
65
+ async function searchEmails(params) {
66
+ try {
67
+ var response = await params.client.users.messages.list({
68
+ userId: USER_ID,
69
+ q: params.query,
70
+ maxResults: params.maxResults || 20,
71
+ pageToken: params.pageToken,
72
+ });
73
+ var messages = response.data.messages || [];
74
+ var emails = [];
75
+ for (var i = 0; i < messages.length; i++) {
76
+ var msgResponse = await params.client.users.messages.get({
77
+ userId: USER_ID,
78
+ id: messages[i].id,
79
+ format: "full",
80
+ });
81
+ emails.push(parseMessage(msgResponse.data));
82
+ }
83
+ return {
84
+ emails: emails,
85
+ total: response.data.resultSizeEstimate || emails.length,
86
+ nextPageToken: response.data.nextPageToken || undefined,
87
+ };
88
+ }
89
+ catch (error) {
90
+ return (0, dovetail_google_auth_1.handleAuthError)(error, "searching emails with query '" + params.query + "'");
91
+ }
92
+ }
93
+ /**
94
+ * @description Fetches a full email thread with all messages.
95
+ * @param params - Object with client and threadId.
96
+ * @returns The email thread with all messages.
97
+ */
98
+ async function getThread(params) {
99
+ try {
100
+ var response = await params.client.users.threads.get({
101
+ userId: USER_ID,
102
+ id: params.threadId,
103
+ format: "full",
104
+ });
105
+ var threadData = response.data;
106
+ var threadMessages = threadData.messages || [];
107
+ var emails = [];
108
+ var participants = [];
109
+ var seen = {};
110
+ for (var i = 0; i < threadMessages.length; i++) {
111
+ var email = parseMessage(threadMessages[i]);
112
+ emails.push(email);
113
+ if (email.from && !seen[email.from]) {
114
+ seen[email.from] = true;
115
+ participants.push(email.from);
116
+ }
117
+ }
118
+ var subject = emails.length > 0 ? emails[0].subject : "(No subject)";
119
+ var snippet = threadData.snippet || "";
120
+ return {
121
+ id: threadData.id || params.threadId,
122
+ messages: emails,
123
+ subject: subject,
124
+ participants: participants,
125
+ messageCount: emails.length,
126
+ snippet: snippet,
127
+ };
128
+ }
129
+ catch (error) {
130
+ return (0, dovetail_google_auth_1.handleAuthError)(error, "fetching thread '" + params.threadId + "'");
131
+ }
132
+ }
133
+ /**
134
+ * @description Fetches unread emails from VIP senders.
135
+ * @param params - Object with client, senders list, and optional maxResults.
136
+ * @returns Search result with VIP emails.
137
+ */
138
+ async function getVipEmails(params) {
139
+ if (!params.senders || params.senders.length === 0) {
140
+ return { emails: [], total: 0 };
141
+ }
142
+ var fromClauses = [];
143
+ for (var i = 0; i < params.senders.length; i++) {
144
+ fromClauses.push("from:" + params.senders[i]);
145
+ }
146
+ var query = "is:unread (" + fromClauses.join(" OR ") + ")";
147
+ return searchEmails({
148
+ client: params.client,
149
+ query: query,
150
+ maxResults: params.maxResults || 10,
151
+ });
152
+ }
153
+ /**
154
+ * @description Fetches action-required emails based on subject patterns and labels.
155
+ * @param params - Object with client, optional labels, subjectPatterns, and maxResults.
156
+ * @returns Search result with action-required emails.
157
+ */
158
+ async function getActionRequired(params) {
159
+ var parts = [];
160
+ // Default subject patterns if none provided
161
+ var patterns = params.subjectPatterns || ["action required", "urgent", "asap", "time sensitive"];
162
+ var subjectClauses = [];
163
+ for (var i = 0; i < patterns.length; i++) {
164
+ subjectClauses.push("subject:(" + patterns[i] + ")");
165
+ }
166
+ if (subjectClauses.length > 0) {
167
+ parts.push("(" + subjectClauses.join(" OR ") + ")");
168
+ }
169
+ // Label filters
170
+ if (params.labels && params.labels.length > 0) {
171
+ var labelClauses = [];
172
+ for (var l = 0; l < params.labels.length; l++) {
173
+ labelClauses.push("label:" + params.labels[l]);
174
+ }
175
+ parts.push("(" + labelClauses.join(" OR ") + ")");
176
+ }
177
+ var query = "is:unread " + parts.join(" ");
178
+ return searchEmails({
179
+ client: params.client,
180
+ query: query,
181
+ maxResults: params.maxResults || 10,
182
+ });
183
+ }
184
+ // --- Write Operations ---
185
+ /**
186
+ * @description Archives an email by removing the INBOX label.
187
+ * @param params - Object with client and messageId.
188
+ */
189
+ async function archiveEmail(params) {
190
+ try {
191
+ await params.client.users.messages.modify({
192
+ userId: USER_ID,
193
+ id: params.messageId,
194
+ requestBody: {
195
+ removeLabelIds: ["INBOX"],
196
+ },
197
+ });
198
+ }
199
+ catch (error) {
200
+ return (0, dovetail_google_auth_1.handleAuthError)(error, "archiving email '" + params.messageId + "'");
201
+ }
202
+ }
203
+ /**
204
+ * @description Adds or removes labels from an email.
205
+ * @param params - Object with client, messageId, and labels to add/remove.
206
+ */
207
+ async function labelEmail(params) {
208
+ try {
209
+ var body = {};
210
+ if (params.addLabels && params.addLabels.length > 0) {
211
+ body.addLabelIds = params.addLabels;
212
+ }
213
+ if (params.removeLabels && params.removeLabels.length > 0) {
214
+ body.removeLabelIds = params.removeLabels;
215
+ }
216
+ await params.client.users.messages.modify({
217
+ userId: USER_ID,
218
+ id: params.messageId,
219
+ requestBody: body,
220
+ });
221
+ }
222
+ catch (error) {
223
+ return (0, dovetail_google_auth_1.handleAuthError)(error, "labeling email '" + params.messageId + "'");
224
+ }
225
+ }
226
+ /**
227
+ * @description Marks an email as read by removing the UNREAD label.
228
+ * @param params - Object with client and messageId.
229
+ */
230
+ async function markAsRead(params) {
231
+ try {
232
+ await params.client.users.messages.modify({
233
+ userId: USER_ID,
234
+ id: params.messageId,
235
+ requestBody: {
236
+ removeLabelIds: ["UNREAD"],
237
+ },
238
+ });
239
+ }
240
+ catch (error) {
241
+ return (0, dovetail_google_auth_1.handleAuthError)(error, "marking email '" + params.messageId + "' as read");
242
+ }
243
+ }
244
+ /**
245
+ * @description Marks an email as unread by adding the UNREAD label.
246
+ * @param params - Object with client and messageId.
247
+ */
248
+ async function markAsUnread(params) {
249
+ try {
250
+ await params.client.users.messages.modify({
251
+ userId: USER_ID,
252
+ id: params.messageId,
253
+ requestBody: {
254
+ addLabelIds: ["UNREAD"],
255
+ },
256
+ });
257
+ }
258
+ catch (error) {
259
+ return (0, dovetail_google_auth_1.handleAuthError)(error, "marking email '" + params.messageId + "' as unread");
260
+ }
261
+ }
262
+ /**
263
+ * @description Moves an email to trash.
264
+ * @param params - Object with client and messageId.
265
+ */
266
+ async function moveToTrash(params) {
267
+ try {
268
+ await params.client.users.messages.trash({
269
+ userId: USER_ID,
270
+ id: params.messageId,
271
+ });
272
+ }
273
+ catch (error) {
274
+ return (0, dovetail_google_auth_1.handleAuthError)(error, "trashing email '" + params.messageId + "'");
275
+ }
276
+ }
277
+ /**
278
+ * @description Stars an email by adding the STARRED label.
279
+ * @param params - Object with client and messageId.
280
+ */
281
+ async function starEmail(params) {
282
+ try {
283
+ await params.client.users.messages.modify({
284
+ userId: USER_ID,
285
+ id: params.messageId,
286
+ requestBody: {
287
+ addLabelIds: ["STARRED"],
288
+ },
289
+ });
290
+ }
291
+ catch (error) {
292
+ return (0, dovetail_google_auth_1.handleAuthError)(error, "starring email '" + params.messageId + "'");
293
+ }
294
+ }
295
+ /**
296
+ * @description Unstars an email by removing the STARRED label.
297
+ * @param params - Object with client and messageId.
298
+ */
299
+ async function unstarEmail(params) {
300
+ try {
301
+ await params.client.users.messages.modify({
302
+ userId: USER_ID,
303
+ id: params.messageId,
304
+ requestBody: {
305
+ removeLabelIds: ["STARRED"],
306
+ },
307
+ });
308
+ }
309
+ catch (error) {
310
+ return (0, dovetail_google_auth_1.handleAuthError)(error, "unstarring email '" + params.messageId + "'");
311
+ }
312
+ }
313
+ // --- Internal Helpers ---
314
+ /**
315
+ * Parses a Gmail API message into a GmailEmail object.
316
+ * Handles header extraction, base64url body decoding, and multipart MIME.
317
+ */
318
+ function parseMessage(message) {
319
+ var headers = message.payload && message.payload.headers
320
+ ? message.payload.headers
321
+ : [];
322
+ var subject = getHeader(headers, "Subject") || "(No subject)";
323
+ var from = getHeader(headers, "From") || "Unknown";
324
+ var to = getHeader(headers, "To") || "";
325
+ var date = getHeader(headers, "Date") || "";
326
+ var labels = message.labelIds || [];
327
+ var isUnread = labels.indexOf("UNREAD") !== -1;
328
+ var isStarred = labels.indexOf("STARRED") !== -1;
329
+ var body = extractBody(message.payload || {});
330
+ return {
331
+ id: message.id || "",
332
+ threadId: message.threadId || "",
333
+ subject: subject,
334
+ from: from,
335
+ to: to,
336
+ date: date,
337
+ snippet: message.snippet || "",
338
+ labels: labels,
339
+ isUnread: isUnread,
340
+ isStarred: isStarred,
341
+ body: body,
342
+ };
343
+ }
344
+ function getHeader(headers, name) {
345
+ for (var i = 0; i < headers.length; i++) {
346
+ if (headers[i].name && headers[i].name.toLowerCase() === name.toLowerCase()) {
347
+ return headers[i].value || "";
348
+ }
349
+ }
350
+ return "";
351
+ }
352
+ /**
353
+ * Extracts the email body from a Gmail message payload.
354
+ * Handles multipart MIME, preferring text/plain over text/html.
355
+ */
356
+ function extractBody(payload) {
357
+ // Direct body on payload
358
+ if (payload.body && payload.body.data) {
359
+ return decodeBase64Url(payload.body.data);
360
+ }
361
+ // Multipart — look for text/plain first, then text/html
362
+ if (payload.parts && Array.isArray(payload.parts)) {
363
+ var plainText = "";
364
+ var htmlText = "";
365
+ for (var i = 0; i < payload.parts.length; i++) {
366
+ var part = payload.parts[i];
367
+ var mimeType = part.mimeType || "";
368
+ if (mimeType === "text/plain" && part.body && part.body.data) {
369
+ plainText = decodeBase64Url(part.body.data);
370
+ }
371
+ else if (mimeType === "text/html" && part.body && part.body.data) {
372
+ htmlText = decodeBase64Url(part.body.data);
373
+ }
374
+ else if (mimeType.indexOf("multipart") === 0 && part.parts) {
375
+ // Nested multipart — recurse
376
+ var nested = extractBody(part);
377
+ if (nested) {
378
+ if (!plainText) {
379
+ plainText = nested;
380
+ }
381
+ }
382
+ }
383
+ }
384
+ // Prefer plain text
385
+ if (plainText) {
386
+ return plainText;
387
+ }
388
+ if (htmlText) {
389
+ return stripHtml(htmlText);
390
+ }
391
+ }
392
+ return "";
393
+ }
394
+ function decodeBase64Url(data) {
395
+ try {
396
+ // Replace URL-safe chars with standard base64
397
+ var base64 = data.replace(/-/g, "+").replace(/_/g, "/");
398
+ return Buffer.from(base64, "base64").toString("utf-8");
399
+ }
400
+ catch (e) {
401
+ return "";
402
+ }
403
+ }
404
+ function stripHtml(html) {
405
+ // Basic HTML stripping — remove tags, decode common entities
406
+ return (0, sanitize_html_1.default)(html
407
+ .replace(/<br\s*\/?>/gi, "\n")
408
+ .replace(/<\/p>/gi, "\n\n")
409
+ .replace(/<\/div>/gi, "\n"), { allowedTags: [], allowedAttributes: {} })
410
+ .replace(/&amp;/g, "&")
411
+ .replace(/&lt;/g, "<")
412
+ .replace(/&gt;/g, ">")
413
+ .replace(/&quot;/g, "\"")
414
+ .replace(/&#39;/g, "'")
415
+ .replace(/&nbsp;/g, " ")
416
+ .replace(/\n{3,}/g, "\n\n")
417
+ .trim();
418
+ }
@@ -0,0 +1,19 @@
1
+ import { FormatDigestParams, FormatThreadParams, FormatEmailSummaryParams } from "./types";
2
+ /**
3
+ * @description Formats email data as a morning brief digest, optimized for LLM consumption.
4
+ * @param params - Object with email arrays (unread, starred, actionRequired, vip), date, and optional accountLabel.
5
+ * @returns Markdown-formatted string.
6
+ */
7
+ export declare function formatDigest(params: FormatDigestParams): string;
8
+ /**
9
+ * @description Formats a full email thread as readable markdown.
10
+ * @param params - Object with the thread.
11
+ * @returns Markdown-formatted string.
12
+ */
13
+ export declare function formatThread(params: FormatThreadParams): string;
14
+ /**
15
+ * @description Formats a single email as a brief one-line summary.
16
+ * @param params - Object with the email.
17
+ * @returns A concise summary string.
18
+ */
19
+ export declare function formatEmailSummary(params: FormatEmailSummaryParams): string;
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatDigest = formatDigest;
4
+ exports.formatThread = formatThread;
5
+ exports.formatEmailSummary = formatEmailSummary;
6
+ /**
7
+ * @description Formats email data as a morning brief digest, optimized for LLM consumption.
8
+ * @param params - Object with email arrays (unread, starred, actionRequired, vip), date, and optional accountLabel.
9
+ * @returns Markdown-formatted string.
10
+ */
11
+ function formatDigest(params) {
12
+ var lines = [];
13
+ var label = params.accountLabel || "Email";
14
+ lines.push("## " + label + " Digest — " + formatDateHeader(params.date));
15
+ lines.push("");
16
+ var hasContent = false;
17
+ // VIP emails — highest priority
18
+ if (params.vip.length > 0) {
19
+ hasContent = true;
20
+ lines.push("### VIP Unread (" + params.vip.length + ")");
21
+ lines.push("");
22
+ for (var v = 0; v < params.vip.length; v++) {
23
+ lines.push(formatEmailLine(params.vip[v]));
24
+ }
25
+ lines.push("");
26
+ }
27
+ // Action required
28
+ if (params.actionRequired.length > 0) {
29
+ hasContent = true;
30
+ lines.push("### Action Required (" + params.actionRequired.length + ")");
31
+ lines.push("");
32
+ for (var a = 0; a < params.actionRequired.length; a++) {
33
+ lines.push(formatEmailLine(params.actionRequired[a]));
34
+ }
35
+ lines.push("");
36
+ }
37
+ // Starred
38
+ if (params.starred.length > 0) {
39
+ hasContent = true;
40
+ lines.push("### Starred (" + params.starred.length + ")");
41
+ lines.push("");
42
+ for (var s = 0; s < params.starred.length; s++) {
43
+ lines.push(formatEmailLine(params.starred[s]));
44
+ }
45
+ lines.push("");
46
+ }
47
+ // Unread summary
48
+ if (params.unread.length > 0) {
49
+ hasContent = true;
50
+ lines.push("### Unread (" + params.unread.length + ")");
51
+ lines.push("");
52
+ // Show top 10 unread
53
+ var showCount = Math.min(params.unread.length, 10);
54
+ for (var u = 0; u < showCount; u++) {
55
+ lines.push(formatEmailLine(params.unread[u]));
56
+ }
57
+ if (params.unread.length > 10) {
58
+ lines.push("- _... and " + (params.unread.length - 10) + " more_");
59
+ }
60
+ lines.push("");
61
+ }
62
+ if (!hasContent) {
63
+ lines.push("_No flagged emails._");
64
+ lines.push("");
65
+ }
66
+ return lines.join("\n");
67
+ }
68
+ /**
69
+ * @description Formats a full email thread as readable markdown.
70
+ * @param params - Object with the thread.
71
+ * @returns Markdown-formatted string.
72
+ */
73
+ function formatThread(params) {
74
+ var thread = params.thread;
75
+ var lines = [];
76
+ lines.push("## Thread: " + thread.subject);
77
+ lines.push("");
78
+ lines.push("**" + thread.messageCount + " messages** — Participants: " + thread.participants.join(", "));
79
+ lines.push("");
80
+ // Messages, most recent first
81
+ var messages = thread.messages.slice().reverse();
82
+ for (var i = 0; i < messages.length; i++) {
83
+ var msg = messages[i];
84
+ lines.push("---");
85
+ lines.push("");
86
+ lines.push("**From:** " + msg.from);
87
+ lines.push("**Date:** " + formatEmailDate(msg.date));
88
+ if (msg.to) {
89
+ lines.push("**To:** " + msg.to);
90
+ }
91
+ lines.push("");
92
+ if (msg.body) {
93
+ // Truncate very long bodies
94
+ var body = msg.body;
95
+ if (body.length > 2000) {
96
+ body = body.substring(0, 2000) + "\n\n_[Truncated — " + (msg.body.length - 2000) + " more characters]_";
97
+ }
98
+ lines.push(body);
99
+ }
100
+ else {
101
+ lines.push(msg.snippet || "_No body content._");
102
+ }
103
+ lines.push("");
104
+ }
105
+ return lines.join("\n");
106
+ }
107
+ /**
108
+ * @description Formats a single email as a brief one-line summary.
109
+ * @param params - Object with the email.
110
+ * @returns A concise summary string.
111
+ */
112
+ function formatEmailSummary(params) {
113
+ var email = params.email;
114
+ var from = extractSenderName(email.from);
115
+ var date = formatEmailDate(email.date);
116
+ return "**" + from + "** — " + email.subject + " (" + date + ")";
117
+ }
118
+ // --- Helpers ---
119
+ function formatEmailLine(email) {
120
+ var from = extractSenderName(email.from);
121
+ var date = formatEmailDate(email.date);
122
+ return "- **" + from + "** — " + email.subject + " (" + date + ")";
123
+ }
124
+ function extractSenderName(from) {
125
+ if (!from) {
126
+ return "Unknown";
127
+ }
128
+ // "John Doe <john@example.com>" -> "John Doe"
129
+ var angleIndex = from.indexOf("<");
130
+ if (angleIndex > 0) {
131
+ return from.substring(0, angleIndex).trim().replace(/"/g, "");
132
+ }
133
+ return from;
134
+ }
135
+ function formatEmailDate(dateStr) {
136
+ if (!dateStr) {
137
+ return "Unknown";
138
+ }
139
+ try {
140
+ var date = new Date(dateStr);
141
+ if (isNaN(date.getTime())) {
142
+ return dateStr;
143
+ }
144
+ var months = [
145
+ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
146
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
147
+ ];
148
+ var hours = date.getHours();
149
+ var ampm = hours >= 12 ? "PM" : "AM";
150
+ var displayHours = hours % 12;
151
+ if (displayHours === 0) {
152
+ displayHours = 12;
153
+ }
154
+ var minutes = date.getMinutes();
155
+ var minStr = minutes < 10 ? "0" + minutes : String(minutes);
156
+ return (months[date.getMonth()] + " " + date.getDate() + ", " +
157
+ displayHours + ":" + minStr + " " + ampm);
158
+ }
159
+ catch (e) {
160
+ return dateStr;
161
+ }
162
+ }
163
+ function formatDateHeader(date) {
164
+ var months = [
165
+ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
166
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
167
+ ];
168
+ return (months[date.getMonth()] + " " +
169
+ date.getDate() + ", " +
170
+ date.getFullYear());
171
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @tenonhq/dovetail-gmail
3
+ *
4
+ * Gmail API client for Dovetail.
5
+ * Provides email management, inbox operations, and LLM-optimized formatting.
6
+ */
7
+ export { createGmailClient, getUnread, getStarred, searchEmails, getThread, getVipEmails, getActionRequired, archiveEmail, labelEmail, markAsRead, markAsUnread, moveToTrash, starEmail, unstarEmail, } from "./client";
8
+ export { formatDigest, formatThread, formatEmailSummary, } from "./formatter";
9
+ export { parseGmailIdentifier } from "./parser";
10
+ export type { GmailEmail, GmailThread, GmailLabel, GmailSearchResult, GmailClient, VipConfig, ActionRequiredConfig, ParsedGmailIdentifier, GetUnreadParams, GetStarredParams, SearchEmailsParams, GetThreadParams, GetVipEmailsParams, GetActionRequiredParams, ArchiveEmailParams, LabelEmailParams, MarkAsReadParams, MarkAsUnreadParams, MoveToTrashParams, StarEmailParams, UnstarEmailParams, FormatDigestParams, FormatThreadParams, FormatEmailSummaryParams, } from "./types";
package/dist/index.js ADDED
@@ -0,0 +1,33 @@
1
+ "use strict";
2
+ /**
3
+ * @tenonhq/dovetail-gmail
4
+ *
5
+ * Gmail API client for Dovetail.
6
+ * Provides email management, inbox operations, and LLM-optimized formatting.
7
+ */
8
+ Object.defineProperty(exports, "__esModule", { value: true });
9
+ exports.parseGmailIdentifier = exports.formatEmailSummary = exports.formatThread = exports.formatDigest = exports.unstarEmail = exports.starEmail = exports.moveToTrash = exports.markAsUnread = exports.markAsRead = exports.labelEmail = exports.archiveEmail = exports.getActionRequired = exports.getVipEmails = exports.getThread = exports.searchEmails = exports.getStarred = exports.getUnread = exports.createGmailClient = void 0;
10
+ // Client and API functions
11
+ var client_1 = require("./client");
12
+ Object.defineProperty(exports, "createGmailClient", { enumerable: true, get: function () { return client_1.createGmailClient; } });
13
+ Object.defineProperty(exports, "getUnread", { enumerable: true, get: function () { return client_1.getUnread; } });
14
+ Object.defineProperty(exports, "getStarred", { enumerable: true, get: function () { return client_1.getStarred; } });
15
+ Object.defineProperty(exports, "searchEmails", { enumerable: true, get: function () { return client_1.searchEmails; } });
16
+ Object.defineProperty(exports, "getThread", { enumerable: true, get: function () { return client_1.getThread; } });
17
+ Object.defineProperty(exports, "getVipEmails", { enumerable: true, get: function () { return client_1.getVipEmails; } });
18
+ Object.defineProperty(exports, "getActionRequired", { enumerable: true, get: function () { return client_1.getActionRequired; } });
19
+ Object.defineProperty(exports, "archiveEmail", { enumerable: true, get: function () { return client_1.archiveEmail; } });
20
+ Object.defineProperty(exports, "labelEmail", { enumerable: true, get: function () { return client_1.labelEmail; } });
21
+ Object.defineProperty(exports, "markAsRead", { enumerable: true, get: function () { return client_1.markAsRead; } });
22
+ Object.defineProperty(exports, "markAsUnread", { enumerable: true, get: function () { return client_1.markAsUnread; } });
23
+ Object.defineProperty(exports, "moveToTrash", { enumerable: true, get: function () { return client_1.moveToTrash; } });
24
+ Object.defineProperty(exports, "starEmail", { enumerable: true, get: function () { return client_1.starEmail; } });
25
+ Object.defineProperty(exports, "unstarEmail", { enumerable: true, get: function () { return client_1.unstarEmail; } });
26
+ // Formatting utilities
27
+ var formatter_1 = require("./formatter");
28
+ Object.defineProperty(exports, "formatDigest", { enumerable: true, get: function () { return formatter_1.formatDigest; } });
29
+ Object.defineProperty(exports, "formatThread", { enumerable: true, get: function () { return formatter_1.formatThread; } });
30
+ Object.defineProperty(exports, "formatEmailSummary", { enumerable: true, get: function () { return formatter_1.formatEmailSummary; } });
31
+ // URL/ID parsing
32
+ var parser_1 = require("./parser");
33
+ Object.defineProperty(exports, "parseGmailIdentifier", { enumerable: true, get: function () { return parser_1.parseGmailIdentifier; } });
@@ -0,0 +1,15 @@
1
+ import { ParsedGmailIdentifier } from "./types";
2
+ /**
3
+ * @description Parses a Gmail message or thread ID from a URL or raw ID.
4
+ * @param input - A Gmail URL or raw message/thread ID.
5
+ * @returns Parsed identifier with extracted messageId or threadId.
6
+ *
7
+ * @example
8
+ * parseGmailIdentifier("18f1234abcd5678")
9
+ * // => { messageId: "18f1234abcd5678", raw: "18f1234abcd5678" }
10
+ *
11
+ * @example
12
+ * parseGmailIdentifier("https://mail.google.com/mail/u/0/#inbox/18f1234abcd5678")
13
+ * // => { threadId: "18f1234abcd5678", raw: "https://mail.google.com/..." }
14
+ */
15
+ export declare function parseGmailIdentifier(input: string): ParsedGmailIdentifier;
package/dist/parser.js ADDED
@@ -0,0 +1,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseGmailIdentifier = parseGmailIdentifier;
4
+ /**
5
+ * @description Parses a Gmail message or thread ID from a URL or raw ID.
6
+ * @param input - A Gmail URL or raw message/thread ID.
7
+ * @returns Parsed identifier with extracted messageId or threadId.
8
+ *
9
+ * @example
10
+ * parseGmailIdentifier("18f1234abcd5678")
11
+ * // => { messageId: "18f1234abcd5678", raw: "18f1234abcd5678" }
12
+ *
13
+ * @example
14
+ * parseGmailIdentifier("https://mail.google.com/mail/u/0/#inbox/18f1234abcd5678")
15
+ * // => { threadId: "18f1234abcd5678", raw: "https://mail.google.com/..." }
16
+ */
17
+ function parseGmailIdentifier(input) {
18
+ if (!input || input.trim() === "") {
19
+ throw new Error("Gmail identifier is empty. Provide a message ID, thread ID, or Gmail URL.");
20
+ }
21
+ var cleaned = input.trim();
22
+ // Handle Gmail URLs
23
+ if (cleaned.indexOf("http://") === 0 || cleaned.indexOf("https://") === 0) {
24
+ var parsedUrl;
25
+ try {
26
+ parsedUrl = new URL(cleaned);
27
+ }
28
+ catch (_err) {
29
+ throw new Error("Could not parse Gmail identifier: '" + input +
30
+ "'. Expected a message ID, thread ID, or Gmail URL.");
31
+ }
32
+ if (parsedUrl.hostname === "mail.google.com") {
33
+ return parseGmailUrl(cleaned, input);
34
+ }
35
+ throw new Error("Could not parse Gmail identifier: '" + input +
36
+ "'. Expected a message ID, thread ID, or Gmail URL.");
37
+ }
38
+ // Raw ID — Gmail message/thread IDs are hex strings (16+ chars)
39
+ if (/^[a-fA-F0-9]+$/.test(cleaned)) {
40
+ return { messageId: cleaned, raw: input };
41
+ }
42
+ // Could be a non-hex ID format
43
+ if (/^[a-zA-Z0-9_-]+$/.test(cleaned)) {
44
+ return { messageId: cleaned, raw: input };
45
+ }
46
+ throw new Error("Could not parse Gmail identifier: '" + input +
47
+ "'. Expected a message ID, thread ID, or Gmail URL.");
48
+ }
49
+ function parseGmailUrl(url, raw) {
50
+ // Gmail URLs look like:
51
+ // https://mail.google.com/mail/u/0/#inbox/18f1234abcd5678
52
+ // https://mail.google.com/mail/u/0/#all/18f1234abcd5678
53
+ // https://mail.google.com/mail/u/0/#label/MyLabel/18f1234abcd5678
54
+ // Extract the fragment (after #)
55
+ var hashIndex = url.indexOf("#");
56
+ if (hashIndex === -1) {
57
+ throw new Error("Could not extract ID from Gmail URL: '" + url +
58
+ "'. Expected a URL with a # fragment containing the thread ID.");
59
+ }
60
+ var fragment = url.substring(hashIndex + 1);
61
+ var segments = fragment.split("/").filter(function (s) {
62
+ return s !== "";
63
+ });
64
+ // The thread ID is the last segment
65
+ if (segments.length > 0) {
66
+ var lastSegment = segments[segments.length - 1];
67
+ if (/^[a-fA-F0-9]+$/.test(lastSegment)) {
68
+ return { threadId: lastSegment, raw: raw };
69
+ }
70
+ }
71
+ throw new Error("Could not extract thread ID from Gmail URL: '" + url +
72
+ "'. Expected a URL ending with a hex thread ID.");
73
+ }
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Gmail API type definitions for Dovetail integration.
3
+ */
4
+ import { gmail_v1 } from "@googleapis/gmail";
5
+ export interface GmailEmail {
6
+ id: string;
7
+ threadId: string;
8
+ subject: string;
9
+ from: string;
10
+ to: string;
11
+ date: string;
12
+ snippet: string;
13
+ labels: string[];
14
+ isUnread: boolean;
15
+ isStarred: boolean;
16
+ body: string;
17
+ }
18
+ export interface GmailThread {
19
+ id: string;
20
+ messages: GmailEmail[];
21
+ subject: string;
22
+ participants: string[];
23
+ messageCount: number;
24
+ snippet: string;
25
+ }
26
+ export interface GmailLabel {
27
+ id: string;
28
+ name: string;
29
+ type: string;
30
+ messagesTotal: number;
31
+ messagesUnread: number;
32
+ }
33
+ export interface GmailSearchResult {
34
+ emails: GmailEmail[];
35
+ total: number;
36
+ nextPageToken?: string;
37
+ }
38
+ export interface VipConfig {
39
+ senders: string[];
40
+ }
41
+ export interface ActionRequiredConfig {
42
+ labels?: string[];
43
+ subjectPatterns?: string[];
44
+ }
45
+ export interface GetUnreadParams {
46
+ maxResults?: number;
47
+ pageToken?: string;
48
+ }
49
+ export interface GetStarredParams {
50
+ maxResults?: number;
51
+ pageToken?: string;
52
+ }
53
+ export interface SearchEmailsParams {
54
+ query: string;
55
+ maxResults?: number;
56
+ pageToken?: string;
57
+ }
58
+ export interface GetThreadParams {
59
+ threadId: string;
60
+ }
61
+ export interface GetVipEmailsParams {
62
+ senders: string[];
63
+ maxResults?: number;
64
+ }
65
+ export interface GetActionRequiredParams {
66
+ labels?: string[];
67
+ subjectPatterns?: string[];
68
+ maxResults?: number;
69
+ }
70
+ export interface ArchiveEmailParams {
71
+ messageId: string;
72
+ }
73
+ export interface LabelEmailParams {
74
+ messageId: string;
75
+ addLabels?: string[];
76
+ removeLabels?: string[];
77
+ }
78
+ export interface MarkAsReadParams {
79
+ messageId: string;
80
+ }
81
+ export interface MarkAsUnreadParams {
82
+ messageId: string;
83
+ }
84
+ export interface MoveToTrashParams {
85
+ messageId: string;
86
+ }
87
+ export interface StarEmailParams {
88
+ messageId: string;
89
+ }
90
+ export interface UnstarEmailParams {
91
+ messageId: string;
92
+ }
93
+ export interface FormatDigestParams {
94
+ unread: GmailEmail[];
95
+ starred: GmailEmail[];
96
+ actionRequired: GmailEmail[];
97
+ vip: GmailEmail[];
98
+ date: Date;
99
+ accountLabel?: string;
100
+ }
101
+ export interface FormatThreadParams {
102
+ thread: GmailThread;
103
+ }
104
+ export interface FormatEmailSummaryParams {
105
+ email: GmailEmail;
106
+ }
107
+ export interface ParsedGmailIdentifier {
108
+ messageId?: string;
109
+ threadId?: string;
110
+ raw: string;
111
+ }
112
+ export type GmailClient = gmail_v1.Gmail;
package/dist/types.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ /**
3
+ * Gmail API type definitions for Dovetail integration.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@tenonhq/dovetail-gmail",
3
+ "version": "0.0.7",
4
+ "description": "Gmail API client for Dovetail — email management, digest formatting, inbox operations",
5
+ "main": "./dist/index.js",
6
+ "scripts": {
7
+ "test": "jest",
8
+ "prepack": "tsc",
9
+ "version:bump": "node ./../../Scripts/bump-version.js ./package.json",
10
+ "postpublish": "npm run version:bump"
11
+ },
12
+ "author": "Multiple",
13
+ "license": "GPL-3.0",
14
+ "dependencies": {
15
+ "@googleapis/gmail": "^5.0.0",
16
+ "sanitize-html": "^2.17.2"
17
+ },
18
+ "peerDependencies": {
19
+ "@tenonhq/dovetail-google-auth": "^0.0.9"
20
+ },
21
+ "devDependencies": {
22
+ "@tenonhq/dovetail-google-auth": "^0.0.9",
23
+ "@types/jest": "^29.5.5",
24
+ "@types/node": ">=20.8.4",
25
+ "@types/sanitize-html": "^2.16.1",
26
+ "jest": "^29.7.0",
27
+ "ts-jest": "^29.1.1",
28
+ "typescript": "^5.2.2"
29
+ },
30
+ "files": [
31
+ "dist"
32
+ ],
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/tenonhq/dovetail.git"
39
+ },
40
+ "bugs": {
41
+ "url": "https://github.com/tenonhq/dovetail/issues"
42
+ }
43
+ }