@openfn/language-gmail 3.0.0 → 3.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/README.md CHANGED
@@ -19,7 +19,8 @@ customize the output.
19
19
  ## Parameters
20
20
 
21
21
  An `options` object can configure the results of the function call. Optional
22
- parameters include: `contents`, `query`, `email`, `processedIds`, `maxResults`
22
+ parameters include: `contents`, `query`, `email`, `processedIds`,
23
+ `maxResults`, `fetchAttachments`
23
24
 
24
25
  ### options.contents
25
26
 
@@ -162,6 +163,34 @@ This works in conjuction with the `options.processedIds` parameter. For example:
162
163
  - this will skip message #1 and resulting dataset will contain a single message
163
164
  #2
164
165
 
166
+ ### options.fetchAttachments
167
+
168
+ Set `fetchAttachments` to `false` to return message IDs and non-attachment
169
+ content without downloading requested file or archive attachments. The default
170
+ is `true`.
171
+
172
+ When downloading is disabled, matched attachments are still reported as
173
+ filename-only objects (without `content`), so a later job can tell which
174
+ messages contain the target attachment:
175
+
176
+ - matched file → `{ filename: 'report.xlsx' }`
177
+ - matched archive → `{ archiveFilename: 'data.zip' }`
178
+ - no match → `null`
179
+
180
+ Pair this with `getMessageById` in a follow-up job to download the attachment
181
+ for exactly the message identified here.
182
+
183
+ ```js
184
+ getContentsFromMessages({
185
+ query: 'after:2026/07/01',
186
+ contents: [
187
+ 'body',
188
+ { type: 'file', name: 'report', file: /\.xlsx$/ },
189
+ ],
190
+ fetchAttachments: false,
191
+ });
192
+ ```
193
+
165
194
  ## Example jobs
166
195
 
