hono-problem-details 0.6.1 → 0.8.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 CHANGED
@@ -38,9 +38,10 @@ can all agree on.
38
38
  - **Zod integration** — `@hono/zod-validator` hook for validation errors
39
39
  - **Valibot integration** — `@hono/valibot-validator` hook for validation errors
40
40
  - **OpenAPI integration** — `@hono/zod-openapi` schemas for API documentation
41
+ - **OpenTelemetry integration** — `@opentelemetry/api` for automatically injecting trace information.
41
42
  - **Standard Schema** — `@hono/standard-validator` hook (works with any schema library)
42
43
  - **Type-safe** — full TypeScript support with inference
43
- - **Zero runtime dependencies** — `hono` is the only required peer dependency; validator integrations are optional
44
+ - **Zero runtime dependencies** — `hono` is the only required peer dependency; validation and opentelemetry integrations are optional
44
45
  - **Localization** — `localize` callback for title/detail translation
45
46
  - **Edge-first** — works on Cloudflare Workers, Deno, Bun, and Node.js
46
47
 
@@ -356,8 +357,8 @@ Use with `@hono/zod-openapi` to document Problem Details error responses in your
356
357
  import { OpenAPIHono, createRoute, z } from "@hono/zod-openapi";
357
358
  import { problemDetailsHandler } from "hono-problem-details";
358
359
  import {
359
- ProblemDetailsSchema,
360
360
  createProblemDetailsSchema,
361
+ getProblemDetailsSchema,
361
362
  problemDetailsResponse,
362
363
  } from "hono-problem-details/openapi";
363
364
 
@@ -385,6 +386,9 @@ const route = createRoute({
385
386
  },
386
387
  });
387
388
 
389
+ // Need the schema itself? Call the factory:
390
+ const ProblemDetailsSchema = getProblemDetailsSchema();
391
+
388
392
  // With extension members
