api 6.1.1 → 7.0.0-alpha.0

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.
Files changed (69) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +0 -12
  3. package/package.json +14 -32
  4. package/src/bin.ts +1 -1
  5. package/src/{cli/codegen → codegen}/language.ts +3 -2
  6. package/src/{cli/codegen → codegen}/languages/typescript/util.ts +1 -1
  7. package/src/{cli/codegen → codegen}/languages/typescript.ts +31 -32
  8. package/src/{cli/commands → commands}/install.ts +1 -1
  9. package/src/fetcher.ts +4 -5
  10. package/src/packageInfo.ts +1 -1
  11. package/src/{cli/storage.ts → storage.ts} +13 -9
  12. package/tsconfig.json +3 -13
  13. package/dist/bin.d.ts +0 -1
  14. package/dist/bin.js +0 -91
  15. package/dist/cache.d.ts +0 -68
  16. package/dist/cache.js +0 -198
  17. package/dist/cli/codegen/index.d.ts +0 -4
  18. package/dist/cli/codegen/index.js +0 -23
  19. package/dist/cli/codegen/language.d.ts +0 -27
  20. package/dist/cli/codegen/language.js +0 -32
  21. package/dist/cli/codegen/languages/typescript/util.d.ts +0 -20
  22. package/dist/cli/codegen/languages/typescript/util.js +0 -176
  23. package/dist/cli/codegen/languages/typescript.d.ts +0 -111
  24. package/dist/cli/codegen/languages/typescript.js +0 -821
  25. package/dist/cli/commands/index.d.ts +0 -4
  26. package/dist/cli/commands/index.js +0 -9
  27. package/dist/cli/commands/install.d.ts +0 -3
  28. package/dist/cli/commands/install.js +0 -236
  29. package/dist/cli/lib/prompt.d.ts +0 -9
  30. package/dist/cli/lib/prompt.js +0 -81
  31. package/dist/cli/logger.d.ts +0 -1
  32. package/dist/cli/logger.js +0 -16
  33. package/dist/cli/storage.d.ts +0 -105
  34. package/dist/cli/storage.js +0 -277
  35. package/dist/core/errors/fetchError.d.ts +0 -12
  36. package/dist/core/errors/fetchError.js +0 -36
  37. package/dist/core/getJSONSchemaDefaults.d.ts +0 -14
  38. package/dist/core/getJSONSchemaDefaults.js +0 -61
  39. package/dist/core/index.d.ts +0 -40
  40. package/dist/core/index.js +0 -168
  41. package/dist/core/parseResponse.d.ts +0 -6
  42. package/dist/core/parseResponse.js +0 -71
  43. package/dist/core/prepareAuth.d.ts +0 -5
  44. package/dist/core/prepareAuth.js +0 -84
  45. package/dist/core/prepareParams.d.ts +0 -21
  46. package/dist/core/prepareParams.js +0 -425
  47. package/dist/core/prepareServer.d.ts +0 -10
  48. package/dist/core/prepareServer.js +0 -47
  49. package/dist/fetcher.d.ts +0 -54
  50. package/dist/fetcher.js +0 -164
  51. package/dist/index.d.ts +0 -6
  52. package/dist/index.js +0 -259
  53. package/dist/packageInfo.d.ts +0 -2
  54. package/dist/packageInfo.js +0 -6
  55. package/src/.sink.d.ts +0 -1
  56. package/src/cache.ts +0 -193
  57. package/src/core/errors/fetchError.ts +0 -31
  58. package/src/core/getJSONSchemaDefaults.ts +0 -74
  59. package/src/core/index.ts +0 -148
  60. package/src/core/parseResponse.ts +0 -26
  61. package/src/core/prepareAuth.ts +0 -109
  62. package/src/core/prepareParams.ts +0 -415
  63. package/src/core/prepareServer.ts +0 -48
  64. package/src/index.ts +0 -203
  65. package/src/typings.d.ts +0 -2
  66. /package/src/{cli/codegen → codegen}/index.ts +0 -0
  67. /package/src/{cli/commands → commands}/index.ts +0 -0
  68. /package/src/{cli/lib → lib}/prompt.ts +0 -0
  69. /package/src/{cli/logger.ts → logger.ts} +0 -0
