hono-openapi 0.1.4 → 0.2.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 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,181 +1,240 @@
1
- # 📜 Hono OpenAPI
2
-
3
- [![npm version](https://img.shields.io/npm/v/hono-openapi.svg)](https://npmjs.org/package/hono-openapi "View this project on NPM")
4
- [![npm downloads](https://img.shields.io/npm/dm/hono-openapi)](https://www.npmjs.com/package/hono-openapi)
5
- [![license](https://img.shields.io/npm/l/hono-openapi)](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
- - [ ] [TypeBox](https://github.com/sinclairzx81/typebox)
13
- - [ ] [Valibot](https://valibot.dev/)
14
-
15
- > [!Note]
16
- > 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.
17
-
18
- ## Usage
19
-
20
- ### Installation
21
-
22
- You can install the package using favorite package manager.
23
-
24
- ```bash
25
- pnpm add hono-openapi
26
- ```
27
-
28
- ### Basic Usage
29
-
30
- #### Setting up your application
31
-
32
- First, define your schemas, here is an example using Zod:
33
-
34
- ```ts
35
- import z from "zod";
36
-
37
- // For extending the Zod schema with OpenAPI properties
38
- import "zod-openapi/extend";
39
-
40
- const querySchema = z
41
- .object({
42
- name: z.string().optional().openapi({ example: "Steven" }),
43
- })
44
- .openapi({ ref: "Query" });
45
-
46
- const responseSchema = z.string().openapi({ example: "Hello Steven!" });
47
- ```
48
-
49
- 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).
50
-
51
- > [!Tip] > `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.
52
-
53
- Next, create your route -
54
-
55
- ```ts
56
- import { Hono } from "hono";
57
- import { describeRoute } from "hono-openapi";
58
- import { resolver, validator as zValidator } from "hono-openapi/zod";
59
-
60
- const app = new Hono();
61
-
62
- app.get(
63
- "/",
64
- describeRoute({
65
- description: "Say hello to the user",
66
- responses: {
67
- 200: {
68
- description: "Successful greeting response",
69
- content: {
70
- "text/plain": {
71
- schema: resolver(responseSchema),
72
- },
73
- },
74
- },
75
- },
76
- }),
77
- zValidator("query", querySchema),
78
- (c) => {
79
- const query = c.req.valid("query");
80
- return c.text(`Hello ${query?.name ?? "Hono"}!`);
81
- }
82
- );
83
- ```
84
-
85
- 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.
86
-
87
- Finally, generate the OpenAPI specification -
88
-
89
- ```ts
90
- app.get(
91
- "/openapi",
92
- openAPISpecs(app, {
93
- documentation: {
94
- info: {
95
- title: "Hono",
96
- version: "1.0.0",
97
- description: "API for greeting users",
98
- },
99
- servers: [
100
- {
101
- url: "http://localhost:3000",
102
- description: "Local server",
103
- },
104
- ],
105
- },
106
- })
107
- );
108
- ```
109
-
110
- 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 -
111
-
112
- - [Swagger UI](https://github.com/honojs/middleware/tree/main/packages/swagger-ui)
113
- - [Scalar](https://github.com/scalar/scalar/tree/main/packages/hono-api-reference)
114
-
115
- ##### Scalar Example
116
-
117
- ```ts
118
- app.get(
119
- "/docs",
120
- apiReference({
121
- theme: "saturn",
122
- spec: {
123
- url: "/openapi",
124
- },
125
- })
126
- );
127
- ```
128
-
129
- And that's it! You have successfully generated the OpenAPI specification for your Hono API.
130
-
131
- ### Advanced Usage
132
-
133
- #### Adding Security Definitions
134
-
135
- You can add security definitions to your OpenAPI specification by using the `security` property in the `openAPISpecs` function.
136
-
137
- ```ts
138
- app.get(
139
- "/openapi",
140
- openAPISpecs(appRouter, {
141
- documentation: {
142
- info: {
143
- title: "Rhinobase Cloud",
144
- version: "1.0.0",
145
- description: "API Documentation",
146
- },
147
- components: {
148
- securitySchemes: {
149
- bearerAuth: {
150
- type: "http",
151
- scheme: "bearer",
152
- bearerFormat: "JWT",
153
- },
154
- },
155
- },
156
- security: [
157
- {
158
- bearerAuth: [],
159
- },
160
- ],
161
- servers: [
162
- {
163
- url: "http://localhost:3004",
164
- description: "Local server",
165
- },
166
- ],
167
- },
168
- })
169
- );
170
- ```
171
-
172
- ## Contributing
173
-
174
- We would love to have more contributors involved!
175
-
176
- To get started, please read our [Contributing Guide](https://github.com/rhinobase/hono-openapi/blob/main/CONTRIBUTING.md).
177
-
178
- ## Credits
179
-
180
- - 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.
181
- - 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
+ [![npm version](https://img.shields.io/npm/v/hono-openapi.svg)](https://npmjs.org/package/hono-openapi "View this project on NPM")
4
+ [![npm downloads](https://img.shields.io/npm/dm/hono-openapi)](https://www.npmjs.com/package/hono-openapi)
5
+ [![license](https://img.shields.io/npm/l/hono-openapi)](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.
@@ -0,0 +1 @@
1
+ export * from "./src\\arktype";
package/arktype.cjs.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var e=require("@hono/arktype-validator"),r=require("@openapi-contrib/json-schema-to-openapi-schema"),a=require("./utils.cjs.js");function t(e){return{builder:async a=>({schema:await r(e.toJsonSchema())}),validator:r=>{e(r)}}}exports.resolver=t,exports.validator=function(r,o,i){const s=e.arktypeValidator(r,o,i);return Object.assign(s,{[a.uniqueSymbol]:{resolver:async e=>a.generateValidatorDocs(r,await t(o).builder(e))}})};
@@ -0,0 +1 @@
1
+ export * from "./src\\arktype";
package/arktype.esm.js ADDED
@@ -0,0 +1 @@
1
+ import{arktypeValidator as o}from"@hono/arktype-validator";import a from"@openapi-contrib/json-schema-to-openapi-schema";import{u as r,g as t}from"./utils.esm.js";function e(o){return{builder:async r=>({schema:await a(o.toJsonSchema())}),validator:a=>{o(a)}}}function i(a,i,n){const s=o(a,i,n);return Object.assign(s,{[r]:{resolver:async o=>t(a,await e(i).builder(o))}})}export{e as resolver,i as validator};
package/index.cjs.d.ts CHANGED
@@ -1 +1 @@
1
- export * from "./src/index";
1
+ export * from "./src\\index";
package/index.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("./constants.cjs.js");const t=["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE"],n=e=>e.charAt(0).toUpperCase()+e.slice(1),s=(e,t)=>{let s=e;if("/"===t)return`${s}Index`;for(const e of t.split("/"))123===e.charCodeAt(0)?s+=`By${n(e.slice(1,-1))}`:s+=n(e);return s};function o({path:e,method:t,data:n,schema:o}){e=(e=>e.split("/").map((e=>{let t=e;return t.startsWith(":")&&(t=t.slice(1,t.length),t.endsWith("?")&&(t=t.slice(0,-1)),t=`{${t}}`),t})).join("/"))(e);const c=t.toLowerCase();o[e]={...o[e]?o[e]:{},[c]:{responses:{},...o[e]?.[c]??{},operationId:s(c,e),...n}}}function c(e,{excludeStaticFile:t=!0,exclude:n=[]}){const s={};for(const[o,c]of Object.entries(e))if(!(n.some((e=>"string"==typeof e?o===e:e.test(o)))||o.includes("*")||t&&o.includes("."))){for(const e of Object.keys(c)){const t=c[e];o.includes("{")&&(t.parameters||(t.parameters=[]),t.parameters=[...o.split("/").filter((e=>e.startsWith("{")&&!t.parameters.find((t=>"path"===t.in&&t.name===e.slice(1,e.length-1))))).map((e=>({schema:{type:"string"},in:"path",name:e.slice(1,e.length-1),required:!0}))),...t.parameters]),t.responses||(t.responses={200:{}})}s[o]=c}return s}exports.describeRoute=function(t){return Object.assign((async(e,t)=>{await t()}),{[e.uniqueSymbol]:{resolver:e=>{const n={...t};let s={};if(n.responses)for(const t of Object.keys(n.responses)){const o=n.responses[t];if(!o||"content"in o)for(const t of Object.keys(o.content??{})){const n=o.content?.[t];if(n&&(n.schema&&"builder"in n.schema)){const t=n.schema.builder(e);n.schema=t.schema,t.components&&(s={...s,...t.components})}}}return{docs:n,components:s}}}})},exports.openAPISpecs=function(n,{documentation:s={},excludeStaticFile:i=!0,exclude:r=[],excludeMethods:a=["OPTIONS"],excludeTags:l=[]}={documentation:{},excludeStaticFile:!0,exclude:[],excludeMethods:["OPTIONS"],excludeTags:[]}){const d={version:"3.0.3",components:{}},m={};for(const s of n.routes){if(!(e.uniqueSymbol in s.handler))continue;if(a.includes(s.method))continue;if(!1===t.includes(s.method)&&"ALL"!==s.method)continue;const{resolver:n,metadata:c={}}=s.handler[e.uniqueSymbol],{docs:i,components:r}=n({...d,...c});if(d.components={...d.components,...r??{}},"ALL"===s.method)for(const e of t)o({path:s.path,data:i,method:e,schema:m});else o({method:s.method,path:s.path,data:i,schema:m})}for(const e in m)for(const t in m[e])m[e][t].hide&&delete m[e][t];const p={openapi:d.version,...{...s,tags:s.tags?.filter((e=>!l?.includes(e?.name))),info:{title:"Hono Documentation",description:"Development documentation",version:"0.0.0",...s.info},paths:{...c(m,{excludeStaticFile:i,exclude:Array.isArray(r)?r:[r]}),...s.paths},components:{...s.components,schemas:{...d.components,...s.components?.schemas}}}};return e=>e.json(p)};
1
+ "use strict";var e=require("hono/http-exception"),t=require("./utils.cjs.js");const n=["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE"],s=e=>e.charAt(0).toUpperCase()+e.slice(1),o=(e,t)=>{let n=e;if("/"===t)return`${n}Index`;for(const e of t.split("/"))123===e.charCodeAt(0)?n+=`By${s(e.slice(1,-1))}`:n+=s(e);return n};function c({path:e,method:t,data:n,schema:s}){e=(e=>e.split("/").map((e=>{let t=e;return t.startsWith(":")&&(t=t.slice(1,t.length),t.endsWith("?")&&(t=t.slice(0,-1)),t=`{${t}}`),t})).join("/"))(e);const c=t.toLowerCase();s[e]={...s[e]?s[e]:{},[c]:{responses:{},...s[e]?.[c]??{},operationId:o(c,e),...n}}}function i(e,{excludeStaticFile:t=!0,exclude:n=[]}){const s={};for(const[o,c]of Object.entries(e))if(!(n.some((e=>"string"==typeof e?o===e:e.test(o)))||o.includes("*")||t&&o.includes("."))){for(const e of Object.keys(c)){const t=c[e];o.includes("{")&&(t.parameters||(t.parameters=[]),t.parameters=[...o.split("/").filter((e=>e.startsWith("{")&&!t.parameters.find((t=>"path"===t.in&&t.name===e.slice(1,e.length-1))))).map((e=>({schema:{type:"string"},in:"path",name:e.slice(1,e.length-1),required:!0}))),...t.parameters]),t.responses||(t.responses={200:{}})}s[o]=c}return s}exports.describeRoute=function(n){return Object.assign((async(t,s)=>{if(await s(),n.validateResponse&&n.responses){const s=t.res.status,o=t.res.headers.get("content-type");if(s&&o){const c=n.responses[s];if(c&&"content"in c&&c.content){const n=c.content[o];if(n?.schema&&"validator"in n.schema)try{await n.schema.validator(t.res.body)}catch(t){throw new e.HTTPException(400,{message:"Response validation failed!"})}}}}}),{[t.uniqueSymbol]:{resolver:async e=>{const t={...n};let s={};if(t.responses)for(const n of Object.keys(t.responses)){const o=t.responses[n];if(!o||"content"in o)for(const t of Object.keys(o.content??{})){const n=o.content?.[t];if(n&&(n.schema&&"builder"in n.schema)){const t=await n.schema.builder(e);n.schema=t.schema,t.components&&(s={...s,...t.components})}}}return{docs:t,components:s}}}})},exports.openAPISpecs=function(e,{documentation:s={},excludeStaticFile:o=!0,exclude:a=[],excludeMethods:r=["OPTIONS"],excludeTags:l=[]}={documentation:{},excludeStaticFile:!0,exclude:[],excludeMethods:["OPTIONS"],excludeTags:[]}){const d={version:"3.1.0",components:{}},p={};let u=null;return async m=>{if(u)return m.json(u);for(const s of e.routes){if(!(t.uniqueSymbol in s.handler))continue;if(r.includes(s.method))continue;if(!1===n.includes(s.method)&&"ALL"!==s.method)continue;const{resolver:e,metadata:o={}}=s.handler[t.uniqueSymbol],{docs:i,components:a}=await e({...d,...o});if(d.components={...d.components,...a??{}},"ALL"===s.method)for(const e of n)c({path:s.path,data:i,method:e,schema:p});else c({method:s.method,path:s.path,data:i,schema:p})}for(const e in p)for(const t in p[e]){const n=p[e][t]?.hide;n&&("boolean"==typeof n?n:n(m))&&delete p[e][t]}return u={openapi:d.version,...{...s,tags:s.tags?.filter((e=>!l?.includes(e?.name))),info:{title:"Hono Documentation",description:"Development documentation",version:"0.0.0",...s.info},paths:{...i(p,{excludeStaticFile:o,exclude:Array.isArray(a)?a:[a]}),...s.paths},components:{...s.components,schemas:{...d.components,...s.components?.schemas}}}},m.json(u)}};
package/index.esm.d.ts CHANGED
@@ -1 +1 @@
1
- export * from "./src/index";
1
+ export * from "./src\\index";
package/index.esm.js CHANGED
@@ -1 +1 @@
1
- import{u as e}from"./constants.esm.js";function t(t){return Object.assign((async(e,t)=>{await t()}),{[e]:{resolver:e=>{const n={...t};let s={};if(n.responses)for(const t of Object.keys(n.responses)){const o=n.responses[t];if(!o||"content"in o)for(const t of Object.keys(o.content??{})){const n=o.content?.[t];if(n&&(n.schema&&"builder"in n.schema)){const t=n.schema.builder(e);n.schema=t.schema,t.components&&(s={...s,...t.components})}}}return{docs:n,components:s}}}})}const n=["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE"],s=e=>e.charAt(0).toUpperCase()+e.slice(1),o=(e,t)=>{let n=e;if("/"===t)return`${n}Index`;for(const e of t.split("/"))123===e.charCodeAt(0)?n+=`By${s(e.slice(1,-1))}`:n+=s(e);return n};function c({path:e,method:t,data:n,schema:s}){e=(e=>e.split("/").map((e=>{let t=e;return t.startsWith(":")&&(t=t.slice(1,t.length),t.endsWith("?")&&(t=t.slice(0,-1)),t=`{${t}}`),t})).join("/"))(e);const c=t.toLowerCase();s[e]={...s[e]?s[e]:{},[c]:{responses:{},...s[e]?.[c]??{},operationId:o(c,e),...n}}}function i(e,{excludeStaticFile:t=!0,exclude:n=[]}){const s={};for(const[o,c]of Object.entries(e))if(!(n.some((e=>"string"==typeof e?o===e:e.test(o)))||o.includes("*")||t&&o.includes("."))){for(const e of Object.keys(c)){const t=c[e];o.includes("{")&&(t.parameters||(t.parameters=[]),t.parameters=[...o.split("/").filter((e=>e.startsWith("{")&&!t.parameters.find((t=>"path"===t.in&&t.name===e.slice(1,e.length-1))))).map((e=>({schema:{type:"string"},in:"path",name:e.slice(1,e.length-1),required:!0}))),...t.parameters]),t.responses||(t.responses={200:{}})}s[o]=c}return s}function a(t,{documentation:s={},excludeStaticFile:o=!0,exclude:a=[],excludeMethods:r=["OPTIONS"],excludeTags:d=[]}={documentation:{},excludeStaticFile:!0,exclude:[],excludeMethods:["OPTIONS"],excludeTags:[]}){const m={version:"3.0.3",components:{}},l={};for(const s of t.routes){if(!(e in s.handler))continue;if(r.includes(s.method))continue;if(!1===n.includes(s.method)&&"ALL"!==s.method)continue;const{resolver:t,metadata:o={}}=s.handler[e],{docs:i,components:a}=t({...m,...o});if(m.components={...m.components,...a??{}},"ALL"===s.method)for(const e of n)c({path:s.path,data:i,method:e,schema:l});else c({method:s.method,path:s.path,data:i,schema:l})}for(const e in l)for(const t in l[e])l[e][t].hide&&delete l[e][t];const p={openapi:m.version,...{...s,tags:s.tags?.filter((e=>!d?.includes(e?.name))),info:{title:"Hono Documentation",description:"Development documentation",version:"0.0.0",...s.info},paths:{...i(l,{excludeStaticFile:o,exclude:Array.isArray(a)?a:[a]}),...s.paths},components:{...s.components,schemas:{...m.components,...s.components?.schemas}}}};return e=>e.json(p)}export{t as describeRoute,a as openAPISpecs};
1
+ import{HTTPException as e}from"hono/http-exception";import{u as t}from"./utils.esm.js";function n(n){return Object.assign((async(t,s)=>{if(await s(),n.validateResponse&&n.responses){const s=t.res.status,o=t.res.headers.get("content-type");if(s&&o){const c=n.responses[s];if(c&&"content"in c&&c.content){const n=c.content[o];if(n?.schema&&"validator"in n.schema)try{await n.schema.validator(t.res.body)}catch(t){throw new e(400,{message:"Response validation failed!"})}}}}}),{[t]:{resolver:async e=>{const t={...n};let s={};if(t.responses)for(const n of Object.keys(t.responses)){const o=t.responses[n];if(!o||"content"in o)for(const t of Object.keys(o.content??{})){const n=o.content?.[t];if(n&&(n.schema&&"builder"in n.schema)){const t=await n.schema.builder(e);n.schema=t.schema,t.components&&(s={...s,...t.components})}}}return{docs:t,components:s}}}})}const s=["GET","PUT","POST","DELETE","OPTIONS","HEAD","PATCH","TRACE"],o=e=>e.charAt(0).toUpperCase()+e.slice(1),c=(e,t)=>{let n=e;if("/"===t)return`${n}Index`;for(const e of t.split("/"))123===e.charCodeAt(0)?n+=`By${o(e.slice(1,-1))}`:n+=o(e);return n};function a({path:e,method:t,data:n,schema:s}){e=(e=>e.split("/").map((e=>{let t=e;return t.startsWith(":")&&(t=t.slice(1,t.length),t.endsWith("?")&&(t=t.slice(0,-1)),t=`{${t}}`),t})).join("/"))(e);const o=t.toLowerCase();s[e]={...s[e]?s[e]:{},[o]:{responses:{},...s[e]?.[o]??{},operationId:c(o,e),...n}}}function i(e,{excludeStaticFile:t=!0,exclude:n=[]}){const s={};for(const[o,c]of Object.entries(e))if(!(n.some((e=>"string"==typeof e?o===e:e.test(o)))||o.includes("*")||t&&o.includes("."))){for(const e of Object.keys(c)){const t=c[e];o.includes("{")&&(t.parameters||(t.parameters=[]),t.parameters=[...o.split("/").filter((e=>e.startsWith("{")&&!t.parameters.find((t=>"path"===t.in&&t.name===e.slice(1,e.length-1))))).map((e=>({schema:{type:"string"},in:"path",name:e.slice(1,e.length-1),required:!0}))),...t.parameters]),t.responses||(t.responses={200:{}})}s[o]=c}return s}function r(e,{documentation:n={},excludeStaticFile:o=!0,exclude:c=[],excludeMethods:r=["OPTIONS"],excludeTags:l=[]}={documentation:{},excludeStaticFile:!0,exclude:[],excludeMethods:["OPTIONS"],excludeTags:[]}){const d={version:"3.1.0",components:{}},m={};let p=null;return async h=>{if(p)return h.json(p);for(const n of e.routes){if(!(t in n.handler))continue;if(r.includes(n.method))continue;if(!1===s.includes(n.method)&&"ALL"!==n.method)continue;const{resolver:e,metadata:o={}}=n.handler[t],{docs:c,components:i}=await e({...d,...o});if(d.components={...d.components,...i??{}},"ALL"===n.method)for(const e of s)a({path:n.path,data:c,method:e,schema:m});else a({method:n.method,path:n.path,data:c,schema:m})}for(const e in m)for(const t in m[e]){const n=m[e][t]?.hide;n&&("boolean"==typeof n?n:n(h))&&delete m[e][t]}return p={openapi:d.version,...{...n,tags:n.tags?.filter((e=>!l?.includes(e?.name))),info:{title:"Hono Documentation",description:"Development documentation",version:"0.0.0",...n.info},paths:{...i(m,{excludeStaticFile:o,exclude:Array.isArray(c)?c:[c]}),...n.paths},components:{...n.components,schemas:{...d.components,...n.components?.schemas}}}},h.json(p)}}export{n as describeRoute,r as openAPISpecs};
package/package.json CHANGED
@@ -1,11 +1,15 @@
1
1
  {
2
2
  "name": "hono-openapi",
3
3
  "description": "OpenAPI schema generator for Hono",
4
- "version": "0.1.4",
4
+ "version": "0.2.0",
5
5
  "license": "MIT",
6
6
  "keywords": [
7
7
  "hono",
8
- "openapi"
8
+ "openapi",
9
+ "zod",
10
+ "valibot",
11
+ "typebox",
12
+ "arktype"
9
13
  ],
10
14
  "homepage": "https://github.com/rhinobase/hono-openapi",
11
15
  "publishConfig": {
@@ -14,31 +18,81 @@
14
18
  "repository": {
15
19
  "type": "git",
16
20
  "url": "git+https://github.com/rhinobase/hono-openapi.git",
17
- "directory": "packages/ui"
21
+ "directory": "packages/core"
18
22
  },
19
23
  "bugs": {
20
24
  "url": "https://github.com/rhinobase/hono-openapi/issues"
21
25
  },
22
- "peerDependencies": {
23
- "hono": "^4.6.4",
26
+ "dependencies": {
27
+ "@openapi-contrib/json-schema-to-openapi-schema": "^3.0.3"
28
+ },
29
+ "optionalDependencies": {
30
+ "@hono/arktype-validator": "^2.0.0",
31
+ "@hono/typebox-validator": "^0.2.6",
32
+ "@hono/valibot-validator": "^0.5.1",
24
33
  "@hono/zod-validator": "^0.4.1",
34
+ "@sinclair/typebox": "^0.34.9",
35
+ "@valibot/to-json-schema": "^1.0.0-beta.3",
36
+ "arktype": "2.0.0-rc.25",
37
+ "hono": "^4.6.4",
38
+ "openapi-types": "^12.1.3",
39
+ "valibot": "^1.0.0-beta.9",
25
40
  "zod": "^3.23.8",
26
- "zod-openapi": "^3.1.1",
27
- "openapi-types": "^12.1.3"
41
+ "zod-openapi": "^4.0.0"
28
42
  },
29
43
  "devDependencies": {
30
44
  "@rollup/plugin-terser": "^0.4.4"
31
45
  },
32
46
  "exports": {
33
47
  ".": {
34
- "import": "./index.esm.js",
35
- "require": "./index.cjs.js",
36
- "types": "./index.cjs.d.ts"
48
+ "import": {
49
+ "default": "./index.esm.js",
50
+ "types": "./index.esm.d.ts"
51
+ },
52
+ "require": {
53
+ "default": "./index.cjs.js",
54
+ "types": "./index.cjs.d.ts"
55
+ }
37
56
  },
38
57
  "./zod": {
39
- "import": "./zod.esm.js",
40
- "require": "./zod.cjs.js",
41
- "types": "./zod.cjs.d.ts"
58
+ "import": {
59
+ "default": "./zod.esm.js",
60
+ "types": "./zod.esm.d.ts"
61
+ },
62
+ "require": {
63
+ "default": "./zod.cjs.js",
64
+ "types": "./zod.cjs.d.ts"
65
+ }
66
+ },
67
+ "./valibot": {
68
+ "import": {
69
+ "default": "./valibot.esm.js",
70
+ "types": "./valibot.esm.d.ts"
71
+ },
72
+ "require": {
73
+ "default": "./valibot.cjs.js",
74
+ "types": "./valibot.cjs.d.ts"
75
+ }
76
+ },
77
+ "./typebox": {
78
+ "import": {
79
+ "default": "./typebox.esm.js",
80
+ "types": "./typebox.esm.d.ts"
81
+ },
82
+ "require": {
83
+ "default": "./typebox.cjs.js",
84
+ "types": "./typebox.cjs.d.ts"
85
+ }
86
+ },
87
+ "./arktype": {
88
+ "import": {
89
+ "default": "./arktype.esm.js",
90
+ "types": "./arktype.esm.d.ts"
91
+ },
92
+ "require": {
93
+ "default": "./arktype.cjs.js",
94
+ "types": "./arktype.cjs.d.ts"
95
+ }
42
96
  }
43
97
  },
44
98
  "module": "./index.esm.js",
@@ -0,0 +1,24 @@
1
+ import { type Hook } from "@hono/arktype-validator";
2
+ import type { Type } from "arktype";
3
+ import type { Env, MiddlewareHandler, ValidationTargets } from "hono";
4
+ import type { HasUndefined, ResolverResult } from "./types";
5
+ export declare function resolver<T extends Type>(schema: T): ResolverResult;
6
+ export declare function validator<T extends Type, Target extends keyof ValidationTargets, E extends Env, P extends string, I = T["inferIn"], O = T["infer"], V extends {
7
+ in: HasUndefined<I> extends true ? {
8
+ [K in Target]?: I;
9
+ } : {
10
+ [K in Target]: I;
11
+ };
12
+ out: {
13
+ [K in Target]: O;
14
+ };
15
+ } = {
16
+ in: HasUndefined<I> extends true ? {
17
+ [K in Target]?: I;
18
+ } : {
19
+ [K in Target]: I;
20
+ };
21
+ out: {
22
+ [K in Target]: O;
23
+ };
24
+ }>(target: Target, schema: T, hook?: Hook<T["infer"], E, P>): MiddlewareHandler<E, P, V>;
@@ -0,0 +1,13 @@
1
+ import type { OpenAPIV3 } from "openapi-types";
2
+ import type { OpenAPIRoute } from "./types";
3
+ export declare const ALLOWED_METHODS: readonly ["GET", "PUT", "POST", "DELETE", "OPTIONS", "HEAD", "PATCH", "TRACE"];
4
+ export declare const toOpenAPIPath: (path: string) => string;
5
+ export declare const capitalize: (word: string) => string;
6
+ export declare const generateOperationId: (method: string, paths: string) => string;
7
+ export declare function registerSchemaPath({ path, method: _method, data, schema, }: OpenAPIRoute & {
8
+ schema: Partial<OpenAPIV3.PathsObject>;
9
+ }): void;
10
+ export declare function filterPaths(paths: OpenAPIV3.PathsObject, { excludeStaticFile, exclude, }: {
11
+ excludeStaticFile: boolean;
12
+ exclude: (string | RegExp)[];
13
+ }): OpenAPIV3.PathsObject<{}, {}>;
package/src/index.d.ts CHANGED
@@ -1,2 +1,3 @@
1
1
  export { describeRoute } from "./route";
2
2
  export { openAPISpecs } from "./openapi";
3
+ export type * from "./types";
package/src/openapi.d.ts CHANGED
@@ -1,3 +1,4 @@
1
- import type { Context, Env, Hono, Input } from "hono";
1
+ import type { Context, Env, Hono, Input, Schema } from "hono";
2
+ import type { BlankSchema } from "hono/types";
2
3
  import type { OpenApiSpecsOptions } from "./types";
3
- export declare function openAPISpecs<E extends Env = Env, P extends string = string, I extends Input = Input>(hono: Hono, { documentation, excludeStaticFile, exclude, excludeMethods, excludeTags, }?: OpenApiSpecsOptions): (c: Context<E, P, I>) => any;
4
+ export declare function openAPISpecs<E extends Env = Env, P extends string = string, I extends Input = Input, S extends Schema = BlankSchema>(hono: Hono<E, S, P>, { documentation, excludeStaticFile, exclude, excludeMethods, excludeTags, }?: OpenApiSpecsOptions): (c: Context<E, P, I>) => Promise<any>;
package/src/route.d.ts CHANGED
@@ -1,33 +1,3 @@
1
1
  import type { Env, Input, MiddlewareHandler } from "hono/types";
2
- import type { DescribeRouteOptions, OpenAPIRouteHandlerConfig } from "./types";
3
- import { uniqueSymbol } from "./constants";
4
- export declare function describeRoute<E extends Env = Env, P extends string = string, I extends Input = Input>(specs: DescribeRouteOptions): MiddlewareHandler<E, P, I> & {
5
- [uniqueSymbol]: {
6
- resolver: (config: OpenAPIRouteHandlerConfig) => {
7
- docs: {
8
- tags?: string[] | undefined;
9
- summary?: string | undefined;
10
- description?: string | undefined;
11
- externalDocs?: import("openapi-types").OpenAPIV3.ExternalDocumentationObject | undefined;
12
- operationId?: string | undefined;
13
- callbacks?: {
14
- [callback: string]: import("openapi-types").OpenAPIV3.ReferenceObject | import("openapi-types").OpenAPIV3.CallbackObject;
15
- } | undefined;
16
- deprecated?: boolean | undefined;
17
- security?: import("openapi-types").OpenAPIV3.SecurityRequirementObject[] | undefined;
18
- servers?: import("openapi-types").OpenAPIV3.ServerObject[] | undefined;
19
- hide?: boolean;
20
- responses?: {
21
- [key: string]: import("openapi-types").OpenAPIV3.ResponseObject & {
22
- content?: {
23
- [key: string]: Omit<import("openapi-types").OpenAPIV3.MediaTypeObject, "schema"> & {
24
- schema?: import("openapi-types").OpenAPIV3.ReferenceObject | import("openapi-types").OpenAPIV3.SchemaObject | import("./types").ResolverResult;
25
- };
26
- };
27
- };
28
- };
29
- };
30
- components: {};
31
- };
32
- };
33
- };
2
+ import type { DescribeRouteOptions } from "./types";
3
+ export declare function describeRoute<E extends Env = Env, P extends string = string, I extends Input = Input>(specs: DescribeRouteOptions<E, P, I>): MiddlewareHandler<E, P, I>;
@@ -0,0 +1,13 @@
1
+ import { type Hook } from "@hono/typebox-validator";
2
+ import type { Static, TSchema } from "@sinclair/typebox";
3
+ import type { Env, MiddlewareHandler, ValidationTargets } from "hono";
4
+ import type { ResolverResult } from "./types";
5
+ export declare function resolver<T extends TSchema>(schema: T): ResolverResult;
6
+ export declare function validator<T extends TSchema, Target extends keyof ValidationTargets, E extends Env, P extends string, V extends {
7
+ in: {
8
+ [K in Target]: Static<T>;
9
+ };
10
+ out: {
11
+ [K in Target]: Static<T>;
12
+ };
13
+ }>(target: Target, schema: T, hook?: Hook<Static<T>, E, P>): MiddlewareHandler<E, P, V>;
package/src/types.d.ts CHANGED
@@ -1,39 +1,50 @@
1
+ import type { Context, Env, Input } from "hono";
2
+ import type { BlankInput } from "hono/types";
1
3
  import type { OpenAPIV3 } from "openapi-types";
2
- import type { ALLOWED_METHODS } from "./utils";
4
+ import type { ALLOWED_METHODS } from "./helper";
5
+ export type HasUndefined<T> = undefined extends T ? true : false;
6
+ export type PromiseOr<T> = T | Promise<T>;
3
7
  export type OpenAPIRouteHandlerConfig = {
4
8
  version: "3.0.0" | "3.0.1" | "3.0.2" | "3.0.3" | "3.1.0";
5
9
  components: OpenAPIV3.ComponentsObject["schemas"];
10
+ } & {
11
+ [key: string]: unknown;
6
12
  };
7
13
  export type ResolverResult = {
8
- builder: (options?: OpenAPIRouteHandlerConfig) => {
14
+ builder: (options?: OpenAPIRouteHandlerConfig) => PromiseOr<{
9
15
  schema: OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject;
10
16
  components?: OpenAPIV3.ComponentsObject["schemas"];
11
- };
12
- validator: (values: unknown) => void | Promise<void>;
17
+ }>;
18
+ validator: (values: unknown) => PromiseOr<void>;
13
19
  };
14
20
  export type HandlerResponse = {
15
- resolver: (config: OpenAPIRouteHandlerConfig) => {
21
+ resolver: (config: OpenAPIRouteHandlerConfig) => PromiseOr<{
16
22
  docs: OpenAPIV3.OperationObject;
17
23
  components?: OpenAPIV3.ComponentsObject["schemas"];
18
- };
24
+ }>;
19
25
  metadata?: Record<string, unknown>;
20
26
  };
21
- export type DescribeRouteOptions = Omit<OpenAPIV3.OperationObject, "responses" | "requestBody" | "parameters"> & {
27
+ export type DescribeRouteOptions<E extends Env = Env, P extends string = string, I extends Input = BlankInput> = Omit<OpenAPIV3.OperationObject, "responses" | "requestBody" | "parameters"> & {
22
28
  /**
23
29
  * Pass `true` to hide route from OpenAPI/swagger document
24
30
  */
25
- hide?: boolean;
31
+ hide?: boolean | ((c: Context<E, P, I>) => boolean);
32
+ /**
33
+ * Validate response of the route
34
+ * @experimental
35
+ */
36
+ validateResponse?: boolean;
26
37
  /**
27
38
  * Responses of the request
28
39
  */
29
40
  responses?: {
30
- [key: string]: OpenAPIV3.ResponseObject & {
41
+ [key: string]: (OpenAPIV3.ResponseObject & {
31
42
  content?: {
32
43
  [key: string]: Omit<OpenAPIV3.MediaTypeObject, "schema"> & {
33
44
  schema?: OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject | ResolverResult;
34
45
  };
35
46
  };
36
- };
47
+ }) | OpenAPIV3.ReferenceObject;
37
48
  };
38
49
  };
39
50
  export interface OpenAPIRoute {
package/src/utils.d.ts CHANGED
@@ -1,13 +1,25 @@
1
+ import type { ValidationTargets } from "hono";
1
2
  import type { OpenAPIV3 } from "openapi-types";
2
- import type { OpenAPIRoute } from "./types";
3
- export declare const ALLOWED_METHODS: readonly ["GET", "PUT", "POST", "DELETE", "OPTIONS", "HEAD", "PATCH", "TRACE"];
4
- export declare const toOpenAPIPath: (path: string) => string;
5
- export declare const capitalize: (word: string) => string;
6
- export declare const generateOperationId: (method: string, paths: string) => string;
7
- export declare function registerSchemaPath({ path, method: _method, data, schema, }: OpenAPIRoute & {
8
- schema: Partial<OpenAPIV3.PathsObject>;
9
- }): void;
10
- export declare function filterPaths(paths: OpenAPIV3.PathsObject, { excludeStaticFile, exclude, }: {
11
- excludeStaticFile: boolean;
12
- exclude: (string | RegExp)[];
13
- }): OpenAPIV3.PathsObject<{}, {}>;
3
+ import type { ResolverResult } from "./types";
4
+ export declare const uniqueSymbol: unique symbol;
5
+ export declare function generateValidatorDocs<Target extends keyof ValidationTargets>(target: Target, _result: ReturnType<ResolverResult["builder"]>): Promise<{
6
+ docs: Pick<{
7
+ tags?: string[];
8
+ summary?: string;
9
+ description?: string;
10
+ externalDocs?: OpenAPIV3.ExternalDocumentationObject;
11
+ operationId?: string;
12
+ parameters?: (OpenAPIV3.ReferenceObject | OpenAPIV3.ParameterObject)[];
13
+ requestBody?: OpenAPIV3.ReferenceObject | OpenAPIV3.RequestBodyObject;
14
+ responses: OpenAPIV3.ResponsesObject;
15
+ callbacks?: {
16
+ [callback: string]: OpenAPIV3.ReferenceObject | OpenAPIV3.CallbackObject;
17
+ };
18
+ deprecated?: boolean;
19
+ security?: OpenAPIV3.SecurityRequirementObject[];
20
+ servers?: OpenAPIV3.ServerObject[];
21
+ }, "parameters" | "requestBody">;
22
+ components: {
23
+ [key: string]: OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject;
24
+ } | undefined;
25
+ }>;
@@ -0,0 +1,23 @@
1
+ import { type Hook } from "@hono/valibot-validator";
2
+ import type { Env, Input as HonoInput, MiddlewareHandler, ValidationTargets } from "hono";
3
+ import { type BaseIssue, type BaseSchema, type GenericSchema, type GenericSchemaAsync, type InferInput, type InferOutput } from "valibot";
4
+ import type { HasUndefined, ResolverResult } from "./types";
5
+ export declare function resolver<T extends BaseSchema<unknown, unknown, BaseIssue<unknown>>>(schema: T): ResolverResult;
6
+ export declare function validator<T extends GenericSchema | GenericSchemaAsync, Target extends keyof ValidationTargets, E extends Env, P extends string, In = InferInput<T>, Out = InferOutput<T>, I extends HonoInput = {
7
+ in: HasUndefined<In> extends true ? {
8
+ [K in Target]?: K extends "json" ? In : HasUndefined<keyof ValidationTargets[K]> extends true ? {
9
+ [K2 in keyof In]?: ValidationTargets[K][K2];
10
+ } : {
11
+ [K2 in keyof In]: ValidationTargets[K][K2];
12
+ };
13
+ } : {
14
+ [K in Target]: K extends "json" ? In : HasUndefined<keyof ValidationTargets[K]> extends true ? {
15
+ [K2 in keyof In]?: ValidationTargets[K][K2];
16
+ } : {
17
+ [K2 in keyof In]: ValidationTargets[K][K2];
18
+ };
19
+ };
20
+ out: {
21
+ [K in Target]: Out;
22
+ };
23
+ }, V extends I = I>(target: Target, schema: T, hook?: Hook<T, E, P>): MiddlewareHandler<E, P, V>;
package/src/zod.d.ts CHANGED
@@ -1,9 +1,8 @@
1
- import type { z, ZodSchema } from "zod";
2
1
  import { type Hook } from "@hono/zod-validator";
3
- import type { ResolverResult } from "./types";
4
2
  import type { Env, Input, MiddlewareHandler, ValidationTargets } from "hono";
3
+ import type { ZodSchema, z } from "zod";
4
+ import type { HasUndefined, ResolverResult } from "./types";
5
5
  export declare function resolver<T extends ZodSchema>(schema: T): ResolverResult;
6
- type HasUndefined<T> = undefined extends T ? true : false;
7
6
  export declare function validator<T extends ZodSchema, Target extends keyof ValidationTargets, E extends Env, P extends string, In = z.input<T>, Out = z.output<T>, I extends Input = {
8
7
  in: HasUndefined<In> extends true ? {
9
8
  [K in Target]?: In extends ValidationTargets[K] ? In : {
@@ -18,4 +17,3 @@ export declare function validator<T extends ZodSchema, Target extends keyof Vali
18
17
  [K in Target]: Out;
19
18
  };
20
19
  }, V extends I = I>(target: Target, schema: T, hook?: Hook<z.infer<T>, E, P, Target>): MiddlewareHandler<E, P, V>;
21
- export {};
@@ -0,0 +1 @@
1
+ export * from "./src\\typebox";
package/typebox.cjs.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var e=require("@hono/typebox-validator"),r=require("@openapi-contrib/json-schema-to-openapi-schema"),a=require("@sinclair/typebox/value"),i=require("./utils.cjs.js");function t(e){return{builder:async a=>({schema:await r(e)}),validator:r=>{a.Value.Parse(e,r)}}}exports.resolver=t,exports.validator=function(r,a,o){const s=e.tbValidator(r,a,o);return Object.assign(s,{[i.uniqueSymbol]:{resolver:async e=>i.generateValidatorDocs(r,await t(a).builder(e))}})};
@@ -0,0 +1 @@
1
+ export * from "./src\\typebox";
package/typebox.esm.js ADDED
@@ -0,0 +1 @@
1
+ import{tbValidator as o}from"@hono/typebox-validator";import r from"@openapi-contrib/json-schema-to-openapi-schema";import{Value as a}from"@sinclair/typebox/value";import{u as t,g as i}from"./utils.esm.js";function e(o){return{builder:async a=>({schema:await r(o)}),validator:r=>{a.Parse(o,r)}}}function s(r,a,s){const n=o(r,a,s);return Object.assign(n,{[t]:{resolver:async o=>i(r,await e(a).builder(o))}})}export{e as resolver,s as validator};
package/utils.cjs.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";const e=Symbol("openapi");exports.generateValidatorDocs=async function(e,s){const o=await s,n={};if("form"===e||"json"===e)n.requestBody={content:{["json"===e?"application/json":"application/x-www-form-urlencoded"]:{schema:o.schema}}};else{const s=[];if("$ref"in o.schema)s.push({in:e,name:o.schema.$ref,schema:o.schema});else for(const[n,c]of Object.entries(o.schema.properties??{}))s.push({in:e,name:n,schema:c});n.parameters=s}return{docs:n,components:o.components}},exports.uniqueSymbol=e;
package/utils.esm.js ADDED
@@ -0,0 +1 @@
1
+ const e=Symbol("openapi");async function s(e,s){const n=await s,o={};if("form"===e||"json"===e)o.requestBody={content:{["json"===e?"application/json":"application/x-www-form-urlencoded"]:{schema:n.schema}}};else{const s=[];if("$ref"in n.schema)s.push({in:e,name:n.schema.$ref,schema:n.schema});else for(const[o,a]of Object.entries(n.schema.properties??{}))s.push({in:e,name:o,schema:a});o.parameters=s}return{docs:o,components:n.components}}export{s as g,e as u};
@@ -0,0 +1 @@
1
+ export * from "./src\\valibot";
package/valibot.cjs.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var e=require("@hono/valibot-validator"),a=require("@openapi-contrib/json-schema-to-openapi-schema"),r=require("@valibot/to-json-schema"),o=require("valibot"),i=require("./utils.cjs.js");function t(e){return{builder:async o=>({schema:await a(r.toJsonSchema(e))}),validator:async a=>{await o.parseAsync(e,a)}}}exports.resolver=t,exports.validator=function(a,r,o){const s=e.vValidator(a,r,o);return Object.assign(s,{[i.uniqueSymbol]:{resolver:async e=>i.generateValidatorDocs(a,await t(r).builder(e))}})};
@@ -0,0 +1 @@
1
+ export * from "./src\\valibot";
package/valibot.esm.js ADDED
@@ -0,0 +1 @@
1
+ import{vValidator as o}from"@hono/valibot-validator";import a from"@openapi-contrib/json-schema-to-openapi-schema";import{toJsonSchema as t}from"@valibot/to-json-schema";import{parseAsync as i}from"valibot";import{u as r,g as s}from"./utils.esm.js";function n(o){return{builder:async i=>({schema:await a(t(o))}),validator:async a=>{await i(o,a)}}}function e(a,t,i){const e=o(a,t,i);return Object.assign(e,{[r]:{resolver:async o=>s(a,await n(t).builder(o))}})}export{n as resolver,e as validator};
package/zod.cjs.d.ts CHANGED
@@ -1 +1 @@
1
- export * from "./src/zod";
1
+ export * from "./src\\zod";
package/zod.cjs.js CHANGED
@@ -1 +1 @@
1
- "use strict";var e=require("@hono/zod-validator"),o=require("zod-openapi"),s=require("./constants.cjs.js");function n(e){return{builder:s=>o.createSchema(e,s?{openapi:s.version,components:s.components}:void 0),validator:e.parse}}exports.resolver=n,exports.validator=function(o,r,t){const a=e.zValidator(o,r,t);return Object.assign(a,{[s.uniqueSymbol]:{resolver:e=>{const s=n(r).builder(e),t={};if("form"===o||"json"===o)t.requestBody={content:{["json"===o?"application/json":"application/x-www-form-urlencoded"]:{schema:s.schema}}};else{const e=[];if("$ref"in s.schema)e.push({in:o,name:s.schema.$ref,schema:s.schema});else for(const[n,r]of Object.entries(s.schema.properties??{}))e.push({in:o,name:n,schema:r});t.parameters=e}return{docs:t,components:s.components}},metadata:{schemaType:"input"}}})};
1
+ "use strict";var e=require("@hono/zod-validator"),r=require("zod-openapi"),a=require("./utils.cjs.js");function t(e){return{builder:a=>{const{version:t,...o}=a??{};return r.createSchema(e,a?{openapi:t,...o}:void 0)},validator:e.parse}}exports.resolver=t,exports.validator=function(r,o,i){const n=e.zValidator(r,o,i);return Object.assign(n,{[a.uniqueSymbol]:{resolver:async e=>a.generateValidatorDocs(r,await t(o).builder(e)),metadata:{schemaType:"input"}}})};
package/zod.esm.d.ts CHANGED
@@ -1 +1 @@
1
- export * from "./src/zod";
1
+ export * from "./src\\zod";
package/zod.esm.js CHANGED
@@ -1 +1 @@
1
- import{zValidator as e}from"@hono/zod-validator";import{createSchema as o}from"zod-openapi";import{u as n}from"./constants.esm.js";function s(e){return{builder:n=>o(e,n?{openapi:n.version,components:n.components}:void 0),validator:e.parse}}function t(o,t,r){const a=e(o,t,r);return Object.assign(a,{[n]:{resolver:e=>{const n=s(t).builder(e),r={};if("form"===o||"json"===o)r.requestBody={content:{["json"===o?"application/json":"application/x-www-form-urlencoded"]:{schema:n.schema}}};else{const e=[];if("$ref"in n.schema)e.push({in:o,name:n.schema.$ref,schema:n.schema});else for(const[s,t]of Object.entries(n.schema.properties??{}))e.push({in:o,name:s,schema:t});r.parameters=e}return{docs:r,components:n.components}},metadata:{schemaType:"input"}}})}export{s as resolver,t as validator};
1
+ import{zValidator as o}from"@hono/zod-validator";import{createSchema as r}from"zod-openapi";import{u as t,g as a}from"./utils.esm.js";function e(o){return{builder:t=>{const{version:a,...e}=t??{};return r(o,t?{openapi:a,...e}:void 0)},validator:o.parse}}function i(r,i,n){const s=o(r,i,n);return Object.assign(s,{[t]:{resolver:async o=>a(r,await e(i).builder(o)),metadata:{schemaType:"input"}}})}export{e as resolver,i as validator};
package/constants.cjs.js DELETED
@@ -1 +0,0 @@
1
- "use strict";const o=Symbol("openapi");exports.uniqueSymbol=o;
package/constants.esm.js DELETED
@@ -1 +0,0 @@
1
- const o=Symbol("openapi");export{o as u};
@@ -1 +0,0 @@
1
- export declare const uniqueSymbol: unique symbol;