@nangohq/node 0.29.5 → 0.29.6

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 (2) hide show
  1. package/dist/index.cjs +372 -0
  2. package/package.json +1 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,372 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // lib/index.ts
31
+ var lib_exports = {};
32
+ __export(lib_exports, {
33
+ Nango: () => Nango,
34
+ SyncType: () => SyncType,
35
+ prodHost: () => prodHost,
36
+ stagingHost: () => stagingHost
37
+ });
38
+ module.exports = __toCommonJS(lib_exports);
39
+ var import_axios = __toESM(require("axios"), 1);
40
+
41
+ // lib/utils.ts
42
+ var validateProxyConfiguration = (config) => {
43
+ const requiredParams = ["endpoint", "providerConfigKey", "connectionId"];
44
+ requiredParams.forEach((param) => {
45
+ if (typeof config[param] === "undefined") {
46
+ throw new Error(`${param} is missing and is required to make a proxy call!`);
47
+ }
48
+ });
49
+ };
50
+ var validateSyncRecordConfiguration = (config) => {
51
+ const requiredParams = ["model", "providerConfigKey", "connectionId"];
52
+ requiredParams.forEach((param) => {
53
+ if (typeof config[param] === "undefined") {
54
+ throw new Error(`${param} is missing and is required to make a proxy call!`);
55
+ }
56
+ });
57
+ };
58
+
59
+ // lib/index.ts
60
+ var stagingHost = "https://api-staging.nango.dev";
61
+ var prodHost = "https://api.nango.dev";
62
+ var SyncType = /* @__PURE__ */ ((SyncType2) => {
63
+ SyncType2["INITIAL"] = "INITIAL";
64
+ SyncType2["INCREMENTAL"] = "INCREMENTAL";
65
+ return SyncType2;
66
+ })(SyncType || {});
67
+ var Nango = class {
68
+ serverUrl;
69
+ secretKey;
70
+ connectionId;
71
+ providerConfigKey;
72
+ isSync = false;
73
+ dryRun = false;
74
+ activityLogId;
75
+ constructor(config) {
76
+ config.host = config.host || prodHost;
77
+ this.serverUrl = config.host;
78
+ if (this.serverUrl.slice(-1) === "/") {
79
+ this.serverUrl = this.serverUrl.slice(0, -1);
80
+ }
81
+ if (!config.secretKey) {
82
+ throw new Error("You must specify a secret key (cf. documentation).");
83
+ }
84
+ try {
85
+ new URL(this.serverUrl);
86
+ } catch (err) {
87
+ throw new Error(`Invalid URL provided for the Nango host: ${this.serverUrl}`);
88
+ }
89
+ this.secretKey = config.secretKey;
90
+ this.connectionId = config.connectionId || "";
91
+ this.providerConfigKey = config.providerConfigKey || "";
92
+ if (config.isSync) {
93
+ this.isSync = config.isSync;
94
+ }
95
+ if (config.dryRun) {
96
+ this.dryRun = config.dryRun;
97
+ }
98
+ if (config.activityLogId) {
99
+ this.activityLogId = config.activityLogId;
100
+ }
101
+ }
102
+ /**
103
+ * For OAuth 2: returns the access token directly as a string.
104
+ * For OAuth 2: If you want to obtain a new refresh token from the provider before the current token has expired,
105
+ * you can set the forceRefresh argument to true."
106
+ * For OAuth 1: returns an object with 'oAuthToken' and 'oAuthTokenSecret' fields.
107
+ * @param providerConfigKey - This is the unique Config Key for the integration
108
+ * @param connectionId - This is the unique connection identifier used to identify this connection
109
+ * @param [forceRefresh] - When set, this is used to obtain a new refresh token from the provider before the current token has expired,
110
+ * you can set the forceRefresh argument to true.
111
+ * */
112
+ async getToken(providerConfigKey, connectionId, forceRefresh) {
113
+ const response = await this.getConnectionDetails(providerConfigKey, connectionId, forceRefresh);
114
+ switch (response.data.credentials.type) {
115
+ case "OAUTH2" /* OAuth2 */:
116
+ return response.data.credentials.access_token;
117
+ case "OAUTH1" /* OAuth1 */:
118
+ return { oAuthToken: response.data.credentials.oauth_token, oAuthTokenSecret: response.data.credentials.oauth_token_secret };
119
+ default:
120
+ return response.data.credentials;
121
+ }
122
+ }
123
+ /**
124
+ * Get the full (fresh) credentials payload returned by the external API,
125
+ * which also contains access credentials.
126
+ * @param providerConfigKey - This is the unique Config Key for the integration
127
+ * @param connectionId - This is the unique connection identifier used to identify this connection
128
+ * @param [forceRefresh] - When set, this is used to obtain a new refresh token from the provider before the current token has expired,
129
+ * you can set the forceRefresh argument to true.
130
+ * */
131
+ async getRawTokenResponse(providerConfigKey, connectionId, forceRefresh) {
132
+ const response = await this.getConnectionDetails(providerConfigKey, connectionId, forceRefresh);
133
+ const credentials = response.data.credentials;
134
+ return credentials.raw;
135
+ }
136
+ /**
137
+ * Get the Connection object, which also contains access credentials and full credentials payload
138
+ * returned by the external API.
139
+ * @param providerConfigKey - This is the unique Config Key for the integration
140
+ * @param connectionId - This is the unique connection identifier used to identify this connection
141
+ * @param [forceRefresh] - When set, this is used to obtain a new refresh token from the provider before the current token has expired,
142
+ * you can set the forceRefresh argument to true.
143
+ * @param [refreshToken] - When set this returns the refresh token as part of the response
144
+ */
145
+ async getConnection(providerConfigKey, connectionId, forceRefresh, refreshToken) {
146
+ const response = await this.getConnectionDetails(providerConfigKey, connectionId, forceRefresh, refreshToken);
147
+ return response.data;
148
+ }
149
+ async proxy(config) {
150
+ if (!config.connectionId && this.connectionId) {
151
+ config.connectionId = this.connectionId;
152
+ }
153
+ if (!config.providerConfigKey && this.providerConfigKey) {
154
+ config.providerConfigKey = this.providerConfigKey;
155
+ }
156
+ validateProxyConfiguration(config);
157
+ const { providerConfigKey, connectionId, method, retries, headers: customHeaders, baseUrlOverride } = config;
158
+ const url = `${this.serverUrl}/proxy${config.endpoint[0] === "/" ? "" : "/"}${config.endpoint}`;
159
+ const customPrefixedHeaders = customHeaders && Object.keys(customHeaders).length > 0 ? Object.keys(customHeaders).reduce((acc, key) => {
160
+ acc[`Nango-Proxy-${key}`] = customHeaders[key];
161
+ return acc;
162
+ }, {}) : {};
163
+ const headers = {
164
+ "Connection-Id": connectionId,
165
+ "Provider-Config-Key": providerConfigKey,
166
+ "Base-Url-Override": baseUrlOverride || "",
167
+ "Nango-Is-Sync": this.isSync,
168
+ "Nango-Is-Dry-Run": this.dryRun,
169
+ "Nango-Activity-Log-Id": this.activityLogId || "",
170
+ ...customPrefixedHeaders
171
+ };
172
+ if (retries) {
173
+ headers["Retries"] = retries;
174
+ }
175
+ const options = {
176
+ headers: this.enrichHeaders(headers)
177
+ };
178
+ if (config.params) {
179
+ options.params = config.params;
180
+ }
181
+ if (config.paramsSerializer) {
182
+ options.paramsSerializer = config.paramsSerializer;
183
+ }
184
+ if (this.dryRun) {
185
+ console.log(`Nango Proxy Request: ${method?.toUpperCase()} ${url}`);
186
+ }
187
+ if (method?.toUpperCase() === "POST") {
188
+ return import_axios.default.post(url, config.data, options);
189
+ } else if (method?.toUpperCase() === "PATCH") {
190
+ return import_axios.default.patch(url, config.data, options);
191
+ } else if (method?.toUpperCase() === "PUT") {
192
+ return import_axios.default.put(url, config.data, options);
193
+ } else if (method?.toUpperCase() === "DELETE") {
194
+ return import_axios.default.delete(url, options);
195
+ } else {
196
+ return import_axios.default.get(url, options);
197
+ }
198
+ }
199
+ async get(config) {
200
+ return this.proxy({
201
+ ...config,
202
+ method: "GET"
203
+ });
204
+ }
205
+ async post(config) {
206
+ return this.proxy({
207
+ ...config,
208
+ method: "POST"
209
+ });
210
+ }
211
+ async patch(config) {
212
+ return this.proxy({
213
+ ...config,
214
+ method: "PATCH"
215
+ });
216
+ }
217
+ async delete(config) {
218
+ return this.proxy({
219
+ ...config,
220
+ method: "DELETE"
221
+ });
222
+ }
223
+ async getRecords(config) {
224
+ const { connectionId, providerConfigKey, model, delta, offset, limit, includeNangoMetadata } = config;
225
+ validateSyncRecordConfiguration(config);
226
+ const order = config?.order === "asc" ? "asc" : "desc";
227
+ let sortBy = "id";
228
+ switch (config.sortBy) {
229
+ case "createdAt":
230
+ sortBy = "created_at";
231
+ break;
232
+ case "updatedAt":
233
+ sortBy = "updated_at";
234
+ break;
235
+ }
236
+ let filter = "";
237
+ switch (config.filter) {
238
+ case "deleted":
239
+ filter = "deleted";
240
+ break;
241
+ case "updated":
242
+ filter = "updated";
243
+ break;
244
+ case "added":
245
+ filter = "added";
246
+ break;
247
+ }
248
+ const includeMetadata = includeNangoMetadata || false;
249
+ const url = `${this.serverUrl}/sync/records/?model=${model}&order=${order}&delta=${delta || ""}&offset=${offset || ""}&limit=${limit || ""}&sort_by=${sortBy || ""}&include_nango_metadata=${includeMetadata}&filter=${filter}`;
250
+ const headers = {
251
+ "Connection-Id": connectionId,
252
+ "Provider-Config-Key": providerConfigKey
253
+ };
254
+ const options = {
255
+ headers: this.enrichHeaders(headers)
256
+ };
257
+ const response = await import_axios.default.get(url, options);
258
+ return response.data;
259
+ }
260
+ async getConnectionDetails(providerConfigKey, connectionId, forceRefresh = false, refreshToken = false, additionalHeader = {}) {
261
+ const url = `${this.serverUrl}/connection/${connectionId}`;
262
+ const headers = {
263
+ "Content-Type": "application/json",
264
+ "Accept-Encoding": "application/json"
265
+ };
266
+ if (additionalHeader) {
267
+ Object.assign(headers, additionalHeader);
268
+ }
269
+ const params = {
270
+ provider_config_key: providerConfigKey,
271
+ force_refresh: forceRefresh,
272
+ refresh_token: refreshToken
273
+ };
274
+ return import_axios.default.get(url, { params, headers: this.enrichHeaders(headers) });
275
+ }
276
+ /**
277
+ * Get the list of Connections, which does not contain access credentials.
278
+ */
279
+ async listConnections(connectionId) {
280
+ const response = await this.listConnectionDetails(connectionId);
281
+ return response.data;
282
+ }
283
+ async getIntegration(providerConfigKey, includeIntegrationCredetials = false) {
284
+ const url = `${this.serverUrl}/config/${providerConfigKey}`;
285
+ const response = await import_axios.default.get(url, { headers: this.enrichHeaders({}), params: { include_creds: includeIntegrationCredetials } });
286
+ return response.data;
287
+ }
288
+ async setMetadata(providerConfigKey, connectionId, metadata) {
289
+ if (!providerConfigKey) {
290
+ throw new Error("Provider Config Key is required");
291
+ }
292
+ if (!connectionId) {
293
+ throw new Error("Connection Id is required");
294
+ }
295
+ if (!metadata) {
296
+ throw new Error("Metadata is required");
297
+ }
298
+ const url = `${this.serverUrl}/connection/${connectionId}/metadata?provider_config_key=${providerConfigKey}`;
299
+ const headers = {
300
+ "Provider-Config-Key": providerConfigKey
301
+ };
302
+ return import_axios.default.post(url, metadata, { headers: this.enrichHeaders(headers) });
303
+ }
304
+ async setFieldMapping(_fieldMapping, _optionalProviderConfigKey, _optionalConnectionId) {
305
+ throw new Error("setFieldMapping is deprecated. Please use setMetadata instead.");
306
+ }
307
+ async getMetadata(providerConfigKey, connectionId) {
308
+ if (!providerConfigKey) {
309
+ throw new Error("Provider Config Key is required");
310
+ }
311
+ if (!connectionId) {
312
+ throw new Error("Connection Id is required");
313
+ }
314
+ const response = await this.getConnectionDetails(providerConfigKey, connectionId, false, false, {
315
+ "Nango-Is-Sync": true,
316
+ "Nango-Is-Dry-Run": this.dryRun
317
+ });
318
+ return response.data.metadata;
319
+ }
320
+ async getFieldMapping(_optionalProviderConfigKey, _optionalConnectionId) {
321
+ throw new Error("getFieldMapping is deprecated. Please use getMetadata instead.");
322
+ }
323
+ async triggerSync(providerConfigKey, connectionId, syncs) {
324
+ const url = `${this.serverUrl}/sync/trigger`;
325
+ const headers = {
326
+ "Connection-Id": connectionId,
327
+ "Provider-Config-Key": providerConfigKey
328
+ };
329
+ if (typeof syncs === "string") {
330
+ throw new Error("Syncs must be an array of strings. If it is a single sync, please wrap it in an array.");
331
+ }
332
+ const body = {
333
+ syncs: syncs || []
334
+ };
335
+ return import_axios.default.post(url, body, { headers: this.enrichHeaders(headers) });
336
+ }
337
+ async createConnection(_connectionArgs) {
338
+ throw new Error(
339
+ "This method has been deprecated, please use the REST API to create a connection. See https://docs.nango.dev/api-reference/connection/post"
340
+ );
341
+ }
342
+ async deleteConnection(providerConfigKey, connectionId) {
343
+ const url = `${this.serverUrl}/connection/${connectionId}?provider_config_key=${providerConfigKey}`;
344
+ const headers = {
345
+ "Content-Type": "application/json",
346
+ "Accept-Encoding": "application/json"
347
+ };
348
+ return import_axios.default.delete(url, { headers: this.enrichHeaders(headers) });
349
+ }
350
+ async listConnectionDetails(connectionId) {
351
+ let url = `${this.serverUrl}/connection?`;
352
+ if (connectionId) {
353
+ url = url.concat(`connectionId=${connectionId}`);
354
+ }
355
+ const headers = {
356
+ "Content-Type": "application/json",
357
+ "Accept-Encoding": "application/json"
358
+ };
359
+ return import_axios.default.get(url, { headers: this.enrichHeaders(headers) });
360
+ }
361
+ enrichHeaders(headers = {}) {
362
+ headers["Authorization"] = "Bearer " + this.secretKey;
363
+ return headers;
364
+ }
365
+ };
366
+ // Annotate the CommonJS export names for ESM import in node:
367
+ 0 && (module.exports = {
368
+ Nango,
369
+ SyncType,
370
+ prodHost,
371
+ stagingHost
372
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nangohq/node",
3
- "version": "0.29.5",
3
+ "version": "0.29.6",
4
4
  "description": "Nango's Node client.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",