@openfn/language-gmail 2.1.1 → 3.0.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
@@ -1,24 +1,33 @@
1
1
  # Gmail adaptor
2
2
 
3
- Send and receive Gmail messages with file attachments using simple, configurable logic.
3
+ Send and receive Gmail messages with file attachments using simple, configurable
4
+ logic.
4
5
 
5
6
  # `getContentsFromMessages`
6
7
 
7
- This function is used to extract specific content from Gmail messages using custom desired "content" configurations. The sample code specifies how to query Gmail for messages and identify desired attachments and metadata.
8
+ This function is used to extract specific content from Gmail messages using
9
+ custom desired "content" configurations. The sample code specifies how to query
10
+ Gmail for messages and identify desired attachments and metadata.
8
11
 
9
- Without any parameters, the `getContentsFromMessages()` function will return an array containing every message in the account of the authenticated user including `from`, `date` and `subject`.
12
+ Without any parameters, the `getContentsFromMessages()` function will return an
13
+ array containing every message in the account of the authenticated user
14
+ including `from`, `date` and `subject`.
10
15
 
11
- A number of options are available to isolated the desired messages and to customize the output.
16
+ A number of options are available to isolated the desired messages and to
17
+ customize the output.
12
18
 
13
19
  ## Parameters
14
20
 
15
- An `options` object can configure the results of the function call. Optional parameters include: `contents`, `query`, `email`, `processedIds`, `maxResults`
21
+ An `options` object can configure the results of the function call. Optional
22
+ parameters include: `contents`, `query`, `email`, `processedIds`, `maxResults`
16
23
 
17
24
  ### options.contents
18
25
 
19
- Use the `options.contents` array to specify the content to retrieve from each message. Always included are `from`, `date`, and `subject`.
26
+ Use the `options.contents` array to specify the content to retrieve from each
27
+ message. Always included are `from`, `date`, and `subject`.
20
28
 
21
- Each item can be a simple string (ie, `'body'`, `'subject'`) or an MessageContent object offering advanced configuration.
29
+ Each item can be a simple string (ie, `'body'`, `'subject'`) or an
30
+ MessageContent object offering advanced configuration.
22
31
 
23
32
  #### Basic metadata
24
33
 
@@ -29,7 +38,8 @@ The following types of content can be extracted:
29
38
  - `date`: Extracts the timestamp of the email.
30
39
  - `from`: Extracts the sender's information.
31
40
 
32
- Optionally, each of these content strings can be expanded to include additional specifications:
41
+ Optionally, each of these content strings can be expanded to include additional
42
+ specifications:
33
43
 
34
44
  ```js
35
45
  const mySubject = {
@@ -41,13 +51,14 @@ const mySubject = {
41
51
 
42
52
  - The `type` property instructs the function which content type to extract.
43
53
  - The `name` property allows you to add a custom name to this information.
44
- - The `maxLength` property allows you to limit the length of the content returned.
54
+ - The `maxLength` property allows you to limit the length of the content
55
+ returned.
45
56
 
46
57
  #### Attachment: basic file
47
58
 
48
59
  Extract content from a file attachment.
49
60
 
50
- `file`: Identify the specific file inside the archive by providing its name as a string or using a regular expression to matching a pattern.
61
+ Set `file` to a string or regex to match the attached file name.
51
62
 
52
63
  ```js
