hono-openapi 0.1.5 → 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/README.md +61 -3
- package/arktype.cjs.d.ts +1 -0
- package/arktype.cjs.js +11 -0
- package/arktype.esm.d.ts +1 -0
- package/arktype.esm.js +8 -0
- package/index.cjs.js +13 -1
- package/index.cjs2.js +9 -0
- package/index.esm.js +10 -1
- package/index.esm2.js +7 -0
- package/package.json +70 -14
- package/src/arktype.d.ts +24 -0
- package/src/helper.d.ts +13 -0
- package/src/index.d.ts +1 -0
- package/src/openapi.d.ts +3 -2
- package/src/route.d.ts +2 -32
- 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/src/typebox.d.ts +13 -0
- package/src/types.d.ts +19 -10
- package/src/utils.d.ts +24 -12
- package/src/valibot.d.ts +23 -0
- package/src/zod.d.ts +2 -4
- package/typebox.cjs.d.ts +1 -0
- package/typebox.cjs.js +12 -0
- package/typebox.esm.d.ts +1 -0
- package/typebox.esm.js +9 -0
- package/utils.cjs.js +6 -0
- package/utils.esm.js +3 -0
- package/valibot.cjs.d.ts +1 -0
- package/valibot.cjs.js +13 -0
- package/valibot.esm.d.ts +1 -0
- package/valibot.esm.js +10 -0
- package/zod.cjs.js +10 -1
- package/zod.esm.js +7 -1
- package/constants.cjs.js +0 -1
- package/constants.esm.js +0 -1
- package/src/constants.d.ts +0 -1
package/README.md
CHANGED
|
@@ -9,8 +9,9 @@ This can automatically generate the OpenAPI specification for the Hono API using
|
|
|
9
9
|
Supported Validation Libraries:
|
|
10
10
|
|
|
11
11
|
- [x] [Zod](https://zod.dev/)
|
|
12
|
-
- [
|
|
13
|
-
- [
|
|
12
|
+
- [x] [Valibot](https://valibot.dev/)
|
|
13
|
+
- [x] [ArkType](https://arktype.io/)
|
|
14
|
+
- [x] [TypeBox](https://github.com/sinclairzx81/typebox)
|
|
14
15
|
|
|
15
16
|
> [!Note]
|
|
16
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.
|
|
@@ -21,8 +22,28 @@ Supported Validation Libraries:
|
|
|
21
22
|
|
|
22
23
|
You can install the package using favorite package manager.
|
|
23
24
|
|
|
25
|
+
#### For Zod
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pnpm add hono-openapi @hono/zod-validator zod zod-openapi
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
#### For Valibot
|
|
32
|
+
|
|
24
33
|
```bash
|
|
25
|
-
pnpm add hono-openapi
|
|
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"
|
|
26
47
|
```
|
|
27
48
|
|
|
28
49
|
### Basic Usage
|
|
@@ -170,6 +191,43 @@ app.get(
|
|
|
170
191
|
);
|
|
171
192
|
```
|
|
172
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
|
+
|
|
173
231
|
## Contributing
|
|
174
232
|
|
|
175
233
|
We would love to have more contributors involved!
|
package/arktype.cjs.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./src/arktype";
|
package/arktype.cjs.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
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
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./src/arktype";
|
package/arktype.esm.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
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.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.js
CHANGED
|
@@ -1 +1,10 @@
|
|
|
1
|
-
import
|
|
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,11 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hono-openapi",
|
|
3
3
|
"description": "OpenAPI schema generator for Hono",
|
|
4
|
-
"version": "0.1
|
|
4
|
+
"version": "0.2.1",
|
|
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,83 @@
|
|
|
14
18
|
"repository": {
|
|
15
19
|
"type": "git",
|
|
16
20
|
"url": "git+https://github.com/rhinobase/hono-openapi.git",
|
|
17
|
-
"directory": "packages/
|
|
21
|
+
"directory": "packages/core"
|
|
18
22
|
},
|
|
19
23
|
"bugs": {
|
|
20
24
|
"url": "https://github.com/rhinobase/hono-openapi/issues"
|
|
21
25
|
},
|
|
22
|
-
"
|
|
23
|
-
"
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"json-schema-walker": "^2.0.0"
|
|
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": "^
|
|
27
|
-
"openapi-types": "^12.1.3"
|
|
41
|
+
"zod-openapi": "^4.0.0"
|
|
28
42
|
},
|
|
29
43
|
"devDependencies": {
|
|
30
|
-
"@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"
|
|
31
47
|
},
|
|
32
48
|
"exports": {
|
|
33
49
|
".": {
|
|
34
|
-
"import":
|
|
35
|
-
|
|
36
|
-
|
|
50
|
+
"import": {
|
|
51
|
+
"default": "./index.esm.js",
|
|
52
|
+
"types": "./index.esm.d.ts"
|
|
53
|
+
},
|
|
54
|
+
"require": {
|
|
55
|
+
"default": "./index.cjs.js",
|
|
56
|
+
"types": "./index.cjs.d.ts"
|
|
57
|
+
}
|
|
37
58
|
},
|
|
38
59
|
"./zod": {
|
|
39
|
-
"import":
|
|
40
|
-
|
|
41
|
-
|
|
60
|
+
"import": {
|
|
61
|
+
"default": "./zod.esm.js",
|
|
62
|
+
"types": "./zod.esm.d.ts"
|
|
63
|
+
},
|
|
64
|
+
"require": {
|
|
65
|
+
"default": "./zod.cjs.js",
|
|
66
|
+
"types": "./zod.cjs.d.ts"
|
|
67
|
+
}
|
|
68
|
+
},
|
|
69
|
+
"./valibot": {
|
|
70
|
+
"import": {
|
|
71
|
+
"default": "./valibot.esm.js",
|
|
72
|
+
"types": "./valibot.esm.d.ts"
|
|
73
|
+
},
|
|
74
|
+
"require": {
|
|
75
|
+
"default": "./valibot.cjs.js",
|
|
76
|
+
"types": "./valibot.cjs.d.ts"
|
|
77
|
+
}
|
|
78
|
+
},
|
|
79
|
+
"./typebox": {
|
|
80
|
+
"import": {
|
|
81
|
+
"default": "./typebox.esm.js",
|
|
82
|
+
"types": "./typebox.esm.d.ts"
|
|
83
|
+
},
|
|
84
|
+
"require": {
|
|
85
|
+
"default": "./typebox.cjs.js",
|
|
86
|
+
"types": "./typebox.cjs.d.ts"
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
"./arktype": {
|
|
90
|
+
"import": {
|
|
91
|
+
"default": "./arktype.esm.js",
|
|
92
|
+
"types": "./arktype.esm.d.ts"
|
|
93
|
+
},
|
|
94
|
+
"require": {
|
|
95
|
+
"default": "./arktype.cjs.js",
|
|
96
|
+
"types": "./arktype.cjs.d.ts"
|
|
97
|
+
}
|
|
42
98
|
}
|
|
43
99
|
},
|
|
44
100
|
"module": "./index.esm.js",
|
package/src/arktype.d.ts
ADDED
|
@@ -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>;
|
package/src/helper.d.ts
ADDED
|
@@ -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
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
|
|
3
|
-
|
|
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 @@
|
|
|
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/src/typebox.d.ts
ADDED
|
@@ -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,5 +1,9 @@
|
|
|
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 "./
|
|
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"];
|
|
@@ -7,35 +11,40 @@ export type OpenAPIRouteHandlerConfig = {
|
|
|
7
11
|
[key: string]: unknown;
|
|
8
12
|
};
|
|
9
13
|
export type ResolverResult = {
|
|
10
|
-
builder: (options?: OpenAPIRouteHandlerConfig) => {
|
|
14
|
+
builder: (options?: OpenAPIRouteHandlerConfig) => PromiseOr<{
|
|
11
15
|
schema: OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject;
|
|
12
16
|
components?: OpenAPIV3.ComponentsObject["schemas"];
|
|
13
|
-
}
|
|
14
|
-
validator: (values: unknown) =>
|
|
17
|
+
}>;
|
|
18
|
+
validator: (values: unknown) => PromiseOr<void>;
|
|
15
19
|
};
|
|
16
20
|
export type HandlerResponse = {
|
|
17
|
-
resolver: (config: OpenAPIRouteHandlerConfig) => {
|
|
21
|
+
resolver: (config: OpenAPIRouteHandlerConfig) => PromiseOr<{
|
|
18
22
|
docs: OpenAPIV3.OperationObject;
|
|
19
23
|
components?: OpenAPIV3.ComponentsObject["schemas"];
|
|
20
|
-
}
|
|
24
|
+
}>;
|
|
21
25
|
metadata?: Record<string, unknown>;
|
|
22
26
|
};
|
|
23
|
-
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"> & {
|
|
24
28
|
/**
|
|
25
29
|
* Pass `true` to hide route from OpenAPI/swagger document
|
|
26
30
|
*/
|
|
27
|
-
hide?: boolean;
|
|
31
|
+
hide?: boolean | ((c: Context<E, P, I>) => boolean);
|
|
32
|
+
/**
|
|
33
|
+
* Validate response of the route
|
|
34
|
+
* @experimental
|
|
35
|
+
*/
|
|
36
|
+
validateResponse?: boolean;
|
|
28
37
|
/**
|
|
29
38
|
* Responses of the request
|
|
30
39
|
*/
|
|
31
40
|
responses?: {
|
|
32
|
-
[key: string]: OpenAPIV3.ResponseObject & {
|
|
41
|
+
[key: string]: (OpenAPIV3.ResponseObject & {
|
|
33
42
|
content?: {
|
|
34
43
|
[key: string]: Omit<OpenAPIV3.MediaTypeObject, "schema"> & {
|
|
35
44
|
schema?: OpenAPIV3.ReferenceObject | OpenAPIV3.SchemaObject | ResolverResult;
|
|
36
45
|
};
|
|
37
46
|
};
|
|
38
|
-
};
|
|
47
|
+
}) | OpenAPIV3.ReferenceObject;
|
|
39
48
|
};
|
|
40
49
|
};
|
|
41
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 {
|
|
3
|
-
export declare const
|
|
4
|
-
export declare
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
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
|
+
}>;
|
package/src/valibot.d.ts
ADDED
|
@@ -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 {};
|
package/typebox.cjs.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./src/typebox";
|
package/typebox.cjs.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
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
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./src/typebox";
|
package/typebox.esm.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
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
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
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
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
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
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./src/valibot";
|
package/valibot.cjs.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
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
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./src/valibot";
|
package/valibot.esm.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
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.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.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 };
|
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};
|
package/src/constants.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const uniqueSymbol: unique symbol;
|