api-def 0.12.0-alpha.20 → 0.12.0-alpha.22

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 (134) hide show
  1. package/bin/index.js +1 -1
  2. package/cjs/tests/mock/MockApi.d.ts +16 -0
  3. package/cjs/tests/mock/MockApi.js +67 -0
  4. package/esm/tests/mock/MockApi.d.ts +16 -0
  5. package/esm/tests/mock/MockApi.js +64 -0
  6. package/package.json +1 -1
  7. package/cjs/cli/OpenApiToSourceCode.d.ts +0 -4
  8. package/cjs/cli/OpenApiToSourceCode.js +0 -197
  9. package/cjs/cli/index.d.ts +0 -2
  10. package/cjs/cli/index.js +0 -73
  11. package/esm/cli/OpenApiToSourceCode.d.ts +0 -4
  12. package/esm/cli/OpenApiToSourceCode.js +0 -166
  13. package/esm/cli/index.d.ts +0 -2
  14. package/esm/cli/index.js +0 -35
  15. /package/cjs/{src/Api.d.ts → Api.d.ts} +0 -0
  16. /package/cjs/{src/Api.js → Api.js} +0 -0
  17. /package/cjs/{src/ApiConstants.d.ts → ApiConstants.d.ts} +0 -0
  18. /package/cjs/{src/ApiConstants.js → ApiConstants.js} +0 -0
  19. /package/cjs/{src/ApiTypes.d.ts → ApiTypes.d.ts} +0 -0
  20. /package/cjs/{src/ApiTypes.js → ApiTypes.js} +0 -0
  21. /package/cjs/{src/ApiUtils.d.ts → ApiUtils.d.ts} +0 -0
  22. /package/cjs/{src/ApiUtils.js → ApiUtils.js} +0 -0
  23. /package/cjs/{src/Endpoint.d.ts → Endpoint.d.ts} +0 -0
  24. /package/cjs/{src/Endpoint.js → Endpoint.js} +0 -0
  25. /package/cjs/{src/EndpointBuilder.d.ts → EndpointBuilder.d.ts} +0 -0
  26. /package/cjs/{src/EndpointBuilder.js → EndpointBuilder.js} +0 -0
  27. /package/cjs/{src/MockingTypes.d.ts → MockingTypes.d.ts} +0 -0
  28. /package/cjs/{src/MockingTypes.js → MockingTypes.js} +0 -0
  29. /package/cjs/{src/QueryHandling.d.ts → QueryHandling.d.ts} +0 -0
  30. /package/cjs/{src/QueryHandling.js → QueryHandling.js} +0 -0
  31. /package/cjs/{src/RequestConfig.d.ts → RequestConfig.d.ts} +0 -0
  32. /package/cjs/{src/RequestConfig.js → RequestConfig.js} +0 -0
  33. /package/cjs/{src/RequestContext.d.ts → RequestContext.d.ts} +0 -0
  34. /package/cjs/{src/RequestContext.js → RequestContext.js} +0 -0
  35. /package/cjs/{src/RequestError.d.ts → RequestError.d.ts} +0 -0
  36. /package/cjs/{src/RequestError.js → RequestError.js} +0 -0
  37. /package/cjs/{src/Requester.d.ts → Requester.d.ts} +0 -0
  38. /package/cjs/{src/Requester.js → Requester.js} +0 -0
  39. /package/cjs/{src/TextDecoding.d.ts → TextDecoding.d.ts} +0 -0
  40. /package/cjs/{src/TextDecoding.js → TextDecoding.js} +0 -0
  41. /package/cjs/{src/UtilTypes.d.ts → UtilTypes.d.ts} +0 -0
  42. /package/cjs/{src/UtilTypes.js → UtilTypes.js} +0 -0
  43. /package/cjs/{src/Utils.d.ts → Utils.d.ts} +0 -0
  44. /package/cjs/{src/Utils.js → Utils.js} +0 -0
  45. /package/cjs/{src/Validation.d.ts → Validation.d.ts} +0 -0
  46. /package/cjs/{src/Validation.js → Validation.js} +0 -0
  47. /package/cjs/{src/backend → backend}/AxiosRequestBackend.d.ts +0 -0
  48. /package/cjs/{src/backend → backend}/AxiosRequestBackend.js +0 -0
  49. /package/cjs/{src/backend → backend}/FetchRequestBackend.d.ts +0 -0
  50. /package/cjs/{src/backend → backend}/FetchRequestBackend.js +0 -0
  51. /package/cjs/{src/backend → backend}/MockRequestBackend.d.ts +0 -0
  52. /package/cjs/{src/backend → backend}/MockRequestBackend.js +0 -0
  53. /package/cjs/{src/backend → backend}/RequestBackend.d.ts +0 -0
  54. /package/cjs/{src/backend → backend}/RequestBackend.js +0 -0
  55. /package/cjs/{src/cache → cache}/CacheBackend.d.ts +0 -0
  56. /package/cjs/{src/cache → cache}/CacheBackend.js +0 -0
  57. /package/cjs/{src/cache → cache}/Caching.d.ts +0 -0
  58. /package/cjs/{src/cache → cache}/Caching.js +0 -0
  59. /package/cjs/{src/cache → cache}/LocalForageCacheBackend.d.ts +0 -0
  60. /package/cjs/{src/cache → cache}/LocalForageCacheBackend.js +0 -0
  61. /package/cjs/{src/cache → cache}/LocalStorageCacheBackend.d.ts +0 -0
  62. /package/cjs/{src/cache → cache}/LocalStorageCacheBackend.js +0 -0
  63. /package/cjs/{src/index.d.ts → index.d.ts} +0 -0
  64. /package/cjs/{src/index.js → index.js} +0 -0
  65. /package/cjs/{src/middleware → middleware}/CacheMiddleware.d.ts +0 -0
  66. /package/cjs/{src/middleware → middleware}/CacheMiddleware.js +0 -0
  67. /package/cjs/{src/middleware → middleware}/LoggingMiddleware.d.ts +0 -0
  68. /package/cjs/{src/middleware → middleware}/LoggingMiddleware.js +0 -0
  69. /package/cjs/{src/util → util}/retry/index.d.ts +0 -0
  70. /package/cjs/{src/util → util}/retry/index.js +0 -0
  71. /package/cjs/{src/util → util}/retry/lib/retry.d.ts +0 -0
  72. /package/cjs/{src/util → util}/retry/lib/retry.js +0 -0
  73. /package/cjs/{src/util → util}/retry/lib/retryOperation.d.ts +0 -0
  74. /package/cjs/{src/util → util}/retry/lib/retryOperation.js +0 -0
  75. /package/esm/{src/Api.d.ts → Api.d.ts} +0 -0
  76. /package/esm/{src/Api.js → Api.js} +0 -0
  77. /package/esm/{src/ApiConstants.d.ts → ApiConstants.d.ts} +0 -0
  78. /package/esm/{src/ApiConstants.js → ApiConstants.js} +0 -0
  79. /package/esm/{src/ApiTypes.d.ts → ApiTypes.d.ts} +0 -0
  80. /package/esm/{src/ApiTypes.js → ApiTypes.js} +0 -0
  81. /package/esm/{src/ApiUtils.d.ts → ApiUtils.d.ts} +0 -0
  82. /package/esm/{src/ApiUtils.js → ApiUtils.js} +0 -0
  83. /package/esm/{src/Endpoint.d.ts → Endpoint.d.ts} +0 -0
  84. /package/esm/{src/Endpoint.js → Endpoint.js} +0 -0
  85. /package/esm/{src/EndpointBuilder.d.ts → EndpointBuilder.d.ts} +0 -0
  86. /package/esm/{src/EndpointBuilder.js → EndpointBuilder.js} +0 -0
  87. /package/esm/{src/MockingTypes.d.ts → MockingTypes.d.ts} +0 -0
  88. /package/esm/{src/MockingTypes.js → MockingTypes.js} +0 -0
  89. /package/esm/{src/QueryHandling.d.ts → QueryHandling.d.ts} +0 -0
  90. /package/esm/{src/QueryHandling.js → QueryHandling.js} +0 -0
  91. /package/esm/{src/RequestConfig.d.ts → RequestConfig.d.ts} +0 -0
  92. /package/esm/{src/RequestConfig.js → RequestConfig.js} +0 -0
  93. /package/esm/{src/RequestContext.d.ts → RequestContext.d.ts} +0 -0
  94. /package/esm/{src/RequestContext.js → RequestContext.js} +0 -0
  95. /package/esm/{src/RequestError.d.ts → RequestError.d.ts} +0 -0
  96. /package/esm/{src/RequestError.js → RequestError.js} +0 -0
  97. /package/esm/{src/Requester.d.ts → Requester.d.ts} +0 -0
  98. /package/esm/{src/Requester.js → Requester.js} +0 -0
  99. /package/esm/{src/TextDecoding.d.ts → TextDecoding.d.ts} +0 -0
  100. /package/esm/{src/TextDecoding.js → TextDecoding.js} +0 -0
  101. /package/esm/{src/UtilTypes.d.ts → UtilTypes.d.ts} +0 -0
  102. /package/esm/{src/UtilTypes.js → UtilTypes.js} +0 -0
  103. /package/esm/{src/Utils.d.ts → Utils.d.ts} +0 -0
  104. /package/esm/{src/Utils.js → Utils.js} +0 -0
  105. /package/esm/{src/Validation.d.ts → Validation.d.ts} +0 -0
  106. /package/esm/{src/Validation.js → Validation.js} +0 -0
  107. /package/esm/{src/backend → backend}/AxiosRequestBackend.d.ts +0 -0
  108. /package/esm/{src/backend → backend}/AxiosRequestBackend.js +0 -0
  109. /package/esm/{src/backend → backend}/FetchRequestBackend.d.ts +0 -0
  110. /package/esm/{src/backend → backend}/FetchRequestBackend.js +0 -0
  111. /package/esm/{src/backend → backend}/MockRequestBackend.d.ts +0 -0
  112. /package/esm/{src/backend → backend}/MockRequestBackend.js +0 -0
  113. /package/esm/{src/backend → backend}/RequestBackend.d.ts +0 -0
  114. /package/esm/{src/backend → backend}/RequestBackend.js +0 -0
  115. /package/esm/{src/cache → cache}/CacheBackend.d.ts +0 -0
  116. /package/esm/{src/cache → cache}/CacheBackend.js +0 -0
  117. /package/esm/{src/cache → cache}/Caching.d.ts +0 -0
  118. /package/esm/{src/cache → cache}/Caching.js +0 -0
  119. /package/esm/{src/cache → cache}/LocalForageCacheBackend.d.ts +0 -0
  120. /package/esm/{src/cache → cache}/LocalForageCacheBackend.js +0 -0
  121. /package/esm/{src/cache → cache}/LocalStorageCacheBackend.d.ts +0 -0
  122. /package/esm/{src/cache → cache}/LocalStorageCacheBackend.js +0 -0
  123. /package/esm/{src/index.d.ts → index.d.ts} +0 -0
  124. /package/esm/{src/index.js → index.js} +0 -0
  125. /package/esm/{src/middleware → middleware}/CacheMiddleware.d.ts +0 -0
  126. /package/esm/{src/middleware → middleware}/CacheMiddleware.js +0 -0
  127. /package/esm/{src/middleware → middleware}/LoggingMiddleware.d.ts +0 -0
  128. /package/esm/{src/middleware → middleware}/LoggingMiddleware.js +0 -0
  129. /package/esm/{src/util → util}/retry/index.d.ts +0 -0
  130. /package/esm/{src/util → util}/retry/index.js +0 -0
  131. /package/esm/{src/util → util}/retry/lib/retry.d.ts +0 -0
  132. /package/esm/{src/util → util}/retry/lib/retry.js +0 -0
  133. /package/esm/{src/util → util}/retry/lib/retryOperation.d.ts +0 -0
  134. /package/esm/{src/util → util}/retry/lib/retryOperation.js +0 -0
