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
@@ -1,277 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- var __generator = (this && this.__generator) || function (thisArg, body) {
12
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
13
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
- function verb(n) { return function (v) { return step([n, v]); }; }
15
- function step(op) {
16
- if (f) throw new TypeError("Generator is already executing.");
17
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
18
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
19
- if (y = 0, t) op = [op[0] & 2, t.value];
20
- switch (op[0]) {
21
- case 0: case 1: t = op; break;
22
- case 4: _.label++; return { value: op[1], done: false };
23
- case 5: _.label++; y = op[1]; op = [0]; continue;
24
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
25
- default:
26
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
27
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
28
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
29
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
30
- if (t[2]) _.ops.pop();
31
- _.trys.pop(); continue;
32
- }
33
- op = body.call(thisArg, _);
34
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
35
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
36
- }
37
- };
38
- var __importDefault = (this && this.__importDefault) || function (mod) {
39
- return (mod && mod.__esModule) ? mod : { "default": mod };
40
- };
41
- exports.__esModule = true;
42
- var fs_1 = __importDefault(require("fs"));
43
- var path_1 = __importDefault(require("path"));
44
- var make_dir_1 = __importDefault(require("make-dir"));
45
- var ssri_1 = __importDefault(require("ssri"));
46
- var validate_npm_package_name_1 = __importDefault(require("validate-npm-package-name"));
47
- var fetcher_1 = __importDefault(require("../fetcher"));
48
- var packageInfo_1 = require("../packageInfo");
49
- var Storage = /** @class */ (function () {
50
- function Storage(source, identifier) {
51
- Storage.setStorageDir();
52
- this.fetcher = new fetcher_1["default"](source);
53
- this.source = source;
54
- this.identifier = identifier;
55
- // This should default to false so we have awareness if we've looked at the lockfile yet.
56
- Storage.lockfile = false;
57
- }
58
- Storage.getLockfilePath = function () {
59
- return path_1["default"].join(Storage.dir, 'api.json');
60
- };
61
- Storage.getAPIsDir = function () {
62
- return path_1["default"].join(Storage.dir, 'apis');
63
- };
64
- Storage.setStorageDir = function (dir) {
65
- if (dir) {
66
- Storage.dir = dir;
67
- return;
68
- }
69
- else if (Storage.dir) {
70
- // If we already have a storage dir set and aren't explicitly it to something new then we
71
- // shouldn't overwrite what we've already got.
72
- return;
73
- }
74
- Storage.dir = make_dir_1["default"].sync(path_1["default"].join(process.cwd(), '.api'));
75
- make_dir_1["default"].sync(Storage.getAPIsDir());
76
- };
77
- /**
78
- * Reset the state of the entire storage system.
79
- *
80
- * This will completely destroy the contents of the `.api/` directory!
81
- */
82
- Storage.reset = function () {
83
- return __awaiter(this, void 0, void 0, function () {
84
- return __generator(this, function (_a) {
85
- switch (_a.label) {
86
- case 0:
87
- if (!Storage.getLockfilePath()) return [3 /*break*/, 2];
88
- return [4 /*yield*/, fs_1["default"].promises.writeFile(Storage.getLockfilePath(), JSON.stringify(Storage.getDefaultLockfile(), null, 2))];
89
- case 1:
90
- _a.sent();
91
- _a.label = 2;
92
- case 2:
93
- if (!Storage.getAPIsDir()) return [3 /*break*/, 5];
94
- return [4 /*yield*/, fs_1["default"].promises.rm(Storage.getAPIsDir(), { recursive: true })];
95
- case 3:
96
- _a.sent();
97
- return [4 /*yield*/, fs_1["default"].promises.mkdir(Storage.getAPIsDir(), { recursive: true })];
98
- case 4:
99
- _a.sent();
100
- _a.label = 5;
101
- case 5: return [2 /*return*/];
102
- }
103
- });
104
- });
105
- };
106
- Storage.getDefaultLockfile = function () {
107
- return {
108
- version: '1.0',
109
- apis: []
110
- };
111
- };
112
- Storage.generateIntegrityHash = function (definition) {
113
- return ssri_1["default"]
114
- .fromData(JSON.stringify(definition), {
115
- algorithms: ['sha512']
116
- })
117
- .toString();
118
- };
119
- Storage.getLockfile = function () {
120
- if (typeof Storage.lockfile === 'object') {
121
- return Storage.lockfile;
122
- }
123
- if (fs_1["default"].existsSync(Storage.getLockfilePath())) {
124
- var file = fs_1["default"].readFileSync(Storage.getLockfilePath(), 'utf8');
125
- Storage.lockfile = JSON.parse(file);
126
- }
127
- else {
128
- Storage.lockfile = Storage.getDefaultLockfile();
129
- }
130
- return Storage.lockfile;
131
- };
132
- Storage.isIdentifierValid = function (identifier, prefixWithAPINamespace) {
133
- // Is this identifier already in storage?
134
- if (Storage.isInLockFile({ identifier: identifier })) {
135
- throw new Error("\"".concat(identifier, "\" is already taken in your `.api/` directory. Please try another identifier."));
136
- }
137
- var isValidForNPM = (0, validate_npm_package_name_1["default"])(prefixWithAPINamespace ? "@api/".concat(identifier) : identifier);
138
- if (!isValidForNPM.validForNewPackages) {
139
- // `prompts` doesn't support surfacing multiple errors in a `validate` call so we can only
140
- // surface the first to the user.
141
- throw new Error("Identifier cannot be used for an NPM package: ".concat(isValidForNPM.errors[0]));
142
- }
143
- return true;
144
- };
145
- Storage.isInLockFile = function (search) {
146
- // Because this method may run before we initialize a new storage object we should make sure
147
- // that we have a storage directory present.
148
- Storage.setStorageDir();
149
- if (!search.identifier && !search.source) {
150
- throw new TypeError('An `identifier` or `source` must be supplied to this method to search in the lockfile.');
151
- }
152
- var lockfile = Storage.getLockfile();
153
- if (typeof lockfile !== 'object' || lockfile === null || !lockfile.apis) {
154
- return false;
155
- }
156
- var res = lockfile.apis.find(function (a) {
157
- if (search.identifier) {
158
- return a.identifier === search.identifier;
159
- }
160
- return a.source === search.source;
161
- });
162
- return res === undefined ? false : res;
163
- };
164
- Storage.prototype.setIdentifier = function (identifier) {
165
- this.identifier = identifier;
166
- };
167
- /**
168
- * Determine if the current spec + identifier we're working with is already in the lockfile.
169
- */
170
- Storage.prototype.isInLockfile = function () {
171
- return Boolean(this.getFromLockfile());
172
- };
173
- /**
174
- * Retrieve the lockfile record for the current spec + identifier if it exists in the lockfile.
175
- */
176
- Storage.prototype.getFromLockfile = function () {
177
- var _this = this;
178
- var lockfile = Storage.getLockfile();
179
- return lockfile.apis.find(function (a) { return a.identifier === _this.identifier; });
180
- };
181
- Storage.prototype.getIdentifierStorageDir = function () {
182
- if (!this.isInLockfile()) {
183
- throw new Error("".concat(this.source, " has not been saved to storage yet and must do so before being retrieved."));
184
- }
185
- return path_1["default"].join(Storage.getAPIsDir(), this.identifier);
186
- };
187
- Storage.prototype.getAPIDefinition = function () {
188
- var file = fs_1["default"].readFileSync(path_1["default"].join(this.getIdentifierStorageDir(), 'openapi.json'), 'utf8');
189
- return JSON.parse(file);
190
- };
191
- Storage.prototype.saveSourceFiles = function (files) {
192
- var _this = this;
193
- if (!this.isInLockfile()) {
194
- throw new Error("".concat(this.source, " has not been saved to storage yet and must do so before being retrieved."));
195
- }
196
- return new Promise(function (resolve) {
197
- var savedSource = [];
198
- Object.entries(files).forEach(function (_a) {
199
- var fileName = _a[0], contents = _a[1];
200
- var sourceFilePath = path_1["default"].join(_this.getIdentifierStorageDir(), fileName);
201
- fs_1["default"].writeFileSync(sourceFilePath, contents);
202
- savedSource.push(sourceFilePath);
203
- });
204
- resolve(savedSource);
205
- });
206
- };
207
- Storage.prototype.load = function () {
208
- return __awaiter(this, void 0, void 0, function () {
209
- var _this = this;
210
- return __generator(this, function (_a) {
211
- return [2 /*return*/, this.fetcher.load().then(function (spec) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
212
- return [2 /*return*/, this.save(spec)];
213
- }); }); })];
214
- });
215
- });
216
- };
217
- /**
218
- * @example <caption>Storage directory structure</caption>
219
- * .api/
220
- * ├── api.json // The `package-lock.json` equivalent that records everything that's
221
- * | // installed, when it was installed, what the original source was,
222
- * | // and what version of `api` was used.
223
- * └── apis/
224
- * ├── readme/
225
- * | ├── node_modules/
226
- * │ ├── index.js // We may offer the option to export a raw TS file for folks who want
227
- * | | // that, but for now it'll be a compiled JS file.
228
- * │ ├── index.d.ts // All types for their SDK, ready to use in an IDE.
229
- * │ |── openapi.json
230
- * │ └── package.json
231
- * └── petstore/
232
- * ├── node_modules/
233
- * ├── index.js
234
- * ├── index.d.ts
235
- * ├── openapi.json
236
- * └── package.json
237
- *
238
- */
239
- Storage.prototype.save = function (spec) {
240
- if (!this.identifier) {
241
- throw new TypeError('An identifier must be set before saving the API definition into storage.');
242
- }
243
- // Create our main `.api/` directory.
244
- if (!fs_1["default"].existsSync(Storage.dir)) {
245
- fs_1["default"].mkdirSync(Storage.dir, { recursive: true });
246
- }
247
- // Create the `.api/apis/` diretory where we'll be storing API definitions.
248
- if (!fs_1["default"].existsSync(Storage.getAPIsDir())) {
249
- fs_1["default"].mkdirSync(Storage.getAPIsDir(), { recursive: true });
250
- }
251
- if (!this.isInLockfile()) {
252
- // This API doesn't exist within our storage system yet so we need to record it in the
253
- // lockfile.
254
- var identifierStorageDir = path_1["default"].join(Storage.getAPIsDir(), this.identifier);
255
- var saved = JSON.stringify(spec, null, 2);
256
- // Create the `.api/apis/<identifier>` directory where we'll be storing this API definition
257
- // and eventually its codegen'd SDK.
258
- if (!fs_1["default"].existsSync(identifierStorageDir)) {
259
- fs_1["default"].mkdirSync(identifierStorageDir, { recursive: true });
260
- }
261
- Storage.lockfile.apis.push({
262
- identifier: this.identifier,
263
- source: this.source,
264
- integrity: Storage.generateIntegrityHash(spec),
265
- installerVersion: packageInfo_1.PACKAGE_VERSION
266
- });
267
- fs_1["default"].writeFileSync(path_1["default"].join(identifierStorageDir, 'openapi.json'), saved);
268
- fs_1["default"].writeFileSync(Storage.getLockfilePath(), JSON.stringify(Storage.lockfile, null, 2));
269
- }
270
- else {
271
- // Is this the same spec that we already have? Should we update it? // @todo
272
- }
273
- return spec;
274
- };
275
- return Storage;
276
- }());
277
- exports["default"] = Storage;
@@ -1,12 +0,0 @@
1
- declare class FetchError<Status = number, Data = unknown> extends Error {
2
- /** HTTP Status */
3
- status: Status;
4
- /** The content of the response. */
5
- data: Data;
6
- /** The Headers of the response. */
7
- headers: Headers;
8
- /** The raw `Response` object. */
9
- res: Response;
10
- constructor(status: Status, data: Data, headers: Headers, res: Response);
11
- }
12
- export default FetchError;
@@ -1,36 +0,0 @@
1
- "use strict";
2
- var __extends = (this && this.__extends) || (function () {
3
- var extendStatics = function (d, b) {
4
- extendStatics = Object.setPrototypeOf ||
5
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7
- return extendStatics(d, b);
8
- };
9
- return function (d, b) {
10
- if (typeof b !== "function" && b !== null)
11
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12
- extendStatics(d, b);
13
- function __() { this.constructor = d; }
14
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15
- };
16
- })();
17
- exports.__esModule = true;
18
- var FetchError = /** @class */ (function (_super) {
19
- __extends(FetchError, _super);
20
- function FetchError(status, data, headers, res) {
21
- var _this = _super.call(this, res.statusText) || this;
22
- _this.name = 'FetchError';
23
- _this.status = status;
24
- _this.data = data;
25
- _this.headers = headers;
26
- _this.res = res;
27
- // We could fix this by updating our target to ES2015 but because we support exporting to CJS
28
- // we can't.
29
- //
30
- // https://www.dannyguo.com/blog/how-to-fix-instanceof-not-working-for-custom-errors-in-typescript/
31
- Object.setPrototypeOf(_this, FetchError.prototype);
32
- return _this;
33
- }
34
- return FetchError;
35
- }(Error));
36
- exports["default"] = FetchError;
@@ -1,14 +0,0 @@
1
- import type { SchemaWrapper } from 'oas/dist/operation/get-parameters-as-json-schema';
2
- /**
3
- * Run through a JSON Schema object and compose up an object containing default data for any schema
4
- * property that is required and also has a defined default.
5
- *
6
- * Code partially adapted from the `json-schema-default` package but modified to only return
7
- * defaults of required properties.
8
- *
9
- * @todo This is a good candidate to be moved into a core `oas` library method.
10
- * @see {@link https://github.com/mdornseif/json-schema-default}
11
- */
12
- export default function getJSONSchemaDefaults(jsonSchemas: SchemaWrapper[]): {
13
- [x: string]: Record<string, unknown>;
14
- };
@@ -1,61 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- exports.__esModule = true;
6
- var json_schema_traverse_1 = __importDefault(require("json-schema-traverse"));
7
- /**
8
- * Run through a JSON Schema object and compose up an object containing default data for any schema
9
- * property that is required and also has a defined default.
10
- *
11
- * Code partially adapted from the `json-schema-default` package but modified to only return
12
- * defaults of required properties.
13
- *
14
- * @todo This is a good candidate to be moved into a core `oas` library method.
15
- * @see {@link https://github.com/mdornseif/json-schema-default}
16
- */
17
- function getJSONSchemaDefaults(jsonSchemas) {
18
- return jsonSchemas
19
- .map(function (_a) {
20
- var _b;
21
- var payloadType = _a.type, jsonSchema = _a.schema;
22
- var defaults = {};
23
- (0, json_schema_traverse_1["default"])(jsonSchema, function (schema, pointer, rootSchema, parentPointer, parentKeyword, parentSchema, indexProperty) {
24
- if (!pointer.startsWith('/properties/')) {
25
- return;
26
- }
27
- if (Array.isArray(parentSchema === null || parentSchema === void 0 ? void 0 : parentSchema.required) && parentSchema.required.includes(indexProperty)) {
28
- if (schema.type === 'object' && indexProperty) {
29
- defaults[indexProperty] = {};
30
- }
31
- var destination_1 = defaults;
32
- if (parentPointer) {
33
- // To map nested objects correct we need to pick apart the parent pointer.
34
- parentPointer
35
- .replace(/\/properties/g, '')
36
- .split('/')
37
- .forEach(function (subSchema) {
38
- if (subSchema === '') {
39
- return;
40
- }
41
- destination_1 = (destination_1 === null || destination_1 === void 0 ? void 0 : destination_1[subSchema]) || {};
42
- });
43
- }
44
- if (schema["default"] !== undefined) {
45
- if (indexProperty !== undefined) {
46
- destination_1[indexProperty] = schema["default"];
47
- }
48
- }
49
- }
50
- });
51
- if (!Object.keys(defaults).length) {
52
- return {};
53
- }
54
- return _b = {},
55
- // @todo should we filter out empty and undefined objects from here with `remove-undefined-objects`?
56
- _b[payloadType] = defaults,
57
- _b;
58
- })
59
- .reduce(function (prev, next) { return Object.assign(prev, next); });
60
- }
61
- exports["default"] = getJSONSchemaDefaults;
@@ -1,40 +0,0 @@
1
- import type Oas from 'oas';
2
- import type { Operation } from 'oas';
3
- import type { HttpMethods } from 'oas/dist/rmoas.types';
4
- import 'isomorphic-fetch';
5
- import getJSONSchemaDefaults from './getJSONSchemaDefaults';
6
- import parseResponse from './parseResponse';
7
- import prepareAuth from './prepareAuth';
8
- import prepareParams from './prepareParams';
9
- import prepareServer from './prepareServer';
10
- export interface ConfigOptions {
11
- /**
12
- * Override the default `fetch` request timeout of 30 seconds. This number should be represented
13
- * in milliseconds.
14
- */
15
- timeout?: number;
16
- }
17
- export interface FetchResponse<status, data> {
18
- data: data;
19
- headers: Headers;
20
- res: Response;
21
- status: status;
22
- }
23
- type Enumerate<N extends number, Acc extends number[] = []> = Acc['length'] extends N ? Acc[number] : Enumerate<N, [...Acc, Acc['length']]>;
24
- export type HTTPMethodRange<F extends number, T extends number> = Exclude<Enumerate<T>, Enumerate<F>>;
25
- export { getJSONSchemaDefaults, parseResponse, prepareAuth, prepareParams, prepareServer };
26
- export default class APICore {
27
- spec: Oas;
28
- private auth;
29
- private server;
30
- private config;
31
- private userAgent;
32
- constructor(spec?: Oas, userAgent?: string);
33
- setSpec(spec: Oas): void;
34
- setConfig(config: ConfigOptions): this;
35
- setUserAgent(userAgent: string): this;
36
- setAuth(...values: string[] | number[]): this;
37
- setServer(url: string, variables?: Record<string, string | number>): this;
38
- fetch(path: string, method: HttpMethods, body?: unknown, metadata?: Record<string, unknown>): Promise<any>;
39
- fetchOperation(operation: Operation, body?: unknown, metadata?: Record<string, unknown>): Promise<any>;
40
- }
@@ -1,168 +0,0 @@
1
- "use strict";
2
- var __assign = (this && this.__assign) || function () {
3
- __assign = Object.assign || function(t) {
4
- for (var s, i = 1, n = arguments.length; i < n; i++) {
5
- s = arguments[i];
6
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
- t[p] = s[p];
8
- }
9
- return t;
10
- };
11
- return __assign.apply(this, arguments);
12
- };
13
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
14
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
15
- return new (P || (P = Promise))(function (resolve, reject) {
16
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
17
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
18
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
19
- step((generator = generator.apply(thisArg, _arguments || [])).next());
20
- });
21
- };
22
- var __generator = (this && this.__generator) || function (thisArg, body) {
23
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
24
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
- function verb(n) { return function (v) { return step([n, v]); }; }
26
- function step(op) {
27
- if (f) throw new TypeError("Generator is already executing.");
28
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
29
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
30
- if (y = 0, t) op = [op[0] & 2, t.value];
31
- switch (op[0]) {
32
- case 0: case 1: t = op; break;
33
- case 4: _.label++; return { value: op[1], done: false };
34
- case 5: _.label++; y = op[1]; op = [0]; continue;
35
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
36
- default:
37
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
38
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
39
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
40
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
41
- if (t[2]) _.ops.pop();
42
- _.trys.pop(); continue;
43
- }
44
- op = body.call(thisArg, _);
45
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
46
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
47
- }
48
- };
49
- var __importDefault = (this && this.__importDefault) || function (mod) {
50
- return (mod && mod.__esModule) ? mod : { "default": mod };
51
- };
52
- exports.__esModule = true;
53
- exports.prepareServer = exports.prepareParams = exports.prepareAuth = exports.parseResponse = exports.getJSONSchemaDefaults = void 0;
54
- var oas_to_har_1 = __importDefault(require("@readme/oas-to-har"));
55
- var fetch_har_1 = __importDefault(require("fetch-har"));
56
- var form_data_encoder_1 = require("form-data-encoder");
57
- require("isomorphic-fetch");
58
- // `AbortController` was shipped in Node 15 so when Node 14 is EOL'd we can drop this dependency.
59
- var node_abort_controller_1 = require("node-abort-controller");
60
- var fetchError_1 = __importDefault(require("./errors/fetchError"));
61
- var getJSONSchemaDefaults_1 = __importDefault(require("./getJSONSchemaDefaults"));
62
- exports.getJSONSchemaDefaults = getJSONSchemaDefaults_1["default"];
63
- var parseResponse_1 = __importDefault(require("./parseResponse"));
64
- exports.parseResponse = parseResponse_1["default"];
65
- var prepareAuth_1 = __importDefault(require("./prepareAuth"));
66
- exports.prepareAuth = prepareAuth_1["default"];
67
- var prepareParams_1 = __importDefault(require("./prepareParams"));
68
- exports.prepareParams = prepareParams_1["default"];
69
- var prepareServer_1 = __importDefault(require("./prepareServer"));
70
- exports.prepareServer = prepareServer_1["default"];
71
- var APICore = /** @class */ (function () {
72
- function APICore(spec, userAgent) {
73
- this.auth = [];
74
- this.server = false;
75
- this.config = {};
76
- this.spec = spec;
77
- this.userAgent = userAgent;
78
- }
79
- APICore.prototype.setSpec = function (spec) {
80
- this.spec = spec;
81
- };
82
- APICore.prototype.setConfig = function (config) {
83
- this.config = config;
84
- return this;
85
- };
86
- APICore.prototype.setUserAgent = function (userAgent) {
87
- this.userAgent = userAgent;
88
- return this;
89
- };
90
- APICore.prototype.setAuth = function () {
91
- var values = [];
92
- for (var _i = 0; _i < arguments.length; _i++) {
93
- values[_i] = arguments[_i];
94
- }
95
- this.auth = values;
96
- return this;
97
- };
98
- APICore.prototype.setServer = function (url, variables) {
99
- if (variables === void 0) { variables = {}; }
100
- this.server = { url: url, variables: variables };
101
- return this;
102
- };
103
- APICore.prototype.fetch = function (path, method, body, metadata) {
104
- return __awaiter(this, void 0, void 0, function () {
105
- var operation;
106
- return __generator(this, function (_a) {
107
- operation = this.spec.operation(path, method);
108
- return [2 /*return*/, this.fetchOperation(operation, body, metadata)];
109
- });
110
- });
111
- };
112
- APICore.prototype.fetchOperation = function (operation, body, metadata) {
113
- return __awaiter(this, void 0, void 0, function () {
114
- var _this = this;
115
- return __generator(this, function (_a) {
116
- return [2 /*return*/, (0, prepareParams_1["default"])(operation, body, metadata).then(function (params) {
117
- var data = __assign({}, params);
118
- // If `sdk.server()` has been issued data then we need to do some extra work to figure out
119
- // how to use that supplied server, and also handle any server variables that were sent
120
- // alongside it.
121
- if (_this.server) {
122
- var preparedServer = (0, prepareServer_1["default"])(_this.spec, _this.server.url, _this.server.variables);
123
- if (preparedServer) {
124
- data.server = preparedServer;
125
- }
126
- }
127
- // @ts-expect-error `this.auth` typing is off. FIXME
128
- var har = (0, oas_to_har_1["default"])(_this.spec, operation, data, (0, prepareAuth_1["default"])(_this.auth, operation));
129
- var timeoutSignal;
130
- var init = {};
131
- if (_this.config.timeout) {
132
- var controller_1 = new node_abort_controller_1.AbortController();
133
- timeoutSignal = setTimeout(function () { return controller_1.abort(); }, _this.config.timeout);
134
- // @todo Typing on `AbortController` coming out of `node-abort-controler` isn't right so when
135
- // we eventually drop that dependency we can remove the `as any` here.
136
- init.signal = controller_1.signal;
137
- }
138
- return (0, fetch_har_1["default"])(har, {
139
- files: data.files || {},
140
- init: init,
141
- multipartEncoder: form_data_encoder_1.FormDataEncoder,
142
- userAgent: _this.userAgent
143
- })
144
- .then(function (res) { return __awaiter(_this, void 0, void 0, function () {
145
- var parsed;
146
- return __generator(this, function (_a) {
147
- switch (_a.label) {
148
- case 0: return [4 /*yield*/, (0, parseResponse_1["default"])(res)];
149
- case 1:
150
- parsed = _a.sent();
151
- if (res.status >= 400 && res.status <= 599) {
152
- throw new fetchError_1["default"](parsed.status, parsed.data, parsed.headers, parsed.res);
153
- }
154
- return [2 /*return*/, parsed];
155
- }
156
- });
157
- }); })["finally"](function () {
158
- if (_this.config.timeout) {
159
- clearTimeout(timeoutSignal);
160
- }
161
- });
162
- })];
163
- });
164
- });
165
- };
166
- return APICore;
167
- }());
168
- exports["default"] = APICore;
@@ -1,6 +0,0 @@
1
- export default function getResponseBody(response: Response): Promise<{
2
- data: string;
3
- status: number;
4
- headers: Headers;
5
- res: Response;
6
- }>;