-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathremove-query-from-paths.js
526 lines (461 loc) · 13.7 KB
/
remove-query-from-paths.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
/**
* @copyright Copyright 2021 Kevin Locke <kevin@kevinlocke.name>
* @license MIT
* @module "openapi-transformers/remove-query-from-paths.js"
*/
import { METHODS } from 'node:http';
import { isDeepStrictEqual } from 'node:util';
import OpenApiTransformerBase from 'openapi-transformer-base';
import visit from 'openapi-transformer-base/visit.js';
const oasVersionSymbol = Symbol('openApiVersion');
const pathVarNameToParamsSymbol = Symbol('pathVarNameToParams');
const httpMethodSet = new Set(METHODS);
function isArrayEqual(array1, array2) {
if (array1 === undefined) {
array1 = [];
}
if (array2 === undefined) {
array2 = [];
}
return isDeepStrictEqual(array1, array2);
}
function valueToType(value) {
const type = typeof value;
if (value === undefined || type === 'symbol') {
throw new TypeError(`${type} type not available in JSON Schema`);
}
return type === 'number' && value % 1 === 0 ? 'integer'
: value === null ? 'null'
: type;
}
function createConstQueryParam(name, value) {
const oasVersion = this[oasVersionSymbol];
if (oasVersion.startsWith('2.')) {
return {
name,
in: 'query',
required: true,
type: valueToType(value),
enum: [value],
};
}
if (oasVersion.startsWith('3.0')) {
return {
name,
in: 'query',
required: true,
schema: {
enum: [value],
},
};
}
return {
name,
in: 'query',
required: true,
schema: {
const: value,
},
};
}
// FIXME: How to handle unpaired {}
// FIXME: How to handle = in {}
// FIXME: How to handle %-encoded characters in {}
// FIXME: How to handle missing variable name (e.g. /a/{}/b)
function parseQueryParams(query) {
const ampQuery = `&${query}`;
const paramValueRE =
/&([^{}&=]*(?:\{[^{}]*\}[^{}&=]*)*)(?:=([^{}&]*(?:\{[^{}]*\}[^{}&]*)*))?/y;
const paramMap = new Map();
let paramValueMatch;
while (paramValueRE.lastIndex < ampQuery.length
// eslint-disable-next-line no-cond-assign
&& (paramValueMatch = paramValueRE.exec(ampQuery)) !== null) {
if (paramValueMatch[0] === '&') {
// Nothing after &
continue;
}
const param = paramValueMatch[1];
const pvarStart = param.indexOf('{');
const pvarEnd = param.indexOf('}');
if (pvarStart > 0) {
if (pvarEnd > pvarStart) {
this.warn('Unable to handle query param with variable name', param);
} else {
this.warn('Unpaired "{" in query param name', param);
}
return undefined;
}
if (pvarEnd >= 0) {
this.warn('Unpaired "}" in query param name', param);
return undefined;
}
const value = paramValueMatch[2] || '';
const qvarStart = value.indexOf('{');
const qvarEnd = value.indexOf('}');
if (qvarStart > 0 || (qvarStart === 0 && qvarEnd !== value.length - 1)) {
this.warn(
'Unable to handle query value with constant and variable parts',
value,
);
return undefined;
}
if (qvarEnd < qvarStart) {
this.warn(
'Unpaired "%s" in query value',
qvarEnd >= 0 ? '}' : '{',
param,
);
return undefined;
}
// TODO: Convert to param with `type: array` and `explode: true`?
if (paramMap.has(param)) {
this.warn('Ignoring path with duplicate query parameter', param);
return undefined;
}
paramMap.set(param, value);
}
if (paramValueRE.lastIndex !== ampQuery.length) {
this.warn('Unable to parse query parameters', query);
return undefined;
}
return paramMap;
}
function combineParameters(opParams, pathParams) {
if (opParams === undefined) {
return pathParams;
}
if (!Array.isArray(opParams)) {
return opParams;
}
if (opParams.length === 0) {
return pathParams;
}
return [
...opParams,
...pathParams
// Don't include params from Path Item overridden by Operation
.filter((pp) => pp && !opParams.some((op) => op
&& op.name === pp.name
&& op.in === pp.in)),
];
}
function moveParameters(pathItem) {
const { parameters, ...newPathItem } = pathItem;
if (parameters === undefined
|| (Array.isArray(parameters) && parameters.length === 0)) {
return pathItem;
}
for (const [method, operation] of Object.entries(pathItem)) {
if (operation !== null
&& typeof operation === 'object'
&& httpMethodSet.has(method.toUpperCase())) {
newPathItem[method] = {
...operation,
parameters: combineParameters(operation.parameters, parameters),
};
}
}
return newPathItem;
}
function moveServers(pathItem) {
const { servers, ...newPathItem } = pathItem;
if (servers === undefined
|| (Array.isArray(servers) && servers.length === 0)) {
return pathItem;
}
for (const [method, operation] of Object.entries(pathItem)) {
if (operation !== null
&& typeof operation === 'object'
&& operation.servers === undefined
&& httpMethodSet.has(method.toUpperCase())) {
newPathItem[method] = {
...operation,
servers,
};
}
}
return newPathItem;
}
function mergePathItems(pathItem1, pathItem2) {
if (!isArrayEqual(pathItem1.parameters, pathItem2.parameters)) {
// TODO: Keep common parameters at Path Item level
pathItem1 = moveParameters(pathItem1);
pathItem2 = moveParameters(pathItem2);
}
if (!isArrayEqual(pathItem1.servers, pathItem2.servers)) {
pathItem1 = moveServers(pathItem1);
pathItem2 = moveServers(pathItem2);
}
const combined = { ...pathItem2 };
for (const [prop, value1] of Object.entries(pathItem1)) {
if (value1 !== undefined
&& prop !== 'parameters'
&& prop !== 'servers') {
const value2 = pathItem2[prop];
if (value2 !== undefined && !isDeepStrictEqual(value1, value2)) {
this.transformPath.push(prop);
this.warn(
'Refusing to overwrite %o with %o',
value2,
value1,
);
this.transformPath.pop();
return undefined;
}
combined[prop] = value1;
}
}
return combined;
}
function transformParameters(parameters) {
const pathVarNameToParams = this[pathVarNameToParamsSymbol];
return parameters.flatMap((param) => {
if (param === null
|| typeof param !== 'object'
|| param.in !== 'path') {
return param;
}
const newParams = pathVarNameToParams.get(param.name);
if (newParams === undefined) {
return param;
}
return newParams
.map((newParam) => ({ ...param, ...newParam }))
// If the parameter already exists, avoid duplicating it
.filter((newParam) => !parameters.some((p) => p
&& p !== param
&& p.name === newParam.name
&& p.in === newParam.in));
});
}
/**
* Transformer to remove query component of path in paths object.
*
* Including the query portion of a URL in path is not allowed in any current
* version of OpenAPI
* https://github.com/OAI/OpenAPI-Specification/issues/468#issuecomment-142393969
* but some authors include it for various reasons.
*
* Operations which would conflict with existing operations on the same path
* (excluding query parameters) are left unchanged.
* See QueriesToXMsPathsTransformer for another way to handle these.
*/
export default class RemoveQueryFromPathsTransformer
extends OpenApiTransformerBase {
constructor() {
super();
this[oasVersionSymbol] = undefined;
this[pathVarNameToParamsSymbol] = undefined;
}
transformOperation(operation) {
if (typeof operation !== 'object'
|| operation === null
|| Array.isArray(operation)) {
this.warn('Ignoring non-object Operation', operation);
return operation;
}
const { parameters } = operation;
if (!Array.isArray(parameters) || parameters.length === 0) {
if (parameters !== undefined && !Array.isArray(parameters)) {
this.warn('Ignoring non-Array parameters', parameters);
}
return operation;
}
return {
...operation,
parameters: visit(
this,
transformParameters,
'parameters',
parameters,
),
};
}
transformPathItem(pathItem) {
pathItem = super.transformPathItem(pathItem);
if (typeof pathItem !== 'object'
|| pathItem === null
|| Array.isArray(pathItem)) {
// Already warned by super.transformPathItem(pathItem)
return pathItem;
}
const { parameters } = pathItem;
if (!Array.isArray(parameters) || parameters.length === 0) {
// Already warned by super.transformPathItem(pathItem)
return pathItem;
}
return {
...pathItem,
parameters: visit(
this,
transformParameters,
'parameters',
parameters,
),
};
}
transformPaths(paths) {
if (typeof paths !== 'object' || paths === null || Array.isArray(paths)) {
this.warn('Ignoring non-object Paths', paths);
return paths;
}
// RegExp to match a path with a query part and optionally fragment part
// Careful to avoid matching ? or # in variable name as part of path
// (OAS 3.1.0 is clear that they are disallowed, but some path templating
// languages use ? in particular, so be prepared.)
const pathRE =
/^([^{?#]*(?:\{[^}]*\}[^{?#]*)*)\?([^{#]*(?:\{[^}]*\}[^{#]*)*)(#.*)?$/;
const pathMatches = Object.keys(paths)
.map((path) => pathRE.exec(path))
.filter(Boolean);
if (pathMatches.length === 0) {
return paths;
}
paths = { ...paths };
for (const [pathQuery, pathname, query, frag] of pathMatches) {
const srcPathItem = paths[pathQuery];
if (srcPathItem === undefined) {
continue;
}
if (srcPathItem === null
|| typeof srcPathItem !== 'object'
|| Array.isArray(srcPathItem)) {
this.transformPath.push(pathQuery);
this.warn('Ignoring non-object Path Item', srcPathItem);
this.transformPath.pop();
continue;
}
if (srcPathItem.parameters !== undefined
&& !Array.isArray(srcPathItem.parameters)) {
this.transformPath.push(pathQuery);
this.warn('Ignoring path with non-Array parameters', srcPathItem);
this.transformPath.pop();
continue;
}
const dstPath = pathname + (frag || '');
const dstPathItem = paths[dstPath];
if (dstPathItem === null
|| (dstPathItem !== undefined && typeof dstPathItem !== 'object')
|| Array.isArray(dstPathItem)) {
this.transformPath.push(dstPath);
this.warn(
'Refusing to overwrite non-object Path Item',
dstPathItem,
);
this.transformPath.pop();
continue;
}
let queryParams;
this.transformPath.push(pathQuery);
try {
queryParams = parseQueryParams(query);
} finally {
this.transformPath.pop();
}
if (queryParams === undefined) {
continue;
}
const constParameters = [];
const pathVarNameToParams = new Map();
for (const [name, value] of queryParams) {
if (value[0] !== '{') {
constParameters.push(createConstQueryParam.call(
this,
name,
value,
));
} else {
const valueName = value.slice(1, -1);
let params = pathVarNameToParams.get(valueName);
if (params === undefined) {
params = [];
if (dstPath.includes(value)) {
// parameter occurs in path and query parts
params.push({ name: valueName, in: 'path' });
}
pathVarNameToParams.set(valueName, params);
}
params.push({ name, in: 'query' });
}
}
let newPathItem = constParameters.length === 0 ? srcPathItem
: {
...srcPathItem,
parameters: combineParameters(
srcPathItem.parameters,
constParameters,
),
};
this[pathVarNameToParamsSymbol] = pathVarNameToParams;
try {
newPathItem = visit(
this,
this.transformPathItem,
pathQuery,
newPathItem,
);
} finally {
this[pathVarNameToParamsSymbol] = undefined;
}
const mergedPathItem = dstPathItem === undefined ? newPathItem : visit(
this,
mergePathItems,
dstPath,
dstPathItem,
newPathItem,
);
if (mergedPathItem !== undefined) {
paths[dstPath] = mergedPathItem;
delete paths[pathQuery];
}
}
return paths;
}
// Override as performance optimization, since only transforming paths
transformOpenApi(openApi) {
if (openApi === null
|| typeof openApi !== 'object'
|| Array.isArray(openApi)) {
this.warn('Ignoring non-object OpenAPI', openApi);
return openApi;
}
let oasVersion = '3.1.0';
if (openApi.openapi !== undefined) {
const openapi = `${openApi.openapi}`;
if (openapi.startsWith('3.')) {
oasVersion = openapi;
} else if (openapi === '3') {
oasVersion = '3.0.0';
} else {
this.warn('Unrecognized OpenAPI version', openApi.openapi);
}
} else if (openApi.swagger !== undefined) {
const swagger = `${openApi.swagger}`;
if (swagger === '2.0' || swagger === '2') {
oasVersion = '2.0';
} else {
this.warn('Unrecognized Swagger version', openApi.openapi);
}
} else {
this.warn('Document missing OpenAPI and Swagger version', openApi);
}
if (openApi.paths !== undefined) {
this[oasVersionSymbol] = oasVersion;
try {
openApi = {
...openApi,
paths: visit(
this,
this.transformPaths,
'paths',
openApi.paths,
),
};
} finally {
this[oasVersionSymbol] = undefined;
}
}
return openApi;
}
}