forked from APIs-guru/aws2openapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1241 lines (1100 loc) · 49.3 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 assert = require('assert');
const _ = require('lodash');
const recurse = require('reftools/lib/recurse.js').recurse;
const awsRegions = require('aws-regions');
const ourVersion = require('./package.json').version;
const actions = ['get','post','put','patch','delete','head','options','trace'];
/*
https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html
https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-swagger-extensions.html
*/
const amzHeaders = ['X-Amz-Content-Sha256','X-Amz-Date','X-Amz-Algorithm','X-Amz-Credential','X-Amz-Security-Token',
'X-Amz-Signature','X-Amz-SignedHeaders'];
const s3Headers = ['x-amz-security-token'];
const v2Params = ['AWSAccessKeyId', 'Action', 'SignatureMethod', 'SignatureVersion', 'Timestamp', 'Version', 'Signature'];
let xmlQuery = false; // needs to be reinitialised per conversion
let multiParams = []; // needs to be reinitialised per conversion
/**
Removes starting and ending <p></p> markup if no other <p>'s exist
@param s {string} the string to clean
@returns the cleaned or original string
*/
function clean(s){
var org = s;
if (s && s.startsWith('<p>')) s = s.substr(3);
if (s && s.endsWith('</p>')) s = s.substr(0,s.length-4);
if (s && ((s.indexOf('<p>')>=0) || (s.indexOf('</p>')>=0))) return org;
return s;
}
/**
Checks the source spec is in a format version and protocol we expect to see
@param src {aws-spec} the specification to check
@returns boolean
*/
function validate(src){
var result = true;
var validProtocols = ['json','rest-json','rest-xml','query','ec2'];
if ((typeof src.version !== 'undefined') && (src.version != '2.0')) result = false; // seems to be ok if missing
if (validProtocols.indexOf(src.metadata.protocol)<0) result = false;
return result;
}
/**
rename an object property by removing and re-adding it
@param obj {object} the object to mutate
@param key {string} the property name to rename
@param newKey {string} the new property name
*/
function rename(obj,key,newKey){
if (typeof obj[key] !== 'undefined') {
obj[newKey] = obj[key];
delete obj[key];
}
}
function checkDef(openapi,container) {
assert.equal(typeof container.shape,'string');
if (!openapi.components.schemas[container.shape]) {
openapi.components.schemas[container.shape] = {};
}
}
// Taken from aws-sdk/lib/region_config.js:
function generateRegionPrefix(region) {
if (!region) return null;
var parts = region.split('-');
if (parts.length < 3) return null;
return parts.slice(0, parts.length - 2).join('-') + '-*';
}
// Build a OpenAPI v3-compatible 'servers' object for this endpoint, for all regions.
// For now this will be attached as x-servers, for v2 compatibility (see swaggerplusplus)
function buildServers(endpointPrefix, serviceName, awsRegionConfig) {
// This uses the same logic for config lookup as aws-sdk/lib/region_config.js
// Build a map of URL -> regions covered by that URL
const regionsByEndpoint = awsRegions.list().reduce((regionsByEndpoint, region) => {
// From the AWS SDK. Defines a list of keys for the config of this service, from
// most to least specific. We'll use the most specific that exists.
const regionPrefix = generateRegionPrefix(region.code);
const endpointKeys = [
[region.code, endpointPrefix],
[regionPrefix, endpointPrefix],
[region.code, '*'],
[regionPrefix, '*'],
['*', endpointPrefix],
['*', '*']
].map((item) => item[0] && item[1] ? item.join('/') : null);
const endpointConfigKey = _.find(endpointKeys, (k) => awsRegionConfig.rules[k]);
// Config is either a config, or a key for a config in the 'patterns' object
const endpointConfig = typeof awsRegionConfig.rules[endpointConfigKey] === 'string'
? awsRegionConfig.patterns[awsRegionConfig.rules[endpointConfigKey]]
: awsRegionConfig.rules[endpointConfigKey];
let endpoints = [];
// If no protocol is specified, both HTTP & HTTPS are allowed
if (endpointConfig.endpoint.match(/^https?:\/\//)) {
endpoints.push(endpointConfig.endpoint);
} else {
endpoints.push('http://' + endpointConfig.endpoint);
endpoints.push('https://' + endpointConfig.endpoint);
}
// If we have both region & general endpoints, add the general endpoint(s) too
if (endpointConfig.generalEndpoint) {
if (endpointConfig.generalEndpoint.match(/^https?:\/\//)) {
endpoints.push(endpointConfig.generalEndpoint);
} else {
endpoints.push('http://' + endpointConfig.generalEndpoint);
endpoints.push('https://' + endpointConfig.generalEndpoint);
}
}
endpoints.forEach((endpoint) => {
if (!regionsByEndpoint[endpoint]) {
regionsByEndpoint[endpoint] = [region];
} else {
regionsByEndpoint[endpoint].push(region);
}
});
return regionsByEndpoint;
}, {});
// Turn the endpoint URLs + regions list into nice url + description + vars objects
return Object.keys(regionsByEndpoint).map((endpoint) => {
const validRegions = regionsByEndpoint[endpoint];
const regionNames = validRegions.map(r => r.full_name);
const url = endpoint.replace('{service}', endpointPrefix);
const variables = {};
let description;
let endpointDescription = (validRegions.length === 1)
? " endpoint for " + regionNames[0]
: (validRegions.length <= 3)
? " endpoint for " + regionNames.slice(0, -1).join(', ')
+ " and " + regionNames[regionNames.length - 1]
: " multi-region endpoint";
if (url.includes('{region}')) {
variables['region'] = {
description: "The AWS region",
enum: validRegions.map((region) => region.code)
};
description = "The " + serviceName + endpointDescription
} else {
description = "The general " + serviceName + endpointDescription;
}
// Just used for s3, which allows either separator in many cases
if (url.includes('{dash-or-dot}')) {
variables['dash-or-dot'] = {
description: 'The service/region URL separator',
enum: ['.', '-']
};
}
for (let v in variables) {
variables[v].default = variables[v].enum[0];
}
return { url, variables, description };
});
}
function findResponsesForShape(openapi,shapeName){
var result = [];
for (var p in openapi.paths) {
var path = openapi.paths[p];
for (var a of actions){
var action = path[actions[a]];
if (action) {
var ok = false;
for (var r in action.responses) {
r = parseInt(r,10);
if ((r>=200) && (r<700)) {
var ref = (r.schema ? r.schema["$ref"] : '');
if (ref == '#/components/schemas/'+shapeName) ok = true;
}
}
if (ok) result.push(r);
}
}
}
}
function attachHeader(openapi,shapeName,header){
var responses = findResponsesForShape(openapi,shapeName);
for (var r in responses) {
var response = responses[r];
if (!response.header) {
response.headers = {};
}
var header = {};
header.description = '';
header.schema = { type: 'string' };
response.headers[header.locationName] = header;
}
}
function convertRegex(pattern) {
/* converted from coffeescript function https://raw.githubusercontent.com/drj11/posixbre/master/code/main.coffee */
var bre1token;
bre1token = function(tok) {
// In POSIX RE in a bracket expression \ matches itself.
if (/^\[/.test(tok)) {
tok = tok.replace(/\\/, '\\\\');
}
// In POSIX RE in a bracket expression an initial ] or initial ^] is allowed.
if (/^\[\^?\]/.test(tok)) {
return tok.replace(/]/, '\\]');
}
// Tokens for which we have to remove a leading backslash.
if (/^\\[(){}]$/.test(tok)) {
return tok[1];
}
// Tokens for which we have to add a leading backslash.
if (/^[+?|(){}]$/.test(tok)) {
return '\\' + tok;
}
// Everything else is unchanged
return tok;
};
// In POSIX RE, (?<!) is a negative lookbehind, which isn't supported in JS.
// We strip the negative lookbehind, creating a more permissive regex.
pattern = pattern.replace(/\(\?\<\![^)]*\)/g, '');
return pattern.replace(/\[\^?\]?[^]]*\]|\\.|./g, bre1token);
}
function transformShape(openapi,shape){
shape = _.cloneDeep(shape);
if (shape.type == 'structure') shape.type = 'object';
if (shape.type == 'float') {
shape.type = 'number';
shape.format = 'float';
}
if (shape.type == 'long') {
shape.type = 'integer'; // TODO verify this, is it simply an unbounded integer?
}
rename(shape,'members','properties');
if (shape.documentation) {
shape.description = clean(shape.documentation);
delete shape.documentation;
}
if (shape.type == 'blob') {
shape.type = 'string';
}
if (shape.type == 'string') {
if (typeof shape.min !== 'undefined') {
rename(shape,'min','minLength');
}
if (typeof shape.max !== 'undefined') {
rename(shape,'max','maxLength');
}
if (typeof shape.minLength === 'string') {
shape.minLength = parseInt(shape.minLength,10);
}
if (typeof shape.maxLength === 'string') {
shape.maxLength = parseInt(shape.maxLength,10);
}
if (shape.sensitive) {
shape.format = 'password';
delete shape.sensitive;
}
if (shape.pattern) {
try {
var regex = new RegExp(shape.pattern);
}
catch (e) {
shape.pattern = convertRegex(shape.pattern);
try {
var regex = new RegExp(shape.pattern);
}
catch (ex) {
rename(shape,'pattern','x-pattern');
}
}
}
}
if (shape.type == 'integer') {
rename(shape,'min','minimum');
rename(shape,'max','maximum');
if (typeof shape.minimum === 'string') {
shape.minimum = parseInt(shape.maximum,10);
}
if (typeof shape.maximum === 'string') {
shape.maximum = parseInt(shape.maximum,10);
}
}
if (shape.type == 'timestamp') {
shape.type = 'string';
delete shape.timestampFormat;
shape.format = 'date-time'; // TODO validate this, add a pattern for rfc822 etc
}
if (shape.type == 'list') {
shape.type = 'array';
rename(shape,'member','items');
rename(shape,'min','minItems');
rename(shape,'max','maxItems');
if (xmlQuery) { // issue #28
if (!shape.items.xml) shape.items.xml = { name: 'member' };
}
}
if (shape.type == 'map') {
rename(shape,'min','minProperties');
rename(shape,'max','maxProperties');
shape.type = 'object';
shape.additionalProperties = {
'$ref': '#/components/schemas/'+shape.value.shape
};
// TODO In OpenAPI 3.1+, we could use propertyNames/Patterns here, and
// use the shape.key.shape to only allow valid keys. For now we allow
// any string.
checkDef(openapi,shape.value);
delete shape.key;
delete shape.value;
}
if (shape.type == 'double') {
shape.type = 'number';
shape.format = 'double';
}
if (shape.type == 'number') {
rename(shape,'min','minimum');
rename(shape,'max','maximum');
}
if (shape.flattened) {
if (!shape.xml) shape.xml = {};
shape.xml.wrapped = (!shape.flattened);
delete shape.flattened;
}
if (typeof shape.union === 'boolean') {
delete shape.union;
}
delete shape.exception;
delete shape.fault;
delete shape.error;
delete shape.sensitive;
delete shape.synthetic;
delete shape.wrapper; // xml
delete shape.xmlOrder; // xml
recurse(shape,{},function(obj,key,state){
if (key == 'shape') {
if (state.pkey !== 'properties') {
obj["$ref"] = '#/components/schemas/'+obj[key];
checkDef(openapi,obj);
}
delete obj[key]; // TODO / FIXME validate this for runtime.lex.v2
}
if (key == 'documentation') {
obj.description = clean(obj.documentation);
delete obj.documentation;
}
if ((key == 'location') && (obj[key] == 'headers')) {
delete obj[key];
}
if ((key == 'location') && (obj[key] == 'statusCode')) {
delete obj[key]; // should already be pointed to by 'output'
}
if ((key == 'location') && ((obj[key] == 'header') || (obj[key] == 'headers'))) {
var header = obj[key]; // JRM clone
var newHeader = _.cloneDeep(header);
var required = shape.required;
var index = (required ? required.indexOf(state.pkey) : -1);
if (index>=0) {
required.splice(index,1);
if (required.length<=0) delete shape.required;
}
// we now need to know which response is referencing this shape
var shapeName = state.pkey;
attachHeader(openapi,shapeName,newHeader);
delete state.parent[state.pkey];
}
if ((key == 'location') && ((obj[key] == 'uri') || (obj[key] == 'querystring'))) {
var required = shape.required;
var index = (required ? required.indexOf(state.pkey) : -1);
if (index>=0) { // should always be true
required.splice(index,1);
if (required.length<=0) delete shape.required;
}
delete state.parent[state.pkey];
}
if (key == 'xmlNamespace') {
if (!shape.xml) shape.xml = {};
shape.xml.namespace = obj[key].uri;
delete obj.xmlNamespace;
}
if (key == 'xmlAttribute') {
if (!shape.xml) shape.xml = {};
shape.xml.attribute = obj[key];
delete obj.xmlAttribute;
}
if (key == 'flattened') {
if (!shape.xml) shape.xml = {};
shape.xml.wrapped = !obj[key];
delete obj.flattened;
}
if ((key == 'locationName') && (typeof obj.locationName === 'string')) {
delete obj.locationName;
}
if (key == 'payload') {
if (state.pkey !== 'properties') {
delete obj.payload; // TODO
}
}
if (key == 'box') {
delete obj.box; // just indicates if this is model around a simple type
}
if (key == 'idempotencyToken') {
delete obj.idempotencyToken; // TODO
}
if (key == 'jsonvalue') {
delete obj.jsonvalue; // TODO
}
if (key == 'queryName') {
delete obj.queryName; // TODO ec2 only
}
if (typeof obj.streaming === 'boolean') {
delete obj.streaming; // TODO
}
if (typeof obj.requiresLength === 'boolean') {
delete obj.requiresLength; // TODO
}
if (key == 'deprecated') {
// if boolean, it's a property which maps to OAS schemaObject
// deprecated ok, if an Object it's a property of the shape/schema
}
if (key == 'deprecatedMessage') {
if (!obj.description) {
obj.description = '';
}
obj.description += obj.deprecatedMessage;
delete obj.deprecatedMessage;
}
if (key === 'required' && Array.isArray(obj.required)) {
if (!obj.required.length) {
delete obj.required;
}
}
if ((key === 'event') && (typeof obj.event === 'boolean')) {
delete obj.event;
}
if (key === 'eventpayload') {
delete obj.eventpayload;
}
if (key === 'eventstream') {
delete obj.eventstream;
}
if (typeof obj[key] === 'object' && obj[key].locationName &&
(typeof obj[key].locationName === 'string')) { // refs #36
const newKey = obj[key].locationName;
if (newKey !== key) {
obj[key].xml = { name: newKey };
}
delete obj[key].locationName;
}
});
recurse(shape,{},function(obj,key,state){
// do this in separate pass, refs #41
if ((key === '$ref') && (typeof obj.$ref === 'string') && (Object.keys(obj).length > 1) && (!obj.allOf)) {
const $ref = obj.$ref;
delete obj.$ref;
delete obj.tags; // were previously being ignored as siblings of a $ref
delete obj.location;
state.parent[state.pkey] = { allOf: [ { $ref }, obj ] };
}
});
return shape;
}
function isEqualParameter(a,b) {
return ((a.name == b.name) && (a.in == b.in));
}
function postProcess(openapi,options){
Object.keys(openapi.paths).forEach(function(action){
if (action.parameters) {
action.parameters = _.uniqWith(action.parameters,isEqualParameter);
}
if (options.waiters) {
for (var w in options.waiters.waiters) {
var waiter = options.waiters.waiters[w];
if (waiter.operation == (action['x-aws-operation-name'] || action.operationId)) {
if (!action["x-waiters"]) {
action["x-waiters"] = [];
}
action["x-waiters"].push(waiter);
}
}
}
});
}
function deparameterisePath(s){
return s
.replace(/(\{.+?\})/g,'{param}')
.replace(/#.*/, '');
}
function doit(methodUri,op,pi) {
methodUri.replace(/(\{.+?\})/g,function(match,group1){
let name = match.replace('{','').replace('}','');
let param = (op.parameters||[]).concat(pi.parameters||[]).find(function(e,i,a){
return ((e.name == name) && (e.in == 'path'));
});
if (!param) {
//console.warn('Missing path parameter '+match);
let nparam = {};
nparam.name = name;
nparam.in = 'path';
nparam.required = true;
nparam.schema = { type: 'string' };
op.parameters.push(nparam); // correct for missing path parameters (2?)
}
return match;
});
}
function fillInMissingPathParameters(openapi) {
for (let p in openapi.paths) {
let pi = openapi.paths[p];
for (let o in pi) {
if (['get','post','put','patch','delete','head','options','trace'].indexOf(o)>=0) {
let op = pi[o];
doit(p,op,pi);
}
}
}
}
function patches(openapi) {
if (openapi.info["x-serviceName"] === 'data.mediastore') {
delete openapi.components.schemas.GetObjectResponse.required;
}
}
function attachParameters(openapi, src, op, action, consumes, options) {
if (op.input && op.input.shape) {
// Build parameters details for these params, according to the
// standard approach for each protocol.
const paramShape = src.shapes[op.input.shape];
paramShape.title = op.input.shape;
switch (src.metadata.protocol) {
case 'rest-xml':
case 'rest-json':
// Querystring/URI/header/headers are sent as params for the corresponding type
// Anything else is a body param
const [queryParams, bodyParams] = _.partition(
_.map(paramShape.members, (member, memberName) => _.omitBy({
name: member.locationName || memberName,
in: {
'header': 'header',
'uri': 'path',
'querystring': 'query'
}[member.location],
required: _.includes(paramShape.required, memberName),
description: clean(member.documentation || ''),
schema: {
...(src.shapes[member.shape] ?
transformShape(openapi, src.shapes[member.shape]) : {}
)
}
}, _.isUndefined)),
(param) => !!param.in
);
action.parameters = queryParams;
if (bodyParams.length) {
const requestBody = {
required: true,
schema: {
type: 'object',
required: bodyParams
.filter(p => p.required)
.map(p => p.name),
properties: _.mapValues(
_.keyBy(bodyParams, 'name'),
(param) => {
_.assign(param, param.schema);
return _.omit(param, ['name', 'required', 'schema'])
}
)
}
};
requestBody.content = {};
for (let mediatype of consumes) {
requestBody.content[mediatype] = {};
requestBody.content[mediatype].schema = requestBody.schema;
}
if (requestBody.schema.required.length === 0) {
delete requestBody.schema.required;
}
delete requestBody.schema;
action.requestBody = requestBody;
}
break;
case 'query':
case 'ec2':
// Serialises all params, into a query string for GET or requestBody for POST
if (op.http.method === 'GET') action.parameters = _.map(paramShape.members, (member, name) => _.omitBy({
name: src.metadata.protocol === 'ec2'
// EC2 uppercases the first char of param names, unless there's a queryName
// is provided. See query_param_serializer's ucfirst() in the AWS SDK.
? member.queryName || _.upperFirst(member.locationName || name)
: member.locationName || name,
in: op.http.method === 'POST' ? 'body' : 'query',
required: _.includes(paramShape.required, name),
description: clean(member.documentation || ''),
schema: {
...(src.shapes[member.shape] ?
transformShape(openapi, src.shapes[member.shape]) : {}
)
}
}, _.isUndefined))
else {
action.requestBody = { content: {} };
for (let mediatype of consumes) {
action.requestBody.content[mediatype] = { schema: { $ref: '#/components/schemas/'+op.input.shape } };
}
}
break;
case 'json':
// All params are sent as a JSON object in the body
checkDef(openapi,op.input);
action.requestBody = { required: true, content: {} };
for (let mediatype of consumes) {
action.requestBody.content[mediatype] = {
schema: { '$ref': '#/components/schemas/' + op.input.shape }
};
}
break;
default:
throw new Error('Unknown protocol: ' + src.metadata.protocol);
}
action.parameters = _.flatMap(action.parameters, (param) => {
// Any list parameters need to be filtered to just param-valid properties
// Any object query params need to be converted into their flattened forms
if (param.in !== 'query' && param.in !== 'body') {
return param;
}
if (param.additionalProperties) {
// A 'map' (in AWS terms) // TODO
// These effectively allow wildcard parameters. We can't represent this properly
// until OpenAPI 3, but in the short term we can enumerate N examples
return _.flatMap(_.range(param.maxProperties || 3), (i) => [{
name: param.name + '.' + i + '.' + 'key',
in: param.in,
schema: { type: 'string' }
}, {
name: param.name + '.' + i + '.' + 'value',
in: param.in,
schema: { type: 'string' } // Not accurate, but enough for now
}]);
} else if (param.type === 'object') {
// A 'structure' (in AWS terms). This is a defined set of properties.
// We don't deal with subobjects here, but we may need to in future.
return _.map(param.properties, (subParam, subParamName) => {
const subParamShape = subParam.$ref ?
transformShape(openapi,
// Go from $ref back to shape name (this is a bit nasty).
src.shapes[subParam.$ref.split('/').slice(-1)[0]]
) : {};
const type = subParam.type || subParamShape.type;
return _.omitBy({
name: param.name + '.' + subParamName,
in: param.in,
required: subParam.required,
description: [param.description, subParam.description].join('\n'),
// Simplify to stringy params. Not accurate, but enough for now:
schema: {
type: type === 'array' ? 'array' : 'string',
items: type === 'array' ? { type: 'string' } : undefined
}
}, _.isUndefined)
})
} else if (param.type === 'array') {
return {
name: param.name,
in: param.in,
required: param.required,
description: param.description,
schema: {
type: 'array',
items: { type: 'string' } // Not accurate, but enough for now
}
};
} else {
return param;
}
});
}
if (options.paginators && options.paginators.pagination[op.name]) {
var pag = options.paginators.pagination[op.name];
if (pag.limit_key && !_.some(action.parameters, { name: pag.limit_key })) {
var param = {};
param.name = pag.limit_key;
param["in"] = 'query';
param.schema = { type: 'string' };
param.description = 'Pagination limit';
param.required = false;
if (!action.parameters) {
action.parameters = [];
}
action.parameters.push(param);
}
if (pag.input_token && !_.some(action.parameters, { name: pag.input_token })) {
if (!Array.isArray(pag.input_token)) { //it usually isn't...
pag.input_token = [pag.input_token];
}
for (var t in pag.input_token) {
var param = {};
param.name = pag.input_token[t];
param["in"] = 'query';
param.schema = { type: 'string' };
param.description = 'Pagination token';
param.required = false;
if (!action.parameters) {
action.parameters = [];
}
action.parameters.push(param);
}
}
}
}
// Attach the given action at the given url/verb in a paths object.
// This assumes there are no conflicts, and will overwrite existing
// actions, so that should be checked first
function attachOperation(paths, url, method, action, signatureVersion) {
if (paths[url]) {
paths[url][method] = action;
return;
}
paths[url] = { [method]: action };
if (signatureVersion === 4) {
paths[url].parameters = [];
for (var h in amzHeaders) {
var param = {};
param["$ref"] = '#/components/parameters/'+amzHeaders[h];
paths[url].parameters.push(param);
}
}
else if (signatureVersion === 3) {
paths[url].parameters = [];
for (var h in s3Headers) {
var param = {};
param["$ref"] = '#/components/parameters/'+s3Headers[h];
paths[url].parameters.push(param);
}
}
else if (signatureVersion === 2) {
paths[url].parameters = [];
for (var p in v2Params) {
var param = {};
param["$ref"] = '#/components/parameters/'+v2Params[p];
paths[url].parameters.push(param);
}
}
}
module.exports = {
convert : function(src,options,callback) {
if (!validate(src)) return false;
process.nextTick(function(){
var err = {};
const produces = [];
const consumes = [];
let multiParams = []; // reinitialise global var
let xmlQuery = false; // reinitialise global var
var s = {};
s.openapi = "3.0.0";
s.info = {};
s.info.version = src.metadata.apiVersion
s.info["x-release"] = src.metadata.signatureVersion;
s.info.title = src.metadata.serviceFullName;
if (src.documentation) s.info.description = clean(src.documentation);
s.info["x-logo"] = {};
s.info["x-logo"].url = 'https://twitter.com/awscloud/profile_image?size=original';
s.info["x-logo"].backgroundColor = '#FFFFFF';
s.info.termsOfService = 'https://aws.amazon.com/service-terms/';
s.info.contact = {};
s.info.contact.name = 'Mike Ralphson';
s.info.contact.email = '[email protected]';
s.info.contact.url = 'https://github.com/mermade/aws2openapi';
s.info.contact["x-twitter"] = 'PermittedSoc';
s.info.license = {};
s.info.license.name = 'Apache 2.0 License';
s.info.license.url = 'http://www.apache.org/licenses/';
s.info['x-providerName'] = 'amazonaws.com';
s.info['x-serviceName'] = src.metadata.endpointPrefix;
if (src.metadata.signingName) s.info['x-aws-signingName'] = src.metadata.signingName;
var xorigin = [];
var origin = {contentType:'application/json',url:'https://raw.githubusercontent.com/aws/aws-sdk-js/master/apis/'+options.filename,converter:{url:'https://github.com/mermade/aws2openapi',version:ourVersion},'x-apisguru-driver': 'external'};
xorigin.push(origin);
s.info['x-origin'] = xorigin;
s.info['x-apiClientRegistration'] = {url:'https://portal.aws.amazon.com/gp/aws/developer/registration/index.html?nc2=h_ct'};
s.info['x-apisguru-categories'] = ['cloud'];
var preferred = true;
if (!options.preferred) options.preferred = [];
var prefEntry = options.preferred.find(function(e,i,a){
return e.serviceName === options.serviceName;
});
if (prefEntry) preferred = (prefEntry.preferred == src.metadata.apiVersion);
s.info['x-preferred'] = preferred;
var epp = src.metadata.endpointPrefix.split('.');
s.externalDocs = {
description: 'Amazon Web Services documentation',
// This is a best guess. Mostly correct, but not always.
// In future, it might be good to test it for 404s, and try
// some other possible URL formats too as a backup.
url: 'https://docs.aws.amazon.com/'+epp[epp.length-1]+'/'
};
s.servers = buildServers(
src.metadata.endpointPrefix,
src.metadata.serviceAbbreviation || src.metadata.serviceFullName,
options.regionConfig
);
s['x-hasEquivalentPaths'] = false; // may get removed later
s.paths = {};
s.components = { parameters: {}, securitySchemes: {}, schemas: {} };
s.components.securitySchemes = {};
s.components.securitySchemes.hmac = {};
s.components.securitySchemes.hmac.type = 'apiKey';
s.components.securitySchemes.hmac.name = 'Authorization';
s.components.securitySchemes.hmac["in"] = 'header';
var signatureVersion = null;
if (src.metadata.signatureVersion) {
if ((src.metadata.signatureVersion == 'v4') || (src.metadata.signatureVersion === 's3v4')) {
s.components.securitySchemes.hmac.description = 'Amazon Signature authorization v4';
s.components.securitySchemes.hmac["x-amazon-apigateway-authtype"] = 'awsSigv4';
signatureVersion = 4;
for (var h in amzHeaders) {
var header = {};
header.name = amzHeaders[h];
header["in"] = 'header';
header.schema = { type: 'string' };
header.required = false;
s.components.parameters[amzHeaders[h]] = header;
}
}
else if (src.metadata.signatureVersion == 's3') {
s.components.securitySchemes.hmac.description = 'Amazon S3 signature';
s.components.securitySchemes.hmac["x-amazon-apigateway-authtype"] = 'awsS3';
signatureVersion = 3;
// https://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html
for (var h in s3Headers) {
var header = {};
header.name = s3Headers[h];
header["in"] = 'header';
header.required = false;
header.schema = { type: 'string' };
s.components.parameters[s3Headers[h]] = header;
}
}
else if (src.metadata.signatureVersion == 'v2') {
s.components.securitySchemes.hmac.description = 'Amazon Signature authorization v2';
s.components.securitySchemes.hmac["x-amazon-apigateway-authtype"] = 'awsSigv2';
signatureVersion = 2;
// https://docs.aws.amazon.com/general/latest/gr/signature-version-2.html
for (var p in v2Params) {
var param = {};
param.name = v2Params[p];
param["in"] = 'query';
param.schema = { type: 'string' };
param.required = true;
s.components.parameters[v2Params[p]] = param;
}
}
else {
console.log('Unknown signatureVersion '+src.metadata.signatureVersion);
}
}
s.security = [];
var sec = {};
sec.hmac = [];
s.security.push(sec);
const protocol = src.metadata.protocol;
if (protocol == 'rest-json' ||
protocol == 'json' ||
(protocol == 'query' && src.metadata.jsonVersion)) {
consumes.push('application/json');
produces.push('application/json');
}
xmlQuery = (protocol == 'query' && src.metadata.xmlNamespace);
if (protocol == 'rest-xml' || protocol === 'ec2' || xmlQuery) {
consumes.push('text/xml');
produces.push('text/xml');
}
assert(produces && produces.length,'No mediatypes: '+protocol);
// EC2/Query protocol operations are all valid as either GET or POST, so in
// those cases we duplicate every operation, once for each method
const operations = (protocol === 'ec2' || protocol === 'query')
? _.flatMap(src.operations, (op) => [
_.merge(_.cloneDeep(op), { http: { method: 'GET' } }),
_.merge(_.cloneDeep(op), { http: { method: 'POST' } }),
])
: Object.values(src.operations);
for (let op of operations) {
var action = { };
if (op.deprecated) action.deprecated = true;
if (op.http) {
//if (s.schemes.indexOf('http')<0) { // TODO FIXME ?
// s.schemes.push('http');
//}
var method = op.http.method.toLocaleLowerCase();
if (protocol === 'ec2' || protocol === 'query') {
action['x-aws-operation-name'] = op.name; // Save separately, for reference elsewhere
action.operationId = method.toUpperCase() + '_' + op.name;
} else {
action.operationId = op.name; // TODO not handled is 'alias', add as a vendor extension if necessary
}
action.description = (op.documentation ? clean(op.documentation) : '');
if (op.documentationUrl) {
action.externalDocs = {
url: op.documentationUrl
};
}
action.responses = {};
var success = {};
success.description = 'Success';
if (op.output && op.output.shape) {
success.content = {};