package/bin/index.js CHANGED
@@ -274958,7 +274958,7 @@ ${source}`;
274958
274958
 
274959
274959
  // cli/index.ts
274960
274960
  program.name("api-def");
274961
- var packageJson = JSON.parse(fs2.readFileSync("package.json", "utf-8"));
274961
+ var packageJson = JSON.parse(fs2.readFileSync(path.resolve(__dirname, "../package.json"), "utf-8"));
274962
274962
  program.version(packageJson.version);
274963
274963
  program.command("generate").argument("<inPath>", "Path to the OpenAPI spec").argument("<outPath>", "Path to the output file").description("Generate an api-def from an OpenAPI spec").action(async (inPath, outPath) => {
274964
274964
  const resolvedInPath = path.resolve(inPath);
@@ -0,0 +1,16 @@
1
+ import { Api } from "../../Api";
2
+ declare const api: Api;
3
+ export declare const fetchRequiresToken: import("../..").Endpoint<any, undefined, undefined, undefined, import("../..").State, "/requires-token", import("../..").RawHeaders | undefined, import("../..").RawHeaders | undefined>;
4
+ export declare const postFormUrlEncoded: import("../..").Endpoint<string[], undefined, undefined, {
5
+ test: number;
6
+ b: string;
7
+ }, import("../..").State, "/send-data", import("../..").RawHeaders | undefined, import("../..").RawHeaders | undefined>;
8
+ export declare const postIdVerifStatus: import("../..").Endpoint<{
9
+ transactionStatus: any;
10
+ transactionId?: string;
11
+ verifPayload?: any;
12
+ }, undefined, undefined, {
13
+ validationService: 1;
14
+ forceReset: boolean;
15
+ }, import("../..").State, "/id-verif/verif-status", import("../..").RawHeaders | undefined, import("../..").RawHeaders | undefined>;
16
+ export default api;
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.postIdVerifStatus = exports.postFormUrlEncoded = exports.fetchRequiresToken = void 0;
4
+ var Api_1 = require("../../Api");
5
+ var ApiConstants_1 = require("../../ApiConstants");
6
+ var api = new Api_1.Api({
7
+ baseUrl: "example.com",
8
+ name: "Example API",
9
+ mocking: {
10
+ enabled: true,
11
+ },
12
+ });
13
+ exports.fetchRequiresToken = api.endpoint().build({
14
+ name: "Requires Token",
15
+ id: "fetchRequiresToken",
16
+ method: ApiConstants_1.RequestMethod.Get,
17
+ path: "/requires-token",
18
+ mocking: {
19
+ handler: function (req, res) {
20
+ if (!req.headers.token) {
21
+ return res.status(400).send({
22
+ code: "auth/invalid-token",
23
+ });
24
+ }
25
+ return res.status(200).send({ hello: true });
26
+ },
27
+ },
28
+ });
29
+ exports.postFormUrlEncoded = api
30
+ .endpoint()
31
+ .bodyOf()
32
+ .responseOf()
33
+ .build({
34
+ id: "sendFormUrlEncoded",
35
+ method: "post",
36
+ path: "/send-data",
37
+ config: {
38
+ headers: {
39
+ "Content-type": "application/x-www-form-urlencoded",
40
+ },
41
+ },
42
+ mocking: {
43
+ handler: function (req, res) {
44
+ return res.status(200).send([req.body.toString()]);
45
+ },
46
+ },
47
+ });
48
+ exports.postIdVerifStatus = api
49
+ .endpoint()
50
+ .bodyOf()
51
+ .responseOf()
52
+ .build({
53
+ id: "id-verif-status",
54
+ method: ApiConstants_1.RequestMethod.POST,
55
+ path: "/id-verif/verif-status",
56
+ responseType: "json",
57
+ config: {
58
+ acceptableStatus: [200],
59
+ retry: false, // outcome screen has it's own retry
60
+ },
61
+ mocking: {
62
+ handler: function (req, res) {
63
+ return res.status(200).send({ url: req.url });
64
+ },
65
+ },
66
+ });
67
+ exports.default = api;
@@ -0,0 +1,16 @@
1
+ import { Api } from "../../Api";
2
+ declare const api: Api;
3
+ export declare const fetchRequiresToken: import("../..").Endpoint<any, undefined, undefined, undefined, import("../..").State, "/requires-token", import("../..").RawHeaders | undefined, import("../..").RawHeaders | undefined>;
4
+ export declare const postFormUrlEncoded: import("../..").Endpoint<string[], undefined, undefined, {
5
+ test: number;
6
+ b: string;
7
+ }, import("../..").State, "/send-data", import("../..").RawHeaders | undefined, import("../..").RawHeaders | undefined>;
8
+ export declare const postIdVerifStatus: import("../..").Endpoint<{
9
+ transactionStatus: any;
10
+ transactionId?: string;
11
+ verifPayload?: any;
12
+ }, undefined, undefined, {
13
+ validationService: 1;
14
+ forceReset: boolean;
15
+ }, import("../..").State, "/id-verif/verif-status", import("../..").RawHeaders | undefined, import("../..").RawHeaders | undefined>;
16
+ export default api;
@@ -0,0 +1,64 @@
1
+ import { Api } from "../../Api";
2
+ import { RequestMethod } from "../../ApiConstants";
3
+ const api = new Api({
4
+ baseUrl: "example.com",
5
+ name: "Example API",
6
+ mocking: {
7
+ enabled: true,
8
+ },
9
+ });
10
+ export const fetchRequiresToken = api.endpoint().build({
11
+ name: "Requires Token",
12
+ id: "fetchRequiresToken",
13
+ method: RequestMethod.Get,
14
+ path: "/requires-token",
15
+ mocking: {
16
+ handler: (req, res) => {
17
+ if (!req.headers.token) {
18
+ return res.status(400).send({
19
+ code: "auth/invalid-token",
20
+ });
21
+ }
22
+ return res.status(200).send({ hello: true });
23
+ },
24
+ },
25
+ });
26
+ export const postFormUrlEncoded = api
27
+ .endpoint()
28
+ .bodyOf()
29
+ .responseOf()
30
+ .build({
31
+ id: "sendFormUrlEncoded",
32
+ method: "post",
33
+ path: "/send-data",
34
+ config: {
35
+ headers: {
36
+ "Content-type": "application/x-www-form-urlencoded",
37
+ },
38
+ },
39
+ mocking: {
40
+ handler: (req, res) => {
41
+ return res.status(200).send([req.body.toString()]);
42
+ },
43
+ },
44
+ });
45
+ export const postIdVerifStatus = api
46
+ .endpoint()
47
+ .bodyOf()
48
+ .responseOf()
49
+ .build({
50
+ id: "id-verif-status",
51
+ method: RequestMethod.POST,
52
+ path: "/id-verif/verif-status",
53
+ responseType: "json",
54
+ config: {
55
+ acceptableStatus: [200],
56
+ retry: false, // outcome screen has it's own retry
57
+ },
58
+ mocking: {
59
+ handler: (req, res) => {
60
+ return res.status(200).send({ url: req.url });
61
+ },
62
+ },
63
+ });
64
+ export default api;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "api-def",
3
- "version": "0.12.0-alpha.20",
3
+ "version": "0.12.0-alpha.22",
4
4
  "description": "Typed API definitions with middleware support",
5
5
  "main": "cjs/index.js",
6
6
  "types": "esm/index.d.ts",
@@ -1,4 +0,0 @@
1
- export interface OpenApiToSourceCodeOptions {
2
- openApiPath: string;
3
- }
4
- export declare const openApiToSourceCode: (options: OpenApiToSourceCodeOptions) => Promise<string>;
@@ -1,197 +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 = 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
- 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
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.openApiToSourceCode = void 0;
40
- var fs = require("node:fs");
41
- var openapi_core_1 = require("@redocly/openapi-core");
42
- // @ts-ignore
43
- var chalk_1 = require("chalk");
44
- var lodash_1 = require("lodash");
45
- var openapi_typescript_1 = require("openapi-typescript");
46
- // @ts-ignore
47
- var METHOD_COLORS = {
48
- get: chalk_1.default.green,
49
- post: chalk_1.default.blue,
50
- put: chalk_1.default.yellow,
51
- delete: chalk_1.default.red,
52
- patch: chalk_1.default.magenta,
53
- };
54
- var openApiToSourceCode = function (options) { return __awaiter(void 0, void 0, void 0, function () {
55
- var openApiPath, inContents, ast, bundleResults, _a, routes, server, extraTypes, source, types, extraTypesSource;
56
- var _b;
57
- return __generator(this, function (_c) {
58
- switch (_c.label) {
59
- case 0:
60
- openApiPath = options.openApiPath;
61
- inContents = fs.readFileSync(openApiPath, "utf-8");
62
- return [4 /*yield*/, (0, openapi_typescript_1.default)(inContents, {})];
63
- case 1:
64
- ast = _c.sent();
65
- _a = openapi_core_1.bundle;
66
- _b = {
67
- ref: openApiPath
68
- };
69
- return [4 /*yield*/, (0, openapi_core_1.createConfig)({})];
70
- case 2: return [4 /*yield*/, _a.apply(void 0, [(_b.config = _c.sent(),
71
- _b)])];
72
- case 3:
73
- bundleResults = _c.sent();
74
- routes = bundleResults.bundle.parsed.paths;
75
- server = bundleResults.bundle.parsed.servers[0];
76
- extraTypes = {};
77
- 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 mutable: true,\n});\n\n").concat(Object.entries(routes)
78
- .flatMap(function (_a) {
79
- var path = _a[0], route = _a[1];
80
- return Object.entries(route).map(function (_a) {
81
- var _b, _c, _d, _e;
82
- var method = _a[0], methodDef = _a[1];
83
- var id = methodDef.operationId;
84
- var responseStatuses = Object.keys(methodDef.responses);
85
- var successfulResponse = responseStatuses.filter(function (status) { return status.startsWith("2") || status.startsWith("3"); });
86
- var responseType = undefined;
87
- var responseTypes = [];
88
- for (var _i = 0, successfulResponse_1 = successfulResponse; _i < successfulResponse_1.length; _i++) {
89
- var status_1 = successfulResponse_1[_i];
90
- var response = methodDef.responses[status_1];
91
- if (response.$ref) {
92
- var responseDef = bundleResults.bundle.parsed.components.responses[response.$ref.split("/").pop()];
93
- for (var mediaType in responseDef.content) {
94
- var schema = responseDef.content[mediaType].schema;
95
- if (!responseType) {
96
- responseType = mediaType.split(";")[0];
97
- }
98
- if (schema === null || schema === void 0 ? void 0 : schema.$ref) {
99
- var name_1 = schema.$ref.split("/").pop();
100
- extraTypes["Response".concat(name_1)] = name_1;
101
- extraTypes[name_1] = "components[\"schemas\"][\"".concat(name_1, "\"]");
102
- responseTypes.push("Response".concat(name_1));
103
- }
104
- }
105
- }
106
- }
107
- var bodyTypes = [];
108
- if ((_b = methodDef.requestBody) === null || _b === void 0 ? void 0 : _b.$ref) {
109
- var name_2 = methodDef.requestBody.$ref.split("/").pop();
110
- extraTypes["Body".concat(name_2)] = name_2;
111
- extraTypes[name_2] = "components[\"schemas\"][\"".concat(name_2, "\"]");
112
- bodyTypes.push("Body".concat(name_2));
113
- }
114
- var queryTypes = [];
115
- if ((_c = methodDef.parameters) === null || _c === void 0 ? void 0 : _c.length) {
116
- var anyQueryParams = methodDef.parameters.some(function (param) {
117
- if (param.in === "query") {
118
- return true;
119
- }
120
- if (param.$ref) {
121
- var ref = param.$ref;
122
- var paramDef = bundleResults.bundle.parsed.components.parameters[ref.split("/").pop()];
123
- return paramDef.in === "query";
124
- }
125
- return false;
126
- });
127
- if (anyQueryParams) {
128
- extraTypes["Query".concat((0, lodash_1.upperFirst)(id))] = (0, lodash_1.upperFirst)(id);
129
- extraTypes[(0, lodash_1.upperFirst)(id)] = "operations[\"".concat(id, "\"][\"parameters\"][\"query\"]");
130
- queryTypes.push("Query".concat((0, lodash_1.upperFirst)(id)));
131
- }
132
- }
133
- var requestHeaderTypes = [];
134
- if ((_d = methodDef.parameters) === null || _d === void 0 ? void 0 : _d.length) {
135
- var anyHeaderParams = methodDef.parameters.some(function (param) {
136
- if (param.in === "header") {
137
- return true;
138
- }
139
- if (param.$ref) {
140
- var ref = param.$ref;
141
- var paramDef = bundleResults.bundle.parsed.components.parameters[ref.split("/").pop()];
142
- return paramDef.in === "header";
143
- }
144
- return false;
145
- });
146
- if (anyHeaderParams) {
147
- extraTypes["Headers".concat((0, lodash_1.upperFirst)(id))] = (0, lodash_1.upperFirst)(id);
148
- extraTypes[(0, lodash_1.upperFirst)(id)] = "NonNullable<operations[\"".concat(id, "\"][\"parameters\"][\"header\"]>");
149
- requestHeaderTypes.push("Headers".concat((0, lodash_1.upperFirst)(id)));
150
- }
151
- }
152
- var responseHeaderTypes = [];
153
- var pathParams = [];
154
- if ((_e = methodDef.parameters) === null || _e === void 0 ? void 0 : _e.length) {
155
- pathParams = methodDef.parameters.reduce(function (pathParams, param) {
156
- if (param.in === "path") {
157
- pathParams.push(param.name);
158
- }
159
- else if (param.$ref) {
160
- var ref = param.$ref;
161
- var paramDef = bundleResults.bundle.parsed.components.parameters[ref.split("/").pop()];
162
- if (paramDef.in === "path") {
163
- pathParams.push(paramDef.name);
164
- }
165
- }
166
- return pathParams;
167
- }, []);
168
- }
169
- /*
170
- const methodColor = METHOD_COLORS[method] || chalk.gray;
171
- console.log(`Generating ${methodColor(method.toUpperCase())} '${id}'`);
172
- */
173
- var endpointParts = [
174
- pathParams.length > 0 ? ".paramsOf<\"".concat(pathParams.join("|"), "\">()") : "",
175
- responseTypes.length > 0 ? ".responseOf<".concat(responseTypes.join("|"), ">()") : "",
176
- bodyTypes.length > 0 ? ".bodyOf<".concat(bodyTypes.join("|"), ">()") : "",
177
- queryTypes.length > 0 ? ".queryOf<".concat(queryTypes.join("|"), ">()") : "",
178
- requestHeaderTypes.length > 0 ? ".requestHeadersOf<".concat(requestHeaderTypes.join("|"), ">()") : "",
179
- responseHeaderTypes.length > 0 ? ".responseHeadersOf<".concat(responseHeaderTypes.join("|"), ">()") : "",
180
- ];
181
- return "export const ".concat(id, " = API.endpoint()\n").concat(endpointParts
182
- .filter(Boolean)
183
- .map(function (part) { return " ".concat(part); })
184
- .join("\n"), "\n .build({\n method: \"").concat(method, "\",\n path: \"").concat(path, "\",\n id: \"").concat(id, "\",\n });");
185
- });
186
- })
187
- .join("\n\n"), "\n\nexport default API;");
188
- types = (0, openapi_typescript_1.astToString)(ast);
189
- extraTypesSource = Object.keys(extraTypes)
190
- .sort()
191
- .map(function (key) { return "export type ".concat(key, " = ").concat(extraTypes[key], ";"); })
192
- .join("\n");
193
- return [2 /*return*/, "// Type Defs\n\n".concat(types, "\n").concat(extraTypesSource, "\n\n//API Def\n\n").concat(source)];
194
- }
195
- });
196
- }); };
197
- exports.openApiToSourceCode = openApiToSourceCode;
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
package/cjs/cli/index.js DELETED
@@ -1,73 +0,0 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
4
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5
- return new (P || (P = Promise))(function (resolve, reject) {
6
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
7
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
8
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
9
- step((generator = generator.apply(thisArg, _arguments || [])).next());
10
- });
11
- };
12
- var __generator = (this && this.__generator) || function (thisArg, body) {
13
- 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);
14
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
15
- function verb(n) { return function (v) { return step([n, v]); }; }
16
- function step(op) {
17
- if (f) throw new TypeError("Generator is already executing.");
18
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
19
- 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;
20
- if (y = 0, t) op = [op[0] & 2, t.value];
21
- switch (op[0]) {
22
- case 0: case 1: t = op; break;
23
- case 4: _.label++; return { value: op[1], done: false };
24
- case 5: _.label++; y = op[1]; op = [0]; continue;
25
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
26
- default:
27
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
28
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
29
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
30
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
31
- if (t[2]) _.ops.pop();
32
- _.trys.pop(); continue;
33
- }
34
- op = body.call(thisArg, _);
35
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
36
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
37
- }
38
- };
39
- Object.defineProperty(exports, "__esModule", { value: true });
40
- var fs = require("node:fs");
41
- var path = require("node:path");
42
- var commander_1 = require("commander");
43
- var OpenApiToSourceCode_1 = require("./OpenApiToSourceCode");
44
- commander_1.program.name("api-def");
45
- var packageJson = JSON.parse(fs.readFileSync("package.json", "utf-8"));
46
- commander_1.program.version(packageJson.version);
47
- commander_1.program
48
- .command("generate")
49
- .argument("<inPath>", "Path to the OpenAPI spec")
50
- .argument("<outPath>", "Path to the output file")
51
- .description("Generate an api-def from an OpenAPI spec")
52
- .action(function (inPath, outPath) { return __awaiter(void 0, void 0, void 0, function () {
53
- var resolvedInPath, output;
54
- return __generator(this, function (_a) {
55
- switch (_a.label) {
56
- case 0:
57
- resolvedInPath = path.resolve(inPath);
58
- if (!fs.existsSync(resolvedInPath)) {
59
- console.error("File not found: ".concat(resolvedInPath));
60
- process.exit(1);
61
- }
62
- return [4 /*yield*/, (0, OpenApiToSourceCode_1.openApiToSourceCode)({
63
- openApiPath: resolvedInPath,
64
- })];
65
- case 1:
66
- output = _a.sent();
67
- fs.writeFileSync(path.resolve(outPath), "// Generated by 'api-def' version ".concat(packageJson.version, "\n").concat(output));
68
- console.log("Generated api-def at ".concat(outPath));
69
- return [2 /*return*/];
70
- }
71
- });
72
- }); });
73
- commander_1.program.parse(process.argv);
@@ -1,4 +0,0 @@
1
- export interface OpenApiToSourceCodeOptions {
2
- openApiPath: string;
3
- }
4
- export declare const openApiToSourceCode: (options: OpenApiToSourceCodeOptions) => Promise<string>;
@@ -1,166 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import * as fs from "node:fs";
11
- import { bundle, createConfig } from "@redocly/openapi-core";
12
- // @ts-ignore
13
- import chalk from "chalk";
14
- import { upperFirst } from "lodash";
15
- import openapiTS, { astToString } from "openapi-typescript";
16
- // @ts-ignore
17
- const METHOD_COLORS = {
18
- get: chalk.green,
19
- post: chalk.blue,
20
- put: chalk.yellow,
21
- delete: chalk.red,
22
- patch: chalk.magenta,
23
- };
24
- export const openApiToSourceCode = (options) => __awaiter(void 0, void 0, void 0, function* () {
25
- const { openApiPath } = options;
26
- const inContents = fs.readFileSync(openApiPath, "utf-8");
27
- const ast = yield openapiTS(inContents, {});
28
- const bundleResults = yield bundle({
29
- ref: openApiPath,
30
- config: yield createConfig({}),
31
- });
32
- const routes = bundleResults.bundle.parsed.paths;
33
- // now generate the api-def API
34
- const server = bundleResults.bundle.parsed.servers[0];
35
- const extraTypes = {};
36
- const source = `import { Api } from "api-def";
37
-
38
- const API = new Api({
39
- name: "${bundleResults.bundle.parsed.info.title || "Generate Api"}",
40
- baseUrl: "${server.url}",
41
- mutable: true,
42
- });
43
-
44
- ${Object.entries(routes)
45
- .flatMap(([path, route]) => {
46
- return Object.entries(route).map(([method, methodDef]) => {
47
- var _a, _b, _c, _d;
48
- const id = methodDef.operationId;
49
- const responseStatuses = Object.keys(methodDef.responses);
50
- const successfulResponse = responseStatuses.filter((status) => status.startsWith("2") || status.startsWith("3"));
51
- let responseType = undefined;
52
- const responseTypes = [];
53
- for (const status of successfulResponse) {
54
- const response = methodDef.responses[status];
55
- if (response.$ref) {
56
- const responseDef = bundleResults.bundle.parsed.components.responses[response.$ref.split("/").pop()];
57
- for (const mediaType in responseDef.content) {
58
- const schema = responseDef.content[mediaType].schema;
59
- if (!responseType) {
60
- responseType = mediaType.split(";")[0];
61
- }
62
- if (schema === null || schema === void 0 ? void 0 : schema.$ref) {
63
- const name = schema.$ref.split("/").pop();
64
- extraTypes[`Response${name}`] = name;
65
- extraTypes[name] = `components["schemas"]["${name}"]`;
66
- responseTypes.push(`Response${name}`);
67
- }
68
- }
69
- }
70
- }
71
- const bodyTypes = [];
72
- if ((_a = methodDef.requestBody) === null || _a === void 0 ? void 0 : _a.$ref) {
73
- const name = methodDef.requestBody.$ref.split("/").pop();
74
- extraTypes[`Body${name}`] = name;
75
- extraTypes[name] = `components["schemas"]["${name}"]`;
76
- bodyTypes.push(`Body${name}`);
77
- }
78
- const queryTypes = [];
79
- if ((_b = methodDef.parameters) === null || _b === void 0 ? void 0 : _b.length) {
80
- const anyQueryParams = methodDef.parameters.some((param) => {
81
- if (param.in === "query") {
82
- return true;
83
- }
84
- if (param.$ref) {
85
- const ref = param.$ref;
86
- const paramDef = bundleResults.bundle.parsed.components.parameters[ref.split("/").pop()];
87
- return paramDef.in === "query";
88
- }
89
- return false;
90
- });
91
- if (anyQueryParams) {
92
- extraTypes[`Query${upperFirst(id)}`] = upperFirst(id);
93
- extraTypes[upperFirst(id)] = `operations["${id}"]["parameters"]["query"]`;
94
- queryTypes.push(`Query${upperFirst(id)}`);
95
- }
96
- }
97
- const requestHeaderTypes = [];
98
- if ((_c = methodDef.parameters) === null || _c === void 0 ? void 0 : _c.length) {
99
- const anyHeaderParams = methodDef.parameters.some((param) => {
100
- if (param.in === "header") {
101
- return true;
102
- }
103
- if (param.$ref) {
104
- const ref = param.$ref;
105
- const paramDef = bundleResults.bundle.parsed.components.parameters[ref.split("/").pop()];
106
- return paramDef.in === "header";
107
- }
108
- return false;
109
- });
110
- if (anyHeaderParams) {
111
- extraTypes[`Headers${upperFirst(id)}`] = upperFirst(id);
112
- extraTypes[upperFirst(id)] = `NonNullable<operations["${id}"]["parameters"]["header"]>`;
113
- requestHeaderTypes.push(`Headers${upperFirst(id)}`);
114
- }
115
- }
116
- const responseHeaderTypes = [];
117
- let pathParams = [];
118
- if ((_d = methodDef.parameters) === null || _d === void 0 ? void 0 : _d.length) {
119
- pathParams = methodDef.parameters.reduce((pathParams, param) => {
120
- if (param.in === "path") {
121
- pathParams.push(param.name);
122
- }
123
- else if (param.$ref) {
124
- const ref = param.$ref;
125
- const paramDef = bundleResults.bundle.parsed.components.parameters[ref.split("/").pop()];
126
- if (paramDef.in === "path") {
127
- pathParams.push(paramDef.name);
128
- }
129
- }
130
- return pathParams;
131
- }, []);
132
- }
133
- /*
134
- const methodColor = METHOD_COLORS[method] || chalk.gray;
135
- console.log(`Generating ${methodColor(method.toUpperCase())} '${id}'`);
136
- */
137
- const endpointParts = [
138
- pathParams.length > 0 ? `.paramsOf<"${pathParams.join("|")}">()` : "",
139
- responseTypes.length > 0 ? `.responseOf<${responseTypes.join("|")}>()` : "",
140
- bodyTypes.length > 0 ? `.bodyOf<${bodyTypes.join("|")}>()` : "",
141
- queryTypes.length > 0 ? `.queryOf<${queryTypes.join("|")}>()` : "",
142
- requestHeaderTypes.length > 0 ? `.requestHeadersOf<${requestHeaderTypes.join("|")}>()` : "",
143
- responseHeaderTypes.length > 0 ? `.responseHeadersOf<${responseHeaderTypes.join("|")}>()` : "",
144
- ];
145
- return `export const ${id} = API.endpoint()
146
- ${endpointParts
147
- .filter(Boolean)
148
- .map((part) => ` ${part}`)
149
- .join("\n")}
150
- .build({
151
- method: "${method}",
152
- path: "${path}",
153
- id: "${id}",
154
- });`;
155
- });
156
- })
157
- .join("\n\n")}
158
-
159
- export default API;`;
160
- const types = astToString(ast);
161
- const extraTypesSource = Object.keys(extraTypes)
162
- .sort()
163
- .map((key) => `export type ${key} = ${extraTypes[key]};`)
164
- .join("\n");
165
- return `// Type Defs\n\n${types}\n${extraTypesSource}\n\n//API Def\n\n${source}`;
166
- });
@@ -1,2 +0,0 @@
1
- #!/usr/bin/env node
2
- export {};
package/esm/cli/index.js DELETED
@@ -1,35 +0,0 @@
1
- #!/usr/bin/env node
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
- import * as fs from "node:fs";
12
- import * as path from "node:path";
13
- import { program } from "commander";
14
- import { openApiToSourceCode } from "./OpenApiToSourceCode";
15
- program.name("api-def");
16
- const packageJson = JSON.parse(fs.readFileSync("package.json", "utf-8"));
17
- program.version(packageJson.version);
18
- program
19
- .command("generate")
20
- .argument("<inPath>", "Path to the OpenAPI spec")
21
- .argument("<outPath>", "Path to the output file")
22
- .description("Generate an api-def from an OpenAPI spec")
23
- .action((inPath, outPath) => __awaiter(void 0, void 0, void 0, function* () {
24
- const resolvedInPath = path.resolve(inPath);
25
- if (!fs.existsSync(resolvedInPath)) {
26
- console.error(`File not found: ${resolvedInPath}`);
27
- process.exit(1);
28
- }
29
- const output = yield openApiToSourceCode({
30
- openApiPath: resolvedInPath,
31
- });
32
- fs.writeFileSync(path.resolve(outPath), `// Generated by 'api-def' version ${packageJson.version}\n${output}`);
33
- console.log(`Generated api-def at ${outPath}`);
34
- }));
35
- program.parse(process.argv);
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes