api-def 0.11.1 → 0.12.0-alpha.2

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.
@@ -0,0 +1,174 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ var __generator = (this && this.__generator) || function (thisArg, body) {
45
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
46
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
47
+ function verb(n) { return function (v) { return step([n, v]); }; }
48
+ function step(op) {
49
+ if (f) throw new TypeError("Generator is already executing.");
50
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
51
+ 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;
52
+ if (y = 0, t) op = [op[0] & 2, t.value];
53
+ switch (op[0]) {
54
+ case 0: case 1: t = op; break;
55
+ case 4: _.label++; return { value: op[1], done: false };
56
+ case 5: _.label++; y = op[1]; op = [0]; continue;
57
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
58
+ default:
59
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
60
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
61
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
62
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
63
+ if (t[2]) _.ops.pop();
64
+ _.trys.pop(); continue;
65
+ }
66
+ op = body.call(thisArg, _);
67
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
68
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
69
+ }
70
+ };
71
+ var __importDefault = (this && this.__importDefault) || function (mod) {
72
+ return (mod && mod.__esModule) ? mod : { "default": mod };
73
+ };
74
+ Object.defineProperty(exports, "__esModule", { value: true });
75
+ exports.openApiToSourceCode = void 0;
76
+ var fs = __importStar(require("node:fs"));
77
+ var openapi_core_1 = require("@redocly/openapi-core");
78
+ // @ts-ignore
79
+ var chalk_1 = __importDefault(require("chalk"));
80
+ var lodash_1 = require("lodash");
81
+ var openapi_typescript_1 = __importStar(require("openapi-typescript"));
82
+ var METHOD_COLORS = {
83
+ get: chalk_1.default.green,
84
+ post: chalk_1.default.blue,
85
+ put: chalk_1.default.yellow,
86
+ delete: chalk_1.default.red,
87
+ patch: chalk_1.default.magenta,
88
+ };
89
+ var openApiToSourceCode = function (options) { return __awaiter(void 0, void 0, void 0, function () {
90
+ var openApiPath, inContents, ast, bundleResults, _a, routes, server, extraTypes, source, types;
91
+ var _b;
92
+ return __generator(this, function (_c) {
93
+ switch (_c.label) {
94
+ case 0:
95
+ openApiPath = options.openApiPath;
96
+ inContents = fs.readFileSync(openApiPath, "utf-8");
97
+ return [4 /*yield*/, (0, openapi_typescript_1.default)(inContents, {
98
+ rootTypes: true,
99
+ })];
100
+ case 1:
101
+ ast = _c.sent();
102
+ _a = openapi_core_1.bundle;
103
+ _b = {
104
+ ref: openApiPath
105
+ };
106
+ return [4 /*yield*/, (0, openapi_core_1.createConfig)({})];
107
+ case 2: return [4 /*yield*/, _a.apply(void 0, [(_b.config = _c.sent(),
108
+ _b)])];
109
+ case 3:
110
+ bundleResults = _c.sent();
111
+ routes = bundleResults.bundle.parsed.paths;
112
+ server = bundleResults.bundle.parsed.servers[0];
113
+ extraTypes = "";
114
+ source = "import { Api } from \"api-def\";\n\nconst API = new Api({\n name: \"".concat(bundleResults.bundle.parsed.info.title || "Generate Api", "\",\n baseUrl: \"").concat(server.url, "\",\n});\n\n").concat(Object.entries(routes)
115
+ .flatMap(function (_a) {
116
+ var path = _a[0], route = _a[1];
117
+ return Object.entries(route).map(function (_a) {
118
+ var _b, _c;
119
+ var method = _a[0], methodDef = _a[1];
120
+ var id = methodDef.operationId;
121
+ var responseStatuses = Object.keys(methodDef.responses);
122
+ var successfulResponse = responseStatuses.filter(function (status) { return status.startsWith("2") || status.startsWith("3"); });
123
+ var responseTypes = [];
124
+ for (var _i = 0, successfulResponse_1 = successfulResponse; _i < successfulResponse_1.length; _i++) {
125
+ var status_1 = successfulResponse_1[_i];
126
+ var response = methodDef.responses[status_1];
127
+ if (response.$ref) {
128
+ responseTypes.push("Response".concat(response.$ref.split("/").pop()));
129
+ }
130
+ }
131
+ var bodyTypes = [];
132
+ if ((_b = methodDef.requestBody) === null || _b === void 0 ? void 0 : _b.$ref) {
133
+ bodyTypes.push("RequestBody".concat(methodDef.requestBody.$ref.split("/").pop()));
134
+ }
135
+ var queryTypes = [];
136
+ if ((_c = methodDef.parameters) === null || _c === void 0 ? void 0 : _c.length) {
137
+ var anyQueryParams = methodDef.parameters.some(function (param) {
138
+ if (param.in === "query") {
139
+ return true;
140
+ }
141
+ if (param.$ref) {
142
+ var ref = param.$ref;
143
+ var paramDef = bundleResults.bundle.parsed.components.parameters[ref.split("/").pop()];
144
+ return paramDef.in === "query";
145
+ }
146
+ return false;
147
+ });
148
+ if (anyQueryParams) {
149
+ extraTypes += "export type Query".concat((0, lodash_1.upperFirst)(id), " = operations[\"").concat(id, "\"][\"parameters\"][\"query\"];\n");
150
+ queryTypes.push("Query".concat((0, lodash_1.upperFirst)(id)));
151
+ }
152
+ }
153
+ /*
154
+ const methodColor = METHOD_COLORS[method] || chalk.gray;
155
+ console.log(`Generating ${methodColor(method.toUpperCase())} '${id}'`);
156
+ */
157
+ var endpointParts = [
158
+ responseTypes.length > 0 ? ".response<".concat(responseTypes.join("|"), ">()") : "",
159
+ bodyTypes.length > 0 ? ".body<".concat(bodyTypes.join("|"), ">()") : "",
160
+ queryTypes.length > 0 ? ".query<".concat(queryTypes.join("|"), ">()") : "",
161
+ ];
162
+ return "export const ".concat(id, " = API.endpoint()\n").concat(endpointParts
163
+ .filter(Boolean)
164
+ .map(function (part) { return " ".concat(part); })
165
+ .join("\n"), "\n .build({\n method: \"").concat(method, "\",\n path: \"").concat(path, "\",\n id: \"").concat(id, "\",\n });");
166
+ });
167
+ })
168
+ .join("\n\n"), "\n\nexport default API;\n ");
169
+ types = (0, openapi_typescript_1.astToString)(ast);
170
+ return [2 /*return*/, "// Type Defs\n\n".concat(types, "\n").concat(extraTypes, "\n\n//API Def\n\n").concat(source)];
171
+ }
172
+ });
173
+ }); };
174
+ exports.openApiToSourceCode = openApiToSourceCode;
package/bin/index.js ADDED
@@ -0,0 +1,98 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ var __generator = (this && this.__generator) || function (thisArg, body) {
45
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
46
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
47
+ function verb(n) { return function (v) { return step([n, v]); }; }
48
+ function step(op) {
49
+ if (f) throw new TypeError("Generator is already executing.");
50
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
51
+ 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;
52
+ if (y = 0, t) op = [op[0] & 2, t.value];
53
+ switch (op[0]) {
54
+ case 0: case 1: t = op; break;
55
+ case 4: _.label++; return { value: op[1], done: false };
56
+ case 5: _.label++; y = op[1]; op = [0]; continue;
57
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
58
+ default:
59
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
60
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
61
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
62
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
63
+ if (t[2]) _.ops.pop();
64
+ _.trys.pop(); continue;
65
+ }
66
+ op = body.call(thisArg, _);
67
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
68
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
69
+ }
70
+ };
71
+ Object.defineProperty(exports, "__esModule", { value: true });
72
+ var fs = __importStar(require("node:fs"));
73
+ var path = __importStar(require("node:path"));
74
+ var commander_1 = require("commander");
75
+ var OpenApiToSourceCode_1 = require("./OpenApiToSourceCode");
76
+ commander_1.program.name("api-def");
77
+ var packageJson = JSON.parse(fs.readFileSync("package.json", "utf-8"));
78
+ commander_1.program.version(packageJson.version);
79
+ commander_1.program
80
+ .command("generate")
81
+ .argument("<inPath>", "Path to the OpenAPI spec")
82
+ .argument("<outPath>", "Path to the output file")
83
+ .description("Generate an api-def from an OpenAPI spec")
84
+ .action(function (inPath, outPath) { return __awaiter(void 0, void 0, void 0, function () {
85
+ var output;
86
+ return __generator(this, function (_a) {
87
+ switch (_a.label) {
88
+ case 0: return [4 /*yield*/, (0, OpenApiToSourceCode_1.openApiToSourceCode)({
89
+ openApiPath: path.resolve(inPath),
90
+ })];
91
+ case 1:
92
+ output = _a.sent();
93
+ fs.writeFileSync(path.resolve(outPath), output);
94
+ return [2 /*return*/];
95
+ }
96
+ });
97
+ }); });
98
+ commander_1.program.parse(process.argv);
package/cjs/Api.d.ts CHANGED
@@ -6,26 +6,41 @@ import type RequestBackend from "./backend/RequestBackend";
6
6
  export declare const getRequestBackend: () => RequestBackend | null;
