@readme/api-core 7.0.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +18 -0
- package/README.md +16 -0
- package/dist/errors/fetchError.d.ts +12 -0
- package/dist/errors/fetchError.js +36 -0
- package/dist/index.d.ts +49 -0
- package/dist/index.js +164 -0
- package/dist/lib/getJSONSchemaDefaults.d.ts +14 -0
- package/dist/lib/getJSONSchemaDefaults.js +61 -0
- package/dist/lib/parseResponse.d.ts +6 -0
- package/dist/lib/parseResponse.js +71 -0
- package/dist/lib/prepareAuth.d.ts +5 -0
- package/dist/lib/prepareAuth.js +84 -0
- package/dist/lib/prepareParams.d.ts +21 -0
- package/dist/lib/prepareParams.js +440 -0
- package/dist/lib/prepareServer.d.ts +10 -0
- package/dist/lib/prepareServer.js +47 -0
- package/package.json +50 -0
- package/src/errors/fetchError.ts +31 -0
- package/src/index.ts +151 -0
- package/src/lib/getJSONSchemaDefaults.ts +74 -0
- package/src/lib/parseResponse.ts +27 -0
- package/src/lib/prepareAuth.ts +110 -0
- package/src/lib/prepareParams.ts +427 -0
- package/src/lib/prepareServer.ts +48 -0
- package/tsconfig.json +13 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import type { Har } from 'har-format';
|
|
2
|
+
import type Oas from 'oas';
|
|
3
|
+
import type { Operation } from 'oas';
|
|
4
|
+
import type { HttpMethods } from 'oas/dist/rmoas.types';
|
|
5
|
+
|
|
6
|
+
import oasToHar from '@readme/oas-to-har';
|
|
7
|
+
import fetchHar from 'fetch-har';
|
|
8
|
+
|
|
9
|
+
import FetchError from './errors/fetchError';
|
|
10
|
+
import getJSONSchemaDefaults from './lib/getJSONSchemaDefaults';
|
|
11
|
+
import parseResponse from './lib/parseResponse';
|
|
12
|
+
import prepareAuth from './lib/prepareAuth';
|
|
13
|
+
import prepareParams from './lib/prepareParams';
|
|
14
|
+
import prepareServer from './lib/prepareServer';
|
|
15
|
+
|
|
16
|
+
export interface ConfigOptions {
|
|
17
|
+
/**
|
|
18
|
+
* Override the default `fetch` request timeout of 30 seconds. This number should be represented
|
|
19
|
+
* in milliseconds.
|
|
20
|
+
*/
|
|
21
|
+
timeout?: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface FetchResponse<HTTPStatus, Data> {
|
|
25
|
+
data: Data;
|
|
26
|
+
headers: Headers;
|
|
27
|
+
res: Response;
|
|
28
|
+
status: HTTPStatus;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
// https://stackoverflow.com/a/39495173
|
|
32
|
+
type Enumerate<N extends number, Acc extends number[] = []> = Acc['length'] extends N
|
|
33
|
+
? Acc[number]
|
|
34
|
+
: Enumerate<N, [...Acc, Acc['length']]>;
|
|
35
|
+
|
|
36
|
+
export type HTTPMethodRange<F extends number, T extends number> = Exclude<Enumerate<T>, Enumerate<F>>;
|
|
37
|
+
|
|
38
|
+
export { getJSONSchemaDefaults, parseResponse, prepareAuth, prepareParams, prepareServer };
|
|
39
|
+
|
|
40
|
+
export default class APICore {
|
|
41
|
+
spec!: Oas;
|
|
42
|
+
|
|
43
|
+
private auth: (number | string)[] = [];
|
|
44
|
+
|
|
45
|
+
private server:
|
|
46
|
+
| false
|
|
47
|
+
| {
|
|
48
|
+
url: string;
|
|
49
|
+
variables?: Record<string, string | number>;
|
|
50
|
+
} = false;
|
|
51
|
+
|
|
52
|
+
private config: ConfigOptions = {};
|
|
53
|
+
|
|
54
|
+
private userAgent!: string;
|
|
55
|
+
|
|
56
|
+
constructor(spec?: Oas, userAgent?: string) {
|
|
57
|
+
if (spec) this.spec = spec;
|
|
58
|
+
if (userAgent) this.userAgent = userAgent;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
setSpec(spec: Oas) {
|
|
62
|
+
this.spec = spec;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
setConfig(config: ConfigOptions) {
|
|
66
|
+
this.config = config;
|
|
67
|
+
return this;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
setUserAgent(userAgent: string) {
|
|
71
|
+
this.userAgent = userAgent;
|
|
72
|
+
return this;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
setAuth(...values: string[] | number[]) {
|
|
76
|
+
this.auth = values;
|
|
77
|
+
return this;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
setServer(url: string, variables: Record<string, string | number> = {}) {
|
|
81
|
+
this.server = { url, variables };
|
|
82
|
+
return this;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async fetch<HTTPStatus extends number = number>(
|
|
86
|
+
path: string,
|
|
87
|
+
method: HttpMethods,
|
|
88
|
+
body?: unknown,
|
|
89
|
+
metadata?: Record<string, unknown>,
|
|
90
|
+
) {
|
|
91
|
+
const operation = this.spec.operation(path, method);
|
|
92
|
+
|
|
93
|
+
return this.fetchOperation<HTTPStatus>(operation, body, metadata);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
async fetchOperation<HTTPStatus extends number = number>(
|
|
97
|
+
operation: Operation,
|
|
98
|
+
body?: unknown,
|
|
99
|
+
metadata?: Record<string, unknown>,
|
|
100
|
+
) {
|
|
101
|
+
return prepareParams(operation, body, metadata).then(params => {
|
|
102
|
+
const data = { ...params };
|
|
103
|
+
|
|
104
|
+
// If `sdk.server()` has been issued data then we need to do some extra work to figure out
|
|
105
|
+
// how to use that supplied server, and also handle any server variables that were sent
|
|
106
|
+
// alongside it.
|
|
107
|
+
if (this.server) {
|
|
108
|
+
const preparedServer = prepareServer(this.spec, this.server.url, this.server.variables);
|
|
109
|
+
if (preparedServer) {
|
|
110
|
+
data.server = preparedServer;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// @ts-expect-error `this.auth` typing is off. FIXME
|
|
115
|
+
const har = oasToHar(this.spec, operation, data, prepareAuth(this.auth, operation));
|
|
116
|
+
|
|
117
|
+
let timeoutSignal: NodeJS.Timeout;
|
|
118
|
+
const init: RequestInit = {};
|
|
119
|
+
if (this.config.timeout) {
|
|
120
|
+
const controller = new AbortController();
|
|
121
|
+
timeoutSignal = setTimeout(() => controller.abort(), this.config.timeout);
|
|
122
|
+
init.signal = controller.signal;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
return fetchHar(har as Har, {
|
|
126
|
+
files: data.files || {},
|
|
127
|
+
init,
|
|
128
|
+
userAgent: this.userAgent,
|
|
129
|
+
})
|
|
130
|
+
.then(async (res: Response) => {
|
|
131
|
+
const parsed = await parseResponse<HTTPStatus>(res);
|
|
132
|
+
|
|
133
|
+
if (res.status >= 400 && res.status <= 599) {
|
|
134
|
+
throw new FetchError<typeof parsed.status, typeof parsed.data>(
|
|
135
|
+
parsed.status,
|
|
136
|
+
parsed.data,
|
|
137
|
+
parsed.headers,
|
|
138
|
+
parsed.res,
|
|
139
|
+
);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return parsed;
|
|
143
|
+
})
|
|
144
|
+
.finally(() => {
|
|
145
|
+
if (this.config.timeout) {
|
|
146
|
+
clearTimeout(timeoutSignal);
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import type { SchemaWrapper } from 'oas/dist/operation/get-parameters-as-json-schema';
|
|
2
|
+
import type { SchemaObject } from 'oas/dist/rmoas.types';
|
|
3
|
+
|
|
4
|
+
import traverse from 'json-schema-traverse';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Run through a JSON Schema object and compose up an object containing default data for any schema
|
|
8
|
+
* property that is required and also has a defined default.
|
|
9
|
+
*
|
|
10
|
+
* Code partially adapted from the `json-schema-default` package but modified to only return
|
|
11
|
+
* defaults of required properties.
|
|
12
|
+
*
|
|
13
|
+
* @todo This is a good candidate to be moved into a core `oas` library method.
|
|
14
|
+
* @see {@link https://github.com/mdornseif/json-schema-default}
|
|
15
|
+
*/
|
|
16
|
+
export default function getJSONSchemaDefaults(jsonSchemas: SchemaWrapper[]) {
|
|
17
|
+
return jsonSchemas
|
|
18
|
+
.map(({ type: payloadType, schema: jsonSchema }) => {
|
|
19
|
+
const defaults: Record<string, unknown> = {};
|
|
20
|
+
traverse(
|
|
21
|
+
jsonSchema,
|
|
22
|
+
(
|
|
23
|
+
schema: SchemaObject,
|
|
24
|
+
pointer: string,
|
|
25
|
+
rootSchema: SchemaObject,
|
|
26
|
+
parentPointer?: string,
|
|
27
|
+
parentKeyword?: string,
|
|
28
|
+
parentSchema?: SchemaObject,
|
|
29
|
+
indexProperty?: string | number,
|
|
30
|
+
) => {
|
|
31
|
+
if (!pointer.startsWith('/properties/')) {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (Array.isArray(parentSchema?.required) && parentSchema?.required.includes(String(indexProperty))) {
|
|
36
|
+
if (schema.type === 'object' && indexProperty) {
|
|
37
|
+
defaults[indexProperty] = {};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
let destination = defaults;
|
|
41
|
+
if (parentPointer) {
|
|
42
|
+
// To map nested objects correct we need to pick apart the parent pointer.
|
|
43
|
+
parentPointer
|
|
44
|
+
.replace(/\/properties/g, '')
|
|
45
|
+
.split('/')
|
|
46
|
+
.forEach((subSchema: string) => {
|
|
47
|
+
if (subSchema === '') {
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
destination = (destination?.[subSchema] as Record<string, unknown>) || {};
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (schema.default !== undefined) {
|
|
56
|
+
if (indexProperty !== undefined) {
|
|
57
|
+
destination[indexProperty] = schema.default;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
);
|
|
63
|
+
|
|
64
|
+
if (!Object.keys(defaults).length) {
|
|
65
|
+
return {};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
// @todo should we filter out empty and undefined objects from here with `remove-undefined-objects`?
|
|
70
|
+
[payloadType]: defaults,
|
|
71
|
+
};
|
|
72
|
+
})
|
|
73
|
+
.reduce((prev, next) => Object.assign(prev, next));
|
|
74
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { utils } from 'oas';
|
|
2
|
+
|
|
3
|
+
const { matchesMimeType } = utils;
|
|
4
|
+
|
|
5
|
+
export default async function parseResponse<HTTPStatus extends number = number>(response: Response) {
|
|
6
|
+
const contentType = response.headers.get('Content-Type');
|
|
7
|
+
const isJSON = contentType && (matchesMimeType.json(contentType) || matchesMimeType.wildcard(contentType));
|
|
8
|
+
|
|
9
|
+
const responseBody = await response.text();
|
|
10
|
+
|
|
11
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
12
|
+
let data: any = responseBody;
|
|
13
|
+
if (isJSON) {
|
|
14
|
+
try {
|
|
15
|
+
data = JSON.parse(responseBody);
|
|
16
|
+
} catch (e) {
|
|
17
|
+
// If our JSON parsing failed then we can just return plaintext instead.
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
return {
|
|
22
|
+
data,
|
|
23
|
+
status: response.status as HTTPStatus,
|
|
24
|
+
headers: response.headers,
|
|
25
|
+
res: response,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
/* eslint-disable no-underscore-dangle */
|
|
2
|
+
import type { Operation } from 'oas';
|
|
3
|
+
import type { KeyedSecuritySchemeObject } from 'oas/dist/rmoas.types';
|
|
4
|
+
|
|
5
|
+
export default function prepareAuth(authKey: (number | string)[], operation: Operation) {
|
|
6
|
+
if (authKey.length === 0) {
|
|
7
|
+
return {};
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
const preparedAuth: Record<
|
|
11
|
+
string,
|
|
12
|
+
| string
|
|
13
|
+
| number
|
|
14
|
+
| {
|
|
15
|
+
pass: string | number;
|
|
16
|
+
user: string | number;
|
|
17
|
+
}
|
|
18
|
+
> = {};
|
|
19
|
+
|
|
20
|
+
const security = operation.getSecurity();
|
|
21
|
+
if (security.length === 0) {
|
|
22
|
+
// If there's no auth configured on this operation, don't prepare anything (even if it was
|
|
23
|
+
// supplied by the user).
|
|
24
|
+
return {};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Does this operation require multiple forms of auth?
|
|
28
|
+
if (security.every(s => Object.keys(s).length > 1)) {
|
|
29
|
+
throw new Error(
|
|
30
|
+
"Sorry, this operation currently requires multiple forms of authentication which this library doesn't yet support.",
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Since we can only handle single auth security configurations, let's pull those out. This code
|
|
35
|
+
// is a bit opaque but `security` here may look like `[{ basic: [] }, { oauth2: [], basic: []}]`
|
|
36
|
+
// and are filtering it down to only single-auth requirements of `[{ basic: [] }]`.
|
|
37
|
+
const usableSecurity = security
|
|
38
|
+
.map(s => {
|
|
39
|
+
return Object.keys(s).length === 1 ? s : false;
|
|
40
|
+
})
|
|
41
|
+
.filter(Boolean);
|
|
42
|
+
|
|
43
|
+
const usableSecuritySchemes = usableSecurity.map(s => Object.keys(s)).reduce((prev, next) => prev.concat(next), []);
|
|
44
|
+
const preparedSecurity = operation.prepareSecurity();
|
|
45
|
+
|
|
46
|
+
// If we have two auth tokens present let's look for Basic Auth in their configuration.
|
|
47
|
+
if (authKey.length >= 2) {
|
|
48
|
+
// If this operation doesn't support HTTP Basic auth but we have two tokens, that's a paddlin.
|
|
49
|
+
if (!('Basic' in preparedSecurity)) {
|
|
50
|
+
throw new Error('Multiple auth tokens were supplied for this endpoint but only a single token is needed.');
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// If we have two auth keys for Basic Auth but Basic isn't a usable security scheme (maybe it's
|
|
54
|
+
// part of an AND or auth configuration -- which we don't support) then we need to error out.
|
|
55
|
+
const schemes = preparedSecurity.Basic.filter(s => usableSecuritySchemes.includes(s._key));
|
|
56
|
+
if (!schemes.length) {
|
|
57
|
+
throw new Error(
|
|
58
|
+
'Credentials for Basic Authentication were supplied but this operation requires another form of auth in that case, which this library does not yet support. This operation does, however, allow supplying a single auth token.',
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const scheme = schemes.shift() as KeyedSecuritySchemeObject;
|
|
63
|
+
preparedAuth[scheme._key] = {
|
|
64
|
+
user: authKey[0],
|
|
65
|
+
pass: authKey.length === 2 ? authKey[1] : '',
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
return preparedAuth;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// If we know we don't need to use HTTP Basic auth because we have a username+password then we
|
|
72
|
+
// can pick the first usable security scheme available and try to use that. This might not always
|
|
73
|
+
// be the auth scheme that the user wants, but we don't have any other way for the user to tell
|
|
74
|
+
// us what they want with the current `sdk.auth()` API.
|
|
75
|
+
const usableScheme = usableSecuritySchemes[0];
|
|
76
|
+
const schemes = Object.entries(preparedSecurity)
|
|
77
|
+
.map(([, ps]) => ps.filter(s => usableScheme === s._key))
|
|
78
|
+
.reduce((prev, next) => prev.concat(next), []);
|
|
79
|
+
|
|
80
|
+
const scheme = schemes.shift() as KeyedSecuritySchemeObject;
|
|
81
|
+
switch (scheme.type) {
|
|
82
|
+
case 'http':
|
|
83
|
+
if (scheme.scheme === 'basic') {
|
|
84
|
+
preparedAuth[scheme._key] = {
|
|
85
|
+
user: authKey[0],
|
|
86
|
+
pass: authKey.length === 2 ? authKey[1] : '',
|
|
87
|
+
};
|
|
88
|
+
} else if (scheme.scheme === 'bearer') {
|
|
89
|
+
preparedAuth[scheme._key] = authKey[0];
|
|
90
|
+
}
|
|
91
|
+
break;
|
|
92
|
+
|
|
93
|
+
case 'oauth2':
|
|
94
|
+
preparedAuth[scheme._key] = authKey[0];
|
|
95
|
+
break;
|
|
96
|
+
|
|
97
|
+
case 'apiKey':
|
|
98
|
+
if (scheme.in === 'query' || scheme.in === 'header' || scheme.in === 'cookie') {
|
|
99
|
+
preparedAuth[scheme._key] = authKey[0];
|
|
100
|
+
}
|
|
101
|
+
break;
|
|
102
|
+
|
|
103
|
+
default:
|
|
104
|
+
throw new Error(
|
|
105
|
+
`Sorry, this API currently uses a security scheme, ${scheme.type}, which this library doesn't yet support.`,
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return preparedAuth;
|
|
110
|
+
}
|