@fsai-flow/core 0.0.5 → 0.1.1

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 (92) hide show
  1. package/dist/index.d.ts +17 -0
  2. package/dist/index.js +61 -0
  3. package/dist/lib/ActiveWebhooks.d.ts +59 -0
  4. package/dist/lib/ActiveWebhooks.js +177 -0
  5. package/dist/lib/ActiveWorkflows.d.ts +87 -0
  6. package/dist/lib/ActiveWorkflows.js +465 -0
  7. package/dist/lib/BinaryDataManager/FileSystem.d.ts +26 -0
  8. package/dist/lib/BinaryDataManager/FileSystem.js +180 -0
  9. package/dist/lib/BinaryDataManager/index.d.ts +21 -0
  10. package/dist/lib/BinaryDataManager/index.js +129 -0
  11. package/dist/lib/ChangeCase.d.ts +9 -0
  12. package/dist/lib/ChangeCase.js +43 -0
  13. package/dist/lib/Constants.d.ts +14 -0
  14. package/dist/lib/Constants.js +18 -0
  15. package/dist/lib/Credentials.d.ts +27 -0
  16. package/dist/lib/Credentials.js +88 -0
  17. package/dist/lib/FileSystem.d.ts +26 -0
  18. package/dist/lib/FileSystem.js +180 -0
  19. package/dist/lib/InputConnectionDataLegacy.d.ts +2 -0
  20. package/dist/lib/InputConnectionDataLegacy.js +72 -0
  21. package/dist/lib/Interfaces.d.ts +147 -0
  22. package/dist/lib/Interfaces.js +2 -0
  23. package/dist/lib/LoadNodeParameterOptions.d.ts +39 -0
  24. package/dist/lib/LoadNodeParameterOptions.js +152 -0
  25. package/dist/lib/NodeExecuteFunctions.d.ts +225 -0
  26. package/dist/lib/NodeExecuteFunctions.js +2467 -0
  27. package/dist/lib/NodesLoader/constants.d.ts +5 -0
  28. package/dist/lib/NodesLoader/constants.js +105 -0
  29. package/dist/lib/NodesLoader/custom-directory-loader.d.ts +9 -0
  30. package/dist/lib/NodesLoader/custom-directory-loader.js +35 -0
  31. package/dist/lib/NodesLoader/directory-loader.d.ts +66 -0
  32. package/dist/lib/NodesLoader/directory-loader.js +367 -0
  33. package/dist/lib/NodesLoader/index.d.ts +5 -0
  34. package/dist/lib/NodesLoader/index.js +11 -0
  35. package/dist/lib/NodesLoader/lazy-package-directory-loader.d.ts +7 -0
  36. package/dist/lib/NodesLoader/lazy-package-directory-loader.js +44 -0
  37. package/dist/lib/NodesLoader/load-class-in-isolation.d.ts +1 -0
  38. package/dist/lib/NodesLoader/load-class-in-isolation.js +17 -0
  39. package/dist/lib/NodesLoader/package-directory-loader.d.ts +17 -0
  40. package/dist/lib/NodesLoader/package-directory-loader.js +92 -0
  41. package/dist/lib/NodesLoader/types.d.ts +14 -0
  42. package/dist/lib/NodesLoader/types.js +2 -0
  43. package/dist/lib/RedisLeaderElectionManager.d.ts +53 -0
  44. package/dist/lib/RedisLeaderElectionManager.js +279 -0
  45. package/dist/lib/RequestTypes.d.ts +58 -0
  46. package/dist/lib/RequestTypes.js +8 -0
  47. package/dist/lib/UserSettings.d.ts +80 -0
  48. package/dist/lib/UserSettings.js +269 -0
  49. package/dist/lib/WorkflowExecute.d.ts +53 -0
  50. package/dist/lib/WorkflowExecute.js +906 -0
  51. package/dist/lib/index.d.ts +21 -0
  52. package/dist/lib/index.js +129 -0
  53. package/dist/utils/crypto.d.ts +1 -0
  54. package/dist/utils/crypto.js +7 -0
  55. package/package.json +52 -52
  56. package/dist/README.md +0 -31
  57. package/dist/package.json +0 -54
  58. package/eslint.config.js +0 -19
  59. package/jest.config.ts +0 -10
  60. package/project.json +0 -19
  61. package/src/index.ts +0 -28
  62. package/src/lib/ActiveWebhooks.ts +0 -245
  63. package/src/lib/ActiveWorkflows.ts +0 -575
  64. package/src/lib/BinaryDataManager/FileSystem.ts +0 -214
  65. package/src/lib/BinaryDataManager/index.ts +0 -187
  66. package/src/lib/ChangeCase.ts +0 -45
  67. package/src/lib/Constants.ts +0 -16
  68. package/src/lib/Credentials.ts +0 -108
  69. package/src/lib/FileSystem.ts +0 -214
  70. package/src/lib/InputConnectionDataLegacy.ts +0 -123
  71. package/src/lib/Interfaces.ts +0 -338
  72. package/src/lib/LoadNodeParameterOptions.ts +0 -235
  73. package/src/lib/NodeExecuteFunctions.ts +0 -3700
  74. package/src/lib/NodesLoader/constants.ts +0 -112
  75. package/src/lib/NodesLoader/custom-directory-loader.ts +0 -31
  76. package/src/lib/NodesLoader/directory-loader.ts +0 -458
  77. package/src/lib/NodesLoader/index.ts +0 -5
  78. package/src/lib/NodesLoader/lazy-package-directory-loader.ts +0 -55
  79. package/src/lib/NodesLoader/load-class-in-isolation.ts +0 -19
  80. package/src/lib/NodesLoader/package-directory-loader.ts +0 -107
  81. package/src/lib/NodesLoader/types.ts +0 -14
  82. package/src/lib/RedisLeaderElectionManager.ts +0 -334
  83. package/src/lib/UserSettings.ts +0 -292
  84. package/src/lib/WorkflowExecute.ts +0 -1128
  85. package/src/lib/index.ts +0 -187
  86. package/src/utils/crypto.ts +0 -5
  87. package/tests/Credentials.test.ts +0 -88
  88. package/tests/Helpers.ts +0 -808
  89. package/tests/WorkflowExecute.test.ts +0 -1242
  90. package/tsconfig.json +0 -41
  91. package/tsconfig.lib.json +0 -10
  92. package/tsconfig.spec.json +0 -14
