nylas 7.0.0-beta.0 → 7.0.0-beta.2

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.
Files changed (204) hide show
  1. package/README.md +27 -19
  2. package/lib/cjs/apiClient.js +114 -0
  3. package/lib/cjs/config.js +32 -0
  4. package/lib/cjs/models/applicationDetails.js +2 -0
  5. package/lib/cjs/models/auth.js +2 -0
  6. package/lib/cjs/models/availability.js +11 -0
  7. package/lib/cjs/models/calendars.js +2 -0
  8. package/lib/cjs/models/error.js +53 -0
  9. package/lib/cjs/models/events.js +2 -0
  10. package/lib/cjs/models/grants.js +2 -0
  11. package/lib/cjs/models/listQueryParams.js +2 -0
  12. package/lib/cjs/models/redirectUri.js +2 -0
  13. package/lib/cjs/models/response.js +2 -0
  14. package/lib/cjs/models/webhooks.js +18 -0
  15. package/lib/cjs/nylas.js +34 -0
  16. package/lib/cjs/package.json +3 -0
  17. package/lib/cjs/resources/applications.js +30 -0
  18. package/lib/cjs/resources/auth.js +153 -0
  19. package/lib/cjs/resources/calendars.js +78 -0
  20. package/lib/cjs/resources/events.js +69 -0
  21. package/lib/cjs/resources/grants.js +65 -0
  22. package/lib/cjs/resources/redirectUris.js +64 -0
  23. package/lib/cjs/resources/resource.js +111 -0
  24. package/lib/cjs/resources/webhooks.js +98 -0
  25. package/lib/cjs/utils.js +58 -0
  26. package/lib/cjs/version.js +5 -0
  27. package/lib/esm/apiClient.js +111 -0
  28. package/lib/esm/config.js +29 -0
  29. package/lib/esm/models/applicationDetails.js +1 -0
  30. package/lib/esm/models/auth.js +1 -0
  31. package/lib/esm/models/availability.js +8 -0
  32. package/lib/esm/models/calendars.js +1 -0
  33. package/lib/esm/models/error.js +45 -0
  34. package/lib/esm/models/events.js +1 -0
  35. package/lib/esm/models/grants.js +1 -0
  36. package/lib/esm/models/listQueryParams.js +1 -0
  37. package/lib/esm/models/redirectUri.js +1 -0
  38. package/lib/esm/models/response.js +1 -0
  39. package/lib/esm/models/webhooks.js +15 -0
  40. package/lib/esm/nylas.js +31 -0
  41. package/lib/esm/package.json +3 -0
  42. package/lib/esm/resources/applications.js +26 -0
  43. package/lib/esm/resources/auth.js +149 -0
  44. package/lib/esm/resources/calendars.js +74 -0
  45. package/lib/esm/resources/events.js +65 -0
  46. package/lib/esm/resources/grants.js +61 -0
  47. package/lib/esm/resources/redirectUris.js +60 -0
  48. package/lib/esm/resources/resource.js +107 -0
  49. package/lib/esm/resources/webhooks.js +94 -0
  50. package/lib/esm/utils.js +53 -0
  51. package/lib/esm/version.js +2 -0
  52. package/lib/types/apiClient.d.ts +65 -0
  53. package/lib/types/config.d.ts +50 -0
  54. package/lib/types/models/applicationDetails.d.ts +93 -0
  55. package/lib/types/models/auth.d.ts +196 -0
  56. package/lib/types/models/availability.d.ts +159 -0
  57. package/lib/types/models/calendars.d.ts +121 -0
  58. package/lib/types/models/error.d.ts +104 -0
  59. package/lib/types/models/events.d.ts +494 -0
  60. package/lib/types/models/grants.d.ts +134 -0
  61. package/lib/types/models/listQueryParams.d.ts +4 -0
  62. package/lib/types/models/redirectUri.d.ts +71 -0
  63. package/lib/types/models/response.d.ts +40 -0
  64. package/lib/types/models/webhooks.d.ts +45 -0
  65. package/lib/types/nylas.d.ts +44 -0
  66. package/lib/types/resources/applications.d.ts +26 -0
  67. package/lib/types/resources/auth.d.ts +66 -0
  68. package/lib/types/resources/calendars.d.ts +97 -0
  69. package/lib/types/resources/events.d.ts +87 -0
  70. package/lib/types/resources/grants.d.ts +63 -0
  71. package/lib/types/resources/redirectUris.d.ts +63 -0
  72. package/lib/types/resources/resource.d.ts +55 -0
  73. package/lib/types/resources/webhooks.d.ts +79 -0
  74. package/lib/types/utils.d.ts +22 -0
  75. package/lib/types/version.d.ts +1 -0
  76. package/package.json +33 -42
  77. package/lib/config.d.ts +0 -70
  78. package/lib/config.js +0 -68
  79. package/lib/models/access-token.d.ts +0 -18
  80. package/lib/models/access-token.js +0 -56
  81. package/lib/models/account.d.ts +0 -27
  82. package/lib/models/account.js +0 -73
  83. package/lib/models/application-details.d.ts +0 -14
  84. package/lib/models/application-details.js +0 -47
  85. package/lib/models/attributes.d.ts +0 -151
  86. package/lib/models/attributes.js +0 -382
  87. package/lib/models/calendar-availability.d.ts +0 -76
  88. package/lib/models/calendar-availability.js +0 -121
  89. package/lib/models/calendar-restful-model-collection.d.ts +0 -17
  90. package/lib/models/calendar-restful-model-collection.js +0 -181
  91. package/lib/models/calendar.d.ts +0 -31
  92. package/lib/models/calendar.js +0 -93
  93. package/lib/models/component-restful-model-collection.d.ts +0 -9
  94. package/lib/models/component-restful-model-collection.js +0 -34
  95. package/lib/models/component.d.ts +0 -37
  96. package/lib/models/component.js +0 -91
  97. package/lib/models/connect.d.ts +0 -73
  98. package/lib/models/connect.js +0 -193
  99. package/lib/models/contact-restful-model-collection.d.ts +0 -9
  100. package/lib/models/contact-restful-model-collection.js +0 -60
  101. package/lib/models/contact.d.ts +0 -129
  102. package/lib/models/contact.js +0 -289
  103. package/lib/models/delta-collection.d.ts +0 -17
  104. package/lib/models/delta-collection.js +0 -139
  105. package/lib/models/delta-stream.d.ts +0 -32
  106. package/lib/models/delta-stream.js +0 -250
  107. package/lib/models/delta.d.ts +0 -28
  108. package/lib/models/delta.js +0 -88
  109. package/lib/models/deltas.d.ts +0 -17
  110. package/lib/models/deltas.js +0 -49
  111. package/lib/models/draft.d.ts +0 -27
  112. package/lib/models/draft.js +0 -156
  113. package/lib/models/email-participant.d.ts +0 -13
  114. package/lib/models/email-participant.js +0 -46
  115. package/lib/models/event-conferencing.d.ts +0 -34
  116. package/lib/models/event-conferencing.js +0 -71
  117. package/lib/models/event-notification.d.ts +0 -27
  118. package/lib/models/event-notification.js +0 -62
  119. package/lib/models/event-participant.d.ts +0 -19
  120. package/lib/models/event-participant.js +0 -56
  121. package/lib/models/event.d.ts +0 -96
  122. package/lib/models/event.js +0 -297
  123. package/lib/models/file.d.ts +0 -29
  124. package/lib/models/file.js +0 -136
  125. package/lib/models/folder.d.ts +0 -21
  126. package/lib/models/folder.js +0 -69
  127. package/lib/models/free-busy.d.ts +0 -58
  128. package/lib/models/free-busy.js +0 -132
  129. package/lib/models/job-status-restful-model-collection.d.ts +0 -9
  130. package/lib/models/job-status-restful-model-collection.js +0 -38
  131. package/lib/models/job-status.d.ts +0 -24
  132. package/lib/models/job-status.js +0 -68
  133. package/lib/models/management-account.d.ts +0 -63
  134. package/lib/models/management-account.js +0 -187
  135. package/lib/models/management-model-collection.d.ts +0 -10
  136. package/lib/models/management-model-collection.js +0 -39
  137. package/lib/models/management-model.d.ts +0 -6
  138. package/lib/models/management-model.js +0 -29
  139. package/lib/models/message-restful-model-collection.d.ts +0 -26
  140. package/lib/models/message-restful-model-collection.js +0 -80
  141. package/lib/models/message.d.ts +0 -57
  142. package/lib/models/message.js +0 -173
  143. package/lib/models/model-collection.d.ts +0 -25
  144. package/lib/models/model-collection.js +0 -201
  145. package/lib/models/model.d.ts +0 -12
  146. package/lib/models/model.js +0 -64
  147. package/lib/models/neural-categorizer.d.ts +0 -28
  148. package/lib/models/neural-categorizer.js +0 -139
  149. package/lib/models/neural-clean-conversation.d.ts +0 -16
  150. package/lib/models/neural-clean-conversation.js +0 -114
  151. package/lib/models/neural-ocr.d.ts +0 -14
  152. package/lib/models/neural-ocr.js +0 -50
  153. package/lib/models/neural-sentiment-analysis.d.ts +0 -20
  154. package/lib/models/neural-sentiment-analysis.js +0 -56
  155. package/lib/models/neural-signature-contact.d.ts +0 -43
  156. package/lib/models/neural-signature-contact.js +0 -142
  157. package/lib/models/neural-signature-extraction.d.ts +0 -17
  158. package/lib/models/neural-signature-extraction.js +0 -54
  159. package/lib/models/neural.d.ts +0 -36
  160. package/lib/models/neural.js +0 -163
  161. package/lib/models/nylas-api-error.d.ts +0 -26
  162. package/lib/models/nylas-api-error.js +0 -61
  163. package/lib/models/outbox-job-status.d.ts +0 -20
  164. package/lib/models/outbox-job-status.js +0 -64
  165. package/lib/models/outbox-message.d.ts +0 -16
  166. package/lib/models/outbox-message.js +0 -54
  167. package/lib/models/outbox.d.ts +0 -35
  168. package/lib/models/outbox.js +0 -158
  169. package/lib/models/resource.d.ts +0 -22
  170. package/lib/models/resource.js +0 -66
  171. package/lib/models/restful-model-collection.d.ts +0 -15
  172. package/lib/models/restful-model-collection.js +0 -169
  173. package/lib/models/restful-model-instance.d.ts +0 -9
  174. package/lib/models/restful-model-instance.js +0 -37
  175. package/lib/models/restful-model.d.ts +0 -36
  176. package/lib/models/restful-model.js +0 -146
  177. package/lib/models/scheduler-booking-request.d.ts +0 -64
  178. package/lib/models/scheduler-booking-request.js +0 -148
  179. package/lib/models/scheduler-restful-model-collection.d.ts +0 -26
  180. package/lib/models/scheduler-restful-model-collection.js +0 -133
  181. package/lib/models/scheduler-time-slot.d.ts +0 -20
  182. package/lib/models/scheduler-time-slot.js +0 -53
  183. package/lib/models/scheduler.d.ts +0 -226
  184. package/lib/models/scheduler.js +0 -446
  185. package/lib/models/thread.d.ts +0 -49
  186. package/lib/models/thread.js +0 -127
  187. package/lib/models/webhook-notification.d.ts +0 -108
  188. package/lib/models/webhook-notification.js +0 -239
  189. package/lib/models/webhook.d.ts +0 -50
  190. package/lib/models/webhook.js +0 -101
  191. package/lib/models/when.d.ts +0 -23
  192. package/lib/models/when.js +0 -65
  193. package/lib/nylas-connection.d.ts +0 -71
  194. package/lib/nylas-connection.js +0 -258
  195. package/lib/nylas.d.ts +0 -57
  196. package/lib/nylas.js +0 -210
  197. package/lib/server-bindings/express-binding.d.ts +0 -18
  198. package/lib/server-bindings/express-binding.js +0 -163
  199. package/lib/server-bindings/server-binding.d.ts +0 -65
  200. package/lib/server-bindings/server-binding.js +0 -87
  201. package/lib/services/routes.d.ts +0 -26
  202. package/lib/services/routes.js +0 -95
  203. package/lib/services/tunnel.d.ts +0 -29
  204. package/lib/services/tunnel.js +0 -112