7
7
  export declare const isRequestBackendDefault: () => boolean;
8
8
  export declare const setRequestBackend: (backend: RequestBackend) => void;
9
- export interface ApiInfo {
9
+ export interface ApiOptions {
10
10
  readonly name: string;
11
11
  readonly baseUrl: string;
12
12
  readonly middleware?: RequestMiddleware[];
13
+ /** @deprecated use `requestConfig` instead */
13
14
  readonly config?: BaseRequestConfig | (() => BaseRequestConfig);
15
+ readonly requestConfig?: BaseRequestConfig | (() => BaseRequestConfig);
14
16
  readonly mocking?: ApiMockingConfig;
15
17
  readonly requestBackend?: RequestBackend;
16
18
  }
19
+ export type ApiInfo = ApiOptions & Required<Pick<ApiOptions, "middleware" | "requestBackend">>;
17
20
  export declare class Api implements ApiInfo {
18
- readonly baseUrl: string;
19
- readonly name: string;
20
- readonly middleware: RequestMiddleware[];
21
- readonly config?: BaseRequestConfig | (() => BaseRequestConfig);
22
- readonly mocking?: ApiMockingConfig;
23
- readonly requestBackend: RequestBackend;
21
+ private readonly info;
24
22
  protected readonly endpoints: Record<string, Endpoint>;
25
- constructor(info: ApiInfo);
23
+ constructor(options: ApiOptions);
24
+ get requestBackend(): RequestBackend;
25
+ get baseUrl(): string;
26
+ /**
27
+ * @deprecated use `requestConfig` instead
28
+ */
29
+ get config(): BaseRequestConfig | (() => BaseRequestConfig) | undefined;
30
+ get requestConfig(): BaseRequestConfig | (() => BaseRequestConfig) | undefined;
31
+ get middleware(): RequestMiddleware[];
32
+ get mocking(): ApiMockingConfig | undefined;
33
+ get name(): string;
26
34
  endpoint(): EndpointBuilder;
35
+ /**
36
+ * @deprecated use `requestBackend` instead
37
+ */
27
38
  getRequestBackend(): RequestBackend;
39
+ /**
40
+ * @deprecated use `computeRequestConfig()` instead
41
+ */
28
42
  getConfig(): BaseRequestConfig;
43
+ computeRequestConfig(): BaseRequestConfig;
29
44
  private hotRequest;
30
45
  get: <R = unknown>(path: string, config: RequestConfig) => Promise<ApiResponse<R>>;
31
46
  post: <R = unknown>(path: string, config: RequestConfig) => Promise<ApiResponse<R>>;
package/cjs/Api.js CHANGED
@@ -9,8 +9,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
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;
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
14
  function verb(n) { return function (v) { return step([n, v]); }; }
15
15
  function step(op) {
16
16
  if (f) throw new TypeError("Generator is already executing.");
@@ -76,7 +76,7 @@ var HotRequestHost = /** @class */ (function () {
76
76
  });
77
77
  HotRequestHost.prototype.computeConfig = function (config) {
78
78
  var apiDefaults = this.api.getConfig();
79
- return (0, RequestConfig_1.computeRequestConfig)([apiDefaults, config]);
79
+ return (0, RequestConfig_1.processRequestConfigs)([apiDefaults, config]);
80
80
  };
81
81
  HotRequestHost.prototype.computePath = function (path, config) {
82
82
  return path.startsWith("/") ? path : "/".concat(path);
@@ -87,10 +87,27 @@ var HotRequestHost = /** @class */ (function () {
87
87
  return HotRequestHost;
88
88
  }());
89
89
  var Api = /** @class */ (function () {
90
- function Api(info) {
90
+ function Api(options) {
91
91
  var _this = this;
92
92
  var _a, _b;
93
93
  this.endpoints = {};
94
+ /*reconfigure(info: Partial<ApiInfo>): void {
95
+ if (info.requestBackend) {
96
+ (this as any).requestBackend = info.requestBackend;
97
+ }
98
+ if (info.config) {
99
+ (this as any).config = info.config;
100
+ }
101
+ if (info.middleware) {
102
+ (this as any).middleware = info.middleware;
103
+ }
104
+ if (info.mocking) {
105
+ (this as any).mocking = info.mocking;
106
+ }
107
+ if (info.baseUrl) {
108
+ (this as any).baseUrl = info.baseUrl;
109
+ }
110
+ }*/
94
111
  this.hotRequest = function (requestMethod) {
95
112
  return function (path, config) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
96
113
  switch (_a.label) {
@@ -104,26 +121,90 @@ var Api = /** @class */ (function () {
104
121
  this.put = this.hotRequest(ApiConstants_1.RequestMethod.PUT);
105
122
  this.delete = this.hotRequest(ApiConstants_1.RequestMethod.DELETE);
106
123
  this.patch = this.hotRequest(ApiConstants_1.RequestMethod.PATCH);
107
- this.name = info.name;
108
- this.baseUrl = info.baseUrl;
109
- this.middleware = info.middleware || [];
110
- this.endpoints = {};
111
- this.config = info.config;
112
- this.mocking = (_a = info.mocking) !== null && _a !== void 0 ? _a : undefined;
113
- var requestBackend = (_b = info.requestBackend) !== null && _b !== void 0 ? _b : (0, exports.getRequestBackend)();
124
+ var requestBackend = (_a = options.requestBackend) !== null && _a !== void 0 ? _a : (0, exports.getRequestBackend)();
114
125
  if (!requestBackend) {
115
126
  throw new Error("[api-def] No request backend provided in either Api options or globally, use `setRequestBackend()` to set one or pass one via `requestBackend`");
116
127
  }
117
- this.requestBackend = requestBackend;
128
+ this.info = {
129
+ name: options.name,
130
+ baseUrl: options.baseUrl,
131
+ middleware: options.middleware || [],
132
+ config: options.config,
133
+ requestConfig: options.requestConfig,
134
+ mocking: (_b = options.mocking) !== null && _b !== void 0 ? _b : undefined,
135
+ requestBackend: requestBackend,
136
+ };
137
+ this.endpoints = {};
118
138
  }
139
+ Object.defineProperty(Api.prototype, "requestBackend", {
140
+ get: function () {
141
+ return this.info.requestBackend;
142
+ },
143
+ enumerable: false,
144
+ configurable: true
145
+ });
146
+ Object.defineProperty(Api.prototype, "baseUrl", {
147
+ get: function () {
148
+ return this.info.baseUrl;
149
+ },
150
+ enumerable: false,
151
+ configurable: true
152
+ });
153
+ Object.defineProperty(Api.prototype, "config", {
154
+ /**
155
+ * @deprecated use `requestConfig` instead
156
+ */
157
+ get: function () {
158
+ return this.info.config;
159
+ },
160
+ enumerable: false,
161
+ configurable: true
162
+ });
163
+ Object.defineProperty(Api.prototype, "requestConfig", {
164
+ get: function () {
165
+ return this.info.requestConfig;
166
+ },
167
+ enumerable: false,
168
+ configurable: true
169
+ });
170
+ Object.defineProperty(Api.prototype, "middleware", {
171
+ get: function () {
172
+ return this.info.middleware;
173
+ },
174
+ enumerable: false,
175
+ configurable: true
176
+ });
177
+ Object.defineProperty(Api.prototype, "mocking", {
178
+ get: function () {
179
+ return this.info.mocking;
180
+ },
181
+ enumerable: false,
182
+ configurable: true
183
+ });
184
+ Object.defineProperty(Api.prototype, "name", {
185
+ get: function () {
186
+ return this.info.name;
187
+ },
188
+ enumerable: false,
189
+ configurable: true
190
+ });
119
191
  Api.prototype.endpoint = function () {
120
192
  return new EndpointBuilder_1.default(this);
121
193
  };
194
+ /**
195
+ * @deprecated use `requestBackend` instead
196
+ */
122
197
  Api.prototype.getRequestBackend = function () {
123
198
  return this.requestBackend;
124
199
  };
200
+ /**
201
+ * @deprecated use `computeRequestConfig()` instead
202
+ */
125
203
  Api.prototype.getConfig = function () {
126
- return (typeof this.config === "function" ? this.config() : this.config) || {};
204
+ return this.computeRequestConfig();
205
+ };
206
+ Api.prototype.computeRequestConfig = function () {
207
+ return (typeof this.requestConfig === "function" ? this.requestConfig() : this.requestConfig) || {};
127
208
  };
128
209
  return Api;
129
210
  }());
package/cjs/Endpoint.d.ts CHANGED
@@ -4,7 +4,7 @@ import type { ApiResponse, BaseRequestConfig, Body, ComputedRequestConfig, Param
4
4
  import type * as Mocking from "./MockingTypes";
5
5
  import type { Validation } from "./Validation";
6
6
  import type RequestBackend from "./backend/RequestBackend";
7
- export interface EndpointConfig<TResult, TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State = State, TPath extends string = string> {
7
+ export interface EndpointOptions<TResult, TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State = State, TPath extends string = string> {
8
8
  readonly id: string;
9
9
  readonly method: RequestMethod;
10
10
  readonly path: TPath;
@@ -32,21 +32,31 @@ export interface EndpointConfig<TResult, TParams extends Params | undefined, TQu
32
32
  readonly mocking?: Mocking.EndpointMockingConfig<TResult, TParams, TQuery, TBody, TState>;
33
33
  readonly validation?: Validation<TResult, TParams, TQuery, TBody, TState>;
34
34
  }
35
- export default class Endpoint<TResponse = any, TParams extends Params | undefined = Params | undefined, TQuery extends Query | undefined = Query | undefined, TBody extends Body | undefined = Body | undefined, TState extends State = State> implements EndpointConfig<TResponse, TParams, TQuery, TBody, TState>, RequestHost {
35
+ export type EndpointInfo<TResult, TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State = State, TPath extends string = string> = EndpointOptions<TResult, TParams, TQuery, TBody, TState, TPath> & Required<Pick<EndpointOptions<TResult, TParams, TQuery, TBody, TState, TPath>, "name" | "validation">>;
36
+ /**
37
+ * @deprecated Use `EndpointInfo` instead
38
+ */
39
+ export type EndpointConfig<TResult, TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State = State, TPath extends string = string> = EndpointInfo<TResult, TParams, TQuery, TBody, TState, TPath>;
40
+ export default class Endpoint<TResponse = any, TParams extends Params | undefined = Params | undefined, TQuery extends Query | undefined = Query | undefined, TBody extends Body | undefined = Body | undefined, TState extends State = State> implements EndpointInfo<TResponse, TParams, TQuery, TBody, TState>, RequestHost {
36
41
  readonly api: Api;
37
- readonly id: string;
38
- readonly method: RequestMethod;
39
- readonly name: string;
40
- readonly description?: string;
41
- readonly path: string;
42
- readonly config?: BaseRequestConfig;
43
- readonly responseType: ResponseType | undefined;
44
- readonly mocking?: Mocking.EndpointMockingConfig<TResponse, TParams, TQuery, TBody, TState>;
45
- readonly validation: Validation<TResponse, TParams, TQuery, TBody, TState>;
46
- constructor(api: Api, info: EndpointConfig<TResponse, TParams, TQuery, TBody, TState>);
42
+ private readonly info;
43
+ constructor(api: Api, options: EndpointOptions<TResponse, TParams, TQuery, TBody, TState>);
44
+ get id(): string;
45
+ get method(): RequestMethod;
46
+ get path(): string;
47
+ get name(): string;
48
+ get description(): string | undefined;
49
+ get config(): BaseRequestConfig;
50
+ get responseType(): ResponseType | undefined;
51
+ get mocking(): Mocking.EndpointMockingConfig<TResponse, TParams, TQuery, TBody, TState> | undefined;
52
+ get validation(): Validation<TResponse, TParams, TQuery, TBody, TState>;
47
53
  submit(config: RequestConfig<TParams, TQuery, TBody, TState>): Promise<ApiResponse<TResponse>>;
48
54
  computePath(path: string, request: RequestConfig): string;
49
55
  get baseUrl(): string;
56
+ /**
57
+ * @deprecated Use `computeRequestConfig` instead
58
+ */
50
59
  computeConfig<TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State>(config: RequestConfig<TParams, TQuery, TBody, TState>): ComputedRequestConfig<TParams, TQuery, TBody, TState>;
60
+ computeRequestConfig<TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State>(config: RequestConfig<TParams, TQuery, TBody, TState>): ComputedRequestConfig<TParams, TQuery, TBody, TState>;
51
61
  getRequestBackend(): RequestBackend;
52
62
  }
package/cjs/Endpoint.js CHANGED
@@ -1,4 +1,15 @@
1
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
+ };
2
13
  var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
14
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
15
  return new (P || (P = Promise))(function (resolve, reject) {
@@ -9,8 +20,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
20
  });
10
21
  };
11
22
  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;
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
25
  function verb(n) { return function (v) { return step([n, v]); }; }
15
26
  function step(op) {
16
27
  if (f) throw new TypeError("Generator is already executing.");
@@ -39,18 +50,73 @@ Object.defineProperty(exports, "__esModule", { value: true });
39
50
  var Requester = require("./Requester");
40
51
  var RequestConfig_1 = require("./RequestConfig");
41
52
  var Endpoint = /** @class */ (function () {
42
- function Endpoint(api, info) {
53
+ function Endpoint(api, options) {
43
54
  this.api = api;
44
- this.id = info.id;
45
- this.method = info.method;
46
- this.name = info.name || info.id;
47
- this.description = info.description;
48
- this.path = info.path;
49
- this.config = info.config;
50
- this.responseType = info.responseType;
51
- this.mocking = info.mocking;
52
- this.validation = info.validation || {};
55
+ this.info = __assign(__assign({}, options), { name: options.name || options.id, validation: options.validation || {} });
53
56
  }
57
+ Object.defineProperty(Endpoint.prototype, "id", {
58
+ get: function () {
59
+ return this.info.id;
60
+ },
61
+ enumerable: false,
62
+ configurable: true
63
+ });
64
+ Object.defineProperty(Endpoint.prototype, "method", {
65
+ get: function () {
66
+ return this.info.method;
67
+ },
68
+ enumerable: false,
69
+ configurable: true
70
+ });
71
+ Object.defineProperty(Endpoint.prototype, "path", {
72
+ get: function () {
73
+ return this.info.path;
74
+ },
75
+ enumerable: false,
76
+ configurable: true
77
+ });
78
+ Object.defineProperty(Endpoint.prototype, "name", {
79
+ get: function () {
80
+ return this.info.name;
81
+ },
82
+ enumerable: false,
83
+ configurable: true
84
+ });
85
+ Object.defineProperty(Endpoint.prototype, "description", {
86
+ get: function () {
87
+ return this.info.description;
88
+ },
89
+ enumerable: false,
90
+ configurable: true
91
+ });
92
+ Object.defineProperty(Endpoint.prototype, "config", {
93
+ get: function () {
94
+ return this.info.config || {};
95
+ },
96
+ enumerable: false,
97
+ configurable: true
98
+ });
99
+ Object.defineProperty(Endpoint.prototype, "responseType", {
100
+ get: function () {
101
+ return this.info.responseType;
102
+ },
103
+ enumerable: false,
104
+ configurable: true
105
+ });
106
+ Object.defineProperty(Endpoint.prototype, "mocking", {
107
+ get: function () {
108
+ return this.info.mocking;
109
+ },
110
+ enumerable: false,
111
+ configurable: true
112
+ });
113
+ Object.defineProperty(Endpoint.prototype, "validation", {
114
+ get: function () {
115
+ return this.info.validation;
116
+ },
117
+ enumerable: false,
118
+ configurable: true
119
+ });
54
120
  Endpoint.prototype.submit = function (config) {
55
121
  return __awaiter(this, void 0, void 0, function () {
56
122
  var mock, apiMocking, mockingEnabled;
@@ -92,12 +158,18 @@ var Endpoint = /** @class */ (function () {
92
158
  enumerable: false,
93
159
  configurable: true
94
160
  });
161
+ /**
162
+ * @deprecated Use `computeRequestConfig` instead
163
+ */
95
164
  Endpoint.prototype.computeConfig = function (config) {
96
- var apiDefaults = this.api.getConfig();
97
- return (0, RequestConfig_1.computeRequestConfig)([apiDefaults, this.config, config]);
165
+ return this.computeRequestConfig(config);
166
+ };
167
+ Endpoint.prototype.computeRequestConfig = function (config) {
168
+ var apiDefaults = this.api.computeRequestConfig();
169
+ return (0, RequestConfig_1.processRequestConfigs)([apiDefaults, this.config, config]);
98
170
  };
99
171
  Endpoint.prototype.getRequestBackend = function () {
100
- return this.api.getRequestBackend();
172
+ return this.api.requestBackend;
101
173
  };
102
174
  return Endpoint;
103
175
  }());
@@ -1,2 +1,2 @@
1
1
  import { type BaseRequestConfig, type Body, type ComputedRequestConfig, type Params, type Query, type RequestConfig, type State } from "./ApiTypes";
2
- export declare const computeRequestConfig: <TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State>(configs: (RequestConfig<TParams, TQuery, TBody, TState> | BaseRequestConfig | undefined)[]) => ComputedRequestConfig<TParams, TQuery, TBody, TState>;
2
+ export declare const processRequestConfigs: <TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State>(configs: (RequestConfig<TParams, TQuery, TBody, TState> | BaseRequestConfig | undefined)[]) => ComputedRequestConfig<TParams, TQuery, TBody, TState>;
@@ -9,12 +9,12 @@ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
9
9
  return to.concat(ar || Array.prototype.slice.call(from));
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.computeRequestConfig = void 0;
12
+ exports.processRequestConfigs = void 0;
13
13
  var ApiTypes_1 = require("./ApiTypes");
14
14
  var QueryHandling_1 = require("./QueryHandling");
15
15
  var Utils = require("./Utils");
16
16
  var MERGED_CONFIG_KEYS = ["headers"];
17
- var computeRequestConfig = function (configs) {
17
+ var processRequestConfigs = function (configs) {
18
18
  var _a;
19
19
  var _b, _c;
20
20
  var computedConfig = Utils.assign.apply(Utils, __spreadArray([(_a = {},
@@ -74,4 +74,4 @@ var computeRequestConfig = function (configs) {
74
74
  }
75
75
  return computedConfig;
76
76
  };
77
- exports.computeRequestConfig = computeRequestConfig;
77
+ exports.processRequestConfigs = processRequestConfigs;
@@ -9,8 +9,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
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;
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
14
  function verb(n) { return function (v) { return step([n, v]); }; }
15
15
  function step(op) {
16
16
  if (f) throw new TypeError("Generator is already executing.");
package/cjs/Requester.js CHANGED
@@ -20,8 +20,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
20
20
  });
21
21
  };
22
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;
23
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
24
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
25
25
  function verb(n) { return function (v) { return step([n, v]); }; }
26
26
  function step(op) {
27
27
  if (f) throw new TypeError("Generator is already executing.");
@@ -9,8 +9,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
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;
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
14
  function verb(n) { return function (v) { return step([n, v]); }; }
15
15
  function step(op) {
16
16
  if (f) throw new TypeError("Generator is already executing.");
@@ -59,10 +59,11 @@ var AxiosRequestBackend = /** @class */ (function () {
59
59
  };
60
60
  AxiosRequestBackend.prototype.convertResponse = function (context, response) {
61
61
  return __awaiter(this, void 0, void 0, function () {
62
- return __generator(this, function (_a) {
62
+ var _a, _b, _c, _d;
63
+ return __generator(this, function (_e) {
63
64
  return [2 /*return*/, {
64
65
  method: context.method,
65
- url: response.request.res.responseUrl,
66
+ url: (_b = (_a = response.request.res) === null || _a === void 0 ? void 0 : _a.responseUrl) !== null && _b !== void 0 ? _b : (_d = (_c = response.request) === null || _c === void 0 ? void 0 : _c._redirectable) === null || _d === void 0 ? void 0 : _d._currentUrl,
66
67
  data: response.data,
67
68
  headers: response.headers,
68
69
  status: response.status,
@@ -24,8 +24,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
24
24
  });
25
25
  };
26
26
  var __generator = (this && this.__generator) || function (thisArg, body) {
27
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
28
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
27
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
28
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
29
29
  function verb(n) { return function (v) { return step([n, v]); }; }
30
30
  function step(op) {
31
31
  if (f) throw new TypeError("Generator is already executing.");
@@ -9,8 +9,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
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;
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
14
  function verb(n) { return function (v) { return step([n, v]); }; }
15
15
  function step(op) {
16
16
  if (f) throw new TypeError("Generator is already executing.");
@@ -9,8 +9,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
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;
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
14
  function verb(n) { return function (v) { return step([n, v]); }; }
15
15
  function step(op) {
16
16
  if (f) throw new TypeError("Generator is already executing.");
@@ -9,8 +9,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
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;
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
14
  function verb(n) { return function (v) { return step([n, v]); }; }
15
15
  function step(op) {
16
16
  if (f) throw new TypeError("Generator is already executing.");
package/cjs/index.d.ts CHANGED
@@ -3,7 +3,7 @@ export * from "./ApiTypes";
3
3
  export * from "./UtilTypes";
4
4
  export * from "./ApiConstants";
5
5
  export { default as retry } from "./util/retry";
6
- export { type RetryOptions } from "./util/retry/interfaces";
6
+ export type { RetryOptions } from "./util/retry/interfaces";
7
7
  export { isRequestError, type RequestError } from "./RequestError";
8
8
  export { default as Endpoint, type EndpointConfig } from "./Endpoint";
9
9
  export { clearCache, setCacheBackend } from "./cache/Caching";
@@ -9,8 +9,8 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
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;
12
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
13
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
14
14
  function verb(n) { return function (v) { return step([n, v]); }; }
15
15
  function step(op) {
16
16
  if (f) throw new TypeError("Generator is already executing.");
package/esm/Api.d.ts CHANGED
@@ -6,26 +6,41 @@ import type RequestBackend from "./backend/RequestBackend";
6
6
  export declare const getRequestBackend: () => RequestBackend | null;
7
7
  export declare const isRequestBackendDefault: () => boolean;
8
8
  export declare const setRequestBackend: (backend: RequestBackend) => void;
9
- export interface ApiInfo {
9
+ export interface ApiOptions {
10
10
  readonly name: string;
11
11
  readonly baseUrl: string;
12
12
  readonly middleware?: RequestMiddleware[];
13
+ /** @deprecated use `requestConfig` instead */
13
14
  readonly config?: BaseRequestConfig | (() => BaseRequestConfig);
15
+ readonly requestConfig?: BaseRequestConfig | (() => BaseRequestConfig);
14
16
  readonly mocking?: ApiMockingConfig;
15
17
  readonly requestBackend?: RequestBackend;
16
18
  }
19
+ export type ApiInfo = ApiOptions & Required<Pick<ApiOptions, "middleware" | "requestBackend">>;
17
20
  export declare class Api implements ApiInfo {
18
- readonly baseUrl: string;
19
- readonly name: string;
20
- readonly middleware: RequestMiddleware[];
21
- readonly config?: BaseRequestConfig | (() => BaseRequestConfig);
22
- readonly mocking?: ApiMockingConfig;
23
- readonly requestBackend: RequestBackend;
21
+ private readonly info;
24
22
  protected readonly endpoints: Record<string, Endpoint>;
25
- constructor(info: ApiInfo);
23
+ constructor(options: ApiOptions);
24
+ get requestBackend(): RequestBackend;
25
+ get baseUrl(): string;
26
+ /**
27
+ * @deprecated use `requestConfig` instead
28
+ */
29
+ get config(): BaseRequestConfig | (() => BaseRequestConfig) | undefined;
30
+ get requestConfig(): BaseRequestConfig | (() => BaseRequestConfig) | undefined;
31
+ get middleware(): RequestMiddleware[];
32
+ get mocking(): ApiMockingConfig | undefined;
33
+ get name(): string;
26
34
  endpoint(): EndpointBuilder;
35
+ /**
36
+ * @deprecated use `requestBackend` instead
37
+ */
27
38
  getRequestBackend(): RequestBackend;
39
+ /**
40
+ * @deprecated use `computeRequestConfig()` instead
41
+ */
28
42
  getConfig(): BaseRequestConfig;
43
+ computeRequestConfig(): BaseRequestConfig;
29
44
  private hotRequest;
30
45
  get: <R = unknown>(path: string, config: RequestConfig) => Promise<ApiResponse<R>>;
31
46
  post: <R = unknown>(path: string, config: RequestConfig) => Promise<ApiResponse<R>>;
package/esm/Api.js CHANGED
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  };
10
10
  import { RequestMethod } from "./ApiConstants";
11
11
  import EndpointBuilder from "./EndpointBuilder";
12
- import { computeRequestConfig } from "./RequestConfig";
12
+ import { processRequestConfigs } from "./RequestConfig";
13
13
  import * as Requester from "./Requester";
14
14
  import * as Utils from "./Utils";
15
15
  import FetchRequestBackend from "./backend/FetchRequestBackend";
@@ -39,7 +39,7 @@ class HotRequestHost {
39
39
  }
40
40
  computeConfig(config) {
41
41
  const apiDefaults = this.api.getConfig();
42
- return computeRequestConfig([apiDefaults, config]);
42
+ return processRequestConfigs([apiDefaults, config]);
43
43
  }
44
44
  computePath(path, config) {
45
45
  return path.startsWith("/") ? path : `/${path}`;
@@ -49,34 +49,87 @@ class HotRequestHost {
49
49
  }
50
50
  }
51
51
  export class Api {
52
- constructor(info) {
52
+ constructor(options) {
53
53
  var _a, _b;
54
54
  this.endpoints = {};
55
+ /*reconfigure(info: Partial<ApiInfo>): void {
56
+ if (info.requestBackend) {
57
+ (this as any).requestBackend = info.requestBackend;
58
+ }
59
+ if (info.config) {
60
+ (this as any).config = info.config;
61
+ }
62
+ if (info.middleware) {
63
+ (this as any).middleware = info.middleware;
64
+ }
65
+ if (info.mocking) {
66
+ (this as any).mocking = info.mocking;
67
+ }
68
+ if (info.baseUrl) {
69
+ (this as any).baseUrl = info.baseUrl;
70
+ }
71
+ }*/
55
72
  this.hotRequest = (requestMethod) => (path, config) => __awaiter(this, void 0, void 0, function* () { return yield Requester.submit(new HotRequestHost(this, path, requestMethod), config, null); });
56
73
  this.get = this.hotRequest(RequestMethod.GET);
57
74
  this.post = this.hotRequest(RequestMethod.POST);
58
75
  this.put = this.hotRequest(RequestMethod.PUT);
59
76
  this.delete = this.hotRequest(RequestMethod.DELETE);
60
77
  this.patch = this.hotRequest(RequestMethod.PATCH);
61
- this.name = info.name;
62
- this.baseUrl = info.baseUrl;
63
- this.middleware = info.middleware || [];
64
- this.endpoints = {};
65
- this.config = info.config;
66
- this.mocking = (_a = info.mocking) !== null && _a !== void 0 ? _a : undefined;
67
- const requestBackend = (_b = info.requestBackend) !== null && _b !== void 0 ? _b : getRequestBackend();
78
+ const requestBackend = (_a = options.requestBackend) !== null && _a !== void 0 ? _a : getRequestBackend();
68
79
  if (!requestBackend) {
69
80
  throw new Error("[api-def] No request backend provided in either Api options or globally, use `setRequestBackend()` to set one or pass one via `requestBackend`");
70
81
  }
71
- this.requestBackend = requestBackend;
82
+ this.info = {
83
+ name: options.name,
84
+ baseUrl: options.baseUrl,
85
+ middleware: options.middleware || [],
86
+ config: options.config,
87
+ requestConfig: options.requestConfig,
88
+ mocking: (_b = options.mocking) !== null && _b !== void 0 ? _b : undefined,
89
+ requestBackend: requestBackend,
90
+ };
91
+ this.endpoints = {};
92
+ }
93
+ get requestBackend() {
94
+ return this.info.requestBackend;
95
+ }
96
+ get baseUrl() {
97
+ return this.info.baseUrl;
98
+ }
99
+ /**
100
+ * @deprecated use `requestConfig` instead
101
+ */
102
+ get config() {
103
+ return this.info.config;
104
+ }
105
+ get requestConfig() {
106
+ return this.info.requestConfig;
107
+ }
108
+ get middleware() {
109
+ return this.info.middleware;
110
+ }
111
+ get mocking() {
112
+ return this.info.mocking;
113
+ }
114
+ get name() {
115
+ return this.info.name;
72
116
  }
73
117
  endpoint() {
74
118
  return new EndpointBuilder(this);
75
119
  }
120
+ /**
121
+ * @deprecated use `requestBackend` instead
122
+ */
76
123
  getRequestBackend() {
77
124
  return this.requestBackend;
78
125
  }
126
+ /**
127
+ * @deprecated use `computeRequestConfig()` instead
128
+ */
79
129
  getConfig() {
80
- return (typeof this.config === "function" ? this.config() : this.config) || {};
130
+ return this.computeRequestConfig();
131
+ }
132
+ computeRequestConfig() {
133
+ return (typeof this.requestConfig === "function" ? this.requestConfig() : this.requestConfig) || {};
81
134
  }
82
135
  }
package/esm/Endpoint.d.ts CHANGED
@@ -4,7 +4,7 @@ import type { ApiResponse, BaseRequestConfig, Body, ComputedRequestConfig, Param
4
4
  import type * as Mocking from "./MockingTypes";
5
5
  import type { Validation } from "./Validation";
6
6
  import type RequestBackend from "./backend/RequestBackend";
7
- export interface EndpointConfig<TResult, TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State = State, TPath extends string = string> {
7
+ export interface EndpointOptions<TResult, TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State = State, TPath extends string = string> {
8
8
  readonly id: string;
9
9
  readonly method: RequestMethod;
10
10
  readonly path: TPath;
@@ -32,21 +32,31 @@ export interface EndpointConfig<TResult, TParams extends Params | undefined, TQu
32
32
  readonly mocking?: Mocking.EndpointMockingConfig<TResult, TParams, TQuery, TBody, TState>;
33
33
  readonly validation?: Validation<TResult, TParams, TQuery, TBody, TState>;
34
34
  }
35
- export default class Endpoint<TResponse = any, TParams extends Params | undefined = Params | undefined, TQuery extends Query | undefined = Query | undefined, TBody extends Body | undefined = Body | undefined, TState extends State = State> implements EndpointConfig<TResponse, TParams, TQuery, TBody, TState>, RequestHost {
35
+ export type EndpointInfo<TResult, TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State = State, TPath extends string = string> = EndpointOptions<TResult, TParams, TQuery, TBody, TState, TPath> & Required<Pick<EndpointOptions<TResult, TParams, TQuery, TBody, TState, TPath>, "name" | "validation">>;
36
+ /**
37
+ * @deprecated Use `EndpointInfo` instead
38
+ */
39
+ export type EndpointConfig<TResult, TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State = State, TPath extends string = string> = EndpointInfo<TResult, TParams, TQuery, TBody, TState, TPath>;
40
+ export default class Endpoint<TResponse = any, TParams extends Params | undefined = Params | undefined, TQuery extends Query | undefined = Query | undefined, TBody extends Body | undefined = Body | undefined, TState extends State = State> implements EndpointInfo<TResponse, TParams, TQuery, TBody, TState>, RequestHost {
36
41
  readonly api: Api;
37
- readonly id: string;
38
- readonly method: RequestMethod;
39
- readonly name: string;
40
- readonly description?: string;
41
- readonly path: string;
42
- readonly config?: BaseRequestConfig;
43
- readonly responseType: ResponseType | undefined;
44
- readonly mocking?: Mocking.EndpointMockingConfig<TResponse, TParams, TQuery, TBody, TState>;
45
- readonly validation: Validation<TResponse, TParams, TQuery, TBody, TState>;
46
- constructor(api: Api, info: EndpointConfig<TResponse, TParams, TQuery, TBody, TState>);
42
+ private readonly info;
43
+ constructor(api: Api, options: EndpointOptions<TResponse, TParams, TQuery, TBody, TState>);
44
+ get id(): string;
45
+ get method(): RequestMethod;
46
+ get path(): string;
47
+ get name(): string;
48
+ get description(): string | undefined;
49
+ get config(): BaseRequestConfig;
50
+ get responseType(): ResponseType | undefined;
51
+ get mocking(): Mocking.EndpointMockingConfig<TResponse, TParams, TQuery, TBody, TState> | undefined;
52
+ get validation(): Validation<TResponse, TParams, TQuery, TBody, TState>;
47
53
  submit(config: RequestConfig<TParams, TQuery, TBody, TState>): Promise<ApiResponse<TResponse>>;
48
54
  computePath(path: string, request: RequestConfig): string;
49
55
  get baseUrl(): string;
56
+ /**
57
+ * @deprecated Use `computeRequestConfig` instead
58
+ */
50
59
  computeConfig<TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State>(config: RequestConfig<TParams, TQuery, TBody, TState>): ComputedRequestConfig<TParams, TQuery, TBody, TState>;
60
+ computeRequestConfig<TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State>(config: RequestConfig<TParams, TQuery, TBody, TState>): ComputedRequestConfig<TParams, TQuery, TBody, TState>;
51
61
  getRequestBackend(): RequestBackend;
52
62
  }
package/esm/Endpoint.js CHANGED
@@ -8,19 +8,38 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  });
9
9
  };
10
10
  import * as Requester from "./Requester";
11
- import { computeRequestConfig } from "./RequestConfig";
11
+ import { processRequestConfigs } from "./RequestConfig";
12
12
  export default class Endpoint {
13
- constructor(api, info) {
13
+ constructor(api, options) {
14
14
  this.api = api;
15
- this.id = info.id;
16
- this.method = info.method;
17
- this.name = info.name || info.id;
18
- this.description = info.description;
19
- this.path = info.path;
20
- this.config = info.config;
21
- this.responseType = info.responseType;
22
- this.mocking = info.mocking;
23
- this.validation = info.validation || {};
15
+ this.info = Object.assign(Object.assign({}, options), { name: options.name || options.id, validation: options.validation || {} });
16
+ }
17
+ get id() {
18
+ return this.info.id;
19
+ }
20
+ get method() {
21
+ return this.info.method;
22
+ }
23
+ get path() {
24
+ return this.info.path;
25
+ }
26
+ get name() {
27
+ return this.info.name;
28
+ }
29
+ get description() {
30
+ return this.info.description;
31
+ }
32
+ get config() {
33
+ return this.info.config || {};
34
+ }
35
+ get responseType() {
36
+ return this.info.responseType;
37
+ }
38
+ get mocking() {
39
+ return this.info.mocking;
40
+ }
41
+ get validation() {
42
+ return this.info.validation;
24
43
  }
25
44
  submit(config) {
26
45
  return __awaiter(this, void 0, void 0, function* () {
@@ -56,11 +75,17 @@ export default class Endpoint {
56
75
  get baseUrl() {
57
76
  return this.api.baseUrl;
58
77
  }
78
+ /**
79
+ * @deprecated Use `computeRequestConfig` instead
80
+ */
59
81
  computeConfig(config) {
60
- const apiDefaults = this.api.getConfig();
61
- return computeRequestConfig([apiDefaults, this.config, config]);
82
+ return this.computeRequestConfig(config);
83
+ }
84
+ computeRequestConfig(config) {
85
+ const apiDefaults = this.api.computeRequestConfig();
86
+ return processRequestConfigs([apiDefaults, this.config, config]);
62
87
  }
63
88
  getRequestBackend() {
64
- return this.api.getRequestBackend();
89
+ return this.api.requestBackend;
65
90
  }
66
91
  }
@@ -1,2 +1,2 @@
1
1
  import { type BaseRequestConfig, type Body, type ComputedRequestConfig, type Params, type Query, type RequestConfig, type State } from "./ApiTypes";
2
- export declare const computeRequestConfig: <TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State>(configs: (RequestConfig<TParams, TQuery, TBody, TState> | BaseRequestConfig | undefined)[]) => ComputedRequestConfig<TParams, TQuery, TBody, TState>;
2
+ export declare const processRequestConfigs: <TParams extends Params | undefined, TQuery extends Query | undefined, TBody extends Body | undefined, TState extends State>(configs: (RequestConfig<TParams, TQuery, TBody, TState> | BaseRequestConfig | undefined)[]) => ComputedRequestConfig<TParams, TQuery, TBody, TState>;
@@ -2,7 +2,7 @@ import { COMPUTED_CONFIG_SYMBOL, } from "./ApiTypes";
2
2
  import { DEFAULT_QUERY_PARSE, DEFAULT_QUERY_STRINGIFY } from "./QueryHandling";
3
3
  import * as Utils from "./Utils";
4
4
  const MERGED_CONFIG_KEYS = ["headers"];
5
- export const computeRequestConfig = (configs) => {
5
+ export const processRequestConfigs = (configs) => {
6
6
  var _a, _b;
7
7
  const computedConfig = Utils.assign({
8
8
  [COMPUTED_CONFIG_SYMBOL]: true,
@@ -26,9 +26,10 @@ export default class AxiosRequestBackend {
26
26
  }
27
27
  convertResponse(context, response) {
28
28
  return __awaiter(this, void 0, void 0, function* () {
29
+ var _a, _b, _c, _d;
29
30
  return {
30
31
  method: context.method,
31
- url: response.request.res.responseUrl,
32
+ url: (_b = (_a = response.request.res) === null || _a === void 0 ? void 0 : _a.responseUrl) !== null && _b !== void 0 ? _b : (_d = (_c = response.request) === null || _c === void 0 ? void 0 : _c._redirectable) === null || _d === void 0 ? void 0 : _d._currentUrl,
32
33
  data: response.data,
33
34
  headers: response.headers,
34
35
  status: response.status,
package/esm/index.d.ts CHANGED
@@ -3,7 +3,7 @@ export * from "./ApiTypes";
3
3
  export * from "./UtilTypes";
4
4
  export * from "./ApiConstants";
5
5
  export { default as retry } from "./util/retry";
6
- export { type RetryOptions } from "./util/retry/interfaces";
6
+ export type { RetryOptions } from "./util/retry/interfaces";
7
7
  export { isRequestError, type RequestError } from "./RequestError";
8
8
  export { default as Endpoint, type EndpointConfig } from "./Endpoint";
9
9
  export { clearCache, setCacheBackend } from "./cache/Caching";
package/package.json CHANGED
@@ -1,10 +1,13 @@
1
1
  {
2
2
  "name": "api-def",
3
- "version": "0.11.1",
3
+ "version": "0.12.0-alpha.2",
4
4
  "description": "Typed API definitions with middleware support",
5
5
  "main": "cjs/index.js",
6
6
  "types": "esm/index.d.ts",
7
7
  "module": "esm/index.js",
8
+ "bin": {
9
+ "api-def": "bin/index.js"
10
+ },
8
11
  "sideEffects": false,
9
12
  "scripts": {
10
13
  "prepublishOnly": "npm run check:fix && npm run test && npm run build",
@@ -13,37 +16,49 @@
13
16
  "check:fix": "tsc --noEmit --project tsconfig.json && npx @biomejs/biome check --write",
14
17
  "check": "tsc --noEmit --project tsconfig.json && npx @biomejs/biome check",
15
18
  "cleanup": "rimraf esm && rimraf cjs",
16
- "build": "npm run cleanup && npm run build:esm && npm run build:cjs",
19
+ "build": "npm run cleanup && npm run build:esm && npm run build:cjs && npm run build:cli",
17
20
  "build:esm": "tsc --module es2015 --target es2016 --outDir esm --preserveWatchOutput",
18
21
  "build:cjs": "tsc --module commonjs --target es5 --outDir cjs --preserveWatchOutput",
22
+ "build:cli": "tsc cli/index.ts --module commonjs --target es5 --outDir bin --preserveWatchOutput --esModuleInterop --skipLibCheck",
19
23
  "website:dev": "cd website && npm run start",
20
24
  "website:deploy": "cd website && npm run deploy"
21
25
  },
22
26
  "keywords": ["typescript", "javascript", "node", "web", "api", "typed", "cache", "fetch", "retry", "middleware"],
23
27
  "author": "James Waterhouse <09jwater@gmail.com>",
24
28
  "license": "MIT",
25
- "files": ["LICENSE", "README.md", "esm/", "cjs/"],
29
+ "files": ["LICENSE", "README.md", "esm/", "cjs/", "bin/"],
26
30
  "jest": {
27
31
  "transform": {
28
- "^.+\\.(t|j)sx?$": "@swc/jest"
32
+ "^.+\\.(t|j)sx?$": [
33
+ "@swc/jest",
34
+ {
35
+ "env": {}
36
+ }
37
+ ]
29
38
  }
30
39
  },
31
40
  "repository": "https://github.com/Censkh/api-def",
32
41
  "devDependencies": {
33
- "@biomejs/biome": "1.8.3",
34
- "@swc/core": "latest",
35
- "@swc/jest": "latest",
42
+ "@biomejs/biome": "1.9.4",
43
+ "@redocly/openapi-core": "^1.27.1",
44
+ "@swc/core": "^1.10.7",
45
+ "@swc/jest": "^0.2.37",
36
46
  "@types/axios": "0.14.0",
37
- "@types/jest": "^29.5.12",
38
- "@types/node": "22.4.0",
39
- "@types/qs": "6.9.15",
40
- "axios": "1.7.4",
47
+ "@types/jest": "^29.5.14",
48
+ "@types/lodash": "^4.17.14",
49
+ "@types/node": "22.10.5",
50
+ "@types/qs": "6.9.17",
51
+ "axios": "1.7.9",
52
+ "chalk": "^4.1.2",
53
+ "commander": "^13.0.0",
41
54
  "cross-env": "7.0.3",
42
55
  "jest": "latest",
56
+ "lodash": "^4.17.21",
43
57
  "npm-run-all": "4.1.5",
44
- "qs": "6.13.0",
58
+ "openapi-typescript": "^7.5.2",
59
+ "qs": "6.13.1",
45
60
  "rimraf": "6.0.1",
46
- "typescript": "5.5.4",
47
- "zod": "3.23.8"
61
+ "typescript": "^5.7.3",
62
+ "zod": "3.24.1"
48
63
  }
49
64
  }