167
196
  ```js
@@ -290,6 +319,28 @@ sendMessage({
290
319
  This will send an email with two plain attachments and one ZIP archive
291
320
  containing two files.
292
321
 
322
+ # `getMessageById`
323
+
324
+ Fetch a single message by its Gmail API message id, instead of searching with
325
+ a query. Takes the same `contents`, `email` and `fetchAttachments` options as
326
+ `getContentsFromMessages`, and returns a single message object (rather than an
327
+ array) on `state.data`.
328
+
329
+ This is the id returned by this adaptor as `messageId` on each result. It is
330
+ not the RFC 822 `Message-ID` header, so it cannot be matched with the
331
+ `rfc822msgid:` search operator.
332
+
333
+ This pairs with `getContentsFromMessages`'s `fetchAttachments: false` for a
334
+ two-step pattern: one job lists messages cheaply and records which contain a
335
+ target attachment, and a later job downloads the attachment for one message at
336
+ a time:
337
+
338
+ ```js
339
+ getMessageById($.data.find(m => m.report).messageId, {
340
+ contents: [{ type: 'file', name: 'report', file: /\.xlsx$/ }],
341
+ });
342
+ ```
343
+
293
344
  # Acquiring an access token
294
345
 
295
346
  The Gmail adaptor implicitly uses the Gmail account of the Google account that
package/ast.json CHANGED
@@ -29,7 +29,7 @@
29
29
  },
30
30
  {
31
31
  "title": "state",
32
- "description": "{Array} data - The returned message objects, of the form `{ messageId, contents } `"
32
+ "description": "{Array} data - The returned message objects, of the form `{ messageId, ...contents } `"
33
33
  },
34
34
  {
35
35
  "title": "state",
@@ -52,6 +52,11 @@
52
52
  "title": "example",
53
53
  "description": "getContentsFromMessages(\n {\n query: 'after:15/01/2025',\n contents: [\n 'subject',\n { type: 'file', name: 'metadata', file: 'report.txt'}\n ]\n }\n)",
54
54
  "caption": "Get messages after a specific date, with subject and report.txt attachment"
55
+ },
56
+ {
57
+ "title": "example",
58
+ "description": "getContentsFromMessages(\n {\n query: 'after:2026/07/01',\n contents: [\n 'body',\n { type: 'file', name: 'report', file: /\\.xlsx$/ }\n ],\n fetchAttachments: false\n }\n)",
59
+ "caption": "Get metadata without downloading requested attachments"
55
60
  }
56
61
  ]
57
62
  },
@@ -121,6 +126,67 @@
121
126
  ]
122
127
  },
123
128
  "valid": true
129
+ },
130
+ {
131
+ "name": "getMessageById",
132
+ "params": [
133
+ "messageId",
134
+ "options"
135
+ ],
136
+ "docs": {
137
+ "description": "Downloads contents from a single message of a Gmail account, identified by\nits Gmail API message id.",
138
+ "tags": [
139
+ {
140
+ "title": "public",
141
+ "description": null,
142
+ "type": null
143
+ },
144
+ {
145
+ "title": "function",
146
+ "description": null,
147
+ "name": null
148
+ },
149
+ {
150
+ "title": "param",
151
+ "description": "Gmail API message id to fetch.",
152
+ "type": {
153
+ "type": "NameExpression",
154
+ "name": "string"
155
+ },
156
+ "name": "messageId"
157
+ },
158
+ {
159
+ "title": "param",
160
+ "description": "Customized options including desired contents.",
161
+ "type": {
162
+ "type": "OptionalType",
163
+ "expression": {
164
+ "type": "NameExpression",
165
+ "name": "MessageIdOptions"
166
+ }
167
+ },
168
+ "name": "options"
169
+ },
170
+ {
171
+ "title": "state",
172
+ "description": "{Object} data - The returned message object, of the form `{ messageId, ...contents } `"
173
+ },
174
+ {
175
+ "title": "returns",
176
+ "description": null,
177
+ "type": {
178
+ "type": "NameExpression",
179
+ "name": "Operation"
180
+ }
181
+ },
182
+ {
183
+ "title": "example",
184
+ "description": "getMessageById(\n $.data.messageId,\n {\n contents: [\n { type: 'file', name: 'report', file: /\\.xlsx$/ }\n ]\n }\n)",
185
+ "caption": "Download attachments for a specific message identified by an earlier step"
186
+ }
187
+ ]
188
+ },
189
+ "valid": true
124
190
  }
125
191
  ],
126
192
  "exports": [],
package/dist/index.cjs CHANGED
@@ -38,6 +38,7 @@ __export(src_exports, {
38
38
  fn: () => import_language_common2.fn,
39
39
  fnIf: () => import_language_common2.fnIf,
40
40
  getContentsFromMessages: () => getContentsFromMessages,
41
+ getMessageById: () => getMessageById,
41
42
  lastReferenceValue: () => import_language_common2.lastReferenceValue,
42
43
  log: () => import_language_common2.log,
43
44
  merge: () => import_language_common2.merge,
@@ -61,6 +62,7 @@ __export(Adaptor_exports, {
61
62
  fn: () => import_language_common2.fn,
62
63
  fnIf: () => import_language_common2.fnIf,
63
64
  getContentsFromMessages: () => getContentsFromMessages,
65
+ getMessageById: () => getMessageById,
64
66
  lastReferenceValue: () => import_language_common2.lastReferenceValue,
65
67
  log: () => import_language_common2.log,
66
68
  merge: () => import_language_common2.merge,
@@ -93,19 +95,26 @@ async function getMessagesResult(userId, query, pageToken) {
93
95
  throw new Error("Error fetching messages: " + error.message);
94
96
  }
95
97
  }
96
- async function getMessageResult(userId, messageId) {
98
+ async function getMessageResult(userId, messageId, format = "full") {
97
99
  var _a, _b;
98
- const { data } = await gmail.users.messages.get({
99
- userId,
100
- id: messageId,
101
- format: "full"
102
- });
103
- return {
104
- userId,
105
- messageId,
106
- parts: (_a = data == null ? void 0 : data.payload) == null ? void 0 : _a.parts,
107
- headers: (_b = data == null ? void 0 : data.payload) == null ? void 0 : _b.headers
108
- };
100
+ try {
101
+ const { data } = await gmail.users.messages.get({
102
+ userId,
103
+ id: messageId,
104
+ format,
105
+ ...format === "metadata" && {
106
+ metadataHeaders: ["From", "Date", "Subject"]
107
+ }
108
+ });
109
+ return {
110
+ userId,
111
+ messageId,
112
+ parts: (_a = data == null ? void 0 : data.payload) == null ? void 0 : _a.parts,
113
+ headers: (_b = data == null ? void 0 : data.payload) == null ? void 0 : _b.headers
114
+ };
115
+ } catch (error) {
116
+ throw new Error(`Error fetching message ${messageId}: ` + error.message);
117
+ }
109
118
  }
110
119
  function getContentIndicators(defaultContentRequests = [], contentRequests = []) {
111
120
  const contentIndicators = contentRequests.map(getContentIndicator);
@@ -133,12 +142,20 @@ function getContentIndicator(contentRequest) {
133
142
  }
134
143
  return contentIndicator;
135
144
  }
136
- async function getMessageContent(message, desiredContent) {
145
+ async function getMessageContent(message, desiredContent, fetchAttachments = true) {
137
146
  switch (desiredContent.type) {
138
147
  case "archive":
139
- return await getFileFromArchiveFromAttachment(message, desiredContent);
148
+ return await getFileFromArchiveFromAttachment(
149
+ message,
150
+ desiredContent,
151
+ fetchAttachments
152
+ );
140
153
  case "file":
141
- return await getFileFromAttachment(message, desiredContent);
154
+ return await getFileFromAttachment(
155
+ message,
156
+ desiredContent,
157
+ fetchAttachments
158
+ );
142
159
  case "body":
143
160
  return getBodyFromMessage(message, desiredContent);
144
161
  case "from":
@@ -149,6 +166,50 @@ async function getMessageContent(message, desiredContent) {
149
166
  return `Unsupported content type: ${desiredContent.type}`;
150
167
  }
151
168
  }
169
+ function resolveContentPlan(defaultContents, requestedContents, fetchAttachments) {
170
+ const contentIndicators = getContentIndicators(
171
+ defaultContents,
172
+ requestedContents
173
+ );
174
+ const needsFullFormat = contentIndicators.some(
175
+ ({ type }) => type === "body" || type === "file" || type === "archive"
176
+ );
177
+ const messageFormat = needsFullFormat ? "full" : "metadata";
178
+ if (!fetchAttachments) {
179
+ const skippedNames = contentIndicators.filter(({ type }) => type === "file" || type === "archive").map(({ name }) => name);
180
+ if (skippedNames.length) {
181
+ console.log(
182
+ `fetchAttachments is false: skipping attachment downloads for ${skippedNames.join(
183
+ ", "
184
+ )}; matched filenames will still be included in the output`
185
+ );
186
+ }
187
+ }
188
+ return { contentIndicators, messageFormat };
189
+ }
190
+ async function buildMessageContent(userId, messageId, contentIndicators, messageFormat, fetchAttachments) {
191
+ var _a;
192
+ const content = { messageId };
193
+ const messageResult = await getMessageResult(
194
+ userId,
195
+ messageId,
196
+ messageFormat
197
+ );
198
+ for (const contentIndicator of contentIndicators) {
199
+ const messageContent = await getMessageContent(
200
+ messageResult,
201
+ contentIndicator,
202
+ fetchAttachments
203
+ );
204
+ if (messageContent && content[contentIndicator.name]) {
205
+ throw new Error(
206
+ `Duplicate content name detected: ${contentIndicator.name}`
207
+ );
208
+ }
209
+ content[_a = contentIndicator.name] ?? (content[_a] = messageContent);
210
+ }
211
+ return content;
212
+ }
152
213
  async function buildAndSendMessage(message) {
153
214
  const attachments = await parseAttachments(message.attachments);
154
215
  const hasAttachments = attachments && attachments.length > 0;
@@ -229,7 +290,11 @@ function removeConnection(state) {
229
290
  gmail = void 0;
230
291
  return state;
231
292
  }
232
- async function getFileFromArchiveFromAttachment(message, desiredContent) {
293
+ async function getFileFromArchiveFromAttachment(message, desiredContent, fetchAttachments) {
294
+ if (!fetchAttachments) {
295
+ const part = findAttachmentPart(message, desiredContent.archive);
296
+ return part ? { archiveFilename: part.filename } : null;
297
+ }
233
298
  const attachmentResult = await getAttachmentResult(
234
299
  message,
235
300
  desiredContent.archive
@@ -239,14 +304,18 @@ async function getFileFromArchiveFromAttachment(message, desiredContent) {
239
304
  desiredContent
240
305
  );
241
306
  }
242
- async function getFileFromAttachment(message, desiredContent) {
307
+ async function getFileFromAttachment(message, desiredContent, fetchAttachments) {
308
+ if (!fetchAttachments) {
309
+ const part = findAttachmentPart(message, desiredContent.file);
310
+ return part ? { filename: part.filename } : null;
311
+ }
243
312
  const attachmentResult = await getAttachmentResult(
244
313
  message,
245
314
  desiredContent.file
246
315
  );
247
316
  return await extractFileFromAttachment(attachmentResult, desiredContent);
248
317
  }
249
- async function getAttachmentResult(message, expression) {
318
+ function findAttachmentPart(message, expression) {
250
319
  var _a;
251
320
  const part = (_a = message.parts) == null ? void 0 : _a.find((p) => {
252
321
  return isExpressionMatch(p.filename, expression);
@@ -255,6 +324,13 @@ async function getAttachmentResult(message, expression) {
255
324
  console.info(`Attachment not found for: ${expression}`);
256
325
  return null;
257
326
  }
327
+ return part;
328
+ }
329
+ async function getAttachmentResult(message, expression) {
330
+ const part = findAttachmentPart(message, expression);
331
+ if (!part) {
332
+ return null;
333
+ }
258
334
  const { data } = await gmail.users.messages.attachments.get({
259
335
  userId: message.userId,
260
336
  messageId: message.messageId,
@@ -392,7 +468,7 @@ function isExpressionMatch(text, expression) {
392
468
  var import_language_common2 = require("@openfn/language-common");
393
469
  function getContentsFromMessages(options) {
394
470
  return async (state) => {
395
- var _a, _b;
471
+ var _a;
396
472
  const [resolvedOptions] = (0, import_util.expandReferences)(state, options);
397
473
  const defaultOptions = {
398
474
  contents: ["from", "date", "subject"],
@@ -403,11 +479,13 @@ function getContentsFromMessages(options) {
403
479
  userId: resolvedOptions.email ?? defaultOptions.userId,
404
480
  query: resolvedOptions.query,
405
481
  processedIds: resolvedOptions.processedIds,
406
- maxResults: resolvedOptions.maxResults ?? defaultOptions.maxResults
482
+ maxResults: resolvedOptions.maxResults ?? defaultOptions.maxResults,
483
+ fetchAttachments: resolvedOptions.fetchAttachments !== false
407
484
  };
408
- const contentIndicators = getContentIndicators(
485
+ const { contentIndicators, messageFormat } = resolveContentPlan(
409
486
  defaultOptions.contents,
410
- resolvedOptions.contents
487
+ resolvedOptions.contents,
488
+ opts.fetchAttachments
411
489
  );
412
490
  const contents = [];
413
491
  const newIds = [];
@@ -430,23 +508,15 @@ function getContentsFromMessages(options) {
430
508
  if (previousIds.includes(message.id)) {
431
509
  continue;
432
510
  }
433
- const content = {
434
- messageId: message.id
435
- };
436
- const messageResult = await getMessageResult(opts.userId, message.id);
437
- for (const contentIndicator of contentIndicators) {
438
- const messageContent = await getMessageContent(
439
- messageResult,
440
- contentIndicator
441
- );
442
- if (messageContent && content[contentIndicator.name]) {
443
- throw new Error(
444
- `Duplicate content name detected: ${contentIndicator.name}`
445
- );
446
- }
447
- content[_b = contentIndicator.name] ?? (content[_b] = messageContent);
448
- }
449
- contents.push(content);
511
+ contents.push(
512
+ await buildMessageContent(
513
+ opts.userId,
514
+ message.id,
515
+ contentIndicators,
516
+ messageFormat,
517
+ opts.fetchAttachments
518
+ )
519
+ );
450
520
  if (contents.length >= opts.maxResults) {
451
521
  break doNextPageToken;
452
522
  }
@@ -472,6 +542,37 @@ function sendMessage(message) {
472
542
  };
473
543
  };
474
544
  }
545
+ function getMessageById(messageId, options = {}) {
546
+ return async (state) => {
547
+ const [resolvedMessageId, resolvedOptions] = (0, import_util.expandReferences)(
548
+ state,
549
+ messageId,
550
+ options
551
+ );
552
+ if (typeof resolvedMessageId !== "string" || !resolvedMessageId) {
553
+ throw new Error("getMessageById: messageId must be a non-empty string");
554
+ }
555
+ const defaultOptions = {
556
+ contents: ["from", "date", "subject"],
557
+ userId: "me"
558
+ };
559
+ const userId = resolvedOptions.email ?? defaultOptions.userId;
560
+ const fetchAttachments = resolvedOptions.fetchAttachments !== false;
561
+ const { contentIndicators, messageFormat } = resolveContentPlan(
562
+ defaultOptions.contents,
563
+ resolvedOptions.contents,
564
+ fetchAttachments
565
+ );
566
+ const content = await buildMessageContent(
567
+ userId,
568
+ resolvedMessageId,
569
+ contentIndicators,
570
+ messageFormat,
571
+ fetchAttachments
572
+ );
573
+ return (0, import_language_common.composeNextState)(state, content);
574
+ };
575
+ }
475
576
  function execute(...operations) {
476
577
  const initialState = {
477
578
  references: [],
@@ -506,6 +607,7 @@ var src_default = Adaptor_exports;
506
607
  fn,
507
608
  fnIf,
508
609
  getContentsFromMessages,
610
+ getMessageById,
509
611
  lastReferenceValue,
510
612
  log,
511
613
  merge,
package/dist/index.js CHANGED
@@ -19,6 +19,7 @@ __export(Adaptor_exports, {
19
19
  fn: () => fn,
20
20
  fnIf: () => fnIf,
21
21
  getContentsFromMessages: () => getContentsFromMessages,
22
+ getMessageById: () => getMessageById,
22
23
  lastReferenceValue: () => lastReferenceValue,
23
24
  log: () => log,
24
25
  merge: () => merge,
@@ -56,19 +57,26 @@ async function getMessagesResult(userId, query, pageToken) {
56
57
  throw new Error("Error fetching messages: " + error.message);
57
58
  }
58
59
  }
59
- async function getMessageResult(userId, messageId) {
60
+ async function getMessageResult(userId, messageId, format = "full") {
60
61
  var _a, _b;
61
- const { data } = await gmail.users.messages.get({
62
- userId,
63
- id: messageId,
64
- format: "full"
65
- });
66
- return {
67
- userId,
68
- messageId,
69
- parts: (_a = data == null ? void 0 : data.payload) == null ? void 0 : _a.parts,
70
- headers: (_b = data == null ? void 0 : data.payload) == null ? void 0 : _b.headers
71
- };
62
+ try {
63
+ const { data } = await gmail.users.messages.get({
64
+ userId,
65
+ id: messageId,
66
+ format,
67
+ ...format === "metadata" && {
68
+ metadataHeaders: ["From", "Date", "Subject"]
69
+ }
70
+ });
71
+ return {
72
+ userId,
73
+ messageId,
74
+ parts: (_a = data == null ? void 0 : data.payload) == null ? void 0 : _a.parts,
75
+ headers: (_b = data == null ? void 0 : data.payload) == null ? void 0 : _b.headers
76
+ };
77
+ } catch (error) {
78
+ throw new Error(`Error fetching message ${messageId}: ` + error.message);
79
+ }
72
80
  }
73
81
  function getContentIndicators(defaultContentRequests = [], contentRequests = []) {
74
82
  const contentIndicators = contentRequests.map(getContentIndicator);
@@ -96,12 +104,20 @@ function getContentIndicator(contentRequest) {
96
104
  }
97
105
  return contentIndicator;
98
106
  }
99
- async function getMessageContent(message, desiredContent) {
107
+ async function getMessageContent(message, desiredContent, fetchAttachments = true) {
100
108
  switch (desiredContent.type) {
101
109
  case "archive":
102
- return await getFileFromArchiveFromAttachment(message, desiredContent);
110
+ return await getFileFromArchiveFromAttachment(
111
+ message,
112
+ desiredContent,
113
+ fetchAttachments
114
+ );
103
115
  case "file":
104
- return await getFileFromAttachment(message, desiredContent);
116
+ return await getFileFromAttachment(
117
+ message,
118
+ desiredContent,
119
+ fetchAttachments
120
+ );
105
121
  case "body":
106
122
  return getBodyFromMessage(message, desiredContent);
107
123
  case "from":
@@ -112,6 +128,50 @@ async function getMessageContent(message, desiredContent) {
112
128
  return `Unsupported content type: ${desiredContent.type}`;
113
129
  }
114
130
  }
131
+ function resolveContentPlan(defaultContents, requestedContents, fetchAttachments) {
132
+ const contentIndicators = getContentIndicators(
133
+ defaultContents,
134
+ requestedContents
135
+ );
136
+ const needsFullFormat = contentIndicators.some(
137
+ ({ type }) => type === "body" || type === "file" || type === "archive"
138
+ );
139
+ const messageFormat = needsFullFormat ? "full" : "metadata";
140
+ if (!fetchAttachments) {
141
+ const skippedNames = contentIndicators.filter(({ type }) => type === "file" || type === "archive").map(({ name }) => name);
142
+ if (skippedNames.length) {
143
+ console.log(
144
+ `fetchAttachments is false: skipping attachment downloads for ${skippedNames.join(
145
+ ", "
146
+ )}; matched filenames will still be included in the output`
147
+ );
148
+ }
149
+ }
150
+ return { contentIndicators, messageFormat };
151
+ }
152
+ async function buildMessageContent(userId, messageId, contentIndicators, messageFormat, fetchAttachments) {
153
+ var _a;
154
+ const content = { messageId };
155
+ const messageResult = await getMessageResult(
156
+ userId,
157
+ messageId,
158
+ messageFormat
159
+ );
160
+ for (const contentIndicator of contentIndicators) {
161
+ const messageContent = await getMessageContent(
162
+ messageResult,
163
+ contentIndicator,
164
+ fetchAttachments
165
+ );
166
+ if (messageContent && content[contentIndicator.name]) {
167
+ throw new Error(
168
+ `Duplicate content name detected: ${contentIndicator.name}`
169
+ );
170
+ }
171
+ content[_a = contentIndicator.name] ?? (content[_a] = messageContent);
172
+ }
173
+ return content;
174
+ }
115
175
  async function buildAndSendMessage(message) {
116
176
  const attachments = await parseAttachments(message.attachments);
117
177
  const hasAttachments = attachments && attachments.length > 0;
@@ -192,7 +252,11 @@ function removeConnection(state) {
192
252
  gmail = void 0;
193
253
  return state;
194
254
  }
195
- async function getFileFromArchiveFromAttachment(message, desiredContent) {
255
+ async function getFileFromArchiveFromAttachment(message, desiredContent, fetchAttachments) {
256
+ if (!fetchAttachments) {
257
+ const part = findAttachmentPart(message, desiredContent.archive);
258
+ return part ? { archiveFilename: part.filename } : null;
259
+ }
196
260
  const attachmentResult = await getAttachmentResult(
197
261
  message,
198
262
  desiredContent.archive
@@ -202,14 +266,18 @@ async function getFileFromArchiveFromAttachment(message, desiredContent) {
202
266
  desiredContent
203
267
  );
204
268
  }
205
- async function getFileFromAttachment(message, desiredContent) {
269
+ async function getFileFromAttachment(message, desiredContent, fetchAttachments) {
270
+ if (!fetchAttachments) {
271
+ const part = findAttachmentPart(message, desiredContent.file);
272
+ return part ? { filename: part.filename } : null;
273
+ }
206
274
  const attachmentResult = await getAttachmentResult(
207
275
  message,
208
276
  desiredContent.file
209
277
  );
210
278
  return await extractFileFromAttachment(attachmentResult, desiredContent);
211
279
  }
212
- async function getAttachmentResult(message, expression) {
280
+ function findAttachmentPart(message, expression) {
213
281
  var _a;
214
282
  const part = (_a = message.parts) == null ? void 0 : _a.find((p) => {
215
283
  return isExpressionMatch(p.filename, expression);
@@ -218,6 +286,13 @@ async function getAttachmentResult(message, expression) {
218
286
  console.info(`Attachment not found for: ${expression}`);
219
287
  return null;
220
288
  }
289
+ return part;
290
+ }
291
+ async function getAttachmentResult(message, expression) {
292
+ const part = findAttachmentPart(message, expression);
293
+ if (!part) {
294
+ return null;
295
+ }
221
296
  const { data } = await gmail.users.messages.attachments.get({
222
297
  userId: message.userId,
223
298
  messageId: message.messageId,
@@ -370,7 +445,7 @@ import {
370
445
  } from "@openfn/language-common";
371
446
  function getContentsFromMessages(options) {
372
447
  return async (state) => {
373
- var _a, _b;
448
+ var _a;
374
449
  const [resolvedOptions] = expandReferences(state, options);
375
450
  const defaultOptions = {
376
451
  contents: ["from", "date", "subject"],
@@ -381,11 +456,13 @@ function getContentsFromMessages(options) {
381
456
  userId: resolvedOptions.email ?? defaultOptions.userId,
382
457
  query: resolvedOptions.query,
383
458
  processedIds: resolvedOptions.processedIds,
384
- maxResults: resolvedOptions.maxResults ?? defaultOptions.maxResults
459
+ maxResults: resolvedOptions.maxResults ?? defaultOptions.maxResults,
460
+ fetchAttachments: resolvedOptions.fetchAttachments !== false
385
461
  };
386
- const contentIndicators = getContentIndicators(
462
+ const { contentIndicators, messageFormat } = resolveContentPlan(
387
463
  defaultOptions.contents,
388
- resolvedOptions.contents
464
+ resolvedOptions.contents,
465
+ opts.fetchAttachments
389
466
  );
390
467
  const contents = [];
391
468
  const newIds = [];
@@ -408,23 +485,15 @@ function getContentsFromMessages(options) {
408
485
  if (previousIds.includes(message.id)) {
409
486
  continue;
410
487
  }
411
- const content = {
412
- messageId: message.id
413
- };
414
- const messageResult = await getMessageResult(opts.userId, message.id);
415
- for (const contentIndicator of contentIndicators) {
416
- const messageContent = await getMessageContent(
417
- messageResult,
418
- contentIndicator
419
- );
420
- if (messageContent && content[contentIndicator.name]) {
421
- throw new Error(
422
- `Duplicate content name detected: ${contentIndicator.name}`
423
- );
424
- }
425
- content[_b = contentIndicator.name] ?? (content[_b] = messageContent);
426
- }
427
- contents.push(content);
488
+ contents.push(
489
+ await buildMessageContent(
490
+ opts.userId,
491
+ message.id,
492
+ contentIndicators,
493
+ messageFormat,
494
+ opts.fetchAttachments
495
+ )
496
+ );
428
497
  if (contents.length >= opts.maxResults) {
429
498
  break doNextPageToken;
430
499
  }
@@ -450,6 +519,37 @@ function sendMessage(message) {
450
519
  };
451
520
  };
452
521
  }
522
+ function getMessageById(messageId, options = {}) {
523
+ return async (state) => {
524
+ const [resolvedMessageId, resolvedOptions] = expandReferences(
525
+ state,
526
+ messageId,
527
+ options
528
+ );
529
+ if (typeof resolvedMessageId !== "string" || !resolvedMessageId) {
530
+ throw new Error("getMessageById: messageId must be a non-empty string");
531
+ }
532
+ const defaultOptions = {
533
+ contents: ["from", "date", "subject"],
534
+ userId: "me"
535
+ };
536
+ const userId = resolvedOptions.email ?? defaultOptions.userId;
537
+ const fetchAttachments = resolvedOptions.fetchAttachments !== false;
538
+ const { contentIndicators, messageFormat } = resolveContentPlan(
539
+ defaultOptions.contents,
540
+ resolvedOptions.contents,
541
+ fetchAttachments
542
+ );
543
+ const content = await buildMessageContent(
544
+ userId,
545
+ resolvedMessageId,
546
+ contentIndicators,
547
+ messageFormat,
548
+ fetchAttachments
549
+ );
550
+ return composeNextState(state, content);
551
+ };
552
+ }
453
553
  function execute(...operations) {
454
554
  const initialState = {
455
555
  references: [],
@@ -484,6 +584,7 @@ export {
484
584
  fn,
485
585
  fnIf,
486
586
  getContentsFromMessages,
587
+ getMessageById,
487
588
  lastReferenceValue,
488
589
  log,
489
590
  merge,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@openfn/language-gmail",
3
3
  "label": "Gmail",
4
- "version": "3.0.0",
4
+ "version": "3.1.0",
5
5
  "badge": "Community",
6
6
  "description": "OpenFn gmail adaptor",
7
7
  "type": "module",
@@ -15,18 +15,20 @@
15
15
  * @typedef {Object} Options
16
16
  * @public
17
17
  * @property {string?} [query] - Gmail search query string.
18
- * @property {Array<string|MessageContent>} [contents=['from', 'date', 'subject', 'body']]
18
+ * @property {Array<string|MessageContent>} [contents=['from', 'date', 'subject']]
19
19
  * An array of strings or MessageContent objects used to specify which parts of the message to retrieve.
20
20
  * @property {Array<string>} [processedIds] - Ignore message ids which have already been processed.
21
21
  * @property {string?} [email] - The user account to retrieve messages from. Defaults to the authenticated user.
22
22
  * @property {int?} [maxResults] - Maximum number of messages to process per request. Default is 1000.
23
+ * @property {boolean} [fetchAttachments=true] - Whether to download file and archive attachments.
24
+ * When false, matched attachments are returned as filename-only objects without content.
23
25
  */
24
26
  /**
25
27
  * Downloads contents from messages of a Gmail account.
26
28
  * @public
27
29
  * @function
28
30
  * @param {Options} options - Customized options including desired contents and query.
29
- * @state {Array} data - The returned message objects, of the form `{ messageId, contents } `
31
+ * @state {Array} data - The returned message objects, of the form `{ messageId, ...contents } `
30
32
  * @state {Array<string>} processedIds - An array of string ids processed by this request
31
33
  * @returns {Operation}
32
34
  * @example <caption>Get a message with a specific subject</caption>
@@ -45,6 +47,17 @@
45
47
  * ]
46
48
  * }
47
49
  * )
50
+ * @example <caption>Get metadata without downloading requested attachments</caption>
51
+ * getContentsFromMessages(
52
+ * {
53
+ * query: 'after:2026/07/01',
54
+ * contents: [
55
+ * 'body',
56
+ * { type: 'file', name: 'report', file: /\.xlsx$/ }
57
+ * ],
58
+ * fetchAttachments: false
59
+ * }
60
+ * )
48
61
  */
49
62
  export function getContentsFromMessages(options: Options): Operation;
50
63
  /**
@@ -75,6 +88,36 @@ export function getContentsFromMessages(options: Options): Operation;
75
88
  * })
76
89
  */
77
90
  export function sendMessage(message: SendMessageOptions | SendMessageOptions[]): Operation;
91
+ /**
92
+ * Configurable options provided to getMessageById.
93
+ * @typedef {Object} MessageIdOptions
94
+ * @public
95
+ * @property {Array<string|MessageContent>} [contents=['from', 'date', 'subject']]
96
+ * An array of strings or MessageContent objects used to specify which parts of the message to retrieve.
97
+ * @property {string?} [email] - The user account to retrieve messages from. Defaults to the authenticated user.
98
+ * @property {boolean} [fetchAttachments=true] - Whether to download file and archive attachments.
99
+ * When false, matched attachments are returned as filename-only objects without content.
100
+ */
101
+ /**
102
+ * Downloads contents from a single message of a Gmail account, identified by
103
+ * its Gmail API message id.
104
+ * @public
105
+ * @function
106
+ * @param {string} messageId - Gmail API message id to fetch.
107
+ * @param {MessageIdOptions} [options] - Customized options including desired contents.
108
+ * @state {Object} data - The returned message object, of the form `{ messageId, ...contents } `
109
+ * @returns {Operation}
110
+ * @example <caption>Download attachments for a specific message identified by an earlier step</caption>
111
+ * getMessageById(
112
+ * $.data.messageId,
113
+ * {
114
+ * contents: [
115
+ * { type: 'file', name: 'report', file: /\.xlsx$/ }
116
+ * ]
117
+ * }
118
+ * )
119
+ */
120
+ export function getMessageById(messageId: string, options?: MessageIdOptions): Operation;
78
121
  /**
79
122
  * Execute a sequence of operations.
80
123
  * Wraps `language-common/execute`, and prepends initial state for http.
@@ -115,4 +158,8 @@ export type SendMessageOptions = {
115
158
  content: string | Buffer;
116
159
  }>;
117
160
  };
161
+ /**
162
+ * Configurable options provided to getMessageById.
163
+ */
164
+ export type MessageIdOptions = any;
118
165
  export { alterState, combine, cursor, dataPath, dataValue, each, field, fields, fn, fnIf, lastReferenceValue, log, merge, sourceValue } from "@openfn/language-common";
package/types/Utils.d.ts CHANGED
@@ -2,14 +2,21 @@ export function getMessagesResult(userId: any, query: any, pageToken: any): Prom
2
2
  messages: any;
3
3
  nextPageToken: any;
4
4
  }>;
5
- export function getMessageResult(userId: any, messageId: any): Promise<{
5
+ export function getMessageResult(userId: any, messageId: any, format?: string): Promise<{
6
6
  userId: any;
7
7
  messageId: any;
8
8
  parts: any;
9
9
  headers: any;
10
10
  }>;
11
11
  export function getContentIndicators(defaultContentRequests?: any[], contentRequests?: any[]): any[];
12
- export function getMessageContent(message: any, desiredContent: any): Promise<any>;
12
+ export function getMessageContent(message: any, desiredContent: any, fetchAttachments?: boolean): Promise<any>;
13
+ export function resolveContentPlan(defaultContents: any, requestedContents: any, fetchAttachments: any): {
14
+ contentIndicators: any[];
15
+ messageFormat: string;
16
+ };
17
+ export function buildMessageContent(userId: any, messageId: any, contentIndicators: any, messageFormat: any, fetchAttachments: any): Promise<{
18
+ messageId: any;
19
+ }>;
13
20
  export function buildAndSendMessage(message: any): Promise<any>;
14
21
  export function createConnection(state: any): any;
15
22
  export function removeConnection(state: any): any;