@@ -1,3700 +0,0 @@
1
- import {
2
- GenericValue,
3
- IAdditionalCredentialOptions,
4
- IAllExecuteFunctions,
5
- IBinaryData,
6
- IContextObject,
7
- ICredentialDataDecryptedObject,
8
- ICredentialsExpressionResolveValues,
9
- IDataObject,
10
- IExecuteFunctions,
11
- IExecuteResponsePromiseData,
12
- IExecuteSingleFunctions,
13
- IExecuteWorkflowInfo,
14
- IHttpRequestOptions,
15
- IN8nHttpFullResponse,
16
- IN8nHttpResponse,
17
- INode,
18
- INodeCredentialDescription,
19
- INodeCredentialsDetails,
20
- INodeExecutionData,
21
- INodeParameters,
22
- INodeType,
23
- IOAuth2Options,
24
- IPollFunctions,
25
- IRunExecutionData,
26
- ITaskDataConnections,
27
- ITriggerFunctions,
28
- IWebhookData,
29
- IWebhookDescription,
30
- IWebhookFunctions,
31
- IWorkflowDataProxyAdditionalKeys,
32
- IWorkflowDataProxyData,
33
- IWorkflowExecuteAdditionalData,
34
- IWorkflowMetadata,
35
- NodeApiError,
36
- NodeHelpers,
37
- NodeOperationError,
38
- NodeParameterValue,
39
- Workflow,
40
- WorkflowActivateMode,
41
- WorkflowDataProxy,
42
- WorkflowExecuteMode,
43
- LoggerProxy as Logger,
44
- JsonObject,
45
- NodeParameterValueType,
46
- IGetNodeParameterOptions,
47
- NodeTypeAndVersion,
48
- IExecuteData,
49
- ISupplyDataFunctions,
50
- NodeConnectionType,
51
- ExecutionError,
52
- ITaskMetadata,
53
- INodeInputConfiguration,
54
- INodeTypeDescription,
55
- SupplyData,
56
- CloseFunction,
57
- AiEvent,
58
- AINodeConnectionType,
59
- ITaskData,
60
- } from '@fsai-flow/workflow';
61
-
62
- import { Agent } from 'https';
63
- import { stringify } from 'qs';
64
- const clientOAuth1 = require('oauth-1.0a');
65
- import { Token } from 'oauth-1.0a';
66
-
67
- import ClientOAuth2, { Data, RequestObject } from 'client-oauth2';
68
- import { AuthorizationCode, ClientCredentials, AccessToken, ModuleOptions } from 'simple-oauth2';
69
-
70
- import * as crypto from 'crypto';
71
- import * as url from 'url';
72
- import { get } from 'lodash';
73
- import { Request, Response } from 'express';
74
- const FormData = require('form-data');
75
- import * as path from 'path';
76
- import { OptionsWithUri, OptionsWithUrl } from 'request';
77
- import * as requestPromise from 'request-promise-native';
78
- import { createHmac } from 'crypto';
79
- import { fromBuffer } from 'file-type';
80
- import { lookup } from 'mime-types';
81
-
82
-
83
- import axios, {
84
- AxiosPromise,
85
- AxiosProxyConfig,
86
- AxiosRequestConfig,
87
- AxiosResponse,
88
- Method,
89
- } from 'axios';
90
- import { URL, URLSearchParams } from 'url';
91
- import { BinaryDataManager } from './BinaryDataManager';
92
- import {
93
- ICredentialTestFunctions,
94
- IHookFunctions,
95
- ILoadOptionsFunctions,
96
- IResponseError,
97
- IWorkflowSettings,
98
- PLACEHOLDER_EMPTY_EXECUTION_ID,
99
- } from '..';
100
- import { arrayBuffer } from 'stream/consumers';
101
- import { promises as fs } from 'fs';
102
-
103
- axios.defaults.timeout = 900000;
104
- // Prevent axios from adding x-form-www-urlencoded headers by default
105
- axios.defaults.headers.post = {};
106
- axios.defaults.headers.put = {};
107
- axios.defaults.headers.patch = {};
108
- axios.defaults.paramsSerializer = (params) => {
109
- if (params instanceof URLSearchParams) {
110
- return params.toString();
111
- }
112
- return stringify(params, { arrayFormat: 'indices' });
113
- };
114
-
115
- const pushFormDataValue = (form: FormData, key: string, value: any) => {
116
- // eslint-disable-next-line no-prototype-builtins
117
- if (value?.hasOwnProperty('value') && Object.prototype.hasOwnProperty.call(value, 'options')) {
118
- // @ts-ignore
119
- form.append(key, value.value, value.options);
120
- } else {
121
- form.append(key, value);
122
- }
123
- };
124
-
125
- const createFormDataObject = (data: object) => {
126
- const formData = new FormData();
127
- const keys = Object.keys(data);
128
- keys.forEach((key) => {
129
- // @ts-ignore
130
- const formField = data[key];
131
-
132
- if (formField instanceof Array) {
133
- formField.forEach((item) => {
134
- pushFormDataValue(formData, key, item);
135
- });
136
- } else {
137
- pushFormDataValue(formData, key, formField);
138
- }
139
- });
140
- return formData;
141
- };
142
-
143
- function searchForHeader(headers: IDataObject, headerName: string) {
144
- if (headers === undefined) {
145
- return undefined;
146
- }
147
-
148
- const headerNames = Object.keys(headers);
149
- headerName = headerName.toLowerCase();
150
- return headerNames.find((thisHeader) => thisHeader.toLowerCase() === headerName);
151
- }
152
-
153
- async function generateContentLengthHeader(formData: any, headers: IDataObject) {
154
- if (!formData || !formData.getLength) {
155
- return;
156
- }
157
- try {
158
- const length = await new Promise((res, rej) => {
159
- formData.getLength((error: Error | null, length: number) => {
160
- if (error) {
161
- rej(error);
162
- return;
163
- }
164
- res(length);
165
- });
166
- });
167
- headers = Object.assign(headers, {
168
- 'content-length': length,
169
- });
170
- } catch (error) {
171
- Logger.error('Unable to calculate form data length', { error });
172
- }
173
- }
174
-
175
- async function parseRequestObject(requestObject: IDataObject) {
176
- // This function is a temporary implementation
177
- // That translates all http requests done via
178
- // the request library to axios directly
179
- // We are not using n8n's interface as it would
180
- // an unnecessary step, considering the `request`
181
- // helper can be deprecated and removed.
182
- const axiosConfig: AxiosRequestConfig = {};
183
-
184
- if (typeof requestObject['headers'] === 'object' && requestObject['headers'] !== null) {
185
- axiosConfig.headers = requestObject['headers'] as any;
186
- }
187
-
188
- // Let's start parsing the hardest part, which is the request body.
189
- // The process here is as following?
190
- // - Check if we have a `content-type` header. If this was set,
191
- // we will follow
192
- // - Check if the `form` property was set. If yes, then it's x-www-form-urlencoded
193
- // - Check if the `formData` property exists. If yes, then it's multipart/form-data
194
- // - Lastly, we should have a regular `body` that is probably a JSON.
195
-
196
- const contentTypeHeaderKeyName =
197
- axiosConfig.headers &&
198
- Object.keys(axiosConfig.headers).find(
199
- (headerName) => headerName.toLowerCase() === 'content-type',
200
- );
201
- const contentType =
202
- contentTypeHeaderKeyName &&
203
- axiosConfig.headers &&
204
- (axiosConfig.headers[contentTypeHeaderKeyName] as unknown as string | undefined);
205
-
206
- if (contentType === 'application/x-www-form-urlencoded' && requestObject['formData'] === undefined) {
207
- // there are nodes incorrectly created, informing the content type header
208
- // and also using formData. Request lib takes precedence for the formData.
209
- // We will do the same.
210
- // Merge body and form properties.
211
- if (typeof requestObject['body'] === 'string') {
212
- axiosConfig.data = requestObject['body'];
213
- } else {
214
- const allData = Object.assign(requestObject['body'] || {}, requestObject['form'] || {}) as Record<
215
- string,
216
- string
217
- >;
218
- if (requestObject['useQuerystring'] === true) {
219
- axiosConfig.data = stringify(allData, { arrayFormat: 'repeat' });
220
- } else {
221
- axiosConfig.data = stringify(allData);
222
- }
223
- }
224
- } else if (contentType && contentType.includes('multipart/form-data') !== false) {
225
- if (requestObject['formData'] !== undefined && requestObject['formData'] instanceof FormData) {
226
- axiosConfig.data = requestObject['formData'];
227
- } else {
228
- const allData = {
229
- ...(requestObject['body'] as object | undefined),
230
- ...(requestObject['formData'] as object | undefined),
231
- };
232
-
233
- axiosConfig.data = createFormDataObject(allData);
234
- }
235
- // replace the existing header with a new one that
236
- // contains the boundary property.
237
- // @ts-ignore
238
- delete axiosConfig.headers[contentTypeHeaderKeyName];
239
- const headers = axiosConfig.data.getHeaders();
240
- axiosConfig.headers = Object.assign(axiosConfig.headers || {}, headers);
241
- if (!axiosConfig.headers) {
242
- axiosConfig.headers = {};
243
- }
244
- await generateContentLengthHeader(axiosConfig.data, axiosConfig.headers as IDataObject);
245
- } else {
246
- // When using the `form` property it means the content should be x-www-form-urlencoded.
247
- if (requestObject['form'] !== undefined && requestObject['body'] === undefined) {
248
- // If we have only form
249
- axiosConfig.data =
250
- typeof requestObject['form'] === 'string'
251
- ? stringify(requestObject['form'], { format: 'RFC3986' })
252
- : stringify(requestObject['form']).toString();
253
-
254
- if (axiosConfig.headers !== undefined) {
255
- const headerName = searchForHeader(axiosConfig.headers, 'content-type');
256
- if (headerName) {
257
- delete axiosConfig.headers[headerName];
258
- }
259
- axiosConfig.headers['Content-Type'] = 'application/x-www-form-urlencoded';
260
- } else {
261
- axiosConfig.headers = {
262
- 'Content-Type': 'application/x-www-form-urlencoded',
263
- };
264
- }
265
- } else if (requestObject['formData'] !== undefined) {
266
- // remove any "content-type" that might exist.
267
- if (axiosConfig.headers !== undefined) {
268
- const headers = Object.keys(axiosConfig.headers);
269
- headers.forEach((header) =>
270
- header.toLowerCase() === 'content-type' && axiosConfig.headers ? delete axiosConfig.headers[header] : null,
271
- );
272
- }
273
-
274
- if (requestObject['formData'] instanceof FormData) {
275
- axiosConfig.data = requestObject['formData'];
276
- } else {
277
- axiosConfig.data = createFormDataObject(requestObject['formData'] as object);
278
- }
279
- // Mix in headers as FormData creates the boundary.
280
- const headers = axiosConfig.data.getHeaders();
281
- axiosConfig.headers = Object.assign(axiosConfig.headers || {}, headers);
282
- await generateContentLengthHeader(axiosConfig.data, axiosConfig.headers as IDataObject);
283
- } else if (requestObject['body'] !== undefined) {
284
- // If we have body and possibly form
285
- if (requestObject['form'] !== undefined) {
286
- // merge both objects when exist.
287
- if (requestObject['body'] && requestObject['form']) {
288
- requestObject['body'] = Object.assign(requestObject['body'], requestObject['form']);
289
- }
290
- }
291
- axiosConfig.data = requestObject['body'] as FormData | GenericValue | GenericValue[];
292
- }
293
- }
294
-
295
- if (requestObject['uri'] !== undefined) {
296
- axiosConfig.url = requestObject['uri']?.toString() as string;
297
- }
298
-
299
- if (requestObject['url'] !== undefined) {
300
- axiosConfig.url = requestObject['url']?.toString() as string;
301
- }
302
-
303
- if (requestObject['baseURL'] !== undefined) {
304
- axiosConfig.baseURL = requestObject['baseURL']?.toString() as string;
305
- }
306
-
307
- if (requestObject['method'] !== undefined) {
308
- axiosConfig.method = requestObject['method'] as Method;
309
- }
310
-
311
- if (requestObject['qs'] !== undefined && Object.keys(requestObject['qs'] as object).length > 0) {
312
- axiosConfig.params = requestObject['qs'] as IDataObject;
313
- }
314
-
315
- if (
316
- requestObject['useQuerystring'] === true ||
317
- // @ts-ignore
318
- requestObject.qsStringifyOptions?.arrayFormat === 'repeat'
319
- ) {
320
- axiosConfig.paramsSerializer = (params) => {
321
- return stringify(params, { arrayFormat: 'repeat' });
322
- };
323
- } else if (requestObject['useQuerystring'] === false) {
324
- axiosConfig.paramsSerializer = (params) => {
325
- return stringify(params, { arrayFormat: 'indices' });
326
- };
327
- }
328
-
329
- // @ts-ignore
330
- if (requestObject.qsStringifyOptions?.arrayFormat === 'brackets') {
331
- axiosConfig.paramsSerializer = (params) => {
332
- return stringify(params, { arrayFormat: 'brackets' });
333
- };
334
- }
335
-
336
- if (requestObject['auth'] !== undefined) {
337
- // Check support for sendImmediately
338
- if ((requestObject['auth'] as IDataObject)['bearer'] !== undefined) {
339
- axiosConfig.headers = Object.assign(axiosConfig.headers || {}, {
340
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
341
- Authorization: `Bearer ${(requestObject['auth'] as IDataObject)['bearer']}`,
342
- });
343
- } else {
344
- const authObj = requestObject['auth'] as IDataObject;
345
- // Request accepts both user/username and pass/password
346
- axiosConfig.auth = {
347
- username: (authObj['user'] || authObj['username']) as string,
348
- password: (authObj['password'] || authObj['pass']) as string,
349
- };
350
- }
351
- }
352
-
353
- // Only set header if we have a body, otherwise it may fail
354
- if (requestObject['json'] === true) {
355
- // Add application/json headers - do not set charset as it breaks a lot of stuff
356
- // only add if no other accept headers was sent.
357
- const acceptHeaderExists =
358
- axiosConfig.headers === undefined
359
- ? false
360
- : Object.keys(axiosConfig.headers)
361
- .map((headerKey) => headerKey.toLowerCase())
362
- .includes('accept');
363
- if (!acceptHeaderExists) {
364
- axiosConfig.headers = Object.assign(axiosConfig.headers || {}, {
365
- Accept: 'application/json',
366
- });
367
- }
368
- }
369
- if (requestObject['json'] === false || requestObject['json'] === undefined) {
370
- // Prevent json parsing
371
- axiosConfig.transformResponse = (res) => res;
372
- }
373
-
374
- // Axios will follow redirects by default, so we simply tell it otherwise if needed.
375
- if (
376
- requestObject['followRedirect'] === false &&
377
- ((requestObject['method'] as string | undefined) || 'get').toLowerCase() === 'get'
378
- ) {
379
- axiosConfig.maxRedirects = 0;
380
- }
381
- if (
382
- requestObject['followAllRedirects'] === false &&
383
- ((requestObject['method'] as string | undefined) || 'get').toLowerCase() !== 'get'
384
- ) {
385
- axiosConfig.maxRedirects = 0;
386
- }
387
-
388
- if (requestObject['rejectUnauthorized'] === false) {
389
- axiosConfig.httpsAgent = new Agent({
390
- rejectUnauthorized: false,
391
- });
392
- }
393
-
394
- if (requestObject['timeout'] !== undefined) {
395
- axiosConfig.timeout = requestObject['timeout'] as number;
396
- }
397
-
398
- if (requestObject['proxy'] !== undefined) {
399
- // try our best to parse the url provided.
400
- if (typeof requestObject['proxy'] === 'string') {
401
- try {
402
- const url = new URL(requestObject['proxy']);
403
- axiosConfig.proxy = {
404
- host: url.hostname,
405
- port: parseInt(url.port, 10),
406
- protocol: url.protocol,
407
- };
408
- if (!url.port) {
409
- // Sets port to a default if not informed
410
- if (url.protocol === 'http') {
411
- axiosConfig.proxy.port = 80;
412
- } else if (url.protocol === 'https') {
413
- axiosConfig.proxy.port = 443;
414
- }
415
- }
416
- if (url.username || url.password) {
417
- axiosConfig.proxy.auth = {
418
- username: url.username,
419
- password: url.password,
420
- };
421
- }
422
- } catch (error) {
423
- // Not a valid URL. We will try to simply parse stuff
424
- // such as user:pass@host:port without protocol (we'll assume http)
425
- if (requestObject['proxy'].includes('@')) {
426
- const [userpass, hostport] = requestObject['proxy'].split('@');
427
- const [username, password] = userpass.split(':');
428
- const [hostname, port] = hostport.split(':');
429
- axiosConfig.proxy = {
430
- host: hostname,
431
- port: parseInt(port, 10),
432
- protocol: 'http',
433
- auth: {
434
- username,
435
- password,
436
- },
437
- };
438
- } else if (requestObject['proxy'].includes(':')) {
439
- const [hostname, port] = requestObject['proxy'].split(':');
440
- axiosConfig.proxy = {
441
- host: hostname,
442
- port: parseInt(port, 10),
443
- protocol: 'http',
444
- };
445
- } else {
446
- axiosConfig.proxy = {
447
- host: requestObject['proxy'],
448
- port: 80,
449
- protocol: 'http',
450
- };
451
- }
452
- }
453
- } else {
454
- axiosConfig.proxy = requestObject['proxy'] as AxiosProxyConfig;
455
- }
456
- }
457
-
458
- if (requestObject['encoding'] === null) {
459
- // When downloading files, return an arrayBuffer.
460
- axiosConfig.responseType = 'arraybuffer';
461
- }
462
-
463
- // If we don't set an accept header
464
- // Axios forces "application/json, text/plan, */*"
465
- // Which causes some nodes like NextCloud to break
466
- // as the service returns XML unless requested otherwise.
467
- const allHeaders = axiosConfig.headers ? Object.keys(axiosConfig.headers) : [];
468
- if (!allHeaders.some((headerKey) => headerKey.toLowerCase() === 'accept')) {
469
- axiosConfig.headers = Object.assign(axiosConfig.headers || {}, { accept: '*/*' });
470
- }
471
- if (
472
- requestObject['json'] !== false &&
473
- axiosConfig.data !== undefined &&
474
- axiosConfig.data !== '' &&
475
- !(axiosConfig.data instanceof Buffer) &&
476
- !allHeaders.some((headerKey) => headerKey.toLowerCase() === 'content-type')
477
- ) {
478
- // Use default header for application/json
479
- // If we don't specify this here, axios will add
480
- // application/json; charset=utf-8
481
- // and this breaks a lot of stuff
482
- axiosConfig.headers = Object.assign(axiosConfig.headers || {}, {
483
- 'content-type': 'application/json',
484
- });
485
- }
486
-
487
- /**
488
- * Missing properties:
489
- * encoding (need testing)
490
- * gzip (ignored - default already works)
491
- * resolveWithFullResponse (implemented elsewhere)
492
- * simple (???)
493
- */
494
-
495
- return axiosConfig;
496
- }
497
-
498
- function digestAuthAxiosConfig(
499
- axiosConfig: AxiosRequestConfig,
500
- response: AxiosResponse,
501
- auth: AxiosRequestConfig['auth'],
502
- ): AxiosRequestConfig {
503
- const authDetails = response.headers['www-authenticate']
504
- .split(',')
505
- .map((v: string) => v.split('='));
506
- if (authDetails) {
507
- const nonceCount = `000000001`;
508
- const cnonce = crypto.randomBytes(24).toString('hex');
509
- const realm: string = authDetails
510
- .find((el: any) => el[0].toLowerCase().indexOf('realm') > -1)[1]
511
- .replace(/"/g, '');
512
- const opaque: string = authDetails
513
- .find((el: any) => el[0].toLowerCase().indexOf('opaque') > -1)[1]
514
- .replace(/"/g, '');
515
- const nonce: string = authDetails
516
- .find((el: any) => el[0].toLowerCase().indexOf('nonce') > -1)[1]
517
- .replace(/"/g, '');
518
- const ha1 = crypto
519
- .createHash('md5')
520
- .update(`${auth?.username as string}:${realm}:${auth?.password as string}`)
521
- .digest('hex');
522
- const path = new url.URL(axiosConfig.url!).pathname;
523
- const ha2 = crypto
524
- .createHash('md5')
525
- .update(`${axiosConfig.method ?? 'GET'}:${path}`)
526
- .digest('hex');
527
- const response = crypto
528
- .createHash('md5')
529
- .update(`${ha1}:${nonce}:${nonceCount}:${cnonce}:auth:${ha2}`)
530
- .digest('hex');
531
- const authorization =
532
- `Digest username="${auth?.username as string}",realm="${realm}",` +
533
- `nonce="${nonce}",uri="${path}",qop="auth",algorithm="MD5",` +
534
- `response="${response}",nc="${nonceCount}",cnonce="${cnonce}",opaque="${opaque}"`;
535
- if (axiosConfig.headers) {
536
- axiosConfig.headers['authorization'] = authorization;
537
- } else {
538
- axiosConfig.headers = { authorization };
539
- }
540
- }
541
- return axiosConfig;
542
- }
543
-
544
- async function proxyRequestToAxios(
545
- uriOrObject: string | IDataObject,
546
- options?: IDataObject
547
- ): Promise<any> {
548
- // tslint:disable-line:no-any
549
-
550
- let axiosConfig: AxiosRequestConfig = {};
551
- let axiosPromise: AxiosPromise;
552
- type ConfigObject = {
553
- auth?: { sendImmediately: boolean };
554
- resolveWithFullResponse?: boolean;
555
- simple?: boolean;
556
- };
557
- let configObject: ConfigObject;
558
- if (uriOrObject !== undefined && typeof uriOrObject === 'string') {
559
- axiosConfig.url = uriOrObject;
560
- }
561
- if (uriOrObject !== undefined && typeof uriOrObject === 'object') {
562
- configObject = uriOrObject;
563
- } else {
564
- configObject = options || {};
565
- }
566
-
567
- axiosConfig = Object.assign(axiosConfig, await parseRequestObject(configObject));
568
-
569
- Logger.debug(
570
- 'Proxying request to axios',
571
- // {
572
- // originalConfig: configObject,
573
- // parsedConfig: axiosConfig,
574
- // }
575
- );
576
-
577
- if (configObject.auth?.sendImmediately === false) {
578
- // for digest-auth
579
- const { auth } = axiosConfig;
580
- delete axiosConfig.auth;
581
- // eslint-disable-next-line no-async-promise-executor
582
- axiosPromise = new Promise(async (resolve, reject) => {
583
- try {
584
- const result = await axios(axiosConfig);
585
- resolve(result);
586
- } catch (resp: any) {
587
- if (
588
- resp.response === undefined ||
589
- resp.response.status !== 401 ||
590
- !resp.response.headers['www-authenticate']?.includes('nonce')
591
- ) {
592
- reject(resp);
593
- }
594
- axiosConfig = digestAuthAxiosConfig(axiosConfig, resp.response, auth);
595
- resolve(axios(axiosConfig));
596
- }
597
- });
598
- } else {
599
- axiosPromise = axios(axiosConfig);
600
- }
601
-
602
- return new Promise((resolve, reject) => {
603
- axiosPromise
604
- .then((response) => {
605
- if (configObject.resolveWithFullResponse === true) {
606
- let body = response.data;
607
- if (response.data === '') {
608
- if (axiosConfig.responseType === 'arraybuffer') {
609
- body = Buffer.alloc(0);
610
- } else {
611
- body = undefined;
612
- }
613
- }
614
- resolve({
615
- body,
616
- headers: response.headers,
617
- statusCode: response.status,
618
- statusMessage: response.statusText,
619
- request: response.request,
620
- });
621
- } else {
622
- let body = response.data;
623
- if (response.data === '') {
624
- if (axiosConfig.responseType === 'arraybuffer') {
625
- body = Buffer.alloc(0);
626
- } else {
627
- body = undefined;
628
- }
629
- }
630
- resolve(body);
631
- }
632
- })
633
- .catch((error) => {
634
- if (configObject.simple === false && error.response) {
635
- if (configObject.resolveWithFullResponse) {
636
- resolve({
637
- body: error.response.data,
638
- headers: error.response.headers,
639
- statusCode: error.response.status,
640
- statusMessage: error.response.statusText,
641
- });
642
- } else {
643
- resolve(error.response.data);
644
- }
645
- return;
646
- }
647
-
648
- Logger.debug('Request proxied to Axios failed', { error });
649
-
650
- // Axios hydrates the original error with more data. We extract them.
651
- // https://github.com/axios/axios/blob/master/lib/core/enhanceError.js
652
- // Note: `code` is ignored as it's an expected part of the errorData.
653
- const { request, response, isAxiosError, toJSON, config, ...errorData } = error;
654
- if (response) {
655
- error.message = `${response.status as number} - ${JSON.stringify(response.data)}`;
656
- }
657
-
658
- error.cause = errorData;
659
- error.error = error.response?.data || errorData;
660
- error.statusCode = error.response?.status;
661
- error.options = config || {};
662
-
663
- // Remove not needed data and so also remove circular references
664
- error.request = undefined;
665
- error.config = undefined;
666
- error.options.adapter = undefined;
667
- error.options.httpsAgent = undefined;
668
- error.options.paramsSerializer = undefined;
669
- error.options.transformRequest = undefined;
670
- error.options.transformResponse = undefined;
671
- error.options.validateStatus = undefined;
672
-
673
- reject(error);
674
- });
675
- });
676
- }
677
-
678
- function convertN8nRequestToAxios(n8nRequest: IHttpRequestOptions): AxiosRequestConfig {
679
- // Destructure properties with the same name first.
680
- const { headers, method, timeout, auth, proxy, url } = n8nRequest;
681
-
682
- const axiosRequest = {
683
- headers: headers ?? {},
684
- method,
685
- timeout,
686
- auth,
687
- proxy,
688
- url,
689
- } as AxiosRequestConfig;
690
-
691
- axiosRequest.params = n8nRequest.qs;
692
-
693
- if (n8nRequest.baseURL !== undefined) {
694
- axiosRequest.baseURL = n8nRequest.baseURL;
695
- }
696
-
697
- if (n8nRequest.disableFollowRedirect === true) {
698
- axiosRequest.maxRedirects = 0;
699
- }
700
-
701
- if (n8nRequest.encoding !== undefined) {
702
- axiosRequest.responseType = n8nRequest.encoding;
703
- }
704
-
705
- if (n8nRequest.skipSslCertificateValidation === true) {
706
- axiosRequest.httpsAgent = new Agent({
707
- rejectUnauthorized: false,
708
- });
709
- }
710
-
711
- if (n8nRequest.arrayFormat !== undefined) {
712
- axiosRequest.paramsSerializer = (params) => {
713
- return stringify(params, { arrayFormat: n8nRequest.arrayFormat });
714
- };
715
- }
716
-
717
- if (n8nRequest.body) {
718
- axiosRequest.data = n8nRequest.body;
719
- // Let's add some useful header standards here.
720
- const existingContentTypeHeaderKey = axiosRequest.headers ? searchForHeader(axiosRequest.headers, 'content-type') : undefined;
721
- if (existingContentTypeHeaderKey === undefined) {
722
- // We are only setting content type headers if the user did
723
- // not set it already manually. We're not overriding, even if it's wrong.
724
- if (axiosRequest.data instanceof FormData) {
725
- axiosRequest.headers = axiosRequest.headers || {};
726
- axiosRequest.headers['Content-Type'] = 'multipart/form-data';
727
- } else if (axiosRequest.data instanceof URLSearchParams) {
728
- axiosRequest.headers = axiosRequest.headers || {};
729
- axiosRequest.headers['Content-Type'] = 'application/x-www-form-urlencoded';
730
- }
731
- }
732
- }
733
-
734
- if (n8nRequest.json) {
735
- const key = axiosRequest.headers ? searchForHeader(axiosRequest.headers, 'accept') : undefined;
736
- // If key exists, then the user has set both accept
737
- // header and the json flag. Header should take precedence.
738
- if (!key) {
739
- axiosRequest.headers = axiosRequest.headers || {};
740
- axiosRequest.headers.Accept = 'application/json';
741
- }
742
- }
743
-
744
- const userAgentHeader = axiosRequest.headers ? searchForHeader(axiosRequest.headers as IDataObject, 'user-agent') : undefined;
745
- // If key exists, then the user has set both accept
746
- // header and the json flag. Header should take precedence.
747
- if (!userAgentHeader) {
748
- axiosRequest.headers = axiosRequest.headers || {};
749
- axiosRequest.headers['User-Agent'] = 'n8n';
750
- }
751
-
752
- if (n8nRequest.ignoreHttpStatusErrors) {
753
- axiosRequest.validateStatus = () => true;
754
- }
755
-
756
- return axiosRequest;
757
- }
758
-
759
- async function httpRequest(
760
- requestOptions: IHttpRequestOptions,
761
- ): Promise<IN8nHttpFullResponse | IN8nHttpResponse> {
762
- const axiosRequest = convertN8nRequestToAxios(requestOptions);
763
- const result = await axios(axiosRequest);
764
- if (requestOptions.returnFullResponse) {
765
- return {
766
- body: result.data,
767
- headers: result.headers,
768
- statusCode: result.status,
769
- statusMessage: result.statusText,
770
- };
771
- }
772
- return result.data;
773
- }
774
-
775
- /**
776
- * Returns binary data buffer for given item index and property name.
777
- *
778
- * @export
779
- * @param {ITaskDataConnections} inputData
780
- * @param {number} itemIndex
781
- * @param {string} propertyName
782
- * @param {number} inputIndex
783
- * @returns {Promise<Buffer>}
784
- */
785
- export async function getBinaryDataBuffer(
786
- inputData: ITaskDataConnections,
787
- itemIndex: number,
788
- propertyName: string,
789
- inputIndex: number,
790
- ): Promise<Buffer> {
791
- const binaryData = inputData['main']![inputIndex]![itemIndex]!.binary![propertyName]!;
792
- return BinaryDataManager.getInstance().retrieveBinaryData(binaryData);
793
- }
794
-
795
- /**
796
- * Takes a buffer and converts it into the format n8n uses. It encodes the binary data as
797
- * base64 and adds metadata.
798
- *
799
- * @export
800
- * @param {Buffer} binaryData
801
- * @param {string} [filePath]
802
- * @param {string} [mimeType]
803
- * @returns {Promise<IBinaryData>}
804
- */
805
- export async function prepareBinaryData(
806
- binaryData: Buffer,
807
- executionId: string,
808
- filePath?: string,
809
- mimeType?: string,
810
- ): Promise<IBinaryData> {
811
- if (!mimeType) {
812
- // If no mime type is given figure it out
813
-
814
- if (filePath) {
815
- // Use file path to guess mime type
816
- const mimeTypeLookup = lookup(filePath);
817
- if (mimeTypeLookup) {
818
- mimeType = mimeTypeLookup;
819
- }
820
- }
821
-
822
- if (!mimeType) {
823
- // Use buffer to guess mime type
824
- const fileTypeData = await fromBuffer(binaryData);
825
- if (fileTypeData) {
826
- mimeType = fileTypeData.mime;
827
- }
828
- }
829
-
830
- if (!mimeType) {
831
- // Fall back to text
832
- mimeType = 'text/plain';
833
- }
834
- }
835
-
836
- const returnData: IBinaryData = {
837
- mimeType,
838
- data: '',
839
- };
840
-
841
- if (filePath) {
842
- if (filePath.includes('?')) {
843
- // Remove maybe present query parameters
844
- filePath = filePath.split('?').shift();
845
- }
846
-
847
- const filePathParts = path.parse(filePath as string);
848
-
849
- if (filePathParts.dir !== '') {
850
- returnData.directory = filePathParts.dir;
851
- }
852
- returnData.fileName = filePathParts.base;
853
-
854
- // Remove the dot
855
- const fileExtension = filePathParts.ext.slice(1);
856
- if (fileExtension) {
857
- returnData.fileExtension = fileExtension;
858
- }
859
- }
860
-
861
- return BinaryDataManager.getInstance().storeBinaryData(returnData, binaryData, executionId);
862
- }
863
-
864
-
865
- export async function getCurrentOAuth2AccessToken(
866
- this: IAllExecuteFunctions,
867
- credentialsType: string,
868
- node: INode,
869
- additionalData: IWorkflowExecuteAdditionalData,
870
- oAuth2Options?: IOAuth2Options,
871
- ): Promise<string> {
872
- const credentials = await this.getCredentials(credentialsType) as ICredentialDataDecryptedObject;
873
- if (!credentials) {
874
- throw new NodeOperationError(node, `No credentials of type "${credentialsType}" were returned!`, { description: 'Credentials not found' });
875
- }
876
- const clientId = credentials['clientId'] as string;
877
- const clientSecret = credentials['clientSecret'] as string;
878
- const scope = credentials['scope'] as string;
879
- const grantType = credentials['grantType'] as "authorizationCode" | "clientCredentials";
880
- const authUrl = credentials['authUrl'] as string | undefined;
881
- const accessTokenUrl = credentials['accessTokenUrl'] as string | undefined;
882
- const httpAgent = credentials['httpAgent'] as string | undefined;
883
- const oauthTokenData = (credentials['oauthTokenData'] ?? {}) as Record<string, unknown>;
884
- let accessToken = (oauthTokenData?.['accessToken'] ?? "") as string;
885
- let refreshToken = (oauthTokenData?.['refreshToken'] ?? "") as string;
886
- let expiresAt = (oauthTokenData?.['expiresAt'] ?? "") as string;
887
- let expiresIn = (oauthTokenData?.['expiresIn'] ?? 0) as number;
888
- let tokenType = (oauthTokenData?.['tokenType'] ?? "") as string;
889
-
890
- const isExpired = !accessToken || !expiresAt || new Date(expiresAt).getTime() <= Date.now();
891
-
892
- if (isExpired) {
893
- Logger.debug(`Node "${node.name}" is using credential "${credentialsType}", however the access token has expired. This will now be refreshed using the "${grantType}" flow.`);
894
-
895
- if(!authUrl){
896
- throw new NodeOperationError(node, `The "authUrl" property is required for the "${grantType}" flow. Please check your credentials configuration.`, { description: 'Missing authUrl' });
897
- }
898
- const config: ModuleOptions<'client_id'> = {
899
- client: { id: clientId, secret: clientSecret },
900
- auth: { tokenHost: authUrl, tokenPath: accessTokenUrl },
901
- http: { agent: httpAgent },
902
- };
903
-
904
- if (grantType === 'authorizationCode') {
905
- const client = new AuthorizationCode(config);
906
-
907
- let token = client.createToken({
908
- access_token: get(oauthTokenData, oAuth2Options?.property as string) || accessToken,
909
- refresh_token: refreshToken,
910
- token_type: oAuth2Options?.tokenType || tokenType || 'Bearer',
911
- expires_at: expiresAt,
912
- expires_in: expiresIn,
913
- });
914
-
915
- const refreshOptions: any = oAuth2Options?.includeCredentialsOnRefreshOnBody ? { // Use of 'any' here is bad, though copying from previous example
916
- body: {
917
- client_id: clientId,
918
- client_secret: clientSecret,
919
- },
920
- headers: {
921
- Authorization: '', // override default basic auth
922
- },
923
- } : {};
924
-
925
- token = await token.refresh(refreshOptions);
926
-
927
- accessToken = token.token['access_token'] as string;
928
- refreshToken = token.token['refresh_token'] as string || refreshToken
929
- expiresAt = token.token['expires_at'] as string;
930
- expiresIn = token.token['expires_in'] as number;
931
- tokenType = token.token['token_type'] as string || 'Bearer';
932
- } else if (grantType === 'clientCredentials') {
933
- const client = new ClientCredentials(config);
934
- const token = await client.getToken({scope});
935
-
936
- accessToken = token.token['access_token'] as string;
937
- refreshToken = token.token['refresh_token'] as string || refreshToken ;
938
- expiresAt = token.token['expires_at'] as string;
939
- expiresIn = token.token['expires_in'] as number;
940
- tokenType = token.token['token_type'] as string || 'Bearer';
941
- } else {
942
- throw new Error(`Unsupported grant type "${grantType}" for Microsoft Graph API`);
943
- }
944
-
945
- oauthTokenData["accessToken"] = accessToken;
946
- oauthTokenData["refreshToken"] = refreshToken;
947
- oauthTokenData["expiresAt"] = expiresAt;
948
- oauthTokenData["expiresIn"] = expiresIn;
949
- oauthTokenData["tokenType"] = tokenType;
950
-
951
- if (!node.credentials || !node.credentials[credentialsType]) {
952
- throw new Error(`Node "${node.name}" has no credentials of type "${credentialsType}"`);
953
- }
954
-
955
- await additionalData.credentialsHelper.updateCredentials(
956
- node.credentials[credentialsType],
957
- credentialsType,
958
- credentials,
959
- );
960
-
961
- Logger.debug(`Access token for credential "${credentialsType}" has been refreshed.`);
962
- }
963
-
964
- return accessToken;
965
- }
966
-
967
- export async function requestOAuth2(
968
- this: IAllExecuteFunctions,
969
- credentialsType: string,
970
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions | IHttpRequestOptions,
971
- node: INode,
972
- additionalData: IWorkflowExecuteAdditionalData,
973
- oAuth2Options?: IOAuth2Options,
974
- isN8nRequest = false,
975
- ) {
976
- const credentials = (await this.getCredentials(
977
- credentialsType,
978
- )) as ICredentialDataDecryptedObject;
979
-
980
- if (!credentials) {
981
- throw new Error('No credentials were returned!');
982
- }
983
-
984
- const oauthTokenData = credentials['oauthTokenData'] as Record<string, any>;
985
- if (!oauthTokenData) {
986
- throw new Error('OAuth credentials not connected!');
987
- }
988
-
989
- const config: ModuleOptions<'client_id'> = {
990
- client: {
991
- id: credentials['clientId'] as string,
992
- secret: credentials['clientSecret'] as string,
993
- },
994
- auth: {
995
- tokenHost: credentials['authUrl'] as string,
996
- tokenPath: credentials['accessTokenUrl'] as string,
997
- },
998
- http: {
999
- agent: credentials['httpAgent'],
1000
- },
1001
- };
1002
-
1003
- const client = new AuthorizationCode(config);
1004
-
1005
- // Construct token from saved data
1006
- const tokenObject: AccessToken = client.createToken({
1007
- access_token: get(oauthTokenData, oAuth2Options?.property as string) || oauthTokenData['accessToken'],
1008
- refresh_token: oauthTokenData['refreshToken'],
1009
- token_type: oAuth2Options?.tokenType || oauthTokenData['tokenType'] || 'Bearer',
1010
- expires_at: oauthTokenData['expiresAt'],
1011
- expires_in: oauthTokenData['expiresIn'],
1012
- });
1013
-
1014
- const currentToken = tokenObject;
1015
-
1016
- const signedOptions = {
1017
- ...requestOptions,
1018
- headers: {
1019
- ...(requestOptions.headers || {}),
1020
- Authorization: `${currentToken.token["token_type"]} ${currentToken.token["access_token"]}`,
1021
- },
1022
- };
1023
-
1024
- // Remove 'Bearer' if `keepBearer` is false
1025
- if (oAuth2Options?.keepBearer === false && signedOptions.headers.Authorization) {
1026
- signedOptions.headers.Authorization = signedOptions.headers.Authorization.split(' ')[1];
1027
- }
1028
-
1029
- try {
1030
- return await this.helpers['request']!(signedOptions);
1031
- } catch (error: any) {
1032
- const statusCodeReturned = oAuth2Options?.tokenExpiredStatusCode ?? 401;
1033
-
1034
- if (error.statusCode === statusCodeReturned && currentToken.expired()) {
1035
- // Refresh token
1036
- Logger.debug(`OAuth2 token for "${credentialsType}" used by node "${node.name}" expired. Refreshing...`);
1037
- Logger.info(`OAuth2 token for "${credentialsType}" used by node "${node.name}" expired. Refreshing...`);
1038
-
1039
- const refreshOptions: any = {};
1040
-
1041
- if (oAuth2Options?.includeCredentialsOnRefreshOnBody) {
1042
- refreshOptions.body = {
1043
- client_id: credentials['clientId'],
1044
- client_secret: credentials['clientSecret'],
1045
- };
1046
- refreshOptions.headers = {
1047
- Authorization: '', // override default basic auth
1048
- };
1049
- }
1050
- let refreshedToken: AccessToken;
1051
-
1052
- try {
1053
- refreshedToken = await currentToken.refresh(refreshOptions);
1054
- } catch (error: any) {
1055
- throw new Error("Failed to refresh token: " + error.message);
1056
- }
1057
-
1058
- credentials['oauthTokenData'] = {
1059
- accessToken: refreshedToken.token["access_token"],
1060
- refreshToken: refreshedToken.token["refresh_token"] || currentToken.token["refresh_token"],
1061
- expiresAt: refreshedToken.token["expires_at"],
1062
- expiresIn: refreshedToken.token["expires_in"],
1063
- tokenType: refreshedToken.token["token_type"],
1064
- } as any;
1065
-
1066
- // Persist new token
1067
- if (!node.credentials || !node.credentials[credentialsType]) {
1068
- throw new Error(`Node "${node.name}" has no credentials of type "${credentialsType}"`);
1069
- }
1070
-
1071
- await additionalData.credentialsHelper.updateCredentials(
1072
- node.credentials[credentialsType],
1073
- credentialsType,
1074
- credentials,
1075
- );
1076
-
1077
- Logger.debug(`OAuth2 token for "${credentialsType}" used by node "${node.name}" has been renewed.`);
1078
- Logger.info(`OAuth2 token for "${credentialsType}" used by node "${node.name}" has been renewed.`);
1079
-
1080
- // Retry the original request with the new token
1081
- const retryOptions = {
1082
- ...requestOptions,
1083
- headers: {
1084
- ...(requestOptions.headers || {}),
1085
- Authorization: `${refreshedToken.token["token_type"]} ${refreshedToken.token["access_token"]}`,
1086
- },
1087
- };
1088
-
1089
- if (oAuth2Options?.keepBearer === false && retryOptions.headers.Authorization) {
1090
- retryOptions.headers.Authorization = retryOptions.headers.Authorization.split(' ')[1];
1091
- }
1092
-
1093
- return isN8nRequest
1094
- ? this.helpers.httpRequest(retryOptions as IHttpRequestOptions)
1095
- : this.helpers['request']!(retryOptions);
1096
- }
1097
-
1098
- throw error;
1099
- }
1100
- }
1101
-
1102
-
1103
- /* Makes a request using OAuth1 data for authentication
1104
- *
1105
- * @export
1106
- * @param {IAllExecuteFunctions} this
1107
- * @param {string} credentialsType
1108
- * @param {(OptionsWithUrl | requestPromise.RequestPromiseOptions)} requestOptionså
1109
- * @returns
1110
- */
1111
- export async function requestOAuth1(
1112
- this: IAllExecuteFunctions,
1113
- credentialsType: string,
1114
- requestOptions:
1115
- | OptionsWithUrl
1116
- | OptionsWithUri
1117
- | requestPromise.RequestPromiseOptions
1118
- | IHttpRequestOptions,
1119
- isN8nRequest = false,
1120
- ) {
1121
- const credentials = (await this.getCredentials(
1122
- credentialsType,
1123
- )) as ICredentialDataDecryptedObject;
1124
-
1125
- if (credentials === undefined) {
1126
- throw new Error('No credentials were returned!');
1127
- }
1128
-
1129
- if (credentials['oauthTokenData'] === undefined) {
1130
- throw new Error('OAuth credentials not connected!');
1131
- }
1132
-
1133
- const oauth = new clientOAuth1({
1134
- consumer: {
1135
- key: credentials['consumerKey'] as string,
1136
- secret: credentials['consumerSecret'] as string,
1137
- },
1138
- signature_method: credentials['signatureMethod'] as string,
1139
- hash_function(base: any, key: any) {
1140
- const algorithm = credentials['signatureMethod'] === 'HMAC-SHA1' ? 'sha1' : 'sha256';
1141
- return createHmac(algorithm, key).update(base).digest('base64');
1142
- },
1143
- });
1144
-
1145
- const oauthTokenData = credentials['oauthTokenData'] as IDataObject;
1146
-
1147
- const token: Token = {
1148
- key: oauthTokenData['oauth_token'] as string,
1149
- secret: oauthTokenData['oauth_token_secret'] as string,
1150
- };
1151
-
1152
- // @ts-ignore
1153
- requestOptions.data = { ...requestOptions.qs, ...requestOptions.form };
1154
-
1155
- // Fixes issue that OAuth1 library only works with "url" property and not with "uri"
1156
- // @ts-ignore
1157
- if (requestOptions.uri && !requestOptions.url) {
1158
- // @ts-ignore
1159
- requestOptions.url = requestOptions.uri;
1160
- // @ts-ignore
1161
- delete requestOptions.uri;
1162
- }
1163
-
1164
- // @ts-ignore
1165
- requestOptions.headers = oauth.toHeader(oauth.authorize(requestOptions, token));
1166
-
1167
- if (isN8nRequest) {
1168
- return this.helpers.httpRequest(requestOptions as IHttpRequestOptions);
1169
- }
1170
-
1171
- return this.helpers['request']!(requestOptions).catch(async (error: IResponseError) => {
1172
- // Unknown error so simply throw it
1173
- throw error;
1174
- });
1175
- }
1176
-
1177
- export async function httpRequestWithAuthentication(
1178
- this: IAllExecuteFunctions,
1179
- credentialsType: string,
1180
- requestOptions: IHttpRequestOptions,
1181
- workflow: Workflow,
1182
- node: INode,
1183
- additionalData: IWorkflowExecuteAdditionalData,
1184
- additionalCredentialOptions?: IAdditionalCredentialOptions,
1185
- ) {
1186
- try {
1187
- const parentTypes = additionalData.credentialsHelper.getParentTypes(credentialsType);
1188
-
1189
- if (parentTypes.includes('oAuth1Api')) {
1190
- return await requestOAuth1.call(this, credentialsType, requestOptions, true);
1191
- }
1192
- if (parentTypes.includes('oAuth2Api')) {
1193
- return await requestOAuth2.call(
1194
- this,
1195
- credentialsType,
1196
- requestOptions,
1197
- node,
1198
- additionalData,
1199
- additionalCredentialOptions?.oauth2,
1200
- true,
1201
- );
1202
- }
1203
-
1204
- let credentialsDecrypted: ICredentialDataDecryptedObject | undefined;
1205
- if (additionalCredentialOptions?.credentialsDecrypted) {
1206
- credentialsDecrypted = additionalCredentialOptions.credentialsDecrypted.data;
1207
- } else {
1208
- credentialsDecrypted = await this.getCredentials(credentialsType);
1209
- }
1210
-
1211
- if (credentialsDecrypted === undefined) {
1212
- throw new NodeOperationError(
1213
- node,
1214
- `Node "${node.name}" does not have any credentials of type "${credentialsType}" set!`,
1215
- );
1216
- }
1217
-
1218
- requestOptions = await additionalData.credentialsHelper.authenticate(
1219
- credentialsDecrypted,
1220
- credentialsType,
1221
- requestOptions,
1222
- workflow,
1223
- node,
1224
- );
1225
-
1226
- return await httpRequest(requestOptions);
1227
- } catch (error) {
1228
- throw new NodeApiError(this.getNode(), error as JsonObject);
1229
- }
1230
- }
1231
-
1232
- /**
1233
- * Takes generic input data and brings it into the json format n8n uses.
1234
- *
1235
- * @export
1236
- * @param {(IDataObject | IDataObject[])} jsonData
1237
- * @returns {INodeExecutionData[]}
1238
- */
1239
- export function returnJsonArray(jsonData: IDataObject | IDataObject[]): INodeExecutionData[] {
1240
- const returnData: INodeExecutionData[] = [];
1241
-
1242
- if (!Array.isArray(jsonData)) {
1243
- jsonData = [jsonData];
1244
- }
1245
-
1246
- jsonData.forEach((data) => {
1247
- returnData.push({ json: data });
1248
- });
1249
-
1250
- return returnData;
1251
- }
1252
-
1253
- /**
1254
- * Automatically put the objects under a 'json' key and don't error,
1255
- * if some objects contain json/binary keys and others don't, throws error 'Inconsistent item format'
1256
- *
1257
- * @export
1258
- * @param {INodeExecutionData | INodeExecutionData[]} executionData
1259
- * @returns {INodeExecutionData[]}
1260
- */
1261
- export function normalizeItems(
1262
- executionData: INodeExecutionData | INodeExecutionData[],
1263
- ): INodeExecutionData[] {
1264
- if (typeof executionData === 'object' && !Array.isArray(executionData))
1265
- executionData = [{ json: executionData as IDataObject }];
1266
- if (executionData.every((item) => typeof item === 'object' && 'json' in item))
1267
- return executionData;
1268
-
1269
- if (executionData.some((item) => typeof item === 'object' && 'json' in item)) {
1270
- throw new Error('Inconsistent item format');
1271
- }
1272
-
1273
- if (executionData.every((item) => typeof item === 'object' && 'binary' in item)) {
1274
- const normalizedItems: INodeExecutionData[] = [];
1275
- executionData.forEach((item) => {
1276
- const json = Object.keys(item).reduce((acc, key) => {
1277
- if (key === 'binary') return acc;
1278
- return { ...acc, [key]: item[key] };
1279
- }, {});
1280
-
1281
- normalizedItems.push({
1282
- json,
1283
- binary: item.binary,
1284
- });
1285
- });
1286
- return normalizedItems;
1287
- }
1288
-
1289
- if (executionData.some((item) => typeof item === 'object' && 'binary' in item)) {
1290
- throw new Error('Inconsistent item format');
1291
- }
1292
-
1293
- return executionData.map((item) => {
1294
- return { json: item };
1295
- });
1296
- }
1297
-
1298
- // TODO: Move up later
1299
- export async function requestWithAuthentication(
1300
- this: IAllExecuteFunctions,
1301
- credentialsType: string,
1302
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
1303
- workflow: Workflow,
1304
- node: INode,
1305
- additionalData: IWorkflowExecuteAdditionalData,
1306
- additionalCredentialOptions?: IAdditionalCredentialOptions,
1307
- ) {
1308
- try {
1309
- const parentTypes = additionalData.credentialsHelper.getParentTypes(credentialsType);
1310
-
1311
- if (parentTypes.includes('oAuth1Api')) {
1312
- return await requestOAuth1.call(this, credentialsType, requestOptions, false);
1313
- }
1314
- if (parentTypes.includes('oAuth2Api')) {
1315
- return await requestOAuth2.call(
1316
- this,
1317
- credentialsType,
1318
- requestOptions,
1319
- node,
1320
- additionalData,
1321
- additionalCredentialOptions?.oauth2,
1322
- false,
1323
- );
1324
- }
1325
-
1326
- let credentialsDecrypted: ICredentialDataDecryptedObject | undefined;
1327
- if (additionalCredentialOptions?.credentialsDecrypted) {
1328
- credentialsDecrypted = additionalCredentialOptions.credentialsDecrypted.data;
1329
- } else {
1330
- credentialsDecrypted = await this.getCredentials(credentialsType);
1331
- }
1332
-
1333
- if (credentialsDecrypted === undefined) {
1334
- throw new NodeOperationError(
1335
- node,
1336
- `Node "${node.name}" does not have any credentials of type "${credentialsType}" set!`,
1337
- );
1338
- }
1339
-
1340
- requestOptions = await additionalData.credentialsHelper.authenticate(
1341
- credentialsDecrypted,
1342
- credentialsType,
1343
- requestOptions as IHttpRequestOptions,
1344
- workflow,
1345
- node,
1346
- );
1347
-
1348
- return await proxyRequestToAxios(requestOptions as IDataObject);
1349
- } catch (error: any) {
1350
- throw new NodeApiError(this.getNode(), error);
1351
- }
1352
- }
1353
-
1354
- /**
1355
- * Returns the additional keys for Expressions and Function-Nodes
1356
- *
1357
- * @export
1358
- * @param {IWorkflowExecuteAdditionalData} additionalData
1359
- * @returns {(IWorkflowDataProxyAdditionalKeys)}
1360
- */
1361
- export function getAdditionalKeys(
1362
- additionalData: IWorkflowExecuteAdditionalData,
1363
- ): IWorkflowDataProxyAdditionalKeys {
1364
- const executionId = additionalData.executionId || PLACEHOLDER_EMPTY_EXECUTION_ID;
1365
- return {
1366
- $executionId: executionId,
1367
- $resumeWebhookUrl: `${additionalData.webhookWaitingBaseUrl}/${executionId}`,
1368
- };
1369
- }
1370
-
1371
- /**
1372
- * Returns the requested decrypted credentials if the node has access to them.
1373
- *
1374
- * @export
1375
- * @param {Workflow} workflow Workflow which requests the data
1376
- * @param {INode} node Node which request the data
1377
- * @param {string} type The credential type to return
1378
- * @param {IWorkflowExecuteAdditionalData} additionalData
1379
- * @returns {(ICredentialDataDecryptedObject | undefined)}
1380
- */
1381
- export async function getCredentials(
1382
- workflow: Workflow,
1383
- node: INode,
1384
- type: string,
1385
- additionalData: IWorkflowExecuteAdditionalData,
1386
- mode: WorkflowExecuteMode,
1387
- runExecutionData?: IRunExecutionData | null,
1388
- runIndex?: number,
1389
- connectionInputData?: INodeExecutionData[],
1390
- itemIndex?: number,
1391
- ): Promise<ICredentialDataDecryptedObject | undefined> {
1392
- // Get the NodeType as it has the information if the credentials are required
1393
- const nodeType = workflow.nodeTypes.getByNameAndVersion(node.type, node.typeVersion);
1394
- if (nodeType === undefined) {
1395
- throw new NodeOperationError(
1396
- node,
1397
- `Node type "${node.type}" is not known so can not get credentials!`,
1398
- );
1399
- }
1400
-
1401
- // Hardcode for now for security reasons that only a single node can access
1402
- // all credentials
1403
- const fullAccess = ['n8n-nodes-base.httpRequest'].includes(node.type);
1404
-
1405
- let nodeCredentialDescription: INodeCredentialDescription | undefined;
1406
- if (!fullAccess) {
1407
- if (nodeType.description.credentials === undefined) {
1408
- throw new NodeOperationError(
1409
- node,
1410
- `Node type "${node.type}" does not have any credentials defined!`,
1411
- );
1412
- }
1413
-
1414
- nodeCredentialDescription = nodeType.description.credentials.find(
1415
- (credentialTypeDescription) => credentialTypeDescription.name === type,
1416
- );
1417
- if (nodeCredentialDescription === undefined) {
1418
- throw new NodeOperationError(
1419
- node,
1420
- `Node type "${node.type}" does not have any credentials of type "${type}" defined!`,
1421
- );
1422
- }
1423
-
1424
- if (
1425
- !NodeHelpers.displayParameter(
1426
- additionalData.currentNodeParameters || node.parameters,
1427
- nodeCredentialDescription,
1428
- node.parameters,
1429
- )
1430
- ) {
1431
- // Credentials should not be displayed so return undefined even if they would be defined
1432
- return undefined;
1433
- }
1434
- }
1435
-
1436
- // Check if node has any credentials defined
1437
- if (!fullAccess && (!node.credentials || !node.credentials[type])) {
1438
- // If none are defined check if the credentials are required or not
1439
-
1440
- if (nodeCredentialDescription?.required === true) {
1441
- // Credentials are required so error
1442
- if (!node.credentials) {
1443
- throw new NodeOperationError(node, 'Node does not have any credentials set!');
1444
- }
1445
- if (!node.credentials[type]) {
1446
- throw new NodeOperationError(node, `Node does not have any credentials set for "${type}"!`);
1447
- }
1448
- } else {
1449
- // Credentials are not required so resolve with undefined
1450
- return undefined;
1451
- }
1452
- }
1453
-
1454
- if (fullAccess && (!node.credentials || !node.credentials[type])) {
1455
- // Make sure that fullAccess nodes still behave like before that if they
1456
- // request access to credentials that are currently not set it returns undefined
1457
- return undefined;
1458
- }
1459
-
1460
- let expressionResolveValues: ICredentialsExpressionResolveValues | undefined;
1461
- if (connectionInputData && runExecutionData && runIndex !== undefined) {
1462
- expressionResolveValues = {
1463
- connectionInputData,
1464
- itemIndex: itemIndex || 0,
1465
- node,
1466
- runExecutionData,
1467
- runIndex,
1468
- workflow,
1469
- } as ICredentialsExpressionResolveValues;
1470
- }
1471
-
1472
- const nodeCredentials = node.credentials
1473
- ? node.credentials[type]
1474
- : ({} as INodeCredentialsDetails);
1475
-
1476
- // TODO: solve using credentials via expression
1477
- // if (name.charAt(0) === '=') {
1478
- // // If the credential name is an expression resolve it
1479
- // const additionalKeys = getAdditionalKeys(additionalData);
1480
- // name = workflow.expression.getParameterValue(
1481
- // name,
1482
- // runExecutionData || null,
1483
- // runIndex || 0,
1484
- // itemIndex || 0,
1485
- // node.name,
1486
- // connectionInputData || [],
1487
- // mode,
1488
- // additionalKeys,
1489
- // ) as string;
1490
- // }
1491
-
1492
- const decryptedDataObject = await additionalData.credentialsHelper.getDecrypted(
1493
- nodeCredentials,
1494
- type,
1495
- mode,
1496
- false,
1497
- expressionResolveValues,
1498
- );
1499
-
1500
- return decryptedDataObject;
1501
- }
1502
-
1503
- /**
1504
- * Returns a copy of the node
1505
- *
1506
- * @export
1507
- * @param {INode} node
1508
- * @returns {INode}
1509
- */
1510
- export function getNode(node: INode): INode {
1511
- return JSON.parse(JSON.stringify(node));
1512
- }
1513
-
1514
- /**
1515
- * Returns the requested resolved (all expressions replaced) node parameters.
1516
- *
1517
- * @export
1518
- * @param {Workflow} workflow
1519
- * @param {(IRunExecutionData | null)} runExecutionData
1520
- * @param {number} runIndex
1521
- * @param {INodeExecutionData[]} connectionInputData
1522
- * @param {INode} node
1523
- * @param {string} parameterName
1524
- * @param {number} itemIndex
1525
- * @param {*} [fallbackValue]
1526
- * @returns {(NodeParameterValue | INodeParameters | NodeParameterValue[] | INodeParameters[] | object)}
1527
- */
1528
-
1529
- export function getNodeParameter(
1530
- workflow: Workflow,
1531
- runExecutionData: IRunExecutionData | null,
1532
- runIndex: number,
1533
- connectionInputData: INodeExecutionData[],
1534
- node: INode,
1535
- parameterName: string,
1536
- itemIndex: number,
1537
- mode: WorkflowExecuteMode,
1538
- additionalKeys: IWorkflowDataProxyAdditionalKeys,
1539
- fallbackValue?: any,
1540
- ): NodeParameterValue | INodeParameters | NodeParameterValue[] | INodeParameters[] | object {
1541
- const nodeType = workflow.nodeTypes.getByNameAndVersion(node.type, node.typeVersion);
1542
- if (nodeType === undefined) {
1543
- throw new Error(`Node type "${node.type}" is not known so can not return paramter value!`);
1544
- }
1545
-
1546
- const value = get(node.parameters, parameterName, fallbackValue);
1547
-
1548
- if (value === undefined) {
1549
- throw new Error(`Could not get parameter "${parameterName}"!`);
1550
- }
1551
-
1552
- let returnData;
1553
- try {
1554
- returnData = workflow.expression.getParameterValue(
1555
- value,
1556
- runExecutionData,
1557
- runIndex,
1558
- itemIndex,
1559
- node.name,
1560
- connectionInputData,
1561
- mode,
1562
- additionalKeys,
1563
- );
1564
- } catch (e: any) {
1565
- e.message += ` [Error in parameter: "${parameterName}"]`;
1566
- throw e;
1567
- }
1568
-
1569
- return returnData;
1570
- }
1571
-
1572
- /**
1573
- * Returns if execution should be continued even if there was an error.
1574
- *
1575
- * @export
1576
- * @param {INode} node
1577
- * @returns {boolean}
1578
- */
1579
- export function continueOnFail(node: INode): boolean {
1580
- return get(node, 'continueOnFail', false);
1581
- }
1582
-
1583
- /**
1584
- * Returns the webhook URL of the webhook with the given name
1585
- *
1586
- * @export
1587
- * @param {string} name
1588
- * @param {Workflow} workflow
1589
- * @param {INode} node
1590
- * @param {IWorkflowExecuteAdditionalData} additionalData
1591
- * @param {boolean} [isTest]
1592
- * @returns {(string | undefined)}
1593
- */
1594
- export function getNodeWebhookUrl(
1595
- name: string,
1596
- workflow: Workflow,
1597
- node: INode,
1598
- additionalData: IWorkflowExecuteAdditionalData,
1599
- mode: WorkflowExecuteMode,
1600
- additionalKeys: IWorkflowDataProxyAdditionalKeys,
1601
- isTest?: boolean,
1602
- ): string | undefined {
1603
- let baseUrl = additionalData.webhookBaseUrl;
1604
- if (isTest === true) {
1605
- baseUrl = additionalData.webhookTestBaseUrl;
1606
- }
1607
-
1608
- // eslint-disable-next-line @typescript-eslint/no-use-before-define
1609
- const webhookDescription = getWebhookDescription(name, workflow, node);
1610
- if (webhookDescription === undefined) {
1611
- return undefined;
1612
- }
1613
-
1614
- const path = workflow.expression.getSimpleParameterValue(
1615
- node,
1616
- webhookDescription.path,
1617
- mode,
1618
- additionalKeys,
1619
- );
1620
- if (path === undefined) {
1621
- return undefined;
1622
- }
1623
-
1624
- const isFullPath: boolean = workflow.expression.getSimpleParameterValue(
1625
- node,
1626
- webhookDescription.isFullPath,
1627
- mode,
1628
- additionalKeys,
1629
- false,
1630
- ) as boolean;
1631
- return NodeHelpers.getNodeWebhookUrl(baseUrl, workflow.id!, node, path.toString(), isFullPath);
1632
- }
1633
-
1634
- /**
1635
- * Returns the timezone for the workflow
1636
- *
1637
- * @export
1638
- * @param {Workflow} workflow
1639
- * @param {IWorkflowExecuteAdditionalData} additionalData
1640
- * @returns {string}
1641
- */
1642
- export function getTimezone(
1643
- workflow: Workflow,
1644
- additionalData: IWorkflowExecuteAdditionalData,
1645
- ): string {
1646
- // eslint-disable-next-line @typescript-eslint/prefer-optional-chain
1647
- if (workflow.settings !== undefined && workflow.settings['timezone'] !== undefined) {
1648
- return (workflow.settings as IWorkflowSettings).timezone as string;
1649
- }
1650
- return additionalData.timezone;
1651
- }
1652
-
1653
- /**
1654
- * Returns the full webhook description of the webhook with the given name
1655
- *
1656
- * @export
1657
- * @param {string} name
1658
- * @param {Workflow} workflow
1659
- * @param {INode} node
1660
- * @returns {(IWebhookDescription | undefined)}
1661
- */
1662
- export function getWebhookDescription(
1663
- name: string,
1664
- workflow: Workflow,
1665
- node: INode,
1666
- ): IWebhookDescription | undefined {
1667
- const nodeType = workflow.nodeTypes.getByNameAndVersion(node.type, node.typeVersion) as INodeType;
1668
-
1669
- if (nodeType.description.webhooks === undefined) {
1670
- // Node does not have any webhooks so return
1671
- return undefined;
1672
- }
1673
-
1674
- // eslint-disable-next-line no-restricted-syntax
1675
- for (const webhookDescription of nodeType.description.webhooks) {
1676
- if (webhookDescription.name === name) {
1677
- return webhookDescription;
1678
- }
1679
- }
1680
-
1681
- return undefined;
1682
- }
1683
-
1684
- /**
1685
- * Returns the workflow metadata
1686
- *
1687
- * @export
1688
- * @param {Workflow} workflow
1689
- * @returns {IWorkflowMetadata}
1690
- */
1691
- export function getWorkflowMetadata(workflow: Workflow): IWorkflowMetadata {
1692
- return {
1693
- id: workflow.id,
1694
- name: workflow.name,
1695
- active: workflow.active,
1696
- };
1697
- }
1698
-
1699
- /**
1700
- * Returns the execute functions the poll nodes have access to.
1701
- *
1702
- * @export
1703
- * @param {Workflow} workflow
1704
- * @param {INode} node
1705
- * @param {IWorkflowExecuteAdditionalData} additionalData
1706
- * @param {WorkflowExecuteMode} mode
1707
- * @returns {ITriggerFunctions}
1708
- */
1709
- // TODO: Check if I can get rid of: additionalData, and so then maybe also at ActiveWorkflowRunner.add
1710
- export function getExecutePollFunctions(
1711
- workflow: Workflow,
1712
- node: INode,
1713
- additionalData: IWorkflowExecuteAdditionalData,
1714
- mode: WorkflowExecuteMode,
1715
- activation: WorkflowActivateMode,
1716
- ): IPollFunctions {
1717
- return ((workflow: Workflow, node: INode) => {
1718
- return {
1719
- __emit: (data: INodeExecutionData[][]): void => {
1720
- throw new Error('Overwrite NodeExecuteFunctions.getExecutePullFunctions.__emit function!');
1721
- },
1722
- async getCredentials(type: string): Promise<ICredentialDataDecryptedObject | undefined> {
1723
- return getCredentials(workflow, node, type, additionalData, mode);
1724
- },
1725
- getMode: (): WorkflowExecuteMode => {
1726
- return mode;
1727
- },
1728
- getActivationMode: (): WorkflowActivateMode => {
1729
- return activation;
1730
- },
1731
- getNode: () => {
1732
- return getNode(node);
1733
- },
1734
- getNodeParameter: (
1735
- parameterName: string,
1736
- fallbackValue?: any,
1737
- ):
1738
- | NodeParameterValue
1739
- | INodeParameters
1740
- | NodeParameterValue[]
1741
- | INodeParameters[]
1742
- | object => {
1743
- const runExecutionData: IRunExecutionData | null = null;
1744
- const itemIndex = 0;
1745
- const runIndex = 0;
1746
- const connectionInputData: INodeExecutionData[] = [];
1747
-
1748
- return getNodeParameter(
1749
- workflow,
1750
- runExecutionData,
1751
- runIndex,
1752
- connectionInputData,
1753
- node,
1754
- parameterName,
1755
- itemIndex,
1756
- mode,
1757
- getAdditionalKeys(additionalData),
1758
- fallbackValue,
1759
- );
1760
- },
1761
- getRestApiUrl: (): string => {
1762
- return additionalData.restApiUrl;
1763
- },
1764
- getTimezone: (): string => {
1765
- return getTimezone(workflow, additionalData);
1766
- },
1767
- getWorkflow: () => {
1768
- return getWorkflowMetadata(workflow);
1769
- },
1770
- getWorkflowStaticData(type: string): IDataObject {
1771
- return workflow.getStaticData(type, node);
1772
- },
1773
- helpers: {
1774
- httpRequest,
1775
- async prepareBinaryData(
1776
- binaryData: Buffer,
1777
- filePath?: string,
1778
- mimeType?: string,
1779
- ): Promise<IBinaryData> {
1780
- return prepareBinaryData.call(
1781
- this,
1782
- binaryData,
1783
- additionalData.executionId!,
1784
- filePath,
1785
- mimeType,
1786
- );
1787
- },
1788
- request: proxyRequestToAxios,
1789
- async requestWithAuthentication(
1790
- this: IAllExecuteFunctions,
1791
- credentialsType: string,
1792
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
1793
- additionalCredentialOptions?: IAdditionalCredentialOptions,
1794
- ): Promise<any> {
1795
- return requestWithAuthentication.call(
1796
- this,
1797
- credentialsType,
1798
- requestOptions,
1799
- workflow,
1800
- node,
1801
- additionalData,
1802
- additionalCredentialOptions,
1803
- );
1804
- },
1805
- async requestOAuth2(
1806
- this: IAllExecuteFunctions,
1807
- credentialsType: string,
1808
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
1809
- oAuth2Options?: IOAuth2Options,
1810
- ): Promise<any> {
1811
- return requestOAuth2.call(
1812
- this,
1813
- credentialsType,
1814
- requestOptions,
1815
- node,
1816
- additionalData,
1817
- oAuth2Options,
1818
- );
1819
- },
1820
- async getCurrentOAuth2AccessToken(
1821
- this: IAllExecuteFunctions,
1822
- credentialsType: string,
1823
- oAuth2Options?: IOAuth2Options,
1824
- ): Promise<any> {
1825
- return getCurrentOAuth2AccessToken.call(
1826
- this,
1827
- credentialsType,
1828
- node,
1829
- additionalData,
1830
- oAuth2Options,
1831
- );
1832
- },
1833
- async requestOAuth1(
1834
- this: IAllExecuteFunctions,
1835
- credentialsType: string,
1836
- requestOptions: OptionsWithUrl | requestPromise.RequestPromiseOptions,
1837
- ): Promise<any> {
1838
- return requestOAuth1.call(this, credentialsType, requestOptions);
1839
- },
1840
- async httpRequestWithAuthentication(
1841
- this: IAllExecuteFunctions,
1842
- credentialsType: string,
1843
- requestOptions: IHttpRequestOptions,
1844
- additionalCredentialOptions?: IAdditionalCredentialOptions,
1845
- ): Promise<any> {
1846
- return httpRequestWithAuthentication.call(
1847
- this,
1848
- credentialsType,
1849
- requestOptions,
1850
- workflow,
1851
- node,
1852
- additionalData,
1853
- additionalCredentialOptions,
1854
- );
1855
- },
1856
- returnJsonArray,
1857
- },
1858
- };
1859
- })(workflow, node);
1860
- }
1861
-
1862
- /**
1863
- * Returns the execute functions the trigger nodes have access to.
1864
- *
1865
- * @export
1866
- * @param {Workflow} workflow
1867
- * @param {INode} node
1868
- * @param {IWorkflowExecuteAdditionalData} additionalData
1869
- * @param {WorkflowExecuteMode} mode
1870
- * @returns {ITriggerFunctions}
1871
- */
1872
- // TODO: Check if I can get rid of: additionalData, and so then maybe also at ActiveWorkflowRunner.add
1873
- export function getExecuteTriggerFunctions(
1874
- workflow: Workflow,
1875
- node: INode,
1876
- additionalData: IWorkflowExecuteAdditionalData,
1877
- mode: WorkflowExecuteMode,
1878
- activation: WorkflowActivateMode,
1879
- ): ITriggerFunctions {
1880
- return ((workflow: Workflow, node: INode) => {
1881
- return {
1882
- emit: (data: INodeExecutionData[][]): void => {
1883
- throw new Error('Overwrite NodeExecuteFunctions.getExecuteTriggerFunctions.emit function!');
1884
- },
1885
- async getCredentials(type: string): Promise<ICredentialDataDecryptedObject | undefined> {
1886
- return getCredentials(workflow, node, type, additionalData, mode);
1887
- },
1888
- getNode: () => {
1889
- return getNode(node);
1890
- },
1891
- getMode: (): WorkflowExecuteMode => {
1892
- return mode;
1893
- },
1894
- getActivationMode: (): WorkflowActivateMode => {
1895
- return activation;
1896
- },
1897
- getNodeParameter: (
1898
- parameterName: string,
1899
- fallbackValue?: any,
1900
- ):
1901
- | NodeParameterValue
1902
- | INodeParameters
1903
- | NodeParameterValue[]
1904
- | INodeParameters[]
1905
- | object => {
1906
- const runExecutionData: IRunExecutionData | null = null;
1907
- const itemIndex = 0;
1908
- const runIndex = 0;
1909
- const connectionInputData: INodeExecutionData[] = [];
1910
-
1911
- return getNodeParameter(
1912
- workflow,
1913
- runExecutionData,
1914
- runIndex,
1915
- connectionInputData,
1916
- node,
1917
- parameterName,
1918
- itemIndex,
1919
- mode,
1920
- getAdditionalKeys(additionalData),
1921
- fallbackValue,
1922
- );
1923
- },
1924
- getRestApiUrl: (): string => {
1925
- return additionalData.restApiUrl;
1926
- },
1927
- getTimezone: (): string => {
1928
- return getTimezone(workflow, additionalData);
1929
- },
1930
- getWorkflow: () => {
1931
- return getWorkflowMetadata(workflow);
1932
- },
1933
- getWorkflowStaticData(type: string): IDataObject {
1934
- return workflow.getStaticData(type, node);
1935
- },
1936
- helpers: {
1937
- httpRequest,
1938
- async requestWithAuthentication(
1939
- this: IAllExecuteFunctions,
1940
- credentialsType: string,
1941
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
1942
- additionalCredentialOptions?: IAdditionalCredentialOptions,
1943
- ): Promise<any> {
1944
- return requestWithAuthentication.call(
1945
- this,
1946
- credentialsType,
1947
- requestOptions,
1948
- workflow,
1949
- node,
1950
- additionalData,
1951
- additionalCredentialOptions,
1952
- );
1953
- },
1954
- async prepareBinaryData(
1955
- binaryData: Buffer,
1956
- filePath?: string,
1957
- mimeType?: string,
1958
- ): Promise<IBinaryData> {
1959
- return prepareBinaryData.call(
1960
- this,
1961
- binaryData,
1962
- additionalData.executionId!,
1963
- filePath,
1964
- mimeType,
1965
- );
1966
- },
1967
- request: proxyRequestToAxios,
1968
- async requestOAuth2(
1969
- this: IAllExecuteFunctions,
1970
- credentialsType: string,
1971
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
1972
- oAuth2Options?: IOAuth2Options,
1973
- ): Promise<any> {
1974
- return requestOAuth2.call(
1975
- this,
1976
- credentialsType,
1977
- requestOptions,
1978
- node,
1979
- additionalData,
1980
- oAuth2Options,
1981
- );
1982
- },
1983
- async requestOAuth1(
1984
- this: IAllExecuteFunctions,
1985
- credentialsType: string,
1986
- requestOptions: OptionsWithUrl | requestPromise.RequestPromiseOptions,
1987
- ): Promise<any> {
1988
- return requestOAuth1.call(this, credentialsType, requestOptions);
1989
- },
1990
- async httpRequestWithAuthentication(
1991
- this: IAllExecuteFunctions,
1992
- credentialsType: string,
1993
- requestOptions: IHttpRequestOptions,
1994
- additionalCredentialOptions?: IAdditionalCredentialOptions,
1995
- ): Promise<any> {
1996
- return httpRequestWithAuthentication.call(
1997
- this,
1998
- credentialsType,
1999
- requestOptions,
2000
- workflow,
2001
- node,
2002
- additionalData,
2003
- additionalCredentialOptions,
2004
- );
2005
- },
2006
- returnJsonArray,
2007
- },
2008
- };
2009
- })(workflow, node);
2010
- }
2011
-
2012
- /**
2013
- * Returns the execute functions regular nodes have access to.
2014
- *
2015
- * @export
2016
- * @param {Workflow} workflow
2017
- * @param {IRunExecutionData} runExecutionData
2018
- * @param {number} runIndex
2019
- * @param {INodeExecutionData[]} connectionInputData
2020
- * @param {ITaskDataConnections} inputData
2021
- * @param {INode} node
2022
- * @param {IWorkflowExecuteAdditionalData} additionalData
2023
- * @param {WorkflowExecuteMode} mode
2024
- * @returns {IExecuteFunctions}
2025
- */
2026
- export function getExecuteFunctions(
2027
- workflow: Workflow,
2028
- runExecutionData: IRunExecutionData,
2029
- runIndex: number,
2030
- connectionInputData: INodeExecutionData[],
2031
- inputData: ITaskDataConnections,
2032
- node: INode,
2033
- additionalData: IWorkflowExecuteAdditionalData,
2034
- mode: WorkflowExecuteMode,
2035
- nodeTypeData: INodeType,
2036
- closeFunctions: CloseFunction[],
2037
- ): IExecuteFunctions {
2038
- return ((workflow, runExecutionData, connectionInputData, inputData, node, nodeTypeData, closeFunctions) => {
2039
- return {
2040
- continueOnFail: () => {
2041
- return continueOnFail(node);
2042
- },
2043
- evaluateExpression: (expression: string, itemIndex: number) => {
2044
- return workflow.expression.resolveSimpleParameterValue(
2045
- `=${expression}`,
2046
- {},
2047
- runExecutionData,
2048
- runIndex,
2049
- itemIndex,
2050
- node.name,
2051
- connectionInputData,
2052
- mode,
2053
- getAdditionalKeys(additionalData),
2054
- );
2055
- },
2056
- async executeWorkflow(
2057
- workflowInfo: IExecuteWorkflowInfo,
2058
- inputData?: INodeExecutionData[],
2059
- ): Promise<any> {
2060
- return additionalData
2061
- .executeWorkflow(workflowInfo, additionalData, inputData)
2062
- .then(async (result) =>
2063
- BinaryDataManager.getInstance().duplicateBinaryData(
2064
- result,
2065
- additionalData.executionId!,
2066
- ),
2067
- );
2068
- },
2069
- getContext(type: string): IContextObject {
2070
- return NodeHelpers.getContext(runExecutionData, type, node);
2071
- },
2072
- async getCredentials(
2073
- type: string,
2074
- itemIndex?: number,
2075
- ): Promise<ICredentialDataDecryptedObject | undefined> {
2076
- return getCredentials(
2077
- workflow,
2078
- node,
2079
- type,
2080
- additionalData,
2081
- mode,
2082
- runExecutionData,
2083
- runIndex,
2084
- connectionInputData,
2085
- itemIndex,
2086
- );
2087
- },
2088
- getExecutionId: (): string => {
2089
- return additionalData.executionId!;
2090
- },
2091
- getInputData: (inputIndex = 0, inputName = 'main') => {
2092
- if (!Object.prototype.hasOwnProperty.call(inputData, inputName)) {
2093
- // Return empty array because else it would throw error when nothing is connected to input
2094
- return [];
2095
- }
2096
-
2097
- // TODO: Check if nodeType has input with that index defined
2098
- if (inputData[inputName].length < inputIndex) {
2099
- throw new Error(`Could not get input index "${inputIndex}" of input "${inputName}"!`);
2100
- }
2101
-
2102
- if (inputData[inputName][inputIndex] === null) {
2103
- // return [];
2104
- throw new Error(`Value "${inputIndex}" of input "${inputName}" did not get set!`);
2105
- }
2106
-
2107
- return inputData[inputName][inputIndex] as INodeExecutionData[];
2108
- },
2109
- getNodeParameter: (
2110
- parameterName: string,
2111
- itemIndex: number,
2112
- fallbackValue?: any,
2113
- ):
2114
- | NodeParameterValue
2115
- | INodeParameters
2116
- | NodeParameterValue[]
2117
- | INodeParameters[]
2118
- | object => {
2119
- return getNodeParameter(
2120
- workflow,
2121
- runExecutionData,
2122
- runIndex,
2123
- connectionInputData,
2124
- node,
2125
- parameterName,
2126
- itemIndex,
2127
- mode,
2128
- getAdditionalKeys(additionalData),
2129
- fallbackValue,
2130
- );
2131
- },
2132
- getMode: (): WorkflowExecuteMode => {
2133
- return mode;
2134
- },
2135
- getNode: () => {
2136
- return getNode(node);
2137
- },
2138
- getRestApiUrl: (): string => {
2139
- return additionalData.restApiUrl;
2140
- },
2141
- getTimezone: (): string => {
2142
- return getTimezone(workflow, additionalData);
2143
- },
2144
- getWorkflow: () => {
2145
- return getWorkflowMetadata(workflow);
2146
- },
2147
- getWorkflowDataProxy: (itemIndex: number): IWorkflowDataProxyData => {
2148
- const dataProxy = new WorkflowDataProxy(
2149
- workflow,
2150
- runExecutionData,
2151
- runIndex,
2152
- itemIndex,
2153
- node.name,
2154
- connectionInputData,
2155
- {},
2156
- mode,
2157
- getAdditionalKeys(additionalData),
2158
- );
2159
- return dataProxy.getDataProxy();
2160
- },
2161
- getWorkflowStaticData(type: string): IDataObject {
2162
- return workflow.getStaticData(type, node);
2163
- },
2164
- prepareOutputData: NodeHelpers.prepareOutputData,
2165
- async putExecutionToWait(waitTill: Date): Promise<void> {
2166
- runExecutionData.waitTill = waitTill;
2167
- },
2168
- sendMessageToUI(...args: any[]): void {
2169
- if (mode !== 'manual') {
2170
- return;
2171
- }
2172
- try {
2173
- if (additionalData.sendMessageToUI) {
2174
- additionalData.sendMessageToUI(node.name, args);
2175
- }
2176
- } catch (error: any) {
2177
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
2178
- Logger.warn(`There was a problem sending messsage to UI: ${error.message}`);
2179
- }
2180
- },
2181
- async sendResponse(response: IExecuteResponsePromiseData): Promise<void> {
2182
- await additionalData.hooks?.executeHookFunctions('sendResponse', [response]);
2183
- },
2184
- helpers: {
2185
- httpRequest,
2186
- async requestWithAuthentication(
2187
- this: IAllExecuteFunctions,
2188
- credentialsType: string,
2189
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
2190
- additionalCredentialOptions?: IAdditionalCredentialOptions,
2191
- ): Promise<any> {
2192
- return requestWithAuthentication.call(
2193
- this,
2194
- credentialsType,
2195
- requestOptions,
2196
- workflow,
2197
- node,
2198
- additionalData,
2199
- additionalCredentialOptions,
2200
- );
2201
- },
2202
- assertBinaryData(
2203
- itemIndex: number,
2204
- propertyName: string,
2205
- inputIndex: number = 0,
2206
- ): IBinaryData {
2207
- const binaryKeyData = inputData['main'][inputIndex]![itemIndex].binary;
2208
- if (binaryKeyData === undefined) {
2209
- throw new NodeOperationError(
2210
- node,
2211
- `This operation expects the node's input data to contain a binary file '${propertyName}', but none was found [item ${itemIndex}]`,
2212
- {
2213
- itemIndex,
2214
- description: 'Make sure that the previous node outputs a binary file',
2215
- },
2216
- );
2217
- }
2218
-
2219
- const binaryPropertyData = binaryKeyData[propertyName];
2220
- if (binaryPropertyData === undefined) {
2221
- throw new NodeOperationError(
2222
- node,
2223
- `The item has no binary field '${propertyName}' [item ${itemIndex}]`,
2224
- {
2225
- itemIndex,
2226
- description:
2227
- 'Check that the parameter where you specified the input binary field name is correct, and that it matches a field in the binary input',
2228
- },
2229
- );
2230
- }
2231
-
2232
- return binaryPropertyData;
2233
- },
2234
-
2235
- async prepareBinaryData(
2236
- binaryData: Buffer,
2237
- filePath?: string,
2238
- mimeType?: string,
2239
- ): Promise<IBinaryData> {
2240
- return prepareBinaryData.call(
2241
- this,
2242
- binaryData,
2243
- additionalData.executionId!,
2244
- filePath,
2245
- mimeType,
2246
- );
2247
- },
2248
- async getBinaryDataBuffer(
2249
- itemIndex: number,
2250
- propertyName: string,
2251
- inputIndex = 0,
2252
- ): Promise<Buffer> {
2253
- return getBinaryDataBuffer.call(this, inputData, itemIndex, propertyName, inputIndex);
2254
- },
2255
- request: proxyRequestToAxios,
2256
- async requestOAuth2(
2257
- this: IAllExecuteFunctions,
2258
- credentialsType: string,
2259
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
2260
- oAuth2Options?: IOAuth2Options,
2261
- ): Promise<any> {
2262
- return requestOAuth2.call(
2263
- this,
2264
- credentialsType,
2265
- requestOptions,
2266
- node,
2267
- additionalData,
2268
- oAuth2Options,
2269
- );
2270
- },
2271
- async requestOAuth1(
2272
- this: IAllExecuteFunctions,
2273
- credentialsType: string,
2274
- requestOptions: OptionsWithUrl | requestPromise.RequestPromiseOptions,
2275
- ): Promise<any> {
2276
- return requestOAuth1.call(this, credentialsType, requestOptions);
2277
- },
2278
- async httpRequestWithAuthentication(
2279
- this: IAllExecuteFunctions,
2280
- credentialsType: string,
2281
- requestOptions: IHttpRequestOptions,
2282
- additionalCredentialOptions?: IAdditionalCredentialOptions,
2283
- ): Promise<any> {
2284
- return httpRequestWithAuthentication.call(
2285
- this,
2286
- credentialsType,
2287
- requestOptions,
2288
- workflow,
2289
- node,
2290
- additionalData,
2291
- additionalCredentialOptions,
2292
- );
2293
- },
2294
- returnJsonArray,
2295
- normalizeItems,
2296
- },
2297
- getInstanceId: () => {
2298
- // Return the node's instance ID if available, otherwise return an empty string
2299
- return node.id || '';
2300
- },
2301
- async getInputConnectionData(
2302
- this: IExecuteFunctions | ISupplyDataFunctions,
2303
- connectionType: NodeConnectionType,
2304
- itemIndex: number,
2305
- ): Promise<unknown> {
2306
- return await getInputConnectionData.call(
2307
- this,
2308
- workflow,
2309
- runExecutionData,
2310
- runIndex,
2311
- connectionInputData,
2312
- inputData,
2313
- additionalData,
2314
- connectionType,
2315
- mode,
2316
- itemIndex,
2317
- nodeTypeData,
2318
- closeFunctions,
2319
- );
2320
- },
2321
-
2322
- addInputData(
2323
- data: INodeExecutionData[][] | ExecutionError,
2324
- node: INode
2325
- ): { index: number, inputExecutionData: IRunExecutionData } {
2326
- const nodeName = node.name;
2327
- let currentNodeRunIndex = 0;
2328
- runExecutionData = {
2329
- startData: {
2330
- destinationNode: nodeName,
2331
- },
2332
- resultData: {
2333
- runData: {
2334
- [nodeName]: [JSON.parse(JSON.stringify(data))]
2335
- },
2336
- lastNodeExecuted: nodeName,
2337
- },
2338
- }
2339
-
2340
- return { index: currentNodeRunIndex, inputExecutionData: runExecutionData };
2341
- },
2342
- addOutputData(
2343
- data: INodeExecutionData[][] | ExecutionError,
2344
- node: INode
2345
- ): { outputExecutionData: IRunExecutionData } {
2346
- const nodeName = node.name;
2347
- const outputExecutionData = {
2348
- startData: {
2349
- destinationNode: nodeName,
2350
- },
2351
- resultData: {
2352
- error: typeof data === 'object' && 'error' in data ? data.error as ExecutionError : undefined,
2353
- runData: {
2354
- [nodeName]: [JSON.parse(JSON.stringify(data))]
2355
- },
2356
- lastNodeExecuted: nodeName,
2357
- },
2358
- }
2359
- return { outputExecutionData };
2360
-
2361
- },
2362
- getExecutionCancelSignal: () => {
2363
- return undefined;
2364
- },
2365
- };
2366
-
2367
-
2368
- })(workflow, runExecutionData, connectionInputData, inputData, node, nodeTypeData, closeFunctions) as unknown as IExecuteFunctions;
2369
- }
2370
-
2371
- /**
2372
- * Returns the execute functions regular nodes have access to when single-function is defined.
2373
- *
2374
- * @export
2375
- * @param {Workflow} workflow
2376
- * @param {IRunExecutionData} runExecutionData
2377
- * @param {number} runIndex
2378
- * @param {INodeExecutionData[]} connectionInputData
2379
- * @param {ITaskDataConnections} inputData
2380
- * @param {INode} node
2381
- * @param {number} itemIndex
2382
- * @param {IWorkflowExecuteAdditionalData} additionalData
2383
- * @param {WorkflowExecuteMode} mode
2384
- * @returns {IExecuteSingleFunctions}
2385
- */
2386
- export function getExecuteSingleFunctions(
2387
- workflow: Workflow,
2388
- runExecutionData: IRunExecutionData,
2389
- runIndex: number,
2390
- connectionInputData: INodeExecutionData[],
2391
- inputData: ITaskDataConnections,
2392
- node: INode,
2393
- itemIndex: number,
2394
- additionalData: IWorkflowExecuteAdditionalData,
2395
- mode: WorkflowExecuteMode,
2396
- ): IExecuteSingleFunctions {
2397
- return ((workflow, runExecutionData, connectionInputData, inputData, node, itemIndex) => {
2398
- return {
2399
- continueOnFail: () => {
2400
- return continueOnFail(node);
2401
- },
2402
- evaluateExpression: (expression: string, evaluateItemIndex: number | undefined) => {
2403
- evaluateItemIndex = evaluateItemIndex === undefined ? itemIndex : evaluateItemIndex;
2404
- return workflow.expression.resolveSimpleParameterValue(
2405
- `=${expression}`,
2406
- {},
2407
- runExecutionData,
2408
- runIndex,
2409
- evaluateItemIndex,
2410
- node.name,
2411
- connectionInputData,
2412
- mode,
2413
- getAdditionalKeys(additionalData),
2414
- );
2415
- },
2416
- getContext(type: string): IContextObject {
2417
- return NodeHelpers.getContext(runExecutionData, type, node);
2418
- },
2419
- async getCredentials(type: string): Promise<ICredentialDataDecryptedObject | undefined> {
2420
- return getCredentials(
2421
- workflow,
2422
- node,
2423
- type,
2424
- additionalData,
2425
- mode,
2426
- runExecutionData,
2427
- runIndex,
2428
- connectionInputData,
2429
- itemIndex,
2430
- );
2431
- },
2432
- getInputData: (inputIndex = 0, inputName = 'main') => {
2433
- if (!Object.prototype.hasOwnProperty.call(inputData, inputName)) {
2434
- // Return empty array because else it would throw error when nothing is connected to input
2435
- return { json: {} };
2436
- }
2437
-
2438
- // TODO: Check if nodeType has input with that index defined
2439
- if (inputData[inputName].length < inputIndex) {
2440
- throw new Error(`Could not get input index "${inputIndex}" of input "${inputName}"!`);
2441
- }
2442
-
2443
- const allItems = inputData[inputName][inputIndex];
2444
-
2445
- if (allItems === null) {
2446
- // return [];
2447
- throw new Error(`Value "${inputIndex}" of input "${inputName}" did not get set!`);
2448
- }
2449
-
2450
- if (allItems[itemIndex] === null) {
2451
- // return [];
2452
- throw new Error(
2453
- `Value "${inputIndex}" of input "${inputName}" with itemIndex "${itemIndex}" did not get set!`,
2454
- );
2455
- }
2456
-
2457
- return allItems[itemIndex];
2458
- },
2459
- getMode: (): WorkflowExecuteMode => {
2460
- return mode;
2461
- },
2462
- getNode: () => {
2463
- return getNode(node);
2464
- },
2465
- getRestApiUrl: (): string => {
2466
- return additionalData.restApiUrl;
2467
- },
2468
- getTimezone: (): string => {
2469
- return getTimezone(workflow, additionalData);
2470
- },
2471
- getNodeParameter: (
2472
- parameterName: string,
2473
- fallbackValue?: any,
2474
- ):
2475
- | NodeParameterValue
2476
- | INodeParameters
2477
- | NodeParameterValue[]
2478
- | INodeParameters[]
2479
- | object => {
2480
- return getNodeParameter(
2481
- workflow,
2482
- runExecutionData,
2483
- runIndex,
2484
- connectionInputData,
2485
- node,
2486
- parameterName,
2487
- itemIndex,
2488
- mode,
2489
- getAdditionalKeys(additionalData),
2490
- fallbackValue,
2491
- );
2492
- },
2493
- getWorkflow: () => {
2494
- return getWorkflowMetadata(workflow);
2495
- },
2496
- getWorkflowDataProxy: (): IWorkflowDataProxyData => {
2497
- const dataProxy = new WorkflowDataProxy(
2498
- workflow,
2499
- runExecutionData,
2500
- runIndex,
2501
- itemIndex,
2502
- node.name,
2503
- connectionInputData,
2504
- {},
2505
- mode,
2506
- getAdditionalKeys(additionalData),
2507
- );
2508
- return dataProxy.getDataProxy();
2509
- },
2510
- getWorkflowStaticData(type: string): IDataObject {
2511
- return workflow.getStaticData(type, node);
2512
- },
2513
- helpers: {
2514
- httpRequest,
2515
- async requestWithAuthentication(
2516
- this: IAllExecuteFunctions,
2517
- credentialsType: string,
2518
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
2519
- additionalCredentialOptions?: IAdditionalCredentialOptions,
2520
- ): Promise<any> {
2521
- return requestWithAuthentication.call(
2522
- this,
2523
- credentialsType,
2524
- requestOptions,
2525
- workflow,
2526
- node,
2527
- additionalData,
2528
- additionalCredentialOptions,
2529
- );
2530
- },
2531
- async prepareBinaryData(
2532
- binaryData: Buffer,
2533
- filePath?: string,
2534
- mimeType?: string,
2535
- ): Promise<IBinaryData> {
2536
- return prepareBinaryData.call(
2537
- this,
2538
- binaryData,
2539
- additionalData.executionId!,
2540
- filePath,
2541
- mimeType,
2542
- );
2543
- },
2544
- request: proxyRequestToAxios,
2545
- async requestOAuth2(
2546
- this: IAllExecuteFunctions,
2547
- credentialsType: string,
2548
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
2549
- oAuth2Options?: IOAuth2Options,
2550
- ): Promise<any> {
2551
- return requestOAuth2.call(
2552
- this,
2553
- credentialsType,
2554
- requestOptions,
2555
- node,
2556
- additionalData,
2557
- oAuth2Options,
2558
- );
2559
- },
2560
- async requestOAuth1(
2561
- this: IAllExecuteFunctions,
2562
- credentialsType: string,
2563
- requestOptions: OptionsWithUrl | requestPromise.RequestPromiseOptions,
2564
- ): Promise<any> {
2565
- return requestOAuth1.call(this, credentialsType, requestOptions);
2566
- },
2567
- async httpRequestWithAuthentication(
2568
- this: IAllExecuteFunctions,
2569
- credentialsType: string,
2570
- requestOptions: IHttpRequestOptions,
2571
- additionalCredentialOptions?: IAdditionalCredentialOptions,
2572
- ): Promise<any> {
2573
- return httpRequestWithAuthentication.call(
2574
- this,
2575
- credentialsType,
2576
- requestOptions,
2577
- workflow,
2578
- node,
2579
- additionalData,
2580
- additionalCredentialOptions,
2581
- );
2582
- },
2583
- },
2584
- getInstanceId: () => {
2585
- // Return the node's instance ID if available, otherwise return an empty string
2586
- return node.id || '';
2587
- },
2588
- };
2589
- })(workflow, runExecutionData, connectionInputData, inputData, node, itemIndex) as IExecuteSingleFunctions;
2590
- }
2591
-
2592
- export function getCredentialTestFunctions(): ICredentialTestFunctions {
2593
- return {
2594
- helpers: {
2595
- request: proxyRequestToAxios,
2596
- },
2597
- };
2598
- }
2599
-
2600
- /**
2601
- * Returns the execute functions regular nodes have access to in load-options-function.
2602
- *
2603
- * @export
2604
- * @param {Workflow} workflow
2605
- * @param {INode} node
2606
- * @param {IWorkflowExecuteAdditionalData} additionalData
2607
- * @returns {ILoadOptionsFunctions}
2608
- */
2609
- export function getLoadOptionsFunctions(
2610
- workflow: Workflow,
2611
- node: INode,
2612
- path: string,
2613
- additionalData: IWorkflowExecuteAdditionalData,
2614
- ): ILoadOptionsFunctions {
2615
- return ((workflow: Workflow, node: INode, path: string) => {
2616
- const that = {
2617
- async getCredentials(type: string): Promise<ICredentialDataDecryptedObject | undefined> {
2618
- return getCredentials(workflow, node, type, additionalData, 'internal');
2619
- },
2620
- getCurrentNodeParameter: (
2621
- parameterPath: string,
2622
- ):
2623
- | NodeParameterValue
2624
- | INodeParameters
2625
- | NodeParameterValue[]
2626
- | INodeParameters[]
2627
- | object
2628
- | undefined => {
2629
- const nodeParameters = additionalData.currentNodeParameters;
2630
-
2631
- if (parameterPath.charAt(0) === '&') {
2632
- parameterPath = `${path.split('.').slice(1, -1).join('.')}.${parameterPath.slice(1)}`;
2633
- }
2634
-
2635
- return get(nodeParameters, parameterPath);
2636
- },
2637
- getCurrentNodeParameters: (): INodeParameters | undefined => {
2638
- return additionalData.currentNodeParameters;
2639
- },
2640
- getNode: () => {
2641
- return getNode(node);
2642
- },
2643
- getNodeParameter: (
2644
- parameterName: string,
2645
- fallbackValue?: any,
2646
- ):
2647
- | NodeParameterValue
2648
- | INodeParameters
2649
- | NodeParameterValue[]
2650
- | INodeParameters[]
2651
- | object => {
2652
- const runExecutionData: IRunExecutionData | null = null;
2653
- const itemIndex = 0;
2654
- const runIndex = 0;
2655
- const connectionInputData: INodeExecutionData[] = [];
2656
-
2657
- return getNodeParameter(
2658
- workflow,
2659
- runExecutionData,
2660
- runIndex,
2661
- connectionInputData,
2662
- node,
2663
- parameterName,
2664
- itemIndex,
2665
- 'internal' as WorkflowExecuteMode,
2666
- getAdditionalKeys(additionalData),
2667
- fallbackValue,
2668
- );
2669
- },
2670
- getTimezone: (): string => {
2671
- return getTimezone(workflow, additionalData);
2672
- },
2673
- getRestApiUrl: (): string => {
2674
- return additionalData.restApiUrl;
2675
- },
2676
- helpers: {
2677
- httpRequest,
2678
- async requestWithAuthentication(
2679
- this: IAllExecuteFunctions,
2680
- credentialsType: string,
2681
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
2682
- additionalCredentialOptions?: IAdditionalCredentialOptions,
2683
- ): Promise<any> {
2684
- return requestWithAuthentication.call(
2685
- this,
2686
- credentialsType,
2687
- requestOptions,
2688
- workflow,
2689
- node,
2690
- additionalData,
2691
- additionalCredentialOptions,
2692
- );
2693
- },
2694
- request: proxyRequestToAxios,
2695
- async requestOAuth2(
2696
- this: IAllExecuteFunctions,
2697
- credentialsType: string,
2698
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
2699
- oAuth2Options?: IOAuth2Options,
2700
- ): Promise<any> {
2701
- return requestOAuth2.call(
2702
- this,
2703
- credentialsType,
2704
- requestOptions,
2705
- node,
2706
- additionalData,
2707
- oAuth2Options,
2708
- );
2709
- },
2710
- async requestOAuth1(
2711
- this: IAllExecuteFunctions,
2712
- credentialsType: string,
2713
- requestOptions: OptionsWithUrl | requestPromise.RequestPromiseOptions,
2714
- ): Promise<any> {
2715
- return requestOAuth1.call(this, credentialsType, requestOptions);
2716
- },
2717
- async httpRequestWithAuthentication(
2718
- this: IAllExecuteFunctions,
2719
- credentialsType: string,
2720
- requestOptions: IHttpRequestOptions,
2721
- additionalCredentialOptions?: IAdditionalCredentialOptions,
2722
- ): Promise<any> {
2723
- return httpRequestWithAuthentication.call(
2724
- this,
2725
- credentialsType,
2726
- requestOptions,
2727
- workflow,
2728
- node,
2729
- additionalData,
2730
- additionalCredentialOptions,
2731
- );
2732
- },
2733
- },
2734
- getInstanceId: () => {
2735
- // Return the node's instance ID if available, otherwise return an empty string
2736
- return node.id || '';
2737
- },
2738
- };
2739
- return that;
2740
- })(workflow, node, path) as ILoadOptionsFunctions;
2741
- }
2742
-
2743
- /**
2744
- * Returns the execute functions regular nodes have access to in hook-function.
2745
- *
2746
- * @export
2747
- * @param {Workflow} workflow
2748
- * @param {INode} node
2749
- * @param {IWorkflowExecuteAdditionalData} additionalData
2750
- * @param {WorkflowExecuteMode} mode
2751
- * @returns {IHookFunctions}
2752
- */
2753
- export function getExecuteHookFunctions(
2754
- workflow: Workflow,
2755
- node: INode,
2756
- additionalData: IWorkflowExecuteAdditionalData,
2757
- mode: WorkflowExecuteMode,
2758
- activation: WorkflowActivateMode,
2759
- isTest?: boolean,
2760
- webhookData?: IWebhookData,
2761
- ): IHookFunctions {
2762
- return ((workflow: Workflow, node: INode) => {
2763
- const that = {
2764
- async getCredentials(type: string): Promise<ICredentialDataDecryptedObject | undefined> {
2765
- return getCredentials(workflow, node, type, additionalData, mode);
2766
- },
2767
- getMode: (): WorkflowExecuteMode => {
2768
- return mode;
2769
- },
2770
- getActivationMode: (): WorkflowActivateMode => {
2771
- return activation;
2772
- },
2773
- getNode: () => {
2774
- return getNode(node);
2775
- },
2776
- getNodeParameter: (
2777
- parameterName: string,
2778
- fallbackValue?: any,
2779
- ):
2780
- | NodeParameterValue
2781
- | INodeParameters
2782
- | NodeParameterValue[]
2783
- | INodeParameters[]
2784
- | object => {
2785
- const runExecutionData: IRunExecutionData | null = null;
2786
- const itemIndex = 0;
2787
- const runIndex = 0;
2788
- const connectionInputData: INodeExecutionData[] = [];
2789
-
2790
- return getNodeParameter(
2791
- workflow,
2792
- runExecutionData,
2793
- runIndex,
2794
- connectionInputData,
2795
- node,
2796
- parameterName,
2797
- itemIndex,
2798
- mode,
2799
- getAdditionalKeys(additionalData),
2800
- fallbackValue,
2801
- );
2802
- },
2803
- getNodeWebhookUrl: (name: string): string | undefined => {
2804
- return getNodeWebhookUrl(
2805
- name,
2806
- workflow,
2807
- node,
2808
- additionalData,
2809
- mode,
2810
- getAdditionalKeys(additionalData),
2811
- isTest,
2812
- );
2813
- },
2814
- getTimezone: (): string => {
2815
- return getTimezone(workflow, additionalData);
2816
- },
2817
- getWebhookName(): string {
2818
- if (webhookData === undefined) {
2819
- throw new Error('Is only supported in webhook functions!');
2820
- }
2821
- return webhookData.webhookDescription.name;
2822
- },
2823
- getWebhookDescription(name: string): IWebhookDescription | undefined {
2824
- return getWebhookDescription(name, workflow, node);
2825
- },
2826
- getWorkflow: () => {
2827
- return getWorkflowMetadata(workflow);
2828
- },
2829
- getWorkflowStaticData(type: string): IDataObject {
2830
- return workflow.getStaticData(type, node);
2831
- },
2832
- helpers: {
2833
- httpRequest,
2834
- async requestWithAuthentication(
2835
- this: IAllExecuteFunctions,
2836
- credentialsType: string,
2837
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
2838
- additionalCredentialOptions?: IAdditionalCredentialOptions,
2839
- ): Promise<any> {
2840
- return requestWithAuthentication.call(
2841
- this,
2842
- credentialsType,
2843
- requestOptions,
2844
- workflow,
2845
- node,
2846
- additionalData,
2847
- additionalCredentialOptions,
2848
- );
2849
- },
2850
- request: proxyRequestToAxios,
2851
- async requestOAuth2(
2852
- this: IAllExecuteFunctions,
2853
- credentialsType: string,
2854
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
2855
- oAuth2Options?: IOAuth2Options,
2856
- ): Promise<any> {
2857
- return requestOAuth2.call(
2858
- this,
2859
- credentialsType,
2860
- requestOptions,
2861
- node,
2862
- additionalData,
2863
- oAuth2Options,
2864
- );
2865
- },
2866
- async requestOAuth1(
2867
- this: IAllExecuteFunctions,
2868
- credentialsType: string,
2869
- requestOptions: OptionsWithUrl | requestPromise.RequestPromiseOptions,
2870
- ): Promise<any> {
2871
- return requestOAuth1.call(this, credentialsType, requestOptions);
2872
- },
2873
- async httpRequestWithAuthentication(
2874
- this: IAllExecuteFunctions,
2875
- credentialsType: string,
2876
- requestOptions: IHttpRequestOptions,
2877
- additionalCredentialOptions?: IAdditionalCredentialOptions,
2878
- ): Promise<any> {
2879
- return httpRequestWithAuthentication.call(
2880
- this,
2881
- credentialsType,
2882
- requestOptions,
2883
- workflow,
2884
- node,
2885
- additionalData,
2886
- additionalCredentialOptions,
2887
- );
2888
- },
2889
- },
2890
- getInstanceId: () => {
2891
- // Return the node's instance ID if available, otherwise return an empty string
2892
- return node.id || '';
2893
- },
2894
- };
2895
- return that;
2896
- })(workflow, node) as IHookFunctions;
2897
- }
2898
-
2899
- /**
2900
- * Returns the execute functions regular nodes have access to when webhook-function is defined.
2901
- *
2902
- * @export
2903
- * @param {Workflow} workflow
2904
- * @param {IRunExecutionData} runExecutionData
2905
- * @param {INode} node
2906
- * @param {IWorkflowExecuteAdditionalData} additionalData
2907
- * @param {WorkflowExecuteMode} mode
2908
- * @returns {IWebhookFunctions}
2909
- */
2910
- export function getExecuteWebhookFunctions(
2911
- workflow: Workflow,
2912
- node: INode,
2913
- additionalData: IWorkflowExecuteAdditionalData,
2914
- mode: WorkflowExecuteMode,
2915
- webhookData: IWebhookData,
2916
- runExecutionData: IRunExecutionData | undefined,
2917
- ): IWebhookFunctions {
2918
- return ((workflow: Workflow, node: INode) => {
2919
- return {
2920
- logger: Logger,
2921
- evaluateExpression: (expression: string, itemIndex?: number) => {
2922
- //TODO: Implement this EVALUATE EXPRESSION in get webhook execute function
2923
- return {} as NodeParameterValueType;
2924
- },
2925
- getChildNodes: (nodeName: string, options?: { includeNodeParameters?: boolean }) => {
2926
- return [];
2927
- },
2928
- getParentNodes: (nodeName: string): NodeTypeAndVersion[] => {
2929
- return [];
2930
- },
2931
- getBodyData(): IDataObject {
2932
- if (additionalData.httpRequest === undefined) {
2933
- throw new Error('Request is missing!');
2934
- }
2935
- return additionalData.httpRequest.body;
2936
- },
2937
- async getCredentials(type: string): Promise<ICredentialDataDecryptedObject | undefined> {
2938
- return getCredentials(workflow, node, type, additionalData, mode);
2939
- },
2940
- nodeHelpers: {
2941
- copyBinaryFile: async (filePath: string, fileName: string, mimeType?: string): Promise<IBinaryData> => {
2942
- // Use fs.promises.readFile instead of fsReadFileAsync
2943
- const buffer = await fs.readFile(filePath);
2944
- return prepareBinaryData(buffer, workflow.id || '', filePath, mimeType);
2945
- },
2946
- },
2947
- getHeaderData(): object {
2948
- if (additionalData.httpRequest === undefined) {
2949
- throw new Error('Request is missing!');
2950
- }
2951
- return additionalData.httpRequest.headers;
2952
- },
2953
- getMode: (): WorkflowExecuteMode => {
2954
- return mode;
2955
- },
2956
- getNode: () => {
2957
- return getNode(node);
2958
- },
2959
- getNodeParameter: (
2960
- parameterName: string,
2961
- fallbackValue?: any,
2962
- options?: IGetNodeParameterOptions,
2963
- ):
2964
- | NodeParameterValue
2965
- | INodeParameters
2966
- | NodeParameterValue[]
2967
- | INodeParameters[]
2968
- | object => {
2969
- const itemIndex = 0;
2970
- const runIndex = 0;
2971
-
2972
- let connectionInputData: INodeExecutionData[] = [];
2973
- let executionData: IExecuteData | undefined;
2974
- if (runExecutionData?.executionData !== undefined) {
2975
- executionData = runExecutionData.executionData.nodeExecutionStack[0];
2976
- if (executionData !== undefined) {
2977
- connectionInputData = executionData.data['main']?.[0] || [];
2978
- }
2979
- }
2980
-
2981
- return getNodeParameter(
2982
- workflow,
2983
- runExecutionData || null,
2984
- runIndex,
2985
- connectionInputData,
2986
- node,
2987
- parameterName,
2988
- itemIndex,
2989
- mode,
2990
- getAdditionalKeys(additionalData),
2991
- fallbackValue,
2992
- );
2993
- },
2994
- getParamsData(): object {
2995
- if (additionalData.httpRequest === undefined) {
2996
- throw new Error('Request is missing!');
2997
- }
2998
- return additionalData.httpRequest.params;
2999
- },
3000
- getQueryData(): object {
3001
- if (additionalData.httpRequest === undefined) {
3002
- throw new Error('Request is missing!');
3003
- }
3004
- return additionalData.httpRequest.query;
3005
- },
3006
- getRequestObject(): Request {
3007
- if (additionalData.httpRequest === undefined) {
3008
- throw new Error('Request is missing!');
3009
- }
3010
- return additionalData.httpRequest;
3011
- },
3012
- getResponseObject(): Response {
3013
- if (additionalData.httpResponse === undefined) {
3014
- throw new Error('Response is missing!');
3015
- }
3016
- return additionalData.httpResponse;
3017
- },
3018
- getNodeWebhookUrl: (name: string): string | undefined => {
3019
- return getNodeWebhookUrl(
3020
- name,
3021
- workflow,
3022
- node,
3023
- additionalData,
3024
- mode,
3025
- getAdditionalKeys(additionalData),
3026
- );
3027
- },
3028
- getTimezone: (): string => {
3029
- return getTimezone(workflow, additionalData);
3030
- },
3031
- getWorkflow: () => {
3032
- return getWorkflowMetadata(workflow);
3033
- },
3034
- getWorkflowStaticData(type: string): IDataObject {
3035
- return workflow.getStaticData(type, node);
3036
- },
3037
- getWebhookName(): string {
3038
- return webhookData.webhookDescription.name;
3039
- },
3040
- addInputData(
3041
- data: INodeExecutionData[][] | ExecutionError,
3042
- node: INode
3043
- ): { index: number, inputExecutionData: IRunExecutionData } {
3044
- const nodeName = node.name;
3045
- let currentNodeRunIndex = 0;
3046
- runExecutionData = {
3047
- startData: {
3048
- destinationNode: nodeName,
3049
- },
3050
- resultData: {
3051
- error: undefined,
3052
- runData: {
3053
- [nodeName]: [JSON.parse(JSON.stringify(data))]
3054
- },
3055
- lastNodeExecuted: nodeName,
3056
- },
3057
- executionData: {
3058
- contextData: {},
3059
- nodeExecutionStack: [],
3060
- waitingExecution: {},
3061
- },
3062
- waitTill: undefined,
3063
- }
3064
-
3065
- return { index: currentNodeRunIndex, inputExecutionData: runExecutionData };
3066
- },
3067
- addOutputData(
3068
- data: INodeExecutionData[][] | ExecutionError,
3069
- node: INode,
3070
- ): { outputExecutionData: IRunExecutionData } {
3071
- const nodeName = node.name;
3072
- const outputExecutionData = {
3073
- startData: {
3074
- destinationNode: nodeName,
3075
- },
3076
- resultData: {
3077
- error: undefined,
3078
- runData: {
3079
- [nodeName]: [JSON.parse(JSON.stringify(data))]
3080
- },
3081
- lastNodeExecuted: nodeName,
3082
- },
3083
- executionData: {
3084
- contextData: {},
3085
- nodeExecutionStack: [],
3086
- waitingExecution: {},
3087
- },
3088
- waitTill: undefined,
3089
- }
3090
- return { outputExecutionData };
3091
-
3092
- },
3093
- logAiEvent: (event: AiEvent, data?: string): void => {
3094
- // Simple implementation for logAiEvent in webhook functions
3095
- return;
3096
- },
3097
- prepareOutputData: NodeHelpers.prepareOutputData,
3098
- helpers: {
3099
- httpRequest,
3100
- async requestWithAuthentication(
3101
- this: IAllExecuteFunctions,
3102
- credentialsType: string,
3103
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
3104
- additionalCredentialOptions?: IAdditionalCredentialOptions,
3105
- ): Promise<any> {
3106
- return requestWithAuthentication.call(
3107
- this,
3108
- credentialsType,
3109
- requestOptions,
3110
- workflow,
3111
- node,
3112
- additionalData,
3113
- additionalCredentialOptions,
3114
- );
3115
- },
3116
- async prepareBinaryData(
3117
- binaryData: Buffer,
3118
- filePath?: string,
3119
- mimeType?: string,
3120
- ): Promise<IBinaryData> {
3121
- return prepareBinaryData.call(
3122
- this,
3123
- binaryData,
3124
- additionalData.executionId!,
3125
- filePath,
3126
- mimeType,
3127
- );
3128
- },
3129
- request: proxyRequestToAxios,
3130
- async requestOAuth2(
3131
- this: IAllExecuteFunctions,
3132
- credentialsType: string,
3133
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
3134
- oAuth2Options?: IOAuth2Options,
3135
- ): Promise<any> {
3136
- return requestOAuth2.call(
3137
- this,
3138
- credentialsType,
3139
- requestOptions,
3140
- node,
3141
- additionalData,
3142
- oAuth2Options,
3143
- );
3144
- },
3145
- async requestOAuth1(
3146
- this: IAllExecuteFunctions,
3147
- credentialsType: string,
3148
- requestOptions: OptionsWithUrl | requestPromise.RequestPromiseOptions,
3149
- ): Promise<any> {
3150
- return requestOAuth1.call(this, credentialsType, requestOptions);
3151
- },
3152
- async httpRequestWithAuthentication(
3153
- this: IAllExecuteFunctions,
3154
- credentialsType: string,
3155
- requestOptions: IHttpRequestOptions,
3156
- additionalCredentialOptions?: IAdditionalCredentialOptions,
3157
- ): Promise<any> {
3158
- return httpRequestWithAuthentication.call(
3159
- this,
3160
- credentialsType,
3161
- requestOptions,
3162
- workflow,
3163
- node,
3164
- additionalData,
3165
- additionalCredentialOptions,
3166
- );
3167
- },
3168
- returnJsonArray,
3169
- },
3170
- getInstanceId: () => {
3171
- // Return the node's instance ID if available, otherwise return an empty string
3172
- return node.id || '';
3173
- },
3174
- };
3175
- })(workflow, node) as IWebhookFunctions;
3176
- }
3177
-
3178
- export function getSupplyDataFunctions(
3179
- workflow: Workflow,
3180
- runExecutionData: IRunExecutionData,
3181
- runIndex: number,
3182
- connectionInputData: INodeExecutionData[],
3183
- inputData: ITaskDataConnections,
3184
- node: INode,
3185
- additionalData: IWorkflowExecuteAdditionalData,
3186
- mode: WorkflowExecuteMode,
3187
- nodeTypeData: INodeType,
3188
- closeFunctions: CloseFunction[],
3189
- ): ISupplyDataFunctions {
3190
- return ((workflow, runExecutionData, connectionInputData, inputData, node, nodeTypeData, closeFunctions) => {
3191
- return {
3192
- logger: Logger,
3193
- continueOnFail: () => {
3194
- return continueOnFail(node);
3195
- },
3196
- evaluateExpression: (expression: string, itemIndex: number) => {
3197
- return workflow.expression.resolveSimpleParameterValue(
3198
- `=${expression}`,
3199
- {},
3200
- runExecutionData,
3201
- runIndex,
3202
- itemIndex,
3203
- node.name,
3204
- connectionInputData,
3205
- mode,
3206
- getAdditionalKeys(additionalData),
3207
- );
3208
- },
3209
- async executeWorkflow(
3210
- workflowInfo: IExecuteWorkflowInfo,
3211
- inputData?: INodeExecutionData[],
3212
- ): Promise<any> {
3213
- return additionalData
3214
- .executeWorkflow(workflowInfo, additionalData, inputData)
3215
- .then(async (result) =>
3216
- BinaryDataManager.getInstance().duplicateBinaryData(
3217
- result,
3218
- additionalData.executionId!,
3219
- ),
3220
- );
3221
- },
3222
- getContext(type: string): IContextObject {
3223
- return NodeHelpers.getContext(runExecutionData, type, node);
3224
- },
3225
- async getCredentials(
3226
- type: string,
3227
- itemIndex?: number,
3228
- ): Promise<ICredentialDataDecryptedObject | undefined> {
3229
- return getCredentials(
3230
- workflow,
3231
- node,
3232
- type,
3233
- additionalData,
3234
- mode,
3235
- runExecutionData,
3236
- runIndex,
3237
- connectionInputData,
3238
- itemIndex,
3239
- );
3240
- },
3241
- getExecutionId: (): string => {
3242
- return additionalData.executionId!;
3243
- },
3244
- getInputData: (inputIndex = 0, inputName = 'main') => {
3245
- if (!Object.prototype.hasOwnProperty.call(inputData, inputName)) {
3246
- // Return empty array because else it would throw error when nothing is connected to input
3247
- return [];
3248
- }
3249
-
3250
- // TODO: Check if nodeType has input with that index defined
3251
- if (inputData[inputName].length < inputIndex) {
3252
- throw new Error(`Could not get input index "${inputIndex}" of input "${inputName}"!`);
3253
- }
3254
-
3255
- if (inputData[inputName][inputIndex] === null) {
3256
- // return [];
3257
- throw new Error(`Value "${inputIndex}" of input "${inputName}" did not get set!`);
3258
- }
3259
-
3260
- return inputData[inputName][inputIndex] as INodeExecutionData[];
3261
- },
3262
- getNodeParameter: (
3263
- parameterName: string,
3264
- itemIndex: number,
3265
- fallbackValue?: any,
3266
- ):
3267
- | NodeParameterValue
3268
- | INodeParameters
3269
- | NodeParameterValue[]
3270
- | INodeParameters[]
3271
- | object => {
3272
- return getNodeParameter(
3273
- workflow,
3274
- runExecutionData,
3275
- runIndex,
3276
- connectionInputData,
3277
- node,
3278
- parameterName,
3279
- itemIndex,
3280
- mode,
3281
- getAdditionalKeys(additionalData),
3282
- fallbackValue,
3283
- );
3284
- },
3285
- getMode: (): WorkflowExecuteMode => {
3286
- return mode;
3287
- },
3288
- getNode: () => {
3289
- return getNode(node);
3290
- },
3291
- getRestApiUrl: (): string => {
3292
- return additionalData.restApiUrl;
3293
- },
3294
- getTimezone: (): string => {
3295
- return getTimezone(workflow, additionalData);
3296
- },
3297
- getWorkflow: () => {
3298
- return getWorkflowMetadata(workflow);
3299
- },
3300
- getWorkflowDataProxy: (itemIndex: number): IWorkflowDataProxyData => {
3301
- const dataProxy = new WorkflowDataProxy(
3302
- workflow,
3303
- runExecutionData,
3304
- runIndex,
3305
- itemIndex,
3306
- node.name,
3307
- connectionInputData,
3308
- {},
3309
- mode,
3310
- getAdditionalKeys(additionalData),
3311
- );
3312
- return dataProxy.getDataProxy();
3313
- },
3314
- getWorkflowStaticData(type: string): IDataObject {
3315
- return workflow.getStaticData(type, node);
3316
- },
3317
- prepareOutputData: NodeHelpers.prepareOutputData,
3318
- async putExecutionToWait(waitTill: Date): Promise<void> {
3319
- runExecutionData.waitTill = waitTill;
3320
- },
3321
- sendMessageToUI(...args: any[]): void {
3322
- if (mode !== 'manual') {
3323
- return;
3324
- }
3325
- try {
3326
- if (additionalData.sendMessageToUI) {
3327
- additionalData.sendMessageToUI(node.name, args);
3328
- }
3329
- } catch (error: any) {
3330
- // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
3331
- Logger.warn(`There was a problem sending messsage to UI: ${error.message}`);
3332
- }
3333
- },
3334
- async sendResponse(response: IExecuteResponsePromiseData): Promise<void> {
3335
- await additionalData.hooks?.executeHookFunctions('sendResponse', [response]);
3336
- },
3337
- helpers: {
3338
- httpRequest,
3339
- async requestWithAuthentication(
3340
- this: IAllExecuteFunctions,
3341
- credentialsType: string,
3342
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
3343
- additionalCredentialOptions?: IAdditionalCredentialOptions,
3344
- ): Promise<any> {
3345
- return requestWithAuthentication.call(
3346
- this,
3347
- credentialsType,
3348
- requestOptions,
3349
- workflow,
3350
- node,
3351
- additionalData,
3352
- additionalCredentialOptions,
3353
- );
3354
- },
3355
- assertBinaryData(
3356
- itemIndex: number,
3357
- propertyName: string,
3358
- inputIndex = 0,
3359
- ): IBinaryData {
3360
- const binaryKeyData = inputData['main'][inputIndex]![itemIndex].binary;
3361
- if (binaryKeyData === undefined) {
3362
- throw new NodeOperationError(
3363
- node,
3364
- `This operation expects the node's input data to contain a binary file '${propertyName}', but none was found [item ${itemIndex}]`,
3365
- {
3366
- itemIndex,
3367
- description: 'Make sure that the previous node outputs a binary file',
3368
- },
3369
- );
3370
- }
3371
-
3372
- const binaryPropertyData = binaryKeyData[propertyName];
3373
- if (binaryPropertyData === undefined) {
3374
- throw new NodeOperationError(
3375
- node,
3376
- `The item has no binary field '${propertyName}' [item ${itemIndex}]`,
3377
- {
3378
- itemIndex,
3379
- description:
3380
- 'Check that the parameter where you specified the input binary field name is correct, and that it matches a field in the binary input',
3381
- },
3382
- );
3383
- }
3384
-
3385
- return binaryPropertyData;
3386
- },
3387
-
3388
- async prepareBinaryData(
3389
- binaryData: Buffer,
3390
- filePath?: string,
3391
- mimeType?: string,
3392
- ): Promise<IBinaryData> {
3393
- return prepareBinaryData.call(
3394
- this,
3395
- binaryData,
3396
- additionalData.executionId!,
3397
- filePath,
3398
- mimeType,
3399
- );
3400
- },
3401
- async getBinaryDataBuffer(
3402
- itemIndex: number,
3403
- propertyName: string,
3404
- inputIndex = 0,
3405
- ): Promise<Buffer> {
3406
- return getBinaryDataBuffer.call(this, inputData, itemIndex, propertyName, inputIndex);
3407
- },
3408
- request: proxyRequestToAxios,
3409
- async requestOAuth2(
3410
- this: IAllExecuteFunctions,
3411
- credentialsType: string,
3412
- requestOptions: OptionsWithUri | requestPromise.RequestPromiseOptions,
3413
- oAuth2Options?: IOAuth2Options,
3414
- ): Promise<any> {
3415
- return requestOAuth2.call(
3416
- this,
3417
- credentialsType,
3418
- requestOptions,
3419
- node,
3420
- additionalData,
3421
- oAuth2Options,
3422
- );
3423
- },
3424
- async requestOAuth1(
3425
- this: IAllExecuteFunctions,
3426
- credentialsType: string,
3427
- requestOptions: OptionsWithUrl | requestPromise.RequestPromiseOptions,
3428
- ): Promise<any> {
3429
- return requestOAuth1.call(this, credentialsType, requestOptions);
3430
- },
3431
- async httpRequestWithAuthentication(
3432
- this: IAllExecuteFunctions,
3433
- credentialsType: string,
3434
- requestOptions: IHttpRequestOptions,
3435
- additionalCredentialOptions?: IAdditionalCredentialOptions,
3436
- ): Promise<any> {
3437
- return httpRequestWithAuthentication.call(
3438
- this,
3439
- credentialsType,
3440
- requestOptions,
3441
- workflow,
3442
- node,
3443
- additionalData,
3444
- additionalCredentialOptions,
3445
- );
3446
- },
3447
- returnJsonArray,
3448
- normalizeItems,
3449
- },
3450
- getInstanceId: () => {
3451
- // Return the node's instance ID if available, otherwise return an empty string
3452
- return node.id || '';
3453
- },
3454
-
3455
- addInputData(
3456
- data: INodeExecutionData[][] | ExecutionError,
3457
- node: INode
3458
- ): { index: number, inputExecutionData: IRunExecutionData } {
3459
- const nodeName = node.name;
3460
- let currentNodeRunIndex = 0;
3461
- runExecutionData = {
3462
- startData: {
3463
- destinationNode: nodeName,
3464
- },
3465
- resultData: {
3466
- error: undefined,
3467
- runData: {
3468
- [nodeName]: [JSON.parse(JSON.stringify(data))]
3469
- },
3470
- lastNodeExecuted: nodeName,
3471
- },
3472
- executionData: {
3473
- contextData: {},
3474
- nodeExecutionStack: [],
3475
- waitingExecution: {},
3476
- },
3477
- waitTill: undefined,
3478
- }
3479
-
3480
- return { index: currentNodeRunIndex, inputExecutionData: runExecutionData };
3481
- },
3482
- addOutputData(
3483
- data: INodeExecutionData[][] | ExecutionError,
3484
- node: INode,
3485
- ): { outputExecutionData: IRunExecutionData } {
3486
- const nodeName = node.name;
3487
- const outputExecutionData = {
3488
- startData: {
3489
- destinationNode: nodeName,
3490
- },
3491
- resultData: {
3492
- error: undefined,
3493
- runData: {
3494
- [nodeName]: [JSON.parse(JSON.stringify(data))]
3495
- },
3496
- lastNodeExecuted: nodeName,
3497
- },
3498
- executionData: {
3499
- contextData: {},
3500
- nodeExecutionStack: [],
3501
- waitingExecution: {},
3502
- },
3503
- waitTill: undefined,
3504
- }
3505
- return { outputExecutionData };
3506
-
3507
- },
3508
- async getInputConnectionData(
3509
- this: IExecuteFunctions | ISupplyDataFunctions,
3510
- connectionType: NodeConnectionType,
3511
- itemIndex: number,
3512
- ): Promise<unknown> {
3513
- return await getInputConnectionData.call(
3514
- this,
3515
- workflow,
3516
- runExecutionData,
3517
- runIndex,
3518
- connectionInputData,
3519
- inputData,
3520
- additionalData,
3521
- connectionType,
3522
- mode,
3523
- itemIndex,
3524
- nodeTypeData,
3525
- closeFunctions,
3526
- );
3527
- },
3528
- };
3529
- })(workflow, runExecutionData, connectionInputData, inputData, node, nodeTypeData, closeFunctions);
3530
- }
3531
-
3532
- export async function getInputConnectionData(
3533
- this: IExecuteFunctions | ISupplyDataFunctions,
3534
- workflow: Workflow,
3535
- runExecutionData: IRunExecutionData,
3536
- runIndex: number,
3537
- connectionInputData: INodeExecutionData[],
3538
- inputData: ITaskDataConnections,
3539
- additionalData: IWorkflowExecuteAdditionalData,
3540
- connectionType: NodeConnectionType,
3541
- mode: WorkflowExecuteMode,
3542
- itemIndex: number,
3543
- nodeTypeData: INodeType,
3544
- closeFunctions: CloseFunction[],
3545
- ): Promise<unknown> {
3546
- const parentNode = this.getNode();
3547
- const startTime = Date.now();
3548
-
3549
- const nodeInputs = getNodeInputs(workflow, parentNode, nodeTypeData.description).map(
3550
- (input) => (typeof input === 'string' ? { type: input } : input),
3551
- ) as INodeInputConfiguration[];
3552
- const inputConfiguration = nodeInputs.find((input) => input.type === connectionType);
3553
- if (inputConfiguration === undefined) {
3554
- throw new NodeOperationError(
3555
- parentNode,
3556
- `Node does not have input of type`,
3557
- {
3558
- description: `Node ${parentNode.name} does not have input of type ${connectionType}`,
3559
- }
3560
- );
3561
- }
3562
-
3563
- const connectedNodes = getConnectedNodes(workflow, parentNode, connectionType);
3564
- if (connectedNodes.length === 0) {
3565
- if (inputConfiguration.required) {
3566
- throw new NodeOperationError(
3567
- parentNode,
3568
- `A ${inputConfiguration?.displayName ?? connectionType} sub-node must be connected and enabled`,
3569
- );
3570
- }
3571
- return inputConfiguration.maxConnections === 1 ? undefined : [];
3572
- }
3573
-
3574
- if (
3575
- inputConfiguration.maxConnections !== undefined &&
3576
- connectedNodes.length > inputConfiguration.maxConnections
3577
- ) {
3578
- throw new NodeOperationError(
3579
- parentNode,
3580
- `Only ${inputConfiguration.maxConnections} ${connectionType} sub-nodes are/is allowed to be connected`,
3581
- );
3582
- }
3583
-
3584
- const nodes: SupplyData[] = [];
3585
- for (const connectedNode of connectedNodes) {
3586
- const connectedNodeType = workflow.nodeTypes.getByNameAndVersion(
3587
- connectedNode.type,
3588
- connectedNode.typeVersion,
3589
- );
3590
-
3591
- if (!connectedNodeType) {
3592
- continue;
3593
- }
3594
-
3595
- if (connectedNodeType && !connectedNodeType.supplyData) {
3596
- throw new NodeOperationError(connectedNode, 'Node does not have a `supplyData` method defined', {
3597
- itemIndex,
3598
- });
3599
- } else {
3600
- try {
3601
- await additionalData.hooks?.executeHookFunctions('nodeExecuteBefore', [connectedNode.name, {
3602
- startTime: startTime,
3603
- executionTime: new Date().getTime() - startTime
3604
- }]);
3605
-
3606
- const context = getSupplyDataFunctions(
3607
- workflow,
3608
- runExecutionData,
3609
- runIndex,
3610
- connectionInputData,
3611
- inputData,
3612
- connectedNode,
3613
- additionalData,
3614
- mode,
3615
- nodeTypeData,
3616
- closeFunctions,
3617
- );
3618
-
3619
- const supplyData = await connectedNodeType.supplyData?.call(context, itemIndex);
3620
- if (supplyData) {
3621
- nodes.push(supplyData);
3622
-
3623
- if (supplyData.closeFunction) {
3624
- closeFunctions.push(supplyData.closeFunction);
3625
- }
3626
-
3627
- const taskData: ITaskData = {
3628
- startTime: startTime,
3629
- executionTime: new Date().getTime() - startTime
3630
- };
3631
-
3632
- if (!Object.prototype.hasOwnProperty.call(runExecutionData.resultData.runData, connectedNode.name)) {
3633
- runExecutionData.resultData.runData[connectedNode.name] = [];
3634
- }
3635
-
3636
- runExecutionData.resultData.runData[connectedNode.name][runIndex] = taskData;
3637
-
3638
- await additionalData.hooks?.executeHookFunctions('nodeExecuteAfter', [
3639
- connectedNode.name,
3640
- taskData,
3641
- runExecutionData
3642
- ]);
3643
- }
3644
- } catch (error: any) {
3645
- const taskData: ITaskData = {
3646
- startTime: startTime,
3647
- executionTime: new Date().getTime() - startTime,
3648
- error: error
3649
- };
3650
- runExecutionData.resultData.runData[connectedNode.name][runIndex] = taskData;
3651
-
3652
- await additionalData.hooks?.executeHookFunctions('nodeExecuteAfter', [
3653
- connectedNode.name,
3654
- taskData,
3655
- runExecutionData
3656
- ]);
3657
-
3658
- throw new NodeOperationError(connectedNode, `Error in sub-node ${connectedNode.name}`, {
3659
- itemIndex,
3660
- description: error?.message ?? 'Unknown error',
3661
- });
3662
- }
3663
- }
3664
- }
3665
-
3666
- return inputConfiguration.maxConnections === 1
3667
- ? (nodes || [])[0]?.response
3668
- : nodes.map((node) => node.response);
3669
- }
3670
-
3671
- function getNodeInputs(
3672
- workflow: Workflow,
3673
- node: INode,
3674
- nodeTypeData: INodeTypeDescription,
3675
- ): Array<NodeConnectionType | INodeInputConfiguration> {
3676
- if (Array.isArray(nodeTypeData?.inputs)) {
3677
- return nodeTypeData.inputs as Array<NodeConnectionType | INodeInputConfiguration>;
3678
- }
3679
-
3680
- // Calculate the outputs dynamically
3681
- try {
3682
- return (workflow.expression.getSimpleParameterValue(
3683
- node,
3684
- nodeTypeData.inputs,
3685
- 'internal',
3686
- {},
3687
- ) || []) as NodeConnectionType[];
3688
- } catch (e) {
3689
- console.warn('Could not calculate inputs dynamically for node: ', node.name);
3690
- return [];
3691
- }
3692
- }
3693
-
3694
- function getConnectedNodes(workflow: Workflow, node: INode, connectionType: NodeConnectionType) {
3695
- return workflow
3696
- .getParentNodes(node.name, connectionType, 1)
3697
- .map((nodeName) => workflow.getNode(nodeName))
3698
- .filter((node) => !!node)
3699
- .filter((node) => node.disabled !== true);
3700
- }