-
Notifications
You must be signed in to change notification settings - Fork 194
/
Copy pathindex.js
1623 lines (1407 loc) · 46.4 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const querystring = require('querystring');
const { promisify } = require('util');
const { URL } = require('url');
const _ = require('lodash');
const flatten = require('flat');
const FormData = require('form-data');
const {
recurseReplaceBank,
} = require('zapier-platform-core/src/tools/cleaner');
const { flattenPaths } = require('zapier-platform-core/src/tools/data');
const {
ErrorException,
HaltedException,
StopRequestException,
ExpiredAuthException,
RefreshTokenException,
InvalidSessionException,
DEFINED_ERROR_NAMES,
} = require('./exceptions');
const createInternalRequestClient = (input) => {
const addQueryParams = require('zapier-platform-core/src/http-middlewares/before/add-query-params');
const createInjectInputMiddleware = require('zapier-platform-core/src/http-middlewares/before/inject-input');
const createRequestClient = require('zapier-platform-core/src/tools/create-request-client');
const disableSSLCertCheck = require('zapier-platform-core/src/http-middlewares/before/disable-ssl-cert-check');
const logResponseModule = require('zapier-platform-core/src/http-middlewares/after/log-response');
const prepareRequest = require('zapier-platform-core/src/http-middlewares/before/prepare-request');
const prepareResponse = require('zapier-platform-core/src/http-middlewares/after/prepare-response');
// Before core 12.0.3, log-response.js module exported the logResponse()
// function, and it's the only export. Since core 12.0.3, logResponse()
// function is inside an exported object. So we do the following to make sure
// legacy-scripting-runner works before and after 12.0.3.
// Related PR: https://github.com/zapier/zapier-platform/pull/525
const logResponse =
typeof logResponseModule === 'function'
? logResponseModule
: logResponseModule.logResponse;
const options = {
skipDefaultMiddle: true,
};
const httpBefores = [
createInjectInputMiddleware(input),
prepareRequest,
addQueryParams,
];
const verifySSL = _.get(input, '_zapier.event.verifySSL');
if (verifySSL === false) {
httpBefores.push(disableSSLCertCheck);
}
const httpAfters = [prepareResponse, logResponse];
return createRequestClient(httpBefores, httpAfters, options);
};
const { bundleConverter, unflattenObject } = require('./bundle');
const {
markFileFieldsInBundle,
isAnyFileFieldSet,
isFileField,
LazyFile,
} = require('./file');
const {
createBeforeRequest,
createAfterResponse,
renderTemplate,
} = require('./middleware-factory');
const FIELD_TYPE_CONVERT_MAP = {
// field_type_in_wb: field_type_in_cli
bool: 'boolean',
copy: 'copy',
datetime: 'datetime',
dict: 'string',
file: 'file',
float: 'number',
int: 'integer',
password: 'password',
text: 'text',
unicode: 'string',
};
const cleanCustomFields = (fields) => {
return fields
.filter((field) => _.isPlainObject(field) && field.key)
.map((field) => {
if (field.type === 'dict') {
// For CLI, we set field.dict to true to represet a dict field instead
// of setting field.type to 'dict'
field.dict = true;
delete field.list;
}
field.type = FIELD_TYPE_CONVERT_MAP[field.type] || field.type;
return field;
});
};
const stringifyForFormData = (value) => {
const dataType = typeof value;
if (dataType === 'string') {
return value;
} else if (dataType === 'boolean') {
return value ? 'True' : 'False'; // mimic str(true) in Python
}
return JSON.stringify(value);
};
// Makes a multipart/form-data request body that can be set to request.body for
// node-fetch.
const makeMultipartForm = async (data, lazyFilesObject) => {
const form = new FormData();
if (data) {
if (_.isPlainObject(data)) {
_.each(data, (v, k) => {
if (v !== undefined && v !== null) {
form.append(k, stringifyForFormData(v));
}
});
} else {
if (typeof data !== 'string') {
data = JSON.stringify(data);
}
form.append('data', data);
}
}
const fileFieldKeys = Object.keys(lazyFilesObject);
const lazyFiles = Object.values(lazyFilesObject);
const fileMetas = await Promise.all(lazyFiles.map((f) => f.meta()));
const fileStreams = await Promise.all(lazyFiles.map((f) => f.readStream()));
_.zip(fileFieldKeys, fileMetas, fileStreams).forEach(
([k, meta, fileStream]) => {
form.append(k, fileStream, meta);
},
);
return form;
};
// Prepares request body from results.files and assign it to result.body. This
// accepts the request object returned by a KEY_pre_ method.
const addFilesToRequestBodyFromPreResult = async (request, event) => {
const originalHydrateUrls = _.map(event.originalFiles, (file, k) => file[1]);
const lazyFiles = _.reduce(
request.files,
(result, file, k) => {
let lazyFile;
if (Array.isArray(file) && file.length === 3) {
const [filename, newFileValue, contentType] = file;
// If pre_write changes the hydrate URL, file[1], we take it as a
// string content even if it looks like a URL
const loadUrl = originalHydrateUrls.includes(newFileValue);
lazyFile = LazyFile(
newFileValue,
{ filename, contentType },
{ dontLoadUrl: !loadUrl },
);
} else if (typeof file === 'string') {
lazyFile = LazyFile(file);
}
if (lazyFile) {
result[k] = lazyFile;
}
return result;
},
{},
);
delete request.headers['Content-Type'];
const form = await makeMultipartForm(request.data || '{}', lazyFiles);
request.body = form;
request.headers = { ...request.headers, ...form.getHeaders() };
return request;
};
// Reformats request.body into multipart/form-data for file upload. This
// accepts the CLI's bundle.request object.
const addFilesToRequestBodyFromBody = async (request, bundle) => {
const data = {};
const lazyFiles = {};
_.each(request.body, (v, k) => {
if (!isFileField(k, bundle)) {
data[k] = v;
} else if (typeof v === 'string') {
lazyFiles[k] = LazyFile(v);
}
});
delete request.headers['Content-Type'];
const form = await makeMultipartForm(JSON.stringify(data), lazyFiles);
request.body = form;
request.headers.Accept = '*/*';
request.headers = { ...request.headers, ...form.getHeaders() };
return request;
};
const pythonSerialize = (value) => {
if (typeof value === 'boolean') {
return value ? 'True' : 'False';
}
return value.toString();
};
const encodeFormData = (data) => {
const parts = Object.entries(data).reduce((result, [name, value]) => {
let newItems;
if (Array.isArray(value)) {
newItems = value;
} else if (_.isPlainObject(value)) {
newItems = Object.keys(value);
} else if (value != null) {
newItems = [value];
}
if (newItems) {
newItems = newItems
.filter((v) => v != null)
.map(pythonSerialize)
.map(encodeURIComponent)
.map((v) => `${name}=${v}`);
result.push(...newItems);
}
return result;
}, []);
return parts.join('&');
};
const parseFinalResult = async (result, event) => {
if (event.name.endsWith('.pre')) {
if (!_.isEmpty(result.files)) {
return addFilesToRequestBodyFromPreResult(result, event);
}
if (result.data) {
if (_.isPlainObject(result.data) && !event.name.startsWith('auth.')) {
// When a pre_(poll|write|search) gives an object for request.data, the
// data will always be form-urlencoded even if content-type is json. If
// the developer wants a JSON-encoded body, they need to encode the data
// using JSON.stringify().
result.body = encodeFormData(result.data);
} else {
// Old request was .data (string), new is .body (object), which matters
// for _pre
try {
result.body = JSON.parse(result.data);
} catch (e) {
result.body = result.data;
}
}
} else if (result.data === null || result.data === '') {
result.body = '';
}
// request.data isn't really used by CLI's z.request()
delete result.data;
return result;
}
// Old writes accepted a list, but CLI doesn't anymore, which matters for _write and _post_write
if (event.name === 'create.write' || event.name === 'create.post') {
let resultObj;
if (Array.isArray(result) && result.length) {
resultObj = result[0];
} else if (!Array.isArray(result)) {
resultObj = result;
} else {
resultObj = {};
}
return resultObj;
}
if (
event.name.endsWith('.input') ||
event.name.endsWith('.output') ||
event.name.endsWith('.input.post') ||
event.name.endsWith('.output.post')
) {
if (Array.isArray(result)) {
result = cleanCustomFields(result);
} else {
result = [];
}
}
return result;
};
const serializeValueForCurlies = (value) => {
if (typeof value === 'boolean') {
return value ? 'True' : 'False';
} else if (Array.isArray(value)) {
return value.join(',');
} else if (_.isPlainObject(value)) {
// Not sure if anyone would ever expect '[object Object]', but who knows?
return value.toString();
}
return value;
};
const createCurliesBank = (bundle, extra) => {
const bank = {
// This is for new curlies syntax, such as '{{bundle.inputData.var}}' and
// '{{bundle.authData.var}}'
bundle,
// These are for legacy curlies syntax without the 'bundle' prefix, such as
// {{var}}. The order matters.
...bundle.inputData,
...bundle.subscribeData,
...bundle.authData,
...extra,
};
const flattenedBank = flattenPaths(bank, {
perseve: {
'bundle.inputData': true,
},
});
return Object.entries(flattenedBank).reduce((coll, [key, value]) => {
coll[`{{${key}}}`] = serializeValueForCurlies(value);
return coll;
}, {});
};
const replaceCurliesInRequest = (request, bundle, extra) => {
const bank = createCurliesBank(bundle, extra);
return recurseReplaceBank(request, bank);
};
const cleanHeaders = (headers) => {
const newHeaders = {};
const badChars = /[\r\n\t]/g;
_.each(headers, (v, k) => {
if (k) {
k = k.replace(badChars, '').trim();
}
if (k) {
if (v && v.replace) {
v = v.replace(badChars, '').trim();
}
newHeaders[k] = v;
}
});
return newHeaders;
};
// Header keys are considered case insensitive. This function removes duplicate
// headers.
// dedupeHeaders({'x-key': 'one', 'X-KEY': 'two'}) returns {'x-key': 'two'}
const dedupeHeaders = (headers) => {
// lowerToFirstKeys stores the mapping from lowercased keys to the key that
// first appears in the headers
const lowerToFirstKeys = {};
const newHeaders = Object.entries(headers).reduce((result, [k, v]) => {
const lowerKey = k.toLowerCase();
if (lowerToFirstKeys[lowerKey] === undefined) {
lowerToFirstKeys[lowerKey] = k;
}
const firstKey = lowerToFirstKeys[lowerKey];
result[firstKey] = v;
return result;
}, {});
return newHeaders;
};
// Move all the query params from req.url to req.params. Make arrays if there
// are multiple values with the same name.
const mergeQueryParams = (req) => {
if (!req.url) {
return req;
}
const sepIndex = req.url.indexOf('?');
if (sepIndex < 0) {
return req;
}
// Extract the querystring. Don't use `new URL()` because the url might have
// curlies.
const querystring = req.url.substring(sepIndex + 1);
const searchParams = new URLSearchParams(querystring);
// Make an object like {name: ['alice', 'bob'], team: 'test'}
const params = Array.from(searchParams).reduce((result, [name, value]) => {
if (result[name] === undefined) {
result[name] = value;
return result;
}
if (!Array.isArray(result[name])) {
result[name] = [result[name]];
}
result[name].push(value);
return result;
}, {});
// Copy params collected from req.url to req.params
req.params = _.mergeWith(params, req.params, (dst, src) => {
if (src === null) {
// Legacy WB relies on Python serializing null, ugh
src = 'None';
}
if (dst === undefined) {
return src;
}
if (Array.isArray(dst)) {
if (Array.isArray(src)) {
return dst.concat(src);
} else {
dst.push(src);
return dst;
}
} else {
if (Array.isArray(src)) {
return [dst].concat(src);
} else {
return [dst, src];
}
}
});
// Remove query params from req.url as they all should be in req.params by now
req.url = req.url.substring(0, sepIndex);
return req;
};
const pruneQueryParams = (params) => {
// Only prune nulls and undefined's. Keep empty strings.
return Object.entries(params).reduce((result, [name, value]) => {
if (Array.isArray(value)) {
result[name] = value.filter((v) => v != null);
} else if (value != null) {
result[name] = value;
}
return result;
}, {});
};
const compileLegacyScriptingSource = (source, zcli, app, logger) => {
const { DOMParser, XMLSerializer } = require('xmldom');
const underscore = require('underscore');
underscore.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g,
};
return new Function( // eslint-disable-line no-new-func
'_',
'crypto',
'async',
'moment',
'DOMParser',
'XMLSerializer',
'atob',
'btoa',
'z',
'$',
'console',
'require',
'ErrorException',
'HaltedException',
'StopRequestException',
'ExpiredAuthException',
'RefreshTokenException',
'InvalidSessionException',
source + '\nreturn Zap;',
)(
underscore,
require('crypto'),
require('async'),
require('moment-timezone'),
DOMParser,
XMLSerializer,
require('./atob'),
require('./btoa'),
require('./zfactory')(zcli, app, logger),
require('./$'),
zcli.console,
require,
ErrorException,
HaltedException,
StopRequestException,
ExpiredAuthException,
RefreshTokenException,
InvalidSessionException,
);
};
const applyBeforeMiddleware = (befores, request, z, bundle) => {
befores = befores || [];
return befores.reduce(
(prev, cur) => prev.then((req) => cur(req, z, bundle)),
Promise.resolve(request),
);
};
const createEventNameToMethodMapping = (key) => {
return {
//
// Auth
//
'auth.session': 'get_session_info',
'auth.connectionLabel': 'get_connection_label',
'auth.oauth2.token.pre': 'pre_oauthv2_token',
'auth.oauth2.token.post': 'post_oauthv2_token',
'auth.oauth2.refresh.pre': 'pre_oauthv2_refresh',
//
// Triggers
//
'trigger.poll': `${key}_poll`,
'trigger.pre': `${key}_pre_poll`,
'trigger.post': `${key}_post_poll`,
'trigger.hook': `${key}_catch_hook`,
'trigger.hook.pre': `${key}_pre_hook`,
'trigger.hook.post': `${key}_post_hook`,
'trigger.hook.subscribe.pre': 'pre_subscribe',
'trigger.hook.subscribe.post': 'post_subscribe',
'trigger.hook.unsubscribe.pre': 'pre_unsubscribe',
'trigger.output.pre': `${key}_pre_custom_trigger_fields`,
'trigger.output.post': `${key}_post_custom_trigger_fields`,
//
// Creates
//
'create.write': `${key}_write`,
'create.pre': `${key}_pre_write`,
'create.post': `${key}_post_write`,
'create.input': `${key}_custom_action_fields`,
'create.input.pre': `${key}_pre_custom_action_fields`,
'create.input.post': `${key}_post_custom_action_fields`,
'create.output': `${key}_custom_action_result_fields`,
'create.output.pre': `${key}_pre_custom_action_result_fields`,
'create.output.post': `${key}_post_custom_action_result_fields`,
//
// Searches
//
'search.search': `${key}_search`,
'search.pre': `${key}_pre_search`,
'search.post': `${key}_post_search`,
'search.resource': `${key}_read_resource`,
'search.resource.pre': `${key}_pre_read_resource`,
'search.resource.post': `${key}_post_read_resource`,
'search.input': `${key}_custom_search_fields`,
'search.input.pre': `${key}_pre_custom_search_fields`,
'search.input.post': `${key}_post_custom_search_fields`,
'search.output': `${key}_custom_search_result_fields`,
'search.output.pre': `${key}_pre_custom_search_result_fields`,
'search.output.post': `${key}_post_custom_search_result_fields`,
//
// Hydration
//
'hydrate.method': key,
};
};
const legacyScriptingRunner = (Zap, zcli, input) => {
const app = _.get(input, '_zapier.app');
const logger = _.get(input, '_zapier.logger');
if (typeof Zap === 'string') {
Zap = compileLegacyScriptingSource(Zap, zcli, app, logger);
}
// Does string replacement ala WB, using bundle and a potential result object
const replaceVars = (templateString, bundle, result) => {
const options = {
interpolate: /{{([\s\S]+?)}}/g,
};
const values = { ...bundle.authData, ...bundle.inputData, ...result };
return _.template(templateString, options)(values);
};
const ensureIsType = (result, type) => {
if (!type) {
return result;
}
if (type.startsWith('array-')) {
if (Array.isArray(result)) {
return result;
} else if (result && typeof result === 'object') {
if (type === 'array-wrap') {
return [result];
} else {
// Find the first array in the response
for (const k in result) {
const value = result[k];
if (Array.isArray(value)) {
return value;
}
}
}
} else if (!result) {
return [];
}
throw new Error('JSON results array could not be located.');
} else if (type.startsWith('object-')) {
if (['number', 'string', 'boolean'].includes(typeof result)) {
// primitive types that aren't null or undefined
return { message: result };
} else if (_.isEmpty(result)) {
// null, undefined, empty object or array
return {};
} else if (_.isPlainObject(result)) {
return result;
} else if (
Array.isArray(result) &&
result.length > 0 &&
_.isPlainObject(result[0])
) {
// Used by auth test and auth label
return result[0];
}
throw new Error('JSON results object could not be located.');
}
return result;
};
/**
flattens trigger data for wb v1 apps
*/
const flattenTriggerData = (data) => {
for (const i in data) {
for (const j in data[i]) {
if (Array.isArray(data[i][j])) {
data[i][j] = textifyList(data[i][j]);
} else if (_.isPlainObject(data[i][j])) {
const flattened = flattenDictionary(j, data[i][j]);
data[i] = { ...data[i], ...flattened };
delete data[i][j];
}
}
}
return data;
};
/**
see handle_legacy_params in the python backend
*/
const handleLegacyParams = (data) => {
if (!_.isPlainObject(data)) {
return data;
}
const params = _.cloneDeep(data);
for (const i in data) {
if (_.isPlainObject(data[i])) {
const param = [];
for (const j in data[i]) {
param.push(j + '|' + data[i][j]);
}
params[i] = param.join('\n');
} else if (Array.isArray(data[i])) {
params[i] = data[i].join();
}
}
return params;
};
/**
see textify_list in the python backend
*/
const textifyList = (data) => {
if (!Array.isArray(data)) {
return data;
}
let out = '';
const allObj = data.every(_.isPlainObject);
const sep = allObj ? '\n' : ',';
for (const el of data) {
if (_.isPlainObject(el)) {
for (const key in el) {
out += `${key}: ${el[key]}${sep}`;
}
} else if (Array.isArray(el)) {
out += textifyList(el) + sep;
} else if (el === null) {
continue;
} else {
out += el + sep;
}
if (allObj) {
out += sep;
}
}
return out.replace(/[\n,]*$/, '');
};
const flattenDictionary = (prefix, data) => {
const flattenedData = flatten(_.cloneDeep(data), { delimiter: '__' });
const out = {};
for (const key in flattenedData) {
out[`${prefix}__${key}`] = flattenedData[key];
}
return out;
};
const chooseBetterError = (responseError, scriptError) => {
if (scriptError) {
if (!responseError || DEFINED_ERROR_NAMES.includes(scriptError.name)) {
return scriptError;
}
}
return responseError;
};
const runEvent = async (event, z, bundle) => {
if (!Zap || _.isEmpty(Zap) || !event || !event.name || !z) {
return;
}
const eventNameToMethod = createEventNameToMethodMapping(event.key);
const methodName = eventNameToMethod[event.name];
if (!methodName || !_.isFunction(Zap[methodName])) {
return;
}
const convertedBundle = await bundleConverter(bundle, event, z);
// In case the scripting method mutates the bundle
const bundleForLog = _.cloneDeep(convertedBundle);
// To know if request.files is changed by scripting
event.originalFiles = _.cloneDeep(
_.get(convertedBundle, 'request.files') || {},
);
const method = Zap[methodName].bind(Zap);
// method.length is the number of args method accepts
const isAsync = method.length > 1;
let result;
try {
if (isAsync) {
result = await promisify(method)(convertedBundle);
} else {
result = method(convertedBundle);
}
} catch (err) {
logger(`Errored calling legacy scripting ${methodName}`, {
log_type: 'bundle',
input: convertedBundle,
error_message: err.stack,
});
throw err;
}
logger(`Called legacy scripting ${methodName}`, {
log_type: 'bundle',
input: bundleForLog,
output: _.cloneDeep(result),
});
return parseFinalResult(result, event);
};
// Simulates how WB backend runs JS scripting methods
const runEventCombo = async (
bundle,
key,
preEventName,
postEventName,
fullEventName,
options,
) => {
options = {
// Options to deal with the final result returned by this function.
// * checkResponseStatus: throws an error if response status is not 2xx.
// * parseResponse:
// assumes response content is JSON and parse it. post method won't
// run if this is false.
// * ensureType: ensures the result type. Could be one of the following values:
// - false:
// returns whatever data parsed from response content or returned
// by the post method.
// - 'array-wrap': returns [result] if result is an object.
// - 'array-first':
// returns the first top-level array in the result if result
// is an object.
// - 'object-first': returns the first object if result is an array.
// * defaultToResponse: default to response if post method returns empty
checkResponseStatus: true,
parseResponse: true,
ensureType: false,
resetRequestForFullMethod: false,
defaultToResponse: false,
...options,
};
if (bundle.request) {
bundle.request = replaceCurliesInRequest(bundle.request, bundle);
}
if (_.get(app, 'legacy.needsTriggerData')) {
bundle.triggerData = {};
}
let result;
const eventNameToMethod = createEventNameToMethodMapping(key);
const preMethodName = preEventName ? eventNameToMethod[preEventName] : null;
const postMethodName = postEventName
? eventNameToMethod[postEventName]
: null;
const fullMethodName = fullEventName
? eventNameToMethod[fullEventName]
: null;
const fullMethod = fullMethodName ? Zap[fullMethodName] : null;
if (fullMethod) {
if (options.resetRequestForFullMethod) {
// Used by custom fields
bundle.request = { ...bundle.request, method: 'GET', url: '' };
}
// Running "full" scripting method like KEY_poll
try {
result = await runEvent({ key, name: fullEventName }, zcli, bundle);
} catch (error) {
if (error.name === 'StopRequestError') {
return ensureIsType(null, options.ensureType);
}
throw error;
}
} else {
const preMethod = preMethodName ? Zap[preMethodName] : null;
let request;
if (preMethod) {
try {
request = await runEvent({ key, name: preEventName }, zcli, bundle);
} catch (error) {
if (error.name === 'StopRequestError') {
return ensureIsType(null, options.ensureType);
}
throw error;
}
} else {
request = {};
}
request = { ...bundle.request, ...request };
const isBodyStream = typeof _.get(request, 'body.pipe') === 'function';
if (!preMethod && !isBodyStream && isAnyFileFieldSet(bundle)) {
// Enter here only when there's no KEY_pre method. When a KEY_pre method
// is defined, addFilesToRequestBodyFromPreResult() already does the
// file handling, so we don't want to do it again here.
await addFilesToRequestBodyFromBody(request, bundle);
}
// encode everything, but retain curlies - those are replaced in z.request
// important to maintain case here; `new URL()` lowercases the hostname,
// which may contain a variable like '{{process.env.URL}}'
request.url = encodeURI(request.url)
.replace(/%25/g, '%') // fixes double encoding
.replace(/%7B/g, '{')
.replace(/%7D/g, '}');
request.headers = cleanHeaders(request.headers);
request.headers = dedupeHeaders(request.headers);
request.allowGetBody = true;
request.serializeValueForCurlies = serializeValueForCurlies;
request.skipThrowForStatus = true;
request = mergeQueryParams(request);
if (request.params) {
request.params = pruneQueryParams(request.params);
}
if (_.get(app, 'legacy.skipEncodingChars')) {
// skipEncodingChars is only supported on core ^9.7.2, ^11.3.2 and >=12.x.
// core versions that don't support it will just ignore it.
request.skipEncodingChars = app.legacy.skipEncodingChars;
}
const response = await zcli.request(request);
if (!options.parseResponse) {
if (options.checkResponseStatus) {
response.skipThrowForStatus = false;
response.throwForStatus();
}
return response;
}
bundle.request = request;
const postMethod = postMethodName ? Zap[postMethodName] : null;
if (postMethod) {
let scriptError, responseError;
try {
result = await runEvent(
{ key, name: postEventName, response },
zcli,
bundle,
);
} catch (error) {
scriptError = error;
}
if (options.checkResponseStatus) {
// Raising this error AFTER postMethod is executed allows devs to
// intercept and throw another error from postMethod
response.skipThrowForStatus = false;
try {
response.throwForStatus();
} catch (error) {
responseError = error;
}
}
if (responseError || scriptError) {
throw chooseBetterError(responseError, scriptError);
}
if (options.defaultToResponse && !result) {
try {
result = zcli.JSON.parse(response.content);
} catch {
result = {};
}
}
} else {
if (options.checkResponseStatus) {
response.skipThrowForStatus = false;
response.throwForStatus();
}
try {
result = zcli.JSON.parse(response.content);
if (postEventName) {
result = await parseFinalResult(result, {
key,
name: postEventName,
});
}
} catch {
result = {};
}
}
}
result = ensureIsType(result, options.ensureType);
return result;
};
const fetchOAuth1Token = async (url, authParams) => {
const response = await zcli.request({
method: 'POST',
url,
auth: authParams,
skipThrowForStatus: true,
});
response.skipThrowForStatus = false;
response.throwForStatus();
return querystring.parse(response.content);
};
const runOAuth1GetRequestToken = (bundle) => {
const url = _.get(
app,
'legacy.authentication.oauth1Config.requestTokenUrl',
);
const templateContext = { ...bundle.authData, ...bundle.inputData };
const consumerKey = renderTemplate(process.env.CLIENT_ID, templateContext);
const consumerSecret = renderTemplate(
process.env.CLIENT_SECRET,
templateContext,
);
return fetchOAuth1Token(url, {
oauth_consumer_key: consumerKey,
oauth_consumer_secret: consumerSecret,
oauth_signature_method: 'HMAC-SHA1',
oauth_callback: bundle.inputData.redirect_uri,
});
};
const runOAuth1AuthorizeUrl = (bundle) => {
let url = _.get(app, 'legacy.authentication.oauth1Config.authorizeUrl');