@sdk-it/hono 0.5.0 → 0.6.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/README.md +203 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +173 -1
- package/dist/index.js.map +3 -3
- package/package.json +2 -2
package/README.md
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
# @sdk-it/hono
|
|
2
|
+
|
|
3
|
+
Hono framework integration for SDK-IT that provides type-safe request validation and standardized response handling.
|
|
4
|
+
|
|
5
|
+
To learn more about SDK code generation, see the [TypeScript Doc](../typescript/readme.md)
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
npm install @sdk-it/{hono,generic}
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Runtime Primitives
|
|
14
|
+
|
|
15
|
+
You can use these functions without the SDK-IT code generation tools, they're completely separate and functional on their own.
|
|
16
|
+
|
|
17
|
+
### Validator Middleware
|
|
18
|
+
|
|
19
|
+
The validator middleware offers type-safe request validation using [Zod](https://github.com/colinhacks/zod) schemas. It automatically validates incoming requests against your defined schemas and provides typed inputs to your handlers.
|
|
20
|
+
|
|
21
|
+
> ![IMPORTANT]
|
|
22
|
+
> For openapi generation to work correctly, you must use the `validate` middleware for each route.
|
|
23
|
+
|
|
24
|
+
```typescript
|
|
25
|
+
import { validate } from '@sdk-it/hono';
|
|
26
|
+
|
|
27
|
+
app.post(
|
|
28
|
+
'/books',
|
|
29
|
+
validate((payload) => ({
|
|
30
|
+
// Query parameter validation
|
|
31
|
+
page: {
|
|
32
|
+
select: payload.query.page,
|
|
33
|
+
against: z.number().min(1).default(1),
|
|
34
|
+
},
|
|
35
|
+
|
|
36
|
+
// Multiple query parameters (array)
|
|
37
|
+
categories: {
|
|
38
|
+
select: payload.queries.category,
|
|
39
|
+
against: z.array(z.string()),
|
|
40
|
+
},
|
|
41
|
+
|
|
42
|
+
// Body property validation
|
|
43
|
+
title: {
|
|
44
|
+
select: payload.body.title,
|
|
45
|
+
against: z.string().min(1),
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
author: {
|
|
49
|
+
select: payload.body.author,
|
|
50
|
+
against: z.string().min(1),
|
|
51
|
+
},
|
|
52
|
+
|
|
53
|
+
// For nested objects in body
|
|
54
|
+
metadata: {
|
|
55
|
+
select: payload.body.metadata,
|
|
56
|
+
against: z.object({
|
|
57
|
+
isbn: z.string(),
|
|
58
|
+
publishedYear: z.number(),
|
|
59
|
+
}),
|
|
60
|
+
},
|
|
61
|
+
|
|
62
|
+
// URL parameter validation
|
|
63
|
+
userId: {
|
|
64
|
+
select: payload.params.userId,
|
|
65
|
+
against: z.string().uuid(),
|
|
66
|
+
},
|
|
67
|
+
|
|
68
|
+
// Header validation
|
|
69
|
+
apiKey: {
|
|
70
|
+
select: payload.headers['x-api-key'],
|
|
71
|
+
against: z.string().min(32),
|
|
72
|
+
},
|
|
73
|
+
})),
|
|
74
|
+
(c) => {
|
|
75
|
+
// TypeScript knows the shape of all inputs
|
|
76
|
+
const { page, categories, title, author, metadata, userId, apiKey } =
|
|
77
|
+
c.var.input;
|
|
78
|
+
return c.json({ success: true });
|
|
79
|
+
},
|
|
80
|
+
);
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### Response Helper
|
|
84
|
+
|
|
85
|
+
The output function provides a clean API for sending HTTP responses with proper status codes and content types. It automatically handles JSON serialization and content type headers.
|
|
86
|
+
|
|
87
|
+
> ![NOTE]
|
|
88
|
+
> You don't necessarily need to use this function for OpenAPI generation, but it provides a clean and consistent way to send responses.
|
|
89
|
+
|
|
90
|
+
```typescript
|
|
91
|
+
import { createOutput } from '@sdk-it/hono';
|
|
92
|
+
|
|
93
|
+
const output = createOutput(() => c);
|
|
94
|
+
|
|
95
|
+
// Success responses
|
|
96
|
+
output.ok({ data: 'success' });
|
|
97
|
+
output.accepted({ status: 'processing' });
|
|
98
|
+
|
|
99
|
+
// Error responses
|
|
100
|
+
output.badRequest({ error: 'Invalid input' });
|
|
101
|
+
output.unauthorized({ error: 'Not authenticated' });
|
|
102
|
+
output.forbidden({ error: 'Not authorized' });
|
|
103
|
+
output.notImplemented({ error: 'Coming soon' });
|
|
104
|
+
|
|
105
|
+
// Redirects
|
|
106
|
+
output.redirect('/new-location');
|
|
107
|
+
|
|
108
|
+
// Custom headers
|
|
109
|
+
output.ok({ data: 'success' }, { 'Cache-Control': 'max-age=3600' });
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## OpenAPI Generation
|
|
113
|
+
|
|
114
|
+
SDK-IT relies on the aforementioned primitives and JSDoc tags to correctly infer each route specification.
|
|
115
|
+
|
|
116
|
+
Consider the following example:
|
|
117
|
+
|
|
118
|
+
- Create hono routes with the `@openapi` tag and validate middleware.
|
|
119
|
+
|
|
120
|
+
```typescript
|
|
121
|
+
import z from 'zod';
|
|
122
|
+
|
|
123
|
+
import { validate } from '@sdk-it/hono';
|
|
124
|
+
|
|
125
|
+
const app = new Hono();
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* @openapi listBooks
|
|
129
|
+
* @tags books
|
|
130
|
+
*/
|
|
131
|
+
app.get(
|
|
132
|
+
'/books',
|
|
133
|
+
validate((payload) => ({
|
|
134
|
+
author: {
|
|
135
|
+
select: payload.query.author,
|
|
136
|
+
against: z.string(),
|
|
137
|
+
},
|
|
138
|
+
})),
|
|
139
|
+
async (c) => {
|
|
140
|
+
const books = [{ name: 'OpenAPI' }];
|
|
141
|
+
return c.json(books);
|
|
142
|
+
},
|
|
143
|
+
);
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
- Use the generate fn to create an OpenAPI spec from your routes.
|
|
147
|
+
|
|
148
|
+
```typescript
|
|
149
|
+
import { join } from 'node:path';
|
|
150
|
+
|
|
151
|
+
import { analyze } from '@sdk-it/generic';
|
|
152
|
+
// Use responseAnalyzer from `@sdk-it/hono`
|
|
153
|
+
// only if you use hono context object to send response
|
|
154
|
+
// e.g. c.json({ data: 'success' });
|
|
155
|
+
import { responseAnalyzer } from '@sdk-it/hono';
|
|
156
|
+
// Use responseAnalyzer from `@sdk-it/generic`
|
|
157
|
+
// only if you use the output function to send response
|
|
158
|
+
// e.g. output.ok({ data: 'success' });
|
|
159
|
+
// import { responseAnalyzer } from '@sdk-it/generic';
|
|
160
|
+
|
|
161
|
+
import { generate } from '@sdk-it/typescript';
|
|
162
|
+
|
|
163
|
+
const { paths, components } = await analyze('apps/backend/tsconfig.app.json', {
|
|
164
|
+
responseAnalyzer,
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
// Now you can use the generated specification to create an SDK or save it to a file
|
|
168
|
+
const spec = {
|
|
169
|
+
info: {
|
|
170
|
+
title: 'My API',
|
|
171
|
+
version: '1.0.0',
|
|
172
|
+
},
|
|
173
|
+
paths,
|
|
174
|
+
components,
|
|
175
|
+
};
|
|
176
|
+
await generate(spec, {
|
|
177
|
+
output: join(process.cwd(), './client'),
|
|
178
|
+
});
|
|
179
|
+
```
|
|
180
|
+
|
|
181
|
+
> [!TIP]
|
|
182
|
+
> See [typescript](../typescript/README.md) for more info.
|
|
183
|
+
|
|
184
|
+
- Use the client
|
|
185
|
+
|
|
186
|
+
```typescript
|
|
187
|
+
import { Client } from './client';
|
|
188
|
+
|
|
189
|
+
const client = new Client({
|
|
190
|
+
baseUrl: 'http://localhost:3000',
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
const [books, error] = await client.request('GET /books', {
|
|
194
|
+
author: 'John Doe',
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
// Check for errors
|
|
198
|
+
if (error) {
|
|
199
|
+
console.error('Error fetching books:', error);
|
|
200
|
+
} else {
|
|
201
|
+
console.log('Books retrieved:', books);
|
|
202
|
+
}
|
|
203
|
+
```
|
package/dist/index.d.ts
CHANGED
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,4BAA4B,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,4BAA4B,CAAC;AAC3C,cAAc,yBAAyB,CAAC;AACxC,cAAc,4BAA4B,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -44,7 +44,179 @@ function resolveStatusCode(node) {
|
|
|
44
44
|
function responseAnalyzer(handler, deriver) {
|
|
45
45
|
return toResponses(handler, deriver);
|
|
46
46
|
}
|
|
47
|
+
|
|
48
|
+
// packages/hono/src/lib/runtime/output.ts
|
|
49
|
+
import { getContext } from "hono/context-storage";
|
|
50
|
+
function send(context, value, status, headers) {
|
|
51
|
+
if (value === void 0 || value === null) {
|
|
52
|
+
return context.body(null, status, headers);
|
|
53
|
+
}
|
|
54
|
+
const responseHeaders = { ...headers };
|
|
55
|
+
responseHeaders["Content-Type"] ??= "application/json";
|
|
56
|
+
if (responseHeaders["Content-Type"].includes("application/json")) {
|
|
57
|
+
return context.body(JSON.stringify(value), status, responseHeaders);
|
|
58
|
+
}
|
|
59
|
+
return context.body(value, status, responseHeaders);
|
|
60
|
+
}
|
|
61
|
+
function createOutput(contextFn) {
|
|
62
|
+
return {
|
|
63
|
+
nocontent() {
|
|
64
|
+
const context = contextFn();
|
|
65
|
+
return context.body(null, 204, {});
|
|
66
|
+
},
|
|
67
|
+
ok(value, headers) {
|
|
68
|
+
return send(contextFn(), value, 200, headers);
|
|
69
|
+
},
|
|
70
|
+
created(valueOrUri, value, headers) {
|
|
71
|
+
if (typeof valueOrUri === "string") {
|
|
72
|
+
return send(contextFn(), value, 201, {
|
|
73
|
+
Location: valueOrUri,
|
|
74
|
+
...headers || {}
|
|
75
|
+
});
|
|
76
|
+
} else {
|
|
77
|
+
return send(contextFn(), valueOrUri, 201, headers);
|
|
78
|
+
}
|
|
79
|
+
},
|
|
80
|
+
redirect(uri, statusCode) {
|
|
81
|
+
const context = contextFn();
|
|
82
|
+
return context.redirect(
|
|
83
|
+
uri.toString(),
|
|
84
|
+
statusCode ?? void 0
|
|
85
|
+
);
|
|
86
|
+
},
|
|
87
|
+
attachment(buffer, filename, mimeType) {
|
|
88
|
+
const context = contextFn();
|
|
89
|
+
return context.body(buffer, 200, {
|
|
90
|
+
"Content-Type": mimeType,
|
|
91
|
+
"Content-Disposition": `attachment; filename="${filename}"`,
|
|
92
|
+
"Content-Length": buffer.length.toString()
|
|
93
|
+
});
|
|
94
|
+
},
|
|
95
|
+
badRequest(value, headers) {
|
|
96
|
+
return send(contextFn(), value, 400, headers);
|
|
97
|
+
},
|
|
98
|
+
unauthorized(value, headers) {
|
|
99
|
+
return send(contextFn(), value, 401, headers);
|
|
100
|
+
},
|
|
101
|
+
forbidden(value, headers) {
|
|
102
|
+
return send(contextFn(), value, 403, headers);
|
|
103
|
+
},
|
|
104
|
+
notFound(value, headers) {
|
|
105
|
+
return send(contextFn(), value, 404, headers);
|
|
106
|
+
},
|
|
107
|
+
notImplemented(value, headers) {
|
|
108
|
+
return send(contextFn(), value, 501, headers);
|
|
109
|
+
},
|
|
110
|
+
accepted(value, headers) {
|
|
111
|
+
return send(contextFn(), value, 202, headers);
|
|
112
|
+
},
|
|
113
|
+
conflict(value, headers) {
|
|
114
|
+
return send(contextFn(), value, 409, headers);
|
|
115
|
+
},
|
|
116
|
+
unprocessableEntity(value, headers) {
|
|
117
|
+
return send(contextFn(), value, 422, headers);
|
|
118
|
+
},
|
|
119
|
+
internalServerError(value, headers) {
|
|
120
|
+
return send(contextFn(), value, 500, headers);
|
|
121
|
+
},
|
|
122
|
+
serviceUnavailable(value, headers) {
|
|
123
|
+
return send(contextFn(), value, 503, headers);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
var output = createOutput(() => getContext());
|
|
128
|
+
|
|
129
|
+
// packages/hono/src/lib/runtime/validator.ts
|
|
130
|
+
import { createMiddleware } from "hono/factory";
|
|
131
|
+
import { HTTPException } from "hono/http-exception";
|
|
132
|
+
import z from "zod";
|
|
133
|
+
var validate = (selector) => {
|
|
134
|
+
return createMiddleware(async (c, next) => {
|
|
135
|
+
const contentType = c.req.header("content-type") ?? "";
|
|
136
|
+
let body = null;
|
|
137
|
+
switch (contentType) {
|
|
138
|
+
case "application/json":
|
|
139
|
+
body = await c.req.json();
|
|
140
|
+
break;
|
|
141
|
+
case "application/x-www-form-urlencoded":
|
|
142
|
+
body = await c.req.parseBody();
|
|
143
|
+
break;
|
|
144
|
+
default:
|
|
145
|
+
body = {};
|
|
146
|
+
}
|
|
147
|
+
const payload = {
|
|
148
|
+
body,
|
|
149
|
+
query: c.req.query(),
|
|
150
|
+
queries: c.req.queries(),
|
|
151
|
+
params: c.req.param(),
|
|
152
|
+
headers: Object.fromEntries(
|
|
153
|
+
Object.entries(c.req.header()).map(([k, v]) => [k, v ?? ""])
|
|
154
|
+
)
|
|
155
|
+
};
|
|
156
|
+
const config = selector(payload);
|
|
157
|
+
const schema = z.object(
|
|
158
|
+
Object.entries(config).reduce(
|
|
159
|
+
(acc, [key, value]) => {
|
|
160
|
+
acc[key] = value.against;
|
|
161
|
+
return acc;
|
|
162
|
+
},
|
|
163
|
+
{}
|
|
164
|
+
)
|
|
165
|
+
);
|
|
166
|
+
const input = Object.entries(config).reduce(
|
|
167
|
+
(acc, [key, value]) => {
|
|
168
|
+
acc[key] = value.select;
|
|
169
|
+
return acc;
|
|
170
|
+
},
|
|
171
|
+
{}
|
|
172
|
+
);
|
|
173
|
+
const parsed = parse(schema, input);
|
|
174
|
+
c.set("input", parsed);
|
|
175
|
+
await next();
|
|
176
|
+
});
|
|
177
|
+
};
|
|
178
|
+
function parse(schema, input) {
|
|
179
|
+
const result = schema.safeParse(input);
|
|
180
|
+
if (!result.success) {
|
|
181
|
+
const error = new HTTPException(400, {
|
|
182
|
+
message: "Validation failed",
|
|
183
|
+
cause: {
|
|
184
|
+
code: "api/validation-failed",
|
|
185
|
+
details: result.error.flatten((issue) => ({
|
|
186
|
+
message: issue.message,
|
|
187
|
+
code: issue.code,
|
|
188
|
+
fatel: issue.fatal,
|
|
189
|
+
path: issue.path.join(".")
|
|
190
|
+
})).fieldErrors
|
|
191
|
+
}
|
|
192
|
+
});
|
|
193
|
+
throw error;
|
|
194
|
+
}
|
|
195
|
+
return result.data;
|
|
196
|
+
}
|
|
197
|
+
var openapi = validate;
|
|
198
|
+
var consume = (contentType) => {
|
|
199
|
+
return createMiddleware(async (context, next) => {
|
|
200
|
+
const clientContentType = context.req.header("Content-Type");
|
|
201
|
+
if (clientContentType !== contentType) {
|
|
202
|
+
throw new HTTPException(415, {
|
|
203
|
+
message: "Unsupported Media Type",
|
|
204
|
+
cause: {
|
|
205
|
+
code: "api/unsupported-media-type",
|
|
206
|
+
details: `Expected content type: ${contentType}, but got: ${clientContentType}`
|
|
207
|
+
}
|
|
208
|
+
});
|
|
209
|
+
}
|
|
210
|
+
await next();
|
|
211
|
+
});
|
|
212
|
+
};
|
|
47
213
|
export {
|
|
48
|
-
|
|
214
|
+
consume,
|
|
215
|
+
createOutput,
|
|
216
|
+
openapi,
|
|
217
|
+
output,
|
|
218
|
+
parse,
|
|
219
|
+
responseAnalyzer,
|
|
220
|
+
validate
|
|
49
221
|
};
|
|
50
222
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/lib/response-analyzer.ts"],
|
|
4
|
-
"sourcesContent": ["import debug from 'debug';\nimport ts from 'typescript';\n\nimport type { ResponseItem, TypeDeriver } from '@sdk-it/core';\n\nconst logger = debug('@sdk-it/hono');\n\nconst handlerVisitor: (\n on: (\n node: ts.Node,\n statusCode: ts.Node | undefined,\n headers: ts.Node | undefined,\n contentType: string,\n ) => void,\n contextVarName: string,\n) => ts.Visitor = (callback, contextVarName) => {\n return (node: ts.Node) => {\n if (ts.isReturnStatement(node) && node.expression) {\n if (\n ts.isCallExpression(node.expression) &&\n ts.isPropertyAccessExpression(node.expression.expression)\n ) {\n const propAccess = node.expression.expression;\n if (\n ts.isIdentifier(propAccess.expression) &&\n propAccess.expression.text === contextVarName\n ) {\n let contentType = 'application/json';\n const callerMethod = propAccess.name.text;\n if (callerMethod === 'body') {\n contentType = 'application/octet-stream';\n }\n const [body, statusCode, headers] = node.expression.arguments;\n callback(body, statusCode, headers, contentType);\n }\n }\n }\n return ts.forEachChild(node, handlerVisitor(callback, contextVarName));\n };\n};\n\nfunction toResponses(handler: ts.ArrowFunction, deriver: TypeDeriver) {\n const contextVarName = handler.parameters[0].name.getText();\n const responsesList: ResponseItem[] = [];\n const visit = handlerVisitor((node, statusCode, headers, contentType) => {\n responsesList.push({\n headers: headers ? Object.keys(deriver.serializeNode(headers)) : [],\n contentType,\n statusCode: statusCode ? resolveStatusCode(statusCode) : '200',\n response: deriver.serializeNode(node),\n });\n }, contextVarName);\n visit(handler.body);\n return responsesList;\n}\n\nfunction resolveStatusCode(node: ts.Node) {\n if (ts.isNumericLiteral(node)) {\n return node.text;\n }\n throw new Error(`Could not resolve status code`);\n}\n\nexport function responseAnalyzer(\n handler: ts.ArrowFunction,\n deriver: TypeDeriver,\n) {\n return toResponses(handler, deriver);\n}\n"],
|
|
5
|
-
"mappings": ";AAAA,OAAO,WAAW;AAClB,OAAO,QAAQ;AAIf,IAAM,SAAS,MAAM,cAAc;AAEnC,IAAM,iBAQY,CAAC,UAAU,mBAAmB;AAC9C,SAAO,CAAC,SAAkB;AACxB,QAAI,GAAG,kBAAkB,IAAI,KAAK,KAAK,YAAY;AACjD,UACE,GAAG,iBAAiB,KAAK,UAAU,KACnC,GAAG,2BAA2B,KAAK,WAAW,UAAU,GACxD;AACA,cAAM,aAAa,KAAK,WAAW;AACnC,YACE,GAAG,aAAa,WAAW,UAAU,KACrC,WAAW,WAAW,SAAS,gBAC/B;AACA,cAAI,cAAc;AAClB,gBAAM,eAAe,WAAW,KAAK;AACrC,cAAI,iBAAiB,QAAQ;AAC3B,0BAAc;AAAA,UAChB;AACA,gBAAM,CAAC,MAAM,YAAY,OAAO,IAAI,KAAK,WAAW;AACpD,mBAAS,MAAM,YAAY,SAAS,WAAW;AAAA,QACjD;AAAA,MACF;AAAA,IACF;AACA,WAAO,GAAG,aAAa,MAAM,eAAe,UAAU,cAAc,CAAC;AAAA,EACvE;AACF;AAEA,SAAS,YAAY,SAA2B,SAAsB;AACpE,QAAM,iBAAiB,QAAQ,WAAW,CAAC,EAAE,KAAK,QAAQ;AAC1D,QAAM,gBAAgC,CAAC;AACvC,QAAM,QAAQ,eAAe,CAAC,MAAM,YAAY,SAAS,gBAAgB;AACvE,kBAAc,KAAK;AAAA,MACjB,SAAS,UAAU,OAAO,KAAK,QAAQ,cAAc,OAAO,CAAC,IAAI,CAAC;AAAA,MAClE;AAAA,MACA,YAAY,aAAa,kBAAkB,UAAU,IAAI;AAAA,MACzD,UAAU,QAAQ,cAAc,IAAI;AAAA,IACtC,CAAC;AAAA,EACH,GAAG,cAAc;AACjB,QAAM,QAAQ,IAAI;AAClB,SAAO;AACT;AAEA,SAAS,kBAAkB,MAAe;AACxC,MAAI,GAAG,iBAAiB,IAAI,GAAG;AAC7B,WAAO,KAAK;AAAA,EACd;AACA,QAAM,IAAI,MAAM,+BAA+B;AACjD;AAEO,SAAS,iBACd,SACA,SACA;AACA,SAAO,YAAY,SAAS,OAAO;AACrC;",
|
|
3
|
+
"sources": ["../src/lib/response-analyzer.ts", "../src/lib/runtime/output.ts", "../src/lib/runtime/validator.ts"],
|
|
4
|
+
"sourcesContent": ["import debug from 'debug';\nimport ts from 'typescript';\n\nimport type { ResponseItem, TypeDeriver } from '@sdk-it/core';\n\nconst logger = debug('@sdk-it/hono');\n\nconst handlerVisitor: (\n on: (\n node: ts.Node,\n statusCode: ts.Node | undefined,\n headers: ts.Node | undefined,\n contentType: string,\n ) => void,\n contextVarName: string,\n) => ts.Visitor = (callback, contextVarName) => {\n return (node: ts.Node) => {\n if (ts.isReturnStatement(node) && node.expression) {\n if (\n ts.isCallExpression(node.expression) &&\n ts.isPropertyAccessExpression(node.expression.expression)\n ) {\n const propAccess = node.expression.expression;\n if (\n ts.isIdentifier(propAccess.expression) &&\n propAccess.expression.text === contextVarName\n ) {\n let contentType = 'application/json';\n const callerMethod = propAccess.name.text;\n if (callerMethod === 'body') {\n contentType = 'application/octet-stream';\n }\n const [body, statusCode, headers] = node.expression.arguments;\n callback(body, statusCode, headers, contentType);\n }\n }\n }\n return ts.forEachChild(node, handlerVisitor(callback, contextVarName));\n };\n};\n\nfunction toResponses(handler: ts.ArrowFunction, deriver: TypeDeriver) {\n const contextVarName = handler.parameters[0].name.getText();\n const responsesList: ResponseItem[] = [];\n const visit = handlerVisitor((node, statusCode, headers, contentType) => {\n responsesList.push({\n headers: headers ? Object.keys(deriver.serializeNode(headers)) : [],\n contentType,\n statusCode: statusCode ? resolveStatusCode(statusCode) : '200',\n response: deriver.serializeNode(node),\n });\n }, contextVarName);\n visit(handler.body);\n return responsesList;\n}\n\nfunction resolveStatusCode(node: ts.Node) {\n if (ts.isNumericLiteral(node)) {\n return node.text;\n }\n throw new Error(`Could not resolve status code`);\n}\n\nexport function responseAnalyzer(\n handler: ts.ArrowFunction,\n deriver: TypeDeriver,\n) {\n return toResponses(handler, deriver);\n}\n", "import type { Context } from 'hono';\nimport { getContext } from 'hono/context-storage';\nimport type {\n ContentfulStatusCode,\n RedirectStatusCode,\n} from 'hono/utils/http-status';\n\ntype Data = any;\nfunction send(\n context: Context,\n value: Data | undefined | null,\n status: ContentfulStatusCode,\n headers?: Readonly<Record<string, string>>,\n) {\n if (value === undefined || value === null) {\n return context.body(null, status, headers);\n }\n const responseHeaders = { ...headers };\n responseHeaders['Content-Type'] ??= 'application/json';\n if (responseHeaders['Content-Type'].includes('application/json')) {\n return context.body(JSON.stringify(value), status, responseHeaders);\n }\n return context.body(value, status, responseHeaders);\n}\n\nexport function createOutput(contextFn: () => Context) {\n return {\n nocontent() {\n const context = contextFn();\n return context.body(null, 204, {});\n },\n ok(value: Data | undefined | null, headers?: Record<string, string>) {\n return send(contextFn(), value, 200, headers);\n },\n created(\n valueOrUri: string | Data,\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n if (typeof valueOrUri === 'string') {\n // If no content is provided, we send null\n return send(contextFn(), value, 201, {\n Location: valueOrUri,\n ...(headers || {}),\n });\n } else {\n // valueOrUri is the data\n return send(contextFn(), valueOrUri, 201, headers);\n }\n },\n redirect(uri: string | URL, statusCode?: unknown) {\n const context = contextFn();\n return context.redirect(\n uri.toString(),\n (statusCode as RedirectStatusCode) ?? undefined,\n );\n },\n attachment(buffer: Buffer, filename: string, mimeType: string) {\n const context = contextFn();\n // https://github.com/honojs/hono/issues/3720\n return context.body(buffer as never, 200, {\n 'Content-Type': mimeType,\n 'Content-Disposition': `attachment; filename=\"${filename}\"`,\n 'Content-Length': buffer.length.toString(),\n });\n },\n badRequest(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 400, headers);\n },\n unauthorized(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 401, headers);\n },\n forbidden(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 403, headers);\n },\n notFound(value: Data | undefined | null, headers?: Record<string, string>) {\n return send(contextFn(), value, 404, headers);\n },\n notImplemented(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 501, headers);\n },\n accepted(value: Data | undefined | null, headers?: Record<string, string>) {\n return send(contextFn(), value, 202, headers);\n },\n conflict(value: Data | undefined | null, headers?: Record<string, string>) {\n return send(contextFn(), value, 409, headers);\n },\n unprocessableEntity(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 422, headers);\n },\n internalServerError(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 500, headers);\n },\n serviceUnavailable(\n value: Data | undefined | null,\n headers?: Record<string, string>,\n ) {\n return send(contextFn(), value, 503, headers);\n },\n };\n}\n\nexport const output = createOutput(() => getContext());\n", "/* eslint-disable no-unused-private-class-members */\nimport type { MiddlewareHandler, ValidationTargets } from 'hono';\nimport { createMiddleware } from 'hono/factory';\nimport { HTTPException } from 'hono/http-exception';\nimport z from 'zod';\n\ntype ValidatorConfig = Record<\n string,\n { select: unknown; against: z.ZodTypeAny; }\n>;\n\ntype ExtractInput<T extends ValidatorConfig> = {\n [K in keyof T]: z.infer<T[K]['against']>;\n};\n\ntype HasUndefined<T> = undefined extends T ? true : false;\n\ntype InferTarget<\n T extends ValidatorConfig,\n S,\n Target extends keyof ValidationTargets,\n> = {\n [K in keyof T as T[K]['select'] extends S ? K : never]: HasUndefined<\n z.infer<T[K]['against']>\n > extends true\n ? z.infer<T[K]['against']> | undefined\n : z.infer<T[K]['against']> extends ValidationTargets[Target]\n ? z.infer<T[K]['against']>\n : z.infer<T[K]['against']>;\n };\n\ntype InferIn<T extends ValidatorConfig> = (\n keyof InferTarget<T, QuerySelect | QueriesSelect, 'query'> extends never\n ? never\n : { query: InferTarget<T, QuerySelect | QueriesSelect, 'query'>; }) &\n (keyof InferTarget<T, BodySelect, 'json'> extends never\n ? never\n : { json: InferTarget<T, BodySelect, 'json'>; }) &\n (keyof InferTarget<T, ParamsSelect, 'param'> extends never\n ? never\n : { param: InferTarget<T, ParamsSelect, 'param'>; }) &\n (keyof InferTarget<T, HeadersSelect, 'header'> extends never\n ? never\n : { header: InferTarget<T, HeadersSelect, 'header'>; }) &\n (keyof InferTarget<T, CookieSelect, 'cookie'> extends never\n ? never\n : { form: InferTarget<T, CookieSelect, 'cookie'>; });\n\n// Marker classes\nclass BodySelect {\n #private = 0;\n}\nclass QuerySelect {\n #private = 0;\n}\nclass QueriesSelect {\n #private = 0;\n}\nclass ParamsSelect {\n #private = 0;\n}\nclass HeadersSelect {\n #private = 0;\n}\nclass CookieSelect {\n #private = 0;\n}\n\nexport const validate = <T extends ValidatorConfig>(\n selector: (payload: {\n body: Record<string, BodySelect>;\n query: Record<string, QuerySelect>;\n queries: Record<string, QueriesSelect>;\n params: Record<string, ParamsSelect>;\n headers: Record<string, HeadersSelect>;\n }) => T,\n): MiddlewareHandler<\n {\n Variables: {\n input: ExtractInput<T>;\n };\n },\n string,\n { in: InferIn<T>; }\n> => {\n return createMiddleware<{\n Variables: {\n input: ExtractInput<T>;\n };\n }>(async (c, next) => {\n const contentType = c.req.header('content-type') ?? '';\n let body: unknown = null;\n\n switch (contentType) {\n case 'application/json':\n body = await c.req.json();\n break;\n case 'application/x-www-form-urlencoded':\n body = await c.req.parseBody();\n break;\n default:\n body = {};\n }\n\n const payload = {\n body,\n query: c.req.query(),\n queries: c.req.queries(),\n params: c.req.param(),\n headers: Object.fromEntries(\n Object.entries(c.req.header()).map(([k, v]) => [k, v ?? '']),\n ),\n };\n\n const config = selector(payload as never);\n const schema = z.object(\n Object.entries(config).reduce(\n (acc, [key, value]) => {\n acc[key] = value.against;\n return acc;\n },\n {} as Record<string, z.ZodTypeAny>,\n ),\n );\n\n const input = Object.entries(config).reduce(\n (acc, [key, value]) => {\n acc[key] = value.select;\n return acc;\n },\n {} as Record<string, unknown>,\n );\n\n const parsed = parse(schema, input);\n c.set('input', parsed as ExtractInput<T>);\n await next();\n });\n};\n\nexport function parse<T extends z.ZodRawShape>(\n schema: z.ZodObject<T>,\n input: unknown,\n) {\n const result = schema.safeParse(input);\n if (!result.success) {\n const error = new HTTPException(400, {\n message: 'Validation failed',\n cause: {\n code: 'api/validation-failed',\n details: result.error.flatten((issue) => ({\n message: issue.message,\n code: issue.code,\n fatel: issue.fatal,\n path: issue.path.join('.'),\n })).fieldErrors,\n },\n });\n throw error;\n }\n return result.data;\n}\n\nexport const openapi = validate;\n\nexport const consume = (\n contentType: 'application/json' | 'application/x-www-form-urlencoded',\n) => {\n return createMiddleware(async (context, next) => {\n const clientContentType = context.req.header('Content-Type');\n if (clientContentType !== contentType) {\n throw new HTTPException(415, {\n message: 'Unsupported Media Type',\n cause: {\n code: 'api/unsupported-media-type',\n details: `Expected content type: ${contentType}, but got: ${clientContentType}`,\n },\n });\n }\n await next();\n });\n};\n"],
|
|
5
|
+
"mappings": ";AAAA,OAAO,WAAW;AAClB,OAAO,QAAQ;AAIf,IAAM,SAAS,MAAM,cAAc;AAEnC,IAAM,iBAQY,CAAC,UAAU,mBAAmB;AAC9C,SAAO,CAAC,SAAkB;AACxB,QAAI,GAAG,kBAAkB,IAAI,KAAK,KAAK,YAAY;AACjD,UACE,GAAG,iBAAiB,KAAK,UAAU,KACnC,GAAG,2BAA2B,KAAK,WAAW,UAAU,GACxD;AACA,cAAM,aAAa,KAAK,WAAW;AACnC,YACE,GAAG,aAAa,WAAW,UAAU,KACrC,WAAW,WAAW,SAAS,gBAC/B;AACA,cAAI,cAAc;AAClB,gBAAM,eAAe,WAAW,KAAK;AACrC,cAAI,iBAAiB,QAAQ;AAC3B,0BAAc;AAAA,UAChB;AACA,gBAAM,CAAC,MAAM,YAAY,OAAO,IAAI,KAAK,WAAW;AACpD,mBAAS,MAAM,YAAY,SAAS,WAAW;AAAA,QACjD;AAAA,MACF;AAAA,IACF;AACA,WAAO,GAAG,aAAa,MAAM,eAAe,UAAU,cAAc,CAAC;AAAA,EACvE;AACF;AAEA,SAAS,YAAY,SAA2B,SAAsB;AACpE,QAAM,iBAAiB,QAAQ,WAAW,CAAC,EAAE,KAAK,QAAQ;AAC1D,QAAM,gBAAgC,CAAC;AACvC,QAAM,QAAQ,eAAe,CAAC,MAAM,YAAY,SAAS,gBAAgB;AACvE,kBAAc,KAAK;AAAA,MACjB,SAAS,UAAU,OAAO,KAAK,QAAQ,cAAc,OAAO,CAAC,IAAI,CAAC;AAAA,MAClE;AAAA,MACA,YAAY,aAAa,kBAAkB,UAAU,IAAI;AAAA,MACzD,UAAU,QAAQ,cAAc,IAAI;AAAA,IACtC,CAAC;AAAA,EAC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AAK;AACrC,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,QAAQ,IAAI,cAAc,KAAK;AAAA,MACnC,SAAS;AAAA,MACT,OAAO;AAAA,QACL,MAAM;AAAA,QACN,SAAS,OAAO,MAAM,QAAQ,CAAC,WAAW;AAAA,UACxC,SAAS,MAAM;AAAA,UACf,MAAM,MAAM;AAAA,UACZ,OAAO,MAAM;AAAA,UACb,MAAM,MAAM,KAAK,KAAK,GAAG;AAAA,QAC3B,EAAE,EAAE;AAAA,MACN;AAAA,IACF,CAAC;AACD,UAAM;AAAA,EACR;AACA,SAAO,OAAO;AAChB;AAEO,IAAM,UAAU;AAEhB,IAAM,UAAU,CACrB,gBACG;AACH,SAAO,iBAAiB,OAAO,SAAS,SAAS;AAC/C,UAAM,oBAAoB,QAAQ,IAAI,OAAO,cAAc;AAC3D,QAAI,sBAAsB,aAAa;AACrC,YAAM,IAAI,cAAc,KAAK;AAAA,QAC3B,SAAS;AAAA,QACT,OAAO;AAAA,UACL,MAAM;AAAA,UACN,SAAS,0BAA0B,WAAW,cAAc,iBAAiB;AAAA,QAC/E;AAAA,MACF,CAAC;AAAA,IACH;AACA,UAAM,KAAK;AAAA,EACb,CAAC;AACH;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sdk-it/hono",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"module": "./dist/index.js",
|
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
"!**/*.tsbuildinfo"
|
|
22
22
|
],
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@sdk-it/core": "0.
|
|
24
|
+
"@sdk-it/core": "0.6.0",
|
|
25
25
|
"debug": "^4.4.0",
|
|
26
26
|
"hono": "^4.7.4",
|
|
27
27
|
"typescript": "^5.7.2",
|