@logbrew/next 0.1.9 → 0.1.10

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
@@ -125,8 +125,13 @@ export const onRequestError = createLogBrewNextRequestErrorHandler({
125
125
  Next.js awaits `onRequestError`, and the LogBrew adapter awaits delivery before
126
126
  it returns. A delivery or callback failure is reported through
127
127
  `onCaptureError` but never replaces the application error that Next.js is
128
- already handling. The Edge runtime is left unchanged; use a Node.js route or
129
- server boundary for LogBrew server delivery.
128
+ already handling. In the Edge runtime (middleware and Edge routes), the hook
129
+ sends the same issue with `fetch` and loads no Node.js modules.
130
+
131
+ Server and Edge issues carry the release and environment from
132
+ `LOGBREW_RELEASE` and `LOGBREW_ENVIRONMENT`, or from Vercel's
133
+ `VERCEL_GIT_COMMIT_SHA` and `VERCEL_ENV` when the LogBrew variables are not
134
+ set. `LOGBREW_SERVICE_NAME` sets the service. Explicit `context` fields win.
130
135
 
131
136
  By default, the issue includes the error message, exception type, structured
132
137
  stack frames, Next.js error digest, method, stable route file path, router kind,
@@ -220,6 +225,10 @@ The metric carries the stable description `Duration of one completed server requ
220
225
 
221
226
  The wrapper expects App Router Route Handlers that return standard `Response` objects. It does not call `NextResponse.next()` and does not use the deprecated `middleware` filename. For Next.js 16 request interception, use the framework's `proxy.js` convention separately and keep LogBrew event creation in server-side route code.
222
227
 
228
+ ### Request User
229
+
230
+ Inside `withLogBrewRouteHandler`, call `helpers.setUser(id)` once you know who made the request. The route span and the route error issue of that request carry `context.subject`. Use an opaque app-owned ID, not an email address or name; pass `{ kind: "anonymous" }` for visitors who have not signed in. The ID never reaches another request.
231
+
223
232
  ## Client Route Spans
224
233
 
225
234
  Use the browser-safe `@logbrew/next/client` subpath from client components. It has no `node:` imports and uses `clientKey` wording for browser setup:
@@ -236,7 +245,7 @@ import {
236
245
  const client = createLogBrewNextBrowserClient({
237
246
  clientKey: "LOGBREW_CLIENT_KEY",
238
247
  sdkName: "my-next-app",
239
- sdkVersion: "0.1.9"
248
+ sdkVersion: "0.1.10"
240
249
  });
241
250
 
242
251
  const routePatterns = [
@@ -265,6 +274,42 @@ The client helper requires explicit W3C trace context through `traceparent` or `
265
274
 
266
275
  Use `captureNextNavigation(client, input)` when you want to emit a route span from app-owned navigation callbacks instead of the React hook.
267
276
 
277
+ ## Client Errors
278
+
279
+ `createLogBrewNextBrowserClient()` sends events on its own with `fetch` (5
280
+ seconds after the first queued event, to save battery). Pass a `transport` to
281
+ replace it, or `transport: null` to keep the client manual. Browser events
282
+ carry the release and environment from `NEXT_PUBLIC_LOGBREW_RELEASE` and
283
+ `NEXT_PUBLIC_LOGBREW_ENVIRONMENT`, or from `NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA`
284
+ and `NEXT_PUBLIC_VERCEL_ENV`.
285
+
286
+ Report errors that reach an error boundary from `app/error.tsx` or
287
+ `app/global-error.tsx`:
288
+
289
+ ```jsx
290
+ "use client";
291
+
292
+ import { useEffect } from "react";
293
+ import { captureNextClientError } from "@logbrew/next/client";
294
+ import { logbrew } from "./logbrew-client";
295
+
296
+ export default function Error({ error, reset }) {
297
+ useEffect(() => {
298
+ void captureNextClientError(logbrew, error, { routeTemplate: "/cart/[cartId]" });
299
+ }, [error]);
300
+ return <button onClick={() => reset()}>Try again</button>;
301
+ }
302
+ ```
303
+
304
+ The issue has mechanism `nextjs.error_boundary`, the exception type and
305
+ frames, and the Next.js `digest` when present. Pass a stable route template,
306
+ never a concrete path.
307
+
308
+ Call `installLogBrewNextClientErrorCapture({ client })` once in a client
309
+ component to also report uncaught browser errors (`nextjs.window_error`) and
310
+ unhandled rejections (`nextjs.unhandled_rejection`), and to flush queued events
311
+ when the page is hidden. `uninstall()` removes the listeners.
312
+
268
313
  ## Server Client Helper
269
314
 
270
315
  ```js
@@ -273,7 +318,7 @@ import { createLogBrewNextClient } from "@logbrew/next";
273
318
  const client = createLogBrewNextClient({
274
319
  serverApiKey: "LOGBREW_SERVER_API_KEY",
275
320
  sdkName: "my-next-app",
276
- sdkVersion: "0.1.9"
321
+ sdkVersion: "0.1.10"
277
322
  });
278
323
  ```
279
324
 
package/client.cjs CHANGED
@@ -4,34 +4,155 @@ const React = require("react");
4
4
  const {
5
5
  LogBrewClient,
6
6
  SdkError,
7
+ createIssueAttributesFromError,
7
8
  parseTraceparent
8
9
  } = require("@logbrew/sdk");
9
10
 
11
+ const DEFAULT_ENDPOINT = "https://api.logbrew.co/v1/events";
12
+ // Browsers keep a 5-second interval to save battery and radio; pagehide flushes the rest.
13
+ const DEFAULT_BROWSER_DELIVERY_INTERVAL_MS = 5000;
14
+
10
15
  function createLogBrewNextBrowserClient({
11
16
  apiKey,
12
17
  clientKey,
13
18
  context,
19
+ deliveryIntervalMs = DEFAULT_BROWSER_DELIVERY_INTERVAL_MS,
20
+ endpoint = DEFAULT_ENDPOINT,
14
21
  eventFilter,
15
22
  sdkName = "logbrew-next-client",
16
- sdkVersion = "0.1.9",
23
+ sdkVersion = "0.1.10",
17
24
  maxQueueSize,
18
25
  maxRetries = 2,
19
- onEventDropped
26
+ onEventDropped,
27
+ transport
20
28
  } = {}) {
21
29
  const authKey = clientKey ?? apiKey;
22
30
  if (!authKey) {
23
31
  throw new SdkError("configuration_error", "createLogBrewNextBrowserClient requires clientKey or apiKey");
24
32
  }
33
+ const deploymentContext = withPublicDeployment(context);
25
34
  return LogBrewClient.create({
26
35
  apiKey: authKey,
27
- context,
36
+ context: deploymentContext,
37
+ deliveryIntervalMs,
28
38
  eventFilter,
29
39
  maxQueueSize,
30
40
  maxRetries,
31
41
  onEventDropped,
32
42
  sdkName,
33
- sdkVersion
43
+ sdkVersion,
44
+ // Sends on its own; pass transport: null to keep the client manual.
45
+ ...(transport === null ? {} : { transport: transport ?? createNextBrowserTransport(endpoint) })
46
+ });
47
+ }
48
+
49
+ // Report an error from app/error.tsx or app/global-error.tsx, then deliver it.
50
+ function captureNextClientError(client, error, { digest, routeTemplate, flush = true } = {}) {
51
+ const safeDigest = typeof digest === "string" && /^[a-zA-Z0-9._:-]{1,128}$/u.test(digest)
52
+ ? digest
53
+ : typeof error?.digest === "string" && /^[a-zA-Z0-9._:-]{1,128}$/u.test(error.digest) ? error.digest : undefined;
54
+ const route = normalizeRouteTemplate(routeTemplate);
55
+ client.issue(`evt_next_client_error_${randomHex(8)}`, new Date().toISOString(), createIssueAttributesFromError(error, {
56
+ handled: false,
57
+ mechanism: "nextjs.error_boundary",
58
+ runtime: "browser",
59
+ source: "nextjs.error_boundary",
60
+ metadata: {
61
+ framework: "nextjs",
62
+ ...(safeDigest ? { errorDigest: safeDigest } : {}),
63
+ ...(route ? { routeTemplate: route } : {})
64
+ }
65
+ }));
66
+ return flush && client.transport ? client.flush().catch(() => undefined) : Promise.resolve(undefined);
67
+ }
68
+
69
+ // Report uncaught browser errors and unhandled rejections, and flush queued events on pagehide.
70
+ function installLogBrewNextClientErrorCapture({ client, browserWindow = globalThis.window } = {}) {
71
+ if (!client || !browserWindow || typeof browserWindow.addEventListener !== "function") {
72
+ throw new SdkError("configuration_error", "installLogBrewNextClientErrorCapture requires a client and a browser window");
73
+ }
74
+ const capture = (error, mechanism) => {
75
+ try {
76
+ client.issue(`evt_next_client_error_${randomHex(8)}`, new Date().toISOString(), createIssueAttributesFromError(error, {
77
+ handled: false,
78
+ mechanism,
79
+ runtime: "browser",
80
+ source: mechanism,
81
+ metadata: { framework: "nextjs" }
82
+ }));
83
+ } catch {
84
+ // Capture failures never reach the page.
85
+ }
86
+ };
87
+ const listeners = {
88
+ error: (event) => { capture(event?.error ?? event?.message ?? "Uncaught browser error", "nextjs.window_error"); },
89
+ unhandledrejection: (event) => { capture(event?.reason, "nextjs.unhandled_rejection"); },
90
+ pagehide: () => { void client.flush?.().catch(() => undefined); }
91
+ };
92
+ for (const [type, listener] of Object.entries(listeners)) {
93
+ browserWindow.addEventListener(type, listener);
94
+ }
95
+ return {
96
+ uninstall() {
97
+ for (const [type, listener] of Object.entries(listeners)) {
98
+ browserWindow.removeEventListener?.(type, listener);
99
+ }
100
+ }
101
+ };
102
+ }
103
+
104
+ function createNextBrowserTransport(endpoint) {
105
+ return {
106
+ async send(apiKey, body) {
107
+ const response = await globalThis.fetch(endpoint, {
108
+ body,
109
+ headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}` },
110
+ keepalive: body.length <= 60000,
111
+ method: "POST"
112
+ });
113
+ return { statusCode: response.status, attempts: 1 };
114
+ }
115
+ };
116
+ }
117
+
118
+ // Next.js inlines NEXT_PUBLIC_* values at build time when they appear literally like this.
119
+ function withPublicDeployment(context) {
120
+ let release;
121
+ let environment;
122
+ try {
123
+ release = process.env.NEXT_PUBLIC_LOGBREW_RELEASE || process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA;
124
+ environment = process.env.NEXT_PUBLIC_LOGBREW_ENVIRONMENT || process.env.NEXT_PUBLIC_VERCEL_ENV;
125
+ } catch {
126
+ return context;
127
+ }
128
+ const deployment = {
129
+ ...(boundedValue(environment) ? { environment: boundedValue(environment) } : {}),
130
+ ...(boundedValue(release) ? { release: boundedValue(release) } : {})
131
+ };
132
+ if (Object.keys(deployment).length === 0) {
133
+ return context;
134
+ }
135
+ if (context !== undefined && (context === null || typeof context !== "object" || context.schemaVersion !== 1)) {
136
+ return context;
137
+ }
138
+ const resource = context?.resource ?? {};
139
+ return {
140
+ ...(context ?? { schemaVersion: 1 }),
141
+ resource: { ...resource, deployment: { ...deployment, ...resource.deployment } }
142
+ };
143
+ }
144
+
145
+ function boundedValue(value) {
146
+ if (typeof value !== "string") {
147
+ return undefined;
148
+ }
149
+ const normalized = value.trim();
150
+ const characters = Array.from(normalized);
151
+ const hasControl = characters.some((character) => {
152
+ const code = character.codePointAt(0);
153
+ return code <= 31 || (code >= 127 && code <= 159);
34
154
  });
155
+ return characters.length > 0 && characters.length <= 256 && !hasControl ? normalized : undefined;
35
156
  }
36
157
 
37
158
  function createNextRouteTemplate({
@@ -308,10 +429,12 @@ function randomHex(bytes) {
308
429
  }
309
430
 
310
431
  const api = {
432
+ captureNextClientError,
311
433
  captureNextNavigation,
312
434
  createLogBrewNextBrowserClient,
313
435
  createNextNavigationSpanEvent,
314
436
  createNextRouteTemplate,
437
+ installLogBrewNextClientErrorCapture,
315
438
  useLogBrewNextNavigation
316
439
  };
317
440
 
package/client.d.cts CHANGED
@@ -4,7 +4,9 @@ import type {
4
4
  LogBrewClient,
5
5
  Metadata,
6
6
  SpanAttributes,
7
- TelemetryContext
7
+ TelemetryContext,
8
+ Transport,
9
+ TransportResponse
8
10
  } from "@logbrew/sdk";
9
11
 
10
12
  export type CreateLogBrewNextBrowserClientConfig = {
@@ -17,8 +19,36 @@ export type CreateLogBrewNextBrowserClientConfig = {
17
19
  eventFilter?: EventFilter;
18
20
  maxQueueSize?: number;
19
21
  onEventDropped?: (drop: DroppedEvent) => void;
22
+ /** Delivery interval after the first queued event. Defaults to 5000 ms to save battery. */
23
+ deliveryIntervalMs?: number;
24
+ /** Ingest endpoint for the built-in fetch transport. */
25
+ endpoint?: string;
26
+ /** Custom transport, or null to keep the client manual. Defaults to a fetch transport that sends automatically. */
27
+ transport?: Transport | null;
20
28
  };
21
29
 
30
+ export type NextClientErrorOptions = {
31
+ /** The `digest` Next.js passes to error boundaries; also read from `error.digest`. */
32
+ digest?: string;
33
+ /** Stable route template such as `/projects/[projectId]`, never a concrete path. */
34
+ routeTemplate?: string;
35
+ /** Deliver right away. Defaults to true. */
36
+ flush?: boolean;
37
+ };
38
+
39
+ /** Report an error from `app/error.tsx` or `app/global-error.tsx` as an unhandled issue. */
40
+ export declare function captureNextClientError(
41
+ client: LogBrewClient,
42
+ error: unknown,
43
+ options?: NextClientErrorOptions
44
+ ): Promise<TransportResponse | undefined>;
45
+
46
+ /** Report uncaught browser errors and unhandled rejections, and flush queued events on pagehide. */
47
+ export declare function installLogBrewNextClientErrorCapture(options: {
48
+ client: LogBrewClient;
49
+ browserWindow?: Window;
50
+ }): { uninstall(): void };
51
+
22
52
  export type NextRoutePattern = string;
23
53
 
24
54
  export type NextRouteTemplateInput = {
@@ -87,7 +117,9 @@ export declare function useLogBrewNextNavigation(
87
117
  ): void;
88
118
 
89
119
  declare const defaultExport: {
120
+ captureNextClientError: typeof captureNextClientError;
90
121
  captureNextNavigation: typeof captureNextNavigation;
122
+ installLogBrewNextClientErrorCapture: typeof installLogBrewNextClientErrorCapture;
91
123
  createLogBrewNextBrowserClient: typeof createLogBrewNextBrowserClient;
92
124
  createNextNavigationSpanEvent: typeof createNextNavigationSpanEvent;
93
125
  createNextRouteTemplate: typeof createNextRouteTemplate;
package/client.d.ts CHANGED
@@ -4,7 +4,9 @@ import type {
4
4
  LogBrewClient,
5
5
  Metadata,
6
6
  SpanAttributes,
7
- TelemetryContext
7
+ TelemetryContext,
8
+ Transport,
9
+ TransportResponse
8
10
  } from "@logbrew/sdk";
9
11
 
10
12
  export type CreateLogBrewNextBrowserClientConfig = {
@@ -17,8 +19,36 @@ export type CreateLogBrewNextBrowserClientConfig = {
17
19
  eventFilter?: EventFilter;
18
20
  maxQueueSize?: number;
19
21
  onEventDropped?: (drop: DroppedEvent) => void;
22
+ /** Delivery interval after the first queued event. Defaults to 5000 ms to save battery. */
23
+ deliveryIntervalMs?: number;
24
+ /** Ingest endpoint for the built-in fetch transport. */
25
+ endpoint?: string;
26
+ /** Custom transport, or null to keep the client manual. Defaults to a fetch transport that sends automatically. */
27
+ transport?: Transport | null;
20
28
  };
21
29
 
30
+ export type NextClientErrorOptions = {
31
+ /** The `digest` Next.js passes to error boundaries; also read from `error.digest`. */
32
+ digest?: string;
33
+ /** Stable route template such as `/projects/[projectId]`, never a concrete path. */
34
+ routeTemplate?: string;
35
+ /** Deliver right away. Defaults to true. */
36
+ flush?: boolean;
37
+ };
38
+
39
+ /** Report an error from `app/error.tsx` or `app/global-error.tsx` as an unhandled issue. */
40
+ export declare function captureNextClientError(
41
+ client: LogBrewClient,
42
+ error: unknown,
43
+ options?: NextClientErrorOptions
44
+ ): Promise<TransportResponse | undefined>;
45
+
46
+ /** Report uncaught browser errors and unhandled rejections, and flush queued events on pagehide. */
47
+ export declare function installLogBrewNextClientErrorCapture(options: {
48
+ client: LogBrewClient;
49
+ browserWindow?: Window;
50
+ }): { uninstall(): void };
51
+
22
52
  export type NextRoutePattern = string;
23
53
 
24
54
  export type NextRouteTemplateInput = {
@@ -87,7 +117,9 @@ export declare function useLogBrewNextNavigation(
87
117
  ): void;
88
118
 
89
119
  declare const defaultExport: {
120
+ captureNextClientError: typeof captureNextClientError;
90
121
  captureNextNavigation: typeof captureNextNavigation;
122
+ installLogBrewNextClientErrorCapture: typeof installLogBrewNextClientErrorCapture;
91
123
  createLogBrewNextBrowserClient: typeof createLogBrewNextBrowserClient;
92
124
  createNextNavigationSpanEvent: typeof createNextNavigationSpanEvent;
93
125
  createNextRouteTemplate: typeof createNextRouteTemplate;
package/client.js CHANGED
@@ -4,34 +4,155 @@ import React from "react";
4
4
  import {
5
5
  LogBrewClient,
6
6
  SdkError,
7
+ createIssueAttributesFromError,
7
8
  parseTraceparent
8
9
  } from "@logbrew/sdk";
9
10
 
11
+ const DEFAULT_ENDPOINT = "https://api.logbrew.co/v1/events";
12
+ // Browsers keep a 5-second interval to save battery and radio; pagehide flushes the rest.
13
+ const DEFAULT_BROWSER_DELIVERY_INTERVAL_MS = 5000;
14
+
10
15
  export function createLogBrewNextBrowserClient({
11
16
  apiKey,
12
17
  clientKey,
13
18
  context,
19
+ deliveryIntervalMs = DEFAULT_BROWSER_DELIVERY_INTERVAL_MS,
20
+ endpoint = DEFAULT_ENDPOINT,
14
21
  eventFilter,
15
22
  sdkName = "logbrew-next-client",
16
- sdkVersion = "0.1.9",
23
+ sdkVersion = "0.1.10",
17
24
  maxQueueSize,
18
25
  maxRetries = 2,
19
- onEventDropped
26
+ onEventDropped,
27
+ transport
20
28
  } = {}) {
21
29
  const authKey = clientKey ?? apiKey;
22
30
  if (!authKey) {
23
31
  throw new SdkError("configuration_error", "createLogBrewNextBrowserClient requires clientKey or apiKey");
24
32
  }
33
+ const deploymentContext = withPublicDeployment(context);
25
34
  return LogBrewClient.create({
26
35
  apiKey: authKey,
27
- context,
36
+ context: deploymentContext,
37
+ deliveryIntervalMs,
28
38
  eventFilter,
29
39
  maxQueueSize,
30
40
  maxRetries,
31
41
  onEventDropped,
32
42
  sdkName,
33
- sdkVersion
43
+ sdkVersion,
44
+ // Sends on its own; pass transport: null to keep the client manual.
45
+ ...(transport === null ? {} : { transport: transport ?? createNextBrowserTransport(endpoint) })
46
+ });
47
+ }
48
+
49
+ // Report an error from app/error.tsx or app/global-error.tsx, then deliver it.
50
+ export function captureNextClientError(client, error, { digest, routeTemplate, flush = true } = {}) {
51
+ const safeDigest = typeof digest === "string" && /^[a-zA-Z0-9._:-]{1,128}$/u.test(digest)
52
+ ? digest
53
+ : typeof error?.digest === "string" && /^[a-zA-Z0-9._:-]{1,128}$/u.test(error.digest) ? error.digest : undefined;
54
+ const route = normalizeRouteTemplate(routeTemplate);
55
+ client.issue(`evt_next_client_error_${randomHex(8)}`, new Date().toISOString(), createIssueAttributesFromError(error, {
56
+ handled: false,
57
+ mechanism: "nextjs.error_boundary",
58
+ runtime: "browser",
59
+ source: "nextjs.error_boundary",
60
+ metadata: {
61
+ framework: "nextjs",
62
+ ...(safeDigest ? { errorDigest: safeDigest } : {}),
63
+ ...(route ? { routeTemplate: route } : {})
64
+ }
65
+ }));
66
+ return flush && client.transport ? client.flush().catch(() => undefined) : Promise.resolve(undefined);
67
+ }
68
+
69
+ // Report uncaught browser errors and unhandled rejections, and flush queued events on pagehide.
70
+ export function installLogBrewNextClientErrorCapture({ client, browserWindow = globalThis.window } = {}) {
71
+ if (!client || !browserWindow || typeof browserWindow.addEventListener !== "function") {
72
+ throw new SdkError("configuration_error", "installLogBrewNextClientErrorCapture requires a client and a browser window");
73
+ }
74
+ const capture = (error, mechanism) => {
75
+ try {
76
+ client.issue(`evt_next_client_error_${randomHex(8)}`, new Date().toISOString(), createIssueAttributesFromError(error, {
77
+ handled: false,
78
+ mechanism,
79
+ runtime: "browser",
80
+ source: mechanism,
81
+ metadata: { framework: "nextjs" }
82
+ }));
83
+ } catch {
84
+ // Capture failures never reach the page.
85
+ }
86
+ };
87
+ const listeners = {
88
+ error: (event) => { capture(event?.error ?? event?.message ?? "Uncaught browser error", "nextjs.window_error"); },
89
+ unhandledrejection: (event) => { capture(event?.reason, "nextjs.unhandled_rejection"); },
90
+ pagehide: () => { void client.flush?.().catch(() => undefined); }
91
+ };
92
+ for (const [type, listener] of Object.entries(listeners)) {
93
+ browserWindow.addEventListener(type, listener);
94
+ }
95
+ return {
96
+ uninstall() {
97
+ for (const [type, listener] of Object.entries(listeners)) {
98
+ browserWindow.removeEventListener?.(type, listener);
99
+ }
100
+ }
101
+ };
102
+ }
103
+
104
+ function createNextBrowserTransport(endpoint) {
105
+ return {
106
+ async send(apiKey, body) {
107
+ const response = await globalThis.fetch(endpoint, {
108
+ body,
109
+ headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}` },
110
+ keepalive: body.length <= 60000,
111
+ method: "POST"
112
+ });
113
+ return { statusCode: response.status, attempts: 1 };
114
+ }
115
+ };
116
+ }
117
+
118
+ // Next.js inlines NEXT_PUBLIC_* values at build time when they appear literally like this.
119
+ function withPublicDeployment(context) {
120
+ let release;
121
+ let environment;
122
+ try {
123
+ release = process.env.NEXT_PUBLIC_LOGBREW_RELEASE || process.env.NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA;
124
+ environment = process.env.NEXT_PUBLIC_LOGBREW_ENVIRONMENT || process.env.NEXT_PUBLIC_VERCEL_ENV;
125
+ } catch {
126
+ return context;
127
+ }
128
+ const deployment = {
129
+ ...(boundedValue(environment) ? { environment: boundedValue(environment) } : {}),
130
+ ...(boundedValue(release) ? { release: boundedValue(release) } : {})
131
+ };
132
+ if (Object.keys(deployment).length === 0) {
133
+ return context;
134
+ }
135
+ if (context !== undefined && (context === null || typeof context !== "object" || context.schemaVersion !== 1)) {
136
+ return context;
137
+ }
138
+ const resource = context?.resource ?? {};
139
+ return {
140
+ ...(context ?? { schemaVersion: 1 }),
141
+ resource: { ...resource, deployment: { ...deployment, ...resource.deployment } }
142
+ };
143
+ }
144
+
145
+ function boundedValue(value) {
146
+ if (typeof value !== "string") {
147
+ return undefined;
148
+ }
149
+ const normalized = value.trim();
150
+ const characters = Array.from(normalized);
151
+ const hasControl = characters.some((character) => {
152
+ const code = character.codePointAt(0);
153
+ return code <= 31 || (code >= 127 && code <= 159);
34
154
  });
155
+ return characters.length > 0 && characters.length <= 256 && !hasControl ? normalized : undefined;
35
156
  }