53
64
  const myMetadata = {
@@ -57,11 +68,23 @@ const myMetadata = {
57
68
  };
58
69
  ```
59
70
 
71
+ Some file types will be parsed automatically:
72
+
73
+ - JSON files will be parsed into JSON
74
+ - XLSX and XLS files will be converted to a simple JSON format (arrays of
75
+ arrays, no headers)
76
+ - XML and text files will be parsed into plain text.
77
+
78
+ Other files will be returned as base64 encoded strings.
79
+
80
+ You can force attachments to be parsed into `xlsx`, `text`, `json` or `base64`
81
+ formats by setting `parseAs`.
82
+
60
83
  ```js
61
84
  const myMetadata = {
62
85
  type: 'file',
63
- file: 'summary.txt',
64
- maxLength: 500,
86
+ file: 'summary.text',
87
+ parseAs: 'json',
65
88
  };
66
89
  ```
67
90
 
@@ -69,8 +92,10 @@ const myMetadata = {
69
92
 
70
93
  Extract content from a file embedded in an archive attachment.
71
94
 
72
- - `archive`: Specify the file name of the archive using either a string for an exact match or a regular expression to match a pattern.
73
- - `file`: Identify the specific file inside the archive by providing its name as a string or using a regular expression to match a pattern.
95
+ - `archive`: Specify the file name of the archive using either a string for an
96
+ exact match or a regular expression to match a pattern.
97
+ - `file`: Identify the specific file inside the archive by providing its name as
98
+ a string or using a regular expression to match a pattern.
74
99
 
75
100
  ```js
76
101
  const myArchivedFile = {
@@ -96,11 +121,14 @@ The query syntax supports the same query format as the Gmail `search` box.
96
121
  options.query = 'from:ple.com rfc822msgid:<somemsgid@example.com> is:unread';
97
122
  ```
98
123
 
99
- A full list of supported search operations can be found here: [Refine searches in Gmail](https://support.google.com/mail/answer/7190)
124
+ A full list of supported search operations can be found here:
125
+ [Refine searches in Gmail](https://support.google.com/mail/answer/7190)
100
126
 
101
127
  ### options.email
102
128
 
103
- Optionally specify the email address used for the Gmail account. This almost always the same email associated with the authenticated user so this parameter is optional.
129
+ Optionally specify the email address used for the Gmail account. This almost
130
+ always the same email associated with the authenticated user so this parameter
131
+ is optional.
104
132
 
105
133
  ```js
106
134
  options.email = '<EMAIL>';
@@ -108,7 +136,10 @@ options.email = '<EMAIL>';
108
136
 
109
137
  ### options.processedIds
110
138
 
111
- In some scenarios, it may be necessary to skip certain messages to prevent the retrieval of duplicate data. Passing an array of messageIds will allow the function to skip these messages if any of the ids are encountered in the returned messages.
139
+ In some scenarios, it may be necessary to skip certain messages to prevent the
140
+ retrieval of duplicate data. Passing an array of messageIds will allow the
141
+ function to skip these messages if any of the ids are encountered in the
142
+ returned messages.
112
143
 
113
144
  ```js
114
145
  options.processedIds = [
@@ -120,14 +151,16 @@ options.processedIds = [
120
151
 
121
152
  ### options.maxResults
122
153
 
123
- To prevent inadventant massive retrieval of messages, you can limit the number of results returned. The default value is 1000.
154
+ To prevent inadventant massive retrieval of messages, you can limit the number
155
+ of results returned. The default value is 1000.
124
156
 
125
157
  This works in conjuction with the `options.processedIds` parameter. For example:
126
158
 
127
159
  - account contains messages [1, 2, 3]
128
160
  - `options.processedIds = [1];`
129
161
  - `options.maxResults = 1;`
130
- - this will skip message #1 and resulting dataset will contain a single message #2
162
+ - this will skip message #1 and resulting dataset will contain a single message
163
+ #2
131
164
 
132
165
  ## Example jobs
133
166
 
@@ -165,7 +198,9 @@ getContentsFromMessages({ query, email, contents });
165
198
 
166
199
  ## Sample `state.data` output
167
200
 
168
- For each matched message, the extracted content is returned as a message object of content properties. Here's an example `state.data` for a single matched message:
201
+ For each matched message, the extracted content is returned as a message object
202
+ of content properties. Here's an example `state.data` for a single matched
203
+ message:
169
204
 
170
205
  ```js
171
206
  [
@@ -187,17 +222,20 @@ For each matched message, the extracted content is returned as a message object
187
222
  ];
188
223
  ```
189
224
 
190
- Each property on the message object represents a specific piece of information extracted:
225
+ Each property on the message object represents a specific piece of information
226
+ extracted:
191
227
 
192
228
  - **from**: Sender's email and name.
193
229
  - **date**: The timestamp when the email was sent.
194
230
  - **subject**: Contains the email subject.
195
231
  - **metadata**: Metadata-named file content, with its matched file name.
196
- - **data**: Data-named archive file content, with its matched archive name and file name.
232
+ - **data**: Data-named archive file content, with its matched archive name and
233
+ file name.
197
234
 
198
235
  # `sendMessage`
199
236
 
200
- Use `sendMessage()` to send an email with optional file attachments. This function supports plain text messages as well as attachments and archives.
237
+ Use `sendMessage()` to send an email with optional file attachments. This
238
+ function supports plain text messages as well as attachments and archives.
201
239
 
202
240
  ## Parameters
203
241
 
@@ -213,33 +251,34 @@ Each item in the `attachments` array must include:
213
251
  - `filename` (string): The name of the file.
214
252
  - Either `content` or `archive`:
215
253
  - `content` (string): The file content.
216
- - `archive` (array): Use this to send a `.zip` file. Provide an array of `{ filename, content }` objects.
254
+ - `archive` (array): Use this to send a `.zip` file. Provide an array of
255
+ `{ filename, content }` objects.
217
256
 
218
257
  ## Example jobs
219
258
 
220
259
  ```js
221
260
  sendMessage({
222
- to: "recipient@gmail.com",
223
- subject: "Device Summary",
224
- body: "Here is the latest device summary.",
261
+ to: 'recipient@gmail.com',
262
+ subject: 'Device Summary',
263
+ body: 'Here is the latest device summary.',
225
264
  attachments: [
226
265
  {
227
- filename: "summary.txt",
228
- content: "This is the summary file.",
266
+ filename: 'summary.txt',
267
+ content: 'This is the summary file.',
229
268
  },
230
269
  {
231
- filename: "report.json",
270
+ filename: 'report.json',
232
271
  content: '{ "status": "OK" }',
233
272
  },
234
273
  {
235
- filename: "data.zip",
274
+ filename: 'data.zip',
236
275
  archive: [
237
276
  {
238
- filename: "one.json",
277
+ filename: 'one.json',
239
278
  content: '{ "value": 1 }',
240
279
  },
241
280
  {
242
- filename: "two.json",
281
+ filename: 'two.json',
243
282
  content: '{ "value": 2 }',
244
283
  },
245
284
  ],
@@ -248,11 +287,13 @@ sendMessage({
248
287
  });
249
288
  ```
250
289
 
251
- This will send an email with two plain attachments and one ZIP archive containing two files.
290
+ This will send an email with two plain attachments and one ZIP archive
291
+ containing two files.
252
292
 
253
293
  # Acquiring an access token
254
294
 
255
- The Gmail adaptor implicitly uses the Gmail account of the Google account that is used to authenticate the application.
295
+ The Gmail adaptor implicitly uses the Gmail account of the Google account that
296
+ is used to authenticate the application.
256
297
 
257
298
  Allowing the Gmail adaptor to access a Gmail account is a multi-step process.
258
299
 
@@ -270,34 +311,43 @@ https://support.google.com/googleapi/answer/6158849
270
311
  - Select Application type "Web application"
271
312
  - Add a uniquely-identifiable name
272
313
  - Click "Create"
273
- - On the resulting popup screen, find and click "DOWNLOAD JSON" and save this file to a secure location.
314
+ - On the resulting popup screen, find and click "DOWNLOAD JSON" and save this
315
+ file to a secure location.
274
316
 
275
317
  ## Retrieve an access token
276
318
 
277
- - Navigate to [OAuth 2.0 Playground](https://developers.google.com/oauthplayground/).
278
- - Find *Step 1 Select & authorize APIs*:
279
- - Find the section for *Gmail API v1*.
319
+ - Navigate to
320
+ [OAuth 2.0 Playground](https://developers.google.com/oauthplayground/).
321
+ - Find _Step 1 Select & authorize APIs_:
322
+ - Find the section for _Gmail API v1_.
280
323
  - Mark the following two scopes:
281
324
  - https://www.googleapis.com/auth/gmail.readonly
282
325
  - https://www.googleapis.com/auth/gmail.send
283
- - In the box labeled with the watermark *Input your own scopes* add `openid`.
326
+ - In the box labeled with the watermark _Input your own scopes_ add `openid`.
284
327
  - Click on the **Authorize APIs** button.
285
328
  - Log in to the Google account to which you want to grant access.
286
- - On the *Sign in to Google OAuth 2.0 Playground* screen, Click **Continue**.
287
- - On the *Google OAuth 2.0 Playground wants access to your Google Account* screen:
329
+ - On the _Sign in to Google OAuth 2.0 Playground_ screen, Click **Continue**.
330
+ - On the _Google OAuth 2.0 Playground wants access to your Google Account_
331
+ screen:
288
332
  - **Select all**, including:
289
333
  - **View your email messages and settings**.
290
334
  - **Send email on your behalf**.
291
335
  - Click **Continue**.
292
- - Find *Step 2 Exchange authorization code for tokens*:
293
- - *Authorization code* will be prepopulated.
336
+ - Find _Step 2 Exchange authorization code for tokens_:
337
+ - _Authorization code_ will be prepopulated.
294
338
  - Click **Exchange authorization code for tokens**.
295
- - *Refresh token* and *Access token* will be populated briefly before the interface automatically advances to *Step 3 Configure request to API*. To view the *Access token*, return to *Step 2 Exchange authorization code for tokens*.
296
- - The *Access token* is valid for 1 hour. You may enable **Auto-refresh the token before it expires** or manually refresh it using the **Refresh access token** button.
339
+ - _Refresh token_ and _Access token_ will be populated briefly before the
340
+ interface automatically advances to _Step 3 Configure request to API_. To
341
+ view the _Access token_, return to _Step 2 Exchange authorization code for
342
+ tokens_.
343
+ - The _Access token_ is valid for 1 hour. You may enable **Auto-refresh the
344
+ token before it expires** or manually refresh it using the **Refresh access
345
+ token** button.
297
346
 
298
347
  ## Configure OpenFn CLI to find the access token
299
348
 
300
- The Gmail adaptor looks for the access token in the configuration section under `access_token`.
349
+ The Gmail adaptor looks for the access token in the configuration section under
350
+ `access_token`.
301
351
 
302
352
  Example configuration using a workflow:
303
353
 
package/dist/index.cjs CHANGED
@@ -72,7 +72,9 @@ var import_util = require("@openfn/language-common/util");
72
72
 
73
73
  // src/Utils.js
74
74
  var import_jszip = __toESM(require("jszip"), 1);
75
+ var import_xlsx = __toESM(require("xlsx"), 1);
75
76
  var import_googleapis = require("googleapis");
77
+ var import_node_path = require("path");
76
78
  var SEND_MESSAGE_BOUNDARY = "----=_Part_0_123456789.123456789";
77
79
  var gmail;
78
80
  async function getMessagesResult(userId, query, pageToken) {
@@ -259,11 +261,47 @@ async function getAttachmentResult(message, expression) {
259
261
  id: part.body.attachmentId
260
262
  });
261
263
  return {
262
- data: data == null ? void 0 : data.data,
264
+ data: data.data,
265
+ headers: part.headers,
263
266
  filename: part.filename,
264
267
  expression
265
268
  };
266
269
  }
270
+ var mimeTypeMap = {
271
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
272
+ "application/vnd.ms-excel": "xlsx",
273
+ "text/plain": "text",
274
+ "application/xml": "text",
275
+ "application/json": "json"
276
+ };
277
+ var parsers = {
278
+ xlsx: (data) => {
279
+ const workbook = import_xlsx.default.read(data, { type: "buffer" });
280
+ const result = {};
281
+ for (const sheet of workbook.SheetNames) {
282
+ result[sheet] = import_xlsx.default.utils.sheet_to_json(workbook.Sheets[sheet], {
283
+ header: 1
284
+ });
285
+ }
286
+ return result;
287
+ },
288
+ text: (data) => data.toString("utf-8"),
289
+ json: (data) => JSON.parse(data.toString("utf-8")),
290
+ base64: (data) => data.toString("base64")
291
+ };
292
+ function parseContent(data, headers, parseAs) {
293
+ var _a;
294
+ if (!data) {
295
+ return;
296
+ }
297
+ const contentTypeRaw = ((_a = headers.find((h) => h.name.toLowerCase() === "content-type")) == null ? void 0 : _a.value) ?? "";
298
+ const contentType = contentTypeRaw.split(";")[0];
299
+ let type = parseAs ?? mimeTypeMap[contentType];
300
+ if (type in parsers) {
301
+ return parsers[type](data);
302
+ }
303
+ return parsers.base64(data);
304
+ }
267
305
  async function extractFileFromArchiveAttachment(attachment, desiredContent) {
268
306
  if (!attachment) {
269
307
  return null;
@@ -301,10 +339,15 @@ async function extractFileFromAttachment(attachment, desiredContent) {
301
339
  );
302
340
  return null;
303
341
  }
304
- const fileContent = Buffer.from(attachment.data, "base64").toString("utf-8");
342
+ const fileContent = Buffer.from(attachment.data, "base64");
343
+ const content = parseContent(
344
+ fileContent,
345
+ attachment.headers,
346
+ desiredContent.parseAs
347
+ );
305
348
  return {
306
349
  filename: attachment.filename,
307
- content: desiredContent.maxLength ? fileContent.substring(0, desiredContent.maxLength) : fileContent
350
+ content: desiredContent.maxLength ? content.substring(0, desiredContent.maxLength) : content
308
351
  };
309
352
  }
310
353
  function getBodyFromMessage(message, desiredContent) {
package/dist/index.js CHANGED
@@ -36,6 +36,7 @@ import {
36
36
 
37
37
  // src/Utils.js
38
38
  import JSZip from "jszip";
39
+ import xlsx from "xlsx";
39
40
  import { google } from "googleapis";
40
41
  var SEND_MESSAGE_BOUNDARY = "----=_Part_0_123456789.123456789";
41
42
  var gmail;
@@ -223,11 +224,47 @@ async function getAttachmentResult(message, expression) {
223
224
  id: part.body.attachmentId
224
225
  });
225
226
  return {
226
- data: data == null ? void 0 : data.data,
227
+ data: data.data,
228
+ headers: part.headers,
227
229
  filename: part.filename,
228
230
  expression
229
231
  };
230
232
  }
233
+ var mimeTypeMap = {
234
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
235
+ "application/vnd.ms-excel": "xlsx",
236
+ "text/plain": "text",
237
+ "application/xml": "text",
238
+ "application/json": "json"
239
+ };
240
+ var parsers = {
241
+ xlsx: (data) => {
242
+ const workbook = xlsx.read(data, { type: "buffer" });
243
+ const result = {};
244
+ for (const sheet of workbook.SheetNames) {
245
+ result[sheet] = xlsx.utils.sheet_to_json(workbook.Sheets[sheet], {
246
+ header: 1
247
+ });
248
+ }
249
+ return result;
250
+ },
251
+ text: (data) => data.toString("utf-8"),
252
+ json: (data) => JSON.parse(data.toString("utf-8")),
253
+ base64: (data) => data.toString("base64")
254
+ };
255
+ function parseContent(data, headers, parseAs) {
256
+ var _a;
257
+ if (!data) {
258
+ return;
259
+ }
260
+ const contentTypeRaw = ((_a = headers.find((h) => h.name.toLowerCase() === "content-type")) == null ? void 0 : _a.value) ?? "";
261
+ const contentType = contentTypeRaw.split(";")[0];
262
+ let type = parseAs ?? mimeTypeMap[contentType];
263
+ if (type in parsers) {
264
+ return parsers[type](data);
265
+ }
266
+ return parsers.base64(data);
267
+ }
231
268
  async function extractFileFromArchiveAttachment(attachment, desiredContent) {
232
269
  if (!attachment) {
233
270
  return null;
@@ -265,10 +302,15 @@ async function extractFileFromAttachment(attachment, desiredContent) {
265
302
  );
266
303
  return null;
267
304
  }
268
- const fileContent = Buffer.from(attachment.data, "base64").toString("utf-8");
305
+ const fileContent = Buffer.from(attachment.data, "base64");
306
+ const content = parseContent(
307
+ fileContent,
308
+ attachment.headers,
309
+ desiredContent.parseAs
310
+ );
269
311
  return {
270
312
  filename: attachment.filename,
271
- content: desiredContent.maxLength ? fileContent.substring(0, desiredContent.maxLength) : fileContent
313
+ content: desiredContent.maxLength ? content.substring(0, desiredContent.maxLength) : content
272
314
  };
273
315
  }
274
316
  function getBodyFromMessage(message, desiredContent) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@openfn/language-gmail",
3
3
  "label": "Gmail",
4
- "version": "2.1.1",
4
+ "version": "3.0.0",
5
5
  "badge": "Community",
6
6
  "description": "OpenFn gmail adaptor",
7
7
  "type": "module",
@@ -24,7 +24,8 @@
24
24
  "dependencies": {
25
25
  "googleapis": "171.4.0",
26
26
  "jszip": "^3.10.1",
27
- "@openfn/language-common": "3.3.3"
27
+ "xlsx": "https://cdn.sheetjs.com/xlsx-0.20.3/xlsx-0.20.3.tgz",
28
+ "@openfn/language-common": "3.3.4"
28
29
  },
29
30
  "devDependencies": {
30
31
  "assertion-error": "2.0.0",
@@ -32,7 +33,7 @@
32
33
  "deep-eql": "4.1.1",
33
34
  "mocha": "^10.8.2",
34
35
  "rimraf": "3.0.2",
35
- "undici": "^7.24.7"
36
+ "undici": "^7.28.0"
36
37
  },
37
38
  "repository": {
38
39
  "type": "git",