@logbrew/next 0.1.6 → 0.1.8

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
@@ -232,7 +232,7 @@ import {
232
232
  const client = createLogBrewNextBrowserClient({
233
233
  clientKey: "LOGBREW_CLIENT_KEY",
234
234
  sdkName: "my-next-app",
235
- sdkVersion: "0.1.6"
235
+ sdkVersion: "0.1.8"
236
236
  });
237
237
 
238
238
  const routePatterns = [
@@ -269,7 +269,7 @@ import { createLogBrewNextClient } from "@logbrew/next";
269
269
  const client = createLogBrewNextClient({
270
270
  serverApiKey: "LOGBREW_SERVER_API_KEY",
271
271
  sdkName: "my-next-app",
272
- sdkVersion: "0.1.6"
272
+ sdkVersion: "0.1.8"
273
273
  });
274
274
  ```
275
275
 
package/client.cjs CHANGED
@@ -7,16 +7,13 @@ const {
7
7
  parseTraceparent
8
8
  } = require("@logbrew/sdk");
9
9
 
10
- const DEFAULT_SDK_NAME = "logbrew-next-client";
11
- const DEFAULT_SDK_VERSION = "0.1.6";
12
-
13
10
  function createLogBrewNextBrowserClient({
14
11
  apiKey,
15
12
  clientKey,
16
13
  context,
17
14
  eventFilter,
18
- sdkName = DEFAULT_SDK_NAME,
19
- sdkVersion = DEFAULT_SDK_VERSION,
15
+ sdkName = "logbrew-next-client",
16
+ sdkVersion = "0.1.8",
20
17
  maxQueueSize,
21
18
  maxRetries = 2,
22
19
  onEventDropped
package/client.js CHANGED
@@ -7,16 +7,13 @@ import {
7
7
  parseTraceparent
8
8
  } from "@logbrew/sdk";
9
9
 
10
- const DEFAULT_SDK_NAME = "logbrew-next-client";
11
- const DEFAULT_SDK_VERSION = "0.1.6";
12
-
13
10
  export function createLogBrewNextBrowserClient({
14
11
  apiKey,
15
12
  clientKey,
16
13
  context,
17
14
  eventFilter,
18
- sdkName = DEFAULT_SDK_NAME,
19
- sdkVersion = DEFAULT_SDK_VERSION,
15
+ sdkName = "logbrew-next-client",
16
+ sdkVersion = "0.1.8",
20
17
  maxQueueSize,
21
18
  maxRetries = 2,
22
19
  onEventDropped
@@ -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.6") {
27
+ if (!event || event.attributes.metadata.routeTemplate !== "/projects/[projectId]/settings" || event.attributes.metadata.operation !== "browser.navigation" || payload.sdk.version !== "0.1.8") {
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.6",
15
+ sdkVersion: "0.1.8",
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.6",
15
+ sdkVersion: "0.1.8",
16
16
  maxRetries: 1,
17
17
  transport
18
18
  }
package/index.cjs CHANGED
@@ -6,8 +6,6 @@ const {
6
6
  } = require("@logbrew/sdk");
7
7
  const { createNodeFetchTransport } = require("@logbrew/node");
8
8
 
9
- const DEFAULT_SDK_NAME = "logbrew-next";
10
- const DEFAULT_SDK_VERSION = "0.1.6";
11
9
  const MAX_REQUEST_ERROR_MESSAGE_LENGTH = 2048;
12
10
  const MAX_REQUEST_ROUTE_PATH_LENGTH = 512;
13
11
  const NEXT_RENDER_SOURCES = new Set([
@@ -25,8 +23,8 @@ function createLogBrewNextClient({
25
23
  apiKey,
26
24
  serverApiKey,
27
25
  context,
28
- sdkName = DEFAULT_SDK_NAME,
29
- sdkVersion = DEFAULT_SDK_VERSION,
26
+ sdkName = "logbrew-next",
27
+ sdkVersion = "0.1.8",
30
28
  maxRetries = 2
31
29
  } = {}) {
32
30
  const authKey = serverApiKey ?? apiKey ?? readEnvServerApiKey() ?? readEnvApiKey();
@@ -51,11 +49,14 @@ function createLogBrewNextRequestErrorHandler(options = {}) {
51
49
  const client = resolvedClient.client;
52
50
  const transport = resolveTransport(options, { ...runtime, client }, defaultTransport);
53
51
  runtime = { ...runtime, client, transport };
54
- const event = typeof options.errorEvent === "function"
55
- ? options.errorEvent(error, runtime)
56
- : createNextRequestErrorEvent(error, request, context, options);
57
-
58
- client.issue(event.id, event.timestamp, event.attributes);
52
+ try {
53
+ const event = typeof options.errorEvent === "function"
54
+ ? options.errorEvent(error, runtime)
55
+ : createNextRequestErrorEvent(error, request, context, options);
56
+ client.issue(event.id, event.timestamp, event.attributes);
57
+ } catch (captureError) {
58
+ await notifyFailure(options, captureError, runtime);
59
+ }
59
60
  const response = resolvedClient.owned
60
61
  ? await client.shutdown(transport)
61
62
  : await client.flush(transport);
@@ -95,6 +96,7 @@ function createNextRequestErrorEvent(error, request = {}, context = {}, {
95
96
  ...nextCategoricalMetadata("renderSource", context?.renderSource, NEXT_RENDER_SOURCES),
96
97
  ...nextCategoricalMetadata("revalidateReason", context?.revalidateReason, NEXT_REVALIDATE_REASONS),
97
98
  ...nextCategoricalMetadata("renderType", context?.renderType, NEXT_RENDER_TYPES),
99
+ ...nextRequestTraceMetadata(request),
98
100
  ...(errorDigest ? { errorDigest } : {}),
99
101
  ...(pathname ? { pathname } : {})
100
102
  }
@@ -112,7 +114,7 @@ function withLogBrewRouteHandler(handler, options = {}) {
112
114
  : undefined;
113
115
 
114
116
  return async function logBrewRouteHandler(request, context = {}) {
115
- const client = resolveClient(options, request, context);
117
+ const { client, owned } = resolveClient(options, request, context);
116
118
  const transport = resolveTransport(options, { request, context, client }, defaultTransport);
117
119
  const trace = createRouteTraceContext(request, undefined, options);
118
120
  const helpers = createRouteHelpers(client, transport, trace);
@@ -122,10 +124,10 @@ function withLogBrewRouteHandler(handler, options = {}) {
122
124
  try {
123
125
  const response = await handler(request, context, helpers);
124
126
  ensureResponse(response);
125
- await captureRouteSuccess(options, { request, response, context, client, transport, startedAt, trace });
127
+ await captureRouteSuccess(options, { request, response, context, client, owned, transport, startedAt, trace });
126
128
  return response;
127
129
  } catch (error) {
128
- await recordRouteError(options, error, { request, context, client, transport, trace });
130
+ await recordRouteError(options, error, { request, context, client, owned, transport, trace });
129
131
  throw error;
130
132
  }
131
133
  });
@@ -144,7 +146,7 @@ function createRouteRequestEvent(request, response, {
144
146
  spanIdFactory = defaultSpanIdFactory,
145
147
  trace
146
148
  } = {}) {
147
- const routePath = routeTemplateOnly(routeTemplate ?? safeUrl(request).pathname);
149
+ const routePath = routeTemplateOnly(routeTemplate);
148
150
  const method = request?.method ?? "GET";
149
151
  const statusCode = Number(response?.status ?? 0);
150
152
  const id = idFactory(request, response, routePath);
@@ -189,7 +191,7 @@ function createRouteErrorEvent(error, request, {
189
191
  trace
190
192
  } = {}) {
191
193
  const url = safeUrl(request);
192
- const routePath = routeTemplateOnly(routeTemplate ?? url.pathname);
194
+ const routePath = routeTemplateOnly(routeTemplate);
193
195
  const method = request?.method ?? "GET";
194
196
  const message = error instanceof Error ? error.message : String(error);
195
197
  const routeTrace = trace ?? getActiveLogBrewTrace();
@@ -220,7 +222,7 @@ function createRequestMetricEvent(request, response, {
220
222
  routeTemplate
221
223
  } = {}) {
222
224
  const method = request?.method ?? "GET";
223
- const resolvedRouteTemplate = routeTemplateOnly(routeTemplate ?? safeUrl(request).pathname);
225
+ const resolvedRouteTemplate = routeTemplateOnly(routeTemplate);
224
226
  const statusCode = Number(response?.status ?? 0);
225
227
  return {
226
228
  id: idFactory(request, response, resolvedRouteTemplate),
@@ -245,12 +247,12 @@ function createRequestMetricEvent(request, response, {
245
247
 
246
248
  function resolveClient(options, request, context) {
247
249
  if (typeof options.client === "function") {
248
- return options.client({ request, context });
250
+ return { client: options.client({ request, context }), owned: true };
249
251
  }
250
252
  if (options.client) {
251
- return options.client;
253
+ return { client: options.client, owned: false };
252
254
  }
253
- return createLogBrewNextClient(options);
255
+ return { client: createLogBrewNextClient(options), owned: true };
254
256
  }
255
257
 
256
258
  function resolveTransport(options, runtime, defaultTransport) {
@@ -295,11 +297,16 @@ async function notifyFlush(options, flushResponse, context) {
295
297
 
296
298
  async function notifyFailure(options, error, context) {
297
299
  if (typeof options.onCaptureError === "function") {
298
- await options.onCaptureError(error, context);
300
+ try {
301
+ await options.onCaptureError(error, context);
302
+ } catch {
303
+ // A capture callback must not change the application's response or error.
304
+ }
299
305
  }
300
306
  }
301
307
 
302
- async function captureRouteSuccess(options, { request, response, context, client, transport, startedAt, trace }) {
308
+ async function captureRouteSuccess(options, runtime) {
309
+ const { request, response, context, client, startedAt, trace } = runtime;
303
310
  try {
304
311
  const durationMs = (options.captureRequests !== false || options.captureRequestMetrics === true)
305
312
  ? routeDurationMs(options, startedAt)
@@ -310,7 +317,17 @@ async function captureRouteSuccess(options, { request, response, context, client
310
317
  if (options.captureRequestMetrics === true) {
311
318
  recordRouteMetric(options, { request, response, context, client, durationMs, trace });
312
319
  }
313
- const flushResponse = await client.shutdown(transport);
320
+ } catch (error) {
321
+ await notifyFailure(options, error, { request, context, client, trace });
322
+ }
323
+ await finalizeRouteCapture(options, runtime);
324
+ }
325
+
326
+ async function finalizeRouteCapture(options, { request, context, client, owned, transport, trace }) {
327
+ try {
328
+ const flushResponse = owned
329
+ ? await client.shutdown(transport)
330
+ : await client.flush(transport);
314
331
  await notifyFlush(options, flushResponse, { request, context, client, trace });
315
332
  } catch (error) {
316
333
  await notifyFailure(options, error, { request, context, client, trace });
@@ -343,25 +360,24 @@ function recordRouteMetric(options, { request, response, context, client, durati
343
360
  captureRouteMetricEvent(client, event);
344
361
  }
345
362
 
346
- async function recordRouteError(options, error, { request, context, client, transport, trace }) {
347
- if (options.captureErrors === false) {
348
- return;
349
- }
363
+ async function recordRouteError(options, error, runtime) {
364
+ const { request, context, client, trace } = runtime;
350
365
  const routeTrace = trace ?? getActiveLogBrewTrace();
351
- const event = typeof options.errorEvent === "function"
352
- ? options.errorEvent(error, { request, context, client, trace: routeTrace })
353
- : createRouteErrorEvent(error, request, {
354
- ...options,
355
- routeTemplate: resolveRouteTemplate(options, request, context),
356
- trace: routeTrace
357
- });
358
366
  try {
359
- client.issue(event.id, event.timestamp, event.attributes);
360
- const flushResponse = await client.shutdown(transport);
361
- await notifyFlush(options, flushResponse, { request, context, client, trace: routeTrace });
367
+ if (options.captureErrors !== false) {
368
+ const event = typeof options.errorEvent === "function"
369
+ ? options.errorEvent(error, { request, context, client, trace: routeTrace })
370
+ : createRouteErrorEvent(error, request, {
371
+ ...options,
372
+ routeTemplate: resolveRouteTemplate(options, request, context),
373
+ trace: routeTrace
374
+ });
375
+ client.issue(event.id, event.timestamp, event.attributes);
376
+ }
362
377
  } catch (captureError) {
363
378
  await notifyFailure(options, captureError, { request, context, client, trace: routeTrace });
364
379
  }
380
+ await finalizeRouteCapture(options, { ...runtime, trace: routeTrace });
365
381
  }
366
382
 
367
383
  function captureRouteRequestEvent(client, event) {
@@ -417,7 +433,7 @@ function nextRoutePath(value) {
417
433
  try {
418
434
  pathname = new URL(value, "http://localhost").pathname;
419
435
  } catch {
420
- pathname = value.split(/[?#]/u)[0];
436
+ return "/";
421
437
  }
422
438
  if (typeof pathname !== "string" || pathname === "") {
423
439
  return "/";
@@ -453,11 +469,35 @@ function nextErrorMessage(error) {
453
469
  : `${normalized.slice(0, MAX_REQUEST_ERROR_MESSAGE_LENGTH - 1)}…`;
454
470
  }
455
471
 
472
+ function nextRequestTraceMetadata(request) {
473
+ try {
474
+ const traceparent = getTraceparentHeader(request);
475
+ if (!traceparent) {
476
+ return {};
477
+ }
478
+ const trace = parseTraceparent(traceparent);
479
+ return {
480
+ traceId: trace.traceId,
481
+ parentSpanId: trace.parentSpanId,
482
+ sampled: trace.sampled
483
+ };
484
+ } catch {
485
+ return {};
486
+ }
487
+ }
488
+
456
489
  function getTraceparentHeader(request) {
457
- if (!request?.headers || typeof request.headers.get !== "function") {
490
+ const headers = request?.headers;
491
+ if (!headers) {
458
492
  return undefined;
459
493
  }
460
- const value = request.headers.get("traceparent");
494
+ let value;
495
+ if (typeof headers.get === "function") {
496
+ value = headers.get("traceparent");
497
+ } else {
498
+ const names = Object.keys(headers).filter(name => name.toLowerCase() === "traceparent");
499
+ value = names.length === 1 ? headers[names[0]] : undefined;
500
+ }
461
501
  return typeof value === "string" ? value : undefined;
462
502
  }
463
503
 
@@ -465,18 +505,11 @@ function resolveRouteTemplate(options, request, context) {
465
505
  const value = typeof options.routeTemplate === "function"
466
506
  ? options.routeTemplate(request, context)
467
507
  : options.routeTemplate;
468
- return routeTemplateOnly(value ?? safeUrl(request).pathname);
508
+ return routeTemplateOnly(value);
469
509
  }
470
510
 
471
511
  function routeTemplateOnly(value) {
472
- if (typeof value !== "string" || value.trim() === "") {
473
- return "/";
474
- }
475
- try {
476
- return new URL(value, "http://localhost").pathname || "/";
477
- } catch {
478
- return value.split(/[?#]/)[0] || "/";
479
- }
512
+ return nextRoutePath(value);
480
513
  }
481
514
 
482
515
  function statusCodeClass(statusCode) {
package/index.d.cts CHANGED
@@ -170,6 +170,7 @@ export type LogBrewRouteMetricEvent = {
170
170
  };
171
171
 
172
172
  export type LogBrewRouteOptions<TContext = LogBrewRouteContext> = CreateLogBrewNextClientConfig & NodeFetchTransportConfig & {
173
+ /** A fixed client stays caller-owned and is flushed, not shut down. A factory must return a fresh client per request. */
173
174
  client?: LogBrewClient | LogBrewClientFactory<TContext>;
174
175
  /** Override the default Node fetch transport, optionally per request. */
175
176
  transport?: Transport | LogBrewTransportFactory<TContext>;
@@ -178,6 +179,7 @@ export type LogBrewRouteOptions<TContext = LogBrewRouteContext> = CreateLogBrewN
178
179
  captureErrors?: boolean;
179
180
  includeSearchParams?: boolean;
180
181
  metricName?: string;
182
+ /** Supply a stable route template. Missing or invalid templates use "/" without reading the request pathname. */
181
183
  routeTemplate?: string | ((request: Request, context: TContext) => string | null | undefined);
182
184
  now?: () => string;
183
185
  nowMs?: () => number;
package/index.d.ts CHANGED
@@ -170,6 +170,7 @@ export type LogBrewRouteMetricEvent = {
170
170
  };
171
171
 
172
172
  export type LogBrewRouteOptions<TContext = LogBrewRouteContext> = CreateLogBrewNextClientConfig & NodeFetchTransportConfig & {
173
+ /** A fixed client stays caller-owned and is flushed, not shut down. A factory must return a fresh client per request. */
173
174
  client?: LogBrewClient | LogBrewClientFactory<TContext>;
174
175
  /** Override the default Node fetch transport, optionally per request. */
175
176
  transport?: Transport | LogBrewTransportFactory<TContext>;
@@ -178,6 +179,7 @@ export type LogBrewRouteOptions<TContext = LogBrewRouteContext> = CreateLogBrewN
178
179
  captureErrors?: boolean;
179
180
  includeSearchParams?: boolean;
180
181
  metricName?: string;
182
+ /** Supply a stable route template. Missing or invalid templates use "/" without reading the request pathname. */
181
183
  routeTemplate?: string | ((request: Request, context: TContext) => string | null | undefined);
182
184
  now?: () => string;
183
185
  nowMs?: () => number;
@@ -3,15 +3,13 @@ let nodeHandlerPromise;
3
3
  function createLogBrewNextRequestErrorHandler(options = {}) {
4
4
  let handler;
5
5
  return async function logBrewNextRequestErrorHandler(error, request, context) {
6
- if (globalThis.process?.env?.NEXT_RUNTIME === "edge") {
7
- return;
8
- }
9
-
10
6
  try {
11
- nodeHandlerPromise ??= Promise.resolve().then(() => require("./index.cjs"));
12
- const module = await nodeHandlerPromise;
13
- handler ??= module.createLogBrewNextRequestErrorHandler(options);
14
- await handler(error, request, context);
7
+ if (process.env.NEXT_RUNTIME !== "edge") {
8
+ nodeHandlerPromise ??= Promise.resolve().then(() => require("./index.cjs"));
9
+ const nodeModule = await nodeHandlerPromise;
10
+ handler ??= nodeModule.createLogBrewNextRequestErrorHandler(options);
11
+ await handler(error, request, context);
12
+ }
15
13
  } catch (captureError) {
16
14
  if (typeof options.onCaptureError === "function") {
17
15
  try {
@@ -3,15 +3,13 @@ let nodeHandlerPromise;
3
3
  export function createLogBrewNextRequestErrorHandler(options = {}) {
4
4
  let handler;
5
5
  return async function logBrewNextRequestErrorHandler(error, request, context) {
6
- if (globalThis.process?.env?.NEXT_RUNTIME === "edge") {
7
- return;
8
- }
9
-
10
6
  try {
11
- nodeHandlerPromise ??= import("./index.js");
12
- const module = await nodeHandlerPromise;
13
- handler ??= module.createLogBrewNextRequestErrorHandler(options);
14
- await handler(error, request, context);
7
+ if (process.env.NEXT_RUNTIME !== "edge") {
8
+ nodeHandlerPromise ??= import("./index.js");
9
+ const module = await nodeHandlerPromise;
10
+ handler ??= module.createLogBrewNextRequestErrorHandler(options);
11
+ await handler(error, request, context);
12
+ }
15
13
  } catch (captureError) {
16
14
  if (typeof options.onCaptureError === "function") {
17
15
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logbrew/next",
3
- "version": "0.1.6",
3
+ "version": "0.1.8",
4
4
  "description": "Next.js App Router helpers for the public LogBrew JavaScript SDK.",
5
5
  "type": "module",
6
6
  "main": "./index.cjs",