forked from Mermade/widdershins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.js
245 lines (224 loc) · 9.07 KB
/
common.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
'use strict';
var util = require('util');
var recurse = require('openapi_optimise/common.js').recurse;
var circular = require('openapi_optimise/circular.js');
var jptr = require('jgexml/jpath.js');
var sampler = require('openapi-sampler');
const MAX_SCHEMA_DEPTH=100;
/* originally from https://github.com/for-GET/know-your-http-well/blob/master/json/status-codes.json */
/* "Unlicensed", public domain */
var statusCodes = require('./statusCodes.json');
// could change these to be regexes...
var xmlContentTypes = ['application/xml', 'text/xml', 'image/svg+xml', 'application/rss+xml', 'application/rdf+xml', 'application/atom+xml', 'application/mathml+xml', 'application/hal+xml'];
var jsonContentTypes = ['application/json; charset=utf-8','application/json', 'text/json', 'application/hal+json', 'application/ld+json', 'application/json-patch+json'];
var yamlContentTypes = ['application/x-yaml', 'text/x-yaml'];
var formContentTypes = ['multipart/form-data', 'application/x-www-form-urlencoded', 'application/octet-stream'];
function clone(obj) {
return JSON.parse(JSON.stringify(obj));
}
function nop(obj) {
return obj;
}
function dereference(obj, circles, api, cloneFunc, aggressive) {
if (!cloneFunc) cloneFunc = nop;
let circFunc = circular.hasCircles;
if (aggressive) circFunc = circular.isCircular;
while (obj && obj["$ref"] && !circular.isCircular(circles, obj.$ref)) {
var oRef = obj.$ref;
obj = cloneFunc(jptr.jptr(api, oRef));
if (obj === false) console.error('Error dereferencing '+oRef);
obj["x-widdershins-oldRef"] = oRef;
}
var changes = 1;
while (changes > 0) {
changes = 0;
recurse(obj, {}, function (obj, state) {
if ((state.key === '$ref') && (typeof obj === 'string') && (!circFunc(circles, obj))) {
state.parents[state.parents.length - 2][state.keys[state.keys.length - 2]] = cloneFunc(jptr.jptr(api, obj));
state.parents[state.parents.length - 2][state.keys[state.keys.length - 2]]["x-widdershins-oldRef"] = obj;
if (state.parents[state.parents.length - 2][state.keys[state.keys.length - 2]] === false) console.error('Error dereferencing '+obj);
delete state.parent["$ref"]; // just in case
changes++;
}
});
}
return obj;
}
function doContentType(types, targets) {
for (var type in types) {
for (var target of targets) {
if (types[type] === target) return true;
}
}
return false;
}
function languageCheck(language, language_tabs, mutate) {
var lcLang = language.toLowerCase();
if (lcLang === 'c#') lcLang = 'csharp';
if (lcLang === 'c++') lcLang = 'cpp';
for (var l in language_tabs) {
var target = language_tabs[l];
if (typeof target === 'object') {
if (Object.keys(target)[0] === lcLang) {
return lcLang;
}
}
else {
if (target === lcLang) return lcLang;
}
}
if (mutate) {
var newLang = {};
newLang[lcLang] = language;
language_tabs.push(newLang);
return lcLang;
}
return false;
}
function gfmLink(text) {
text = text.trim().toLowerCase();
text = text.split("'").join('');
text = text.split('"').join('');
text = text.split('.').join('');
text = text.split('`').join('');
text = text.split(':').join('');
text = text.split('/').join('');
text = text.split('<').join('');
text = text.split('>').join('');
text = text.split('<').join('');
text = text.split('>').join('');
text = text.split(' ').join('-');
return text;
}
function extract(o,parent,seen,depth,callback){
JSON.stringify(o,function(k,v){
if (v && v.properties) {
for (let p in v.properties) {
var already = seen.indexOf(v.properties[p])>=0;
if (v.properties[p] && v.properties[p].type === 'array') already = true; // array processing
if (!already) {
let required = false;
if (v.required && Array.isArray(v.required)) {
required = v.required.indexOf(p)>=0;
}
let oldRef = '';
if (v.properties[p]) {
oldRef = v.properties[p]["x-widdershins-oldRef"]||v.properties[p].$ref||'';
}
let newProp = {};
newProp[p] = v.properties[p];
callback(newProp,depth,required,oldRef);
seen.push(v.properties[p]);
if (depth<MAX_SCHEMA_DEPTH) {
extract(v.properties[p],p,seen,depth+1,callback);
}
else {
throw new Error('Max schema depth exceeded');
}
}
}
}
if (v && v.type && v.type === 'array' && v.items) { // array processing
var name = k||'anonymous';
var dummy = {};
dummy.properties = {};
dummy.properties[name] = v.items;
dummy.properties[name].description = v.description;
dummy.properties[name]["x-widdershins-isArray"] = true;
extract(dummy,k,seen,depth,callback);
}
return v;
});
}
function schemaToArray(schema,depth,lines,trim) {
let seen = [];
extract(schema,'',seen,depth,function(obj,depth,required,oldRef){
let prefix = '»'.repeat(depth);
for (let p in obj) {
if (obj[p]) {
var prop = {};
prop.name = (prefix+' '+p).trim();
prop.in = 'body';
prop.type = obj[p].type||'Unknown';
if (obj[p].format) prop.type = prop.type+'('+obj[p].format+')';
if (((prop.type === 'object') || (prop.type === 'Unknown')) && oldRef) {
oldRef = oldRef.split('/').pop();
prop.type = '['+oldRef+'](#schema'+gfmLink(oldRef)+')';
}
if (obj[p]["x-widdershins-isArray"]) {
prop.type = '['+prop.type+']';
}
prop.required = required;
prop.description = (obj[p].description && obj[p].description !== 'undefined') ? obj[p].description : 'No description'; // the actual string 'undefined'
if (trim && typeof prop.description === 'string') prop.description = prop.description.split('\n').join(' ');
prop.depth = depth;
if (obj[p].enum) prop.schema = {enum:obj[p].enum};
lines.push(prop);
// #PS widdershins for some odd reason adds the pagination metadata to
// the top of the schema even though we specify in the swagger-php
// annotations to appear at the bottom, so we need to make sure for
// each schema to push these values to the bottom of the object.
var metaFields = ['result_count', 'result_offset', 'result_limit', 'result_total'];
for (var val in lines) {
metaFields.forEach(function(metaField) {
if (lines[val].name == metaField) {
lines.push(lines.splice(val,1)[0]);
}
});
}
}
}
});
if (!schema.properties && !schema.items) {
let prop = {};
prop.name = schema.title;
if (!prop.name && schema.type && schema.type !== 'object') prop.name = 'simple';
if (!prop.name && schema.additionalProperties) prop.name = 'additionalProperties';
if (!prop.name && schema.patternProperties) prop.name = 'patternProperties';
prop.description = schema.description||'No description';
if (trim) prop.description = prop.description.split('\n').join(' ');
prop.type = schema.type||'Unknown';
prop.required = false;
prop.in = 'body';
if (schema.format) prop.type = prop.type+'('+schema.format+')';
prop.depth = 0;
lines.unshift(prop);
}
}
function clean(obj) {
if (!obj) return {};
return JSON.parse(JSON.stringify(obj,function(k,v){
if (k.startsWith('x-widdershins')) return;
return v;
}));
}
function getSample(obj,options,samplerOptions,api){
if (options.sample && obj) {
try {
var sample = sampler.sample(obj,samplerOptions,api);
if (typeof sample !== 'undefined') return sample;
}
catch (ex) {
console.error('# ' + ex);
if (options.verbose) {
console.error(ex);
}
}
}
return clean(obj);
}
module.exports = {
statusCodes : statusCodes,
xmlContentTypes : xmlContentTypes,
jsonContentTypes : jsonContentTypes,
yamlContentTypes : yamlContentTypes,
formContentTypes : formContentTypes,
dereference : dereference,
doContentType : doContentType,
languageCheck : languageCheck,
clone : clone,
clean : clean,
getSample : getSample,
gfmLink : gfmLink,
schemaToArray : schemaToArray
};