36
157
 
37
158
  export function createNextRouteTemplate({
@@ -308,10 +429,12 @@ function randomHex(bytes) {
308
429
  }
309
430
 
310
431
  const defaultExport = {
432
+ captureNextClientError,
311
433
  captureNextNavigation,
312
434
  createLogBrewNextBrowserClient,
313
435
  createNextNavigationSpanEvent,
314
436
  createNextRouteTemplate,
437
+ installLogBrewNextClientErrorCapture,
315
438
  useLogBrewNextNavigation
316
439
  };
317
440
 
package/edge.cjs ADDED
@@ -0,0 +1,55 @@
1
+ "use strict";
2
+
3
+ // Edge runtime request-error capture: Web APIs only, no Node.js imports.
4
+ const { LogBrewClient, SdkError } = require("@logbrew/sdk");
5
+ const {
6
+ createNextRequestErrorEvent,
7
+ nextDeploymentContext,
8
+ readEnvApiKey,
9
+ readEnvServerApiKey
10
+ } = require("./request-error-event.cjs");
11
+
12
+ const DEFAULT_ENDPOINT = "https://api.logbrew.co/v1/events";
13
+
14
+ function createLogBrewNextEdgeRequestErrorHandler(options = {}) {
15
+ return async function logBrewNextEdgeRequestErrorHandler(error, request = {}, context = {}) {
16
+ const authKey = options.serverApiKey ?? options.apiKey ?? readEnvServerApiKey() ?? readEnvApiKey();
17
+ if (!authKey) {
18
+ throw new SdkError(
19
+ "configuration_error",
20
+ "Edge request-error capture requires serverApiKey, apiKey, LOGBREW_SERVER_API_KEY, or LOGBREW_API_KEY"
21
+ );
22
+ }
23
+ const deploymentContext = nextDeploymentContext(options.context);
24
+ const client = LogBrewClient.create({
25
+ apiKey: authKey,
26
+ context: deploymentContext,
27
+ sdkName: options.sdkName ?? "logbrew-next",
28
+ sdkVersion: options.sdkVersion ?? "0.1.10",
29
+ maxRetries: options.maxRetries ?? 2
30
+ });
31
+ const event = typeof options.errorEvent === "function"
32
+ ? options.errorEvent(error, { error, request, context, client })
33
+ : createNextRequestErrorEvent(error, request, context, options);
34
+ client.issue(event.id, event.timestamp, event.attributes);
35
+ const response = await client.shutdown(options.transport ?? createEdgeFetchTransport(options));
36
+ if (typeof options.onFlush === "function") {
37
+ await options.onFlush(response, { error, request, context, client });
38
+ }
39
+ };
40
+ }
41
+
42
+ function createEdgeFetchTransport({ endpoint = DEFAULT_ENDPOINT, headers = {}, fetchImpl = globalThis.fetch } = {}) {
43
+ return {
44
+ async send(apiKey, body) {
45
+ const response = await fetchImpl(endpoint, {
46
+ body,
47
+ headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}`, ...headers },
48
+ method: "POST"
49
+ });
50
+ return { statusCode: response.status, attempts: 1 };
51
+ }
52
+ };
53
+ }
54
+
55
+ module.exports = { createLogBrewNextEdgeRequestErrorHandler };
package/edge.js ADDED
@@ -0,0 +1,5 @@
1
+ import edge from "./edge.cjs";
2
+
3
+ export const { createLogBrewNextEdgeRequestErrorHandler } = edge;
4
+
5
+ export default edge;
@@ -24,7 +24,7 @@ const event = captureNextNavigation(client, {
24
24
  });
25
25
 
26
26
  const payload = JSON.parse(client.previewJson());
27
- if (!event || event.attributes.metadata.routeTemplate !== "/projects/[projectId]/settings" || event.attributes.metadata.operation !== "browser.navigation" || payload.sdk.version !== "0.1.9") {
27
+ if (!event || event.attributes.metadata.routeTemplate !== "/projects/[projectId]/settings" || event.attributes.metadata.operation !== "browser.navigation" || payload.sdk.version !== "0.1.10") {
28
28
  throw new Error(`unexpected Next client route span: ${JSON.stringify(event)}`);
29
29
  }
30
30
 
@@ -12,7 +12,7 @@ const POST = withLogBrewRouteHandler(
12
12
  serverApiKey: "LOGBREW_SERVER_API_KEY",
13
13
  captureRequests: false,
14
14
  sdkName: "logbrew-next-readme-example",
15
- sdkVersion: "0.1.9",
15
+ sdkVersion: "0.1.10",
16
16
  transport
17
17
  }
18
18
  );
@@ -12,7 +12,7 @@ const POST = withLogBrewRouteHandler(
12
12
  serverApiKey: "LOGBREW_SERVER_API_KEY",
13
13
  captureRequests: false,
14
14
  sdkName: "logbrew-next-real-user-smoke",
15
- sdkVersion: "0.1.9",
15
+ sdkVersion: "0.1.10",
16
16
  maxRetries: 1,
17
17
  transport
18
18
  }
package/index.cjs CHANGED
@@ -6,18 +6,16 @@ const {
6
6
  parseTraceparent
7
7
  } = require("@logbrew/sdk");
8
8
  const { createNodeFetchTransport } = require("@logbrew/node");
9
+ const {
10
+ createNextRequestErrorEvent,
11
+ getTraceparentHeader,
12
+ nextDeploymentContext,
13
+ nextRoutePath,
14
+ randomHex,
15
+ readEnvApiKey,
16
+ readEnvServerApiKey
17
+ } = require("./request-error-event.cjs");
9
18
 
10
- const MAX_REQUEST_ERROR_MESSAGE_LENGTH = 2048;
11
- const MAX_REQUEST_ROUTE_PATH_LENGTH = 512;
12
- const NEXT_RENDER_SOURCES = new Set([
13
- "react-server-components",
14
- "react-server-components-payload",
15
- "server-rendering"
16
- ]);
17
- const NEXT_RENDER_TYPES = new Set(["dynamic", "dynamic-resume"]);
18
- const NEXT_REVALIDATE_REASONS = new Set(["on-demand", "stale"]);
19
- const NEXT_ROUTE_TYPES = new Set(["action", "middleware", "proxy", "render", "route"]);
20
- const NEXT_ROUTER_KINDS = new Set(["App Router", "Pages Router"]);
21
19
  const activeTraceContext = new AsyncLocalStorage();
22
20
 
23
21
  function createLogBrewNextClient({
@@ -25,7 +23,7 @@ function createLogBrewNextClient({
25
23
  serverApiKey,
26
24
  context,
27
25
  sdkName = "logbrew-next",
28
- sdkVersion = "0.1.9",
26
+ sdkVersion = "0.1.10",
29
27
  maxRetries = 2
30
28
  } = {}) {
31
29
  const authKey = serverApiKey ?? apiKey ?? readEnvServerApiKey() ?? readEnvApiKey();
@@ -35,7 +33,8 @@ function createLogBrewNextClient({
35
33
  "createLogBrewNextClient requires serverApiKey, apiKey, LOGBREW_SERVER_API_KEY, or LOGBREW_API_KEY"
36
34
  );
37
35
  }
38
- return LogBrewClient.create({ apiKey: authKey, context, sdkName, sdkVersion, maxRetries });
36
+ const deploymentContext = nextDeploymentContext(context);
37
+ return LogBrewClient.create({ apiKey: authKey, context: deploymentContext, sdkName, sdkVersion, maxRetries });
39
38
  }
40
39
 
41
40
  function createLogBrewNextRequestErrorHandler(options = {}) {
@@ -72,43 +71,6 @@ function createLogBrewNextRequestErrorHandler(options = {}) {
72
71
  };
73
72
  }
74
73
 
75
- function createNextRequestErrorEvent(error, request = {}, context = {}, {
76
- includeErrorStack = false,
77
- includePathname = false,
78
- now = () => new Date().toISOString(),
79
- idFactory = defaultNextRequestErrorId
80
- } = {}) {
81
- const method = nextRequestMethod(request);
82
- const routePath = nextRoutePath(context?.routePath);
83
- const pathname = includePathname ? nextRoutePath(request?.path) : undefined;
84
- const errorDigest = nextErrorDigest(error);
85
- return {
86
- id: idFactory(error, request, context),
87
- timestamp: now(),
88
- attributes: createIssueAttributesFromError(error, {
89
- title: `${method} ${routePath} failed`,
90
- message: nextErrorMessage(error),
91
- mechanism: "nextjs.on_request_error",
92
- handled: false,
93
- source: "nextjs.on_request_error",
94
- includeErrorStack,
95
- metadata: {
96
- framework: "nextjs",
97
- method,
98
- routePath,
99
- ...nextCategoricalMetadata("routerKind", context?.routerKind, NEXT_ROUTER_KINDS),
100
- ...nextCategoricalMetadata("routeType", context?.routeType, NEXT_ROUTE_TYPES),
101
- ...nextCategoricalMetadata("renderSource", context?.renderSource, NEXT_RENDER_SOURCES),
102
- ...nextCategoricalMetadata("revalidateReason", context?.revalidateReason, NEXT_REVALIDATE_REASONS),
103
- ...nextCategoricalMetadata("renderType", context?.renderType, NEXT_RENDER_TYPES),
104
- ...nextRequestTraceMetadata(request),
105
- ...(errorDigest ? { errorDigest } : {}),
106
- ...(pathname ? { pathname } : {})
107
- }
108
- })
109
- };
110
- }
111
-
112
74
  function withLogBrewRouteHandler(handler, options = {}) {
113
75
  if (typeof handler !== "function") {
114
76
  throw new SdkError("configuration_error", "withLogBrewRouteHandler requires a handler function");
@@ -122,7 +84,7 @@ function withLogBrewRouteHandler(handler, options = {}) {
122
84
  const { client, owned } = resolveClient(options, request, context);
123
85
  const transport = resolveTransport(options, { request, context, client }, defaultTransport);
124
86
  const trace = createRouteTraceContext(request, undefined, options);
125
- const helpers = createRouteHelpers(client, transport, trace);
87
+ const helpers = createRouteHelpers(client, transport, trace, request);
126
88
  const startedAt = nowMs(options);
127
89
 
128
90
  return activeTraceContext.run(trace, async () => {
@@ -279,10 +241,43 @@ function resolveRequestErrorClient(options, runtime) {
279
241
  return { client: createLogBrewNextClient(options), owned: true };
280
242
  }
281
243
 
282
- function createRouteHelpers(client, transport, trace) {
244
+ // Users belong to one route request, so one request's user never reaches another request.
245
+ const routeSubjects = new WeakMap();
246
+ const MAX_USER_ID_LENGTH = 200;
247
+
248
+ function setRouteUser(request, id, { kind = "user" } = {}) {
249
+ const normalized = typeof id === "string" ? id.trim() : "";
250
+ const characters = Array.from(normalized);
251
+ if (characters.length === 0 || characters.length > MAX_USER_ID_LENGTH || characters.some((character) => {
252
+ const code = character.codePointAt(0);
253
+ return code <= 31 || (code >= 127 && code <= 159);
254
+ })) {
255
+ throw new SdkError("configuration_error", `LogBrew user id must be 1-${MAX_USER_ID_LENGTH} characters without control characters`);
256
+ }
257
+ if (kind !== "user" && kind !== "anonymous") {
258
+ throw new SdkError("configuration_error", "LogBrew user kind must be user or anonymous");
259
+ }
260
+ if (!request || typeof request !== "object") {
261
+ return false;
262
+ }
263
+ routeSubjects.set(request, { id: normalized, kind });
264
+ return true;
265
+ }
266
+
267
+ function withRouteSubject(attributes, request) {
268
+ const subject = request && typeof request === "object" ? routeSubjects.get(request) : undefined;
269
+ if (!subject || attributes?.context?.subject) {
270
+ return attributes;
271
+ }
272
+ return { ...attributes, context: { ...(attributes.context ?? { schemaVersion: 1 }), subject } };
273
+ }
274
+
275
+ function createRouteHelpers(client, transport, trace, request) {
283
276
  return {
284
277
  client,
285
278
  logbrew: client,
279
+ // Tags this request's route span and route error issue with an opaque app-owned user ID.
280
+ setUser: (id, options) => setRouteUser(request, id, options),
286
281
  trace,
287
282
  previewJson: () => client.previewJson(),
288
283
  flush: () => client.flush(transport),
@@ -351,7 +346,7 @@ function recordRouteRequest(options, { request, response, context, client, durat
351
346
  routeTemplate: resolveRouteTemplate(options, request, context),
352
347
  trace
353
348
  });
354
- captureRouteRequestEvent(client, event);
349
+ captureRouteRequestEvent(client, { ...event, attributes: withRouteSubject(event.attributes, request) });
355
350
  }
356
351
 
357
352
  function recordRouteMetric(options, { request, response, context, client, durationMs, trace }) {
@@ -379,7 +374,7 @@ async function recordRouteError(options, error, runtime) {
379
374
  routeTemplate: resolveRouteTemplate(options, request, context),
380
375
  trace: routeTrace
381
376
  });
382
- client.issue(event.id, event.timestamp, event.attributes);
377
+ client.issue(event.id, event.timestamp, withRouteSubject(event.attributes, request));
383
378
  }
384
379
  } catch (captureError) {
385
380
  await notifyFailure(options, captureError, { request, context, client, trace: routeTrace });
@@ -411,10 +406,6 @@ function defaultRouteErrorId() {
411
406
  return `evt_next_error_${randomHex(8)}`;
412
407
  }
413
408
 
414
- function defaultNextRequestErrorId() {
415
- return `evt_next_request_error_${randomHex(8)}`;
416
- }
417
-
418
409
  function defaultRouteMetricId() {
419
410
  return `evt_next_metric_${randomHex(8)}`;
420
411
  }
@@ -427,87 +418,6 @@ function safeUrl(request) {
427
418
  }
428
419
  }
429
420
 
430
- function nextRequestMethod(request) {
431
- const method = typeof request?.method === "string" ? request.method.trim().toUpperCase() : "";
432
- return /^[A-Z]{1,16}$/u.test(method) ? method : "UNKNOWN";
433
- }
434
-
435
- function nextRoutePath(value) {
436
- if (typeof value !== "string" || value.trim() === "") {
437
- return "/";
438
- }
439
- let pathname;
440
- try {
441
- pathname = new URL(value, "http://localhost").pathname;
442
- } catch {
443
- return "/";
444
- }
445
- if (typeof pathname !== "string" || pathname === "") {
446
- return "/";
447
- }
448
- const normalized = pathname.startsWith("/") ? pathname : `/${pathname}`;
449
- return normalized.length <= MAX_REQUEST_ROUTE_PATH_LENGTH ? normalized : "/";
450
- }
451
-
452
- function nextCategoricalMetadata(key, value, allowed) {
453
- return typeof value === "string" && allowed.has(value) ? { [key]: value } : {};
454
- }
455
-
456
- function nextErrorDigest(error) {
457
- const digest = error && typeof error === "object" ? error.digest : undefined;
458
- if (typeof digest !== "string" || !/^[a-zA-Z0-9._:-]{1,128}$/u.test(digest)) {
459
- return undefined;
460
- }
461
- return digest;
462
- }
463
-
464
- function nextErrorMessage(error) {
465
- let message;
466
- try {
467
- message = error instanceof Error ? error.message : String(error);
468
- } catch {
469
- message = "Next.js request failed";
470
- }
471
- const normalized = typeof message === "string" && message.trim() !== ""
472
- ? message
473
- : "Next.js request failed";
474
- return normalized.length <= MAX_REQUEST_ERROR_MESSAGE_LENGTH
475
- ? normalized
476
- : `${normalized.slice(0, MAX_REQUEST_ERROR_MESSAGE_LENGTH - 1)}…`;
477
- }
478
-
479
- function nextRequestTraceMetadata(request) {
480
- try {
481
- const traceparent = getTraceparentHeader(request);
482
- if (!traceparent) {
483
- return {};
484
- }
485
- const trace = parseTraceparent(traceparent);
486
- return {
487
- traceId: trace.traceId,
488
- parentSpanId: trace.parentSpanId,
489
- sampled: trace.sampled
490
- };
491
- } catch {
492
- return {};
493
- }
494
- }
495
-
496
- function getTraceparentHeader(request) {
497
- const headers = request?.headers;
498
- if (!headers) {
499
- return undefined;
500
- }
501
- let value;
502
- if (typeof headers.get === "function") {
503
- value = headers.get("traceparent");
504
- } else {
505
- const names = Object.keys(headers).filter(name => name.toLowerCase() === "traceparent");
506
- value = names.length === 1 ? headers[names[0]] : undefined;
507
- }
508
- return typeof value === "string" ? value : undefined;
509
- }
510
-
511
421
  function resolveRouteTemplate(options, request, context) {
512
422
  const value = typeof options.routeTemplate === "function"
513
423
  ? options.routeTemplate(request, context)
@@ -620,27 +530,6 @@ function nowMs(options) {
620
530
  return performance.now();
621
531
  }
622
532
 
623
- function randomHex(byteLength) {
624
- const bytes = new Uint8Array(byteLength);
625
- if (globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") {
626
- globalThis.crypto.getRandomValues(bytes);
627
- } else {
628
- for (let index = 0; index < bytes.length; index += 1) {
629
- bytes[index] = Math.floor(Math.random() * 256);
630
- }
631
- }
632
- const value = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
633
- return /^0+$/.test(value) ? "0000000000000001" : value;
634
- }
635
-
636
- function readEnvApiKey() {
637
- return globalThis.process?.env?.LOGBREW_API_KEY;
638
- }
639
-
640
- function readEnvServerApiKey() {
641
- return globalThis.process?.env?.LOGBREW_SERVER_API_KEY;
642
- }
643
-
644
533
  module.exports = {
645
534
  createLogBrewNextClient,
646
535
  createLogBrewNextRequestErrorHandler,
package/index.d.cts CHANGED
@@ -106,6 +106,8 @@ export type LogBrewTraceContext = {
106
106
  };
107
107
 
108
108
  export type LogBrewRouteHelpers = {
109
+ /** Tag this request's route span and route error issue with an opaque app-owned user ID. */
110
+ setUser(id: string, options?: { kind?: "user" | "anonymous" }): boolean;
109
111
  client: LogBrewClient;
110
112
  logbrew: LogBrewClient;
111
113
  trace?: LogBrewTraceContext;
package/index.d.ts CHANGED
@@ -106,6 +106,8 @@ export type LogBrewTraceContext = {
106
106
  };
107
107
 
108
108
  export type LogBrewRouteHelpers = {
109
+ /** Tag this request's route span and route error issue with an opaque app-owned user ID. */
110
+ setUser(id: string, options?: { kind?: "user" | "anonymous" }): boolean;
109
111
  client: LogBrewClient;
110
112
  logbrew: LogBrewClient;
111
113
  trace?: LogBrewTraceContext;
@@ -1,10 +1,18 @@
1
1
  let nodeHandlerPromise;
2
+ let edgeHandlerPromise;
2
3
 
3
4
  function createLogBrewNextRequestErrorHandler(options = {}) {
4
5
  let handler;
6
+ let edgeHandler;
5
7
  return async function logBrewNextRequestErrorHandler(error, request, context) {
6
8
  try {
7
- if (process.env.NEXT_RUNTIME !== "edge") {
9
+ if (process.env.NEXT_RUNTIME === "edge") {
10
+ // The Edge runtime has no Node.js modules; this path sends with fetch only.
11
+ edgeHandlerPromise ??= Promise.resolve().then(() => require("./edge.cjs"));
12
+ const edgeModule = await edgeHandlerPromise;
13
+ edgeHandler ??= edgeModule.createLogBrewNextEdgeRequestErrorHandler(options);
14
+ await edgeHandler(error, request, context);
15
+ } else {
8
16
  nodeHandlerPromise ??= Promise.resolve().then(() => require("./index.cjs"));
9
17
  const nodeModule = await nodeHandlerPromise;
10
18
  handler ??= nodeModule.createLogBrewNextRequestErrorHandler(options);
@@ -1,10 +1,18 @@
1
1
  let nodeHandlerPromise;
2
+ let edgeHandlerPromise;
2
3
 
3
4
  export function createLogBrewNextRequestErrorHandler(options = {}) {
4
5
  let handler;
6
+ let edgeHandler;
5
7
  return async function logBrewNextRequestErrorHandler(error, request, context) {
6
8
  try {
7
- if (process.env.NEXT_RUNTIME !== "edge") {
9
+ if (process.env.NEXT_RUNTIME === "edge") {
10
+ // The Edge runtime has no Node.js modules; this path sends with fetch only.
11
+ edgeHandlerPromise ??= import("./edge.js");
12
+ const edgeModule = await edgeHandlerPromise;
13
+ edgeHandler ??= edgeModule.createLogBrewNextEdgeRequestErrorHandler(options);
14
+ await edgeHandler(error, request, context);
15
+ } else {
8
16
  nodeHandlerPromise ??= import("./index.js");
9
17
  const module = await nodeHandlerPromise;
10
18
  handler ??= module.createLogBrewNextRequestErrorHandler(options);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logbrew/next",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "description": "Next.js App Router helpers for the public LogBrew JavaScript SDK.",
5
5
  "type": "module",
6
6
  "main": "./index.cjs",
@@ -57,6 +57,9 @@
57
57
  "index.d.ts",
58
58
  "index.d.cts",
59
59
  "client.cjs",
60
+ "edge.cjs",
61
+ "edge.js",
62
+ "request-error-event.cjs",
60
63
  "client.js",
61
64
  "client.d.ts",
62
65
  "client.d.cts",
@@ -97,6 +100,6 @@
97
100
  "react-dom": ">=18"
98
101
  },
99
102
  "scripts": {
100
- "test": "node --check index.js && node --check index.cjs && node --check client.js && node --check client.cjs && node --check instrumentation.js && node --check instrumentation.cjs && node --check release-artifacts.js && node --check release-artifacts.cjs && node --check examples/index.mjs && node --check examples/client-route-spans.mjs && node --check examples/readme-example.mjs && node --check examples/request-errors.mjs && node --check examples/real-user-smoke.mjs && node --test"
103
+ "test": "node --check index.js && node --check index.cjs && node --check client.js && node --check client.cjs && node --check instrumentation.js && node --check instrumentation.cjs && node --check edge.js && node --check edge.cjs && node --check request-error-event.cjs && node --check release-artifacts.js && node --check release-artifacts.cjs && node --check examples/index.mjs && node --check examples/client-route-spans.mjs && node --check examples/readme-example.mjs && node --check examples/request-errors.mjs && node --check examples/real-user-smoke.mjs && node --test"
101
104
  }
102
105
  }
@@ -0,0 +1,216 @@
1
+ "use strict";
2
+
3
+ // Request-error event building and deployment detection without Node-only imports, so the Edge runtime can use them.
4
+ const { createIssueAttributesFromError, parseTraceparent } = require("@logbrew/sdk");
5
+
6
+ const MAX_REQUEST_ERROR_MESSAGE_LENGTH = 2048;
7
+ const MAX_REQUEST_ROUTE_PATH_LENGTH = 512;
8
+ const NEXT_RENDER_SOURCES = new Set([
9
+ "react-server-components",
10
+ "react-server-components-payload",
11
+ "server-rendering"
12
+ ]);
13
+ const NEXT_RENDER_TYPES = new Set(["dynamic", "dynamic-resume"]);
14
+ const NEXT_REVALIDATE_REASONS = new Set(["on-demand", "stale"]);
15
+ const NEXT_ROUTE_TYPES = new Set(["action", "middleware", "proxy", "render", "route"]);
16
+ const NEXT_ROUTER_KINDS = new Set(["App Router", "Pages Router"]);
17
+
18
+ function createNextRequestErrorEvent(error, request = {}, context = {}, {
19
+ includeErrorStack = false,
20
+ includePathname = false,
21
+ now = () => new Date().toISOString(),
22
+ idFactory = defaultNextRequestErrorId
23
+ } = {}) {
24
+ const method = nextRequestMethod(request);
25
+ const routePath = nextRoutePath(context?.routePath);
26
+ const pathname = includePathname ? nextRoutePath(request?.path) : undefined;
27
+ const errorDigest = nextErrorDigest(error);
28
+ return {
29
+ id: idFactory(error, request, context),
30
+ timestamp: now(),
31
+ attributes: createIssueAttributesFromError(error, {
32
+ title: `${method} ${routePath} failed`,
33
+ message: nextErrorMessage(error),
34
+ mechanism: "nextjs.on_request_error",
35
+ handled: false,
36
+ source: "nextjs.on_request_error",
37
+ includeErrorStack,
38
+ metadata: {
39
+ framework: "nextjs",
40
+ method,
41
+ routePath,
42
+ ...nextCategoricalMetadata("routerKind", context?.routerKind, NEXT_ROUTER_KINDS),
43
+ ...nextCategoricalMetadata("routeType", context?.routeType, NEXT_ROUTE_TYPES),
44
+ ...nextCategoricalMetadata("renderSource", context?.renderSource, NEXT_RENDER_SOURCES),
45
+ ...nextCategoricalMetadata("revalidateReason", context?.revalidateReason, NEXT_REVALIDATE_REASONS),
46
+ ...nextCategoricalMetadata("renderType", context?.renderType, NEXT_RENDER_TYPES),
47
+ ...nextRequestTraceMetadata(request),
48
+ ...(errorDigest ? { errorDigest } : {}),
49
+ ...(pathname ? { pathname } : {})
50
+ }
51
+ })
52
+ };
53
+ }
54
+
55
+ function defaultNextRequestErrorId() {
56
+ return `evt_next_request_error_${randomHex(8)}`;
57
+ }
58
+
59
+ function nextRequestMethod(request) {
60
+ const method = typeof request?.method === "string" ? request.method.trim().toUpperCase() : "";
61
+ return /^[A-Z]{1,16}$/u.test(method) ? method : "UNKNOWN";
62
+ }
63
+
64
+ function nextRoutePath(value) {
65
+ if (typeof value !== "string" || value.trim() === "") {
66
+ return "/";
67
+ }
68
+ let pathname;
69
+ try {
70
+ pathname = new URL(value, "http://localhost").pathname;
71
+ } catch {
72
+ return "/";
73
+ }
74
+ if (typeof pathname !== "string" || pathname === "") {
75
+ return "/";
76
+ }
77
+ const normalized = pathname.startsWith("/") ? pathname : `/${pathname}`;
78
+ return normalized.length <= MAX_REQUEST_ROUTE_PATH_LENGTH ? normalized : "/";
79
+ }
80
+
81
+ function nextCategoricalMetadata(key, value, allowed) {
82
+ return typeof value === "string" && allowed.has(value) ? { [key]: value } : {};
83
+ }
84
+
85
+ function nextErrorDigest(error) {
86
+ const digest = error && typeof error === "object" ? error.digest : undefined;
87
+ if (typeof digest !== "string" || !/^[a-zA-Z0-9._:-]{1,128}$/u.test(digest)) {
88
+ return undefined;
89
+ }
90
+ return digest;
91
+ }
92
+
93
+ function nextErrorMessage(error) {
94
+ let message;
95
+ try {
96
+ message = error instanceof Error ? error.message : String(error);
97
+ } catch {
98
+ message = "Next.js request failed";
99
+ }
100
+ const normalized = typeof message === "string" && message.trim() !== ""
101
+ ? message
102
+ : "Next.js request failed";
103
+ return normalized.length <= MAX_REQUEST_ERROR_MESSAGE_LENGTH
104
+ ? normalized
105
+ : `${normalized.slice(0, MAX_REQUEST_ERROR_MESSAGE_LENGTH - 1)}…`;
106
+ }
107
+
108
+ function nextRequestTraceMetadata(request) {
109
+ try {
110
+ const traceparent = getTraceparentHeader(request);
111
+ if (!traceparent) {
112
+ return {};
113
+ }
114
+ const trace = parseTraceparent(traceparent);
115
+ return {
116
+ traceId: trace.traceId,
117
+ parentSpanId: trace.parentSpanId,
118
+ sampled: trace.sampled
119
+ };
120
+ } catch {
121
+ return {};
122
+ }
123
+ }
124
+
125
+ function getTraceparentHeader(request) {
126
+ const headers = request?.headers;
127
+ if (!headers) {
128
+ return undefined;
129
+ }
130
+ let value;
131
+ if (typeof headers.get === "function") {
132
+ value = headers.get("traceparent");
133
+ } else {
134
+ const names = Object.keys(headers).filter(name => name.toLowerCase() === "traceparent");
135
+ value = names.length === 1 ? headers[names[0]] : undefined;
136
+ }
137
+ return typeof value === "string" ? value : undefined;
138
+ }
139
+
140
+ function randomHex(byteLength) {
141
+ const bytes = new Uint8Array(byteLength);
142
+ if (globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") {
143
+ globalThis.crypto.getRandomValues(bytes);
144
+ } else {
145
+ for (let index = 0; index < bytes.length; index += 1) {
146
+ bytes[index] = Math.floor(Math.random() * 256);
147
+ }
148
+ }
149
+ const value = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
150
+ return /^0+$/.test(value) ? "0000000000000001" : value;
151
+ }
152
+
153
+ function readEnvApiKey() {
154
+ return globalThis.process?.env?.LOGBREW_API_KEY;
155
+ }
156
+
157
+ function readEnvServerApiKey() {
158
+ return globalThis.process?.env?.LOGBREW_SERVER_API_KEY;
159
+ }
160
+
161
+ // Release, environment, and service from LOGBREW_* variables, then Vercel's system variables.
162
+ function nextDeploymentContext(context, env = globalThis.process?.env ?? {}) {
163
+ const release = boundedEnv(env.LOGBREW_RELEASE) ?? boundedEnv(env.VERCEL_GIT_COMMIT_SHA);
164
+ const environment = boundedEnv(env.LOGBREW_ENVIRONMENT) ?? boundedEnv(env.VERCEL_ENV);
165
+ const service = boundedEnv(env.LOGBREW_SERVICE_NAME);
166
+ return mergeDeployment(context, { release, environment, service });
167
+ }
168
+
169
+ function mergeDeployment(context, { release, environment, service }) {
170
+ if (release === undefined && environment === undefined && service === undefined) {
171
+ return context;
172
+ }
173
+ if (context !== undefined && (context === null || typeof context !== "object" || context.schemaVersion !== 1)) {
174
+ return context;
175
+ }
176
+ const resource = context?.resource ?? {};
177
+ const deployment = {
178
+ ...(environment === undefined ? {} : { environment }),
179
+ ...(release === undefined ? {} : { release }),
180
+ ...resource.deployment
181
+ };
182
+ return {
183
+ ...(context ?? { schemaVersion: 1 }),
184
+ resource: {
185
+ ...resource,
186
+ ...(Object.keys(deployment).length === 0 ? {} : { deployment }),
187
+ ...(service === undefined || resource.service ? {} : { service: { name: service } })
188
+ }
189
+ };
190
+ }
191
+
192
+ function boundedEnv(value) {
193
+ if (typeof value !== "string") {
194
+ return undefined;
195
+ }
196
+ const normalized = value.trim();
197
+ const characters = Array.from(normalized);
198
+ if (characters.length === 0 || characters.length > 256 || characters.some((character) => {
199
+ const code = character.codePointAt(0);
200
+ return code <= 31 || (code >= 127 && code <= 159);
201
+ })) {
202
+ return undefined;
203
+ }
204
+ return normalized;
205
+ }
206
+
207
+ module.exports = {
208
+ createNextRequestErrorEvent,
209
+ getTraceparentHeader,
210
+ mergeDeployment,
211
+ nextDeploymentContext,
212
+ nextRoutePath,
213
+ randomHex,
214
+ readEnvApiKey,
215
+ readEnvServerApiKey
216
+ };