@sebspark/openapi-typegen 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +20 -0
- package/cli.mjs +30 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +568 -0
- package/package.json +34 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [2023] [SEB]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# `@sebspark/openapi-typegen`
|
|
2
|
+
|
|
3
|
+
Generates types and a routerdefinition from OpenAPI specs
|
|
4
|
+
|
|
5
|
+
## Usage
|
|
6
|
+
|
|
7
|
+
This is an example assuming that you have one schema, `marketdata.json`. The name
|
|
8
|
+
of this file will be used to generate Server and Client names.
|
|
9
|
+
|
|
10
|
+
This example can be found in [@sebspark/openapi-e2e](../packages/openapi-e2e)
|
|
11
|
+
|
|
12
|
+
```zsh
|
|
13
|
+
yarn openapi-typegen -i ./src/schemas/marketdata.json -o ./src/schemas/
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
The schema will export all types defined in the OpenAPI spec as well as:
|
|
17
|
+
|
|
18
|
+
`MarketdataAPIServer` - a server definition meant to be used with [@sebspark/openapi-express](./packages/openapi-express)
|
|
19
|
+
|
|
20
|
+
`MarketDataAPIClient` - a client definition meant to be used with [@sebspark/openapi-client](./packages/openapi-client)
|
package/cli.mjs
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import { generate } from '@sebspark/openapi-typegen'
|
|
4
|
+
import yargs from 'yargs'
|
|
5
|
+
import chalk from 'chalk'
|
|
6
|
+
import boxen from 'boxen'
|
|
7
|
+
|
|
8
|
+
const usage = chalk.magenta(
|
|
9
|
+
'\nUsage: @sebspark/typegen --input ./schemas --output ./dist \n' +
|
|
10
|
+
boxen(
|
|
11
|
+
chalk.green('\n' + 'Generates Typescript from OpenAPI schemas' + '\n'),
|
|
12
|
+
{
|
|
13
|
+
padding: 1,
|
|
14
|
+
borderColor: 'green',
|
|
15
|
+
dimBorder: true,
|
|
16
|
+
},
|
|
17
|
+
) +
|
|
18
|
+
'\n',
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
const argv = yargs(process.argv.slice(2))
|
|
22
|
+
.usage(usage)
|
|
23
|
+
.options({
|
|
24
|
+
input: { alias: 'i', type: 'string', demandOption: true },
|
|
25
|
+
output: { alias: 'o', type: 'string', demandOption: false },
|
|
26
|
+
})
|
|
27
|
+
.help()
|
|
28
|
+
.parseSync()
|
|
29
|
+
|
|
30
|
+
generate({ input: argv.input, output: argv.output })
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,568 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var src_exports = {};
|
|
32
|
+
__export(src_exports, {
|
|
33
|
+
generate: () => generate
|
|
34
|
+
});
|
|
35
|
+
module.exports = __toCommonJS(src_exports);
|
|
36
|
+
|
|
37
|
+
// src/generator.ts
|
|
38
|
+
var fastGlob = __toESM(require("fast-glob"));
|
|
39
|
+
var import_promises = require("fs/promises");
|
|
40
|
+
var import_path = require("path");
|
|
41
|
+
var import_yaml = require("yaml");
|
|
42
|
+
|
|
43
|
+
// src/shared/format.ts
|
|
44
|
+
var prettier = require("prettier");
|
|
45
|
+
var header = `/**
|
|
46
|
+
* This file was auto-generated.
|
|
47
|
+
* Do not make direct changes to the file.
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
import {
|
|
51
|
+
APIServerDefinition,
|
|
52
|
+
BaseClient,
|
|
53
|
+
GenericRouteHandler,
|
|
54
|
+
} from '@sebspark/openapi-core'
|
|
55
|
+
|
|
56
|
+
/* tslint:disable */
|
|
57
|
+
/* eslint-disable */`;
|
|
58
|
+
var formatFile = async (rows) => {
|
|
59
|
+
const withHeader = [header, ...rows];
|
|
60
|
+
const code = withHeader.join("\n\n");
|
|
61
|
+
const formatted = await prettier.format(code, {
|
|
62
|
+
parser: "typescript",
|
|
63
|
+
singleQuote: true,
|
|
64
|
+
semi: false
|
|
65
|
+
});
|
|
66
|
+
return formatted;
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
// src/shared/imports/format.ts
|
|
70
|
+
var formatImports = (imports) => {
|
|
71
|
+
const rows = [];
|
|
72
|
+
const importsMap = imports.reduce(
|
|
73
|
+
(map, it) => {
|
|
74
|
+
if (!map[it.file])
|
|
75
|
+
map[it.file] = /* @__PURE__ */ new Set();
|
|
76
|
+
map[it.file].add(it.type);
|
|
77
|
+
return map;
|
|
78
|
+
},
|
|
79
|
+
{}
|
|
80
|
+
);
|
|
81
|
+
Object.entries(importsMap).forEach(([file, types]) => {
|
|
82
|
+
rows.push(`import { ${Array.from(types).join(", ")} } from './${file}'`);
|
|
83
|
+
});
|
|
84
|
+
return rows;
|
|
85
|
+
};
|
|
86
|
+
|
|
87
|
+
// src/shared/schema/format.ts
|
|
88
|
+
var formatDocs = (description) => {
|
|
89
|
+
if (description) {
|
|
90
|
+
return `
|
|
91
|
+
/**
|
|
92
|
+
* ${description}
|
|
93
|
+
*/
|
|
94
|
+
`;
|
|
95
|
+
} else {
|
|
96
|
+
return "";
|
|
97
|
+
}
|
|
98
|
+
};
|
|
99
|
+
var formatTypeName = (name) => {
|
|
100
|
+
return name.replace(/[^a-zA-Z0-9_$]/g, "_");
|
|
101
|
+
};
|
|
102
|
+
var formatParsedType = (parsedType) => {
|
|
103
|
+
return `${formatDocs(parsedType.description)}export type ${parsedType.name} = ${parsedType.type}`;
|
|
104
|
+
};
|
|
105
|
+
var formatParsedTypes = (types) => {
|
|
106
|
+
const rows = [];
|
|
107
|
+
Object.values(types).forEach((values) => rows.push(formatParsedType(values)));
|
|
108
|
+
return rows;
|
|
109
|
+
};
|
|
110
|
+
var formatProperties = (properties) => {
|
|
111
|
+
const allProps = properties.map(({ name, required, value, description }) => {
|
|
112
|
+
return `${formatDocs(description)}'${name}'${required ? "" : "?"}: ${value}`;
|
|
113
|
+
}).join(`; `);
|
|
114
|
+
return `{${allProps}}`;
|
|
115
|
+
};
|
|
116
|
+
|
|
117
|
+
// src/shared/schema/parser.ts
|
|
118
|
+
var parseRefString = (refString, addImport) => {
|
|
119
|
+
const [file, rest] = refString.split("#");
|
|
120
|
+
const typeName = formatTypeName(rest.substring(rest.lastIndexOf("/") + 1));
|
|
121
|
+
if (file && file.length > 0) {
|
|
122
|
+
const [fileName] = file.split(".");
|
|
123
|
+
addImport({ file: fileName, type: typeName });
|
|
124
|
+
}
|
|
125
|
+
return typeName;
|
|
126
|
+
};
|
|
127
|
+
var parseTypes = (schemas) => {
|
|
128
|
+
const imports = [];
|
|
129
|
+
const types = Object.entries(schemas).map(([name, schema]) => {
|
|
130
|
+
const schemaObj = schema;
|
|
131
|
+
return {
|
|
132
|
+
name: formatTypeName(name),
|
|
133
|
+
type: generateFromSchemaObject(schemaObj, (importData) => {
|
|
134
|
+
imports.push(importData);
|
|
135
|
+
}),
|
|
136
|
+
description: schemaObj.description
|
|
137
|
+
};
|
|
138
|
+
});
|
|
139
|
+
return [types, imports];
|
|
140
|
+
};
|
|
141
|
+
var guessType = (schema) => {
|
|
142
|
+
if (schema.type) {
|
|
143
|
+
return schema.type;
|
|
144
|
+
} else if (schema.enum) {
|
|
145
|
+
return "string";
|
|
146
|
+
} else if (schema.properties) {
|
|
147
|
+
return "object";
|
|
148
|
+
} else {
|
|
149
|
+
return void 0;
|
|
150
|
+
}
|
|
151
|
+
};
|
|
152
|
+
var generateFromSchemaObject = (schema, addImport) => {
|
|
153
|
+
if ("$ref" in schema) {
|
|
154
|
+
const { $ref } = schema;
|
|
155
|
+
return parseRefString($ref, addImport);
|
|
156
|
+
}
|
|
157
|
+
const type = guessType(schema);
|
|
158
|
+
let schemaString = "";
|
|
159
|
+
if (type) {
|
|
160
|
+
if (type === "object") {
|
|
161
|
+
schemaString = generateObject(schema, addImport);
|
|
162
|
+
} else if (type === "array") {
|
|
163
|
+
const arrayType = generateFromSchemaObject(schema.items, addImport);
|
|
164
|
+
if (arrayType && arrayType.length) {
|
|
165
|
+
schemaString = `(${arrayType})[]`;
|
|
166
|
+
} else {
|
|
167
|
+
schemaString = "[]";
|
|
168
|
+
}
|
|
169
|
+
} else {
|
|
170
|
+
switch (type) {
|
|
171
|
+
case "integer":
|
|
172
|
+
schemaString = "number";
|
|
173
|
+
break;
|
|
174
|
+
case "string": {
|
|
175
|
+
if (schema.format === "date-time" || schema.format === "date") {
|
|
176
|
+
schemaString = "Date";
|
|
177
|
+
} else if (schema.enum) {
|
|
178
|
+
schemaString = schema.enum.map((it) => `'${it}'`).join(" | ");
|
|
179
|
+
} else {
|
|
180
|
+
schemaString = "string";
|
|
181
|
+
}
|
|
182
|
+
break;
|
|
183
|
+
}
|
|
184
|
+
default:
|
|
185
|
+
schemaString = type;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (schema.allOf) {
|
|
190
|
+
const allOfString = schema.allOf.map((it) => generateFromSchemaObject(it, addImport)).join(" & ");
|
|
191
|
+
if (allOfString.length > 0) {
|
|
192
|
+
schemaString = schemaString + " & " + allOfString;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (schema.anyOf) {
|
|
196
|
+
const anyOfString = schema.anyOf.map((it) => generateFromSchemaObject(it, addImport)).map((it) => `Partial<${it}>`).join(" & ");
|
|
197
|
+
if (anyOfString.length > 0) {
|
|
198
|
+
schemaString = schemaString + " & " + anyOfString;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
if (schema.oneOf) {
|
|
202
|
+
const oneOfString = schema.oneOf.map((it) => generateFromSchemaObject(it, addImport)).join(" | ");
|
|
203
|
+
if (oneOfString.length > 0) {
|
|
204
|
+
schemaString = schemaString + " & (" + oneOfString + ")";
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
if (!schemaString || !schemaString.length) {
|
|
208
|
+
schemaString = "string";
|
|
209
|
+
}
|
|
210
|
+
return schemaString;
|
|
211
|
+
};
|
|
212
|
+
var generateObject = (schema, addImport) => {
|
|
213
|
+
const requiredFields = schema.required ?? [];
|
|
214
|
+
const properties = Object.entries(
|
|
215
|
+
schema.properties ?? []
|
|
216
|
+
).map(([name, schema2]) => ({
|
|
217
|
+
[name]: {
|
|
218
|
+
name,
|
|
219
|
+
value: generateFromSchemaObject(schema2, addImport),
|
|
220
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
221
|
+
description: schema2["description"],
|
|
222
|
+
required: requiredFields.includes(name)
|
|
223
|
+
}
|
|
224
|
+
})).reduce((acc, current) => {
|
|
225
|
+
for (const key in current) {
|
|
226
|
+
acc[key] = current[key];
|
|
227
|
+
}
|
|
228
|
+
return acc;
|
|
229
|
+
}, {});
|
|
230
|
+
return formatProperties(Object.values(properties));
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
// src/shared/schema/generator.ts
|
|
234
|
+
var generateSchemas = (components) => {
|
|
235
|
+
const [types, imports] = parseTypes(components.components.schemas);
|
|
236
|
+
return formatFile([...formatImports(imports), ...formatParsedTypes(types)]);
|
|
237
|
+
};
|
|
238
|
+
|
|
239
|
+
// src/format.ts
|
|
240
|
+
var formatTitle = (title) => {
|
|
241
|
+
return title.replace(/ /g, "").replace(/[^a-zA-Z0-9]/g, "_");
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
// src/openapi/format.ts
|
|
245
|
+
var import_change_case = require("change-case");
|
|
246
|
+
var formatRoutes = (title, routes) => {
|
|
247
|
+
const formattedTitle = formatTitle(title);
|
|
248
|
+
const routeDefinitions = generateRouteDefinitions(routes);
|
|
249
|
+
const server = generateServerAPI(formattedTitle, routeDefinitions);
|
|
250
|
+
const client = generateClientAPI(formattedTitle, routeDefinitions);
|
|
251
|
+
return server.concat(client);
|
|
252
|
+
};
|
|
253
|
+
var generateServerAPI = (name, routes) => {
|
|
254
|
+
const map = generateServerType(routes);
|
|
255
|
+
const rows = [];
|
|
256
|
+
rows.push(
|
|
257
|
+
`export type ${name}Server = APIServerDefinition & {
|
|
258
|
+
${Object.entries(map).map(
|
|
259
|
+
([url, methods]) => ` '${url}': {
|
|
260
|
+
${Object.entries(methods).map(
|
|
261
|
+
([method, definition]) => ` '${method}': {
|
|
262
|
+
handler: (${serializeArgs(definition.args)}) => Promise<[${definition.response.code}, ${definition.response.type}]>
|
|
263
|
+
pre?: GenericRouteHandler | GenericRouteHandler[]
|
|
264
|
+
}`
|
|
265
|
+
).join("\n")}
|
|
266
|
+
},`
|
|
267
|
+
).join("\n")}
|
|
268
|
+
}
|
|
269
|
+
`
|
|
270
|
+
);
|
|
271
|
+
return rows;
|
|
272
|
+
};
|
|
273
|
+
var generateClientAPI = (name, routes) => {
|
|
274
|
+
const code = [];
|
|
275
|
+
const clientHandlers = [];
|
|
276
|
+
const verbMap = generateClientType(routes);
|
|
277
|
+
Object.entries(verbMap).forEach(([verb, definitions]) => {
|
|
278
|
+
const type = `${name}Client${(0, import_change_case.pascalCase)(verb)}`;
|
|
279
|
+
clientHandlers.push(`${verb}: ${type}`);
|
|
280
|
+
code.push(`type ${type} = {`);
|
|
281
|
+
definitions.forEach((def) => {
|
|
282
|
+
const args = serializeArgs(def.args);
|
|
283
|
+
const argsString = args ? `, ${args}` : "";
|
|
284
|
+
code.push(
|
|
285
|
+
`(url: '${def.url}'${argsString}): Promise<${def.response.type}>`
|
|
286
|
+
);
|
|
287
|
+
});
|
|
288
|
+
code.push("}");
|
|
289
|
+
});
|
|
290
|
+
code.push(
|
|
291
|
+
`export type ${name}Client = Pick<BaseClient, ${Object.keys(verbMap).map((v) => `'${v}'`).join(" | ")}> & {`
|
|
292
|
+
);
|
|
293
|
+
code.push(clientHandlers.join("\n"));
|
|
294
|
+
code.push("}");
|
|
295
|
+
return code;
|
|
296
|
+
};
|
|
297
|
+
var generateRouteDefinitions = (routes) => routes.map((route) => ({
|
|
298
|
+
method: route.method.toLowerCase(),
|
|
299
|
+
response: route.response,
|
|
300
|
+
url: route.url,
|
|
301
|
+
args: parseArgs(route)
|
|
302
|
+
}));
|
|
303
|
+
var generateClientType = (routes) => routes.reduce((router, routeDefinition) => {
|
|
304
|
+
if (!router[routeDefinition.method])
|
|
305
|
+
router[routeDefinition.method] = [];
|
|
306
|
+
router[routeDefinition.method].push(routeDefinition);
|
|
307
|
+
return router;
|
|
308
|
+
}, {});
|
|
309
|
+
var generateServerType = (routes) => routes.reduce((router, routeDefinition) => {
|
|
310
|
+
const route = router[routeDefinition.url] || {};
|
|
311
|
+
route[routeDefinition.method] = routeDefinition;
|
|
312
|
+
router[routeDefinition.url] = route;
|
|
313
|
+
return router;
|
|
314
|
+
}, {});
|
|
315
|
+
var parseArgs = (route) => {
|
|
316
|
+
const args = {};
|
|
317
|
+
if (route.requestParams !== "never")
|
|
318
|
+
args.params = route.requestParams;
|
|
319
|
+
if (route.requestQuery !== "never")
|
|
320
|
+
args.query = route.requestQuery;
|
|
321
|
+
if (route.requestHeaders !== "never")
|
|
322
|
+
args.headers = route.requestHeaders;
|
|
323
|
+
if (route.requestBody !== "never")
|
|
324
|
+
args.body = route.requestBody;
|
|
325
|
+
if (args.headers || args.params || args.query || args.body)
|
|
326
|
+
return args;
|
|
327
|
+
};
|
|
328
|
+
var serializeArgs = (args) => {
|
|
329
|
+
if (!args)
|
|
330
|
+
return "";
|
|
331
|
+
const argsString = Object.entries(args).map(([key, value]) => `${key}: ${value}`).join(",");
|
|
332
|
+
return `args: {${argsString}}`;
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
// src/openapi/parser.ts
|
|
336
|
+
var parseReferencableObjects = (name, record) => {
|
|
337
|
+
const objects = {};
|
|
338
|
+
if (record) {
|
|
339
|
+
const allParameters = Object.entries(record);
|
|
340
|
+
const referenceParameters = allParameters.filter((it) => "$ref" in it[1]).map((it) => [it[0], it[1]]);
|
|
341
|
+
const normalParameters = allParameters.filter((it) => !("$ref" in it[1])).map((it) => [it[0], it[1]]);
|
|
342
|
+
normalParameters.forEach((it) => {
|
|
343
|
+
objects[`#/components/${name}/${it[0]}`] = it[1];
|
|
344
|
+
});
|
|
345
|
+
referenceParameters.forEach((it) => {
|
|
346
|
+
objects[`#/components/${name}/${it[0]}`] = objects[it[1].$ref];
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
return objects;
|
|
350
|
+
};
|
|
351
|
+
|
|
352
|
+
// src/openapi/paths.ts
|
|
353
|
+
var pathGenerator = (globalParameters) => {
|
|
354
|
+
const expressifyPath = (path) => path.replace(/{/g, ":").replace(/}/g, "");
|
|
355
|
+
const parseResponse = (response, addImports) => {
|
|
356
|
+
var _a, _b;
|
|
357
|
+
const schema = (_b = (_a = response.content) == null ? void 0 : _a["application/json"]) == null ? void 0 : _b.schema;
|
|
358
|
+
if (!schema)
|
|
359
|
+
return "";
|
|
360
|
+
return generateFromSchemaObject(schema, addImports);
|
|
361
|
+
};
|
|
362
|
+
const getType = (param, addImport) => {
|
|
363
|
+
if (param.type)
|
|
364
|
+
param.type;
|
|
365
|
+
if (param.schema) {
|
|
366
|
+
if ("type" in param.schema)
|
|
367
|
+
return generateFromSchemaObject(param.schema, addImport);
|
|
368
|
+
}
|
|
369
|
+
return "any";
|
|
370
|
+
};
|
|
371
|
+
const propName = (name) => {
|
|
372
|
+
if (name.indexOf("-") === -1)
|
|
373
|
+
return name;
|
|
374
|
+
return `'${name}'`;
|
|
375
|
+
};
|
|
376
|
+
const generateProps = (params, filter, addImport) => {
|
|
377
|
+
const props = params.map((it) => {
|
|
378
|
+
if ("$ref" in it) {
|
|
379
|
+
return globalParameters[it.$ref];
|
|
380
|
+
} else {
|
|
381
|
+
return it;
|
|
382
|
+
}
|
|
383
|
+
}).filter((p) => p.in === filter).map(
|
|
384
|
+
(p) => `${propName(p.name)}${p.required ? "" : "?"}: ${getType(
|
|
385
|
+
p,
|
|
386
|
+
addImport
|
|
387
|
+
)}`
|
|
388
|
+
);
|
|
389
|
+
if (props.length)
|
|
390
|
+
return `{${props.join(", ")}}`;
|
|
391
|
+
return "never";
|
|
392
|
+
};
|
|
393
|
+
const generateBody = (body, addImport) => {
|
|
394
|
+
var _a, _b;
|
|
395
|
+
if ((_a = body == null ? void 0 : body.content) == null ? void 0 : _a["application/json"]) {
|
|
396
|
+
const content = (_b = body.content["application/json"]) == null ? void 0 : _b.schema;
|
|
397
|
+
return generateFromSchemaObject(content, addImport);
|
|
398
|
+
}
|
|
399
|
+
return "never";
|
|
400
|
+
};
|
|
401
|
+
const generateResponses = (responses, addImport, errors = false) => {
|
|
402
|
+
const responseTypes = Object.entries(responses).map(([strCode, response]) => {
|
|
403
|
+
const code = parseInt(strCode, 10);
|
|
404
|
+
if (code >= 400 !== errors)
|
|
405
|
+
return;
|
|
406
|
+
if ("$ref" in response) {
|
|
407
|
+
return {
|
|
408
|
+
code,
|
|
409
|
+
type: parseRefString(response.$ref, addImport)
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
return {
|
|
413
|
+
code,
|
|
414
|
+
type: parseResponse(response, addImport) || "void"
|
|
415
|
+
};
|
|
416
|
+
}).filter((r) => r);
|
|
417
|
+
return responseTypes;
|
|
418
|
+
};
|
|
419
|
+
const generateRoutes = (path, item, addImport) => {
|
|
420
|
+
const verbs = ["get", "post", "put", "patch", "delete"];
|
|
421
|
+
const routes = verbs.map((verb) => {
|
|
422
|
+
const operation = item[verb];
|
|
423
|
+
if (!operation)
|
|
424
|
+
return void 0;
|
|
425
|
+
const route = {
|
|
426
|
+
url: expressifyPath(path),
|
|
427
|
+
method: verb,
|
|
428
|
+
requestBody: generateBody(
|
|
429
|
+
operation.requestBody,
|
|
430
|
+
addImport
|
|
431
|
+
),
|
|
432
|
+
requestParams: generateProps(
|
|
433
|
+
operation.parameters || [],
|
|
434
|
+
"path",
|
|
435
|
+
addImport
|
|
436
|
+
),
|
|
437
|
+
requestQuery: generateProps(
|
|
438
|
+
operation.parameters || [],
|
|
439
|
+
"query",
|
|
440
|
+
addImport
|
|
441
|
+
),
|
|
442
|
+
requestHeaders: generateProps(
|
|
443
|
+
operation.parameters || [],
|
|
444
|
+
"header",
|
|
445
|
+
addImport
|
|
446
|
+
),
|
|
447
|
+
response: generateResponses(operation.responses, addImport)[0],
|
|
448
|
+
errorResponses: generateResponses(
|
|
449
|
+
operation.responses,
|
|
450
|
+
addImport,
|
|
451
|
+
true
|
|
452
|
+
)
|
|
453
|
+
};
|
|
454
|
+
return route;
|
|
455
|
+
}).filter((r) => r);
|
|
456
|
+
return routes;
|
|
457
|
+
};
|
|
458
|
+
const generatePaths = (paths) => {
|
|
459
|
+
const imports = [];
|
|
460
|
+
const routes = Object.entries(paths).flatMap(
|
|
461
|
+
([path, item]) => generateRoutes(path, item, (imp) => imports.push(imp))
|
|
462
|
+
);
|
|
463
|
+
return [routes, imports];
|
|
464
|
+
};
|
|
465
|
+
return {
|
|
466
|
+
generate: generatePaths
|
|
467
|
+
};
|
|
468
|
+
};
|
|
469
|
+
|
|
470
|
+
// src/openapi/generator.ts
|
|
471
|
+
var generateData = (schema) => {
|
|
472
|
+
var _a, _b, _c;
|
|
473
|
+
const [types, importsFromTypes] = ((_a = schema.components) == null ? void 0 : _a.schemas) ? parseTypes(schema.components.schemas) : [[], []];
|
|
474
|
+
const parameters = parseReferencableObjects(
|
|
475
|
+
"parameters",
|
|
476
|
+
((_b = schema.components) == null ? void 0 : _b.parameters) || {}
|
|
477
|
+
);
|
|
478
|
+
const [paths, importsFromPaths] = pathGenerator(parameters).generate(
|
|
479
|
+
schema.paths || {}
|
|
480
|
+
);
|
|
481
|
+
return {
|
|
482
|
+
types,
|
|
483
|
+
paths,
|
|
484
|
+
imports: importsFromPaths.concat(importsFromTypes),
|
|
485
|
+
title: ((_c = schema.info) == null ? void 0 : _c.title) ?? ""
|
|
486
|
+
};
|
|
487
|
+
};
|
|
488
|
+
var generateFormattedString = async ({
|
|
489
|
+
title,
|
|
490
|
+
imports,
|
|
491
|
+
paths,
|
|
492
|
+
types
|
|
493
|
+
}) => {
|
|
494
|
+
const formattedImports = formatImports(imports);
|
|
495
|
+
const formattedTypes = formatParsedTypes(types);
|
|
496
|
+
const formattedRoutes = formatRoutes(title, paths);
|
|
497
|
+
const formatted = await formatFile([
|
|
498
|
+
...formattedImports,
|
|
499
|
+
...formattedTypes,
|
|
500
|
+
...formattedRoutes
|
|
501
|
+
]);
|
|
502
|
+
return formatted;
|
|
503
|
+
};
|
|
504
|
+
var generateOpenApi = async (schema) => {
|
|
505
|
+
const data = generateData(schema);
|
|
506
|
+
const formatted = await generateFormattedString(data);
|
|
507
|
+
return formatted;
|
|
508
|
+
};
|
|
509
|
+
|
|
510
|
+
// src/generator.ts
|
|
511
|
+
var getSchemas = async (input) => {
|
|
512
|
+
const schemas = {
|
|
513
|
+
openApi: {},
|
|
514
|
+
// asyncApi: {},
|
|
515
|
+
sharedTypes: {}
|
|
516
|
+
};
|
|
517
|
+
const files = fastGlob.sync(input, { globstar: true, dot: true });
|
|
518
|
+
for (const file of files) {
|
|
519
|
+
const { name } = (0, import_path.parse)(file);
|
|
520
|
+
const content = await (0, import_promises.readFile)(file, "utf-8");
|
|
521
|
+
const parsed = file.endsWith(".yaml") || file.endsWith(".yml") ? (0, import_yaml.parse)(content) : JSON.parse(content);
|
|
522
|
+
if (parsed["asyncapi"]) {
|
|
523
|
+
} else if (parsed["openapi"]) {
|
|
524
|
+
schemas.openApi[name] = parsed;
|
|
525
|
+
} else if (parsed["components"]) {
|
|
526
|
+
schemas.sharedTypes[name] = parsed;
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
return schemas;
|
|
530
|
+
};
|
|
531
|
+
var generate = async ({
|
|
532
|
+
input,
|
|
533
|
+
output
|
|
534
|
+
}) => {
|
|
535
|
+
if (!input)
|
|
536
|
+
throw new Error("You need to supply at least one schema");
|
|
537
|
+
const schemas = await getSchemas(input);
|
|
538
|
+
const generatedOpenApi = await Promise.all(
|
|
539
|
+
Object.entries(schemas.openApi).map(async ([name, schema]) => ({
|
|
540
|
+
name,
|
|
541
|
+
schema: await generateOpenApi(schema)
|
|
542
|
+
}))
|
|
543
|
+
);
|
|
544
|
+
const generatedSharedTypes = await Promise.all(
|
|
545
|
+
Object.entries(schemas.sharedTypes).map(async ([name, schema]) => ({
|
|
546
|
+
name,
|
|
547
|
+
schema: await generateSchemas(schema)
|
|
548
|
+
}))
|
|
549
|
+
);
|
|
550
|
+
if (!output)
|
|
551
|
+
return generatedOpenApi.concat(generatedSharedTypes).map(
|
|
552
|
+
({ name, schema }) => `/**
|
|
553
|
+
* ${name}
|
|
554
|
+
*/
|
|
555
|
+
${schema}
|
|
556
|
+
`
|
|
557
|
+
).join("\n");
|
|
558
|
+
await (0, import_promises.mkdir)(output, { recursive: true });
|
|
559
|
+
for (const { name, schema } of generatedOpenApi.concat(generatedSharedTypes)) {
|
|
560
|
+
const path = (0, import_path.join)(output, `${name}.ts`);
|
|
561
|
+
await (0, import_promises.writeFile)(path, schema, "utf-8");
|
|
562
|
+
}
|
|
563
|
+
return;
|
|
564
|
+
};
|
|
565
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
566
|
+
0 && (module.exports = {
|
|
567
|
+
generate
|
|
568
|
+
});
|
package/package.json
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@sebspark/openapi-typegen",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"main": "dist/index.js",
|
|
6
|
+
"types": "dist/index.d.ts",
|
|
7
|
+
"bin": {
|
|
8
|
+
"openapi-typegen": "./cli.mjs"
|
|
9
|
+
},
|
|
10
|
+
"files": [
|
|
11
|
+
"dist",
|
|
12
|
+
"cli.mjs"
|
|
13
|
+
],
|
|
14
|
+
"scripts": {
|
|
15
|
+
"build": "tsup-node src/index.ts src/cli.ts --format cjs --dts",
|
|
16
|
+
"dev": "tsc --watch --noEmit",
|
|
17
|
+
"lint": "eslint \"src/**/*.ts*\"",
|
|
18
|
+
"test": "vitest --passWithNoTests --coverage",
|
|
19
|
+
"typecheck": "vitest typecheck --passWithNoTests"
|
|
20
|
+
},
|
|
21
|
+
"devDependencies": {
|
|
22
|
+
"@types/yargs": "17.0.30",
|
|
23
|
+
"tsconfig": "*"
|
|
24
|
+
},
|
|
25
|
+
"dependencies": {
|
|
26
|
+
"@sebspark/openapi-core": "*",
|
|
27
|
+
"boxen": "<6",
|
|
28
|
+
"chalk": "<5",
|
|
29
|
+
"change-case": "4.1.2",
|
|
30
|
+
"prettier": "3.0.3",
|
|
31
|
+
"yargs": "17.7.2",
|
|
32
|
+
"yarn": "1.22.19"
|
|
33
|
+
}
|
|
34
|
+
}
|