hono-openapi 0.2.0 → 0.2.1
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 +21 -21
- package/README.md +240 -240
- package/arktype.cjs.d.ts +1 -1
- package/arktype.cjs.js +11 -1
- package/arktype.esm.d.ts +1 -1
- package/arktype.esm.js +8 -1
- package/index.cjs.d.ts +1 -1
- package/index.cjs.js +13 -1
- package/index.cjs2.js +9 -0
- package/index.esm.d.ts +1 -1
- package/index.esm.js +10 -1
- package/index.esm2.js +7 -0
- package/package.json +5 -3
- package/src/toOpenAPISchema/const.d.ts +1 -0
- package/src/toOpenAPISchema/index.d.ts +5 -0
- package/src/toOpenAPISchema/types.d.ts +18 -0
- package/typebox.cjs.d.ts +1 -1
- package/typebox.cjs.js +12 -1
- package/typebox.esm.d.ts +1 -1
- package/typebox.esm.js +9 -1
- package/utils.cjs.js +6 -1
- package/utils.esm.js +3 -1
- package/valibot.cjs.d.ts +1 -1
- package/valibot.cjs.js +13 -1
- package/valibot.esm.d.ts +1 -1
- package/valibot.esm.js +10 -1
- package/zod.cjs.d.ts +1 -1
- package/zod.cjs.js +10 -1
- package/zod.esm.d.ts +1 -1
- package/zod.esm.js +7 -1
package/LICENSE
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
|
-
MIT License
|
|
2
|
-
|
|
3
|
-
Copyright (c) 2024 Rhinobase
|
|
4
|
-
|
|
5
|
-
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
-
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
-
in the Software without restriction, including without limitation the rights
|
|
8
|
-
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
-
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
-
furnished to do so, subject to the following conditions:
|
|
11
|
-
|
|
12
|
-
The above copyright notice and this permission notice shall be included in all
|
|
13
|
-
copies or substantial portions of the Software.
|
|
14
|
-
|
|
15
|
-
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
-
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
-
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
-
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
-
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
-
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
-
SOFTWARE.
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2024 Rhinobase
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,240 +1,240 @@
|
|
|
1
|
-
# 📜 Hono OpenAPI
|
|
2
|
-
|
|
3
|
-
[](https://npmjs.org/package/hono-openapi "View this project on NPM")
|
|
4
|
-
[](https://www.npmjs.com/package/hono-openapi)
|
|
5
|
-
[](LICENSE)
|
|
6
|
-
|
|
7
|
-
This can automatically generate the OpenAPI specification for the Hono API using your validation schema, which can be used to generate client libraries, documentation, and more.
|
|
8
|
-
|
|
9
|
-
Supported Validation Libraries:
|
|
10
|
-
|
|
11
|
-
- [x] [Zod](https://zod.dev/)
|
|
12
|
-
- [x] [Valibot](https://valibot.dev/)
|
|
13
|
-
- [x] [ArkType](https://arktype.io/)
|
|
14
|
-
- [x] [TypeBox](https://github.com/sinclairzx81/typebox)
|
|
15
|
-
|
|
16
|
-
> [!Note]
|
|
17
|
-
> This package is still in development and your feedback is highly appreciated. If you have any suggestions or issues, please let us know by creating an issue on GitHub.
|
|
18
|
-
|
|
19
|
-
## Usage
|
|
20
|
-
|
|
21
|
-
### Installation
|
|
22
|
-
|
|
23
|
-
You can install the package using favorite package manager.
|
|
24
|
-
|
|
25
|
-
#### For Zod
|
|
26
|
-
|
|
27
|
-
```bash
|
|
28
|
-
pnpm add hono-openapi @hono/zod-validator zod zod-openapi
|
|
29
|
-
```
|
|
30
|
-
|
|
31
|
-
#### For Valibot
|
|
32
|
-
|
|
33
|
-
```bash
|
|
34
|
-
pnpm add hono-openapi @hono/valibot-validator valibot @valibot/to-json-schema
|
|
35
|
-
```
|
|
36
|
-
|
|
37
|
-
#### For ArkType
|
|
38
|
-
|
|
39
|
-
```bash
|
|
40
|
-
pnpm add hono-openapi @hono/arktype-validator arktype
|
|
41
|
-
```
|
|
42
|
-
|
|
43
|
-
#### For TypeBox
|
|
44
|
-
|
|
45
|
-
```bash
|
|
46
|
-
pnpm add hono-openapi @hono/typebox-validator @sinclair/typebox"
|
|
47
|
-
```
|
|
48
|
-
|
|
49
|
-
### Basic Usage
|
|
50
|
-
|
|
51
|
-
#### Setting up your application
|
|
52
|
-
|
|
53
|
-
First, define your schemas, here is an example using Zod:
|
|
54
|
-
|
|
55
|
-
```ts
|
|
56
|
-
import z from "zod";
|
|
57
|
-
|
|
58
|
-
// For extending the Zod schema with OpenAPI properties
|
|
59
|
-
import "zod-openapi/extend";
|
|
60
|
-
|
|
61
|
-
const querySchema = z
|
|
62
|
-
.object({
|
|
63
|
-
name: z.string().optional().openapi({ example: "Steven" }),
|
|
64
|
-
})
|
|
65
|
-
.openapi({ ref: "Query" });
|
|
66
|
-
|
|
67
|
-
const responseSchema = z.string().openapi({ example: "Hello Steven!" });
|
|
68
|
-
```
|
|
69
|
-
|
|
70
|
-
Extending the Zod schema with OpenAPI properties is optional, but it will help you generate the OpenAPI specification. You can learn more about it here - [https://github.com/samchungy/zod-openapi](https://github.com/samchungy/zod-openapi).
|
|
71
|
-
|
|
72
|
-
> [!Tip]
|
|
73
|
-
> The `querySchema` schema will be registered as "#/components/schemas/Query" refs in the OpenAPI document. If you want to register the schema as referenced components, use .openapi() method.
|
|
74
|
-
|
|
75
|
-
Next, create your route -
|
|
76
|
-
|
|
77
|
-
```ts
|
|
78
|
-
import { Hono } from "hono";
|
|
79
|
-
import { describeRoute } from "hono-openapi";
|
|
80
|
-
import { resolver, validator as zValidator } from "hono-openapi/zod";
|
|
81
|
-
|
|
82
|
-
const app = new Hono();
|
|
83
|
-
|
|
84
|
-
app.get(
|
|
85
|
-
"/",
|
|
86
|
-
describeRoute({
|
|
87
|
-
description: "Say hello to the user",
|
|
88
|
-
responses: {
|
|
89
|
-
200: {
|
|
90
|
-
description: "Successful greeting response",
|
|
91
|
-
content: {
|
|
92
|
-
"text/plain": {
|
|
93
|
-
schema: resolver(responseSchema),
|
|
94
|
-
},
|
|
95
|
-
},
|
|
96
|
-
},
|
|
97
|
-
},
|
|
98
|
-
}),
|
|
99
|
-
zValidator("query", querySchema),
|
|
100
|
-
(c) => {
|
|
101
|
-
const query = c.req.valid("query");
|
|
102
|
-
return c.text(`Hello ${query?.name ?? "Hono"}!`);
|
|
103
|
-
}
|
|
104
|
-
);
|
|
105
|
-
```
|
|
106
|
-
|
|
107
|
-
You might be wondering why are we importing `validator` from `hono-openapi/zod` instead of `@hono/zod-validator` and as `zValidator`? This is because `hono-openapi` provides a wrapper around the `@hono/zod-validator` to make it easier to use. The idea is if you are already using `@hono/zod-validator` to validate your schemas, you can easily switch to `hono-openapi` without changing much of your code.
|
|
108
|
-
|
|
109
|
-
Finally, generate the OpenAPI specification -
|
|
110
|
-
|
|
111
|
-
```ts
|
|
112
|
-
app.get(
|
|
113
|
-
"/openapi",
|
|
114
|
-
openAPISpecs(app, {
|
|
115
|
-
documentation: {
|
|
116
|
-
info: {
|
|
117
|
-
title: "Hono",
|
|
118
|
-
version: "1.0.0",
|
|
119
|
-
description: "API for greeting users",
|
|
120
|
-
},
|
|
121
|
-
servers: [
|
|
122
|
-
{
|
|
123
|
-
url: "http://localhost:3000",
|
|
124
|
-
description: "Local server",
|
|
125
|
-
},
|
|
126
|
-
],
|
|
127
|
-
},
|
|
128
|
-
})
|
|
129
|
-
);
|
|
130
|
-
```
|
|
131
|
-
|
|
132
|
-
Now, you can access the OpenAPI specification by visiting `http://localhost:3000/openapi`, and you can use this specification to generate client libraries, documentation, and more. Some tools that I used to generate documentation are -
|
|
133
|
-
|
|
134
|
-
- [Swagger UI](https://github.com/honojs/middleware/tree/main/packages/swagger-ui)
|
|
135
|
-
- [Scalar](https://github.com/scalar/scalar/tree/main/packages/hono-api-reference)
|
|
136
|
-
|
|
137
|
-
##### Scalar Example
|
|
138
|
-
|
|
139
|
-
```ts
|
|
140
|
-
app.get(
|
|
141
|
-
"/docs",
|
|
142
|
-
apiReference({
|
|
143
|
-
theme: "saturn",
|
|
144
|
-
spec: {
|
|
145
|
-
url: "/openapi",
|
|
146
|
-
},
|
|
147
|
-
})
|
|
148
|
-
);
|
|
149
|
-
```
|
|
150
|
-
|
|
151
|
-
And that's it! You have successfully generated the OpenAPI specification for your Hono API.
|
|
152
|
-
|
|
153
|
-
### Advanced Usage
|
|
154
|
-
|
|
155
|
-
#### Adding Security Definitions
|
|
156
|
-
|
|
157
|
-
You can add security definitions to your OpenAPI specification by using the `security` property in the `openAPISpecs` function.
|
|
158
|
-
|
|
159
|
-
```ts
|
|
160
|
-
app.get(
|
|
161
|
-
"/openapi",
|
|
162
|
-
openAPISpecs(appRouter, {
|
|
163
|
-
documentation: {
|
|
164
|
-
info: {
|
|
165
|
-
title: "Rhinobase Cloud",
|
|
166
|
-
version: "1.0.0",
|
|
167
|
-
description: "API Documentation",
|
|
168
|
-
},
|
|
169
|
-
components: {
|
|
170
|
-
securitySchemes: {
|
|
171
|
-
bearerAuth: {
|
|
172
|
-
type: "http",
|
|
173
|
-
scheme: "bearer",
|
|
174
|
-
bearerFormat: "JWT",
|
|
175
|
-
},
|
|
176
|
-
},
|
|
177
|
-
},
|
|
178
|
-
security: [
|
|
179
|
-
{
|
|
180
|
-
bearerAuth: [],
|
|
181
|
-
},
|
|
182
|
-
],
|
|
183
|
-
servers: [
|
|
184
|
-
{
|
|
185
|
-
url: "http://localhost:3004",
|
|
186
|
-
description: "Local server",
|
|
187
|
-
},
|
|
188
|
-
],
|
|
189
|
-
},
|
|
190
|
-
})
|
|
191
|
-
);
|
|
192
|
-
```
|
|
193
|
-
|
|
194
|
-
#### Conditionaly Hiding Routes
|
|
195
|
-
|
|
196
|
-
You can conditionally hide routes from the OpenAPI specification by using the `hide` property in the `describeRoute` function.
|
|
197
|
-
|
|
198
|
-
```ts
|
|
199
|
-
app.get(
|
|
200
|
-
"/",
|
|
201
|
-
describeRoute({
|
|
202
|
-
// ...
|
|
203
|
-
hide: process.env.NODE_ENV === "production",
|
|
204
|
-
}),
|
|
205
|
-
(c) => {
|
|
206
|
-
return c.text("Private Route");
|
|
207
|
-
}
|
|
208
|
-
);
|
|
209
|
-
```
|
|
210
|
-
|
|
211
|
-
#### Validating Responses
|
|
212
|
-
|
|
213
|
-
> [!Warning]
|
|
214
|
-
> Experimental
|
|
215
|
-
|
|
216
|
-
You can validate the responses using the `validateResponse` property in the `describeRoute` function. This will validate the response against the schema and return an error if the response is invalid.
|
|
217
|
-
|
|
218
|
-
```ts
|
|
219
|
-
app.get(
|
|
220
|
-
"/",
|
|
221
|
-
describeRoute({
|
|
222
|
-
// ...
|
|
223
|
-
validateResponse: process.env.NODE_ENV === "development",
|
|
224
|
-
}),
|
|
225
|
-
(c) => {
|
|
226
|
-
return c.text("Private Route");
|
|
227
|
-
}
|
|
228
|
-
);
|
|
229
|
-
```
|
|
230
|
-
|
|
231
|
-
## Contributing
|
|
232
|
-
|
|
233
|
-
We would love to have more contributors involved!
|
|
234
|
-
|
|
235
|
-
To get started, please read our [Contributing Guide](https://github.com/rhinobase/hono-openapi/blob/main/CONTRIBUTING.md).
|
|
236
|
-
|
|
237
|
-
## Credits
|
|
238
|
-
|
|
239
|
-
- The idea for this project was inspired by [ElysiaJS](https://elysiajs.com/) and their amazing work on generating [OpenAPI](https://elysiajs.com/recipe/openapi.html) specifications.
|
|
240
|
-
- This project would not have been possible without the work of [Sam Chung](https://github.com/samchungy) and his [Zod OpenAPI](https://github.com/samchungy/zod-openapi) package.
|
|
1
|
+
# 📜 Hono OpenAPI
|
|
2
|
+
|
|
3
|
+
[](https://npmjs.org/package/hono-openapi "View this project on NPM")
|
|
4
|
+
[](https://www.npmjs.com/package/hono-openapi)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
|
|
7
|
+
This can automatically generate the OpenAPI specification for the Hono API using your validation schema, which can be used to generate client libraries, documentation, and more.
|
|
8
|
+
|
|
9
|
+
Supported Validation Libraries:
|
|
10
|
+
|
|
11
|
+
- [x] [Zod](https://zod.dev/)
|
|
12
|
+
- [x] [Valibot](https://valibot.dev/)
|
|
13
|
+
- [x] [ArkType](https://arktype.io/)
|
|
14
|
+
- [x] [TypeBox](https://github.com/sinclairzx81/typebox)
|
|
15
|
+
|
|
16
|
+
> [!Note]
|
|
17
|
+
> This package is still in development and your feedback is highly appreciated. If you have any suggestions or issues, please let us know by creating an issue on GitHub.
|
|
18
|
+
|
|
19
|
+
## Usage
|
|
20
|
+
|
|
21
|
+
### Installation
|
|
22
|
+
|
|
23
|
+
You can install the package using favorite package manager.
|
|
24
|
+
|
|
25
|
+
#### For Zod
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pnpm add hono-openapi @hono/zod-validator zod zod-openapi
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
#### For Valibot
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pnpm add hono-openapi @hono/valibot-validator valibot @valibot/to-json-schema
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
#### For ArkType
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
pnpm add hono-openapi @hono/arktype-validator arktype
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
#### For TypeBox
|
|
44
|
+
|
|
45
|
+
```bash
|
|
46
|
+
pnpm add hono-openapi @hono/typebox-validator @sinclair/typebox"
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### Basic Usage
|
|
50
|
+
|
|
51
|
+
#### Setting up your application
|
|
52
|
+
|
|
53
|
+
First, define your schemas, here is an example using Zod:
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
import z from "zod";
|
|
57
|
+
|
|
58
|
+
// For extending the Zod schema with OpenAPI properties
|
|
59
|
+
import "zod-openapi/extend";
|
|
60
|
+
|
|
61
|
+
const querySchema = z
|
|
62
|
+
.object({
|
|
63
|
+
name: z.string().optional().openapi({ example: "Steven" }),
|
|
64
|
+
})
|
|
65
|
+
.openapi({ ref: "Query" });
|
|
66
|
+
|
|
67
|
+
const responseSchema = z.string().openapi({ example: "Hello Steven!" });
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Extending the Zod schema with OpenAPI properties is optional, but it will help you generate the OpenAPI specification. You can learn more about it here - [https://github.com/samchungy/zod-openapi](https://github.com/samchungy/zod-openapi).
|
|
71
|
+
|
|
72
|
+
> [!Tip]
|
|
73
|
+
> The `querySchema` schema will be registered as "#/components/schemas/Query" refs in the OpenAPI document. If you want to register the schema as referenced components, use .openapi() method.
|
|
74
|
+
|
|
75
|
+
Next, create your route -
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
import { Hono } from "hono";
|
|
79
|
+
import { describeRoute } from "hono-openapi";
|
|
80
|
+
import { resolver, validator as zValidator } from "hono-openapi/zod";
|
|
81
|
+
|
|
82
|
+
const app = new Hono();
|
|
83
|
+
|
|
84
|
+
app.get(
|
|
85
|
+
"/",
|
|
86
|
+
describeRoute({
|
|
87
|
+
description: "Say hello to the user",
|
|
88
|
+
responses: {
|
|
89
|
+
200: {
|
|
90
|
+
description: "Successful greeting response",
|
|
91
|
+
content: {
|
|
92
|
+
"text/plain": {
|
|
93
|
+
schema: resolver(responseSchema),
|
|
94
|
+
},
|
|
95
|
+
},
|
|
96
|
+
},
|
|
97
|
+
},
|
|
98
|
+
}),
|
|
99
|
+
zValidator("query", querySchema),
|
|
100
|
+
(c) => {
|
|
101
|
+
const query = c.req.valid("query");
|
|
102
|
+
return c.text(`Hello ${query?.name ?? "Hono"}!`);
|
|
103
|
+
}
|
|
104
|
+
);
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
You might be wondering why are we importing `validator` from `hono-openapi/zod` instead of `@hono/zod-validator` and as `zValidator`? This is because `hono-openapi` provides a wrapper around the `@hono/zod-validator` to make it easier to use. The idea is if you are already using `@hono/zod-validator` to validate your schemas, you can easily switch to `hono-openapi` without changing much of your code.
|
|
108
|
+
|
|
109
|
+
Finally, generate the OpenAPI specification -
|
|
110
|
+
|
|
111
|
+
```ts
|
|
112
|
+
app.get(
|
|
113
|
+
"/openapi",
|
|
114
|
+
openAPISpecs(app, {
|
|
115
|
+
documentation: {
|
|
116
|
+
info: {
|
|
117
|
+
title: "Hono",
|
|
118
|
+
version: "1.0.0",
|
|
119
|
+
description: "API for greeting users",
|
|
120
|
+
},
|
|
121
|
+
servers: [
|
|
122
|
+
{
|
|
123
|
+
url: "http://localhost:3000",
|
|
124
|
+
description: "Local server",
|
|
125
|
+
},
|
|
126
|
+
],
|
|
127
|
+
},
|
|
128
|
+
})
|
|
129
|
+
);
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Now, you can access the OpenAPI specification by visiting `http://localhost:3000/openapi`, and you can use this specification to generate client libraries, documentation, and more. Some tools that I used to generate documentation are -
|
|
133
|
+
|
|
134
|
+
- [Swagger UI](https://github.com/honojs/middleware/tree/main/packages/swagger-ui)
|
|
135
|
+
- [Scalar](https://github.com/scalar/scalar/tree/main/packages/hono-api-reference)
|
|
136
|
+
|
|
137
|
+
##### Scalar Example
|
|
138
|
+
|
|
139
|
+
```ts
|
|
140
|
+
app.get(
|
|
141
|
+
"/docs",
|
|
142
|
+
apiReference({
|
|
143
|
+
theme: "saturn",
|
|
144
|
+
spec: {
|
|
145
|
+
url: "/openapi",
|
|
146
|
+
},
|
|
147
|
+
})
|
|
148
|
+
);
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
And that's it! You have successfully generated the OpenAPI specification for your Hono API.
|
|
152
|
+
|
|
153
|
+
### Advanced Usage
|
|
154
|
+
|
|
155
|
+
#### Adding Security Definitions
|
|
156
|
+
|
|
157
|
+
You can add security definitions to your OpenAPI specification by using the `security` property in the `openAPISpecs` function.
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
app.get(
|
|
161
|
+
"/openapi",
|
|
162
|
+
openAPISpecs(appRouter, {
|
|
163
|
+
documentation: {
|
|
164
|
+
info: {
|
|
165
|
+
title: "Rhinobase Cloud",
|
|
166
|
+
version: "1.0.0",
|
|
167
|
+
description: "API Documentation",
|
|
168
|
+
},
|
|
169
|
+
components: {
|
|
170
|
+
securitySchemes: {
|
|
171
|
+
bearerAuth: {
|
|
172
|
+
type: "http",
|
|
173
|
+
scheme: "bearer",
|
|
174
|
+
bearerFormat: "JWT",
|
|
175
|
+
},
|
|
176
|
+
},
|
|
177
|
+
},
|
|
178
|
+
security: [
|
|
179
|
+
{
|
|
180
|
+
bearerAuth: [],
|
|
181
|
+
},
|
|
182
|
+
],
|
|
183
|
+
servers: [
|
|
184
|
+
{
|
|
185
|
+
url: "http://localhost:3004",
|
|
186
|
+
description: "Local server",
|
|
187
|
+
},
|
|
188
|
+
],
|
|
189
|
+
},
|
|
190
|
+
})
|
|
191
|
+
);
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
#### Conditionaly Hiding Routes
|
|
195
|
+
|
|
196
|
+
You can conditionally hide routes from the OpenAPI specification by using the `hide` property in the `describeRoute` function.
|
|
197
|
+
|
|
198
|
+
```ts
|
|
199
|
+
app.get(
|
|
200
|
+
"/",
|
|
201
|
+
describeRoute({
|
|
202
|
+
// ...
|
|
203
|
+
hide: process.env.NODE_ENV === "production",
|
|
204
|
+
}),
|
|
205
|
+
(c) => {
|
|
206
|
+
return c.text("Private Route");
|
|
207
|
+
}
|
|
208
|
+
);
|
|
209
|
+
```
|
|
210
|
+
|
|
211
|
+
#### Validating Responses
|
|
212
|
+
|
|
213
|
+
> [!Warning]
|
|
214
|
+
> Experimental
|
|
215
|
+
|
|
216
|
+
You can validate the responses using the `validateResponse` property in the `describeRoute` function. This will validate the response against the schema and return an error if the response is invalid.
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
app.get(
|
|
220
|
+
"/",
|
|
221
|
+
describeRoute({
|
|
222
|
+
// ...
|
|
223
|
+
validateResponse: process.env.NODE_ENV === "development",
|
|
224
|
+
}),
|
|
225
|
+
(c) => {
|
|
226
|
+
return c.text("Private Route");
|
|
227
|
+
}
|
|
228
|
+
);
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
## Contributing
|
|
232
|
+
|
|
233
|
+
We would love to have more contributors involved!
|
|
234
|
+
|
|
235
|
+
To get started, please read our [Contributing Guide](https://github.com/rhinobase/hono-openapi/blob/main/CONTRIBUTING.md).
|
|
236
|
+
|
|
237
|
+
## Credits
|
|
238
|
+
|
|
239
|
+
- The idea for this project was inspired by [ElysiaJS](https://elysiajs.com/) and their amazing work on generating [OpenAPI](https://elysiajs.com/recipe/openapi.html) specifications.
|
|
240
|
+
- This project would not have been possible without the work of [Sam Chung](https://github.com/samchungy) and his [Zod OpenAPI](https://github.com/samchungy/zod-openapi) package.
|
package/arktype.cjs.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export * from "./src
|
|
1
|
+
export * from "./src/arktype";
|
package/arktype.cjs.js
CHANGED
|
@@ -1 +1,11 @@
|
|
|
1
|
-
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var arktypeValidator = require('@hono/arktype-validator');
|
|
4
|
+
var index = require('./index.cjs2.js');
|
|
5
|
+
var utils = require('./utils.cjs.js');
|
|
6
|
+
require('json-schema-walker');
|
|
7
|
+
|
|
8
|
+
function resolver(schema){return {builder:async options=>({schema:await index.convert(schema.toJsonSchema())}),validator:value=>{schema(value);}}}function validator(target,schema,hook){const middleware=arktypeValidator.arktypeValidator(target,schema,hook);return Object.assign(middleware,{[utils.uniqueSymbol]:{resolver:async config=>utils.generateValidatorDocs(target,await resolver(schema).builder(config))}})}
|
|
9
|
+
|
|
10
|
+
exports.resolver = resolver;
|
|
11
|
+
exports.validator = validator;
|
package/arktype.esm.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export * from "./src
|
|
1
|
+
export * from "./src/arktype";
|
package/arktype.esm.js
CHANGED
|
@@ -1 +1,8 @@
|
|
|
1
|
-
import{arktypeValidator
|
|
1
|
+
import { arktypeValidator } from '@hono/arktype-validator';
|
|
2
|
+
import { c as convert } from './index.esm2.js';
|
|
3
|
+
import { u as uniqueSymbol, g as generateValidatorDocs } from './utils.esm.js';
|
|
4
|
+
import 'json-schema-walker';
|
|
5
|
+
|
|
6
|
+
function resolver(schema){return {builder:async options=>({schema:await convert(schema.toJsonSchema())}),validator:value=>{schema(value);}}}function validator(target,schema,hook){const middleware=arktypeValidator(target,schema,hook);return Object.assign(middleware,{[uniqueSymbol]:{resolver:async config=>generateValidatorDocs(target,await resolver(schema).builder(config))}})}
|
|
7
|
+
|
|
8
|
+
export { resolver, validator };
|
package/index.cjs.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export * from "./src
|
|
1
|
+
export * from "./src/index";
|
package/index.cjs.js
CHANGED
|
@@ -1 +1,13 @@
|
|
|
1
|
-
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var httpException = require('hono/http-exception');
|
|
4
|
+
var utils = require('./utils.cjs.js');
|
|
5
|
+
|
|
6
|
+
function describeRoute(specs){const middleware=async(c,next)=>{await next();if(specs.validateResponse&&specs.responses){const status=c.res.status;const contentType=c.res.headers.get("content-type");if(status&&contentType){const response=specs.responses[status];if(response&&"content"in response&&response.content){const content=response.content[contentType];if(content?.schema&&"validator"in content.schema){try{await content.schema.validator(c.res.body);}catch(error){throw new httpException.HTTPException(400,{message:"Response validation failed!"})}}}}}};return Object.assign(middleware,{[utils.uniqueSymbol]:{resolver:async config=>{const docs={...specs};let components={};if(docs.responses){for(const key of Object.keys(docs.responses)){const response=docs.responses[key];if(response&&!("content"in response))continue;for(const contentKey of Object.keys(response.content??{})){const raw=response.content?.[contentKey];if(!raw)continue;if(raw.schema&&"builder"in raw.schema){const result=await raw.schema.builder(config);raw.schema=result.schema;if(result.components){components={...components,...result.components};}}}}}return {docs,components}}}})}
|
|
7
|
+
|
|
8
|
+
const ALLOWED_METHODS=["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE"];const toOpenAPIPath=path=>path.split("/").map(x=>{let tmp=x;if(tmp.startsWith(":")){tmp=tmp.slice(1,tmp.length);if(tmp.endsWith("?"))tmp=tmp.slice(0,-1);tmp=`{${tmp}}`;}return tmp}).join("/");const capitalize=word=>word.charAt(0).toUpperCase()+word.slice(1);const generateOperationId=(method,paths)=>{let operationId=method;if(paths==="/")return `${operationId}Index`;for(const path of paths.split("/")){if(path.charCodeAt(0)===123){operationId+=`By${capitalize(path.slice(1,-1))}`;}else {operationId+=capitalize(path);}}return operationId};function registerSchemaPath({path,method:_method,data,schema}){path=toOpenAPIPath(path);const method=_method.toLowerCase();schema[path]={...schema[path]?schema[path]:{},[method]:{responses:{},...schema[path]?.[method]??{},operationId:generateOperationId(method,path),...data}};}function filterPaths(paths,{excludeStaticFile=true,exclude=[]}){const newPaths={};for(const[key,value]of Object.entries(paths)){if(!exclude.some(x=>{if(typeof x==="string")return key===x;return x.test(key)})&&!key.includes("*")&&(excludeStaticFile?!key.includes("."):true)){for(const method of Object.keys(value)){const schema=value[method];if(key.includes("{")){if(!schema.parameters)schema.parameters=[];schema.parameters=[...key.split("/").filter(x=>x.startsWith("{")&&!schema.parameters.find(params=>params.in==="path"&¶ms.name===x.slice(1,x.length-1))).map(x=>({schema:{type:"string"},in:"path",name:x.slice(1,x.length-1),required:true})),...schema.parameters];}if(!schema.responses)schema.responses={200:{}};}newPaths[key]=value;}}return newPaths}
|
|
9
|
+
|
|
10
|
+
function openAPISpecs(hono,{documentation={},excludeStaticFile=true,exclude=[],excludeMethods=["OPTIONS"],excludeTags=[]}={documentation:{},excludeStaticFile:true,exclude:[],excludeMethods:["OPTIONS"],excludeTags:[]}){const config={version:"3.1.0",components:{}};const schema={};let specs=null;return async c=>{if(specs)return c.json(specs);for(const route of hono.routes){if(!(utils.uniqueSymbol in route.handler))continue;if(excludeMethods.includes(route.method))continue;if(ALLOWED_METHODS.includes(route.method)===false&&route.method!=="ALL")continue;const{resolver,metadata={}}=route.handler[utils.uniqueSymbol];const{docs,components}=await resolver({...config,...metadata});config.components={...config.components,...components??{}};if(route.method==="ALL"){for(const method of ALLOWED_METHODS){registerSchemaPath({path:route.path,data:docs,method,schema});}}else {registerSchemaPath({method:route.method,path:route.path,data:docs,schema});}}for(const path in schema){for(const method in schema[path]){const valueOrFunc=schema[path][method]?.hide;if(valueOrFunc&&(typeof valueOrFunc==="boolean"?valueOrFunc:valueOrFunc(c))){delete schema[path][method];}}}specs={openapi:config.version,...{...documentation,tags:documentation.tags?.filter(tag=>!excludeTags?.includes(tag?.name)),info:{title:"Hono Documentation",description:"Development documentation",version:"0.0.0",...documentation.info},paths:{...filterPaths(schema,{excludeStaticFile,exclude:Array.isArray(exclude)?exclude:[exclude]}),...documentation.paths},components:{...documentation.components,schemas:{...config.components,...documentation.components?.schemas}}}};return c.json(specs)}}
|
|
11
|
+
|
|
12
|
+
exports.describeRoute = describeRoute;
|
|
13
|
+
exports.openAPISpecs = openAPISpecs;
|
package/index.cjs2.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var jsonSchemaWalker = require('json-schema-walker');
|
|
4
|
+
|
|
5
|
+
const allowedKeywords=["$ref","definitions","title","multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","enum","type","not","allOf","oneOf","anyOf","items","properties","additionalProperties","description","format","default","nullable","discriminator","readOnly","writeOnly","example","externalDocs","deprecated","xml"];
|
|
6
|
+
|
|
7
|
+
let InvalidTypeError=class InvalidTypeError extends Error{constructor(message){super(message);this.name="InvalidTypeError";this.message=message;}};const oasExtensionPrefix="x-";const handleDefinition=async(def,schema)=>{if(typeof def!=="object"){return def}const type=def.type;if(type){const walker=new jsonSchemaWalker.Walker;await walker.loadSchema({definitions:schema["definitions"]||[],...def,$schema:schema["$schema"]},{dereference:true,cloneSchema:true,dereferenceOptions:{dereference:{circular:"ignore"}}});await walker.walk(convertSchema,walker.vocabularies.DRAFT_07);if("definitions"in walker.rootSchema){walker.rootSchema.definitions=undefined;}return walker.rootSchema}if(Array.isArray(def)){const typeArr=def;const hasNull=typeArr.includes("null");if(hasNull){const actualTypes=typeArr.filter(l=>l!=="null");return {type:actualTypes.length===1?actualTypes[0]:actualTypes,nullable:true}}}return def};const convert=async(schema,options)=>{const walker=new jsonSchemaWalker.Walker;await walker.loadSchema(schema,options);await walker.walk(convertSchema,walker.vocabularies.DRAFT_07);const rootSchema=walker.rootSchema;if(rootSchema?.definitions){for(const defName in rootSchema.definitions){const def=rootSchema.definitions[defName];rootSchema.definitions[defName]=await handleDefinition(def,schema);}}return rootSchema};function stripIllegalKeywords(schema){if(typeof schema!=="object"){return schema}schema["$schema"]=undefined;schema["$id"]=undefined;if("id"in schema){schema["id"]=undefined;}return schema}function convertSchema(schema){if(!schema){return schema}schema=stripIllegalKeywords(schema);schema=convertTypes(schema);schema=rewriteConst(schema);schema=convertDependencies(schema);schema=convertNullable(schema);schema=rewriteIfThenElse(schema);schema=rewriteExclusiveMinMax(schema);schema=convertExamples(schema);if(typeof schema["patternProperties"]==="object"){schema=convertPatternProperties(schema);}if(schema.type==="array"&&typeof schema.items==="undefined"){schema.items={};}schema=convertIllegalKeywordsAsExtensions(schema);return schema}const validTypes=new Set(["null","boolean","object","array","number","string","integer"]);function validateType(type){if(typeof type==="object"&&!Array.isArray(type)){if(type.$ref){return}if(type.properties){return}}const types=Array.isArray(type)?type:[type];for(const type of types){if(type&&!validTypes.has(type))throw new InvalidTypeError(`Type "${type}" is not a valid type`)}}function convertDependencies(schema){const deps=schema.dependencies;if(typeof deps!=="object"){return schema}schema.dependencies=undefined;if(!Array.isArray(schema.allOf)){schema.allOf=[];}for(const key in deps){const foo={oneOf:[{not:{required:[key]}},{required:[key,deps[key]].flat()}]};schema.allOf.push(foo);}return schema}function convertNullable(schema){for(const key of ["oneOf","anyOf"]){const schemas=schema[key];if(!schemas)continue;if(!Array.isArray(schemas)){return schema}const hasNullable=schemas.some(item=>item.type==="null");if(!hasNullable){return schema}const filtered=schemas.filter(l=>l.type!=="null");for(const schemaEntry of filtered){schemaEntry.nullable=true;}schema[key]=filtered;}return schema}function convertTypes(schema){if(typeof schema!=="object"){return schema}if(schema.type===undefined){return schema}validateType(schema.type);if(Array.isArray(schema.type)){if(schema.type.includes("null")){schema.nullable=true;}const typesWithoutNull=schema.type.filter(type=>type!=="null");if(typesWithoutNull.length===0){schema.type=undefined;}else if(typesWithoutNull.length===1){schema.type=typesWithoutNull[0];}else {schema.type=undefined;schema.anyOf=typesWithoutNull.map(type=>({type}));}}else if(schema.type==="null"){schema.type=undefined;schema.nullable=true;}return schema}function convertPatternProperties(schema){schema["x-patternProperties"]=schema.patternProperties;schema.patternProperties=undefined;schema.additionalProperties??=true;return schema}function convertIllegalKeywordsAsExtensions(schema){const keys=Object.keys(schema);for(const keyword of keys){if(!keyword.startsWith(oasExtensionPrefix)&&!allowedKeywords.includes(keyword)){const key=`${oasExtensionPrefix}${keyword}`;schema[key]=schema[keyword];schema[keyword]=undefined;}}return schema}function convertExamples(schema){if(schema["examples"]&&Array.isArray(schema["examples"])){schema["example"]=schema["examples"][0];schema["examples"]=undefined;}return schema}function rewriteConst(schema){if(Object.hasOwnProperty.call(schema,"const")){schema.enum=[schema.const];schema.const=undefined;}return schema}function rewriteIfThenElse(schema){if(typeof schema!=="object"){return schema}if("if"in schema&&schema.if&&schema.then){schema.oneOf=[{allOf:[schema.if,schema.then].filter(Boolean)},{allOf:[{not:schema.if},schema.else].filter(Boolean)}];schema.if=undefined;schema.then=undefined;schema.else=undefined;}return schema}function rewriteExclusiveMinMax(schema){if(typeof schema.exclusiveMaximum==="number"){schema.maximum=schema.exclusiveMaximum;schema.exclusiveMaximum=true;}if(typeof schema.exclusiveMinimum==="number"){schema.minimum=schema.exclusiveMinimum;schema.exclusiveMinimum=true;}return schema}
|
|
8
|
+
|
|
9
|
+
exports.convert = convert;
|
package/index.esm.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export * from "./src
|
|
1
|
+
export * from "./src/index";
|
package/index.esm.js
CHANGED
|
@@ -1 +1,10 @@
|
|
|
1
|
-
import{HTTPException
|
|
1
|
+
import { HTTPException } from 'hono/http-exception';
|
|
2
|
+
import { u as uniqueSymbol } from './utils.esm.js';
|
|
3
|
+
|
|
4
|
+
function describeRoute(specs){const middleware=async(c,next)=>{await next();if(specs.validateResponse&&specs.responses){const status=c.res.status;const contentType=c.res.headers.get("content-type");if(status&&contentType){const response=specs.responses[status];if(response&&"content"in response&&response.content){const content=response.content[contentType];if(content?.schema&&"validator"in content.schema){try{await content.schema.validator(c.res.body);}catch(error){throw new HTTPException(400,{message:"Response validation failed!"})}}}}}};return Object.assign(middleware,{[uniqueSymbol]:{resolver:async config=>{const docs={...specs};let components={};if(docs.responses){for(const key of Object.keys(docs.responses)){const response=docs.responses[key];if(response&&!("content"in response))continue;for(const contentKey of Object.keys(response.content??{})){const raw=response.content?.[contentKey];if(!raw)continue;if(raw.schema&&"builder"in raw.schema){const result=await raw.schema.builder(config);raw.schema=result.schema;if(result.components){components={...components,...result.components};}}}}}return {docs,components}}}})}
|
|
5
|
+
|
|
6
|
+
const ALLOWED_METHODS=["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE"];const toOpenAPIPath=path=>path.split("/").map(x=>{let tmp=x;if(tmp.startsWith(":")){tmp=tmp.slice(1,tmp.length);if(tmp.endsWith("?"))tmp=tmp.slice(0,-1);tmp=`{${tmp}}`;}return tmp}).join("/");const capitalize=word=>word.charAt(0).toUpperCase()+word.slice(1);const generateOperationId=(method,paths)=>{let operationId=method;if(paths==="/")return `${operationId}Index`;for(const path of paths.split("/")){if(path.charCodeAt(0)===123){operationId+=`By${capitalize(path.slice(1,-1))}`;}else {operationId+=capitalize(path);}}return operationId};function registerSchemaPath({path,method:_method,data,schema}){path=toOpenAPIPath(path);const method=_method.toLowerCase();schema[path]={...schema[path]?schema[path]:{},[method]:{responses:{},...schema[path]?.[method]??{},operationId:generateOperationId(method,path),...data}};}function filterPaths(paths,{excludeStaticFile=true,exclude=[]}){const newPaths={};for(const[key,value]of Object.entries(paths)){if(!exclude.some(x=>{if(typeof x==="string")return key===x;return x.test(key)})&&!key.includes("*")&&(excludeStaticFile?!key.includes("."):true)){for(const method of Object.keys(value)){const schema=value[method];if(key.includes("{")){if(!schema.parameters)schema.parameters=[];schema.parameters=[...key.split("/").filter(x=>x.startsWith("{")&&!schema.parameters.find(params=>params.in==="path"&¶ms.name===x.slice(1,x.length-1))).map(x=>({schema:{type:"string"},in:"path",name:x.slice(1,x.length-1),required:true})),...schema.parameters];}if(!schema.responses)schema.responses={200:{}};}newPaths[key]=value;}}return newPaths}
|
|
7
|
+
|
|
8
|
+
function openAPISpecs(hono,{documentation={},excludeStaticFile=true,exclude=[],excludeMethods=["OPTIONS"],excludeTags=[]}={documentation:{},excludeStaticFile:true,exclude:[],excludeMethods:["OPTIONS"],excludeTags:[]}){const config={version:"3.1.0",components:{}};const schema={};let specs=null;return async c=>{if(specs)return c.json(specs);for(const route of hono.routes){if(!(uniqueSymbol in route.handler))continue;if(excludeMethods.includes(route.method))continue;if(ALLOWED_METHODS.includes(route.method)===false&&route.method!=="ALL")continue;const{resolver,metadata={}}=route.handler[uniqueSymbol];const{docs,components}=await resolver({...config,...metadata});config.components={...config.components,...components??{}};if(route.method==="ALL"){for(const method of ALLOWED_METHODS){registerSchemaPath({path:route.path,data:docs,method,schema});}}else {registerSchemaPath({method:route.method,path:route.path,data:docs,schema});}}for(const path in schema){for(const method in schema[path]){const valueOrFunc=schema[path][method]?.hide;if(valueOrFunc&&(typeof valueOrFunc==="boolean"?valueOrFunc:valueOrFunc(c))){delete schema[path][method];}}}specs={openapi:config.version,...{...documentation,tags:documentation.tags?.filter(tag=>!excludeTags?.includes(tag?.name)),info:{title:"Hono Documentation",description:"Development documentation",version:"0.0.0",...documentation.info},paths:{...filterPaths(schema,{excludeStaticFile,exclude:Array.isArray(exclude)?exclude:[exclude]}),...documentation.paths},components:{...documentation.components,schemas:{...config.components,...documentation.components?.schemas}}}};return c.json(specs)}}
|
|
9
|
+
|
|
10
|
+
export { describeRoute, openAPISpecs };
|
package/index.esm2.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { Walker } from 'json-schema-walker';
|
|
2
|
+
|
|
3
|
+
const allowedKeywords=["$ref","definitions","title","multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","enum","type","not","allOf","oneOf","anyOf","items","properties","additionalProperties","description","format","default","nullable","discriminator","readOnly","writeOnly","example","externalDocs","deprecated","xml"];
|
|
4
|
+
|
|
5
|
+
let InvalidTypeError=class InvalidTypeError extends Error{constructor(message){super(message);this.name="InvalidTypeError";this.message=message;}};const oasExtensionPrefix="x-";const handleDefinition=async(def,schema)=>{if(typeof def!=="object"){return def}const type=def.type;if(type){const walker=new Walker;await walker.loadSchema({definitions:schema["definitions"]||[],...def,$schema:schema["$schema"]},{dereference:true,cloneSchema:true,dereferenceOptions:{dereference:{circular:"ignore"}}});await walker.walk(convertSchema,walker.vocabularies.DRAFT_07);if("definitions"in walker.rootSchema){walker.rootSchema.definitions=undefined;}return walker.rootSchema}if(Array.isArray(def)){const typeArr=def;const hasNull=typeArr.includes("null");if(hasNull){const actualTypes=typeArr.filter(l=>l!=="null");return {type:actualTypes.length===1?actualTypes[0]:actualTypes,nullable:true}}}return def};const convert=async(schema,options)=>{const walker=new Walker;await walker.loadSchema(schema,options);await walker.walk(convertSchema,walker.vocabularies.DRAFT_07);const rootSchema=walker.rootSchema;if(rootSchema?.definitions){for(const defName in rootSchema.definitions){const def=rootSchema.definitions[defName];rootSchema.definitions[defName]=await handleDefinition(def,schema);}}return rootSchema};function stripIllegalKeywords(schema){if(typeof schema!=="object"){return schema}schema["$schema"]=undefined;schema["$id"]=undefined;if("id"in schema){schema["id"]=undefined;}return schema}function convertSchema(schema){if(!schema){return schema}schema=stripIllegalKeywords(schema);schema=convertTypes(schema);schema=rewriteConst(schema);schema=convertDependencies(schema);schema=convertNullable(schema);schema=rewriteIfThenElse(schema);schema=rewriteExclusiveMinMax(schema);schema=convertExamples(schema);if(typeof schema["patternProperties"]==="object"){schema=convertPatternProperties(schema);}if(schema.type==="array"&&typeof schema.items==="undefined"){schema.items={};}schema=convertIllegalKeywordsAsExtensions(schema);return schema}const validTypes=new Set(["null","boolean","object","array","number","string","integer"]);function validateType(type){if(typeof type==="object"&&!Array.isArray(type)){if(type.$ref){return}if(type.properties){return}}const types=Array.isArray(type)?type:[type];for(const type of types){if(type&&!validTypes.has(type))throw new InvalidTypeError(`Type "${type}" is not a valid type`)}}function convertDependencies(schema){const deps=schema.dependencies;if(typeof deps!=="object"){return schema}schema.dependencies=undefined;if(!Array.isArray(schema.allOf)){schema.allOf=[];}for(const key in deps){const foo={oneOf:[{not:{required:[key]}},{required:[key,deps[key]].flat()}]};schema.allOf.push(foo);}return schema}function convertNullable(schema){for(const key of ["oneOf","anyOf"]){const schemas=schema[key];if(!schemas)continue;if(!Array.isArray(schemas)){return schema}const hasNullable=schemas.some(item=>item.type==="null");if(!hasNullable){return schema}const filtered=schemas.filter(l=>l.type!=="null");for(const schemaEntry of filtered){schemaEntry.nullable=true;}schema[key]=filtered;}return schema}function convertTypes(schema){if(typeof schema!=="object"){return schema}if(schema.type===undefined){return schema}validateType(schema.type);if(Array.isArray(schema.type)){if(schema.type.includes("null")){schema.nullable=true;}const typesWithoutNull=schema.type.filter(type=>type!=="null");if(typesWithoutNull.length===0){schema.type=undefined;}else if(typesWithoutNull.length===1){schema.type=typesWithoutNull[0];}else {schema.type=undefined;schema.anyOf=typesWithoutNull.map(type=>({type}));}}else if(schema.type==="null"){schema.type=undefined;schema.nullable=true;}return schema}function convertPatternProperties(schema){schema["x-patternProperties"]=schema.patternProperties;schema.patternProperties=undefined;schema.additionalProperties??=true;return schema}function convertIllegalKeywordsAsExtensions(schema){const keys=Object.keys(schema);for(const keyword of keys){if(!keyword.startsWith(oasExtensionPrefix)&&!allowedKeywords.includes(keyword)){const key=`${oasExtensionPrefix}${keyword}`;schema[key]=schema[keyword];schema[keyword]=undefined;}}return schema}function convertExamples(schema){if(schema["examples"]&&Array.isArray(schema["examples"])){schema["example"]=schema["examples"][0];schema["examples"]=undefined;}return schema}function rewriteConst(schema){if(Object.hasOwnProperty.call(schema,"const")){schema.enum=[schema.const];schema.const=undefined;}return schema}function rewriteIfThenElse(schema){if(typeof schema!=="object"){return schema}if("if"in schema&&schema.if&&schema.then){schema.oneOf=[{allOf:[schema.if,schema.then].filter(Boolean)},{allOf:[{not:schema.if},schema.else].filter(Boolean)}];schema.if=undefined;schema.then=undefined;schema.else=undefined;}return schema}function rewriteExclusiveMinMax(schema){if(typeof schema.exclusiveMaximum==="number"){schema.maximum=schema.exclusiveMaximum;schema.exclusiveMaximum=true;}if(typeof schema.exclusiveMinimum==="number"){schema.minimum=schema.exclusiveMinimum;schema.exclusiveMinimum=true;}return schema}
|
|
6
|
+
|
|
7
|
+
export { convert as c };
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hono-openapi",
|
|
3
3
|
"description": "OpenAPI schema generator for Hono",
|
|
4
|
-
"version": "0.2.
|
|
4
|
+
"version": "0.2.1",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"hono",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"url": "https://github.com/rhinobase/hono-openapi/issues"
|
|
25
25
|
},
|
|
26
26
|
"dependencies": {
|
|
27
|
-
"
|
|
27
|
+
"json-schema-walker": "^2.0.0"
|
|
28
28
|
},
|
|
29
29
|
"optionalDependencies": {
|
|
30
30
|
"@hono/arktype-validator": "^2.0.0",
|
|
@@ -41,7 +41,9 @@
|
|
|
41
41
|
"zod-openapi": "^4.0.0"
|
|
42
42
|
},
|
|
43
43
|
"devDependencies": {
|
|
44
|
-
"@rollup/plugin-terser": "^0.4.4"
|
|
44
|
+
"@rollup/plugin-terser": "^0.4.4",
|
|
45
|
+
"@apidevtools/json-schema-ref-parser": "^11.7.2",
|
|
46
|
+
"@types/json-schema": "^7.0.15"
|
|
45
47
|
},
|
|
46
48
|
"exports": {
|
|
47
49
|
".": {
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const allowedKeywords: string[];
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { JSONSchema4 } from "json-schema";
|
|
2
|
+
import type { Options } from "./types";
|
|
3
|
+
import type { OpenAPIV3 } from "openapi-types";
|
|
4
|
+
declare const convert: <T extends object = JSONSchema4>(schema: T, options?: Options) => Promise<OpenAPIV3.Document>;
|
|
5
|
+
export default convert;
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { JSONSchema, ParserOptions } from "@apidevtools/json-schema-ref-parser";
|
|
2
|
+
export type addPrefixToObject = {
|
|
3
|
+
[K in keyof JSONSchema as `x-${K}`]: JSONSchema[K];
|
|
4
|
+
};
|
|
5
|
+
export interface Options {
|
|
6
|
+
cloneSchema?: boolean;
|
|
7
|
+
dereference?: boolean;
|
|
8
|
+
convertUnreferencedDefinitions?: boolean;
|
|
9
|
+
dereferenceOptions?: ParserOptions | undefined;
|
|
10
|
+
}
|
|
11
|
+
type ExtendedJSONSchema = addPrefixToObject & JSONSchema;
|
|
12
|
+
export type SchemaType = ExtendedJSONSchema & {
|
|
13
|
+
example?: JSONSchema["examples"][number];
|
|
14
|
+
"x-patternProperties"?: JSONSchema["patternProperties"];
|
|
15
|
+
nullable?: boolean;
|
|
16
|
+
};
|
|
17
|
+
export type SchemaTypeKeys = keyof SchemaType;
|
|
18
|
+
export {};
|
package/typebox.cjs.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export * from "./src
|
|
1
|
+
export * from "./src/typebox";
|
package/typebox.cjs.js
CHANGED
|
@@ -1 +1,12 @@
|
|
|
1
|
-
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var typeboxValidator = require('@hono/typebox-validator');
|
|
4
|
+
var index = require('./index.cjs2.js');
|
|
5
|
+
var value = require('@sinclair/typebox/value');
|
|
6
|
+
var utils = require('./utils.cjs.js');
|
|
7
|
+
require('json-schema-walker');
|
|
8
|
+
|
|
9
|
+
function resolver(schema){return {builder:async options=>({schema:await index.convert(schema)}),validator:value$1=>{value.Value.Parse(schema,value$1);}}}function validator(target,schema,hook){const middleware=typeboxValidator.tbValidator(target,schema,hook);return Object.assign(middleware,{[utils.uniqueSymbol]:{resolver:async config=>utils.generateValidatorDocs(target,await resolver(schema).builder(config))}})}
|
|
10
|
+
|
|
11
|
+
exports.resolver = resolver;
|
|
12
|
+
exports.validator = validator;
|
package/typebox.esm.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export * from "./src
|
|
1
|
+
export * from "./src/typebox";
|
package/typebox.esm.js
CHANGED
|
@@ -1 +1,9 @@
|
|
|
1
|
-
import{tbValidator
|
|
1
|
+
import { tbValidator } from '@hono/typebox-validator';
|
|
2
|
+
import { c as convert } from './index.esm2.js';
|
|
3
|
+
import { Value } from '@sinclair/typebox/value';
|
|
4
|
+
import { u as uniqueSymbol, g as generateValidatorDocs } from './utils.esm.js';
|
|
5
|
+
import 'json-schema-walker';
|
|
6
|
+
|
|
7
|
+
function resolver(schema){return {builder:async options=>({schema:await convert(schema)}),validator:value=>{Value.Parse(schema,value);}}}function validator(target,schema,hook){const middleware=tbValidator(target,schema,hook);return Object.assign(middleware,{[uniqueSymbol]:{resolver:async config=>generateValidatorDocs(target,await resolver(schema).builder(config))}})}
|
|
8
|
+
|
|
9
|
+
export { resolver, validator };
|
package/utils.cjs.js
CHANGED
|
@@ -1 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const uniqueSymbol=Symbol("openapi");async function generateValidatorDocs(target,_result){const result=await _result;const docs={};if(target==="form"||target==="json"){docs.requestBody={content:{[target==="json"?"application/json":"application/x-www-form-urlencoded"]:{schema:result.schema}}};}else {const parameters=[];if("$ref"in result.schema){parameters.push({in:target,name:result.schema.$ref,schema:result.schema});}else {for(const[key,value]of Object.entries(result.schema.properties??{})){parameters.push({in:target,name:key,schema:value,required:result.schema.required?.includes(key)});}}docs.parameters=parameters;}return {docs,components:result.components}}
|
|
4
|
+
|
|
5
|
+
exports.generateValidatorDocs = generateValidatorDocs;
|
|
6
|
+
exports.uniqueSymbol = uniqueSymbol;
|
package/utils.esm.js
CHANGED
|
@@ -1 +1,3 @@
|
|
|
1
|
-
const
|
|
1
|
+
const uniqueSymbol=Symbol("openapi");async function generateValidatorDocs(target,_result){const result=await _result;const docs={};if(target==="form"||target==="json"){docs.requestBody={content:{[target==="json"?"application/json":"application/x-www-form-urlencoded"]:{schema:result.schema}}};}else {const parameters=[];if("$ref"in result.schema){parameters.push({in:target,name:result.schema.$ref,schema:result.schema});}else {for(const[key,value]of Object.entries(result.schema.properties??{})){parameters.push({in:target,name:key,schema:value,required:result.schema.required?.includes(key)});}}docs.parameters=parameters;}return {docs,components:result.components}}
|
|
2
|
+
|
|
3
|
+
export { generateValidatorDocs as g, uniqueSymbol as u };
|
package/valibot.cjs.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export * from "./src
|
|
1
|
+
export * from "./src/valibot";
|
package/valibot.cjs.js
CHANGED
|
@@ -1 +1,13 @@
|
|
|
1
|
-
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var valibotValidator = require('@hono/valibot-validator');
|
|
4
|
+
var index = require('./index.cjs2.js');
|
|
5
|
+
var toJsonSchema = require('@valibot/to-json-schema');
|
|
6
|
+
var valibot = require('valibot');
|
|
7
|
+
var utils = require('./utils.cjs.js');
|
|
8
|
+
require('json-schema-walker');
|
|
9
|
+
|
|
10
|
+
function resolver(schema){return {builder:async options=>({schema:await index.convert(toJsonSchema.toJsonSchema(schema))}),validator:async value=>{await valibot.parseAsync(schema,value);}}}function validator(target,schema,hook){const middleware=valibotValidator.vValidator(target,schema,hook);return Object.assign(middleware,{[utils.uniqueSymbol]:{resolver:async config=>utils.generateValidatorDocs(target,await resolver(schema).builder(config))}})}
|
|
11
|
+
|
|
12
|
+
exports.resolver = resolver;
|
|
13
|
+
exports.validator = validator;
|
package/valibot.esm.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export * from "./src
|
|
1
|
+
export * from "./src/valibot";
|
package/valibot.esm.js
CHANGED
|
@@ -1 +1,10 @@
|
|
|
1
|
-
import{vValidator
|
|
1
|
+
import { vValidator } from '@hono/valibot-validator';
|
|
2
|
+
import { c as convert } from './index.esm2.js';
|
|
3
|
+
import { toJsonSchema } from '@valibot/to-json-schema';
|
|
4
|
+
import { parseAsync } from 'valibot';
|
|
5
|
+
import { u as uniqueSymbol, g as generateValidatorDocs } from './utils.esm.js';
|
|
6
|
+
import 'json-schema-walker';
|
|
7
|
+
|
|
8
|
+
function resolver(schema){return {builder:async options=>({schema:await convert(toJsonSchema(schema))}),validator:async value=>{await parseAsync(schema,value);}}}function validator(target,schema,hook){const middleware=vValidator(target,schema,hook);return Object.assign(middleware,{[uniqueSymbol]:{resolver:async config=>generateValidatorDocs(target,await resolver(schema).builder(config))}})}
|
|
9
|
+
|
|
10
|
+
export { resolver, validator };
|
package/zod.cjs.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export * from "./src
|
|
1
|
+
export * from "./src/zod";
|
package/zod.cjs.js
CHANGED
|
@@ -1 +1,10 @@
|
|
|
1
|
-
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var zodValidator = require('@hono/zod-validator');
|
|
4
|
+
var zodOpenapi = require('zod-openapi');
|
|
5
|
+
var utils = require('./utils.cjs.js');
|
|
6
|
+
|
|
7
|
+
function resolver(schema){return {builder:options=>{const{version,...rest}=options??{};return zodOpenapi.createSchema(schema,options?{openapi:version,...rest}:undefined)},validator:schema.parse}}function validator(target,schema,hook){const middleware=zodValidator.zValidator(target,schema,hook);return Object.assign(middleware,{[utils.uniqueSymbol]:{resolver:async config=>utils.generateValidatorDocs(target,await resolver(schema).builder(config)),metadata:{schemaType:"input"}}})}
|
|
8
|
+
|
|
9
|
+
exports.resolver = resolver;
|
|
10
|
+
exports.validator = validator;
|
package/zod.esm.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export * from "./src
|
|
1
|
+
export * from "./src/zod";
|
package/zod.esm.js
CHANGED
|
@@ -1 +1,7 @@
|
|
|
1
|
-
import{zValidator
|
|
1
|
+
import { zValidator } from '@hono/zod-validator';
|
|
2
|
+
import { createSchema } from 'zod-openapi';
|
|
3
|
+
import { u as uniqueSymbol, g as generateValidatorDocs } from './utils.esm.js';
|
|
4
|
+
|
|
5
|
+
function resolver(schema){return {builder:options=>{const{version,...rest}=options??{};return createSchema(schema,options?{openapi:version,...rest}:undefined)},validator:schema.parse}}function validator(target,schema,hook){const middleware=zValidator(target,schema,hook);return Object.assign(middleware,{[uniqueSymbol]:{resolver:async config=>generateValidatorDocs(target,await resolver(schema).builder(config)),metadata:{schemaType:"input"}}})}
|
|
6
|
+
|
|
7
|
+
export { resolver, validator };
|