package/lib/nylas.js DELETED
@@ -1,210 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- var __importStar = (this && this.__importStar) || function (mod) {
6
- if (mod && mod.__esModule) return mod;
7
- var result = {};
8
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
9
- result["default"] = mod;
10
- return result;
11
- };
12
- // TODO since node 10 URL is global
13
- var url_1 = require("url");
14
- var node_fetch_1 = __importDefault(require("node-fetch"));
15
- var config = __importStar(require("./config"));
16
- var nylas_connection_1 = __importDefault(require("./nylas-connection"));
17
- var management_account_1 = __importDefault(require("./models/management-account"));
18
- var account_1 = __importDefault(require("./models/account"));
19
- var connect_1 = __importDefault(require("./models/connect"));
20
- var restful_model_collection_1 = __importDefault(require("./models/restful-model-collection"));
21
- var management_model_collection_1 = __importDefault(require("./models/management-model-collection"));
22
- var webhook_1 = __importDefault(require("./models/webhook"));
23
- var access_token_1 = __importDefault(require("./models/access-token"));
24
- var application_details_1 = __importDefault(require("./models/application-details"));
25
- var Nylas = /** @class */ (function () {
26
- function Nylas(config) {
27
- this.clientId = '';
28
- if (config.apiServer && config.apiServer.indexOf('://') === -1) {
29
- throw new Error('Please specify a fully qualified URL for the API Server.');
30
- }
31
- if (config.clientId) {
32
- this.clientId = config.clientId;
33
- }
34
- if (config.clientSecret) {
35
- this.clientSecret = config.clientSecret;
36
- }
37
- if (config.apiServer) {
38
- this.apiServer = config.apiServer;
39
- }
40
- else {
41
- this.apiServer = 'https://api.nylas.com';
42
- }
43
- var conn = new nylas_connection_1.default(this.clientSecret, {
44
- clientId: this.clientId,
45
- });
46
- this.connect = new connect_1.default(conn, this.clientId, this.clientSecret);
47
- this.webhooks = new management_model_collection_1.default(webhook_1.default, conn, this.clientId);
48
- if (this.clientCredentials()) {
49
- this.accounts = new management_model_collection_1.default(management_account_1.default, conn, this.clientId);
50
- }
51
- else {
52
- this.accounts = new restful_model_collection_1.default(account_1.default, conn);
53
- }
54
- return this;
55
- }
56
- Object.defineProperty(Nylas.prototype, "clientSecret", {
57
- get: function () {
58
- return config.clientSecret;
59
- },
60
- set: function (newClientSecret) {
61
- config.setClientSecret(newClientSecret);
62
- },
63
- enumerable: true,
64
- configurable: true
65
- });
66
- Object.defineProperty(Nylas.prototype, "apiServer", {
67
- get: function () {
68
- return config.apiServer;
69
- },
70
- set: function (newApiServer) {
71
- config.setApiServer(newApiServer);
72
- },
73
- enumerable: true,
74
- configurable: true
75
- });
76
- /**
77
- * Checks if the Nylas instance has been configured with credentials
78
- * @return True if the Nylas instance has been configured with credentials
79
- */
80
- Nylas.prototype.clientCredentials = function () {
81
- return this.clientId != null && this.clientSecret != null;
82
- };
83
- /**
84
- * Configure a NylasConnection instance to access a user's resources
85
- * @param accessToken The access token to access the user's resources
86
- * @return The configured NylasConnection instance
87
- */
88
- Nylas.prototype.with = function (accessToken) {
89
- if (!accessToken) {
90
- throw new Error('This function requires an access token');
91
- }
92
- return new nylas_connection_1.default(accessToken, { clientId: this.clientId });
93
- };
94
- /**
95
- * Return information about a Nylas application
96
- * @param options Application details to overwrite
97
- * @return Information about the Nylas application
98
- */
99
- Nylas.prototype.application = function (options) {
100
- if (!this.clientId) {
101
- throw new Error('This function requires a clientId');
102
- }
103
- if (!this.clientSecret) {
104
- throw new Error('This function requires a clientSecret');
105
- }
106
- var connection = new nylas_connection_1.default(null, { clientId: this.clientId });
107
- var requestOptions = {
108
- path: "/a/" + this.clientId,
109
- };
110
- if (options) {
111
- requestOptions.body = {
112
- application_name: options.applicationName,
113
- icon_url: options.iconUrl,
114
- redirect_uris: options.redirectUris,
115
- };
116
- requestOptions.method = 'PUT';
117
- }
118
- return connection.request(requestOptions).then(function (res) {
119
- return new application_details_1.default().fromJSON(res);
120
- });
121
- };
122
- /**
123
- * Exchange an authorization code for an access token
124
- * @param code One-time authorization code from Nylas
125
- * @param callback Callback before returning the access token
126
- * @return The {@link AccessToken} object containing the access token and other information
127
- */
128
- Nylas.prototype.exchangeCodeForToken = function (code, callback) {
129
- if (!this.clientId || !this.clientSecret) {
130
- throw new Error('exchangeCodeForToken() cannot be called until you provide a clientId and secret via config()');
131
- }
132
- if (!code) {
133
- throw new Error('exchangeCodeForToken() must be called with a code');
134
- }
135
- var url = new url_1.URL(this.apiServer + "/oauth/token");
136
- url.searchParams.set('client_id', this.clientId);
137
- url.searchParams.set('client_secret', this.clientSecret);
138
- url.searchParams.set('grant_type', 'authorization_code');
139
- url.searchParams.set('code', code);
140
- return node_fetch_1.default(url)
141
- .then(function (response) {
142
- if (response.ok) {
143
- return response.json();
144
- }
145
- })
146
- .then(function (body) {
147
- if (!body || !body['access_token']) {
148
- var errorMessage = 'No access token in response';
149
- if (body && body.message)
150
- errorMessage = body.message;
151
- throw new Error(errorMessage);
152
- }
153
- var accessToken = new access_token_1.default().fromJSON(body);
154
- if (callback) {
155
- callback(null, accessToken);
156
- }
157
- return accessToken;
158
- }, function (error) {
159
- var newError = new Error(error.message);
160
- if (callback) {
161
- callback(newError);
162
- }
163
- throw newError;
164
- });
165
- };
166
- /**
167
- * Build the URL for authenticating users to your application via Hosted Authentication
168
- * @param options Configuration for the authentication process
169
- * @return The URL for hosted authentication
170
- */
171
- Nylas.prototype.urlForAuthentication = function (options) {
172
- if (!this.clientId) {
173
- throw new Error('urlForAuthentication() cannot be called until you provide a clientId via config()');
174
- }
175
- if (!options.redirectURI) {
176
- throw new Error('urlForAuthentication() requires options.redirectURI');
177
- }
178
- if (!options.loginHint) {
179
- options.loginHint = '';
180
- }
181
- var url = this.apiServer + "/oauth/authorize?client_id=" + this.clientId + "&response_type=code&login_hint=" + options.loginHint + "&redirect_uri=" + options.redirectURI;
182
- if (options.state != null) {
183
- url += "&state=" + options.state;
184
- }
185
- if (options.scopes != null) {
186
- url += "&scopes=" + options.scopes.join(',');
187
- }
188
- if (options.provider != null) {
189
- url += "&provider=" + options.provider;
190
- }
191
- if (options.redirectOnError) {
192
- url += '&redirect_on_error=true';
193
- }
194
- return url;
195
- };
196
- /**
197
- * Revoke a single access token
198
- * @param accessToken The access token to revoke
199
- */
200
- Nylas.prototype.revoke = function (accessToken) {
201
- return this.with(accessToken)
202
- .request({
203
- method: 'POST',
204
- path: '/oauth/revoke',
205
- })
206
- .catch(function (err) { return Promise.reject(err); });
207
- };
208
- return Nylas;
209
- }());
210
- module.exports = Nylas;
@@ -1,18 +0,0 @@
1
- import Nylas from '../nylas';
2
- import { RequestHandler, Router } from 'express';
3
- import { ServerBindingOptions, ServerBinding } from './server-binding';
4
- export default class ExpressBinding extends ServerBinding {
5
- constructor(nylasClient: Nylas, options: ServerBindingOptions);
6
- /**
7
- * Middleware for the webhook endpoint so we can verify that Nylas is sending the events
8
- */
9
- webhookVerificationMiddleware(): RequestHandler;
10
- /**
11
- * Build middleware for an Express app with routes for:
12
- * 1. '/nylas/webhook': Receiving webhook events, verifying its authenticity, and emitting webhook objects
13
- * 2. '/nylas/generate-auth-url': Building the URL for authenticating users to your application via Hosted Authentication
14
- * 3. '/nylas/exchange-mailbox-token': Exchange an authorization code for an access token
15
- * @return The routes packaged as Express middleware
16
- */
17
- buildMiddleware(): Router;
18
- }
@@ -1,163 +0,0 @@
1
- "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- extendStatics(d, b);
11
- function __() { this.constructor = d; }
12
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13
- };
14
- })();
15
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
16
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
17
- return new (P || (P = Promise))(function (resolve, reject) {
18
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
19
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
20
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
21
- step((generator = generator.apply(thisArg, _arguments || [])).next());
22
- });
23
- };
24
- var __generator = (this && this.__generator) || function (thisArg, body) {
25
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
26
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
27
- function verb(n) { return function (v) { return step([n, v]); }; }
28
- function step(op) {
29
- if (f) throw new TypeError("Generator is already executing.");
30
- while (_) try {
31
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
32
- if (y = 0, t) op = [op[0] & 2, t.value];
33
- switch (op[0]) {
34
- case 0: case 1: t = op; break;
35
- case 4: _.label++; return { value: op[1], done: false };
36
- case 5: _.label++; y = op[1]; op = [0]; continue;
37
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
38
- default:
39
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
40
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
41
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
42
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
43
- if (t[2]) _.ops.pop();
44
- _.trys.pop(); continue;
45
- }
46
- op = body.call(thisArg, _);
47
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
48
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
49
- }
50
- };
51
- var __importDefault = (this && this.__importDefault) || function (mod) {
52
- return (mod && mod.__esModule) ? mod : { "default": mod };
53
- };
54
- Object.defineProperty(exports, "__esModule", { value: true });
55
- var express_1 = __importDefault(require("express"));
56
- var server_binding_1 = require("./server-binding");
57
- var body_parser_1 = __importDefault(require("body-parser"));
58
- var routes_1 = require("../services/routes");
59
- var ExpressBinding = /** @class */ (function (_super) {
60
- __extends(ExpressBinding, _super);
61
- function ExpressBinding(nylasClient, options) {
62
- return _super.call(this, nylasClient, options) || this;
63
- }
64
- /**
65
- * Middleware for the webhook endpoint so we can verify that Nylas is sending the events
66
- */
67
- ExpressBinding.prototype.webhookVerificationMiddleware = function () {
68
- var _this = this;
69
- return function (req, res, next) {
70
- var isVerified = _this.verifyWebhookSignature(req.header(server_binding_1.ServerBinding.NYLAS_SIGNATURE_HEADER), req.body);
71
- if (!isVerified) {
72
- return res
73
- .status(401)
74
- .send('X-Nylas-Signature failed verification 🚷 ');
75
- }
76
- next();
77
- };
78
- };
79
- /**
80
- * Build middleware for an Express app with routes for:
81
- * 1. '/nylas/webhook': Receiving webhook events, verifying its authenticity, and emitting webhook objects
82
- * 2. '/nylas/generate-auth-url': Building the URL for authenticating users to your application via Hosted Authentication
83
- * 3. '/nylas/exchange-mailbox-token': Exchange an authorization code for an access token
84
- * @return The routes packaged as Express middleware
85
- */
86
- ExpressBinding.prototype.buildMiddleware = function () {
87
- var _this = this;
88
- var _a, _b, _c;
89
- var router = express_1.default.Router();
90
- // For the Nylas webhook endpoint, we should get the raw body to use for verification
91
- router.use(routes_1.DefaultPaths.webhooks, body_parser_1.default.raw({ inflate: true, type: 'application/json' }));
92
- router.use(express_1.default.json(), body_parser_1.default.urlencoded({ limit: '5mb', extended: true }) // support encoded bodies
93
- );
94
- router.post(((_a = this.overridePaths) === null || _a === void 0 ? void 0 : _a.webhooks) || routes_1.DefaultPaths.webhooks, this.webhookVerificationMiddleware(), function (req, res) {
95
- var deltas = req.body.deltas || [];
96
- _this.emitDeltaEvents(deltas);
97
- res.status(200).send('ok');
98
- });
99
- router.post(((_b = this.overridePaths) === null || _b === void 0 ? void 0 : _b.buildAuthUrl) || routes_1.DefaultPaths.buildAuthUrl, function (req, res) { return __awaiter(_this, void 0, void 0, function () {
100
- var state, authUrl;
101
- return __generator(this, function (_a) {
102
- switch (_a.label) {
103
- case 0:
104
- state = '';
105
- if (!this.csrfTokenExchangeOpts) return [3 /*break*/, 2];
106
- return [4 /*yield*/, this.csrfTokenExchangeOpts.generateCsrfToken(req)];
107
- case 1:
108
- state = _a.sent();
109
- _a.label = 2;
110
- case 2: return [4 /*yield*/, this.buildAuthUrl({
111
- scopes: this.defaultScopes,
112
- clientUri: this.clientUri,
113
- emailAddress: req.body.email_address,
114
- successUrl: req.body.success_url,
115
- state: state,
116
- })];
117
- case 3:
118
- authUrl = _a.sent();
119
- res.status(200).send(authUrl);
120
- return [2 /*return*/];
121
- }
122
- });
123
- }); });
124
- router.post(((_c = this.overridePaths) === null || _c === void 0 ? void 0 : _c.exchangeCodeForToken) ||
125
- routes_1.DefaultPaths.exchangeCodeForToken, function (req, res) { return __awaiter(_this, void 0, void 0, function () {
126
- var csrfToken, isValidToken, accessTokenObj, e_1;
127
- return __generator(this, function (_a) {
128
- switch (_a.label) {
129
- case 0:
130
- _a.trys.push([0, 5, , 6]);
131
- if (!this.csrfTokenExchangeOpts) return [3 /*break*/, 2];
132
- csrfToken = req.body.csrfToken;
133
- return [4 /*yield*/, this.csrfTokenExchangeOpts.validateCsrfToken(csrfToken, req)];
134
- case 1:
135
- isValidToken = _a.sent();
136
- if (!isValidToken) {
137
- return [2 /*return*/, res.status(401).send('Invalid CSRF State Token')];
138
- }
139
- _a.label = 2;
140
- case 2: return [4 /*yield*/, this.exchangeCodeForToken(req.body.token)];
141
- case 3:
142
- accessTokenObj = _a.sent();
143
- return [4 /*yield*/, this.exchangeMailboxTokenCallback(accessTokenObj, res)];
144
- case 4:
145
- _a.sent();
146
- // If the callback event already sent a response then we don't need to do anything
147
- if (!res.writableEnded) {
148
- res.status(200).send('success');
149
- }
150
- return [3 /*break*/, 6];
151
- case 5:
152
- e_1 = _a.sent();
153
- res.status(500).send(e_1.message);
154
- return [3 /*break*/, 6];
155
- case 6: return [2 /*return*/];
156
- }
157
- });
158
- }); });
159
- return router;
160
- };
161
- return ExpressBinding;
162
- }(server_binding_1.ServerBinding));
163
- exports.default = ExpressBinding;
@@ -1,65 +0,0 @@
1
- /// <reference types="node" />
2
- import { Request, Response, Router } from 'express';
3
- import { Scope } from '../models/connect';
4
- import { EventEmitter } from 'events';
5
- import Webhook, { WebhookTriggers } from '../models/webhook';
6
- import { WebhookDelta } from '../models/webhook-notification';
7
- import AccessToken from '../models/access-token';
8
- import Nylas from '../nylas';
9
- import { OpenWebhookTunnelOptions } from '../services/tunnel';
10
- import { BuildAuthUrl, ExchangeCodeForToken, VerifyWebhookSignature } from '../services/routes';
11
- declare type Middleware = Router;
12
- declare type ServerRequest = Request;
13
- declare type ServerResponse = Response;
14
- declare type ExchangeMailboxTokenCallback = (accessToken: AccessToken, res: ServerResponse) => void;
15
- declare type CsrfTokenExchangeOptions = {
16
- generateCsrfToken: (req: ServerRequest) => Promise<string>;
17
- validateCsrfToken: (csrfToken: string, req: ServerRequest) => Promise<boolean>;
18
- };
19
- declare type OverridePaths = {
20
- buildAuthUrl?: string;
21
- exchangeCodeForToken?: string;
22
- webhooks?: string;
23
- };
24
- export declare type ServerBindingOptions = {
25
- defaultScopes: Scope[];
26
- exchangeMailboxTokenCallback: ExchangeMailboxTokenCallback;
27
- csrfTokenExchangeOpts?: CsrfTokenExchangeOptions;
28
- clientUri?: string;
29
- overridePaths?: OverridePaths;
30
- };
31
- export declare abstract class ServerBinding extends EventEmitter implements ServerBindingOptions {
32
- nylasClient: Nylas;
33
- defaultScopes: Scope[];
34
- exchangeMailboxTokenCallback: ExchangeMailboxTokenCallback;
35
- csrfTokenExchangeOpts?: CsrfTokenExchangeOptions;
36
- clientUri?: string;
37
- overridePaths?: OverridePaths;
38
- static NYLAS_SIGNATURE_HEADER: string;
39
- protected buildAuthUrl: BuildAuthUrl;
40
- protected exchangeCodeForToken: ExchangeCodeForToken;
41
- protected verifyWebhookSignature: VerifyWebhookSignature;
42
- private _untypedOn;
43
- private _untypedEmit;
44
- protected constructor(nylasClient: Nylas, options: ServerBindingOptions);
45
- abstract buildMiddleware(): Middleware;
46
- on: <K extends WebhookTriggers>(event: K, listener: (payload: WebhookDelta) => void) => this;
47
- emit: <K extends WebhookTriggers>(event: K, payload: WebhookDelta) => boolean;
48
- /**
49
- * Emit all incoming delta events
50
- * @param deltas The list of delta JSON objects
51
- */
52
- emitDeltaEvents(deltas: Record<string, unknown>[]): void;
53
- /**
54
- * Start a local development websocket to get webhook events
55
- * @param webhookTunnelConfig Optional configuration for setting region, triggers, and overriding callbacks
56
- * @return The webhook details response from the API
57
- */
58
- startDevelopmentWebsocket(webhookTunnelConfig?: Partial<OpenWebhookTunnelOptions>): Promise<Webhook>;
59
- /**
60
- * Delta event processor to be used either by websocket or webhook
61
- * @param d The delta event
62
- */
63
- protected handleDeltaEvent: (d: WebhookDelta) => void;
64
- }
65
- export {};
@@ -1,87 +0,0 @@
1
- "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- extendStatics(d, b);
11
- function __() { this.constructor = d; }
12
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
13
- };
14
- })();
15
- Object.defineProperty(exports, "__esModule", { value: true });
16
- var events_1 = require("events");
17
- var webhook_notification_1 = require("../models/webhook-notification");
18
- var tunnel_1 = require("../services/tunnel");
19
- var routes_1 = require("../services/routes");
20
- var ServerBinding = /** @class */ (function (_super) {
21
- __extends(ServerBinding, _super);
22
- function ServerBinding(nylasClient, options) {
23
- var _a;
24
- var _this = _super.call(this) || this;
25
- _this._untypedOn = _this.on;
26
- _this._untypedEmit = _this.emit;
27
- // Taken from the best StackOverflow answer of all time https://stackoverflow.com/a/56228127
28
- _this.on = function (event, listener) { return _this._untypedOn(event, listener); };
29
- _this.emit = function (event, payload) { return _this._untypedEmit(event, payload); };
30
- /**
31
- * Delta event processor to be used either by websocket or webhook
32
- * @param d The delta event
33
- */
34
- _this.handleDeltaEvent = function (d) {
35
- d.type && _this.emit(d.type, d);
36
- };
37
- _this.nylasClient = nylasClient;
38
- _this.defaultScopes = options.defaultScopes;
39
- _this.exchangeMailboxTokenCallback = options.exchangeMailboxTokenCallback;
40
- _this.csrfTokenExchangeOpts = options.csrfTokenExchangeOpts;
41
- _this.clientUri = options.clientUri;
42
- (_a = routes_1.Routes(nylasClient), _this.buildAuthUrl = _a.buildAuthUrl, _this.exchangeCodeForToken = _a.exchangeCodeForToken, _this.verifyWebhookSignature = _a.verifyWebhookSignature);
43
- _this.overridePaths = options.overridePaths;
44
- return _this;
45
- }
46
- /**
47
- * Emit all incoming delta events
48
- * @param deltas The list of delta JSON objects
49
- */
50
- ServerBinding.prototype.emitDeltaEvents = function (deltas) {
51
- var _this = this;
52
- deltas.forEach(function (d) { return _this.handleDeltaEvent(new webhook_notification_1.WebhookDelta().fromJSON(d)); });
53
- };
54
- /**
55
- * Start a local development websocket to get webhook events
56
- * @param webhookTunnelConfig Optional configuration for setting region, triggers, and overriding callbacks
57
- * @return The webhook details response from the API
58
- */
59
- ServerBinding.prototype.startDevelopmentWebsocket = function (webhookTunnelConfig) {
60
- /* eslint-disable no-console */
61
- var defaultOnClose = function () {
62
- return console.log('Nylas websocket client connection closed');
63
- };
64
- var defaultOnConnectFail = function (e) {
65
- return console.log('Failed to connect Nylas websocket client', e.message);
66
- };
67
- var defaultOnError = function (e) {
68
- return console.log('Error in Nylas websocket client', e.message);
69
- };
70
- var defaultOnConnect = function () {
71
- return console.log('Nylas websocket client connected');
72
- };
73
- /* eslint-enable no-console */
74
- return tunnel_1.openWebhookTunnel(this.nylasClient, {
75
- onMessage: (webhookTunnelConfig === null || webhookTunnelConfig === void 0 ? void 0 : webhookTunnelConfig.onMessage) || this.handleDeltaEvent,
76
- onClose: (webhookTunnelConfig === null || webhookTunnelConfig === void 0 ? void 0 : webhookTunnelConfig.onClose) || defaultOnClose,
77
- onConnectFail: (webhookTunnelConfig === null || webhookTunnelConfig === void 0 ? void 0 : webhookTunnelConfig.onConnectFail) || defaultOnConnectFail,
78
- onError: (webhookTunnelConfig === null || webhookTunnelConfig === void 0 ? void 0 : webhookTunnelConfig.onError) || defaultOnError,
79
- onConnect: (webhookTunnelConfig === null || webhookTunnelConfig === void 0 ? void 0 : webhookTunnelConfig.onConnect) || defaultOnConnect,
80
- region: webhookTunnelConfig === null || webhookTunnelConfig === void 0 ? void 0 : webhookTunnelConfig.region,
81
- triggers: webhookTunnelConfig === null || webhookTunnelConfig === void 0 ? void 0 : webhookTunnelConfig.triggers,
82
- });
83
- };
84
- ServerBinding.NYLAS_SIGNATURE_HEADER = 'x-nylas-signature';
85
- return ServerBinding;
86
- }(events_1.EventEmitter));
87
- exports.ServerBinding = ServerBinding;
@@ -1,26 +0,0 @@
1
- /// <reference types="node" />
2
- import { Scope } from '../models/connect';
3
- import Nylas from '../nylas';
4
- import AccessToken from '../models/access-token';
5
- export declare enum DefaultPaths {
6
- buildAuthUrl = "/nylas/generate-auth-url",
7
- exchangeCodeForToken = "/nylas/exchange-mailbox-token",
8
- webhooks = "/nylas/webhook"
9
- }
10
- export declare type BuildAuthUrl = (options: BuildAuthUrlOptions) => Promise<string>;
11
- export declare type ExchangeCodeForToken = (code: string) => Promise<AccessToken>;
12
- export declare type VerifyWebhookSignature = (nylasSignature: string, rawBody: Buffer) => boolean;
13
- export declare type BuildAuthUrlOptions = {
14
- scopes: Scope[];
15
- emailAddress: string;
16
- successUrl: string;
17
- clientUri?: string;
18
- state?: string;
19
- };
20
- declare type Routes = {
21
- buildAuthUrl: BuildAuthUrl;
22
- exchangeCodeForToken: ExchangeCodeForToken;
23
- verifyWebhookSignature: VerifyWebhookSignature;
24
- };
25
- export declare const Routes: (nylasClient: Nylas) => Routes;
26
- export default Routes;
@@ -1,95 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (_) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- var __importDefault = (this && this.__importDefault) || function (mod) {
39
- return (mod && mod.__esModule) ? mod : { "default": mod };
40
- };
41
- Object.defineProperty(exports, "__esModule", { value: true });
42
- var crypto_1 = __importDefault(require("crypto"));
43
- var DefaultPaths;
44
- (function (DefaultPaths) {
45
- DefaultPaths["buildAuthUrl"] = "/nylas/generate-auth-url";
46
- DefaultPaths["exchangeCodeForToken"] = "/nylas/exchange-mailbox-token";
47
- DefaultPaths["webhooks"] = "/nylas/webhook";
48
- })(DefaultPaths = exports.DefaultPaths || (exports.DefaultPaths = {}));
49
- exports.Routes = function (nylasClient) {
50
- /**
51
- * Build the URL for authenticating users to your application via Hosted Authentication
52
- * @param options Configuration for the authentication process
53
- * @return The URL for hosted authentication
54
- */
55
- var buildAuthUrl = function (options) { return __awaiter(void 0, void 0, void 0, function () {
56
- var scopes, emailAddress, successUrl, clientUri, state;
57
- return __generator(this, function (_a) {
58
- scopes = options.scopes, emailAddress = options.emailAddress, successUrl = options.successUrl, clientUri = options.clientUri, state = options.state;
59
- return [2 /*return*/, nylasClient.urlForAuthentication({
60
- loginHint: emailAddress,
61
- redirectURI: (clientUri || '') + successUrl,
62
- scopes: scopes,
63
- state: state,
64
- })];
65
- });
66
- }); };
67
- /**
68
- * Exchange an authorization code for an access token
69
- * @param code One-time authorization code from Nylas
70
- * @param callback Callback before returning the access token
71
- * @return The {@link AccessToken} object containing the access token and other information
72
- */
73
- var exchangeCodeForToken = function (code, callback) { return __awaiter(void 0, void 0, void 0, function () {
74
- return __generator(this, function (_a) {
75
- switch (_a.label) {
76
- case 0: return [4 /*yield*/, nylasClient.exchangeCodeForToken(code, callback)];
77
- case 1: return [2 /*return*/, _a.sent()];
78
- }
79
- });
80
- }); };
81
- /**
82
- * Verify incoming webhook signature came from Nylas
83
- * @param nylasSignature The signature to verify
84
- * @param rawBody The raw body from the payload
85
- * @return true if the webhook signature was verified from Nylas
86
- */
87
- var verifyWebhookSignature = function (nylasSignature, rawBody) {
88
- var digest = crypto_1.default
89
- .createHmac('sha256', nylasClient.clientSecret)
90
- .update(rawBody)
91
- .digest('hex');
92
- return digest === nylasSignature;
93
- };
94
- return { buildAuthUrl: buildAuthUrl, exchangeCodeForToken: exchangeCodeForToken, verifyWebhookSignature: verifyWebhookSignature };
95
- };