@honeybadger-io/nextjs 5.11.5 → 6.0.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.
Files changed (62) hide show
  1. package/README.md +5 -42
  2. package/dist/capture-request-error.d.ts +35 -0
  3. package/dist/capture-request-error.test.d.ts +2 -0
  4. package/dist/capture-router-transition-start.d.ts +21 -0
  5. package/dist/client.d.ts +2 -0
  6. package/dist/copy-config-files.js +106 -34
  7. package/dist/copy-config-files.js.map +1 -1
  8. package/dist/edge.d.ts +2 -1
  9. package/dist/flush.d.ts +24 -0
  10. package/dist/honeybadger-nextjs-client.cjs.js +35 -0
  11. package/dist/honeybadger-nextjs-client.cjs.js.map +1 -0
  12. package/dist/honeybadger-nextjs-client.esm.js +27 -0
  13. package/dist/honeybadger-nextjs-client.esm.js.map +1 -0
  14. package/dist/honeybadger-nextjs-edge.cjs.js +320 -240
  15. package/dist/honeybadger-nextjs-edge.cjs.js.map +1 -1
  16. package/dist/honeybadger-nextjs-edge.esm.js +317 -240
  17. package/dist/honeybadger-nextjs-edge.esm.js.map +1 -1
  18. package/dist/honeybadger-nextjs.cjs.js +835 -387
  19. package/dist/honeybadger-nextjs.cjs.js.map +1 -1
  20. package/dist/honeybadger-nextjs.esm.js +829 -386
  21. package/dist/honeybadger-nextjs.esm.js.map +1 -1
  22. package/dist/index.d.ts +5 -2
  23. package/dist/insights-instrumentation.d.ts +30 -2
  24. package/dist/insights.d.ts +72 -0
  25. package/dist/insights.test.d.ts +2 -0
  26. package/dist/setup.d.ts +11 -0
  27. package/dist/setup.test.d.ts +2 -0
  28. package/dist/source-maps.d.ts +55 -0
  29. package/dist/source-maps.test.d.ts +2 -0
  30. package/dist/types.d.ts +20 -8
  31. package/package.json +34 -12
  32. package/src/capture-request-error.test.ts +245 -0
  33. package/src/capture-request-error.ts +92 -0
  34. package/src/capture-router-transition-start.ts +33 -0
  35. package/src/client.ts +4 -0
  36. package/src/copy-config-files.test.ts +250 -16
  37. package/src/copy-config-files.ts +117 -34
  38. package/src/edge.ts +12 -1
  39. package/src/flush.ts +58 -0
  40. package/src/index.ts +7 -2
  41. package/src/insights-instrumentation.ts +104 -11
  42. package/src/insights.test.ts +192 -0
  43. package/src/insights.ts +225 -0
  44. package/src/setup.test.ts +214 -0
  45. package/src/setup.ts +172 -0
  46. package/src/source-maps.test.ts +803 -0
  47. package/src/source-maps.ts +515 -0
  48. package/src/types.ts +38 -21
  49. package/templates/_error.js +14 -10
  50. package/templates/_error_app_router.js +1 -1
  51. package/templates/_error_app_router.tsx +1 -1
  52. package/templates/honeybadger.server.config.js +5 -16
  53. package/templates/instrumentation-client.js +21 -0
  54. package/templates/instrumentation.js +29 -0
  55. package/dist/webpack.d.ts +0 -3
  56. package/dist/with-honeybadger.d.ts +0 -32
  57. package/dist/with-honeybadger.test.d.ts +0 -2
  58. package/src/webpack.ts +0 -228
  59. package/src/with-honeybadger.test.ts +0 -527
  60. package/src/with-honeybadger.ts +0 -286
  61. package/templates/honeybadger.browser.config.js +0 -13
  62. package/templates/honeybadger.edge.config.js +0 -13
