@sdk-it/hono 0.46.7 → 0.46.8

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdk-it/hono",
3
- "version": "0.46.7",
3
+ "version": "0.46.8",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -16,18 +16,22 @@
16
16
  "default": "./dist/index.js"
17
17
  },
18
18
  "./runtime": {
19
- "types": "./dist/lib/runtime/index.d.ts",
19
+ "types": {
20
+ "@sdk-it/source": "./src/lib/runtime/index.ts",
21
+ "default": "./dist/lib/runtime/index.d.ts"
22
+ },
20
23
  "import": "./dist/lib/runtime/index.js",
21
24
  "default": "./dist/lib/runtime/index.js"
22
25
  }
23
26
  },
24
27
  "files": [
25
28
  "dist",
29
+ "src/lib/runtime",
26
30
  "!**/*.tsbuildinfo",
27
31
  "!**/*.test.*"
28
32
  ],
29
33
  "dependencies": {
30
- "@sdk-it/core": "0.46.7",
34
+ "@sdk-it/core": "0.46.8",
31
35
  "hono": "^4.7.4",
32
36
  "zod": "^4.3.0",
33
37
  "fast-content-type-parse": "^3.0.0"
@@ -0,0 +1,2 @@
1
+ export * from './output.js';
2
+ export * from './validator.js';
@@ -0,0 +1,121 @@
1
+ import type { Context } from 'hono';
2
+ import { getContext } from 'hono/context-storage';
3
+ import type {
4
+ ContentfulStatusCode,
5
+ RedirectStatusCode,
6
+ } from 'hono/utils/http-status';
7
+
8
+ type Data = any;
9
+ function send(
10
+ context: Context,
11
+ value: Data | undefined | null,
12
+ status: ContentfulStatusCode,
13
+ headers?: Readonly<Record<string, string>>,
14
+ ) {
15
+ if (value === undefined || value === null) {
16
+ return context.body(null, status, headers);
17
+ }
18
+ const responseHeaders = { ...headers };
19
+ responseHeaders['Content-Type'] ??= 'application/json';
20
+ if (responseHeaders['Content-Type'].includes('application/json')) {
21
+ return context.body(JSON.stringify(value), status, responseHeaders);
22
+ }
23
+ return context.body(value, status, responseHeaders);
24
+ }
25
+
26
+ export function createOutput(contextFn: () => Context) {
27
+ return {
28
+ nocontent() {
29
+ const context = contextFn();
30
+ return context.body(null, 204, {});
31
+ },
32
+ ok(value: Data | undefined | null, headers?: Record<string, string>) {
33
+ return send(contextFn(), value, 200, headers);
34
+ },
35
+ created(
36
+ valueOrUri: string | Data,
37
+ value: Data | undefined | null,
38
+ headers?: Record<string, string>,
39
+ ) {
40
+ if (typeof valueOrUri === 'string') {
41
+ // If no content is provided, we send null
42
+ return send(contextFn(), value, 201, {
43
+ Location: valueOrUri,
44
+ ...(headers || {}),
45
+ });
46
+ } else {
47
+ // valueOrUri is the data
48
+ return send(contextFn(), valueOrUri, 201, headers);
49
+ }
50
+ },
51
+ redirect(uri: string | URL, statusCode?: unknown) {
52
+ const context = contextFn();
53
+ return context.redirect(
54
+ uri.toString(),
55
+ (statusCode as RedirectStatusCode) ?? undefined,
56
+ );
57
+ },
58
+ attachment(buffer: Buffer, filename: string, mimeType: string) {
59
+ const context = contextFn();
60
+ // https://github.com/honojs/hono/issues/3720
61
+ return context.body(buffer as never, 200, {
62
+ 'Content-Type': mimeType,
63
+ 'Content-Disposition': `attachment; filename="${filename}"`,
64
+ 'Content-Length': buffer.length.toString(),
65
+ });
66
+ },
67
+ badRequest(
68
+ value: Data | undefined | null,
69
+ headers?: Record<string, string>,
70
+ ) {
71
+ return send(contextFn(), value, 400, headers);
72
+ },
73
+ unauthorized(
74
+ value: Data | undefined | null,
75
+ headers?: Record<string, string>,
76
+ ) {
77
+ return send(contextFn(), value, 401, headers);
78
+ },
79
+ forbidden(
80
+ value: Data | undefined | null,
81
+ headers?: Record<string, string>,
82
+ ) {
83
+ return send(contextFn(), value, 403, headers);
84
+ },
85
+ notFound(value: Data | undefined | null, headers?: Record<string, string>) {
86
+ return send(contextFn(), value, 404, headers);
87
+ },
88
+ notImplemented(
89
+ value: Data | undefined | null,
90
+ headers?: Record<string, string>,
91
+ ) {
92
+ return send(contextFn(), value, 501, headers);
93
+ },
94
+ accepted(value: Data | undefined | null, headers?: Record<string, string>) {
95
+ return send(contextFn(), value, 202, headers);
96
+ },
97
+ conflict(value: Data | undefined | null, headers?: Record<string, string>) {
98
+ return send(contextFn(), value, 409, headers);
99
+ },
100
+ unprocessableEntity(
101
+ value: Data | undefined | null,
102
+ headers?: Record<string, string>,
103
+ ) {
104
+ return send(contextFn(), value, 422, headers);
105
+ },
106
+ internalServerError(
107
+ value: Data | undefined | null,
108
+ headers?: Record<string, string>,
109
+ ) {
110
+ return send(contextFn(), value, 500, headers);
111
+ },
112
+ serviceUnavailable(
113
+ value: Data | undefined | null,
114
+ headers?: Record<string, string>,
115
+ ) {
116
+ return send(contextFn(), value, 503, headers);
117
+ },
118
+ };
119
+ }
120
+
121
+ export const output = createOutput(() => getContext());
@@ -0,0 +1,281 @@
1
+ import { safeParse } from 'fast-content-type-parse';
2
+ import type { MiddlewareHandler, ValidationTargets } from 'hono';
3
+ import { createMiddleware } from 'hono/factory';
4
+ import { HTTPException } from 'hono/http-exception';
5
+ import z from 'zod';
6
+
7
+ type ContentType =
8
+ | 'application/json'
9
+ | 'application/x-www-form-urlencoded'
10
+ | 'multipart/form-data'
11
+ | 'text/plain';
12
+
13
+ // z.ZodType<any> mirrors zod v3's ZodTypeAny: with the default `unknown`
14
+ // output, concrete middlewares stop being assignable to
15
+ // ValidateMiddleware<ValidatorConfig>.
16
+
17
+ type ValidatorConfig = Record<
18
+ string,
19
+ { select: unknown; against: z.ZodType<any> }
20
+ >;
21
+
22
+ type ExtractInput<T extends ValidatorConfig> = z.output<
23
+ z.ZodObject<{ [K in keyof T]: T[K]['against'] }>
24
+ >;
25
+
26
+ type HasUndefined<T> = undefined extends T ? true : false;
27
+
28
+ type InferTarget<
29
+ T extends ValidatorConfig,
30
+ S,
31
+ Target extends keyof ValidationTargets,
32
+ > = {
33
+ [K in keyof T as T[K]['select'] extends S ? K : never]: HasUndefined<
34
+ z.infer<T[K]['against']>
35
+ > extends true
36
+ ? z.infer<T[K]['against']> | undefined
37
+ : z.infer<T[K]['against']> extends ValidationTargets[Target]
38
+ ? z.infer<T[K]['against']>
39
+ : z.infer<T[K]['against']>;
40
+ };
41
+
42
+ type InferIn<T extends ValidatorConfig> = (keyof InferTarget<
43
+ T,
44
+ QuerySelect | QueriesSelect,
45
+ 'query'
46
+ > extends never
47
+ ? never
48
+ : { query: InferTarget<T, QuerySelect | QueriesSelect, 'query'> }) &
49
+ (keyof InferTarget<T, BodySelect, 'json'> extends never
50
+ ? never
51
+ : { json: InferTarget<T, BodySelect, 'json'> }) &
52
+ (keyof InferTarget<T, ParamsSelect, 'param'> extends never
53
+ ? never
54
+ : { param: InferTarget<T, ParamsSelect, 'param'> }) &
55
+ (keyof InferTarget<T, HeadersSelect, 'header'> extends never
56
+ ? never
57
+ : { header: InferTarget<T, HeadersSelect, 'header'> }) &
58
+ (keyof InferTarget<T, CookieSelect, 'cookie'> extends never
59
+ ? never
60
+ : { cookie: InferTarget<T, CookieSelect, 'cookie'> });
61
+
62
+ // Type-only markers distinguish request sources; no marker objects exist at runtime.
63
+ type Select<Target extends string> = {
64
+ readonly validationTarget: Target;
65
+ };
66
+
67
+ type BodySelect = Select<'body'>;
68
+ type QuerySelect = Select<'query'>;
69
+ type QueriesSelect = Select<'queries'>;
70
+ type ParamsSelect = Select<'params'>;
71
+ type HeadersSelect = Select<'headers'>;
72
+ type CookieSelect = Select<'cookie'>;
73
+
74
+ type SelectorFn<T> = (payload: {
75
+ body: Record<string, BodySelect>;
76
+ query: Record<string, QuerySelect>;
77
+ queries: Record<string, QueriesSelect>;
78
+ params: Record<string, ParamsSelect>;
79
+ headers: Record<string, HeadersSelect>;
80
+ }) => T;
81
+ type ValidateMiddleware<T extends ValidatorConfig> = MiddlewareHandler<
82
+ {
83
+ Variables: {
84
+ input: ExtractInput<T>;
85
+ };
86
+ },
87
+ string,
88
+ { in: InferIn<T> }
89
+ >;
90
+
91
+ /** Validate selected request values and expose Zod's parsed output as `c.var.input`. */
92
+ export function validate<T extends ValidatorConfig>(
93
+ selector: SelectorFn<T>,
94
+ ): ValidateMiddleware<T>;
95
+ /** Enforce a content type before validating the selected request values. */
96
+ export function validate<T extends ValidatorConfig>(
97
+ expectedContentTypeOrSelector: ContentType,
98
+ selector: SelectorFn<T>,
99
+ ): ValidateMiddleware<T>;
100
+ export function validate<T extends ValidatorConfig>(
101
+ expectedContentTypeOrSelector: ContentType | SelectorFn<T>,
102
+ selector?: SelectorFn<T>,
103
+ ): ValidateMiddleware<T> {
104
+ const expectedContentType =
105
+ typeof expectedContentTypeOrSelector === 'string'
106
+ ? expectedContentTypeOrSelector
107
+ : undefined;
108
+ const _selector =
109
+ typeof expectedContentTypeOrSelector === 'function'
110
+ ? expectedContentTypeOrSelector
111
+ : selector;
112
+ if (!_selector) {
113
+ throw new Error('Selector function is required');
114
+ }
115
+
116
+ return createMiddleware(async (c, next) => {
117
+ const ct = c.req.header('content-type');
118
+ if (c.req.method === 'GET' && ct) {
119
+ throw new HTTPException(415, {
120
+ message: 'Unsupported Media Type',
121
+ cause: {
122
+ code: 'api/unsupported-media-type',
123
+ detail: `GET requests cannot have a content type header`,
124
+ },
125
+ });
126
+ }
127
+ if (expectedContentType) {
128
+ verifyContentType(ct, expectedContentType);
129
+ }
130
+
131
+ const contentType = ct ? parseContentType(ct) : null;
132
+ let body: unknown = null;
133
+
134
+ switch (contentType?.type) {
135
+ case 'application/json':
136
+ try {
137
+ body = await c.req.json();
138
+ } catch {
139
+ throw new HTTPException(400, {
140
+ message: 'Invalid JSON body',
141
+ cause: {
142
+ code: 'api/invalid-json',
143
+ detail: 'Request body must be valid JSON.',
144
+ },
145
+ });
146
+ }
147
+ break;
148
+ case 'application/x-www-form-urlencoded':
149
+ case 'multipart/form-data':
150
+ body = await c.req.parseBody({ all: true });
151
+ break;
152
+ default:
153
+ body = {};
154
+ }
155
+
156
+ // Whole-body schemas may accept any JSON value. A field selector, however,
157
+ // requires an object: guard the property read itself rather than catching
158
+ // arbitrary errors thrown by the application's selector.
159
+ const selectedBody =
160
+ body !== null && typeof body === 'object' && !Array.isArray(body)
161
+ ? body
162
+ : new Proxy(
163
+ {},
164
+ {
165
+ get() {
166
+ throw new HTTPException(400, {
167
+ message: 'Invalid request body',
168
+ cause: {
169
+ code: 'api/invalid-body',
170
+ detail:
171
+ 'Request body must be an object when selecting fields.',
172
+ },
173
+ });
174
+ },
175
+ },
176
+ );
177
+ const payload = {
178
+ body: selectedBody,
179
+ query: c.req.query(),
180
+ queries: c.req.queries(),
181
+ params: c.req.param(),
182
+ headers: c.req.header(),
183
+ };
184
+
185
+ const config = _selector(payload as never);
186
+ const schema = z.object(
187
+ Object.fromEntries(
188
+ Object.entries(config).map(([key, value]) => [key, value.against]),
189
+ ),
190
+ );
191
+
192
+ const input = Object.fromEntries(
193
+ Object.entries(config).map(([key, value]) => [
194
+ key,
195
+ value.select === selectedBody ? body : value.select,
196
+ ]),
197
+ );
198
+
199
+ const parsed = await parse(schema, input);
200
+ c.set('input', parsed as ExtractInput<T>);
201
+ await next();
202
+ });
203
+ }
204
+
205
+ /** Parse any Zod schema asynchronously, throwing a structured HTTP 400 on rejection. */
206
+ export async function parse<T extends z.ZodType>(
207
+ schema: T,
208
+ input: unknown,
209
+ ): Promise<z.output<T>> {
210
+ const result = await schema.safeParseAsync(input);
211
+ if (!result.success) {
212
+ const { fieldErrors, formErrors } = z.flattenError(
213
+ result.error,
214
+ (issue) => ({
215
+ message: issue.message,
216
+ code: issue.code,
217
+ path: issue.path.join('.'),
218
+ }),
219
+ );
220
+ const error = new HTTPException(400, {
221
+ message: 'Validation failed',
222
+ cause: {
223
+ code: 'api/validation-failed',
224
+ detail: 'The input data is invalid',
225
+ errors: fieldErrors,
226
+ formErrors,
227
+ },
228
+ });
229
+ throw error;
230
+ }
231
+ return result.data;
232
+ }
233
+
234
+ export const openapi = validate;
235
+
236
+ /** Enforce a request content type without reading or validating its body. */
237
+ export const consume = (contentType: ContentType) => {
238
+ return createMiddleware(async (context, next) => {
239
+ verifyContentType(context.req.header('content-type'), contentType);
240
+ await next();
241
+ });
242
+ };
243
+
244
+ function parseContentType(header: string) {
245
+ const contentType = safeParse(header);
246
+ if (!contentType.type) {
247
+ throw new HTTPException(415, {
248
+ message: 'Unsupported Media Type',
249
+ cause: {
250
+ code: 'api/unsupported-media-type',
251
+ detail: 'Invalid content type header',
252
+ },
253
+ });
254
+ }
255
+ return contentType;
256
+ }
257
+
258
+ export function verifyContentType(
259
+ actual: string | undefined,
260
+ expected: ContentType,
261
+ ): asserts actual is ContentType {
262
+ if (!actual) {
263
+ throw new HTTPException(415, {
264
+ message: 'Unsupported Media Type',
265
+ cause: {
266
+ code: 'api/unsupported-media-type',
267
+ detail: 'Missing content type header',
268
+ },
269
+ });
270
+ }
271
+ const { type: incomingContentType } = parseContentType(actual);
272
+ if (incomingContentType !== expected) {
273
+ throw new HTTPException(415, {
274
+ message: 'Unsupported Media Type',
275
+ cause: {
276
+ code: 'api/unsupported-media-type',
277
+ detail: `Expected content type: ${expected}, but got: ${incomingContentType}`,
278
+ },
279
+ });
280
+ }
281
+ }