-
Notifications
You must be signed in to change notification settings - Fork 214
/
Copy pathschemaUtils.js
5274 lines (4741 loc) · 199 KB
/
schemaUtils.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
/**
* This file contains util functions that need OAS-awareness
* utils.js contains other util functions
*/
const { ParseError } = require('./common/ParseError.js');
const { formatDataPath, checkIsCorrectType, isKnownType } = require('./common/schemaUtilsCommon.js'),
{ getConcreteSchemaUtils, isSwagger, validateSupportedVersion } = require('./common/versionUtils.js'),
async = require('async'),
sdk = require('postman-collection'),
schemaFaker = require('../assets/json-schema-faker.js'),
deref = require('./deref.js'),
_ = require('lodash'),
xmlFaker = require('./xmlSchemaFaker.js'),
openApiErr = require('./error.js'),
ajvValidationError = require('./ajValidation/ajvValidationError'),
utils = require('./utils.js'),
defaultOptions = require('../lib/options.js').getOptions('use'),
{ Node, Trie } = require('./trie.js'),
{ validateSchema } = require('./ajValidation/ajvValidation'),
inputValidation = require('./30XUtils/inputValidation'),
traverseUtility = require('traverse'),
SCHEMA_FORMATS = {
DEFAULT: 'default', // used for non-request-body data and json
XML: 'xml' // used for request-body XMLs
},
URLENCODED = 'application/x-www-form-urlencoded',
APP_JSON = 'application/json',
APP_JS = 'application/javascript',
TEXT_XML = 'text/xml',
APP_XML = 'application/xml',
TEXT_PLAIN = 'text/plain',
TEXT_HTML = 'text/html',
FORM_DATA = 'multipart/form-data',
REQUEST_TYPE = {
EXAMPLE: 'EXAMPLE',
ROOT: 'ROOT'
},
PARAMETER_SOURCE = {
REQUEST: 'REQUEST',
RESPONSE: 'RESPONSE'
},
HEADER_TYPE = {
JSON: 'json',
XML: 'xml',
INVALID: 'invalid'
},
PREVIEW_LANGUAGE = {
JSON: 'json',
XML: 'xml',
TEXT: 'text',
HTML: 'html'
},
authMap = {
basicAuth: 'basic',
bearerAuth: 'bearer',
digestAuth: 'digest',
hawkAuth: 'hawk',
oAuth1: 'oauth1',
oAuth2: 'oauth2',
ntlmAuth: 'ntlm',
awsSigV4: 'awsv4',
normal: null
},
propNames = {
QUERYPARAM: 'query parameter',
PATHVARIABLE: 'path variable',
HEADER: 'header',
BODY: 'request body',
RESPONSE_HEADER: 'response header',
RESPONSE_BODY: 'response body'
},
// Specifies types of processing Refs
PROCESSING_TYPE = {
VALIDATION: 'VALIDATION',
CONVERSION: 'CONVERSION'
},
FLOW_TYPE = {
authorizationCode: 'authorization_code',
implicit: 'implicit',
password: 'password_credentials',
clientCredentials: 'client_credentials'
},
// These are the methods supported in the PathItem schema
// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#pathItemObject
METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'],
// These headers are to be validated explicitly
// As these are not defined under usual parameters object and need special handling
IMPLICIT_HEADERS = [
'content-type', // 'content-type' is defined based on content/media-type of req/res body,
'accept',
'authorization'
],
crypto = require('crypto'),
DEFAULT_SCHEMA_UTILS = require('./30XUtils/schemaUtils30X'),
{ getRelatedFiles } = require('./relatedFiles'),
{ compareVersion } = require('./common/versionUtils.js'),
parse = require('./parse'),
{ getBundleContentAndComponents, parseFileOrThrow } = require('./bundle.js'),
MULTI_FILE_API_TYPE_ALLOWED_VALUE = 'multiFile',
MEDIA_TYPE_ALL_RANGES = '*/*';
/* eslint-enable */
// See https://github.com/json-schema-faker/json-schema-faker/tree/master/docs#available-options
schemaFaker.option({
requiredOnly: false,
optionalsProbability: 1.0, // always add optional fields
maxLength: 256,
minItems: 1, // for arrays
maxItems: 20, // limit on maximum number of items faked for (type: arrray)
useDefaultValue: true,
ignoreMissingRefs: true,
avoidExampleItemsLength: true // option to avoid validating type array schema example's minItems and maxItems props.
});
/**
*
* @param {*} input - input string that needs to be hashed
* @returns {*} sha1 hash of the string
*/
function hash(input) {
return crypto.createHash('sha1').update(input).digest('base64');
}
/**
* Remove or keep the deprecated properties according to the option
* @param {object} resolvedSchema - the schema to verify properties
* @param {boolean} includeDeprecated - Whether to include the deprecated properties
* @returns {undefined} undefined
*/
function verifyDeprecatedProperties(resolvedSchema, includeDeprecated) {
traverseUtility(resolvedSchema.properties).forEach(function (property) {
if (property && typeof property === 'object') {
if (property.deprecated === true && includeDeprecated === false) {
this.delete();
}
}
});
}
/**
* Safe wrapper for schemaFaker that resolves references and
* removes things that might make schemaFaker crash
* @param {*} oldSchema the schema to fake
* @param {string} resolveTo The desired JSON-generation mechanism (schema: prefer using the JSONschema to
generate a fake object, example: use specified examples as-is). Default: schema
* @param {*} resolveFor - resolve refs for flow validation/conversion (value to be one of VALIDATION/CONVERSION)
* @param {string} parameterSourceOption Specifies whether the schema being faked is from a request or response.
* @param {*} components list of predefined components (with schemas)
* @param {string} schemaFormat default or xml
* @param {object} schemaCache - object storing schemaFaker and schemaResolution caches
* @param {object} options - a standard list of options that's globally passed around. Check options.js for more.
* @returns {object} fakedObject
*/
function safeSchemaFaker(oldSchema, resolveTo, resolveFor, parameterSourceOption, components,
schemaFormat, schemaCache, options) {
var prop, key, resolvedSchema, fakedSchema,
schemaResolutionCache = _.get(schemaCache, 'schemaResolutionCache', {}),
schemaFakerCache = _.get(schemaCache, 'schemaFakerCache', {});
let concreteUtils = components && components.hasOwnProperty('concreteUtils') ?
components.concreteUtils :
DEFAULT_SCHEMA_UTILS;
const indentCharacter = options.indentCharacter,
stackLimit = options.stackLimit,
includeDeprecated = options.includeDeprecated;
resolvedSchema = deref.resolveRefs(oldSchema, parameterSourceOption, components, schemaResolutionCache,
resolveFor, resolveTo, 0, {}, stackLimit);
resolvedSchema = concreteUtils.fixExamplesByVersion(resolvedSchema);
key = JSON.stringify(resolvedSchema);
if (resolveTo === 'schema') {
key = 'resolveToSchema ' + key;
schemaFaker.option({
useExamplesValue: false
});
}
else if (resolveTo === 'example') {
key = 'resolveToExample ' + key;
schemaFaker.option({
useExamplesValue: true
});
}
if (resolveFor === PROCESSING_TYPE.VALIDATION) {
schemaFaker.option({
useDefaultValue: false,
avoidExampleItemsLength: false
});
}
key = hash(key);
if (schemaFakerCache[key]) {
return schemaFakerCache[key];
}
if (resolvedSchema.properties) {
// If any property exists with format:binary (and type: string) schemaFaker crashes
// we just delete based on format=binary
for (prop in resolvedSchema.properties) {
if (resolvedSchema.properties.hasOwnProperty(prop)) {
if (resolvedSchema.properties[prop].format === 'binary') {
delete resolvedSchema.properties[prop].format;
}
}
}
verifyDeprecatedProperties(resolvedSchema, includeDeprecated);
}
try {
if (schemaFormat === SCHEMA_FORMATS.XML) {
fakedSchema = xmlFaker(null, resolvedSchema, indentCharacter);
schemaFakerCache[key] = fakedSchema;
return fakedSchema;
}
// for JSON, the indentCharacter will be applied in the JSON.stringify step later on
fakedSchema = schemaFaker(resolvedSchema);
schemaFakerCache[key] = fakedSchema;
return fakedSchema;
}
catch (e) {
console.warn(
'Error faking a schema. Not faking this schema. Schema:', resolvedSchema,
'Error', e
);
return null;
}
}
/**
* Verifies if the deprecated operations should be added
*
* @param {object} operation - openAPI operation object
* @param {object} options - a standard list of options that's globally passed around. Check options.js for more.
* @returns {boolean} whether to add or not the deprecated operation
*/
function shouldAddDeprecatedOperation (operation, options) {
if (typeof operation === 'object') {
return !operation.deprecated ||
(operation.deprecated === true && options.includeDeprecated === true);
}
return false;
}
module.exports = {
safeSchemaFaker: safeSchemaFaker,
/** Analyzes the spec to determine the size of the spec,
* number of request that will be generated out this spec, and
* number or references present in the spec.
*
* @param {Object} spec JSON
* @return {Object} returns number of requests that will be generated,
* number of refs present and size of the spec.
*/
analyzeSpec: function (spec) {
var size,
numberOfRefs = 0,
specString,
numberOfRequests = 0;
// Stringify and add whitespaces as there would be in a normal file
// To get accurate disk size
specString = JSON.stringify(spec);
// Size in MB
size = Buffer.byteLength(specString, 'utf8') / (1024 * 1024);
// No need to check for number of requests or refs if the size is greater than 8 MB
// The complexity is 10.
if (size < 8) {
// Finds the number of requests that would be generated from this spec
if (spec.paths) {
Object.values(spec.paths).forEach((value) => {
Object.keys(value).forEach((key) => {
if (METHODS.includes(key)) {
numberOfRequests++;
}
});
});
}
// Number of times the term $ref is repeated in the spec.
numberOfRefs = (specString.match(/\$ref/g) || []).length;
}
return {
size,
numberOfRefs,
numberOfRequests
};
},
/** Determines the complexity score and stackLimit
*
* @param {Object} analysis the object returned by analyzeSpec function
* @param {Object} options Current options
*
* @returns {Object} computedOptions - contains two new options i.e. stackLimit and complexity score
*/
determineOptions: function (analysis, options) {
let size = analysis.size,
numberOfRefs = analysis.numberOfRefs,
numberOfRequests = analysis.numberOfRequests;
var computedOptions = _.clone(options);
computedOptions.stackLimit = 8;
// This is the score that is given to each spec on the basis of the
// number of references present in spec and the number of requests that will be generated.
// This ranges from 0-10.
computedOptions.complexityScore = 0;
// Anything above the size of 8MB will be considered a big spec and given the
// least stack limit and the highest complexity score.
if (size >= 8) {
console.warn('Complexity score = 10');
computedOptions.stackLimit = 2;
computedOptions.complexityScore = 10;
return computedOptions;
}
else if (size >= 5 || numberOfRequests > 1500 || numberOfRefs > 1500) {
computedOptions.stackLimit = 3;
computedOptions.complexityScore = 9;
return computedOptions;
}
else if (size >= 1 && (numberOfRequests > 1000 || numberOfRefs > 1000)) {
computedOptions.stackLimit = 5;
computedOptions.complexityScore = 8;
return computedOptions;
}
else if (numberOfRefs > 500 || numberOfRequests > 500) {
computedOptions.stackLimit = 6;
computedOptions.complexityScore = 6;
return computedOptions;
}
return computedOptions;
},
/**
* Changes the {} around scheme and path variables to :variable
* @param {string} url - the url string
* @returns {string} string after replacing /{pet}/ with /:pet/
*/
fixPathVariablesInUrl: function (url) {
// All complicated logic removed
// This simply replaces all instances of {text} with {{text}}
// text cannot have any of these 3 chars: /{}
// {{text}} will not be converted
let replacer = function (match, p1, offset, string) {
if (string[offset - 1] === '{' && string[offset + match.length + 1] !== '}') {
return match;
}
return '{' + p1 + '}';
};
return url.replace(/(\{[^\/\{\}]+\})/g, replacer);
},
/**
* Changes path structure that contains {var} to :var and '/' to '_'
* This is done so generated collection variable is in correct format
* i.e. variable '{{item/{itemId}}}' is considered separates variable in URL by collection sdk
* @param {string} path - path defined in openapi spec
* @returns {string} - string after replacing {itemId} with :itemId
*/
fixPathVariableName: function (path) {
// Replaces structure like 'item/{itemId}' into 'item-itemId-Url'
return path.replace(/\//g, '-').replace(/[{}]/g, '') + '-Url';
},
/**
* Returns a description that's usable at the collection-level
* Adds the collection description and uses any relevant contact info
* @param {*} openapi The JSON representation of the OAS spec
* @returns {string} description
*/
getCollectionDescription: function (openapi) {
let description = _.get(openapi, 'info.description', '');
if (_.get(openapi, 'info.contact')) {
let contact = [];
if (openapi.info.contact.name) {
contact.push(' Name: ' + openapi.info.contact.name);
}
if (openapi.info.contact.email) {
contact.push(' Email: ' + openapi.info.contact.email);
}
if (contact.length > 0) {
// why to add unnecessary lines if there is no description
if (description !== '') {
description += '\n\n';
}
description += 'Contact Support:\n' + contact.join('\n');
}
}
return description;
},
/**
* Get the format of content type header
* @param {string} cTypeHeader - the content type header string
* @returns {string} type of content type header
*/
getHeaderFamily: function(cTypeHeader) {
let mediaType = this.parseMediaType(cTypeHeader);
if (mediaType.type === 'application' &&
(mediaType.subtype === 'json' || _.endsWith(mediaType.subtype, '+json'))) {
return HEADER_TYPE.JSON;
}
if ((mediaType.type === 'application' || mediaType.type === 'text') &&
(mediaType.subtype === 'xml' || _.endsWith(mediaType.subtype, '+xml'))) {
return HEADER_TYPE.XML;
}
return HEADER_TYPE.INVALID;
},
/**
* Gets the description of the parameter.
* If the parameter is required, it prepends a `(Requried)` before the parameter description
* If the parameter type is enum, it appends the possible enum values
* @param {object} parameter - input param for which description needs to be returned
* @returns {string} description of the parameters
*/
getParameterDescription: function(parameter) {
if (!_.isObject(parameter)) {
return '';
}
return (parameter.required ? '(Required) ' : '') + (parameter.description || '') +
(parameter.enum ? ' (This can only be one of ' + parameter.enum + ')' : '');
},
/**
* Given parameter objects, it assigns example/examples of parameter object as schema example.
*
* @param {Object} parameter - parameter object
* @returns {null} - null
*/
assignParameterExamples: function (parameter) {
let example = _.get(parameter, 'example'),
examples = _.values(_.get(parameter, 'examples'));
if (example !== undefined) {
_.set(parameter, 'schema.example', example);
}
else if (examples) {
let exampleToUse = _.get(examples, '[0].value');
!_.isUndefined(exampleToUse) && (_.set(parameter, 'schema.example', exampleToUse));
}
},
/**
* Converts the necessary server variables to the
* something that can be added to the collection
* TODO: Figure out better description
* @param {object} serverVariables - Object containing the server variables at the root/path-item level
* @param {string} keyName - an additional key to add the serverUrl to the variable list
* @param {string} serverUrl - URL from the server object
* @returns {object} modified collection after the addition of the server variables
*/
convertToPmCollectionVariables: function(serverVariables, keyName, serverUrl = '') {
var variables = [];
if (serverVariables) {
_.forOwn(serverVariables, (value, key) => {
let description = this.getParameterDescription(value);
variables.push(new sdk.Variable({
key: key,
value: value.default || '',
description: description
}));
});
}
if (keyName) {
variables.push(new sdk.Variable({
key: keyName,
value: serverUrl,
type: 'string'
}));
}
return variables;
},
/**
* Returns params applied to specific operation with resolved references. Params from parent
* blocks (collection/folder) are merged, so that the request has a flattened list of params needed.
* OperationParams take precedence over pathParams
* @param {array} operationParam operation (Postman request)-level params.
* @param {array} pathParam are path parent-level params.
* @param {object} components - components defined in the OAS spec. These are used to
* resolve references while generating params.
* @param {object} options - a standard list of options that's globally passed around. Check options.js for more.
* @returns {*} combined requestParams from operation and path params.
*/
getRequestParams: function(operationParam, pathParam, components, options) {
options = _.merge({}, defaultOptions, options);
if (!Array.isArray(operationParam)) {
operationParam = [];
}
if (!Array.isArray(pathParam)) {
pathParam = [];
}
pathParam.forEach((param, index, arr) => {
if (_.has(param, '$ref')) {
arr[index] = this.getRefObject(param.$ref, components, options);
}
});
operationParam.forEach((param, index, arr) => {
if (_.has(param, '$ref')) {
arr[index] = this.getRefObject(param.$ref, components, options);
}
});
if (_.isEmpty(pathParam)) {
return operationParam;
}
else if (_.isEmpty(operationParam)) {
return pathParam;
}
// If both path and operation params exist,
// we need to de-duplicate
// A param with the same name and 'in' value from operationParam
// will get precedence
var reqParam = operationParam.slice();
pathParam.forEach((param) => {
var dupParam = operationParam.find(function(element) {
return element.name === param.name && element.in === param.in &&
// the below two conditions because undefined === undefined returns true
element.name && param.name &&
element.in && param.in;
});
if (!dupParam) {
// if there's no duplicate param in operationParam,
// use the one from the common pathParam list
// this ensures that operationParam is given precedence
reqParam.push(param);
}
});
return reqParam;
},
/**
* Generates a Trie-like folder structure from the root path object of the OpenAPI specification.
* @param {Object} spec - specification in json format
* @param {object} options - a standard list of options that's globally passed around. Check options.js for more.
* @param {boolean} fromWebhooks - true when we are creating the webhooks group trie - default: false
* @returns {Object} - The final object consists of the tree structure
*/
generateTrieFromPaths: function (spec, options, fromWebhooks = false) {
options = _.merge({}, defaultOptions, options);
// We only dereference the elements(if exist) that references to components/pathItems
spec = deref.dereferenceByConstraint(spec, /#\/components\/pathItems/);
let concreteUtils = getConcreteSchemaUtils({ type: 'json', data: spec }),
specComponentsAndUtils = {
concreteUtils
};
var paths = fromWebhooks ? spec.webhooks : spec.paths, // the first level of paths
currentPath = '',
currentPathObject = '',
commonParams = '',
collectionVariables = {},
operationItem,
pathLevelServers = '',
pathLength,
currentPathRequestCount,
currentNode,
i,
summary,
path,
pathMethods = [],
// creating a root node for the trie (serves as the root dir)
trie = new Trie(new Node({
name: '/'
})),
// returns a list of methods supported at each pathItem
// some pathItem props are not methods
// https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.2.md#pathItemObject
getPathMethods = function(pathKeys) {
var methods = [];
// TODO: Show warning for incorrect schema if !pathKeys
pathKeys && pathKeys.forEach(function(element) {
if (METHODS.includes(element)) {
methods.push(element);
}
});
return methods;
};
Object.assign(specComponentsAndUtils, concreteUtils.getRequiredData(spec));
for (path in paths) {
if (paths.hasOwnProperty(path)) {
currentPathObject = paths[path];
// discard the leading slash, if it exists
if (path[0] === '/') {
path = path.substring(1);
}
if (fromWebhooks) {
// When we work with webhooks the path value corresponds to the webhook's name
// and it won't be treated as path
currentPath = path === '' ? ['(root)'] : [path];
}
else {
// split the path into indiv. segments for trie generation
// unless path it the root endpoint
currentPath = path === '' ? ['(root)'] : path.split('/').filter((pathItem) => {
// remove any empty pathItems that might have cropped in
// due to trailing or double '/' characters
return pathItem !== '';
});
}
pathLength = currentPath.length;
// get method names available for this path
pathMethods = getPathMethods(Object.keys(currentPathObject));
// the number of requests under this node
currentPathRequestCount = pathMethods.length;
currentNode = trie.root;
// adding children for the nodes in the trie
// start at the top-level and do a DFS
for (i = 0; i < pathLength; i++) {
if (!currentNode.children[currentPath[i]]) {
// if the currentPath doesn't already exist at this node,
// add it as a folder
currentNode.addChildren(currentPath[i], new Node({
name: currentPath[i],
requestCount: 0,
requests: [],
children: {},
type: 'item-group',
childCount: 0
}));
// We are keeping the count children in a folder which can be a request or folder
// For ex- In case of /pets/a/b, pets has 1 childCount (i.e a)
currentNode.childCount += 1;
}
// requestCount increment for the node we just added
currentNode.children[currentPath[i]].requestCount += currentPathRequestCount;
currentNode = currentNode.children[currentPath[i]];
}
// extracting common parameters for all the methods in the current path item
if (currentPathObject.hasOwnProperty('parameters')) {
commonParams = currentPathObject.parameters;
}
// storing common path/collection vars from the server object at the path item level
if (currentPathObject.hasOwnProperty('servers')) {
pathLevelServers = currentPathObject.servers;
collectionVariables[this.fixPathVariableName(path)] = pathLevelServers[0];
delete currentPathObject.servers;
}
// add methods to node
// eslint-disable-next-line no-loop-func
_.each(pathMethods, (method) => {
// base operationItem
operationItem = currentPathObject[method] || {};
// params - these contain path/header/body params
operationItem.parameters = this.getRequestParams(operationItem.parameters, commonParams,
specComponentsAndUtils, options);
summary = operationItem.summary || operationItem.description;
currentNode.addMethod({
name: summary,
method: method,
path: path,
properties: operationItem,
type: 'item',
servers: pathLevelServers || undefined
});
currentNode.childCount += 1;
});
pathLevelServers = undefined;
commonParams = [];
}
}
return {
tree: trie,
variables: collectionVariables // server variables that are to be converted into collection variables.
};
},
addCollectionItemsFromWebhooks: function(spec, generatedStore, components, options, schemaCache) {
let webhooksObj = this.generateTrieFromPaths(spec, options, true),
webhooksTree = webhooksObj.tree,
webhooksFolder = new sdk.ItemGroup({ name: 'Webhooks' }),
variableStore = {},
webhooksVariables = [];
if (Object.keys(webhooksTree.root.children).length === 0) {
return;
}
for (let child in webhooksTree.root.children) {
if (
webhooksTree.root.children.hasOwnProperty(child) &&
webhooksTree.root.children[child].requestCount > 0
) {
webhooksVariables.push(new sdk.Variable({
key: this.cleanWebhookName(child),
value: '/',
type: 'string'
}));
webhooksFolder.items.add(
this.convertChildToItemGroup(
spec,
webhooksTree.root.children[child],
components,
options,
schemaCache,
variableStore,
true
),
);
}
}
generatedStore.collection.items.add(webhooksFolder);
webhooksVariables.forEach((variable) => {
generatedStore.collection.variables.add(variable);
});
},
/**
* Adds Postman Collection Items using paths.
* Folders are grouped based on trie that's generated using all paths.
*
* @param {object} spec - openAPI spec object
* @param {object} generatedStore - the store that holds the generated collection. Modified in-place
* @param {object} components - components defined in the OAS spec. These are used to
* resolve references while generating params.
* @param {object} options - a standard list of options that's globally passed around. Check options.js for more.
* @param {object} schemaCache - object storing schemaFaker and schmeResolution caches
* @returns {void} - generatedStore is modified in-place
*/
addCollectionItemsUsingPaths: function (spec, generatedStore, components, options, schemaCache) {
var folderTree,
folderObj,
child,
key,
variableStore = {};
/**
We need a trie because the decision of whether or not a node
is a folder or request can only be made once the whole trie is generated
This has a .trie and a .variables prop
*/
folderObj = this.generateTrieFromPaths(spec, options);
folderTree = folderObj.tree;
/*
* these are variables identified at the collection level
* they need to be added explicitly to collection variables
* deeper down in the trie, variables will be added directly to folders
* If the folderObj.variables have their own variables, we add
* them to the collectionVars
*/
if (folderObj.variables) {
_.forOwn(folderObj.variables, (server, key) => {
// TODO: Figure out what this does
this.convertToPmCollectionVariables(
server.variables, // these are path variables in the server block
key, // the name of the variable
this.fixPathVariablesInUrl(server.url)
).forEach((element) => {
generatedStore.collection.variables.add(element);
});
});
}
// Adds items from the trie into the collection that's in the store
for (child in folderTree.root.children) {
// A Postman request or folder is added if atleast one request is present in that sub-child's tree
// requestCount is a property added to each node (folder/request) while constructing the trie
if (folderTree.root.children.hasOwnProperty(child) && folderTree.root.children[child].requestCount > 0) {
generatedStore.collection.items.add(
this.convertChildToItemGroup(spec, folderTree.root.children[child],
components, options, schemaCache, variableStore)
);
}
}
for (key in variableStore) {
// variableStore contains all the kinds of variable created.
// Add only the variables with type 'collection' to generatedStore.collection.variables
if (variableStore[key].type === 'collection') {
const collectionVar = new sdk.Variable(variableStore[key]);
generatedStore.collection.variables.add(collectionVar);
}
}
},
/**
* Adds Postman Collection Items using tags.
* Each tag from OpenAPI tags object is mapped to a collection item-group (Folder), and all operation that has
* corresponding tag in operation object's tags array is included in mapped item-group.
*
* @param {object} spec - openAPI spec object
* @param {object} generatedStore - the store that holds the generated collection. Modified in-place
* @param {object} components - components defined in the OAS spec. These are used to
* resolve references while generating params.
* @param {object} options - a standard list of options that's globally passed around. Check options.js for more.
* @param {object} schemaCache - object storing schemaFaker and schmeResolution caches
* @returns {object} returns an object containing objects of tags and their requests
*/
addCollectionItemsUsingTags: function(spec, generatedStore, components, options, schemaCache) {
var globalTags = spec.tags || [],
paths = spec.paths || {},
pathMethods,
variableStore = {},
tagFolders = {};
// adding globalTags in the tagFolder object that are defined at the root level
_.forEach(globalTags, (globalTag) => {
tagFolders[globalTag.name] = {
description: _.get(globalTag, 'description', ''),
requests: []
};
});
_.forEach(paths, (currentPathObject, path) => {
var commonParams = [],
collectionVariables,
pathLevelServers = '';
// discard the leading slash, if it exists
if (path[0] === '/') {
path = path.substring(1);
}
// extracting common parameters for all the methods in the current path item
if (currentPathObject.hasOwnProperty('parameters')) {
commonParams = currentPathObject.parameters;
}
// storing common path/collection vars from the server object at the path item level
if (currentPathObject.hasOwnProperty('servers')) {
pathLevelServers = currentPathObject.servers;
// add path level server object's URL as collection variable
collectionVariables = this.convertToPmCollectionVariables(
pathLevelServers[0].variables, // these are path variables in the server block
this.fixPathVariableName(path), // the name of the variable
this.fixPathVariablesInUrl(pathLevelServers[0].url)
);
_.forEach(collectionVariables, (collectionVariable) => {
generatedStore.collection.variables.add(collectionVariable);
});
delete currentPathObject.servers;
}
// get available method names for this path (path item object can have keys apart from operations)
pathMethods = _.filter(_.keys(currentPathObject), (key) => {
return _.includes(METHODS, key);
});
_.forEach(pathMethods, (pathMethod) => {
var summary,
operationItem = currentPathObject[pathMethod] || {},
localTags = operationItem.tags;
// params - these contain path/header/body params
operationItem.parameters = this.getRequestParams(operationItem.parameters, commonParams,
components, options);
summary = operationItem.summary || operationItem.description;
// add the request which has not any tags
if (_.isEmpty(localTags)) {
let tempRequest = {
name: summary,
method: pathMethod,
path: path,
properties: operationItem,
type: 'item',
servers: pathLevelServers || undefined
};
if (shouldAddDeprecatedOperation(tempRequest.properties, options)) {
generatedStore.collection.items.add(this.convertRequestToItem(
spec, tempRequest, components, options, schemaCache, variableStore));
}
}
else {
_.forEach(localTags, (localTag) => {
// add undefined tag object with empty description
if (!_.has(tagFolders, localTag)) {
tagFolders[localTag] = {
description: '',
requests: []
};
}
tagFolders[localTag].requests.push({
name: summary,
method: pathMethod,
path: path,
properties: operationItem,
type: 'item',
servers: pathLevelServers || undefined
});
});
}
});
});
// Add all folders created from tags and corresponding operations
// Iterate from bottom to top order to maintain tag order in spec
_.forEachRight(tagFolders, (tagFolder, tagName) => {
var itemGroup = new sdk.ItemGroup({
name: tagName,
description: tagFolder.description
});
_.forEach(tagFolder.requests, (request) => {
if (shouldAddDeprecatedOperation(request.properties, options)) {
itemGroup.items.add(
this.convertRequestToItem(spec, request, components, options, schemaCache, variableStore));
}
});
// Add folders first (before requests) in generated collection
generatedStore.collection.items.prepend(itemGroup);
});
// variableStore contains all the kinds of variable created.
// Add only the variables with type 'collection' to generatedStore.collection.variables
_.forEach(variableStore, (variable) => {
if (variable.type === 'collection') {
const collectionVar = new sdk.Variable(variable);
generatedStore.collection.variables.add(collectionVar);
}
});
},
/**
* Generates an array of SDK Variables from the common and provided path vars
* @param {string} type - Level at the tree root/path level. Can be method/root/param.
* method: request(operation)-level, root: spec-level, param: url-level
* @param {Array<object>} providedPathVars - Array of path variables
* @param {object|array} commonPathVars - Object of path variables taken from the specification
* @param {object} components - components defined in the OAS spec. These are used to
* resolve references while generating params.
* @param {object} options - a standard list of options that's globally passed around. Check options.js for more.
* @param {object} schemaCache - object storing schemaFaker and schmeResolution caches
* @returns {Array<object>} returns an array of sdk.Variable
*/
convertPathVariables: function(type, providedPathVars, commonPathVars, components, options, schemaCache) {
options = _.merge({}, defaultOptions, options);
var variables = [];
// converting the base uri path variables, if any
// commonPathVars is an object for type = root/method
// array otherwise
if (type === 'root' || type === 'method') {
_.forOwn(commonPathVars, (value, key) => {
let description = this.getParameterDescription(value);
variables.push({
key: key,
value: type === 'root' ? '{{' + key + '}}' : value.default,
description: description
});
});
}
else {
_.forEach(commonPathVars, (variable) => {
let fakedData,
convertedPathVar;
this.assignParameterExamples(variable);
fakedData = options.schemaFaker ?
safeSchemaFaker(variable.schema || {}, options.requestParametersResolution, PROCESSING_TYPE.CONVERSION,
PARAMETER_SOURCE.REQUEST, components, SCHEMA_FORMATS.DEFAULT, schemaCache, options) : '';
convertedPathVar = this.convertParamsWithStyle(variable, fakedData, PARAMETER_SOURCE.REQUEST,
components, schemaCache, options);
variables = _.concat(variables, convertedPathVar);
});
}
// keep already provided varables (server variables) at last
return _.concat(variables, providedPathVars);
},