@@ -3,7 +3,7 @@ import Honeybadger from '@honeybadger-io/js';
3
3
  /**
4
4
  * Edge-safe equivalents of the inbound instrumentation helpers in
5
5
  * `@honeybadger-io/js` (src/server/instrumentation/http_event.ts). They are
6
- * duplicated here because this module must also load on the edge runtime where
6
+ * duplicated here because this module must load in every runtime where
7
7
  * Node builtins (the `crypto` module, `process.hrtime`) are unavailable. Keep
8
8
  * the header names and the `request_id` / `correlation_id` contract in sync
9
9
  * with that file.
@@ -75,34 +75,92 @@ function readNodeHeader(headers: NodeHeaders, name: string): string | undefined
75
75
  }
76
76
 
77
77
  // A type alias (not an interface) so it stays assignable to the
78
- // Record<string, unknown> that setEventContext expects.
78
+ // Record<string, unknown> that event payloads expect.
79
79
  export type RequestIds = {
80
80
  request_id: string
81
81
  correlation_id: string
82
+ // Present only when an OpenTelemetry span is available. Carried alongside the two ids
83
+ // above rather than folded into them, so a fault can be joined to the trace — and to the
84
+ // `request.handled` events — of the request it failed in.
85
+ trace_id?: string
86
+ span_id?: string
82
87
  }
83
88
 
84
- // Shared id precedence. Kept in one place (rather than once per request shape)
85
- // so the header-name contract documented above is only spelled out once.
86
- function seedIds(read: (name: string) => string | undefined): RequestIds {
89
+ /**
90
+ * Span and trace ids, when OpenTelemetry is in play.
91
+ */
92
+ export type SpanIds = { traceId?: string; spanId?: string }
93
+
94
+ /**
95
+ * Shared id precedence. Kept in one place (rather than once per request shape)
96
+ * so the header-name contract documented above is only spelled out once.
97
+ *
98
+ * The span ids do double duty. They are emitted as `trace_id` / `span_id`, and they also
99
+ * back-fill `request_id` / `correlation_id` when no header supplied them — a trace id
100
+ * already has exactly the semantics we want for a correlation id, since W3C trace context
101
+ * reuses an inbound `traceparent` and mints a new one when there is none.
102
+ *
103
+ * That double duty is what makes a fault joinable to its request's events: both paths seed
104
+ * from the same span, so with no id headers present a fault and its `request.handled` event
105
+ * carry identical values for all four.
106
+ */
107
+ function seedIds(
108
+ read: (name: string) => string | undefined,
109
+ span: SpanIds = {}
110
+ ): RequestIds {
87
111
  const requestId =
88
112
  read('x-request-id') ??
89
113
  read('request-id') ??
114
+ span.spanId ??
90
115
  generateId()
91
116
  const correlationId =
92
117
  read('x-correlation-id') ??
93
118
  read('x-amzn-trace-id') ??
119
+ span.traceId ??
94
120
  requestId
95
- return { request_id: requestId, correlation_id: correlationId }
121
+
122
+ const ids: RequestIds = { request_id: requestId, correlation_id: correlationId }
123
+ if (span.traceId) {
124
+ ids.trace_id = span.traceId
125
+ }
126
+ if (span.spanId) {
127
+ ids.span_id = span.spanId
128
+ }
129
+
130
+ return ids
131
+ }
132
+
133
+ /**
134
+ * The active span's ids, or an empty object when OpenTelemetry is not in play.
135
+ *
136
+ * `@opentelemetry/api` is an optional peer dependency, and this module is reachable from
137
+ * every runtime entry point, so it is loaded on demand and any failure to resolve it is
138
+ * treated as "no tracing configured" rather than an error.
139
+ */
140
+ export async function activeSpanIds(): Promise<SpanIds> {
141
+ try {
142
+ const { trace } = await import('@opentelemetry/api')
143
+ const spanContext = trace.getActiveSpan()?.spanContext()
144
+ if (!spanContext) {
145
+ return {}
146
+ }
147
+
148
+ return { traceId: spanContext.traceId, spanId: spanContext.spanId }
149
+ }
150
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
151
+ catch (error) {
152
+ return {}
153
+ }
96
154
  }
97
155
 
98
156
  // App Router / middleware: headers are a web `Headers` instance.
