hono-problem-details 0.2.0 → 0.3.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 +136 -16
- package/dist/{chunk-XPBA7IIJ.js → chunk-63332VQA.js} +2 -2
- package/dist/{chunk-NFHWC5GI.js → chunk-JW7PXR25.js} +1 -1
- package/dist/{chunk-GMDHMECS.js → chunk-O5AEI2VV.js} +2 -2
- package/dist/index.cjs +9 -0
- package/dist/index.d.cts +66 -2
- package/dist/index.d.ts +66 -2
- package/dist/index.js +11 -2
- package/dist/integrations/openapi.js +1 -1
- package/dist/integrations/standard-schema.d.cts +5 -0
- package/dist/integrations/standard-schema.d.ts +5 -0
- package/dist/integrations/standard-schema.js +3 -3
- package/dist/integrations/valibot.d.cts +4 -0
- package/dist/integrations/valibot.d.ts +4 -0
- package/dist/integrations/valibot.js +3 -3
- package/dist/integrations/zod.d.cts +4 -0
- package/dist/integrations/zod.d.ts +4 -0
- package/dist/integrations/zod.js +3 -3
- package/package.json +7 -4
- package/dist/chunk-GMDHMECS.js.map +0 -1
- package/dist/chunk-NFHWC5GI.js.map +0 -1
- package/dist/chunk-XPBA7IIJ.js.map +0 -1
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/integrations/openapi.cjs.map +0 -1
- package/dist/integrations/openapi.js.map +0 -1
- package/dist/integrations/standard-schema.cjs.map +0 -1
- package/dist/integrations/standard-schema.js.map +0 -1
- package/dist/integrations/valibot.cjs.map +0 -1
- package/dist/integrations/valibot.js.map +0 -1
- package/dist/integrations/zod.cjs.map +0 -1
- package/dist/integrations/zod.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
# hono-problem-details
|
|
2
2
|
|
|
3
3
|
[](https://www.npmjs.com/package/hono-problem-details)
|
|
4
|
+
[](https://www.npmjs.com/package/hono-problem-details)
|
|
5
|
+
[](https://bundlephobia.com/package/hono-problem-details)
|
|
6
|
+
[](https://github.com/paveg/hono-problem-details/stargazers)
|
|
4
7
|
[](https://github.com/paveg/hono-problem-details/actions/workflows/ci.yml)
|
|
5
8
|
[](https://opensource.org/licenses/MIT)
|
|
6
9
|
[](https://coderabbit.ai)
|
|
@@ -10,16 +13,34 @@
|
|
|
10
13
|
|
|
11
14
|
Returns `application/problem+json` structured error responses with a single `app.onError` setup.
|
|
12
15
|
|
|
16
|
+
> If this saved you from hand-rolling RFC 9457 in yet another Hono project, please [⭐ star the repo](https://github.com/paveg/hono-problem-details) — it helps others discover it.
|
|
17
|
+
|
|
18
|
+
## Why hono-problem-details?
|
|
19
|
+
|
|
20
|
+
Without a contract, HTTP error bodies drift. Every Hono project ends up reinventing the same
|
|
21
|
+
scaffolding — and every client ends up parsing whatever shows up.
|
|
22
|
+
|
|
23
|
+
- **Inconsistent shapes** across routes: `{ message }`, `{ error }`, `{ code, reason }`, or raw text
|
|
24
|
+
- **Validation errors** from each schema library return a different format, so clients special-case each
|
|
25
|
+
- **OpenAPI drift**: docs describe one error shape, the server returns another
|
|
26
|
+
- **No standard for extensions**: adding `retryAfter` or `correlationId` means breaking your own contract
|
|
27
|
+
|
|
28
|
+
[RFC 9457](https://www.rfc-editor.org/rfc/rfc9457.html) defines one structure — `{ type, status, title,
|
|
29
|
+
detail, instance }` plus arbitrary extension members — and this middleware makes it the default for every
|
|
30
|
+
error in your Hono app: thrown `ProblemDetailsError`, `HTTPException`, validation failures, and unhandled
|
|
31
|
+
exceptions alike. One `app.onError()` line, one contract your clients, OpenAPI spec, and integration tests
|
|
32
|
+
can all agree on.
|
|
33
|
+
|
|
13
34
|
## Features
|
|
14
35
|
|
|
15
|
-
- **RFC 9457 compliant** —
|
|
16
|
-
- **Hono native** — `app.onError` handler
|
|
36
|
+
- **RFC 9457 compliant** — `type`, `status`, `title`, `detail`, `instance` + extension members (flattened per §3.1, standard fields always win)
|
|
37
|
+
- **Hono native** — `app.onError` handler with RFC-compliant defaults
|
|
17
38
|
- **Zod integration** — `@hono/zod-validator` hook for validation errors
|
|
18
39
|
- **Valibot integration** — `@hono/valibot-validator` hook for validation errors
|
|
19
40
|
- **OpenAPI integration** — `@hono/zod-openapi` schemas for API documentation
|
|
20
41
|
- **Standard Schema** — `@hono/standard-validator` hook (works with any schema library)
|
|
21
42
|
- **Type-safe** — full TypeScript support with inference
|
|
22
|
-
- **Zero
|
|
43
|
+
- **Zero runtime dependencies** — `hono` is the only required peer dependency; validator integrations are optional
|
|
23
44
|
- **Localization** — `localize` callback for title/detail translation
|
|
24
45
|
- **Edge-first** — works on Cloudflare Workers, Deno, Bun, and Node.js
|
|
25
46
|
|
|
@@ -33,6 +54,7 @@ npm install hono-problem-details
|
|
|
33
54
|
|
|
34
55
|
```ts
|
|
35
56
|
import { Hono } from "hono";
|
|
57
|
+
import { HTTPException } from "hono/http-exception";
|
|
36
58
|
import { problemDetailsHandler } from "hono-problem-details";
|
|
37
59
|
|
|
38
60
|
const app = new Hono();
|
|
@@ -54,22 +76,90 @@ app.get("/not-found", (c) => {
|
|
|
54
76
|
// }
|
|
55
77
|
```
|
|
56
78
|
|
|
57
|
-
##
|
|
79
|
+
## Patterns
|
|
80
|
+
|
|
81
|
+
Common error shapes for day-to-day API work. Validation errors are covered separately by the
|
|
82
|
+
[Zod](#zod-validator-integration) / [Valibot](#valibot-validator-integration) / [Standard Schema](#standard-schema-integration)
|
|
83
|
+
hooks — this section is for errors you throw yourself.
|
|
58
84
|
|
|
59
85
|
```ts
|
|
60
86
|
import { problemDetails } from "hono-problem-details";
|
|
87
|
+
```
|
|
61
88
|
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
89
|
+
### Unauthorized — 401
|
|
90
|
+
|
|
91
|
+
```ts
|
|
92
|
+
throw problemDetails({
|
|
93
|
+
status: 401,
|
|
94
|
+
title: "Unauthorized",
|
|
95
|
+
detail: "Missing or invalid credentials",
|
|
96
|
+
type: "https://api.example.com/problems/unauthorized",
|
|
70
97
|
});
|
|
71
98
|
```
|
|
72
99
|
|
|
100
|
+
Clients key off `type` to trigger a re-auth flow — no need to parse `detail`.
|
|
101
|
+
|
|
102
|
+
### Forbidden — 403
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
throw problemDetails({
|
|
106
|
+
status: 403,
|
|
107
|
+
title: "Forbidden",
|
|
108
|
+
detail: `User ${userId} cannot access resource ${resourceId}`,
|
|
109
|
+
type: "https://api.example.com/problems/forbidden",
|
|
110
|
+
extensions: { requiredRole: "admin" },
|
|
111
|
+
});
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### Not Found — 404
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
throw problemDetails({
|
|
118
|
+
status: 404,
|
|
119
|
+
title: "Not Found",
|
|
120
|
+
detail: `Order ${orderId} does not exist`,
|
|
121
|
+
instance: `/orders/${orderId}`,
|
|
122
|
+
});
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
`instance` points at the specific occurrence — clients can use it as a key for retry logic
|
|
126
|
+
or deduplication.
|
|
127
|
+
|
|
128
|
+
> **Auto-fill shortcuts.** `title` is optional — when omitted, the standard HTTP reason phrase
|
|
129
|
+
> for `status` is used (`404` → `"Not Found"`). Similarly, `instance` can be populated from
|
|
130
|
+
> the request path automatically via `problemDetailsHandler({ autoInstance: true })`. Both
|
|
131
|
+
> shortcuts skip the boilerplate in the example above; explicit values always win.
|
|
132
|
+
|
|
133
|
+
### Conflict — 409
|
|
134
|
+
|
|
135
|
+
```ts
|
|
136
|
+
throw problemDetails({
|
|
137
|
+
status: 409,
|
|
138
|
+
title: "Order Conflict",
|
|
139
|
+
detail: `Order ${orderId} already exists`,
|
|
140
|
+
type: "https://api.example.com/problems/order-conflict",
|
|
141
|
+
instance: `/orders/${orderId}`,
|
|
142
|
+
});
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
Domain conflicts should always carry a project-specific `type` URI. `about:blank` is fine for
|
|
146
|
+
generic 4xx/5xx but loses its value the moment a client needs to distinguish two conflicts.
|
|
147
|
+
|
|
148
|
+
### Too Many Requests — 429
|
|
149
|
+
|
|
150
|
+
```ts
|
|
151
|
+
throw problemDetails({
|
|
152
|
+
status: 429,
|
|
153
|
+
title: "Too Many Requests",
|
|
154
|
+
detail: "Request quota exceeded",
|
|
155
|
+
type: "https://api.example.com/problems/rate-limited",
|
|
156
|
+
extensions: { retryAfter: 60, quota: 1000, remaining: 0 },
|
|
157
|
+
});
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Rate-limit metadata goes in `extensions` — clients read it straight from the body instead
|
|
161
|
+
of juggling `Retry-After` headers.
|
|
162
|
+
|
|
73
163
|
## Extension Members
|
|
74
164
|
|
|
75
165
|
Extension members are flattened to top level per RFC 9457:
|
|
@@ -128,6 +218,16 @@ throw problems.create("RATE_LIMITED", {
|
|
|
128
218
|
});
|
|
129
219
|
```
|
|
130
220
|
|
|
221
|
+
### When to use the registry vs `problemDetails()`
|
|
222
|
+
|
|
223
|
+
Reach for `createProblemTypeRegistry` when your API has a fixed set of domain errors and you
|
|
224
|
+
want one source of truth for `type` / `status` / `title`. It pays off the moment the same error
|
|
225
|
+
is thrown from more than one handler — renames and URI changes happen in one place.
|
|
226
|
+
|
|
227
|
+
Use `problemDetails()` directly for one-off errors, prototypes, or generic 4xx/5xx where
|
|
228
|
+
`about:blank` is the right `type`. RFC 9457 explicitly allows `about:blank` when the HTTP status
|
|
229
|
+
code alone is enough context — don't force a URI just to have one.
|
|
230
|
+
|
|
131
231
|
## Zod Validator Integration
|
|
132
232
|
|
|
133
233
|
```ts
|
|
@@ -242,14 +342,16 @@ const errorWithExtensions = createProblemDetailsSchema(
|
|
|
242
342
|
|
|
243
343
|
## Localization
|
|
244
344
|
|
|
245
|
-
Use the `localize` callback to translate `title` and `detail` based on the request context
|
|
345
|
+
Use the `localize` callback to translate `title` and `detail` based on the request context.
|
|
346
|
+
Return a partial patch with just the fields you want to override — everything else falls
|
|
347
|
+
through unchanged. Returning nothing (or `undefined`) leaves the response untouched.
|
|
246
348
|
|
|
247
349
|
```ts
|
|
248
350
|
problemDetailsHandler({
|
|
249
351
|
localize: (pd, c) => {
|
|
250
352
|
const lang = c.req.header("Accept-Language");
|
|
251
353
|
if (lang?.startsWith("ja")) {
|
|
252
|
-
return {
|
|
354
|
+
return { title: translate("ja", pd.title) };
|
|
253
355
|
}
|
|
254
356
|
return pd;
|
|
255
357
|
},
|
|
@@ -258,6 +360,16 @@ problemDetailsHandler({
|
|
|
258
360
|
|
|
259
361
|
The callback receives the fully-built `ProblemDetails` object and the Hono `Context`, allowing access to headers like `Accept-Language`. Return a new `ProblemDetails` with translated fields.
|
|
260
362
|
|
|
363
|
+
> **Note on caching**: If your responses vary by `Accept-Language`, add `Vary: Accept-Language`
|
|
364
|
+
> from your own middleware so CDNs and browser caches don't serve the wrong translation.
|
|
365
|
+
> This middleware intentionally does not set `Vary` — error handlers shouldn't mutate
|
|
366
|
+
> request-scope headers that also apply to successful responses.
|
|
367
|
+
|
|
368
|
+
> **Note on failures**: If your `localize` callback throws, the handler falls back to the
|
|
369
|
+
> un-localized `ProblemDetails` and continues. Throwing from inside `app.onError` would cause
|
|
370
|
+
> the error handler to re-enter itself, so the swallow is deliberate. Catch errors inside your
|
|
371
|
+
> callback if you need to observe them.
|
|
372
|
+
|
|
261
373
|
## Handler Options
|
|
262
374
|
|
|
263
375
|
```ts
|
|
@@ -271,8 +383,15 @@ problemDetailsHandler({
|
|
|
271
383
|
// Include stack trace in detail (for development)
|
|
272
384
|
includeStack: process.env.NODE_ENV === "development",
|
|
273
385
|
|
|
274
|
-
//
|
|
275
|
-
|
|
386
|
+
// Populate `instance` from `c.req.path` when the thrown problem didn't specify one
|
|
387
|
+
autoInstance: true,
|
|
388
|
+
|
|
389
|
+
// Localize title/detail before sending the response.
|
|
390
|
+
// Return a partial patch — fields you omit fall through from the original.
|
|
391
|
+
localize: (pd, c) => {
|
|
392
|
+
const lang = c.req.header("Accept-Language") ?? "en";
|
|
393
|
+
return { title: `[${lang}] ${pd.title}` };
|
|
394
|
+
},
|
|
276
395
|
|
|
277
396
|
// Custom error mapping
|
|
278
397
|
mapError: (error) => {
|
|
@@ -294,6 +413,7 @@ The following Hono middleware libraries use `hono-problem-details` as an optiona
|
|
|
294
413
|
|
|
295
414
|
- [hono-idempotency](https://github.com/paveg/hono-idempotency) — Idempotency key middleware for Hono
|
|
296
415
|
- [hono-webhook-verify](https://github.com/paveg/hono-webhook-verify) — Webhook signature verification middleware for Hono
|
|
416
|
+
- [hono-cf-access](https://github.com/paveg/hono-cf-access) — Country / ASN blocking and maintenance mode via Cloudflare Workers `request.cf`
|
|
297
417
|
|
|
298
418
|
## License
|
|
299
419
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
statusToPhrase
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-JW7PXR25.js";
|
|
4
4
|
|
|
5
5
|
// src/utils.ts
|
|
6
6
|
var PROBLEM_JSON_CONTENT_TYPE = "application/problem+json; charset=utf-8";
|
|
@@ -56,4 +56,4 @@ export {
|
|
|
56
56
|
normalizeProblemDetails,
|
|
57
57
|
buildProblemResponse
|
|
58
58
|
};
|
|
59
|
-
//# sourceMappingURL=chunk-
|
|
59
|
+
//# sourceMappingURL=chunk-63332VQA.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
PROBLEM_JSON_CONTENT_TYPE
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-63332VQA.js";
|
|
4
4
|
|
|
5
5
|
// src/integrations/validation.ts
|
|
6
6
|
var CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/g;
|
|
@@ -31,4 +31,4 @@ function buildValidationResponse(errors, options) {
|
|
|
31
31
|
export {
|
|
32
32
|
buildValidationResponse
|
|
33
33
|
};
|
|
34
|
-
//# sourceMappingURL=chunk-
|
|
34
|
+
//# sourceMappingURL=chunk-O5AEI2VV.js.map
|
package/dist/index.cjs
CHANGED
|
@@ -137,13 +137,19 @@ function safeStringify(body) {
|
|
|
137
137
|
|
|
138
138
|
// src/error.ts
|
|
139
139
|
var ProblemDetailsError = class extends Error {
|
|
140
|
+
/** The normalized RFC 9457 Problem Details object. */
|
|
140
141
|
problemDetails;
|
|
142
|
+
/**
|
|
143
|
+
* @param input - Missing `type` defaults to `"about:blank"`;
|
|
144
|
+
* missing `title` is derived from the HTTP status code.
|
|
145
|
+
*/
|
|
141
146
|
constructor(input) {
|
|
142
147
|
const pd = normalizeProblemDetails(input);
|
|
143
148
|
super(pd.detail ?? pd.title);
|
|
144
149
|
this.name = "ProblemDetailsError";
|
|
145
150
|
this.problemDetails = pd;
|
|
146
151
|
}
|
|
152
|
+
/** Build a standalone `application/problem+json` Response without the handler middleware. */
|
|
147
153
|
getResponse() {
|
|
148
154
|
return buildProblemResponse(this.problemDetails);
|
|
149
155
|
}
|
|
@@ -165,6 +171,9 @@ function buildType(status, options) {
|
|
|
165
171
|
}
|
|
166
172
|
function toResponse(input, c, options) {
|
|
167
173
|
let pd = normalizeProblemDetails(input);
|
|
174
|
+
if (options.autoInstance && pd.instance === void 0) {
|
|
175
|
+
pd = { ...pd, instance: c.req.path };
|
|
176
|
+
}
|
|
168
177
|
if (options.localize) {
|
|
169
178
|
try {
|
|
170
179
|
pd = { ...pd, ...options.localize(pd, c) };
|
package/dist/index.d.cts
CHANGED
|
@@ -40,25 +40,74 @@ interface ProblemDetailsHandlerOptions {
|
|
|
40
40
|
defaultType?: string;
|
|
41
41
|
/** Include stack trace in detail (for development) */
|
|
42
42
|
includeStack?: boolean;
|
|
43
|
+
/**
|
|
44
|
+
* When `true`, populate `instance` from the request path (`c.req.path`) if
|
|
45
|
+
* the thrown problem didn't specify one. Explicit values always win.
|
|
46
|
+
* Default: `false` — opt-in to avoid silently changing response shape.
|
|
47
|
+
*/
|
|
48
|
+
autoInstance?: boolean;
|
|
43
49
|
/** Custom error to ProblemDetails mapping */
|
|
44
50
|
mapError?: (error: Error) => ProblemDetailsInput | undefined;
|
|
45
|
-
/**
|
|
46
|
-
|
|
51
|
+
/**
|
|
52
|
+
* Localize title/detail before sending the response.
|
|
53
|
+
* Returned fields are merged onto the original ProblemDetails, so callers may
|
|
54
|
+
* return a partial patch (e.g. `{ title: "..." }`) or omit the return entirely.
|
|
55
|
+
*/
|
|
56
|
+
localize?: (pd: ProblemDetails, c: Context) => Partial<ProblemDetails> | undefined;
|
|
47
57
|
}
|
|
48
58
|
|
|
59
|
+
/** Look up the standard HTTP reason phrase for a status code (e.g. 404 → `"Not Found"`). */
|
|
49
60
|
declare function statusToPhrase(status: number): string | undefined;
|
|
61
|
+
/** Look up a URL-safe slug for a status code (e.g. 404 → `"not-found"`). Used by the `typePrefix` handler option. */
|
|
50
62
|
declare function statusToSlug(status: number): string | undefined;
|
|
51
63
|
|
|
64
|
+
/**
|
|
65
|
+
* Error class for RFC 9457 Problem Details.
|
|
66
|
+
* Thrown by {@link problemDetails} and caught by the handler to produce
|
|
67
|
+
* `application/problem+json` responses.
|
|
68
|
+
*/
|
|
52
69
|
declare class ProblemDetailsError extends Error {
|
|
70
|
+
/** The normalized RFC 9457 Problem Details object. */
|
|
53
71
|
readonly problemDetails: ProblemDetails;
|
|
72
|
+
/**
|
|
73
|
+
* @param input - Missing `type` defaults to `"about:blank"`;
|
|
74
|
+
* missing `title` is derived from the HTTP status code.
|
|
75
|
+
*/
|
|
54
76
|
constructor(input: ProblemDetailsInput);
|
|
77
|
+
/** Build a standalone `application/problem+json` Response without the handler middleware. */
|
|
55
78
|
getResponse(): Response;
|
|
56
79
|
}
|
|
57
80
|
|
|
81
|
+
/**
|
|
82
|
+
* Create a {@link ProblemDetailsError} from the given input.
|
|
83
|
+
* Missing `type` defaults to `"about:blank"`; missing `title` is derived from the status code.
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```ts
|
|
87
|
+
* throw problemDetails({
|
|
88
|
+
* status: 404,
|
|
89
|
+
* detail: `Order ${orderId} does not exist`,
|
|
90
|
+
* });
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
58
93
|
declare function problemDetails<T extends Record<string, unknown>>(input: ProblemDetailsInput<T>): ProblemDetailsError;
|
|
59
94
|
|
|
95
|
+
/** RFC 9457 media type: `application/problem+json; charset=utf-8`. */
|
|
60
96
|
declare const PROBLEM_JSON_CONTENT_TYPE = "application/problem+json; charset=utf-8";
|
|
61
97
|
|
|
98
|
+
/**
|
|
99
|
+
* Create an `app.onError` handler that returns RFC 9457 Problem Details responses.
|
|
100
|
+
* Handles {@link ProblemDetailsError}, Hono `HTTPException`, and unhandled exceptions.
|
|
101
|
+
*
|
|
102
|
+
* @example
|
|
103
|
+
* ```ts
|
|
104
|
+
* import { Hono } from "hono";
|
|
105
|
+
* import { problemDetailsHandler } from "hono-problem-details";
|
|
106
|
+
*
|
|
107
|
+
* const app = new Hono();
|
|
108
|
+
* app.onError(problemDetailsHandler());
|
|
109
|
+
* ```
|
|
110
|
+
*/
|
|
62
111
|
declare function problemDetailsHandler(options?: ProblemDetailsHandlerOptions): ErrorHandler;
|
|
63
112
|
|
|
64
113
|
interface ProblemTypeDefinition {
|
|
@@ -72,13 +121,28 @@ interface CreateOptions<T extends Record<string, unknown> = Record<string, unkno
|
|
|
72
121
|
extensions?: T;
|
|
73
122
|
}
|
|
74
123
|
interface ProblemTypeRegistry<K extends string> {
|
|
124
|
+
/** Create a {@link ProblemDetailsError} from a registered problem type key. */
|
|
75
125
|
create: <T extends Record<string, unknown>>(key: K, options?: CreateOptions<T>) => ProblemDetailsError;
|
|
126
|
+
/** Get the base definition (type, status, title) for a registered key. */
|
|
76
127
|
get: (key: K) => ProblemTypeDefinition;
|
|
128
|
+
/** List all registered problem type keys. */
|
|
77
129
|
types: () => K[];
|
|
78
130
|
}
|
|
79
131
|
/**
|
|
80
132
|
* Create a registry of pre-defined problem types.
|
|
81
133
|
* Provides type-safe error creation from registered definitions.
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* ```ts
|
|
137
|
+
* const problems = createProblemTypeRegistry({
|
|
138
|
+
* ORDER_CONFLICT: {
|
|
139
|
+
* type: "https://api.example.com/problems/order-conflict",
|
|
140
|
+
* status: 409,
|
|
141
|
+
* title: "Order Conflict",
|
|
142
|
+
* },
|
|
143
|
+
* });
|
|
144
|
+
* throw problems.create("ORDER_CONFLICT", { detail: "Already exists" });
|
|
145
|
+
* ```
|
|
82
146
|
*/
|
|
83
147
|
declare function createProblemTypeRegistry<K extends string>(definitions: Record<K, ProblemTypeDefinition>): ProblemTypeRegistry<K>;
|
|
84
148
|
|
package/dist/index.d.ts
CHANGED
|
@@ -40,25 +40,74 @@ interface ProblemDetailsHandlerOptions {
|
|
|
40
40
|
defaultType?: string;
|
|
41
41
|
/** Include stack trace in detail (for development) */
|
|
42
42
|
includeStack?: boolean;
|
|
43
|
+
/**
|
|
44
|
+
* When `true`, populate `instance` from the request path (`c.req.path`) if
|
|
45
|
+
* the thrown problem didn't specify one. Explicit values always win.
|
|
46
|
+
* Default: `false` — opt-in to avoid silently changing response shape.
|
|
47
|
+
*/
|
|
48
|
+
autoInstance?: boolean;
|
|
43
49
|
/** Custom error to ProblemDetails mapping */
|
|
44
50
|
mapError?: (error: Error) => ProblemDetailsInput | undefined;
|
|
45
|
-
/**
|
|
46
|
-
|
|
51
|
+
/**
|
|
52
|
+
* Localize title/detail before sending the response.
|
|
53
|
+
* Returned fields are merged onto the original ProblemDetails, so callers may
|
|
54
|
+
* return a partial patch (e.g. `{ title: "..." }`) or omit the return entirely.
|
|
55
|
+
*/
|
|
56
|
+
localize?: (pd: ProblemDetails, c: Context) => Partial<ProblemDetails> | undefined;
|
|
47
57
|
}
|
|
48
58
|
|
|
59
|
+
/** Look up the standard HTTP reason phrase for a status code (e.g. 404 → `"Not Found"`). */
|
|
49
60
|
declare function statusToPhrase(status: number): string | undefined;
|
|
61
|
+
/** Look up a URL-safe slug for a status code (e.g. 404 → `"not-found"`). Used by the `typePrefix` handler option. */
|
|
50
62
|
declare function statusToSlug(status: number): string | undefined;
|
|
51
63
|
|
|
64
|
+
/**
|
|
65
|
+
* Error class for RFC 9457 Problem Details.
|
|
66
|
+
* Thrown by {@link problemDetails} and caught by the handler to produce
|
|
67
|
+
* `application/problem+json` responses.
|
|
68
|
+
*/
|
|
52
69
|
declare class ProblemDetailsError extends Error {
|
|
70
|
+
/** The normalized RFC 9457 Problem Details object. */
|
|
53
71
|
readonly problemDetails: ProblemDetails;
|
|
72
|
+
/**
|
|
73
|
+
* @param input - Missing `type` defaults to `"about:blank"`;
|
|
74
|
+
* missing `title` is derived from the HTTP status code.
|
|
75
|
+
*/
|
|
54
76
|
constructor(input: ProblemDetailsInput);
|
|
77
|
+
/** Build a standalone `application/problem+json` Response without the handler middleware. */
|
|
55
78
|
getResponse(): Response;
|
|
56
79
|
}
|
|
57
80
|
|
|
81
|
+
/**
|
|
82
|
+
* Create a {@link ProblemDetailsError} from the given input.
|
|
83
|
+
* Missing `type` defaults to `"about:blank"`; missing `title` is derived from the status code.
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```ts
|
|
87
|
+
* throw problemDetails({
|
|
88
|
+
* status: 404,
|
|
89
|
+
* detail: `Order ${orderId} does not exist`,
|
|
90
|
+
* });
|
|
91
|
+
* ```
|
|
92
|
+
*/
|
|
58
93
|
declare function problemDetails<T extends Record<string, unknown>>(input: ProblemDetailsInput<T>): ProblemDetailsError;
|
|
59
94
|
|
|
95
|
+
/** RFC 9457 media type: `application/problem+json; charset=utf-8`. */
|
|
60
96
|
declare const PROBLEM_JSON_CONTENT_TYPE = "application/problem+json; charset=utf-8";
|
|
61
97
|
|
|
98
|
+
/**
|
|
99
|
+
* Create an `app.onError` handler that returns RFC 9457 Problem Details responses.
|
|
100
|
+
* Handles {@link ProblemDetailsError}, Hono `HTTPException`, and unhandled exceptions.
|
|
101
|
+
*
|
|
102
|
+
* @example
|
|
103
|
+
* ```ts
|
|
104
|
+
* import { Hono } from "hono";
|
|
105
|
+
* import { problemDetailsHandler } from "hono-problem-details";
|
|
106
|
+
*
|
|
107
|
+
* const app = new Hono();
|
|
108
|
+
* app.onError(problemDetailsHandler());
|
|
109
|
+
* ```
|
|
110
|
+
*/
|
|
62
111
|
declare function problemDetailsHandler(options?: ProblemDetailsHandlerOptions): ErrorHandler;
|
|
63
112
|
|
|
64
113
|
interface ProblemTypeDefinition {
|
|
@@ -72,13 +121,28 @@ interface CreateOptions<T extends Record<string, unknown> = Record<string, unkno
|
|
|
72
121
|
extensions?: T;
|
|
73
122
|
}
|
|
74
123
|
interface ProblemTypeRegistry<K extends string> {
|
|
124
|
+
/** Create a {@link ProblemDetailsError} from a registered problem type key. */
|
|
75
125
|
create: <T extends Record<string, unknown>>(key: K, options?: CreateOptions<T>) => ProblemDetailsError;
|
|
126
|
+
/** Get the base definition (type, status, title) for a registered key. */
|
|
76
127
|
get: (key: K) => ProblemTypeDefinition;
|
|
128
|
+
/** List all registered problem type keys. */
|
|
77
129
|
types: () => K[];
|
|
78
130
|
}
|
|
79
131
|
/**
|
|
80
132
|
* Create a registry of pre-defined problem types.
|
|
81
133
|
* Provides type-safe error creation from registered definitions.
|
|
134
|
+
*
|
|
135
|
+
* @example
|
|
136
|
+
* ```ts
|
|
137
|
+
* const problems = createProblemTypeRegistry({
|
|
138
|
+
* ORDER_CONFLICT: {
|
|
139
|
+
* type: "https://api.example.com/problems/order-conflict",
|
|
140
|
+
* status: 409,
|
|
141
|
+
* title: "Order Conflict",
|
|
142
|
+
* },
|
|
143
|
+
* });
|
|
144
|
+
* throw problems.create("ORDER_CONFLICT", { detail: "Already exists" });
|
|
145
|
+
* ```
|
|
82
146
|
*/
|
|
83
147
|
declare function createProblemTypeRegistry<K extends string>(definitions: Record<K, ProblemTypeDefinition>): ProblemTypeRegistry<K>;
|
|
84
148
|
|
package/dist/index.js
CHANGED
|
@@ -2,21 +2,27 @@ import {
|
|
|
2
2
|
PROBLEM_JSON_CONTENT_TYPE,
|
|
3
3
|
buildProblemResponse,
|
|
4
4
|
normalizeProblemDetails
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-63332VQA.js";
|
|
6
6
|
import {
|
|
7
7
|
statusToPhrase,
|
|
8
8
|
statusToSlug
|
|
9
|
-
} from "./chunk-
|
|
9
|
+
} from "./chunk-JW7PXR25.js";
|
|
10
10
|
|
|
11
11
|
// src/error.ts
|
|
12
12
|
var ProblemDetailsError = class extends Error {
|
|
13
|
+
/** The normalized RFC 9457 Problem Details object. */
|
|
13
14
|
problemDetails;
|
|
15
|
+
/**
|
|
16
|
+
* @param input - Missing `type` defaults to `"about:blank"`;
|
|
17
|
+
* missing `title` is derived from the HTTP status code.
|
|
18
|
+
*/
|
|
14
19
|
constructor(input) {
|
|
15
20
|
const pd = normalizeProblemDetails(input);
|
|
16
21
|
super(pd.detail ?? pd.title);
|
|
17
22
|
this.name = "ProblemDetailsError";
|
|
18
23
|
this.problemDetails = pd;
|
|
19
24
|
}
|
|
25
|
+
/** Build a standalone `application/problem+json` Response without the handler middleware. */
|
|
20
26
|
getResponse() {
|
|
21
27
|
return buildProblemResponse(this.problemDetails);
|
|
22
28
|
}
|
|
@@ -38,6 +44,9 @@ function buildType(status, options) {
|
|
|
38
44
|
}
|
|
39
45
|
function toResponse(input, c, options) {
|
|
40
46
|
let pd = normalizeProblemDetails(input);
|
|
47
|
+
if (options.autoInstance && pd.instance === void 0) {
|
|
48
|
+
pd = { ...pd, instance: c.req.path };
|
|
49
|
+
}
|
|
41
50
|
if (options.localize) {
|
|
42
51
|
try {
|
|
43
52
|
pd = { ...pd, ...options.localize(pd, c) };
|
|
@@ -2,6 +2,11 @@ import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
|
2
2
|
import { Context } from 'hono';
|
|
3
3
|
import { V as ValidationHookOptions } from '../validation-DqPEnoIw.cjs';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Create a `@hono/standard-validator` hook that returns RFC 9457 Problem Details
|
|
7
|
+
* on validation failure (422 Unprocessable Content with `errors` extension).
|
|
8
|
+
* Works with any Standard Schema-compatible library (Zod, Valibot, ArkType, etc.).
|
|
9
|
+
*/
|
|
5
10
|
declare function standardSchemaProblemHook(options?: ValidationHookOptions): (result: {
|
|
6
11
|
success: true;
|
|
7
12
|
data: unknown;
|
|
@@ -2,6 +2,11 @@ import { StandardSchemaV1 } from '@standard-schema/spec';
|
|
|
2
2
|
import { Context } from 'hono';
|
|
3
3
|
import { V as ValidationHookOptions } from '../validation-DqPEnoIw.js';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Create a `@hono/standard-validator` hook that returns RFC 9457 Problem Details
|
|
7
|
+
* on validation failure (422 Unprocessable Content with `errors` extension).
|
|
8
|
+
* Works with any Standard Schema-compatible library (Zod, Valibot, ArkType, etc.).
|
|
9
|
+
*/
|
|
5
10
|
declare function standardSchemaProblemHook(options?: ValidationHookOptions): (result: {
|
|
6
11
|
success: true;
|
|
7
12
|
data: unknown;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
buildValidationResponse
|
|
3
|
-
} from "../chunk-
|
|
4
|
-
import "../chunk-
|
|
5
|
-
import "../chunk-
|
|
3
|
+
} from "../chunk-O5AEI2VV.js";
|
|
4
|
+
import "../chunk-63332VQA.js";
|
|
5
|
+
import "../chunk-JW7PXR25.js";
|
|
6
6
|
|
|
7
7
|
// src/integrations/standard-schema.ts
|
|
8
8
|
function formatPath(path) {
|
|
@@ -2,6 +2,10 @@ import { Context } from 'hono';
|
|
|
2
2
|
import { GenericSchema, GenericSchemaAsync, SafeParseResult } from 'valibot';
|
|
3
3
|
import { V as ValidationHookOptions } from '../validation-DqPEnoIw.cjs';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Create a `@hono/valibot-validator` hook that returns RFC 9457 Problem Details
|
|
7
|
+
* on validation failure (422 Unprocessable Content with `errors` extension).
|
|
8
|
+
*/
|
|
5
9
|
declare function valibotProblemHook<T extends GenericSchema | GenericSchemaAsync = GenericSchema>(options?: ValidationHookOptions): (result: SafeParseResult<T> & {
|
|
6
10
|
target: string;
|
|
7
11
|
}, c: Context) => Response | undefined;
|
|
@@ -2,6 +2,10 @@ import { Context } from 'hono';
|
|
|
2
2
|
import { GenericSchema, GenericSchemaAsync, SafeParseResult } from 'valibot';
|
|
3
3
|
import { V as ValidationHookOptions } from '../validation-DqPEnoIw.js';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Create a `@hono/valibot-validator` hook that returns RFC 9457 Problem Details
|
|
7
|
+
* on validation failure (422 Unprocessable Content with `errors` extension).
|
|
8
|
+
*/
|
|
5
9
|
declare function valibotProblemHook<T extends GenericSchema | GenericSchemaAsync = GenericSchema>(options?: ValidationHookOptions): (result: SafeParseResult<T> & {
|
|
6
10
|
target: string;
|
|
7
11
|
}, c: Context) => Response | undefined;
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
buildValidationResponse
|
|
3
|
-
} from "../chunk-
|
|
4
|
-
import "../chunk-
|
|
5
|
-
import "../chunk-
|
|
3
|
+
} from "../chunk-O5AEI2VV.js";
|
|
4
|
+
import "../chunk-63332VQA.js";
|
|
5
|
+
import "../chunk-JW7PXR25.js";
|
|
6
6
|
|
|
7
7
|
// src/integrations/valibot.ts
|
|
8
8
|
function formatIssues(issues) {
|
|
@@ -2,6 +2,10 @@ import { Context } from 'hono';
|
|
|
2
2
|
import { ZodError } from 'zod';
|
|
3
3
|
import { V as ValidationHookOptions } from '../validation-DqPEnoIw.cjs';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Create a `@hono/zod-validator` hook that returns RFC 9457 Problem Details
|
|
7
|
+
* on validation failure (422 Unprocessable Content with `errors` extension).
|
|
8
|
+
*/
|
|
5
9
|
declare function zodProblemHook(options?: ValidationHookOptions): (result: {
|
|
6
10
|
success: true;
|
|
7
11
|
data: unknown;
|
|
@@ -2,6 +2,10 @@ import { Context } from 'hono';
|
|
|
2
2
|
import { ZodError } from 'zod';
|
|
3
3
|
import { V as ValidationHookOptions } from '../validation-DqPEnoIw.js';
|
|
4
4
|
|
|
5
|
+
/**
|
|
6
|
+
* Create a `@hono/zod-validator` hook that returns RFC 9457 Problem Details
|
|
7
|
+
* on validation failure (422 Unprocessable Content with `errors` extension).
|
|
8
|
+
*/
|
|
5
9
|
declare function zodProblemHook(options?: ValidationHookOptions): (result: {
|
|
6
10
|
success: true;
|
|
7
11
|
data: unknown;
|
package/dist/integrations/zod.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import {
|
|
2
2
|
buildValidationResponse
|
|
3
|
-
} from "../chunk-
|
|
4
|
-
import "../chunk-
|
|
5
|
-
import "../chunk-
|
|
3
|
+
} from "../chunk-O5AEI2VV.js";
|
|
4
|
+
import "../chunk-63332VQA.js";
|
|
5
|
+
import "../chunk-JW7PXR25.js";
|
|
6
6
|
|
|
7
7
|
// src/integrations/zod.ts
|
|
8
8
|
function formatErrors(zodError) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "hono-problem-details",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "RFC 9457 Problem Details middleware for Hono",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -75,7 +75,8 @@
|
|
|
75
75
|
}
|
|
76
76
|
},
|
|
77
77
|
"files": [
|
|
78
|
-
"dist"
|
|
78
|
+
"dist",
|
|
79
|
+
"!dist/**/*.map"
|
|
79
80
|
],
|
|
80
81
|
"sideEffects": false,
|
|
81
82
|
"keywords": [
|
|
@@ -97,13 +98,14 @@
|
|
|
97
98
|
"bugs": "https://github.com/paveg/hono-problem-details/issues",
|
|
98
99
|
"license": "MIT",
|
|
99
100
|
"author": "Ryota Ikezawa",
|
|
101
|
+
"funding": "https://github.com/sponsors/paveg",
|
|
100
102
|
"peerDependencies": {
|
|
101
103
|
"@hono/standard-validator": "^0.2.0",
|
|
102
104
|
"@hono/valibot-validator": "^0.6.0",
|
|
103
105
|
"@hono/zod-openapi": "^0.19.0",
|
|
104
106
|
"@hono/zod-validator": "^0.7.5",
|
|
105
107
|
"@standard-schema/spec": "^1.0.0",
|
|
106
|
-
"hono": ">=4.
|
|
108
|
+
"hono": ">=4.12.14",
|
|
107
109
|
"valibot": "^1.0.0",
|
|
108
110
|
"zod": "^3.25.0"
|
|
109
111
|
},
|
|
@@ -140,7 +142,7 @@
|
|
|
140
142
|
"@hono/zod-validator": "^0.7.6",
|
|
141
143
|
"@standard-schema/spec": "1.1.0",
|
|
142
144
|
"@vitest/coverage-v8": "^3.0.0",
|
|
143
|
-
"hono": "^4.
|
|
145
|
+
"hono": "^4.12.14",
|
|
144
146
|
"lefthook": "2.1.5",
|
|
145
147
|
"tsup": "^8.0.0",
|
|
146
148
|
"typescript": "^5.7.0",
|
|
@@ -158,6 +160,7 @@
|
|
|
158
160
|
"scripts": {
|
|
159
161
|
"build": "tsup",
|
|
160
162
|
"test": "vitest run",
|
|
163
|
+
"bench": "vitest bench",
|
|
161
164
|
"test:watch": "vitest",
|
|
162
165
|
"lint": "biome check .",
|
|
163
166
|
"lint:fix": "biome check --write .",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/integrations/validation.ts"],"sourcesContent":["import { PROBLEM_JSON_CONTENT_TYPE } from \"../utils.js\";\n\nexport interface ValidationError {\n\tfield: string;\n\tmessage: string;\n\tcode?: string;\n}\n\nexport interface ValidationHookOptions {\n\ttitle?: string;\n\tdetail?: string;\n}\n\n/**\n * Strip C0 control characters (\\x00-\\x1f) and DEL (\\x7f) from untrusted text.\n * Bidi/format control chars (U+2028, U+202E, etc.) are intentionally left intact\n * to avoid breaking legitimate i18n content; log consumers should apply their\n * own bidi-safe rendering.\n */\n// biome-ignore lint/suspicious/noControlCharactersInRegex: intentional stripping of C0 controls\nconst CONTROL_CHAR_RE = /[\\x00-\\x1f\\x7f]/g;\n\nfunction stripControlChars(input: string): string {\n\treturn input.replace(CONTROL_CHAR_RE, \"\");\n}\n\nfunction sanitizeError(error: ValidationError): ValidationError {\n\treturn {\n\t\tfield: stripControlChars(error.field),\n\t\tmessage: stripControlChars(error.message),\n\t\t...(error.code !== undefined ? { code: stripControlChars(error.code) } : {}),\n\t};\n}\n\n/** Build a RFC 9457 validation error response from formatted errors */\nexport function buildValidationResponse(\n\terrors: ValidationError[],\n\toptions?: ValidationHookOptions,\n): Response {\n\tconst body = {\n\t\ttype: \"about:blank\",\n\t\tstatus: 422,\n\t\ttitle: options?.title ?? \"Validation Error\",\n\t\tdetail: options?.detail ?? \"Request validation failed\",\n\t\terrors: errors.map(sanitizeError),\n\t};\n\n\treturn new Response(JSON.stringify(body), {\n\t\tstatus: 422,\n\t\theaders: { \"Content-Type\": PROBLEM_JSON_CONTENT_TYPE },\n\t});\n}\n"],"mappings":";;;;;AAoBA,IAAM,kBAAkB;AAExB,SAAS,kBAAkB,OAAuB;AACjD,SAAO,MAAM,QAAQ,iBAAiB,EAAE;AACzC;AAEA,SAAS,cAAc,OAAyC;AAC/D,SAAO;AAAA,IACN,OAAO,kBAAkB,MAAM,KAAK;AAAA,IACpC,SAAS,kBAAkB,MAAM,OAAO;AAAA,IACxC,GAAI,MAAM,SAAS,SAAY,EAAE,MAAM,kBAAkB,MAAM,IAAI,EAAE,IAAI,CAAC;AAAA,EAC3E;AACD;AAGO,SAAS,wBACf,QACA,SACW;AACX,QAAM,OAAO;AAAA,IACZ,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,OAAO,SAAS,SAAS;AAAA,IACzB,QAAQ,SAAS,UAAU;AAAA,IAC3B,QAAQ,OAAO,IAAI,aAAa;AAAA,EACjC;AAEA,SAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;AAAA,IACzC,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,0BAA0B;AAAA,EACtD,CAAC;AACF;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/status.ts"],"sourcesContent":["const STATUS_PHRASES: Record<number, string> = {\n\t400: \"Bad Request\",\n\t401: \"Unauthorized\",\n\t402: \"Payment Required\",\n\t403: \"Forbidden\",\n\t404: \"Not Found\",\n\t405: \"Method Not Allowed\",\n\t406: \"Not Acceptable\",\n\t407: \"Proxy Authentication Required\",\n\t408: \"Request Timeout\",\n\t409: \"Conflict\",\n\t410: \"Gone\",\n\t411: \"Length Required\",\n\t412: \"Precondition Failed\",\n\t413: \"Content Too Large\",\n\t414: \"URI Too Long\",\n\t415: \"Unsupported Media Type\",\n\t416: \"Range Not Satisfiable\",\n\t417: \"Expectation Failed\",\n\t418: \"I'm a Teapot\",\n\t421: \"Misdirected Request\",\n\t422: \"Unprocessable Content\",\n\t423: \"Locked\",\n\t424: \"Failed Dependency\",\n\t425: \"Too Early\",\n\t426: \"Upgrade Required\",\n\t428: \"Precondition Required\",\n\t429: \"Too Many Requests\",\n\t431: \"Request Header Fields Too Large\",\n\t451: \"Unavailable For Legal Reasons\",\n\t500: \"Internal Server Error\",\n\t501: \"Not Implemented\",\n\t502: \"Bad Gateway\",\n\t503: \"Service Unavailable\",\n\t504: \"Gateway Timeout\",\n\t505: \"HTTP Version Not Supported\",\n\t506: \"Variant Also Negotiates\",\n\t507: \"Insufficient Storage\",\n\t508: \"Loop Detected\",\n\t510: \"Not Extended\",\n\t511: \"Network Authentication Required\",\n};\n\nconst STATUS_SLUGS: Record<number, string> = Object.fromEntries(\n\tObject.entries(STATUS_PHRASES).map(([code, phrase]) => [\n\t\tNumber(code),\n\t\tphrase\n\t\t\t.toLowerCase()\n\t\t\t.replace(/'/g, \"\")\n\t\t\t.replace(/[^a-z0-9]+/g, \"-\")\n\t\t\t.replace(/^-|-$/g, \"\"),\n\t]),\n);\n\nexport function statusToPhrase(status: number): string | undefined {\n\treturn STATUS_PHRASES[status];\n}\n\nexport function statusToSlug(status: number): string | undefined {\n\treturn STATUS_SLUGS[status];\n}\n"],"mappings":";AAAA,IAAM,iBAAyC;AAAA,EAC9C,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACN;AAEA,IAAM,eAAuC,OAAO;AAAA,EACnD,OAAO,QAAQ,cAAc,EAAE,IAAI,CAAC,CAAC,MAAM,MAAM,MAAM;AAAA,IACtD,OAAO,IAAI;AAAA,IACX,OACE,YAAY,EACZ,QAAQ,MAAM,EAAE,EAChB,QAAQ,eAAe,GAAG,EAC1B,QAAQ,UAAU,EAAE;AAAA,EACvB,CAAC;AACF;AAEO,SAAS,eAAe,QAAoC;AAClE,SAAO,eAAe,MAAM;AAC7B;AAEO,SAAS,aAAa,QAAoC;AAChE,SAAO,aAAa,MAAM;AAC3B;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils.ts"],"sourcesContent":["import { statusToPhrase } from \"./status.js\";\nimport type { ProblemDetails, ProblemDetailsInput } from \"./types.js\";\n\nexport const PROBLEM_JSON_CONTENT_TYPE = \"application/problem+json; charset=utf-8\";\n\nconst DANGEROUS_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/** Strip keys that could cause prototype pollution in downstream consumers */\nexport function sanitizeExtensions(\n\textensions: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n\tif (!extensions) return extensions;\n\tlet filtered: Record<string, unknown> | undefined;\n\tfor (const key of Object.keys(extensions)) {\n\t\tif (DANGEROUS_KEYS.has(key)) {\n\t\t\tif (!filtered) filtered = { ...extensions };\n\t\t\tdelete filtered[key];\n\t\t}\n\t}\n\treturn filtered ?? extensions;\n}\n\n/** Clamp HTTP status to 200-599 integer range; returns 500 for out-of-range or non-integer values */\nexport function clampHttpStatus(status: number): number {\n\treturn Number.isInteger(status) && status >= 200 && status <= 599 ? status : 500;\n}\n\nconst FALLBACK_BODY = JSON.stringify({\n\ttype: \"about:blank\",\n\tstatus: 500,\n\ttitle: \"Internal Server Error\",\n});\n\n/** Normalize ProblemDetailsInput to ProblemDetails with defaults for type and title */\nexport function normalizeProblemDetails<T extends Record<string, unknown>>(\n\tinput: ProblemDetailsInput<T>,\n): ProblemDetails<T> {\n\treturn {\n\t\ttype: input.type ?? \"about:blank\",\n\t\tstatus: input.status,\n\t\ttitle: input.title ?? statusToPhrase(input.status) ?? \"Unknown Error\",\n\t\tdetail: input.detail,\n\t\tinstance: input.instance,\n\t\textensions: input.extensions,\n\t};\n}\n\n/** Build a RFC 9457 Problem Details Response from a ProblemDetails object */\nexport function buildProblemResponse(pd: ProblemDetails): Response {\n\tconst { extensions, ...standard } = pd;\n\tconst body = { ...sanitizeExtensions(extensions), ...standard };\n\tconst { json, fallback } = safeStringify(body);\n\treturn new Response(json, {\n\t\tstatus: fallback ? 500 : clampHttpStatus(pd.status),\n\t\theaders: { \"Content-Type\": PROBLEM_JSON_CONTENT_TYPE },\n\t});\n}\n\n/** JSON.stringify with fallback for non-serializable values (circular refs, BigInt) */\nexport function safeStringify(body: unknown): { json: string; fallback: boolean } {\n\ttry {\n\t\treturn { json: JSON.stringify(body), fallback: false };\n\t} catch {\n\t\treturn { json: FALLBACK_BODY, fallback: true };\n\t}\n}\n"],"mappings":";;;;;AAGO,IAAM,4BAA4B;AAEzC,IAAM,iBAAiB,oBAAI,IAAI,CAAC,aAAa,eAAe,WAAW,CAAC;AAGjE,SAAS,mBACf,YACsC;AACtC,MAAI,CAAC,WAAY,QAAO;AACxB,MAAI;AACJ,aAAW,OAAO,OAAO,KAAK,UAAU,GAAG;AAC1C,QAAI,eAAe,IAAI,GAAG,GAAG;AAC5B,UAAI,CAAC,SAAU,YAAW,EAAE,GAAG,WAAW;AAC1C,aAAO,SAAS,GAAG;AAAA,IACpB;AAAA,EACD;AACA,SAAO,YAAY;AACpB;AAGO,SAAS,gBAAgB,QAAwB;AACvD,SAAO,OAAO,UAAU,MAAM,KAAK,UAAU,OAAO,UAAU,MAAM,SAAS;AAC9E;AAEA,IAAM,gBAAgB,KAAK,UAAU;AAAA,EACpC,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,OAAO;AACR,CAAC;AAGM,SAAS,wBACf,OACoB;AACpB,SAAO;AAAA,IACN,MAAM,MAAM,QAAQ;AAAA,IACpB,QAAQ,MAAM;AAAA,IACd,OAAO,MAAM,SAAS,eAAe,MAAM,MAAM,KAAK;AAAA,IACtD,QAAQ,MAAM;AAAA,IACd,UAAU,MAAM;AAAA,IAChB,YAAY,MAAM;AAAA,EACnB;AACD;AAGO,SAAS,qBAAqB,IAA8B;AAClE,QAAM,EAAE,YAAY,GAAG,SAAS,IAAI;AACpC,QAAM,OAAO,EAAE,GAAG,mBAAmB,UAAU,GAAG,GAAG,SAAS;AAC9D,QAAM,EAAE,MAAM,SAAS,IAAI,cAAc,IAAI;AAC7C,SAAO,IAAI,SAAS,MAAM;AAAA,IACzB,QAAQ,WAAW,MAAM,gBAAgB,GAAG,MAAM;AAAA,IAClD,SAAS,EAAE,gBAAgB,0BAA0B;AAAA,EACtD,CAAC;AACF;AAGO,SAAS,cAAc,MAAoD;AACjF,MAAI;AACH,WAAO,EAAE,MAAM,KAAK,UAAU,IAAI,GAAG,UAAU,MAAM;AAAA,EACtD,QAAQ;AACP,WAAO,EAAE,MAAM,eAAe,UAAU,KAAK;AAAA,EAC9C;AACD;","names":[]}
|
package/dist/index.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/status.ts","../src/utils.ts","../src/error.ts","../src/factory.ts","../src/handler.ts","../src/registry.ts"],"sourcesContent":["export type {\n\tProblemDetails,\n\tProblemDetailsHandlerOptions,\n\tProblemDetailsInput,\n} from \"./types.js\";\nexport { statusToPhrase, statusToSlug } from \"./status.js\";\nexport { ProblemDetailsError } from \"./error.js\";\nexport { problemDetails } from \"./factory.js\";\nexport { PROBLEM_JSON_CONTENT_TYPE } from \"./utils.js\";\nexport { problemDetailsHandler } from \"./handler.js\";\nexport { createProblemTypeRegistry } from \"./registry.js\";\n","const STATUS_PHRASES: Record<number, string> = {\n\t400: \"Bad Request\",\n\t401: \"Unauthorized\",\n\t402: \"Payment Required\",\n\t403: \"Forbidden\",\n\t404: \"Not Found\",\n\t405: \"Method Not Allowed\",\n\t406: \"Not Acceptable\",\n\t407: \"Proxy Authentication Required\",\n\t408: \"Request Timeout\",\n\t409: \"Conflict\",\n\t410: \"Gone\",\n\t411: \"Length Required\",\n\t412: \"Precondition Failed\",\n\t413: \"Content Too Large\",\n\t414: \"URI Too Long\",\n\t415: \"Unsupported Media Type\",\n\t416: \"Range Not Satisfiable\",\n\t417: \"Expectation Failed\",\n\t418: \"I'm a Teapot\",\n\t421: \"Misdirected Request\",\n\t422: \"Unprocessable Content\",\n\t423: \"Locked\",\n\t424: \"Failed Dependency\",\n\t425: \"Too Early\",\n\t426: \"Upgrade Required\",\n\t428: \"Precondition Required\",\n\t429: \"Too Many Requests\",\n\t431: \"Request Header Fields Too Large\",\n\t451: \"Unavailable For Legal Reasons\",\n\t500: \"Internal Server Error\",\n\t501: \"Not Implemented\",\n\t502: \"Bad Gateway\",\n\t503: \"Service Unavailable\",\n\t504: \"Gateway Timeout\",\n\t505: \"HTTP Version Not Supported\",\n\t506: \"Variant Also Negotiates\",\n\t507: \"Insufficient Storage\",\n\t508: \"Loop Detected\",\n\t510: \"Not Extended\",\n\t511: \"Network Authentication Required\",\n};\n\nconst STATUS_SLUGS: Record<number, string> = Object.fromEntries(\n\tObject.entries(STATUS_PHRASES).map(([code, phrase]) => [\n\t\tNumber(code),\n\t\tphrase\n\t\t\t.toLowerCase()\n\t\t\t.replace(/'/g, \"\")\n\t\t\t.replace(/[^a-z0-9]+/g, \"-\")\n\t\t\t.replace(/^-|-$/g, \"\"),\n\t]),\n);\n\nexport function statusToPhrase(status: number): string | undefined {\n\treturn STATUS_PHRASES[status];\n}\n\nexport function statusToSlug(status: number): string | undefined {\n\treturn STATUS_SLUGS[status];\n}\n","import { statusToPhrase } from \"./status.js\";\nimport type { ProblemDetails, ProblemDetailsInput } from \"./types.js\";\n\nexport const PROBLEM_JSON_CONTENT_TYPE = \"application/problem+json; charset=utf-8\";\n\nconst DANGEROUS_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/** Strip keys that could cause prototype pollution in downstream consumers */\nexport function sanitizeExtensions(\n\textensions: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n\tif (!extensions) return extensions;\n\tlet filtered: Record<string, unknown> | undefined;\n\tfor (const key of Object.keys(extensions)) {\n\t\tif (DANGEROUS_KEYS.has(key)) {\n\t\t\tif (!filtered) filtered = { ...extensions };\n\t\t\tdelete filtered[key];\n\t\t}\n\t}\n\treturn filtered ?? extensions;\n}\n\n/** Clamp HTTP status to 200-599 integer range; returns 500 for out-of-range or non-integer values */\nexport function clampHttpStatus(status: number): number {\n\treturn Number.isInteger(status) && status >= 200 && status <= 599 ? status : 500;\n}\n\nconst FALLBACK_BODY = JSON.stringify({\n\ttype: \"about:blank\",\n\tstatus: 500,\n\ttitle: \"Internal Server Error\",\n});\n\n/** Normalize ProblemDetailsInput to ProblemDetails with defaults for type and title */\nexport function normalizeProblemDetails<T extends Record<string, unknown>>(\n\tinput: ProblemDetailsInput<T>,\n): ProblemDetails<T> {\n\treturn {\n\t\ttype: input.type ?? \"about:blank\",\n\t\tstatus: input.status,\n\t\ttitle: input.title ?? statusToPhrase(input.status) ?? \"Unknown Error\",\n\t\tdetail: input.detail,\n\t\tinstance: input.instance,\n\t\textensions: input.extensions,\n\t};\n}\n\n/** Build a RFC 9457 Problem Details Response from a ProblemDetails object */\nexport function buildProblemResponse(pd: ProblemDetails): Response {\n\tconst { extensions, ...standard } = pd;\n\tconst body = { ...sanitizeExtensions(extensions), ...standard };\n\tconst { json, fallback } = safeStringify(body);\n\treturn new Response(json, {\n\t\tstatus: fallback ? 500 : clampHttpStatus(pd.status),\n\t\theaders: { \"Content-Type\": PROBLEM_JSON_CONTENT_TYPE },\n\t});\n}\n\n/** JSON.stringify with fallback for non-serializable values (circular refs, BigInt) */\nexport function safeStringify(body: unknown): { json: string; fallback: boolean } {\n\ttry {\n\t\treturn { json: JSON.stringify(body), fallback: false };\n\t} catch {\n\t\treturn { json: FALLBACK_BODY, fallback: true };\n\t}\n}\n","import type { ProblemDetails, ProblemDetailsInput } from \"./types.js\";\nimport { buildProblemResponse, normalizeProblemDetails } from \"./utils.js\";\n\nexport class ProblemDetailsError extends Error {\n\treadonly problemDetails: ProblemDetails;\n\n\tconstructor(input: ProblemDetailsInput) {\n\t\tconst pd = normalizeProblemDetails(input);\n\t\tsuper(pd.detail ?? pd.title);\n\t\tthis.name = \"ProblemDetailsError\";\n\t\tthis.problemDetails = pd;\n\t}\n\n\tgetResponse(): Response {\n\t\treturn buildProblemResponse(this.problemDetails);\n\t}\n}\n","import { ProblemDetailsError } from \"./error.js\";\nimport type { ProblemDetailsInput } from \"./types.js\";\n\nexport function problemDetails<T extends Record<string, unknown>>(\n\tinput: ProblemDetailsInput<T>,\n): ProblemDetailsError {\n\treturn new ProblemDetailsError(input);\n}\n","import type { Context, ErrorHandler } from \"hono\";\nimport { HTTPException } from \"hono/http-exception\";\nimport { ProblemDetailsError } from \"./error.js\";\nimport { statusToPhrase, statusToSlug } from \"./status.js\";\nimport type { ProblemDetailsHandlerOptions, ProblemDetailsInput } from \"./types.js\";\nimport { buildProblemResponse, normalizeProblemDetails } from \"./utils.js\";\n\nfunction buildType(status: number, options: ProblemDetailsHandlerOptions): string {\n\tif (options.typePrefix) {\n\t\tconst slug = statusToSlug(status);\n\t\tif (slug) return `${options.typePrefix}/${slug}`;\n\t}\n\treturn options.defaultType ?? \"about:blank\";\n}\n\nfunction toResponse(\n\tinput: ProblemDetailsInput,\n\tc: Context,\n\toptions: ProblemDetailsHandlerOptions,\n): Response {\n\tlet pd = normalizeProblemDetails(input);\n\n\tif (options.localize) {\n\t\ttry {\n\t\t\tpd = { ...pd, ...options.localize(pd, c) };\n\t\t} catch {\n\t\t\t// Fall through with the un-localized pd. A throwing localize must not\n\t\t\t// cause the error handler itself to throw — that would re-enter onError.\n\t\t}\n\t}\n\n\tc.set(\"problemDetails\", pd);\n\n\treturn buildProblemResponse(pd);\n}\n\nexport function problemDetailsHandler(options: ProblemDetailsHandlerOptions = {}): ErrorHandler {\n\treturn (error, c) => {\n\t\tif (error instanceof ProblemDetailsError) {\n\t\t\treturn toResponse(error.problemDetails, c, options);\n\t\t}\n\n\t\tif (options.mapError) {\n\t\t\tconst mapped = options.mapError(error);\n\t\t\tif (mapped) {\n\t\t\t\treturn toResponse(mapped, c, options);\n\t\t\t}\n\t\t}\n\n\t\tif (error instanceof HTTPException) {\n\t\t\treturn toResponse(\n\t\t\t\t{\n\t\t\t\t\tstatus: error.status,\n\t\t\t\t\ttype: buildType(error.status, options),\n\t\t\t\t\ttitle: statusToPhrase(error.status),\n\t\t\t\t\tdetail: error.message,\n\t\t\t\t},\n\t\t\t\tc,\n\t\t\t\toptions,\n\t\t\t);\n\t\t}\n\n\t\treturn toResponse(\n\t\t\t{\n\t\t\t\tstatus: 500,\n\t\t\t\ttype: buildType(500, options),\n\t\t\t\ttitle: \"Internal Server Error\",\n\t\t\t\tdetail: options.includeStack ? error.stack : undefined,\n\t\t\t},\n\t\t\tc,\n\t\t\toptions,\n\t\t);\n\t};\n}\n","import { ProblemDetailsError } from \"./error.js\";\n\ninterface ProblemTypeDefinition {\n\ttype: string;\n\tstatus: number;\n\ttitle: string;\n}\n\ninterface CreateOptions<T extends Record<string, unknown> = Record<string, unknown>> {\n\tdetail?: string;\n\tinstance?: string;\n\textensions?: T;\n}\n\ninterface ProblemTypeRegistry<K extends string> {\n\tcreate: <T extends Record<string, unknown>>(\n\t\tkey: K,\n\t\toptions?: CreateOptions<T>,\n\t) => ProblemDetailsError;\n\tget: (key: K) => ProblemTypeDefinition;\n\ttypes: () => K[];\n}\n\n/**\n * Create a registry of pre-defined problem types.\n * Provides type-safe error creation from registered definitions.\n */\nexport function createProblemTypeRegistry<K extends string>(\n\tdefinitions: Record<K, ProblemTypeDefinition>,\n): ProblemTypeRegistry<K> {\n\treturn {\n\t\tcreate: (key, options) => new ProblemDetailsError({ ...definitions[key], ...options }),\n\t\tget: (key) => definitions[key],\n\t\ttypes: () => Object.keys(definitions) as K[],\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAM,iBAAyC;AAAA,EAC9C,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACN;AAEA,IAAM,eAAuC,OAAO;AAAA,EACnD,OAAO,QAAQ,cAAc,EAAE,IAAI,CAAC,CAAC,MAAM,MAAM,MAAM;AAAA,IACtD,OAAO,IAAI;AAAA,IACX,OACE,YAAY,EACZ,QAAQ,MAAM,EAAE,EAChB,QAAQ,eAAe,GAAG,EAC1B,QAAQ,UAAU,EAAE;AAAA,EACvB,CAAC;AACF;AAEO,SAAS,eAAe,QAAoC;AAClE,SAAO,eAAe,MAAM;AAC7B;AAEO,SAAS,aAAa,QAAoC;AAChE,SAAO,aAAa,MAAM;AAC3B;;;ACzDO,IAAM,4BAA4B;AAEzC,IAAM,iBAAiB,oBAAI,IAAI,CAAC,aAAa,eAAe,WAAW,CAAC;AAGjE,SAAS,mBACf,YACsC;AACtC,MAAI,CAAC,WAAY,QAAO;AACxB,MAAI;AACJ,aAAW,OAAO,OAAO,KAAK,UAAU,GAAG;AAC1C,QAAI,eAAe,IAAI,GAAG,GAAG;AAC5B,UAAI,CAAC,SAAU,YAAW,EAAE,GAAG,WAAW;AAC1C,aAAO,SAAS,GAAG;AAAA,IACpB;AAAA,EACD;AACA,SAAO,YAAY;AACpB;AAGO,SAAS,gBAAgB,QAAwB;AACvD,SAAO,OAAO,UAAU,MAAM,KAAK,UAAU,OAAO,UAAU,MAAM,SAAS;AAC9E;AAEA,IAAM,gBAAgB,KAAK,UAAU;AAAA,EACpC,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,OAAO;AACR,CAAC;AAGM,SAAS,wBACf,OACoB;AACpB,SAAO;AAAA,IACN,MAAM,MAAM,QAAQ;AAAA,IACpB,QAAQ,MAAM;AAAA,IACd,OAAO,MAAM,SAAS,eAAe,MAAM,MAAM,KAAK;AAAA,IACtD,QAAQ,MAAM;AAAA,IACd,UAAU,MAAM;AAAA,IAChB,YAAY,MAAM;AAAA,EACnB;AACD;AAGO,SAAS,qBAAqB,IAA8B;AAClE,QAAM,EAAE,YAAY,GAAG,SAAS,IAAI;AACpC,QAAM,OAAO,EAAE,GAAG,mBAAmB,UAAU,GAAG,GAAG,SAAS;AAC9D,QAAM,EAAE,MAAM,SAAS,IAAI,cAAc,IAAI;AAC7C,SAAO,IAAI,SAAS,MAAM;AAAA,IACzB,QAAQ,WAAW,MAAM,gBAAgB,GAAG,MAAM;AAAA,IAClD,SAAS,EAAE,gBAAgB,0BAA0B;AAAA,EACtD,CAAC;AACF;AAGO,SAAS,cAAc,MAAoD;AACjF,MAAI;AACH,WAAO,EAAE,MAAM,KAAK,UAAU,IAAI,GAAG,UAAU,MAAM;AAAA,EACtD,QAAQ;AACP,WAAO,EAAE,MAAM,eAAe,UAAU,KAAK;AAAA,EAC9C;AACD;;;AC9DO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EACrC;AAAA,EAET,YAAY,OAA4B;AACvC,UAAM,KAAK,wBAAwB,KAAK;AACxC,UAAM,GAAG,UAAU,GAAG,KAAK;AAC3B,SAAK,OAAO;AACZ,SAAK,iBAAiB;AAAA,EACvB;AAAA,EAEA,cAAwB;AACvB,WAAO,qBAAqB,KAAK,cAAc;AAAA,EAChD;AACD;;;ACbO,SAAS,eACf,OACsB;AACtB,SAAO,IAAI,oBAAoB,KAAK;AACrC;;;ACNA,4BAA8B;AAM9B,SAAS,UAAU,QAAgB,SAA+C;AACjF,MAAI,QAAQ,YAAY;AACvB,UAAM,OAAO,aAAa,MAAM;AAChC,QAAI,KAAM,QAAO,GAAG,QAAQ,UAAU,IAAI,IAAI;AAAA,EAC/C;AACA,SAAO,QAAQ,eAAe;AAC/B;AAEA,SAAS,WACR,OACA,GACA,SACW;AACX,MAAI,KAAK,wBAAwB,KAAK;AAEtC,MAAI,QAAQ,UAAU;AACrB,QAAI;AACH,WAAK,EAAE,GAAG,IAAI,GAAG,QAAQ,SAAS,IAAI,CAAC,EAAE;AAAA,IAC1C,QAAQ;AAAA,IAGR;AAAA,EACD;AAEA,IAAE,IAAI,kBAAkB,EAAE;AAE1B,SAAO,qBAAqB,EAAE;AAC/B;AAEO,SAAS,sBAAsB,UAAwC,CAAC,GAAiB;AAC/F,SAAO,CAAC,OAAO,MAAM;AACpB,QAAI,iBAAiB,qBAAqB;AACzC,aAAO,WAAW,MAAM,gBAAgB,GAAG,OAAO;AAAA,IACnD;AAEA,QAAI,QAAQ,UAAU;AACrB,YAAM,SAAS,QAAQ,SAAS,KAAK;AACrC,UAAI,QAAQ;AACX,eAAO,WAAW,QAAQ,GAAG,OAAO;AAAA,MACrC;AAAA,IACD;AAEA,QAAI,iBAAiB,qCAAe;AACnC,aAAO;AAAA,QACN;AAAA,UACC,QAAQ,MAAM;AAAA,UACd,MAAM,UAAU,MAAM,QAAQ,OAAO;AAAA,UACrC,OAAO,eAAe,MAAM,MAAM;AAAA,UAClC,QAAQ,MAAM;AAAA,QACf;AAAA,QACA;AAAA,QACA;AAAA,MACD;AAAA,IACD;AAEA,WAAO;AAAA,MACN;AAAA,QACC,QAAQ;AAAA,QACR,MAAM,UAAU,KAAK,OAAO;AAAA,QAC5B,OAAO;AAAA,QACP,QAAQ,QAAQ,eAAe,MAAM,QAAQ;AAAA,MAC9C;AAAA,MACA;AAAA,MACA;AAAA,IACD;AAAA,EACD;AACD;;;AC9CO,SAAS,0BACf,aACyB;AACzB,SAAO;AAAA,IACN,QAAQ,CAAC,KAAK,YAAY,IAAI,oBAAoB,EAAE,GAAG,YAAY,GAAG,GAAG,GAAG,QAAQ,CAAC;AAAA,IACrF,KAAK,CAAC,QAAQ,YAAY,GAAG;AAAA,IAC7B,OAAO,MAAM,OAAO,KAAK,WAAW;AAAA,EACrC;AACD;","names":[]}
|
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/error.ts","../src/factory.ts","../src/handler.ts","../src/registry.ts"],"sourcesContent":["import type { ProblemDetails, ProblemDetailsInput } from \"./types.js\";\nimport { buildProblemResponse, normalizeProblemDetails } from \"./utils.js\";\n\nexport class ProblemDetailsError extends Error {\n\treadonly problemDetails: ProblemDetails;\n\n\tconstructor(input: ProblemDetailsInput) {\n\t\tconst pd = normalizeProblemDetails(input);\n\t\tsuper(pd.detail ?? pd.title);\n\t\tthis.name = \"ProblemDetailsError\";\n\t\tthis.problemDetails = pd;\n\t}\n\n\tgetResponse(): Response {\n\t\treturn buildProblemResponse(this.problemDetails);\n\t}\n}\n","import { ProblemDetailsError } from \"./error.js\";\nimport type { ProblemDetailsInput } from \"./types.js\";\n\nexport function problemDetails<T extends Record<string, unknown>>(\n\tinput: ProblemDetailsInput<T>,\n): ProblemDetailsError {\n\treturn new ProblemDetailsError(input);\n}\n","import type { Context, ErrorHandler } from \"hono\";\nimport { HTTPException } from \"hono/http-exception\";\nimport { ProblemDetailsError } from \"./error.js\";\nimport { statusToPhrase, statusToSlug } from \"./status.js\";\nimport type { ProblemDetailsHandlerOptions, ProblemDetailsInput } from \"./types.js\";\nimport { buildProblemResponse, normalizeProblemDetails } from \"./utils.js\";\n\nfunction buildType(status: number, options: ProblemDetailsHandlerOptions): string {\n\tif (options.typePrefix) {\n\t\tconst slug = statusToSlug(status);\n\t\tif (slug) return `${options.typePrefix}/${slug}`;\n\t}\n\treturn options.defaultType ?? \"about:blank\";\n}\n\nfunction toResponse(\n\tinput: ProblemDetailsInput,\n\tc: Context,\n\toptions: ProblemDetailsHandlerOptions,\n): Response {\n\tlet pd = normalizeProblemDetails(input);\n\n\tif (options.localize) {\n\t\ttry {\n\t\t\tpd = { ...pd, ...options.localize(pd, c) };\n\t\t} catch {\n\t\t\t// Fall through with the un-localized pd. A throwing localize must not\n\t\t\t// cause the error handler itself to throw — that would re-enter onError.\n\t\t}\n\t}\n\n\tc.set(\"problemDetails\", pd);\n\n\treturn buildProblemResponse(pd);\n}\n\nexport function problemDetailsHandler(options: ProblemDetailsHandlerOptions = {}): ErrorHandler {\n\treturn (error, c) => {\n\t\tif (error instanceof ProblemDetailsError) {\n\t\t\treturn toResponse(error.problemDetails, c, options);\n\t\t}\n\n\t\tif (options.mapError) {\n\t\t\tconst mapped = options.mapError(error);\n\t\t\tif (mapped) {\n\t\t\t\treturn toResponse(mapped, c, options);\n\t\t\t}\n\t\t}\n\n\t\tif (error instanceof HTTPException) {\n\t\t\treturn toResponse(\n\t\t\t\t{\n\t\t\t\t\tstatus: error.status,\n\t\t\t\t\ttype: buildType(error.status, options),\n\t\t\t\t\ttitle: statusToPhrase(error.status),\n\t\t\t\t\tdetail: error.message,\n\t\t\t\t},\n\t\t\t\tc,\n\t\t\t\toptions,\n\t\t\t);\n\t\t}\n\n\t\treturn toResponse(\n\t\t\t{\n\t\t\t\tstatus: 500,\n\t\t\t\ttype: buildType(500, options),\n\t\t\t\ttitle: \"Internal Server Error\",\n\t\t\t\tdetail: options.includeStack ? error.stack : undefined,\n\t\t\t},\n\t\t\tc,\n\t\t\toptions,\n\t\t);\n\t};\n}\n","import { ProblemDetailsError } from \"./error.js\";\n\ninterface ProblemTypeDefinition {\n\ttype: string;\n\tstatus: number;\n\ttitle: string;\n}\n\ninterface CreateOptions<T extends Record<string, unknown> = Record<string, unknown>> {\n\tdetail?: string;\n\tinstance?: string;\n\textensions?: T;\n}\n\ninterface ProblemTypeRegistry<K extends string> {\n\tcreate: <T extends Record<string, unknown>>(\n\t\tkey: K,\n\t\toptions?: CreateOptions<T>,\n\t) => ProblemDetailsError;\n\tget: (key: K) => ProblemTypeDefinition;\n\ttypes: () => K[];\n}\n\n/**\n * Create a registry of pre-defined problem types.\n * Provides type-safe error creation from registered definitions.\n */\nexport function createProblemTypeRegistry<K extends string>(\n\tdefinitions: Record<K, ProblemTypeDefinition>,\n): ProblemTypeRegistry<K> {\n\treturn {\n\t\tcreate: (key, options) => new ProblemDetailsError({ ...definitions[key], ...options }),\n\t\tget: (key) => definitions[key],\n\t\ttypes: () => Object.keys(definitions) as K[],\n\t};\n}\n"],"mappings":";;;;;;;;;;;AAGO,IAAM,sBAAN,cAAkC,MAAM;AAAA,EACrC;AAAA,EAET,YAAY,OAA4B;AACvC,UAAM,KAAK,wBAAwB,KAAK;AACxC,UAAM,GAAG,UAAU,GAAG,KAAK;AAC3B,SAAK,OAAO;AACZ,SAAK,iBAAiB;AAAA,EACvB;AAAA,EAEA,cAAwB;AACvB,WAAO,qBAAqB,KAAK,cAAc;AAAA,EAChD;AACD;;;ACbO,SAAS,eACf,OACsB;AACtB,SAAO,IAAI,oBAAoB,KAAK;AACrC;;;ACNA,SAAS,qBAAqB;AAM9B,SAAS,UAAU,QAAgB,SAA+C;AACjF,MAAI,QAAQ,YAAY;AACvB,UAAM,OAAO,aAAa,MAAM;AAChC,QAAI,KAAM,QAAO,GAAG,QAAQ,UAAU,IAAI,IAAI;AAAA,EAC/C;AACA,SAAO,QAAQ,eAAe;AAC/B;AAEA,SAAS,WACR,OACA,GACA,SACW;AACX,MAAI,KAAK,wBAAwB,KAAK;AAEtC,MAAI,QAAQ,UAAU;AACrB,QAAI;AACH,WAAK,EAAE,GAAG,IAAI,GAAG,QAAQ,SAAS,IAAI,CAAC,EAAE;AAAA,IAC1C,QAAQ;AAAA,IAGR;AAAA,EACD;AAEA,IAAE,IAAI,kBAAkB,EAAE;AAE1B,SAAO,qBAAqB,EAAE;AAC/B;AAEO,SAAS,sBAAsB,UAAwC,CAAC,GAAiB;AAC/F,SAAO,CAAC,OAAO,MAAM;AACpB,QAAI,iBAAiB,qBAAqB;AACzC,aAAO,WAAW,MAAM,gBAAgB,GAAG,OAAO;AAAA,IACnD;AAEA,QAAI,QAAQ,UAAU;AACrB,YAAM,SAAS,QAAQ,SAAS,KAAK;AACrC,UAAI,QAAQ;AACX,eAAO,WAAW,QAAQ,GAAG,OAAO;AAAA,MACrC;AAAA,IACD;AAEA,QAAI,iBAAiB,eAAe;AACnC,aAAO;AAAA,QACN;AAAA,UACC,QAAQ,MAAM;AAAA,UACd,MAAM,UAAU,MAAM,QAAQ,OAAO;AAAA,UACrC,OAAO,eAAe,MAAM,MAAM;AAAA,UAClC,QAAQ,MAAM;AAAA,QACf;AAAA,QACA;AAAA,QACA;AAAA,MACD;AAAA,IACD;AAEA,WAAO;AAAA,MACN;AAAA,QACC,QAAQ;AAAA,QACR,MAAM,UAAU,KAAK,OAAO;AAAA,QAC5B,OAAO;AAAA,QACP,QAAQ,QAAQ,eAAe,MAAM,QAAQ;AAAA,MAC9C;AAAA,MACA;AAAA,MACA;AAAA,IACD;AAAA,EACD;AACD;;;AC9CO,SAAS,0BACf,aACyB;AACzB,SAAO;AAAA,IACN,QAAQ,CAAC,KAAK,YAAY,IAAI,oBAAoB,EAAE,GAAG,YAAY,GAAG,GAAG,GAAG,QAAQ,CAAC;AAAA,IACrF,KAAK,CAAC,QAAQ,YAAY,GAAG;AAAA,IAC7B,OAAO,MAAM,OAAO,KAAK,WAAW;AAAA,EACrC;AACD;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/openapi.ts","../../src/status.ts"],"sourcesContent":["import { z } from \"@hono/zod-openapi\";\nimport { statusToPhrase } from \"../status.js\";\n\n/**\n * Base RFC 9457 Problem Details Zod schema for OpenAPI documentation.\n * Use in createRoute() response definitions with @hono/zod-openapi.\n */\nexport const ProblemDetailsSchema: z.ZodObject<{\n\ttype: z.ZodString;\n\tstatus: z.ZodNumber;\n\ttitle: z.ZodString;\n\tdetail: z.ZodOptional<z.ZodString>;\n\tinstance: z.ZodOptional<z.ZodString>;\n}> = z\n\t.object({\n\t\ttype: z.string().openapi({ description: \"Problem type URI\", example: \"about:blank\" }),\n\t\tstatus: z.number().int().openapi({ description: \"HTTP status code\", example: 400 }),\n\t\ttitle: z\n\t\t\t.string()\n\t\t\t.openapi({ description: \"Short summary of the problem type\", example: \"Bad Request\" }),\n\t\tdetail: z.string().optional().openapi({ description: \"Human-readable explanation\" }),\n\t\tinstance: z.string().optional().openapi({ description: \"URI identifying the occurrence\" }),\n\t})\n\t.openapi({ title: \"ProblemDetails\" });\n\n/**\n * Create a Problem Details schema with typed extension members.\n * Extensions are merged at top level per RFC 9457.\n */\nexport function createProblemDetailsSchema<T extends z.ZodRawShape>(\n\textensions: z.ZodObject<T>,\n): z.AnyZodObject {\n\treturn ProblemDetailsSchema.merge(extensions).openapi({ title: \"ProblemDetails\" });\n}\n\n/**\n * Create an OpenAPI response object for Problem Details.\n * Use in createRoute() responses: { 422: problemDetailsResponse(422) }\n */\nexport function problemDetailsResponse(\n\tstatus: number,\n\tdescription?: string,\n\tschema: z.ZodTypeAny = ProblemDetailsSchema,\n): {\n\tcontent: { \"application/problem+json\": { schema: z.ZodTypeAny } };\n\tdescription: string;\n} {\n\treturn {\n\t\tcontent: {\n\t\t\t\"application/problem+json\": { schema },\n\t\t},\n\t\tdescription: description ?? statusToPhrase(status) ?? \"Error\",\n\t};\n}\n","const STATUS_PHRASES: Record<number, string> = {\n\t400: \"Bad Request\",\n\t401: \"Unauthorized\",\n\t402: \"Payment Required\",\n\t403: \"Forbidden\",\n\t404: \"Not Found\",\n\t405: \"Method Not Allowed\",\n\t406: \"Not Acceptable\",\n\t407: \"Proxy Authentication Required\",\n\t408: \"Request Timeout\",\n\t409: \"Conflict\",\n\t410: \"Gone\",\n\t411: \"Length Required\",\n\t412: \"Precondition Failed\",\n\t413: \"Content Too Large\",\n\t414: \"URI Too Long\",\n\t415: \"Unsupported Media Type\",\n\t416: \"Range Not Satisfiable\",\n\t417: \"Expectation Failed\",\n\t418: \"I'm a Teapot\",\n\t421: \"Misdirected Request\",\n\t422: \"Unprocessable Content\",\n\t423: \"Locked\",\n\t424: \"Failed Dependency\",\n\t425: \"Too Early\",\n\t426: \"Upgrade Required\",\n\t428: \"Precondition Required\",\n\t429: \"Too Many Requests\",\n\t431: \"Request Header Fields Too Large\",\n\t451: \"Unavailable For Legal Reasons\",\n\t500: \"Internal Server Error\",\n\t501: \"Not Implemented\",\n\t502: \"Bad Gateway\",\n\t503: \"Service Unavailable\",\n\t504: \"Gateway Timeout\",\n\t505: \"HTTP Version Not Supported\",\n\t506: \"Variant Also Negotiates\",\n\t507: \"Insufficient Storage\",\n\t508: \"Loop Detected\",\n\t510: \"Not Extended\",\n\t511: \"Network Authentication Required\",\n};\n\nconst STATUS_SLUGS: Record<number, string> = Object.fromEntries(\n\tObject.entries(STATUS_PHRASES).map(([code, phrase]) => [\n\t\tNumber(code),\n\t\tphrase\n\t\t\t.toLowerCase()\n\t\t\t.replace(/'/g, \"\")\n\t\t\t.replace(/[^a-z0-9]+/g, \"-\")\n\t\t\t.replace(/^-|-$/g, \"\"),\n\t]),\n);\n\nexport function statusToPhrase(status: number): string | undefined {\n\treturn STATUS_PHRASES[status];\n}\n\nexport function statusToSlug(status: number): string | undefined {\n\treturn STATUS_SLUGS[status];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAAkB;;;ACAlB,IAAM,iBAAyC;AAAA,EAC9C,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AACN;AAEA,IAAM,eAAuC,OAAO;AAAA,EACnD,OAAO,QAAQ,cAAc,EAAE,IAAI,CAAC,CAAC,MAAM,MAAM,MAAM;AAAA,IACtD,OAAO,IAAI;AAAA,IACX,OACE,YAAY,EACZ,QAAQ,MAAM,EAAE,EAChB,QAAQ,eAAe,GAAG,EAC1B,QAAQ,UAAU,EAAE;AAAA,EACvB,CAAC;AACF;AAEO,SAAS,eAAe,QAAoC;AAClE,SAAO,eAAe,MAAM;AAC7B;;;ADjDO,IAAM,uBAMR,qBACH,OAAO;AAAA,EACP,MAAM,qBAAE,OAAO,EAAE,QAAQ,EAAE,aAAa,oBAAoB,SAAS,cAAc,CAAC;AAAA,EACpF,QAAQ,qBAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,aAAa,oBAAoB,SAAS,IAAI,CAAC;AAAA,EAClF,OAAO,qBACL,OAAO,EACP,QAAQ,EAAE,aAAa,qCAAqC,SAAS,cAAc,CAAC;AAAA,EACtF,QAAQ,qBAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,aAAa,6BAA6B,CAAC;AAAA,EACnF,UAAU,qBAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,aAAa,iCAAiC,CAAC;AAC1F,CAAC,EACA,QAAQ,EAAE,OAAO,iBAAiB,CAAC;AAM9B,SAAS,2BACf,YACiB;AACjB,SAAO,qBAAqB,MAAM,UAAU,EAAE,QAAQ,EAAE,OAAO,iBAAiB,CAAC;AAClF;AAMO,SAAS,uBACf,QACA,aACA,SAAuB,sBAItB;AACD,SAAO;AAAA,IACN,SAAS;AAAA,MACR,4BAA4B,EAAE,OAAO;AAAA,IACtC;AAAA,IACA,aAAa,eAAe,eAAe,MAAM,KAAK;AAAA,EACvD;AACD;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/openapi.ts"],"sourcesContent":["import { z } from \"@hono/zod-openapi\";\nimport { statusToPhrase } from \"../status.js\";\n\n/**\n * Base RFC 9457 Problem Details Zod schema for OpenAPI documentation.\n * Use in createRoute() response definitions with @hono/zod-openapi.\n */\nexport const ProblemDetailsSchema: z.ZodObject<{\n\ttype: z.ZodString;\n\tstatus: z.ZodNumber;\n\ttitle: z.ZodString;\n\tdetail: z.ZodOptional<z.ZodString>;\n\tinstance: z.ZodOptional<z.ZodString>;\n}> = z\n\t.object({\n\t\ttype: z.string().openapi({ description: \"Problem type URI\", example: \"about:blank\" }),\n\t\tstatus: z.number().int().openapi({ description: \"HTTP status code\", example: 400 }),\n\t\ttitle: z\n\t\t\t.string()\n\t\t\t.openapi({ description: \"Short summary of the problem type\", example: \"Bad Request\" }),\n\t\tdetail: z.string().optional().openapi({ description: \"Human-readable explanation\" }),\n\t\tinstance: z.string().optional().openapi({ description: \"URI identifying the occurrence\" }),\n\t})\n\t.openapi({ title: \"ProblemDetails\" });\n\n/**\n * Create a Problem Details schema with typed extension members.\n * Extensions are merged at top level per RFC 9457.\n */\nexport function createProblemDetailsSchema<T extends z.ZodRawShape>(\n\textensions: z.ZodObject<T>,\n): z.AnyZodObject {\n\treturn ProblemDetailsSchema.merge(extensions).openapi({ title: \"ProblemDetails\" });\n}\n\n/**\n * Create an OpenAPI response object for Problem Details.\n * Use in createRoute() responses: { 422: problemDetailsResponse(422) }\n */\nexport function problemDetailsResponse(\n\tstatus: number,\n\tdescription?: string,\n\tschema: z.ZodTypeAny = ProblemDetailsSchema,\n): {\n\tcontent: { \"application/problem+json\": { schema: z.ZodTypeAny } };\n\tdescription: string;\n} {\n\treturn {\n\t\tcontent: {\n\t\t\t\"application/problem+json\": { schema },\n\t\t},\n\t\tdescription: description ?? statusToPhrase(status) ?? \"Error\",\n\t};\n}\n"],"mappings":";;;;;AAAA,SAAS,SAAS;AAOX,IAAM,uBAMR,EACH,OAAO;AAAA,EACP,MAAM,EAAE,OAAO,EAAE,QAAQ,EAAE,aAAa,oBAAoB,SAAS,cAAc,CAAC;AAAA,EACpF,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE,aAAa,oBAAoB,SAAS,IAAI,CAAC;AAAA,EAClF,OAAO,EACL,OAAO,EACP,QAAQ,EAAE,aAAa,qCAAqC,SAAS,cAAc,CAAC;AAAA,EACtF,QAAQ,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,aAAa,6BAA6B,CAAC;AAAA,EACnF,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,EAAE,aAAa,iCAAiC,CAAC;AAC1F,CAAC,EACA,QAAQ,EAAE,OAAO,iBAAiB,CAAC;AAM9B,SAAS,2BACf,YACiB;AACjB,SAAO,qBAAqB,MAAM,UAAU,EAAE,QAAQ,EAAE,OAAO,iBAAiB,CAAC;AAClF;AAMO,SAAS,uBACf,QACA,aACA,SAAuB,sBAItB;AACD,SAAO;AAAA,IACN,SAAS;AAAA,MACR,4BAA4B,EAAE,OAAO;AAAA,IACtC;AAAA,IACA,aAAa,eAAe,eAAe,MAAM,KAAK;AAAA,EACvD;AACD;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/standard-schema.ts","../../src/utils.ts","../../src/integrations/validation.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Context } from \"hono\";\nimport {\n\ttype ValidationError,\n\ttype ValidationHookOptions,\n\tbuildValidationResponse,\n} from \"./validation.js\";\n\nexport type { ValidationHookOptions as StandardSchemaProblemHookOptions };\n\nfunction formatPath(path: ReadonlyArray<PropertyKey | StandardSchemaV1.PathSegment>): string {\n\treturn path\n\t\t.map((segment) => (typeof segment === \"object\" ? String(segment.key) : String(segment)))\n\t\t.join(\".\");\n}\n\nfunction formatIssues(issues: readonly StandardSchemaV1.Issue[]): ValidationError[] {\n\treturn issues.map((issue) => ({\n\t\tfield: issue.path ? formatPath(issue.path) : \"\",\n\t\tmessage: issue.message,\n\t}));\n}\n\nexport function standardSchemaProblemHook(\n\toptions?: ValidationHookOptions,\n): (\n\tresult:\n\t\t| { success: true; data: unknown }\n\t\t| { success: false; error: readonly StandardSchemaV1.Issue[] },\n\tc: Context,\n) => Response | undefined {\n\treturn (result, _c) => {\n\t\tif (result.success) return;\n\t\treturn buildValidationResponse(formatIssues(result.error), options);\n\t};\n}\n","import { statusToPhrase } from \"./status.js\";\nimport type { ProblemDetails, ProblemDetailsInput } from \"./types.js\";\n\nexport const PROBLEM_JSON_CONTENT_TYPE = \"application/problem+json; charset=utf-8\";\n\nconst DANGEROUS_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/** Strip keys that could cause prototype pollution in downstream consumers */\nexport function sanitizeExtensions(\n\textensions: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n\tif (!extensions) return extensions;\n\tlet filtered: Record<string, unknown> | undefined;\n\tfor (const key of Object.keys(extensions)) {\n\t\tif (DANGEROUS_KEYS.has(key)) {\n\t\t\tif (!filtered) filtered = { ...extensions };\n\t\t\tdelete filtered[key];\n\t\t}\n\t}\n\treturn filtered ?? extensions;\n}\n\n/** Clamp HTTP status to 200-599 integer range; returns 500 for out-of-range or non-integer values */\nexport function clampHttpStatus(status: number): number {\n\treturn Number.isInteger(status) && status >= 200 && status <= 599 ? status : 500;\n}\n\nconst FALLBACK_BODY = JSON.stringify({\n\ttype: \"about:blank\",\n\tstatus: 500,\n\ttitle: \"Internal Server Error\",\n});\n\n/** Normalize ProblemDetailsInput to ProblemDetails with defaults for type and title */\nexport function normalizeProblemDetails<T extends Record<string, unknown>>(\n\tinput: ProblemDetailsInput<T>,\n): ProblemDetails<T> {\n\treturn {\n\t\ttype: input.type ?? \"about:blank\",\n\t\tstatus: input.status,\n\t\ttitle: input.title ?? statusToPhrase(input.status) ?? \"Unknown Error\",\n\t\tdetail: input.detail,\n\t\tinstance: input.instance,\n\t\textensions: input.extensions,\n\t};\n}\n\n/** Build a RFC 9457 Problem Details Response from a ProblemDetails object */\nexport function buildProblemResponse(pd: ProblemDetails): Response {\n\tconst { extensions, ...standard } = pd;\n\tconst body = { ...sanitizeExtensions(extensions), ...standard };\n\tconst { json, fallback } = safeStringify(body);\n\treturn new Response(json, {\n\t\tstatus: fallback ? 500 : clampHttpStatus(pd.status),\n\t\theaders: { \"Content-Type\": PROBLEM_JSON_CONTENT_TYPE },\n\t});\n}\n\n/** JSON.stringify with fallback for non-serializable values (circular refs, BigInt) */\nexport function safeStringify(body: unknown): { json: string; fallback: boolean } {\n\ttry {\n\t\treturn { json: JSON.stringify(body), fallback: false };\n\t} catch {\n\t\treturn { json: FALLBACK_BODY, fallback: true };\n\t}\n}\n","import { PROBLEM_JSON_CONTENT_TYPE } from \"../utils.js\";\n\nexport interface ValidationError {\n\tfield: string;\n\tmessage: string;\n\tcode?: string;\n}\n\nexport interface ValidationHookOptions {\n\ttitle?: string;\n\tdetail?: string;\n}\n\n/**\n * Strip C0 control characters (\\x00-\\x1f) and DEL (\\x7f) from untrusted text.\n * Bidi/format control chars (U+2028, U+202E, etc.) are intentionally left intact\n * to avoid breaking legitimate i18n content; log consumers should apply their\n * own bidi-safe rendering.\n */\n// biome-ignore lint/suspicious/noControlCharactersInRegex: intentional stripping of C0 controls\nconst CONTROL_CHAR_RE = /[\\x00-\\x1f\\x7f]/g;\n\nfunction stripControlChars(input: string): string {\n\treturn input.replace(CONTROL_CHAR_RE, \"\");\n}\n\nfunction sanitizeError(error: ValidationError): ValidationError {\n\treturn {\n\t\tfield: stripControlChars(error.field),\n\t\tmessage: stripControlChars(error.message),\n\t\t...(error.code !== undefined ? { code: stripControlChars(error.code) } : {}),\n\t};\n}\n\n/** Build a RFC 9457 validation error response from formatted errors */\nexport function buildValidationResponse(\n\terrors: ValidationError[],\n\toptions?: ValidationHookOptions,\n): Response {\n\tconst body = {\n\t\ttype: \"about:blank\",\n\t\tstatus: 422,\n\t\ttitle: options?.title ?? \"Validation Error\",\n\t\tdetail: options?.detail ?? \"Request validation failed\",\n\t\terrors: errors.map(sanitizeError),\n\t};\n\n\treturn new Response(JSON.stringify(body), {\n\t\tstatus: 422,\n\t\theaders: { \"Content-Type\": PROBLEM_JSON_CONTENT_TYPE },\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,4BAA4B;AAwBzC,IAAM,gBAAgB,KAAK,UAAU;AAAA,EACpC,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,OAAO;AACR,CAAC;;;ACXD,IAAM,kBAAkB;AAExB,SAAS,kBAAkB,OAAuB;AACjD,SAAO,MAAM,QAAQ,iBAAiB,EAAE;AACzC;AAEA,SAAS,cAAc,OAAyC;AAC/D,SAAO;AAAA,IACN,OAAO,kBAAkB,MAAM,KAAK;AAAA,IACpC,SAAS,kBAAkB,MAAM,OAAO;AAAA,IACxC,GAAI,MAAM,SAAS,SAAY,EAAE,MAAM,kBAAkB,MAAM,IAAI,EAAE,IAAI,CAAC;AAAA,EAC3E;AACD;AAGO,SAAS,wBACf,QACA,SACW;AACX,QAAM,OAAO;AAAA,IACZ,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,OAAO,SAAS,SAAS;AAAA,IACzB,QAAQ,SAAS,UAAU;AAAA,IAC3B,QAAQ,OAAO,IAAI,aAAa;AAAA,EACjC;AAEA,SAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;AAAA,IACzC,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,0BAA0B;AAAA,EACtD,CAAC;AACF;;;AFzCA,SAAS,WAAW,MAAyE;AAC5F,SAAO,KACL,IAAI,CAAC,YAAa,OAAO,YAAY,WAAW,OAAO,QAAQ,GAAG,IAAI,OAAO,OAAO,CAAE,EACtF,KAAK,GAAG;AACX;AAEA,SAAS,aAAa,QAA8D;AACnF,SAAO,OAAO,IAAI,CAAC,WAAW;AAAA,IAC7B,OAAO,MAAM,OAAO,WAAW,MAAM,IAAI,IAAI;AAAA,IAC7C,SAAS,MAAM;AAAA,EAChB,EAAE;AACH;AAEO,SAAS,0BACf,SAMyB;AACzB,SAAO,CAAC,QAAQ,OAAO;AACtB,QAAI,OAAO,QAAS;AACpB,WAAO,wBAAwB,aAAa,OAAO,KAAK,GAAG,OAAO;AAAA,EACnE;AACD;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/standard-schema.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { Context } from \"hono\";\nimport {\n\ttype ValidationError,\n\ttype ValidationHookOptions,\n\tbuildValidationResponse,\n} from \"./validation.js\";\n\nexport type { ValidationHookOptions as StandardSchemaProblemHookOptions };\n\nfunction formatPath(path: ReadonlyArray<PropertyKey | StandardSchemaV1.PathSegment>): string {\n\treturn path\n\t\t.map((segment) => (typeof segment === \"object\" ? String(segment.key) : String(segment)))\n\t\t.join(\".\");\n}\n\nfunction formatIssues(issues: readonly StandardSchemaV1.Issue[]): ValidationError[] {\n\treturn issues.map((issue) => ({\n\t\tfield: issue.path ? formatPath(issue.path) : \"\",\n\t\tmessage: issue.message,\n\t}));\n}\n\nexport function standardSchemaProblemHook(\n\toptions?: ValidationHookOptions,\n): (\n\tresult:\n\t\t| { success: true; data: unknown }\n\t\t| { success: false; error: readonly StandardSchemaV1.Issue[] },\n\tc: Context,\n) => Response | undefined {\n\treturn (result, _c) => {\n\t\tif (result.success) return;\n\t\treturn buildValidationResponse(formatIssues(result.error), options);\n\t};\n}\n"],"mappings":";;;;;;;AAUA,SAAS,WAAW,MAAyE;AAC5F,SAAO,KACL,IAAI,CAAC,YAAa,OAAO,YAAY,WAAW,OAAO,QAAQ,GAAG,IAAI,OAAO,OAAO,CAAE,EACtF,KAAK,GAAG;AACX;AAEA,SAAS,aAAa,QAA8D;AACnF,SAAO,OAAO,IAAI,CAAC,WAAW;AAAA,IAC7B,OAAO,MAAM,OAAO,WAAW,MAAM,IAAI,IAAI;AAAA,IAC7C,SAAS,MAAM;AAAA,EAChB,EAAE;AACH;AAEO,SAAS,0BACf,SAMyB;AACzB,SAAO,CAAC,QAAQ,OAAO;AACtB,QAAI,OAAO,QAAS;AACpB,WAAO,wBAAwB,aAAa,OAAO,KAAK,GAAG,OAAO;AAAA,EACnE;AACD;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/valibot.ts","../../src/utils.ts","../../src/integrations/validation.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { BaseIssue, GenericSchema, GenericSchemaAsync, SafeParseResult } from \"valibot\";\nimport {\n\ttype ValidationError,\n\ttype ValidationHookOptions,\n\tbuildValidationResponse,\n} from \"./validation.js\";\n\nexport type { ValidationHookOptions as ValibotProblemHookOptions };\n\nfunction formatIssues(issues: BaseIssue<unknown>[]): ValidationError[] {\n\treturn issues.map((issue) => ({\n\t\tfield: issue.path?.map((p) => p.key).join(\".\") ?? \"\",\n\t\tmessage: issue.message,\n\t\tcode: issue.type,\n\t}));\n}\n\nexport function valibotProblemHook<T extends GenericSchema | GenericSchemaAsync = GenericSchema>(\n\toptions?: ValidationHookOptions,\n): (result: SafeParseResult<T> & { target: string }, c: Context) => Response | undefined {\n\treturn (result, _c) => {\n\t\tif (result.success) return;\n\t\treturn buildValidationResponse(formatIssues(result.issues), options);\n\t};\n}\n","import { statusToPhrase } from \"./status.js\";\nimport type { ProblemDetails, ProblemDetailsInput } from \"./types.js\";\n\nexport const PROBLEM_JSON_CONTENT_TYPE = \"application/problem+json; charset=utf-8\";\n\nconst DANGEROUS_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/** Strip keys that could cause prototype pollution in downstream consumers */\nexport function sanitizeExtensions(\n\textensions: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n\tif (!extensions) return extensions;\n\tlet filtered: Record<string, unknown> | undefined;\n\tfor (const key of Object.keys(extensions)) {\n\t\tif (DANGEROUS_KEYS.has(key)) {\n\t\t\tif (!filtered) filtered = { ...extensions };\n\t\t\tdelete filtered[key];\n\t\t}\n\t}\n\treturn filtered ?? extensions;\n}\n\n/** Clamp HTTP status to 200-599 integer range; returns 500 for out-of-range or non-integer values */\nexport function clampHttpStatus(status: number): number {\n\treturn Number.isInteger(status) && status >= 200 && status <= 599 ? status : 500;\n}\n\nconst FALLBACK_BODY = JSON.stringify({\n\ttype: \"about:blank\",\n\tstatus: 500,\n\ttitle: \"Internal Server Error\",\n});\n\n/** Normalize ProblemDetailsInput to ProblemDetails with defaults for type and title */\nexport function normalizeProblemDetails<T extends Record<string, unknown>>(\n\tinput: ProblemDetailsInput<T>,\n): ProblemDetails<T> {\n\treturn {\n\t\ttype: input.type ?? \"about:blank\",\n\t\tstatus: input.status,\n\t\ttitle: input.title ?? statusToPhrase(input.status) ?? \"Unknown Error\",\n\t\tdetail: input.detail,\n\t\tinstance: input.instance,\n\t\textensions: input.extensions,\n\t};\n}\n\n/** Build a RFC 9457 Problem Details Response from a ProblemDetails object */\nexport function buildProblemResponse(pd: ProblemDetails): Response {\n\tconst { extensions, ...standard } = pd;\n\tconst body = { ...sanitizeExtensions(extensions), ...standard };\n\tconst { json, fallback } = safeStringify(body);\n\treturn new Response(json, {\n\t\tstatus: fallback ? 500 : clampHttpStatus(pd.status),\n\t\theaders: { \"Content-Type\": PROBLEM_JSON_CONTENT_TYPE },\n\t});\n}\n\n/** JSON.stringify with fallback for non-serializable values (circular refs, BigInt) */\nexport function safeStringify(body: unknown): { json: string; fallback: boolean } {\n\ttry {\n\t\treturn { json: JSON.stringify(body), fallback: false };\n\t} catch {\n\t\treturn { json: FALLBACK_BODY, fallback: true };\n\t}\n}\n","import { PROBLEM_JSON_CONTENT_TYPE } from \"../utils.js\";\n\nexport interface ValidationError {\n\tfield: string;\n\tmessage: string;\n\tcode?: string;\n}\n\nexport interface ValidationHookOptions {\n\ttitle?: string;\n\tdetail?: string;\n}\n\n/**\n * Strip C0 control characters (\\x00-\\x1f) and DEL (\\x7f) from untrusted text.\n * Bidi/format control chars (U+2028, U+202E, etc.) are intentionally left intact\n * to avoid breaking legitimate i18n content; log consumers should apply their\n * own bidi-safe rendering.\n */\n// biome-ignore lint/suspicious/noControlCharactersInRegex: intentional stripping of C0 controls\nconst CONTROL_CHAR_RE = /[\\x00-\\x1f\\x7f]/g;\n\nfunction stripControlChars(input: string): string {\n\treturn input.replace(CONTROL_CHAR_RE, \"\");\n}\n\nfunction sanitizeError(error: ValidationError): ValidationError {\n\treturn {\n\t\tfield: stripControlChars(error.field),\n\t\tmessage: stripControlChars(error.message),\n\t\t...(error.code !== undefined ? { code: stripControlChars(error.code) } : {}),\n\t};\n}\n\n/** Build a RFC 9457 validation error response from formatted errors */\nexport function buildValidationResponse(\n\terrors: ValidationError[],\n\toptions?: ValidationHookOptions,\n): Response {\n\tconst body = {\n\t\ttype: \"about:blank\",\n\t\tstatus: 422,\n\t\ttitle: options?.title ?? \"Validation Error\",\n\t\tdetail: options?.detail ?? \"Request validation failed\",\n\t\terrors: errors.map(sanitizeError),\n\t};\n\n\treturn new Response(JSON.stringify(body), {\n\t\tstatus: 422,\n\t\theaders: { \"Content-Type\": PROBLEM_JSON_CONTENT_TYPE },\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,4BAA4B;AAwBzC,IAAM,gBAAgB,KAAK,UAAU;AAAA,EACpC,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,OAAO;AACR,CAAC;;;ACXD,IAAM,kBAAkB;AAExB,SAAS,kBAAkB,OAAuB;AACjD,SAAO,MAAM,QAAQ,iBAAiB,EAAE;AACzC;AAEA,SAAS,cAAc,OAAyC;AAC/D,SAAO;AAAA,IACN,OAAO,kBAAkB,MAAM,KAAK;AAAA,IACpC,SAAS,kBAAkB,MAAM,OAAO;AAAA,IACxC,GAAI,MAAM,SAAS,SAAY,EAAE,MAAM,kBAAkB,MAAM,IAAI,EAAE,IAAI,CAAC;AAAA,EAC3E;AACD;AAGO,SAAS,wBACf,QACA,SACW;AACX,QAAM,OAAO;AAAA,IACZ,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,OAAO,SAAS,SAAS;AAAA,IACzB,QAAQ,SAAS,UAAU;AAAA,IAC3B,QAAQ,OAAO,IAAI,aAAa;AAAA,EACjC;AAEA,SAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;AAAA,IACzC,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,0BAA0B;AAAA,EACtD,CAAC;AACF;;;AFzCA,SAAS,aAAa,QAAiD;AACtE,SAAO,OAAO,IAAI,CAAC,WAAW;AAAA,IAC7B,OAAO,MAAM,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,KAAK,GAAG,KAAK;AAAA,IAClD,SAAS,MAAM;AAAA,IACf,MAAM,MAAM;AAAA,EACb,EAAE;AACH;AAEO,SAAS,mBACf,SACwF;AACxF,SAAO,CAAC,QAAQ,OAAO;AACtB,QAAI,OAAO,QAAS;AACpB,WAAO,wBAAwB,aAAa,OAAO,MAAM,GAAG,OAAO;AAAA,EACpE;AACD;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/valibot.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { BaseIssue, GenericSchema, GenericSchemaAsync, SafeParseResult } from \"valibot\";\nimport {\n\ttype ValidationError,\n\ttype ValidationHookOptions,\n\tbuildValidationResponse,\n} from \"./validation.js\";\n\nexport type { ValidationHookOptions as ValibotProblemHookOptions };\n\nfunction formatIssues(issues: BaseIssue<unknown>[]): ValidationError[] {\n\treturn issues.map((issue) => ({\n\t\tfield: issue.path?.map((p) => p.key).join(\".\") ?? \"\",\n\t\tmessage: issue.message,\n\t\tcode: issue.type,\n\t}));\n}\n\nexport function valibotProblemHook<T extends GenericSchema | GenericSchemaAsync = GenericSchema>(\n\toptions?: ValidationHookOptions,\n): (result: SafeParseResult<T> & { target: string }, c: Context) => Response | undefined {\n\treturn (result, _c) => {\n\t\tif (result.success) return;\n\t\treturn buildValidationResponse(formatIssues(result.issues), options);\n\t};\n}\n"],"mappings":";;;;;;;AAUA,SAAS,aAAa,QAAiD;AACtE,SAAO,OAAO,IAAI,CAAC,WAAW;AAAA,IAC7B,OAAO,MAAM,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,KAAK,GAAG,KAAK;AAAA,IAClD,SAAS,MAAM;AAAA,IACf,MAAM,MAAM;AAAA,EACb,EAAE;AACH;AAEO,SAAS,mBACf,SACwF;AACxF,SAAO,CAAC,QAAQ,OAAO;AACtB,QAAI,OAAO,QAAS;AACpB,WAAO,wBAAwB,aAAa,OAAO,MAAM,GAAG,OAAO;AAAA,EACpE;AACD;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/zod.ts","../../src/utils.ts","../../src/integrations/validation.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { ZodError } from \"zod\";\nimport {\n\ttype ValidationError,\n\ttype ValidationHookOptions,\n\tbuildValidationResponse,\n} from \"./validation.js\";\n\nexport type { ValidationHookOptions as ZodProblemHookOptions };\n\nfunction formatErrors(zodError: ZodError): ValidationError[] {\n\treturn zodError.issues.map((issue) => ({\n\t\tfield: issue.path.join(\".\"),\n\t\tmessage: issue.message,\n\t\tcode: issue.code,\n\t}));\n}\n\nexport function zodProblemHook(\n\toptions?: ValidationHookOptions,\n): (\n\tresult: { success: true; data: unknown } | { success: false; error: ZodError },\n\tc: Context,\n) => Response | undefined {\n\treturn (result, _c) => {\n\t\tif (result.success) return;\n\t\treturn buildValidationResponse(formatErrors(result.error), options);\n\t};\n}\n","import { statusToPhrase } from \"./status.js\";\nimport type { ProblemDetails, ProblemDetailsInput } from \"./types.js\";\n\nexport const PROBLEM_JSON_CONTENT_TYPE = \"application/problem+json; charset=utf-8\";\n\nconst DANGEROUS_KEYS = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/** Strip keys that could cause prototype pollution in downstream consumers */\nexport function sanitizeExtensions(\n\textensions: Record<string, unknown> | undefined,\n): Record<string, unknown> | undefined {\n\tif (!extensions) return extensions;\n\tlet filtered: Record<string, unknown> | undefined;\n\tfor (const key of Object.keys(extensions)) {\n\t\tif (DANGEROUS_KEYS.has(key)) {\n\t\t\tif (!filtered) filtered = { ...extensions };\n\t\t\tdelete filtered[key];\n\t\t}\n\t}\n\treturn filtered ?? extensions;\n}\n\n/** Clamp HTTP status to 200-599 integer range; returns 500 for out-of-range or non-integer values */\nexport function clampHttpStatus(status: number): number {\n\treturn Number.isInteger(status) && status >= 200 && status <= 599 ? status : 500;\n}\n\nconst FALLBACK_BODY = JSON.stringify({\n\ttype: \"about:blank\",\n\tstatus: 500,\n\ttitle: \"Internal Server Error\",\n});\n\n/** Normalize ProblemDetailsInput to ProblemDetails with defaults for type and title */\nexport function normalizeProblemDetails<T extends Record<string, unknown>>(\n\tinput: ProblemDetailsInput<T>,\n): ProblemDetails<T> {\n\treturn {\n\t\ttype: input.type ?? \"about:blank\",\n\t\tstatus: input.status,\n\t\ttitle: input.title ?? statusToPhrase(input.status) ?? \"Unknown Error\",\n\t\tdetail: input.detail,\n\t\tinstance: input.instance,\n\t\textensions: input.extensions,\n\t};\n}\n\n/** Build a RFC 9457 Problem Details Response from a ProblemDetails object */\nexport function buildProblemResponse(pd: ProblemDetails): Response {\n\tconst { extensions, ...standard } = pd;\n\tconst body = { ...sanitizeExtensions(extensions), ...standard };\n\tconst { json, fallback } = safeStringify(body);\n\treturn new Response(json, {\n\t\tstatus: fallback ? 500 : clampHttpStatus(pd.status),\n\t\theaders: { \"Content-Type\": PROBLEM_JSON_CONTENT_TYPE },\n\t});\n}\n\n/** JSON.stringify with fallback for non-serializable values (circular refs, BigInt) */\nexport function safeStringify(body: unknown): { json: string; fallback: boolean } {\n\ttry {\n\t\treturn { json: JSON.stringify(body), fallback: false };\n\t} catch {\n\t\treturn { json: FALLBACK_BODY, fallback: true };\n\t}\n}\n","import { PROBLEM_JSON_CONTENT_TYPE } from \"../utils.js\";\n\nexport interface ValidationError {\n\tfield: string;\n\tmessage: string;\n\tcode?: string;\n}\n\nexport interface ValidationHookOptions {\n\ttitle?: string;\n\tdetail?: string;\n}\n\n/**\n * Strip C0 control characters (\\x00-\\x1f) and DEL (\\x7f) from untrusted text.\n * Bidi/format control chars (U+2028, U+202E, etc.) are intentionally left intact\n * to avoid breaking legitimate i18n content; log consumers should apply their\n * own bidi-safe rendering.\n */\n// biome-ignore lint/suspicious/noControlCharactersInRegex: intentional stripping of C0 controls\nconst CONTROL_CHAR_RE = /[\\x00-\\x1f\\x7f]/g;\n\nfunction stripControlChars(input: string): string {\n\treturn input.replace(CONTROL_CHAR_RE, \"\");\n}\n\nfunction sanitizeError(error: ValidationError): ValidationError {\n\treturn {\n\t\tfield: stripControlChars(error.field),\n\t\tmessage: stripControlChars(error.message),\n\t\t...(error.code !== undefined ? { code: stripControlChars(error.code) } : {}),\n\t};\n}\n\n/** Build a RFC 9457 validation error response from formatted errors */\nexport function buildValidationResponse(\n\terrors: ValidationError[],\n\toptions?: ValidationHookOptions,\n): Response {\n\tconst body = {\n\t\ttype: \"about:blank\",\n\t\tstatus: 422,\n\t\ttitle: options?.title ?? \"Validation Error\",\n\t\tdetail: options?.detail ?? \"Request validation failed\",\n\t\terrors: errors.map(sanitizeError),\n\t};\n\n\treturn new Response(JSON.stringify(body), {\n\t\tstatus: 422,\n\t\theaders: { \"Content-Type\": PROBLEM_JSON_CONTENT_TYPE },\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,4BAA4B;AAwBzC,IAAM,gBAAgB,KAAK,UAAU;AAAA,EACpC,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,OAAO;AACR,CAAC;;;ACXD,IAAM,kBAAkB;AAExB,SAAS,kBAAkB,OAAuB;AACjD,SAAO,MAAM,QAAQ,iBAAiB,EAAE;AACzC;AAEA,SAAS,cAAc,OAAyC;AAC/D,SAAO;AAAA,IACN,OAAO,kBAAkB,MAAM,KAAK;AAAA,IACpC,SAAS,kBAAkB,MAAM,OAAO;AAAA,IACxC,GAAI,MAAM,SAAS,SAAY,EAAE,MAAM,kBAAkB,MAAM,IAAI,EAAE,IAAI,CAAC;AAAA,EAC3E;AACD;AAGO,SAAS,wBACf,QACA,SACW;AACX,QAAM,OAAO;AAAA,IACZ,MAAM;AAAA,IACN,QAAQ;AAAA,IACR,OAAO,SAAS,SAAS;AAAA,IACzB,QAAQ,SAAS,UAAU;AAAA,IAC3B,QAAQ,OAAO,IAAI,aAAa;AAAA,EACjC;AAEA,SAAO,IAAI,SAAS,KAAK,UAAU,IAAI,GAAG;AAAA,IACzC,QAAQ;AAAA,IACR,SAAS,EAAE,gBAAgB,0BAA0B;AAAA,EACtD,CAAC;AACF;;;AFzCA,SAAS,aAAa,UAAuC;AAC5D,SAAO,SAAS,OAAO,IAAI,CAAC,WAAW;AAAA,IACtC,OAAO,MAAM,KAAK,KAAK,GAAG;AAAA,IAC1B,SAAS,MAAM;AAAA,IACf,MAAM,MAAM;AAAA,EACb,EAAE;AACH;AAEO,SAAS,eACf,SAIyB;AACzB,SAAO,CAAC,QAAQ,OAAO;AACtB,QAAI,OAAO,QAAS;AACpB,WAAO,wBAAwB,aAAa,OAAO,KAAK,GAAG,OAAO;AAAA,EACnE;AACD;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/integrations/zod.ts"],"sourcesContent":["import type { Context } from \"hono\";\nimport type { ZodError } from \"zod\";\nimport {\n\ttype ValidationError,\n\ttype ValidationHookOptions,\n\tbuildValidationResponse,\n} from \"./validation.js\";\n\nexport type { ValidationHookOptions as ZodProblemHookOptions };\n\nfunction formatErrors(zodError: ZodError): ValidationError[] {\n\treturn zodError.issues.map((issue) => ({\n\t\tfield: issue.path.join(\".\"),\n\t\tmessage: issue.message,\n\t\tcode: issue.code,\n\t}));\n}\n\nexport function zodProblemHook(\n\toptions?: ValidationHookOptions,\n): (\n\tresult: { success: true; data: unknown } | { success: false; error: ZodError },\n\tc: Context,\n) => Response | undefined {\n\treturn (result, _c) => {\n\t\tif (result.success) return;\n\t\treturn buildValidationResponse(formatErrors(result.error), options);\n\t};\n}\n"],"mappings":";;;;;;;AAUA,SAAS,aAAa,UAAuC;AAC5D,SAAO,SAAS,OAAO,IAAI,CAAC,WAAW;AAAA,IACtC,OAAO,MAAM,KAAK,KAAK,GAAG;AAAA,IAC1B,SAAS,MAAM;AAAA,IACf,MAAM,MAAM;AAAA,EACb,EAAE;AACH;AAEO,SAAS,eACf,SAIyB;AACzB,SAAO,CAAC,QAAQ,OAAO;AACtB,QAAI,OAAO,QAAS;AACpB,WAAO,wBAAwB,aAAa,OAAO,KAAK,GAAG,OAAO;AAAA,EACnE;AACD;","names":[]}
|