package/src/cache.ts DELETED
@@ -1,193 +0,0 @@
1
- import type { OASDocument } from 'oas/dist/rmoas.types';
2
-
3
- import crypto from 'crypto';
4
- import fs from 'fs';
5
- import os from 'os';
6
- import path from 'path';
7
-
8
- import findCacheDir from 'find-cache-dir';
9
- import 'isomorphic-fetch';
10
- import makeDir from 'make-dir';
11
-
12
- import Fetcher from './fetcher';
13
- import { PACKAGE_NAME } from './packageInfo';
14
-
15
- type CacheStore = Record<
16
- string,
17
- {
18
- hash: string;
19
- original: string | OASDocument;
20
- /**
21
- * @deprecated Deprecated in v4.5.0 in favor of `hash`.
22
- */
23
- path?: string;
24
- title?: string;
25
- version?: string;
26
- }
27
- >;
28
-
29
- export default class Cache {
30
- static dir: string;
31
-
32
- static cacheStore: string;
33
-
34
- static specsCache: string;
35
-
36
- uri: string | OASDocument;
37
-
38
- uriHash: string;
39
-
40
- cached: false | CacheStore;
41
-
42
- fetcher: Fetcher;
43
-
44
- constructor(uri: string | OASDocument, cacheDir: string | false = false) {
45
- Cache.setCacheDir(cacheDir);
46
- Cache.cacheStore = path.join(Cache.dir, 'cache.json');
47
- Cache.specsCache = path.join(Cache.dir, 'specs');
48
-
49
- this.fetcher = new Fetcher(uri);
50
-
51
- this.uri = this.fetcher.uri;
52
- this.uriHash = Cache.getCacheHash(this.uri);
53
-
54
- // This should default to false so we have awareness if we've looked at the cache yet.
55
- this.cached = false;
56
- }
57
-
58
- static getCacheHash(file: string | OASDocument) {
59
- let data: string;
60
- if (typeof file === 'object') {
61
- // Under certain unit testing circumstances, we might be supplying the class with a raw JSON
62
- // object so we'll need to convert it to a string in order to hand it off to the crypto
63
- // module.
64
- data = JSON.stringify(file);
65
- } else {
66
- data = file;
67
- }
68
-
69
- return crypto.createHash('md5').update(data).digest('hex');
70
- }
71
-
72
- static setCacheDir(dir?: string | false) {
73
- if (dir) {
74
- Cache.dir = dir;
75
- return;
76
- } else if (Cache.dir) {
77
- // If we already have a cache dir set and aren't explicitly it to something new then we
78
- // shouldn't overwrite what we've already got.
79
- return;
80
- }
81
-
82
- Cache.dir = findCacheDir({ name: PACKAGE_NAME });
83
- if (typeof Cache.dir === 'undefined') {
84
- // The `find-cache-dir` module returns `undefined` if the `node_modules/` directory isn't
85
- // writable, or there's no `package.json` in the root-most directory. If this happens, we can
86
- // instead adhoc create a cache directory in the users OS temp directory and store our data
87
- // there.
88
- //
89
- // @link https://github.com/avajs/find-cache-dir/issues/29
90
- Cache.dir = makeDir.sync(path.join(os.tmpdir(), PACKAGE_NAME));
91
- }
92
- }
93
-
94
- static async reset() {
95
- if (Cache.cacheStore) {
96
- await fs.promises.rm(Cache.cacheStore).catch(() => {
97
- // no-op
98
- });
99
- }
100
-
101
- if (Cache.specsCache) {
102
- await fs.promises.rm(Cache.specsCache, { recursive: true }).catch(() => {
103
- // no-op
104
- });
105
- }
106
- }
107
-
108
- isCached() {
109
- const cache = this.getCache();
110
- return cache && this.uriHash in cache;
111
- }
112
-
113
- getCache() {
114
- if (typeof this.cached === 'object') {
115
- return this.cached;
116
- }
117
-
118
- this.cached = {};
119
-
120
- if (fs.existsSync(Cache.cacheStore)) {
121
- this.cached = JSON.parse(fs.readFileSync(Cache.cacheStore, 'utf8')) as CacheStore;
122
- }
123
-
124
- return this.cached;
125
- }
126
-
127
- get() {
128
- // If the class was supplied a raw object, just go ahead and bypass the caching system and
129
- // return that.
130
- if (typeof this.uri === 'object') {
131
- return this.uri;
132
- }
133
-
134
- if (!this.isCached()) {
135
- throw new Error(`${this.uri} has not been cached yet and must do so before being retrieved.`);
136
- }
137
-
138
- const cache = this.getCache();
139
-
140
- // Prior to v4.5.0 we were putting a fully resolved path to the API definition in the cache
141
- // store but if you had specified a custom caching directory and would generate the cache on
142
- // your system, that filepath would obviously not be the same in other environments. For this
143
- // reason the `path` was removed from the cache store in favor of storing the `hash` instead.
144
- //
145
- // If we still have `path` in the config cache for backwards compatibility we should use it.
146
- if ('path' in cache[this.uriHash]) {
147
- return JSON.parse(fs.readFileSync(cache[this.uriHash].path, 'utf8'));
148
- }
149
-
150
- return JSON.parse(fs.readFileSync(path.join(Cache.specsCache, `${cache[this.uriHash].hash}.json`), 'utf8'));
151
- }
152
-
153
- async load() {
154
- // If the class was supplied a raw object we should still validate and make sure that it's
155
- // dereferenced in order for everything to function, but we shouldn't worry about saving it
156
- // into the cache directory architecture.
157
- if (typeof this.uri === 'object') {
158
- return Fetcher.validate(this.uri);
159
- }
160
-
161
- return this.fetcher.load().then(async spec => this.save(spec));
162
- }
163
-
164
- save(spec: OASDocument) {
165
- if (!fs.existsSync(Cache.dir)) {
166
- fs.mkdirSync(Cache.dir, { recursive: true });
167
- }
168
-
169
- if (!fs.existsSync(Cache.specsCache)) {
170
- fs.mkdirSync(Cache.specsCache, { recursive: true });
171
- }
172
-
173
- const cache = this.getCache();
174
- if (!(this.uriHash in cache)) {
175
- const saved = JSON.stringify(spec, null, 2);
176
- const fileHash = crypto.createHash('md5').update(saved).digest('hex');
177
-
178
- cache[this.uriHash] = {
179
- hash: fileHash,
180
- original: this.uri,
181
- title: 'title' in spec.info ? spec.info.title : undefined,
182
- version: 'version' in spec.info ? spec.info.version : undefined,
183
- };
184
-
185
- fs.writeFileSync(path.join(Cache.specsCache, `${fileHash}.json`), saved);
186
- fs.writeFileSync(Cache.cacheStore, JSON.stringify(cache, null, 2));
187
-
188
- this.cached = cache;
189
- }
190
-
191
- return spec;
192
- }
193
- }
@@ -1,31 +0,0 @@
1
- class FetchError<Status = number, Data = unknown> extends Error {
2
- /** HTTP Status */
3
- status: Status;
4
-
5
- /** The content of the response. */
6
- data: Data;
7
-
8
- /** The Headers of the response. */
9
- headers: Headers;
10
-
11
- /** The raw `Response` object. */
12
- res: Response;
13
-
14
- constructor(status: Status, data: Data, headers: Headers, res: Response) {
15
- super(res.statusText);
16
-
17
- this.name = 'FetchError';
18
- this.status = status;
19
- this.data = data;
20
- this.headers = headers;
21
- this.res = res;
22
-
23
- // We could fix this by updating our target to ES2015 but because we support exporting to CJS
24
- // we can't.
25
- //
26
- // https://www.dannyguo.com/blog/how-to-fix-instanceof-not-working-for-custom-errors-in-typescript/
27
- Object.setPrototypeOf(this, FetchError.prototype);
28
- }
29
- }
30
-
31
- export default FetchError;
@@ -1,74 +0,0 @@
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,
30
- ) => {
31
- if (!pointer.startsWith('/properties/')) {
32
- return;
33
- }
34
-
35
- if (Array.isArray(parentSchema?.required) && parentSchema.required.includes(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
- }
package/src/core/index.ts DELETED
@@ -1,148 +0,0 @@
1
- import type Oas from 'oas';
2
- import type { Operation } from 'oas';
3
- import type { HttpMethods } from 'oas/dist/rmoas.types';
4
-
5
- import oasToHar from '@readme/oas-to-har';
6
- import fetchHar from 'fetch-har';
7
- import { FormDataEncoder } from 'form-data-encoder';
8
- import 'isomorphic-fetch';
9
- // `AbortController` was shipped in Node 15 so when Node 14 is EOL'd we can drop this dependency.
10
- import { AbortController } from 'node-abort-controller';
11
-
12
- import FetchError from './errors/fetchError';
13
- import getJSONSchemaDefaults from './getJSONSchemaDefaults';
14
- import parseResponse from './parseResponse';
15
- import prepareAuth from './prepareAuth';
16
- import prepareParams from './prepareParams';
17
- import prepareServer from './prepareServer';
18
-
19
- export interface ConfigOptions {
20
- /**
21
- * Override the default `fetch` request timeout of 30 seconds. This number should be represented
22
- * in milliseconds.
23
- */
24
- timeout?: number;
25
- }
26
-
27
- export interface FetchResponse<status, data> {
28
- data: data;
29
- headers: Headers;
30
- res: Response;
31
- status: status;
32
- }
33
-
34
- // https://stackoverflow.com/a/39495173
35
- type Enumerate<N extends number, Acc extends number[] = []> = Acc['length'] extends N
36
- ? Acc[number]
37
- : Enumerate<N, [...Acc, Acc['length']]>;
38
-
39
- export type HTTPMethodRange<F extends number, T extends number> = Exclude<Enumerate<T>, Enumerate<F>>;
40
-
41
- export { getJSONSchemaDefaults, parseResponse, prepareAuth, prepareParams, prepareServer };
42
-
43
- export default class APICore {
44
- spec: Oas;
45
-
46
- private auth: (number | string)[] = [];
47
-
48
- private server:
49
- | false
50
- | {
51
- url?: string;
52
- variables?: Record<string, string | number>;
53
- } = false;
54
-
55
- private config: ConfigOptions = {};
56
-
57
- private userAgent: string;
58
-
59
- constructor(spec?: Oas, userAgent?: string) {
60
- this.spec = spec;
61
- this.userAgent = userAgent;
62
- }
63
-
64
- setSpec(spec: Oas) {
65
- this.spec = spec;
66
- }
67
-
68
- setConfig(config: ConfigOptions) {
69
- this.config = config;
70
- return this;
71
- }
72
-
73
- setUserAgent(userAgent: string) {
74
- this.userAgent = userAgent;
75
- return this;
76
- }
77
-
78
- setAuth(...values: string[] | number[]) {
79
- this.auth = values;
80
- return this;
81
- }
82
-
83
- setServer(url: string, variables: Record<string, string | number> = {}) {
84
- this.server = { url, variables };
85
- return this;
86
- }
87
-
88
- async fetch(path: string, method: HttpMethods, body?: unknown, metadata?: Record<string, unknown>) {
89
- const operation = this.spec.operation(path, method);
90
-
91
- return this.fetchOperation(operation, body, metadata);
92
- }
93
-
94
- async fetchOperation(operation: Operation, body?: unknown, metadata?: Record<string, unknown>) {
95
- return prepareParams(operation, body, metadata).then(params => {
96
- const data = { ...params };
97
-
98
- // If `sdk.server()` has been issued data then we need to do some extra work to figure out
99
- // how to use that supplied server, and also handle any server variables that were sent
100
- // alongside it.
101
- if (this.server) {
102
- const preparedServer = prepareServer(this.spec, this.server.url, this.server.variables);
103
- if (preparedServer) {
104
- data.server = preparedServer;
105
- }
106
- }
107
-
108
- // @ts-expect-error `this.auth` typing is off. FIXME
109
- const har = oasToHar(this.spec, operation, data, prepareAuth(this.auth, operation));
110
-
111
- let timeoutSignal: any;
112
- const init: RequestInit = {};
113
- if (this.config.timeout) {
114
- const controller = new AbortController();
115
- timeoutSignal = setTimeout(() => controller.abort(), this.config.timeout);
116
- // @todo Typing on `AbortController` coming out of `node-abort-controler` isn't right so when
117
- // we eventually drop that dependency we can remove the `as any` here.
118
- init.signal = controller.signal as any;
119
- }
120
-
121
- return fetchHar(har as any, {
122
- files: data.files || {},
123
- init,
124
- multipartEncoder: FormDataEncoder,
125
- userAgent: this.userAgent,
126
- })
127
- .then(async (res: Response) => {
128
- const parsed = await parseResponse(res);
129
-
130
- if (res.status >= 400 && res.status <= 599) {
131
- throw new FetchError<typeof parsed.status, typeof parsed.data>(
132
- parsed.status,
133
- parsed.data,
134
- parsed.headers,
135
- parsed.res,
136
- );
137
- }
138
-
139
- return parsed;
140
- })
141
- .finally(() => {
142
- if (this.config.timeout) {
143
- clearTimeout(timeoutSignal);
144
- }
145
- });
146
- });
147
- }
148
- }
@@ -1,26 +0,0 @@
1
- import { utils } from 'oas';
2
-
3
- const { matchesMimeType } = utils;
4
-
5
- export default async function getResponseBody(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
- let data = responseBody;
12
- if (isJSON) {
13
- try {
14
- data = JSON.parse(responseBody);
15
- } catch (e) {
16
- // If our JSON parsing failed then we can just return plaintext instead.
17
- }
18
- }
19
-
20
- return {
21
- data,
22
- status: response.status,
23
- headers: response.headers,
24
- res: response,
25
- };
26
- }
@@ -1,109 +0,0 @@
1
- /* eslint-disable no-underscore-dangle */
2
- import type { Operation } from 'oas';
3
-
4
- export default function prepareAuth(authKey: (number | string)[], operation: Operation) {
5
- if (authKey.length === 0) {
6
- return {};
7
- }
8
-
9
- const preparedAuth: Record<
10
- string,
11
- | string
12
- | number
13
- | {
14
- pass: string | number;
15
- user: string | number;
16
- }
17
- > = {};
18
-
19
- const security = operation.getSecurity();
20
- if (security.length === 0) {
21
- // If there's no auth configured on this operation, don't prepare anything (even if it was
22
- // supplied by the user).
23
- return {};
24
- }
25
-
26
- // Does this operation require multiple forms of auth?
27
- if (security.every(s => Object.keys(s).length > 1)) {
28
- throw new Error(
29
- "Sorry, this operation currently requires multiple forms of authentication which this library doesn't yet support.",
30
- );
31
- }
32
-
33
- // Since we can only handle single auth security configurations, let's pull those out. This code
34
- // is a bit opaque but `security` here may look like `[{ basic: [] }, { oauth2: [], basic: []}]`
35
- // and are filtering it down to only single-auth requirements of `[{ basic: [] }]`.
36
- const usableSecurity = security
37
- .map(s => {
38
- return Object.keys(s).length === 1 ? s : false;
39
- })
40
- .filter(Boolean);
41
-
42
- const usableSecuritySchemes = usableSecurity.map(s => Object.keys(s)).reduce((prev, next) => prev.concat(next), []);
43
- const preparedSecurity = operation.prepareSecurity();
44
-
45
- // If we have two auth tokens present let's look for Basic Auth in their configuration.
46
- if (authKey.length >= 2) {
47
- // If this operation doesn't support HTTP Basic auth but we have two tokens, that's a paddlin.
48
- if (!('Basic' in preparedSecurity)) {
49
- throw new Error('Multiple auth tokens were supplied for this endpoint but only a single token is needed.');
50
- }
51
-
52
- // If we have two auth keys for Basic Auth but Basic isn't a usable security scheme (maybe it's
53
- // part of an AND or auth configuration -- which we don't support) then we need to error out.
54
- const schemes = preparedSecurity.Basic.filter(s => usableSecuritySchemes.includes(s._key));
55
- if (!schemes.length) {
56
- throw new Error(
57
- '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.',
58
- );
59
- }
60
-
61
- const scheme = schemes.shift();
62
- preparedAuth[scheme._key] = {
63
- user: authKey[0],
64
- pass: authKey.length === 2 ? authKey[1] : '',
65
- };
66
-
67
- return preparedAuth;
68
- }
69
-
70
- // If we know we don't need to use HTTP Basic auth because we have a username+password then we
71
- // can pick the first usable security scheme available and try to use that. This might not always
72
- // be the auth scheme that the user wants, but we don't have any other way for the user to tell
73
- // us what they want with the current `sdk.auth()` API.
74
- const usableScheme = usableSecuritySchemes[0];
75
- const schemes = Object.entries(preparedSecurity)
76
- .map(([, ps]) => ps.filter(s => usableScheme === s._key))
77
- .reduce((prev, next) => prev.concat(next), []);
78
-
79
- const scheme = schemes.shift();
80
- switch (scheme.type) {
81
- case 'http':
82
- if (scheme.scheme === 'basic') {
83
- preparedAuth[scheme._key] = {
84
- user: authKey[0],
85
- pass: authKey.length === 2 ? authKey[1] : '',
86
- };
87
- } else if (scheme.scheme === 'bearer') {
88
- preparedAuth[scheme._key] = authKey[0];
89
- }
90
- break;
91
-
92
- case 'oauth2':
93
- preparedAuth[scheme._key] = authKey[0];
94
- break;
95
-
96
- case 'apiKey':
97
- if (scheme.in === 'query' || scheme.in === 'header' || scheme.in === 'cookie') {
98
- preparedAuth[scheme._key] = authKey[0];
99
- }
100
- break;
101
-
102
- default:
103
- throw new Error(
104
- `Sorry, this API currently uses a security scheme, ${scheme.type}, which this library doesn't yet support.`,
105
- );
106
- }
107
-
108
- return preparedAuth;
109
- }