hono-problem-details 0.10.1 → 0.12.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 +76 -3
- package/dist/chunk-LIQQKPXQ.js +34 -0
- package/dist/{chunk-BBJKRRB3.js → chunk-R6NMRTVW.js} +18 -4
- package/dist/{chunk-VPS467Z5.js → chunk-URAOTABQ.js} +1 -0
- package/dist/index.cjs +40 -11
- package/dist/index.d.cts +11 -1
- package/dist/index.d.ts +11 -1
- package/dist/index.js +44 -38
- package/dist/integrations/openapi-json-schema.cjs +127 -0
- package/dist/integrations/openapi-json-schema.d.cts +40 -0
- package/dist/integrations/openapi-json-schema.d.ts +40 -0
- package/dist/integrations/openapi-json-schema.js +45 -0
- package/dist/integrations/standard-schema.cjs +135 -3
- package/dist/integrations/standard-schema.d.cts +1 -1
- package/dist/integrations/standard-schema.d.ts +1 -1
- package/dist/integrations/standard-schema.js +3 -2
- package/dist/integrations/valibot.cjs +135 -3
- package/dist/integrations/valibot.d.cts +1 -1
- package/dist/integrations/valibot.d.ts +1 -1
- package/dist/integrations/valibot.js +3 -2
- package/dist/integrations/zod.cjs +135 -3
- package/dist/integrations/zod.d.cts +1 -1
- package/dist/integrations/zod.d.ts +1 -1
- package/dist/integrations/zod.js +3 -2
- package/dist/validation-CZHjSmb_.d.cts +14 -0
- package/dist/validation-CZHjSmb_.d.ts +14 -0
- package/package.json +22 -7
- package/dist/validation-DqPEnoIw.d.cts +0 -6
- package/dist/validation-DqPEnoIw.d.ts +0 -6
package/README.md
CHANGED
|
@@ -37,7 +37,7 @@ can all agree on.
|
|
|
37
37
|
- **Hono native** — `app.onError` handler with RFC-compliant defaults
|
|
38
38
|
- **Zod integration** — `@hono/zod-validator` hook for validation errors
|
|
39
39
|
- **Valibot integration** — `@hono/valibot-validator` hook for validation errors
|
|
40
|
-
- **OpenAPI integration** — `@hono/zod-openapi` schemas for API documentation
|
|
40
|
+
- **OpenAPI integration** — `@hono/zod-openapi` schemas for API documentation, plus dependency-free plain JSON Schema helpers for non-Zod stacks
|
|
41
41
|
- **OpenTelemetry integration** — `@opentelemetry/api` for automatically injecting trace information.
|
|
42
42
|
- **Standard Schema** — `@hono/standard-validator` hook (works with any schema library)
|
|
43
43
|
- **Type-safe** — full TypeScript support with inference
|
|
@@ -210,6 +210,18 @@ problemDetailsHandler({
|
|
|
210
210
|
Keep `includeStack` off in production — stack traces should not leave the server even via
|
|
211
211
|
opt-in extension fields.
|
|
212
212
|
|
|
213
|
+
Unlike Hono's default error handler, `problemDetailsHandler()` does not log anything. Pass
|
|
214
|
+
`onUnhandledError` to log (or report) errors that fall through to the generic 500. It is not
|
|
215
|
+
called for `ProblemDetailsError`, `HTTPException`, or errors matched by `mapError`:
|
|
216
|
+
|
|
217
|
+
```ts
|
|
218
|
+
app.onError(
|
|
219
|
+
problemDetailsHandler({
|
|
220
|
+
onUnhandledError: (err) => console.error(err),
|
|
221
|
+
}),
|
|
222
|
+
);
|
|
223
|
+
```
|
|
224
|
+
|
|
213
225
|
## Extension Members
|
|
214
226
|
|
|
215
227
|
Extension members are flattened to top level per RFC 9457:
|
|
@@ -354,6 +366,17 @@ app.post("/users", zValidator("json", schema, zodProblemHook()), (c) => {
|
|
|
354
366
|
// }
|
|
355
367
|
```
|
|
356
368
|
|
|
369
|
+
By default the hooks build the response themselves, so `problemDetailsHandler` options (`typePrefix`, `defaultType`, `localize`, `autoInstance`, `otelApi`) do not apply to validation errors. Pass `delegateToHandler: true` to any of the validator hooks (`zodProblemHook`, `valibotProblemHook`, `standardSchemaProblemHook`) to throw a `ProblemDetailsError` instead and let the handler produce the response. The handler options only apply with `app.onError(problemDetailsHandler(...))`; without it, Hono's default error handler falls back to `ProblemDetailsError.getResponse()` and returns the plain 422 body:
|
|
370
|
+
|
|
371
|
+
```ts
|
|
372
|
+
app.onError(problemDetailsHandler({ typePrefix: "https://example.com/problems", autoInstance: true }));
|
|
373
|
+
|
|
374
|
+
app.post("/users", zValidator("json", schema, zodProblemHook({ delegateToHandler: true })), (c) => {
|
|
375
|
+
// ...
|
|
376
|
+
});
|
|
377
|
+
// type: "https://example.com/problems/unprocessable-content", instance: "/users"
|
|
378
|
+
```
|
|
379
|
+
|
|
357
380
|
## Valibot Validator Integration
|
|
358
381
|
|
|
359
382
|
```ts
|
|
@@ -452,6 +475,50 @@ const errorWithExtensions = createProblemDetailsSchema(
|
|
|
452
475
|
> See [ADR-0004](./docs/adr/0004-defer-openapi-schema-construction-via-factory.md)
|
|
453
476
|
> for the bundler-related reason this changed.
|
|
454
477
|
|
|
478
|
+
### Without Zod: plain JSON Schema
|
|
479
|
+
|
|
480
|
+
Not on Zod? `hono-problem-details/openapi-json-schema` emits the same Problem Details
|
|
481
|
+
schema as **plain JSON Schema** (draft 2020-12, the OpenAPI 3.1 base dialect) with zero
|
|
482
|
+
dependencies. It works with any documentation layer that accepts raw JSON Schema — e.g.
|
|
483
|
+
[`hono-openapi`](https://github.com/rhinobase/hono-openapi) on a Valibot, ArkType, or
|
|
484
|
+
typia stack:
|
|
485
|
+
|
|
486
|
+
```ts
|
|
487
|
+
import { describeRoute } from "hono-openapi";
|
|
488
|
+
import {
|
|
489
|
+
problemDetailsJsonSchema,
|
|
490
|
+
problemDetailsResponseJsonSchema,
|
|
491
|
+
} from "hono-problem-details/openapi-json-schema";
|
|
492
|
+
|
|
493
|
+
app.post(
|
|
494
|
+
"/reservations",
|
|
495
|
+
describeRoute({
|
|
496
|
+
responses: {
|
|
497
|
+
409: problemDetailsResponseJsonSchema(409, "Slot already taken"),
|
|
498
|
+
422: problemDetailsResponseJsonSchema(422),
|
|
499
|
+
},
|
|
500
|
+
}),
|
|
501
|
+
// ...
|
|
502
|
+
);
|
|
503
|
+
|
|
504
|
+
// Need the schema itself? With typed extension members:
|
|
505
|
+
const schema = problemDetailsJsonSchema({
|
|
506
|
+
extensions: {
|
|
507
|
+
conflictingResources: { type: "array", items: { type: "string" } },
|
|
508
|
+
},
|
|
509
|
+
});
|
|
510
|
+
// Use: problemDetailsResponseJsonSchema(409, "Slot already taken", schema)
|
|
511
|
+
```
|
|
512
|
+
|
|
513
|
+
Extension members merge at the top level, and standard RFC 9457 fields win on key
|
|
514
|
+
collision — the same rule the Zod helpers and the runtime follow
|
|
515
|
+
([ADR-0002](./docs/adr/0002-extension-flatten-with-standard-field-precedence.md)).
|
|
516
|
+
Keys the runtime strips as prototype-pollution guards (`__proto__`, `constructor`,
|
|
517
|
+
`prototype`) are excluded too, so the schema never documents a member that real
|
|
518
|
+
responses omit. Each call returns a fresh object with extension schemas cloned, so
|
|
519
|
+
you can safely tweak the result (e.g. push extra keys into `required`) without
|
|
520
|
+
affecting other call sites or your own input.
|
|
521
|
+
|
|
455
522
|
## Localization
|
|
456
523
|
|
|
457
524
|
Use the `localize` callback to translate `title` and `detail` based on the request context.
|
|
@@ -494,7 +561,7 @@ problemDetailsHandler({
|
|
|
494
561
|
});
|
|
495
562
|
```
|
|
496
563
|
|
|
497
|
-
When enabled, the handler adds a `traceId` extension member to every response it produces (thrown `ProblemDetailsError`s, `HTTPException`s, and unhandled errors) when a trace is active. Validation-hook responses (`zodProblemHook`, `valibotProblemHook`, `standardSchemaProblemHook`) are returned directly by the validator and never pass through the handler, so they do not carry `traceId
|
|
564
|
+
When enabled, the handler adds a `traceId` extension member to every response it produces (thrown `ProblemDetailsError`s, `HTTPException`s, and unhandled errors) when a trace is active. Validation-hook responses (`zodProblemHook`, `valibotProblemHook`, `standardSchemaProblemHook`) are returned directly by the validator and never pass through the handler, so they do not carry `traceId` unless you set `delegateToHandler: true` (see [Zod Validator Integration](#zod-validator-integration)).
|
|
498
565
|
This allows clients to correlate errors with server-side traces for easier debugging.
|
|
499
566
|
|
|
500
567
|
## Handler Options
|
|
@@ -520,7 +587,13 @@ problemDetailsHandler({
|
|
|
520
587
|
return { title: `[${lang}] ${pd.title}` };
|
|
521
588
|
},
|
|
522
589
|
|
|
523
|
-
//
|
|
590
|
+
// Called for errors that become the generic 500 (not ProblemDetailsError, HTTPException,
|
|
591
|
+
// or mapError results). The handler doesn't log by default; use this to restore logging.
|
|
592
|
+
// A throwing callback is swallowed; the return value is not awaited.
|
|
593
|
+
onUnhandledError: (err, c) => console.error(err),
|
|
594
|
+
|
|
595
|
+
// Custom error mapping. A throwing callback is silently swallowed
|
|
596
|
+
// and the error is handled as if mapError returned undefined.
|
|
524
597
|
mapError: (error) => {
|
|
525
598
|
if (error instanceof MyCustomError) {
|
|
526
599
|
return {
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import {
|
|
2
|
+
buildProblemResponse,
|
|
3
|
+
normalizeProblemDetails
|
|
4
|
+
} from "./chunk-URAOTABQ.js";
|
|
5
|
+
|
|
6
|
+
// src/error.ts
|
|
7
|
+
var ProblemDetailsError = class extends Error {
|
|
8
|
+
/** The normalized RFC 9457 Problem Details object. */
|
|
9
|
+
problemDetails;
|
|
10
|
+
/**
|
|
11
|
+
* Whether the input carried an explicit `type`. Lets the handler apply
|
|
12
|
+
* `typePrefix`/`defaultType` only when the thrower left `type` unset.
|
|
13
|
+
*/
|
|
14
|
+
hasExplicitType;
|
|
15
|
+
/**
|
|
16
|
+
* @param input - Missing `type` defaults to `"about:blank"`;
|
|
17
|
+
* missing `title` is derived from the HTTP status code.
|
|
18
|
+
*/
|
|
19
|
+
constructor(input) {
|
|
20
|
+
const pd = normalizeProblemDetails(input);
|
|
21
|
+
super(pd.detail ?? pd.title);
|
|
22
|
+
this.name = "ProblemDetailsError";
|
|
23
|
+
this.problemDetails = pd;
|
|
24
|
+
this.hasExplicitType = input.type !== void 0;
|
|
25
|
+
}
|
|
26
|
+
/** Build a standalone `application/problem+json` Response without the handler middleware. */
|
|
27
|
+
getResponse() {
|
|
28
|
+
return buildProblemResponse(this.problemDetails);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export {
|
|
33
|
+
ProblemDetailsError
|
|
34
|
+
};
|
|
@@ -1,6 +1,9 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ProblemDetailsError
|
|
3
|
+
} from "./chunk-LIQQKPXQ.js";
|
|
1
4
|
import {
|
|
2
5
|
PROBLEM_JSON_CONTENT_TYPE
|
|
3
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-URAOTABQ.js";
|
|
4
7
|
|
|
5
8
|
// src/integrations/validation.ts
|
|
6
9
|
var CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/g;
|
|
@@ -15,12 +18,23 @@ function sanitizeError(error) {
|
|
|
15
18
|
};
|
|
16
19
|
}
|
|
17
20
|
function buildValidationResponse(errors, options) {
|
|
21
|
+
const title = options?.title ?? "Validation Error";
|
|
22
|
+
const detail = options?.detail ?? "Request validation failed";
|
|
23
|
+
const sanitizedErrors = errors.map(sanitizeError);
|
|
24
|
+
if (options?.delegateToHandler) {
|
|
25
|
+
throw new ProblemDetailsError({
|
|
26
|
+
status: 422,
|
|
27
|
+
title,
|
|
28
|
+
detail,
|
|
29
|
+
extensions: { errors: sanitizedErrors }
|
|
30
|
+
});
|
|
31
|
+
}
|
|
18
32
|
const body = {
|
|
19
33
|
type: "about:blank",
|
|
20
34
|
status: 422,
|
|
21
|
-
title
|
|
22
|
-
detail
|
|
23
|
-
errors:
|
|
35
|
+
title,
|
|
36
|
+
detail,
|
|
37
|
+
errors: sanitizedErrors
|
|
24
38
|
};
|
|
25
39
|
return new Response(JSON.stringify(body), {
|
|
26
40
|
status: 422,
|
package/dist/index.cjs
CHANGED
|
@@ -182,6 +182,13 @@ function getOtelTraceId(api) {
|
|
|
182
182
|
}
|
|
183
183
|
|
|
184
184
|
// src/handler.ts
|
|
185
|
+
var REPRESENTATION_HEADERS = /* @__PURE__ */ new Set([
|
|
186
|
+
"transfer-encoding",
|
|
187
|
+
"etag",
|
|
188
|
+
"last-modified",
|
|
189
|
+
"digest",
|
|
190
|
+
"accept-ranges"
|
|
191
|
+
]);
|
|
185
192
|
function buildType(status, options) {
|
|
186
193
|
if (options.typePrefix) {
|
|
187
194
|
const slug = statusToSlug(status);
|
|
@@ -189,6 +196,16 @@ function buildType(status, options) {
|
|
|
189
196
|
}
|
|
190
197
|
return options.defaultType ?? "about:blank";
|
|
191
198
|
}
|
|
199
|
+
function copyResHeaders(error, response) {
|
|
200
|
+
if (error instanceof import_http_exception.HTTPException) {
|
|
201
|
+
error.res?.headers.forEach((value, name) => {
|
|
202
|
+
if (!name.startsWith("content-") && !REPRESENTATION_HEADERS.has(name)) {
|
|
203
|
+
response.headers.append(name, value);
|
|
204
|
+
}
|
|
205
|
+
});
|
|
206
|
+
}
|
|
207
|
+
return response;
|
|
208
|
+
}
|
|
192
209
|
function toResponse(input, c, options) {
|
|
193
210
|
let pd = normalizeProblemDetails({
|
|
194
211
|
...input,
|
|
@@ -222,22 +239,34 @@ function problemDetailsHandler(options = {}) {
|
|
|
222
239
|
return toResponse(error.hasExplicitType ? pd : { ...pd, type: void 0 }, c, options);
|
|
223
240
|
}
|
|
224
241
|
if (options.mapError) {
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
242
|
+
try {
|
|
243
|
+
const mapped = options.mapError(error);
|
|
244
|
+
if (mapped) {
|
|
245
|
+
return copyResHeaders(error, toResponse(mapped, c, options));
|
|
246
|
+
}
|
|
247
|
+
} catch {
|
|
228
248
|
}
|
|
229
249
|
}
|
|
230
250
|
if (error instanceof import_http_exception.HTTPException) {
|
|
231
|
-
return
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
251
|
+
return copyResHeaders(
|
|
252
|
+
error,
|
|
253
|
+
toResponse(
|
|
254
|
+
{
|
|
255
|
+
status: error.status,
|
|
256
|
+
title: statusToPhrase(error.status),
|
|
257
|
+
detail: error.message || void 0
|
|
258
|
+
},
|
|
259
|
+
c,
|
|
260
|
+
options
|
|
261
|
+
)
|
|
239
262
|
);
|
|
240
263
|
}
|
|
264
|
+
if (options.onUnhandledError) {
|
|
265
|
+
try {
|
|
266
|
+
options.onUnhandledError(error, c);
|
|
267
|
+
} catch {
|
|
268
|
+
}
|
|
269
|
+
}
|
|
241
270
|
return toResponse(
|
|
242
271
|
{
|
|
243
272
|
status: 500,
|
package/dist/index.d.cts
CHANGED
|
@@ -66,7 +66,10 @@ interface ProblemDetailsHandlerOptions {
|
|
|
66
66
|
* ```
|
|
67
67
|
*/
|
|
68
68
|
otelApi?: OtelApiLike;
|
|
69
|
-
/**
|
|
69
|
+
/**
|
|
70
|
+
* Custom error to ProblemDetails mapping. A throwing callback is swallowed
|
|
71
|
+
* (ADR-0005) and the error is handled as if mapError returned undefined.
|
|
72
|
+
*/
|
|
70
73
|
mapError?: (error: Error) => ProblemDetailsInput | undefined;
|
|
71
74
|
/**
|
|
72
75
|
* Localize title/detail before sending the response.
|
|
@@ -74,6 +77,13 @@ interface ProblemDetailsHandlerOptions {
|
|
|
74
77
|
* return a partial patch (e.g. `{ title: "..." }`) or omit the return entirely.
|
|
75
78
|
*/
|
|
76
79
|
localize?: (pd: ProblemDetails, c: Context) => Partial<ProblemDetails> | undefined;
|
|
80
|
+
/**
|
|
81
|
+
* Called for errors that fall through to the generic 500 response, before it is built.
|
|
82
|
+
* Not called for `ProblemDetailsError`, `HTTPException`, or errors matched by `mapError`.
|
|
83
|
+
* A throwing callback is swallowed. The return value is not awaited: do async work
|
|
84
|
+
* fire-and-forget and catch its rejections yourself.
|
|
85
|
+
*/
|
|
86
|
+
onUnhandledError?: (error: Error, c: Context) => void;
|
|
77
87
|
}
|
|
78
88
|
interface OtelApiLike {
|
|
79
89
|
trace: {
|
package/dist/index.d.ts
CHANGED
|
@@ -66,7 +66,10 @@ interface ProblemDetailsHandlerOptions {
|
|
|
66
66
|
* ```
|
|
67
67
|
*/
|
|
68
68
|
otelApi?: OtelApiLike;
|
|
69
|
-
/**
|
|
69
|
+
/**
|
|
70
|
+
* Custom error to ProblemDetails mapping. A throwing callback is swallowed
|
|
71
|
+
* (ADR-0005) and the error is handled as if mapError returned undefined.
|
|
72
|
+
*/
|
|
70
73
|
mapError?: (error: Error) => ProblemDetailsInput | undefined;
|
|
71
74
|
/**
|
|
72
75
|
* Localize title/detail before sending the response.
|
|
@@ -74,6 +77,13 @@ interface ProblemDetailsHandlerOptions {
|
|
|
74
77
|
* return a partial patch (e.g. `{ title: "..." }`) or omit the return entirely.
|
|
75
78
|
*/
|
|
76
79
|
localize?: (pd: ProblemDetails, c: Context) => Partial<ProblemDetails> | undefined;
|
|
80
|
+
/**
|
|
81
|
+
* Called for errors that fall through to the generic 500 response, before it is built.
|
|
82
|
+
* Not called for `ProblemDetailsError`, `HTTPException`, or errors matched by `mapError`.
|
|
83
|
+
* A throwing callback is swallowed. The return value is not awaited: do async work
|
|
84
|
+
* fire-and-forget and catch its rejections yourself.
|
|
85
|
+
*/
|
|
86
|
+
onUnhandledError?: (error: Error, c: Context) => void;
|
|
77
87
|
}
|
|
78
88
|
interface OtelApiLike {
|
|
79
89
|
trace: {
|
package/dist/index.js
CHANGED
|
@@ -1,39 +1,16 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ProblemDetailsError
|
|
3
|
+
} from "./chunk-LIQQKPXQ.js";
|
|
1
4
|
import {
|
|
2
5
|
PROBLEM_JSON_CONTENT_TYPE,
|
|
3
6
|
buildProblemResponse,
|
|
4
7
|
normalizeProblemDetails
|
|
5
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-URAOTABQ.js";
|
|
6
9
|
import {
|
|
7
10
|
statusToPhrase,
|
|
8
11
|
statusToSlug
|
|
9
12
|
} from "./chunk-P4D7EVU3.js";
|
|
10
13
|
|
|
11
|
-
// src/error.ts
|
|
12
|
-
var ProblemDetailsError = class extends Error {
|
|
13
|
-
/** The normalized RFC 9457 Problem Details object. */
|
|
14
|
-
problemDetails;
|
|
15
|
-
/**
|
|
16
|
-
* Whether the input carried an explicit `type`. Lets the handler apply
|
|
17
|
-
* `typePrefix`/`defaultType` only when the thrower left `type` unset.
|
|
18
|
-
*/
|
|
19
|
-
hasExplicitType;
|
|
20
|
-
/**
|
|
21
|
-
* @param input - Missing `type` defaults to `"about:blank"`;
|
|
22
|
-
* missing `title` is derived from the HTTP status code.
|
|
23
|
-
*/
|
|
24
|
-
constructor(input) {
|
|
25
|
-
const pd = normalizeProblemDetails(input);
|
|
26
|
-
super(pd.detail ?? pd.title);
|
|
27
|
-
this.name = "ProblemDetailsError";
|
|
28
|
-
this.problemDetails = pd;
|
|
29
|
-
this.hasExplicitType = input.type !== void 0;
|
|
30
|
-
}
|
|
31
|
-
/** Build a standalone `application/problem+json` Response without the handler middleware. */
|
|
32
|
-
getResponse() {
|
|
33
|
-
return buildProblemResponse(this.problemDetails);
|
|
34
|
-
}
|
|
35
|
-
};
|
|
36
|
-
|
|
37
14
|
// src/factory.ts
|
|
38
15
|
function problemDetails(input) {
|
|
39
16
|
return new ProblemDetailsError(input);
|
|
@@ -54,6 +31,13 @@ function getOtelTraceId(api) {
|
|
|
54
31
|
}
|
|
55
32
|
|
|
56
33
|
// src/handler.ts
|
|
34
|
+
var REPRESENTATION_HEADERS = /* @__PURE__ */ new Set([
|
|
35
|
+
"transfer-encoding",
|
|
36
|
+
"etag",
|
|
37
|
+
"last-modified",
|
|
38
|
+
"digest",
|
|
39
|
+
"accept-ranges"
|
|
40
|
+
]);
|
|
57
41
|
function buildType(status, options) {
|
|
58
42
|
if (options.typePrefix) {
|
|
59
43
|
const slug = statusToSlug(status);
|
|
@@ -61,6 +45,16 @@ function buildType(status, options) {
|
|
|
61
45
|
}
|
|
62
46
|
return options.defaultType ?? "about:blank";
|
|
63
47
|
}
|
|
48
|
+
function copyResHeaders(error, response) {
|
|
49
|
+
if (error instanceof HTTPException) {
|
|
50
|
+
error.res?.headers.forEach((value, name) => {
|
|
51
|
+
if (!name.startsWith("content-") && !REPRESENTATION_HEADERS.has(name)) {
|
|
52
|
+
response.headers.append(name, value);
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
return response;
|
|
57
|
+
}
|
|
64
58
|
function toResponse(input, c, options) {
|
|
65
59
|
let pd = normalizeProblemDetails({
|
|
66
60
|
...input,
|
|
@@ -94,22 +88,34 @@ function problemDetailsHandler(options = {}) {
|
|
|
94
88
|
return toResponse(error.hasExplicitType ? pd : { ...pd, type: void 0 }, c, options);
|
|
95
89
|
}
|
|
96
90
|
if (options.mapError) {
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
91
|
+
try {
|
|
92
|
+
const mapped = options.mapError(error);
|
|
93
|
+
if (mapped) {
|
|
94
|
+
return copyResHeaders(error, toResponse(mapped, c, options));
|
|
95
|
+
}
|
|
96
|
+
} catch {
|
|
100
97
|
}
|
|
101
98
|
}
|
|
102
99
|
if (error instanceof HTTPException) {
|
|
103
|
-
return
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
100
|
+
return copyResHeaders(
|
|
101
|
+
error,
|
|
102
|
+
toResponse(
|
|
103
|
+
{
|
|
104
|
+
status: error.status,
|
|
105
|
+
title: statusToPhrase(error.status),
|
|
106
|
+
detail: error.message || void 0
|
|
107
|
+
},
|
|
108
|
+
c,
|
|
109
|
+
options
|
|
110
|
+
)
|
|
111
111
|
);
|
|
112
112
|
}
|
|
113
|
+
if (options.onUnhandledError) {
|
|
114
|
+
try {
|
|
115
|
+
options.onUnhandledError(error, c);
|
|
116
|
+
} catch {
|
|
117
|
+
}
|
|
118
|
+
}
|
|
113
119
|
return toResponse(
|
|
114
120
|
{
|
|
115
121
|
status: 500,
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/integrations/openapi-json-schema.ts
|
|
21
|
+
var openapi_json_schema_exports = {};
|
|
22
|
+
__export(openapi_json_schema_exports, {
|
|
23
|
+
problemDetailsJsonSchema: () => problemDetailsJsonSchema,
|
|
24
|
+
problemDetailsResponseJsonSchema: () => problemDetailsResponseJsonSchema
|
|
25
|
+
});
|
|
26
|
+
module.exports = __toCommonJS(openapi_json_schema_exports);
|
|
27
|
+
|
|
28
|
+
// src/status.ts
|
|
29
|
+
var STATUS_PHRASES = {
|
|
30
|
+
400: "Bad Request",
|
|
31
|
+
401: "Unauthorized",
|
|
32
|
+
402: "Payment Required",
|
|
33
|
+
403: "Forbidden",
|
|
34
|
+
404: "Not Found",
|
|
35
|
+
405: "Method Not Allowed",
|
|
36
|
+
406: "Not Acceptable",
|
|
37
|
+
407: "Proxy Authentication Required",
|
|
38
|
+
408: "Request Timeout",
|
|
39
|
+
409: "Conflict",
|
|
40
|
+
410: "Gone",
|
|
41
|
+
411: "Length Required",
|
|
42
|
+
412: "Precondition Failed",
|
|
43
|
+
413: "Content Too Large",
|
|
44
|
+
414: "URI Too Long",
|
|
45
|
+
415: "Unsupported Media Type",
|
|
46
|
+
416: "Range Not Satisfiable",
|
|
47
|
+
417: "Expectation Failed",
|
|
48
|
+
418: "I'm a Teapot",
|
|
49
|
+
421: "Misdirected Request",
|
|
50
|
+
422: "Unprocessable Content",
|
|
51
|
+
423: "Locked",
|
|
52
|
+
424: "Failed Dependency",
|
|
53
|
+
425: "Too Early",
|
|
54
|
+
426: "Upgrade Required",
|
|
55
|
+
428: "Precondition Required",
|
|
56
|
+
429: "Too Many Requests",
|
|
57
|
+
431: "Request Header Fields Too Large",
|
|
58
|
+
451: "Unavailable For Legal Reasons",
|
|
59
|
+
500: "Internal Server Error",
|
|
60
|
+
501: "Not Implemented",
|
|
61
|
+
502: "Bad Gateway",
|
|
62
|
+
503: "Service Unavailable",
|
|
63
|
+
504: "Gateway Timeout",
|
|
64
|
+
505: "HTTP Version Not Supported",
|
|
65
|
+
506: "Variant Also Negotiates",
|
|
66
|
+
507: "Insufficient Storage",
|
|
67
|
+
508: "Loop Detected",
|
|
68
|
+
510: "Not Extended",
|
|
69
|
+
511: "Network Authentication Required"
|
|
70
|
+
};
|
|
71
|
+
var STATUS_SLUGS = Object.fromEntries(
|
|
72
|
+
Object.entries(STATUS_PHRASES).map(([code, phrase]) => [
|
|
73
|
+
Number(code),
|
|
74
|
+
phrase.toLowerCase().replace(/'/g, "").replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "")
|
|
75
|
+
])
|
|
76
|
+
);
|
|
77
|
+
function statusToPhrase(status) {
|
|
78
|
+
return STATUS_PHRASES[status];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// src/utils.ts
|
|
82
|
+
var DANGEROUS_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
|
|
83
|
+
var FALLBACK_BODY = JSON.stringify({
|
|
84
|
+
type: "about:blank",
|
|
85
|
+
status: 500,
|
|
86
|
+
title: "Internal Server Error"
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
// src/integrations/openapi-json-schema.ts
|
|
90
|
+
var STANDARD_FIELD_KEYS = /* @__PURE__ */ new Set(["type", "status", "title", "detail", "instance"]);
|
|
91
|
+
function problemDetailsJsonSchema(options) {
|
|
92
|
+
const properties = {
|
|
93
|
+
type: { type: "string", description: "Problem type URI", examples: ["about:blank"] },
|
|
94
|
+
status: { type: "integer", description: "HTTP status code", examples: [400] },
|
|
95
|
+
title: {
|
|
96
|
+
type: "string",
|
|
97
|
+
description: "Short summary of the problem type",
|
|
98
|
+
examples: ["Bad Request"]
|
|
99
|
+
},
|
|
100
|
+
detail: { type: "string", description: "Human-readable explanation" },
|
|
101
|
+
instance: { type: "string", description: "URI identifying the occurrence" }
|
|
102
|
+
};
|
|
103
|
+
for (const [key, schema] of Object.entries(options?.extensions ?? {})) {
|
|
104
|
+
if (!STANDARD_FIELD_KEYS.has(key) && !DANGEROUS_KEYS.has(key)) {
|
|
105
|
+
properties[key] = structuredClone(schema);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return {
|
|
109
|
+
title: "ProblemDetails",
|
|
110
|
+
type: "object",
|
|
111
|
+
properties,
|
|
112
|
+
required: ["type", "status", "title"]
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
function problemDetailsResponseJsonSchema(status, description, schema) {
|
|
116
|
+
return {
|
|
117
|
+
content: {
|
|
118
|
+
"application/problem+json": { schema: schema ?? problemDetailsJsonSchema() }
|
|
119
|
+
},
|
|
120
|
+
description: description ?? statusToPhrase(status) ?? "Error"
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
124
|
+
0 && (module.exports = {
|
|
125
|
+
problemDetailsJsonSchema,
|
|
126
|
+
problemDetailsResponseJsonSchema
|
|
127
|
+
});
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
type JsonSchemaObject = Record<string, unknown>;
|
|
2
|
+
type ProblemDetailsJsonSchema = {
|
|
3
|
+
title: "ProblemDetails";
|
|
4
|
+
type: "object";
|
|
5
|
+
properties: Record<string, JsonSchemaObject>;
|
|
6
|
+
required: string[];
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Build the RFC 9457 Problem Details schema as plain JSON Schema
|
|
10
|
+
* (draft 2020-12, the OpenAPI 3.1 base dialect), for stacks that document
|
|
11
|
+
* responses without Zod (hono-openapi, Valibot, ArkType, typia, ...).
|
|
12
|
+
*
|
|
13
|
+
* Extensions are merged at top level per RFC 9457 §3.1, and **standard fields
|
|
14
|
+
* always win** over extension keys that collide (mirroring the runtime spread
|
|
15
|
+
* order in `problemDetails()`). Conflicting extension keys are silently
|
|
16
|
+
* dropped from the schema (see ADR-0002), as are the prototype-pollution
|
|
17
|
+
* guard keys `sanitizeExtensions` strips from every real response.
|
|
18
|
+
*
|
|
19
|
+
* A fresh object is returned on every call, with extension schemas cloned,
|
|
20
|
+
* so callers can safely mutate the result (e.g. append to `required`)
|
|
21
|
+
* without affecting other call sites or their own input.
|
|
22
|
+
*/
|
|
23
|
+
declare function problemDetailsJsonSchema(options?: {
|
|
24
|
+
extensions?: Record<string, JsonSchemaObject>;
|
|
25
|
+
}): ProblemDetailsJsonSchema;
|
|
26
|
+
/**
|
|
27
|
+
* Create an OpenAPI response object for Problem Details as plain JSON Schema.
|
|
28
|
+
* Ready to drop into hono-openapi's describeRoute():
|
|
29
|
+
* responses: { 422: problemDetailsResponseJsonSchema(422) }
|
|
30
|
+
*/
|
|
31
|
+
declare function problemDetailsResponseJsonSchema(status: number, description?: string, schema?: JsonSchemaObject): {
|
|
32
|
+
content: {
|
|
33
|
+
"application/problem+json": {
|
|
34
|
+
schema: JsonSchemaObject;
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
description: string;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export { type JsonSchemaObject, type ProblemDetailsJsonSchema, problemDetailsJsonSchema, problemDetailsResponseJsonSchema };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
type JsonSchemaObject = Record<string, unknown>;
|
|
2
|
+
type ProblemDetailsJsonSchema = {
|
|
3
|
+
title: "ProblemDetails";
|
|
4
|
+
type: "object";
|
|
5
|
+
properties: Record<string, JsonSchemaObject>;
|
|
6
|
+
required: string[];
|
|
7
|
+
};
|
|
8
|
+
/**
|
|
9
|
+
* Build the RFC 9457 Problem Details schema as plain JSON Schema
|
|
10
|
+
* (draft 2020-12, the OpenAPI 3.1 base dialect), for stacks that document
|
|
11
|
+
* responses without Zod (hono-openapi, Valibot, ArkType, typia, ...).
|
|
12
|
+
*
|
|
13
|
+
* Extensions are merged at top level per RFC 9457 §3.1, and **standard fields
|
|
14
|
+
* always win** over extension keys that collide (mirroring the runtime spread
|
|
15
|
+
* order in `problemDetails()`). Conflicting extension keys are silently
|
|
16
|
+
* dropped from the schema (see ADR-0002), as are the prototype-pollution
|
|
17
|
+
* guard keys `sanitizeExtensions` strips from every real response.
|
|
18
|
+
*
|
|
19
|
+
* A fresh object is returned on every call, with extension schemas cloned,
|
|
20
|
+
* so callers can safely mutate the result (e.g. append to `required`)
|
|
21
|
+
* without affecting other call sites or their own input.
|
|
22
|
+
*/
|
|
23
|
+
declare function problemDetailsJsonSchema(options?: {
|
|
24
|
+
extensions?: Record<string, JsonSchemaObject>;
|
|
25
|
+
}): ProblemDetailsJsonSchema;
|
|
26
|
+
/**
|
|
27
|
+
* Create an OpenAPI response object for Problem Details as plain JSON Schema.
|
|
28
|
+
* Ready to drop into hono-openapi's describeRoute():
|
|
29
|
+
* responses: { 422: problemDetailsResponseJsonSchema(422) }
|
|
30
|
+
*/
|
|
31
|
+
declare function problemDetailsResponseJsonSchema(status: number, description?: string, schema?: JsonSchemaObject): {
|
|
32
|
+
content: {
|
|
33
|
+
"application/problem+json": {
|
|
34
|
+
schema: JsonSchemaObject;
|
|
35
|
+
};
|
|
36
|
+
};
|
|
37
|
+
description: string;
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export { type JsonSchemaObject, type ProblemDetailsJsonSchema, problemDetailsJsonSchema, problemDetailsResponseJsonSchema };
|