99
- export function seedRequestEventContext(headers: Headers): RequestIds {
100
- return seedIds((name) => readHeader(headers, name))
157
+ export function seedRequestEventContext(headers: Headers, span: SpanIds = {}): RequestIds {
158
+ return seedIds((name) => readHeader(headers, name), span)
101
159
  }
102
160
 
103
161
  // Pages Router: headers are a Node bag (Pages routes are Node-only, never edge).
104
- export function seedNodeRequestEventContext(headers: NodeHeaders): RequestIds {
105
- return seedIds((name) => readNodeHeader(headers, name))
162
+ export function seedNodeRequestEventContext(headers: NodeHeaders, span: SpanIds = {}): RequestIds {
163
+ return seedIds((name) => readNodeHeader(headers, name), span)
106
164
  }
107
165
 
108
166
  export function now(): number {
@@ -117,7 +175,7 @@ export function insightsHttpEnabled(): boolean {
117
175
  }
118
176
 
119
177
  // The ids are embedded directly in the payload (instead of relying on the
120
- // store's eventContext merge) so the event carries them even on the edge
178
+ // store's eventContext merge) so the event carries them even where the
121
179
  // runtime, where there is no per-request store isolation. On the Node.js
122
180
  // runtime they match the seeded event context, so embedding is a no-op.
123
181
  function emitHandledEvent(method: string | undefined, path: string | undefined, status: number | undefined, start: number, ids: RequestIds): void {
@@ -153,3 +211,38 @@ export function emitNodeRequestEvent(req: NodeRequestLike, status: number | unde
153
211
  const path = typeof req.url === 'string' ? req.url.split('?')[0] : undefined
154
212
  emitHandledEvent(req.method, path, status, start, ids)
155
213
  }
214
+
215
+ /**
216
+ * OpenTelemetry path. Header values are not on the span by default; they arrive as
217
+ * `http.request.header.*` attributes when the HTTP instrumentation is configured with
218
+ * `headersToSpanAttributes`. Hyphens become underscores under the older semantic
219
+ * conventions and are preserved under the stable ones, so both spellings are read.
220
+ *
221
+ * When no header is present the span and trace ids are used, so the ids stay
222
+ * meaningful — and joinable to a trace — on platforms where the HTTP layer is not
223
+ * visible, such as serverless platforms.
224
+ */
225
+ export function seedSpanEventContext(
226
+ attributes: Record<string, unknown>,
227
+ spanContext: SpanIds
228
+ ): RequestIds {
229
+ const read = (name: string): string | undefined => {
230
+ const lower = name.toLowerCase()
231
+ for (const key of [
232
+ `http.request.header.${lower}`,
233
+ `http.request.header.${lower.replace(/-/g, '_')}`,
234
+ ]) {
235
+ const value = attributes[key]
236
+ const first = Array.isArray(value) ? value[0] : value
237
+ if (typeof first === 'string' && first.trim().length) {
238
+ return first.trim()
239
+ }
240
+ }
241
+ return undefined
242
+ }
243
+
244
+ return seedIds(read, {
245
+ traceId: spanContext.traceId || undefined,
246
+ spanId: spanContext.spanId || undefined,
247
+ })
248
+ }
@@ -0,0 +1,192 @@
1
+ import Honeybadger from '@honeybadger-io/js'
2
+ import { HONEYBADGER_HEADER_ATTRIBUTES, honeybadgerSpanProcessor } from './insights'
3
+
4
+ const REQUEST_SPAN = 'BaseServer.handleRequest'
5
+
6
+ type SpanLike = {
7
+ attributes?: Record<string, unknown>
8
+ duration?: [number, number]
9
+ spanContext?: () => { traceId?: string; spanId?: string }
10
+ }
11
+
12
+ function span(attributes: Record<string, unknown>, options: {
13
+ duration?: [number, number]
14
+ traceId?: string
15
+ spanId?: string
16
+ } = {}): SpanLike {
17
+ return {
18
+ attributes,
19
+ duration: options.duration ?? [0, 0],
20
+ spanContext: () => ({
21
+ traceId: options.traceId ?? 'trace-aaa',
22
+ spanId: options.spanId ?? 'span-bbb',
23
+ }),
24
+ }
25
+ }
26
+
27
+ function requestSpan(extra: Record<string, unknown> = {}, options = {}) {
28
+ return span({ 'next.span_type': REQUEST_SPAN, ...extra }, options)
29
+ }
30
+
31
+ describe('honeybadgerSpanProcessor', () => {
32
+ let events: Array<{ name: string; payload: Record<string, unknown> }>
33
+
34
+ beforeEach(() => {
35
+ events = []
36
+ Honeybadger.configure({
37
+ apiKey: 'test-key',
38
+ insights: { enabled: true, http: true },
39
+ })
40
+ jest.spyOn(Honeybadger, 'event').mockImplementation(((name, payload) => {
41
+ events.push({ name: name as string, payload: payload as Record<string, unknown> })
42
+ }) as typeof Honeybadger.event)
43
+ // scheduleFlush() delivers via flushAsync; keep it off the network.
44
+ jest.spyOn(Honeybadger, 'flushAsync').mockResolvedValue(true as never)
45
+ })
46
+
47
+ afterEach(() => {
48
+ jest.restoreAllMocks()
49
+ })
50
+
51
+ function onEnd(s: SpanLike) {
52
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
53
+ honeybadgerSpanProcessor().onEnd(s as any)
54
+ }
55
+
56
+ it('emits request.handled for the Next.js request span', () => {
57
+ onEnd(requestSpan({
58
+ 'http.method': 'GET',
59
+ 'http.target': '/api/hello',
60
+ 'http.status_code': 200,
61
+ }, { duration: [1, 500_000_000] }))
62
+
63
+ expect(events).toHaveLength(1)
64
+ expect(events[0].name).toBe('request.handled')
65
+ expect(events[0].payload).toMatchObject({
66
+ method: 'GET',
67
+ path: '/api/hello',
68
+ status: 200,
69
+ duration: 1500,
70
+ })
71
+ })
72
+
73
+ it('ignores spans that are not the request span', () => {
74
+ onEnd(span({ 'next.span_type': 'AppRender.getBodyResult', 'http.method': 'GET' }))
75
+ onEnd(span({ 'http.method': 'GET' }))
76
+
77
+ expect(events).toHaveLength(0)
78
+ })
79
+
80
+ it('emits nothing when insights http is disabled', () => {
81
+ Honeybadger.configure({ apiKey: 'test-key', insights: { enabled: false, http: true } })
82
+ onEnd(requestSpan({ 'http.method': 'GET' }))
83
+
84
+ Honeybadger.configure({ apiKey: 'test-key', insights: { enabled: true, http: false } })
85
+ onEnd(requestSpan({ 'http.method': 'GET' }))
86
+
87
+ expect(events).toHaveLength(0)
88
+ })
89
+
90
+ it('reads the stable semantic-convention attribute names too', () => {
91
+ onEnd(requestSpan({
92
+ 'http.request.method': 'POST',
93
+ 'url.path': '/submit',
94
+ 'http.response.status_code': 201,
95
+ }))
96
+
97
+ expect(events[0].payload).toMatchObject({ method: 'POST', path: '/submit', status: 201 })
98
+ })
99
+
100
+ it('strips the query string from the path', () => {
101
+ onEnd(requestSpan({ 'http.method': 'GET', 'http.target': '/search?q=badger&page=2' }))
102
+
103
+ expect(events[0].payload.path).toBe('/search')
104
+ })
105
+
106
+ it('always reports trace_id and span_id alongside the ids', () => {
107
+ onEnd(requestSpan({ 'http.method': 'GET' }, { traceId: 'trace-123', spanId: 'span-456' }))
108
+
109
+ expect(events[0].payload).toMatchObject({ trace_id: 'trace-123', span_id: 'span-456' })
110
+ })
111
+
112
+ describe('request_id and correlation_id', () => {
113
+ it('falls back to the span and trace ids when no headers were captured', () => {
114
+ onEnd(requestSpan({ 'http.method': 'GET' }, { traceId: 'trace-123', spanId: 'span-456' }))
115
+
116
+ // A trace id already behaves like a correlation id: W3C trace context reuses an
117
+ // inbound traceparent and mints a new one when there is none.
118
+ expect(events[0].payload).toMatchObject({
119
+ request_id: 'span-456',
120
+ correlation_id: 'trace-123',
121
+ })
122
+ })
123
+
124
+ it('prefers captured headers over the span ids', () => {
125
+ onEnd(requestSpan({
126
+ 'http.method': 'GET',
127
+ 'http.request.header.x-request-id': 'req-from-header',
128
+ 'http.request.header.x-correlation-id': 'corr-from-header',
129
+ }, { traceId: 'trace-123', spanId: 'span-456' }))
130
+
131
+ expect(events[0].payload).toMatchObject({
132
+ request_id: 'req-from-header',
133
+ correlation_id: 'corr-from-header',
134
+ // still emitted, so the event can be joined to a trace
135
+ trace_id: 'trace-123',
136
+ span_id: 'span-456',
137
+ })
138
+ })
139
+
140
+ it('reads the underscored attribute spelling used by older semantic conventions', () => {
141
+ onEnd(requestSpan({
142
+ 'http.method': 'GET',
143
+ 'http.request.header.x_request_id': 'req-underscored',
144
+ }))
145
+
146
+ expect(events[0].payload.request_id).toBe('req-underscored')
147
+ })
148
+
149
+ it('takes the first value when a header was captured as an array', () => {
150
+ onEnd(requestSpan({
151
+ 'http.method': 'GET',
152
+ 'http.request.header.x-request-id': ['req-first', 'req-second'],
153
+ }))
154
+
155
+ expect(events[0].payload.request_id).toBe('req-first')
156
+ })
157
+
158
+ it('ignores blank header values', () => {
159
+ onEnd(requestSpan({
160
+ 'http.method': 'GET',
161
+ 'http.request.header.x-request-id': ' ',
162
+ }, { spanId: 'span-456' }))
163
+
164
+ expect(events[0].payload.request_id).toBe('span-456')
165
+ })
166
+ })
167
+
168
+ it('survives a span with no attributes or context', () => {
169
+ expect(() => onEnd({})).not.toThrow()
170
+ expect(events).toHaveLength(0)
171
+ })
172
+
173
+ describe('HONEYBADGER_HEADER_ATTRIBUTES', () => {
174
+ // The map tells @vercel/otel which headers to copy onto the root span. If it drifts
175
+ // from what the seeder reads, header ids silently stop being reused and everything
176
+ // falls back to the span/trace ids - which still works, so nothing would fail loudly.
177
+ it('every mapped attribute is actually read back as an id', () => {
178
+ const entries = Object.entries(HONEYBADGER_HEADER_ATTRIBUTES)
179
+ expect(entries.length).toBeGreaterThan(0)
180
+
181
+ for (const [attribute, header] of entries) {
182
+ expect(attribute).toBe(`http.request.header.${header}`)
183
+
184
+ events = []
185
+ onEnd(requestSpan({ 'http.method': 'GET', [attribute]: `value-of-${header}` }))
186
+
187
+ const { request_id: requestId, correlation_id: correlationId } = events[0].payload
188
+ expect([requestId, correlationId]).toContain(`value-of-${header}`)
189
+ }
190
+ })
191
+ })
192
+ })
@@ -0,0 +1,225 @@
1
+ import Honeybadger from '@honeybadger-io/js';
2
+ import { insightsHttpEnabled, seedSpanEventContext } from './insights-instrumentation';
3
+ import { scheduleFlush } from './flush';
4
+
5
+ /**
6
+ * Next.js instruments itself with OpenTelemetry and emits one root span per request,
7
+ * `[http.method] [next.route]`, tagged `next.span_type: BaseServer.handleRequest`. Its
8
+ * attributes carry the method, route, target and status, so mapping that span to a
9
+ * `request.handled` event reports every request without wrapping any handler.
10
+ *
11
+ * Next instruments but does not export: spans only reach us once a tracer provider with
12
+ * this processor is registered. See `registerHoneybadgerInsights`.
13
+ */
14
+ const NEXT_REQUEST_SPAN_TYPE = 'BaseServer.handleRequest'
15
+
16
+ /**
17
+ * Request headers to copy onto the root span, so `request_id` and `correlation_id` can be
18
+ * reused from an inbound request instead of falling back to the span and trace ids.
19
+ *
20
+ * Header values are not span attributes by default. `@vercel/otel` applies this map when
21
+ * it creates the root span, which is the span this processor reads — and, unlike Node's
22
+ * HTTP instrumentation, it works on serverless platforms too.
23
+ *
24
+ * Spread it into your own `registerOTel` call if you register OpenTelemetry yourself:
25
+ *
26
+ * ```ts
27
+ * registerOTel({
28
+ * attributesFromHeaders: { ...HONEYBADGER_HEADER_ATTRIBUTES },
29
+ * spanProcessors: [honeybadgerSpanProcessor()],
30
+ * })
31
+ * ```
32
+ *
33
+ * Keep the header names in sync with `seedIds` in ./insights-instrumentation.
34
+ */
35
+ export const HONEYBADGER_HEADER_ATTRIBUTES: Record<string, string> = {
36
+ 'http.request.header.x-request-id': 'x-request-id',
37
+ 'http.request.header.request-id': 'request-id',
38
+ 'http.request.header.x-correlation-id': 'x-correlation-id',
39
+ 'http.request.header.x-amzn-trace-id': 'x-amzn-trace-id',
40
+ }
41
+
42
+ // Minimal structural types, so `@opentelemetry/*` stays an optional peer rather than
43
+ // something every consumer of this package has to install.
44
+ type HrTime = [number, number]
45
+
46
+ type ReadableSpanLike = {
47
+ attributes?: Record<string, unknown>
48
+ duration?: HrTime
49
+ spanContext?: () => { traceId?: string; spanId?: string }
50
+ }
51
+
52
+ export type SpanProcessorLike = {
53
+ onStart(): void
54
+ onEnd(span: ReadableSpanLike): void
55
+ forceFlush(): Promise<void>
56
+ shutdown(): Promise<void>
57
+ }
58
+
59
+ function readString(attributes: Record<string, unknown>, ...names: string[]): string | undefined {
60
+ for (const name of names) {
61
+ const value = attributes[name]
62
+ if (typeof value === 'string' && value.length) {
63
+ return value
64
+ }
65
+ }
66
+ return undefined
67
+ }
68
+
69
+ function readNumber(attributes: Record<string, unknown>, ...names: string[]): number | undefined {
70
+ for (const name of names) {
71
+ const value = attributes[name]
72
+ if (typeof value === 'number') {
73
+ return value
74
+ }
75
+ if (typeof value === 'string' && value.trim().length && Number.isFinite(Number(value))) {
76
+ return Number(value)
77
+ }
78
+ }
79
+ return undefined
80
+ }
81
+
82
+ function durationMs(duration: HrTime | undefined): number {
83
+ if (!Array.isArray(duration) || duration.length !== 2) {
84
+ return 0
85
+ }
86
+ const [seconds, nanos] = duration
87
+ return Math.round(seconds * 1000 + nanos / 1e6)
88
+ }
89
+
90
+ /**
91
+ * Path without the query string. `http.target` includes the query under the older
92
+ * semantic conventions; `url.path` is already bare under the stable ones.
93
+ */
94
+ function readPath(attributes: Record<string, unknown>): string | undefined {
95
+ const target = readString(attributes, 'url.path', 'http.target')
96
+ return typeof target === 'string' ? target.split('?')[0] : undefined
97
+ }
98
+
99
+ /**
100
+ * Maps Next.js's per-request span to a Honeybadger `request.handled` Insights event.
101
+ *
102
+ * Pass it to whatever registers OpenTelemetry in your `instrumentation.ts`:
103
+ *
104
+ * ```ts
105
+ * import { registerOTel } from '@vercel/otel'
106
+ * import { honeybadgerSpanProcessor } from '@honeybadger-io/nextjs'
107
+ *
108
+ * export function register() {
109
+ * registerOTel({ serviceName: 'my-app', spanProcessors: [honeybadgerSpanProcessor()] })
110
+ * }
111
+ * ```
112
+ *
113
+ * `registerHoneybadgerInsights()` is the one-line equivalent when you have no other
114
+ * OpenTelemetry setup of your own.
115
+ */
116
+ export function honeybadgerSpanProcessor(): SpanProcessorLike {
117
+ return {
118
+ onStart() {
119
+ // Nothing to do: the event is emitted once the request span is complete, which is
120
+ // when the status and duration are known.
121
+ },
122
+
123
+ onEnd(span: ReadableSpanLike) {
124
+ const attributes = span.attributes ?? {}
125
+ if (attributes['next.span_type'] !== NEXT_REQUEST_SPAN_TYPE) {
126
+ return
127
+ }
128
+
129
+ // Checked per event rather than at registration: configuration is loaded by
130
+ // `register()` importing the honeybadger config files, which may happen after the
131
+ // processor is constructed.
132
+ if (!insightsHttpEnabled()) {
133
+ return
134
+ }
135
+
136
+ const spanContext = typeof span.spanContext === 'function' ? span.spanContext() : {}
137
+ const ids = seedSpanEventContext(attributes, spanContext ?? {})
138
+
139
+ const payload: Record<string, unknown> = {
140
+ method: readString(attributes, 'http.request.method', 'http.method'),
141
+ duration: durationMs(span.duration),
142
+ ...ids,
143
+ }
144
+
145
+ const path = readPath(attributes)
146
+ if (path) {
147
+ payload.path = path
148
+ }
149
+
150
+ const status = readNumber(attributes, 'http.response.status_code', 'http.status_code')
151
+ if (typeof status === 'number') {
152
+ payload.status = status
153
+ }
154
+
155
+ // Emitted alongside the ids rather than replacing them, so an event can be joined
156
+ // to a trace in another tool without changing what existing consumers read.
157
+ if (spanContext?.traceId) {
158
+ payload.trace_id = spanContext.traceId
159
+ }
160
+ if (spanContext?.spanId) {
161
+ payload.span_id = spanContext.spanId
162
+ }
163
+
164
+ Honeybadger.event('request.handled', payload)
165
+
166
+ // A span processor batches on its own lifecycle, which is not enough on a platform
167
+ // that can freeze the invocation as soon as the response is sent.
168
+ scheduleFlush({ useAfter: true })
169
+ },
170
+
171
+ async forceFlush() {
172
+ await Honeybadger.flushAsync().catch(() => { /* logged by the events worker */ })
173
+ },
174
+
175
+ async shutdown() {
176
+ await Honeybadger.flushAsync().catch(() => { /* logged by the events worker */ })
177
+ },
178
+ }
179
+ }
180
+
181
+ export type RegisterHoneybadgerInsightsOptions = {
182
+ serviceName?: string
183
+ /** Additional attribute-name -> header-name pairs, merged over the defaults. */
184
+ attributesFromHeaders?: Record<string, string>
185
+ }
186
+
187
+ /**
188
+ * Registers OpenTelemetry with only Honeybadger's span processor attached, for apps that
189
+ * have no OpenTelemetry setup of their own. Call it from `register()` in
190
+ * `instrumentation.ts`.
191
+ *
192
+ * `@vercel/otel` is an optional peer dependency: it is only needed for Insights, and it
193
+ * loads where the full Node SDK cannot, such as serverless platforms. If you
194
+ * already call `registerOTel` yourself, add `honeybadgerSpanProcessor()` to your
195
+ * `spanProcessors` instead of calling this — registering twice would compete for the
196
+ * global provider.
197
+ */
198
+ export async function registerHoneybadgerInsights(
199
+ options: RegisterHoneybadgerInsightsOptions = {}
200
+ ): Promise<void> {
201
+ let registerOTel: (config: Record<string, unknown>) => void
202
+
203
+ try {
204
+ ({ registerOTel } = await import('@vercel/otel'))
205
+ }
206
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
207
+ catch (error) {
208
+ Honeybadger.logger.error(
209
+ '[Honeybadger] Insights request events need @vercel/otel. Install it, or drop the ' +
210
+ 'registerHoneybadgerInsights() call — error reporting works without it.'
211
+ )
212
+ return
213
+ }
214
+
215
+ registerOTel({
216
+ serviceName: options.serviceName ?? process.env.NEXT_PUBLIC_HONEYBADGER_SERVICE_NAME ?? 'nextjs-app',
217
+ // Without this the id headers never reach the span, so request_id and
218
+ // correlation_id would always fall back to the span and trace ids.
219
+ attributesFromHeaders: {
220
+ ...HONEYBADGER_HEADER_ATTRIBUTES,
221
+ ...options.attributesFromHeaders,
222
+ },
223
+ spanProcessors: [honeybadgerSpanProcessor()],
224
+ })
225
+ }