389
393
  const errorWithExtensions = createProblemDetailsSchema(
390
394
  z.object({
@@ -394,6 +398,13 @@ const errorWithExtensions = createProblemDetailsSchema(
394
398
  // Use: problemDetailsResponse(422, "Validation Error", errorWithExtensions)
395
399
  ```
396
400
 
401
+ > **Migrating from v0.6.x**: `ProblemDetailsSchema` (the const export) was removed
402
+ > in v0.7.0. Replace `import { ProblemDetailsSchema }` with
403
+ > `import { getProblemDetailsSchema }` and call it where you previously read
404
+ > the const. The factory is memoized — repeat calls return the same instance.
405
+ > See [ADR-0004](./docs/adr/0004-defer-openapi-schema-construction-via-factory.md)
406
+ > for the bundler-related reason this changed.
407
+
397
408
  ## Localization
398
409
 
399
410
  Use the `localize` callback to translate `title` and `detail` based on the request context.
@@ -424,6 +435,21 @@ The callback receives the fully-built `ProblemDetails` object and the Hono `Cont
424
435
  > the error handler to re-enter itself, so the swallow is deliberate. Catch errors inside your
425
436
  > callback if you need to observe them.
426
437
 
438
+ ## OpenTelemetry Integration
439
+
440
+ To enable OpenTelemetry instrumentation in problem details responses, pass the OpenTelemetry API as an option to the handler:
441
+
442
+ ```ts
443
+ import * as otelApi from "@opentelemetry/api";
444
+
445
+ problemDetailsHandler({
446
+ otelApi,
447
+ });
448
+ ```
449
+
450
+ When enabled, the handler adds a `traceId` extension member to all problem details responses when a trace is active.
451
+ This allows clients to correlate errors with server-side traces for easier debugging.
452
+
427
453
  ## Handler Options
428
454
 
429
455
  ```ts
package/dist/index.cjs CHANGED
@@ -162,6 +162,19 @@ function problemDetails(input) {
162
162
 
163
163
  // src/handler.ts
164
164
  var import_http_exception = require("hono/http-exception");
165
+
166
+ // src/integrations/opentelemetry.ts
167
+ function getOtelTraceId(api) {
168
+ try {
169
+ const span = api.trace.getSpan(api.context.active());
170
+ const traceId = span?.spanContext().traceId;
171
+ return traceId;
172
+ } catch {
173
+ return void 0;
174
+ }
175
+ }
176
+
177
+ // src/handler.ts
165
178
  function buildType(status, options) {
166
179
  if (options.typePrefix) {
167
180
  const slug = statusToSlug(status);
@@ -174,6 +187,15 @@ function toResponse(input, c, options) {
174
187
  if (options.autoInstance && pd.instance === void 0) {
175
188
  pd = { ...pd, instance: c.req.path };
176
189
  }
190
+ if (options.otelApi && pd.extensions?.traceId === void 0) {
191
+ const traceId = getOtelTraceId(options.otelApi);
192
+ if (traceId) {
193
+ if (!pd.extensions) {
194
+ pd.extensions = {};
195
+ }
196
+ pd.extensions.traceId = traceId;
197
+ }
198
+ }
177
199
  if (options.localize) {
178
200
  try {
179
201
  pd = { ...pd, ...options.localize(pd, c) };
package/dist/index.d.cts CHANGED
@@ -51,6 +51,21 @@ interface ProblemDetailsHandlerOptions {
51
51
  * Default: `false` — opt-in to avoid silently changing response shape.
52
52
  */
53
53
  autoInstance?: boolean;
54
+ /**
55
+ * If the OpenTelemetry API is available, the handler will attempt to
56
+ * include the current trace ID in the Problem Details response.
57
+ *
58
+ * To use this feature, pass the OpenTelemetry API as `otelApi` in the options:
59
+ *
60
+ * ```ts
61
+ * import * as api from "@opentelemetry/api";
62
+ *
63
+ * app.onError(problemDetailsHandler({
64
+ * otelApi: api,
65
+ * }));
66
+ * ```
67
+ */
68
+ otelApi?: OtelApiLike;
54
69
  /** Custom error to ProblemDetails mapping */
55
70
  mapError?: (error: Error) => ProblemDetailsInput | undefined;
56
71
  /**
@@ -60,6 +75,18 @@ interface ProblemDetailsHandlerOptions {
60
75
  */
61
76
  localize?: (pd: ProblemDetails, c: Context) => Partial<ProblemDetails> | undefined;
62
77
  }
78
+ interface OtelApiLike {
79
+ trace: {
80
+ getSpan(context: unknown): {
81
+ spanContext(): {
82
+ traceId: string;
83
+ };
84
+ } | undefined;
85
+ };
86
+ context: {
87
+ active(): unknown;
88
+ };
89
+ }
63
90
 
64
91
  /**
65
92
  * Error class for RFC 9457 Problem Details.
package/dist/index.d.ts CHANGED
@@ -51,6 +51,21 @@ interface ProblemDetailsHandlerOptions {
51
51
  * Default: `false` — opt-in to avoid silently changing response shape.
52
52
  */
53
53
  autoInstance?: boolean;
54
+ /**
55
+ * If the OpenTelemetry API is available, the handler will attempt to
56
+ * include the current trace ID in the Problem Details response.
57
+ *
58
+ * To use this feature, pass the OpenTelemetry API as `otelApi` in the options:
59
+ *
60
+ * ```ts
61
+ * import * as api from "@opentelemetry/api";
62
+ *
63
+ * app.onError(problemDetailsHandler({
64
+ * otelApi: api,
65
+ * }));
66
+ * ```
67
+ */
68
+ otelApi?: OtelApiLike;
54
69
  /** Custom error to ProblemDetails mapping */
55
70
  mapError?: (error: Error) => ProblemDetailsInput | undefined;
56
71
  /**
@@ -60,6 +75,18 @@ interface ProblemDetailsHandlerOptions {
60
75
  */
61
76
  localize?: (pd: ProblemDetails, c: Context) => Partial<ProblemDetails> | undefined;
62
77
  }
78
+ interface OtelApiLike {
79
+ trace: {
80
+ getSpan(context: unknown): {
81
+ spanContext(): {
82
+ traceId: string;
83
+ };
84
+ } | undefined;
85
+ };
86
+ context: {
87
+ active(): unknown;
88
+ };
89
+ }
63
90
 
64
91
  /**
65
92
  * Error class for RFC 9457 Problem Details.
package/dist/index.js CHANGED
@@ -35,6 +35,19 @@ function problemDetails(input) {
35
35
 
36
36
  // src/handler.ts
37
37
  import { HTTPException } from "hono/http-exception";
38
+
39
+ // src/integrations/opentelemetry.ts
40
+ function getOtelTraceId(api) {
41
+ try {
42
+ const span = api.trace.getSpan(api.context.active());
43
+ const traceId = span?.spanContext().traceId;
44
+ return traceId;
45
+ } catch {
46
+ return void 0;
47
+ }
48
+ }
49
+
50
+ // src/handler.ts
38
51
  function buildType(status, options) {
39
52
  if (options.typePrefix) {
40
53
  const slug = statusToSlug(status);
@@ -47,6 +60,15 @@ function toResponse(input, c, options) {
47
60
  if (options.autoInstance && pd.instance === void 0) {
48
61
  pd = { ...pd, instance: c.req.path };
49
62
  }
63
+ if (options.otelApi && pd.extensions?.traceId === void 0) {
64
+ const traceId = getOtelTraceId(options.otelApi);
65
+ if (traceId) {
66
+ if (!pd.extensions) {
67
+ pd.extensions = {};
68
+ }
69
+ pd.extensions.traceId = traceId;
70
+ }
71
+ }
50
72
  if (options.localize) {
51
73
  try {
52
74
  pd = { ...pd, ...options.localize(pd, c) };
@@ -20,8 +20,8 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/integrations/openapi.ts
21
21
  var openapi_exports = {};
22
22
  __export(openapi_exports, {
23
- ProblemDetailsSchema: () => ProblemDetailsSchema,
24
23
  createProblemDetailsSchema: () => createProblemDetailsSchema,
24
+ getProblemDetailsSchema: () => getProblemDetailsSchema,
25
25
  problemDetailsResponse: () => problemDetailsResponse
26
26
  });
27
27
  module.exports = __toCommonJS(openapi_exports);
@@ -81,28 +81,38 @@ function statusToPhrase(status) {
81
81
  }
82
82
 
83
83
  // src/integrations/openapi.ts
84
- var ProblemDetailsSchema = import_zod_openapi.z.object({
85
- type: import_zod_openapi.z.string().openapi({ description: "Problem type URI", example: "about:blank" }),
86
- status: import_zod_openapi.z.number().int().openapi({ description: "HTTP status code", example: 400 }),
87
- title: import_zod_openapi.z.string().openapi({ description: "Short summary of the problem type", example: "Bad Request" }),
88
- detail: import_zod_openapi.z.string().optional().openapi({ description: "Human-readable explanation" }),
89
- instance: import_zod_openapi.z.string().optional().openapi({ description: "URI identifying the occurrence" })
90
- }).openapi({ title: "ProblemDetails" });
84
+ var _cached;
85
+ function getProblemDetailsSchema() {
86
+ if (!_cached) {
87
+ _cached = import_zod_openapi.z.object({
88
+ type: import_zod_openapi.z.string().openapi({ description: "Problem type URI", example: "about:blank" }),
89
+ status: import_zod_openapi.z.number().int().openapi({ description: "HTTP status code", example: 400 }),
90
+ title: import_zod_openapi.z.string().openapi({ description: "Short summary of the problem type", example: "Bad Request" }),
91
+ detail: import_zod_openapi.z.string().optional().openapi({ description: "Human-readable explanation" }),
92
+ instance: import_zod_openapi.z.string().optional().openapi({ description: "URI identifying the occurrence" })
93
+ }).openapi({ title: "ProblemDetails" });
94
+ }
95
+ return _cached;
96
+ }
97
+ var STANDARD_FIELD_KEYS = /* @__PURE__ */ new Set(["type", "status", "title", "detail", "instance"]);
91
98
  function createProblemDetailsSchema(extensions) {
92
- return ProblemDetailsSchema.extend(extensions.shape).openapi({ title: "ProblemDetails" });
99
+ const safeShape = Object.fromEntries(
100
+ Object.entries(extensions.shape).filter(([key]) => !STANDARD_FIELD_KEYS.has(key))
101
+ );
102
+ return getProblemDetailsSchema().extend(safeShape).openapi({ title: "ProblemDetails" });
93
103
  }
94
- function problemDetailsResponse(status, description, schema = ProblemDetailsSchema) {
104
+ function problemDetailsResponse(status, description, schema) {
95
105
  return {
96
106
  content: {
97
- "application/problem+json": { schema }
107
+ "application/problem+json": { schema: schema ?? getProblemDetailsSchema() }
98
108
  },
99
109
  description: description ?? statusToPhrase(status) ?? "Error"
100
110
  };
101
111
  }
102
112
  // Annotate the CommonJS export names for ESM import in node:
103
113
  0 && (module.exports = {
104
- ProblemDetailsSchema,
105
114
  createProblemDetailsSchema,
115
+ getProblemDetailsSchema,
106
116
  problemDetailsResponse
107
117
  });
108
118
  //# sourceMappingURL=openapi.cjs.map
@@ -1,19 +1,29 @@
1
1
  import { z } from '@hono/zod-openapi';
2
2
 
3
- /**
4
- * Base RFC 9457 Problem Details Zod schema for OpenAPI documentation.
5
- * Use in createRoute() response definitions with @hono/zod-openapi.
6
- */
7
- declare const ProblemDetailsSchema: z.ZodObject<{
3
+ type ProblemDetailsShape = {
8
4
  type: z.ZodString;
9
5
  status: z.ZodNumber;
10
6
  title: z.ZodString;
11
7
  detail: z.ZodOptional<z.ZodString>;
12
8
  instance: z.ZodOptional<z.ZodString>;
13
- }>;
9
+ };
10
+ /**
11
+ * Build the RFC 9457 Problem Details Zod schema for OpenAPI documentation.
12
+ *
13
+ * The schema is constructed lazily on first call and memoized for subsequent
14
+ * calls. Deferring construction past module load avoids `TypeError` failures
15
+ * under bundlers that resolve duplicate `zod` instances, because the
16
+ * `@hono/zod-openapi` prototype patch must be in place before `.openapi()`
17
+ * runs. See ADR-0004 for the full rationale.
18
+ */
19
+ declare function getProblemDetailsSchema(): z.ZodObject<ProblemDetailsShape>;
14
20
  /**
15
21
  * Create a Problem Details schema with typed extension members.
16
- * Extensions are merged at top level per RFC 9457.
22
+ *
23
+ * Extensions are merged at top level per RFC 9457 §3.1, and **standard fields
24
+ * always win** over extension keys that collide (mirroring the runtime spread
25
+ * order in `problemDetails()`). Conflicting extension keys are silently
26
+ * dropped from the schema.
17
27
  */
18
28
  declare function createProblemDetailsSchema<T extends z.ZodRawShape>(extensions: z.ZodObject<T>): z.ZodObject;
19
29
  /**
@@ -29,4 +39,4 @@ declare function problemDetailsResponse(status: number, description?: string, sc
29
39
  description: string;
30
40
  };
31
41
 
32
- export { ProblemDetailsSchema, createProblemDetailsSchema, problemDetailsResponse };
42
+ export { createProblemDetailsSchema, getProblemDetailsSchema, problemDetailsResponse };
@@ -1,19 +1,29 @@
1
1
  import { z } from '@hono/zod-openapi';
2
2
 
3
- /**
4
- * Base RFC 9457 Problem Details Zod schema for OpenAPI documentation.
5
- * Use in createRoute() response definitions with @hono/zod-openapi.
6
- */
7
- declare const ProblemDetailsSchema: z.ZodObject<{
3
+ type ProblemDetailsShape = {
8
4
  type: z.ZodString;
9
5
  status: z.ZodNumber;
10
6
  title: z.ZodString;
11
7
  detail: z.ZodOptional<z.ZodString>;
12
8
  instance: z.ZodOptional<z.ZodString>;
13
- }>;
9
+ };
10
+ /**
11
+ * Build the RFC 9457 Problem Details Zod schema for OpenAPI documentation.
12
+ *
13
+ * The schema is constructed lazily on first call and memoized for subsequent
14
+ * calls. Deferring construction past module load avoids `TypeError` failures
15
+ * under bundlers that resolve duplicate `zod` instances, because the
16
+ * `@hono/zod-openapi` prototype patch must be in place before `.openapi()`
17
+ * runs. See ADR-0004 for the full rationale.
18
+ */
19
+ declare function getProblemDetailsSchema(): z.ZodObject<ProblemDetailsShape>;
14
20
  /**
15
21
  * Create a Problem Details schema with typed extension members.
16
- * Extensions are merged at top level per RFC 9457.
22
+ *
23
+ * Extensions are merged at top level per RFC 9457 §3.1, and **standard fields
24
+ * always win** over extension keys that collide (mirroring the runtime spread
25
+ * order in `problemDetails()`). Conflicting extension keys are silently
26
+ * dropped from the schema.
17
27
  */
18
28
  declare function createProblemDetailsSchema<T extends z.ZodRawShape>(extensions: z.ZodObject<T>): z.ZodObject;
19
29
  /**
@@ -29,4 +39,4 @@ declare function problemDetailsResponse(status: number, description?: string, sc
29
39
  description: string;
30
40
  };
31
41
 
32
- export { ProblemDetailsSchema, createProblemDetailsSchema, problemDetailsResponse };
42
+ export { createProblemDetailsSchema, getProblemDetailsSchema, problemDetailsResponse };
@@ -4,27 +4,37 @@ import {
4
4
 
5
5
  // src/integrations/openapi.ts
6
6
  import { z } from "@hono/zod-openapi";
7
- var ProblemDetailsSchema = z.object({
8
- type: z.string().openapi({ description: "Problem type URI", example: "about:blank" }),
9
- status: z.number().int().openapi({ description: "HTTP status code", example: 400 }),
10
- title: z.string().openapi({ description: "Short summary of the problem type", example: "Bad Request" }),
11
- detail: z.string().optional().openapi({ description: "Human-readable explanation" }),
12
- instance: z.string().optional().openapi({ description: "URI identifying the occurrence" })
13
- }).openapi({ title: "ProblemDetails" });
7
+ var _cached;
8
+ function getProblemDetailsSchema() {
9
+ if (!_cached) {
10
+ _cached = z.object({
11
+ type: z.string().openapi({ description: "Problem type URI", example: "about:blank" }),
12
+ status: z.number().int().openapi({ description: "HTTP status code", example: 400 }),
13
+ title: z.string().openapi({ description: "Short summary of the problem type", example: "Bad Request" }),
14
+ detail: z.string().optional().openapi({ description: "Human-readable explanation" }),
15
+ instance: z.string().optional().openapi({ description: "URI identifying the occurrence" })
16
+ }).openapi({ title: "ProblemDetails" });
17
+ }
18
+ return _cached;
19
+ }
20
+ var STANDARD_FIELD_KEYS = /* @__PURE__ */ new Set(["type", "status", "title", "detail", "instance"]);
14
21
  function createProblemDetailsSchema(extensions) {
15
- return ProblemDetailsSchema.extend(extensions.shape).openapi({ title: "ProblemDetails" });
22
+ const safeShape = Object.fromEntries(
23
+ Object.entries(extensions.shape).filter(([key]) => !STANDARD_FIELD_KEYS.has(key))
24
+ );
25
+ return getProblemDetailsSchema().extend(safeShape).openapi({ title: "ProblemDetails" });
16
26
  }
17
- function problemDetailsResponse(status, description, schema = ProblemDetailsSchema) {
27
+ function problemDetailsResponse(status, description, schema) {
18
28
  return {
19
29
  content: {
20
- "application/problem+json": { schema }
30
+ "application/problem+json": { schema: schema ?? getProblemDetailsSchema() }
21
31
  },
22
32
  description: description ?? statusToPhrase(status) ?? "Error"
23
33
  };
24
34
  }
25
35
  export {
26
- ProblemDetailsSchema,
27
36
  createProblemDetailsSchema,
37
+ getProblemDetailsSchema,
28
38
  problemDetailsResponse
29
39
  };
30
40
  //# sourceMappingURL=openapi.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hono-problem-details",
3
- "version": "0.6.1",
3
+ "version": "0.8.0",
4
4
  "description": "RFC 9457 Problem Details middleware for Hono",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
@@ -104,6 +104,7 @@
104
104
  "@hono/valibot-validator": "^0.6.0",
105
105
  "@hono/zod-openapi": "^1.0.0",
106
106
  "@hono/zod-validator": "^0.7.5",
107
+ "@opentelemetry/api": "^1.0.0",
107
108
  "@standard-schema/spec": "^1.0.0",
108
109
  "hono": ">=4.12.14",
109
110
  "valibot": "^1.0.0",
@@ -128,6 +129,9 @@
128
129
  "@hono/standard-validator": {
129
130
  "optional": true
130
131
  },
132
+ "@opentelemetry/api": {
133
+ "optional": true
134
+ },
131
135
  "@standard-schema/spec": {
132
136
  "optional": true
133
137
  }
@@ -140,6 +144,7 @@
140
144
  "@hono/valibot-validator": "^0.6.1",
141
145
  "@hono/zod-openapi": "1.3.0",
142
146
  "@hono/zod-validator": "^0.7.6",
147
+ "@opentelemetry/api": "^1.0.0",
143
148
  "@standard-schema/spec": "1.1.0",
144
149
  "@vitest/coverage-v8": "^3.0.0",
145
150
  "hono": "^4.12.14",