@logbrew/next 0.1.0 → 0.1.2
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 +190 -27
- package/client.cjs +340 -0
- package/client.d.cts +95 -0
- package/client.d.ts +95 -0
- package/client.js +339 -0
- package/examples/client-route-spans.mjs +38 -0
- package/examples/index.mjs +4 -0
- package/examples/package.json +1 -0
- package/examples/readme-example.mjs +1 -1
- package/examples/real-user-smoke.mjs +1 -1
- package/index.cjs +218 -64
- package/index.d.cts +53 -3
- package/index.d.ts +53 -3
- package/index.js +218 -64
- package/package.json +34 -3
- package/release-artifacts.cjs +199 -0
- package/release-artifacts.d.cts +35 -0
- package/release-artifacts.d.ts +35 -0
- package/release-artifacts.js +6 -0
package/README.md
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
# @logbrew/next
|
|
2
2
|
|
|
3
|
+
<p align="center">
|
|
4
|
+
<img src="https://raw.githubusercontent.com/LogBrewCo/sdk/main/assets/brand/logbrew-logo-transparent-512.png" alt="LogBrew logo" width="96" height="96">
|
|
5
|
+
</p>
|
|
6
|
+
|
|
3
7
|
Next.js App Router helpers for the public LogBrew JavaScript SDK.
|
|
4
8
|
|
|
5
9
|
This package is intentionally thin. It creates server-side LogBrew clients, wraps App Router Route Handlers, captures successful route requests and thrown route errors, and still keeps manual event creation available through the route helpers.
|
|
@@ -7,46 +11,219 @@ This package is intentionally thin. It creates server-side LogBrew clients, wrap
|
|
|
7
11
|
## Install
|
|
8
12
|
|
|
9
13
|
```bash
|
|
10
|
-
npm install @logbrew/sdk @logbrew/next next react react-dom
|
|
11
|
-
pnpm add @logbrew/sdk @logbrew/next next react react-dom
|
|
14
|
+
npm install @logbrew/sdk @logbrew/node @logbrew/next next react react-dom
|
|
15
|
+
pnpm add @logbrew/sdk @logbrew/node @logbrew/next next react react-dom
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Set `LOGBREW_SERVER_API_KEY` to a project-scoped server ingest key before starting
|
|
19
|
+
the app.
|
|
20
|
+
|
|
21
|
+
If you are automating setup, follow the same safe path as a person.
|
|
22
|
+
Do not ask a person to paste an ingest key.
|
|
23
|
+
Do not treat a missing environment variable as a reason to stop setup.
|
|
24
|
+
First run `logbrew status --json`. When it reports approved authentication,
|
|
25
|
+
create a temporary project and key with the commands below.
|
|
26
|
+
Continue without a browser handoff. Confirm authenticated readback, and then
|
|
27
|
+
archive the project.
|
|
28
|
+
Only stop for account authentication when the status command reports that no
|
|
29
|
+
approved authentication is available.
|
|
30
|
+
|
|
31
|
+
## Create a Project and Confirm Hosted Delivery
|
|
32
|
+
|
|
33
|
+
Use LogBrew CLI 0.1.32 or newer with approved account authentication to create
|
|
34
|
+
the project. This requires no dashboard sign-in. The destination key file must
|
|
35
|
+
not already exist. The CLI creates it with owner-only permissions and never
|
|
36
|
+
prints the one-time key or its file path.
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
logbrew status --json
|
|
40
|
+
install -d -m 700 "$HOME/.logbrew"
|
|
41
|
+
|
|
42
|
+
project_result="$(
|
|
43
|
+
logbrew projects create next-service \
|
|
44
|
+
--runtime node \
|
|
45
|
+
--environment development \
|
|
46
|
+
--ingest-key-file "$HOME/.logbrew/next-service.ingest" \
|
|
47
|
+
--json
|
|
48
|
+
)"
|
|
49
|
+
export LOGBREW_PROJECT_ID="$(jq -er '.project.id' <<<"$project_result")"
|
|
50
|
+
unset project_result
|
|
51
|
+
export LOGBREW_SERVER_API_KEY="$(< "$HOME/.logbrew/next-service.ingest")"
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Start the app after wrapping the Route Handler below, then request one safe
|
|
55
|
+
route that your app already owns. For example:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
curl --fail --request POST http://127.0.0.1:3000/api/logbrew
|
|
59
|
+
|
|
60
|
+
logbrew doctor --project "$LOGBREW_PROJECT_ID" --json
|
|
61
|
+
logbrew read logs --project "$LOGBREW_PROJECT_ID" \
|
|
62
|
+
--search "POST /api/logbrew" \
|
|
63
|
+
--since 1h \
|
|
64
|
+
--json
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
A successful ingest response proves submission. The authenticated read proves
|
|
68
|
+
that the event is indexed for the same project. If you no longer need the
|
|
69
|
+
temporary project, archive it and remove its revoked one-time key file:
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
unset LOGBREW_SERVER_API_KEY
|
|
73
|
+
logbrew projects archive "$LOGBREW_PROJECT_ID" --yes --json
|
|
74
|
+
rm -f "$HOME/.logbrew/next-service.ingest"
|
|
75
|
+
unset LOGBREW_PROJECT_ID
|
|
12
76
|
```
|
|
13
77
|
|
|
78
|
+
## Release Artifacts
|
|
79
|
+
|
|
80
|
+
For production Next.js builds, wrap `next.config.mjs` with the build-time release-artifact helper. It enables `productionBrowserSourceMaps` only when your config has not chosen a value, runs after the production compile, injects matching Debug IDs, strips embedded source text by default, writes a privacy-bounded manifest next to `.next`, and can upload the prepared artifacts before the build completes:
|
|
81
|
+
|
|
82
|
+
```js
|
|
83
|
+
// next.config.mjs
|
|
84
|
+
import { withLogBrewNextReleaseArtifacts } from "@logbrew/next/release-artifacts";
|
|
85
|
+
|
|
86
|
+
export default withLogBrewNextReleaseArtifacts(
|
|
87
|
+
{
|
|
88
|
+
turbopack: {}
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
release: "2026.06.18",
|
|
92
|
+
environment: "production",
|
|
93
|
+
service: "checkout-next-web",
|
|
94
|
+
projectId: "550e8400-e29b-41d4-a716-446655440000",
|
|
95
|
+
upload: {
|
|
96
|
+
endpoint: "https://api.logbrew.com/api/release-artifacts",
|
|
97
|
+
allowHostedUpload: true,
|
|
98
|
+
maxRetries: 2
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
);
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
The helper defaults minified URLs to `app:///_next/static/chunks/...`. Use `minifiedPathPrefix`, `manifestPath`, `repositoryUrl`, `commitSha`, or `stripSourcePrefix` when your deploy needs explicit paths or source-link metadata. Set `LOGBREW_RELEASE_ARTIFACT_TOKEN` in the build environment to a dedicated release-artifact token. Use `tokenEnv` for a different CI variable, or `dryRun: true` to prepare the complete build output without a network request. Existing `compiler.runAfterProductionCompile` work runs first. Upload is disabled when `upload` is omitted, and any unsafe preparation or upload result fails the production build without exposing response text or secret values.
|
|
105
|
+
|
|
14
106
|
## App Router Route Handler
|
|
15
107
|
|
|
16
108
|
```js
|
|
17
109
|
// app/api/logbrew/route.js
|
|
18
|
-
import {
|
|
19
|
-
import { withLogBrewRouteHandler } from "@logbrew/next";
|
|
110
|
+
import { getActiveLogBrewTrace, withLogBrewRouteHandler } from "@logbrew/next";
|
|
20
111
|
|
|
21
112
|
export const runtime = "nodejs";
|
|
22
113
|
|
|
23
114
|
export const POST = withLogBrewRouteHandler(
|
|
24
|
-
async (_request, _context, { client }) => {
|
|
115
|
+
async (_request, _context, { client, trace }) => {
|
|
116
|
+
const activeTrace = trace ?? getActiveLogBrewTrace();
|
|
117
|
+
|
|
25
118
|
client.log("evt_log_001", "2026-06-02T10:00:03Z", {
|
|
26
119
|
message: "worker started",
|
|
27
120
|
level: "info",
|
|
28
|
-
logger: "job-runner"
|
|
121
|
+
logger: "job-runner",
|
|
122
|
+
...(activeTrace
|
|
123
|
+
? { metadata: { traceId: activeTrace.traceId, spanId: activeTrace.spanId } }
|
|
124
|
+
: {})
|
|
29
125
|
});
|
|
30
126
|
|
|
31
127
|
return Response.json(JSON.parse(client.previewJson()));
|
|
32
128
|
},
|
|
33
129
|
{
|
|
34
|
-
serverApiKey:
|
|
130
|
+
serverApiKey: process.env.LOGBREW_SERVER_API_KEY,
|
|
35
131
|
spanIdFactory: () => "b7ad6b7169203331",
|
|
36
|
-
|
|
132
|
+
onCaptureError(error) {
|
|
133
|
+
console.error("LogBrew route capture failed", error);
|
|
134
|
+
}
|
|
37
135
|
}
|
|
38
136
|
);
|
|
39
137
|
```
|
|
40
138
|
|
|
139
|
+
With no `transport` option, the wrapper sends to the LogBrew ingest API by default
|
|
140
|
+
through `@logbrew/node`. You can pass `endpoint`, `fetchImpl`, or `headers` to
|
|
141
|
+
configure that fetch transport, or pass an explicit LogBrew `Transport`.
|
|
142
|
+
Delivery failures call `onCaptureError`; they are never converted into a
|
|
143
|
+
simulated successful response.
|
|
144
|
+
|
|
41
145
|
Use `serverApiKey` directly for local server examples, or set `LOGBREW_SERVER_API_KEY` in your server environment and omit it. `apiKey` and `LOGBREW_API_KEY` are still accepted for compatibility with lower-level SDK examples, but Next.js Route Handlers should use server-side keys only. Use the Browser, React, Vue, Svelte, Angular, or React Native packages for frontend `clientKey` setup.
|
|
42
146
|
|
|
43
|
-
|
|
147
|
+
`RecordingTransport` remains available from `@logbrew/sdk` when you want to
|
|
148
|
+
inspect serialized server events locally. It does not send data to LogBrew;
|
|
149
|
+
use the default Node fetch transport for production telemetry:
|
|
150
|
+
|
|
151
|
+
```js
|
|
152
|
+
import { RecordingTransport } from "@logbrew/sdk";
|
|
153
|
+
|
|
154
|
+
const previewTransport = RecordingTransport.alwaysAccept();
|
|
155
|
+
export const POST = withLogBrewRouteHandler(handler, {
|
|
156
|
+
serverApiKey: "local-preview-key",
|
|
157
|
+
transport: previewTransport
|
|
158
|
+
});
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
By default, successful Route Handler responses are captured after your handler returns. When the incoming `Request` has a valid W3C `traceparent` header, the wrapper exposes a normalized trace object through `helpers.trace` and `getActiveLogBrewTrace()`, then records the request as a LogBrew `span` that continues the incoming trace. Use that same `traceId` and `spanId` in app-owned logs, product actions, or custom event callbacks when you want route-level debugging correlation. Requests without `traceparent`, or with a malformed header, fall back to a request `log` event so bad client headers do not break your route. Use `captureRequests: false` when a route should only flush manual events, use `spanIdFactory` when your runtime needs app-provided child span IDs, and use `onCaptureError` to observe telemetry delivery failures without letting observability own the route response.
|
|
162
|
+
|
|
163
|
+
The public trace helper only includes normalized W3C IDs plus sampled state: `traceId`, `spanId`, `parentSpanId`, and `sampled`. It does not expose the raw `traceparent` header, request headers, request bodies, cookies, or query strings.
|
|
44
164
|
|
|
45
165
|
Automatic route error events record the method and pathname, but omit query strings by default. Pass `includeSearchParams: true` only when query capture is intentional and safe for the route.
|
|
46
166
|
|
|
167
|
+
Request metrics are opt-in. Enable `captureRequestMetrics` when you want the route wrapper to emit an explicit `http.server.duration` histogram for completed App Router requests:
|
|
168
|
+
|
|
169
|
+
```js
|
|
170
|
+
export const GET = withLogBrewRouteHandler(handler, {
|
|
171
|
+
serverApiKey: process.env.LOGBREW_SERVER_API_KEY,
|
|
172
|
+
captureRequestMetrics: true,
|
|
173
|
+
routeTemplate: "/api/orders/[id]"
|
|
174
|
+
});
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
The metric includes primitive, low-cardinality metadata: `framework`, `method`, `routeTemplate`, `statusCode`, and `statusCodeClass`. Next.js Route Handlers expose standard `Request` and `Response` objects, so pass a stable `routeTemplate` when a route contains dynamic segments. Query strings and hashes are omitted. Avoid user IDs, request payloads, headers, or free-form text in custom metric metadata. Use `metricName`, `metricIdFactory`, or `requestMetricEvent` when your app needs a different naming or metadata policy. Set `captureRequests: false` with `captureRequestMetrics: true` when you only want the duration metric and not the request log/span.
|
|
178
|
+
|
|
47
179
|
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.
|
|
48
180
|
|
|
49
|
-
## Client
|
|
181
|
+
## Client Route Spans
|
|
182
|
+
|
|
183
|
+
Use the browser-safe `@logbrew/next/client` subpath from client components. It has no `node:` imports and uses `clientKey` wording for browser setup:
|
|
184
|
+
|
|
185
|
+
```jsx
|
|
186
|
+
"use client";
|
|
187
|
+
|
|
188
|
+
import { usePathname } from "next/navigation";
|
|
189
|
+
import {
|
|
190
|
+
createLogBrewNextBrowserClient,
|
|
191
|
+
useLogBrewNextNavigation
|
|
192
|
+
} from "@logbrew/next/client";
|
|
193
|
+
|
|
194
|
+
const client = createLogBrewNextBrowserClient({
|
|
195
|
+
clientKey: "LOGBREW_CLIENT_KEY",
|
|
196
|
+
sdkName: "my-next-app",
|
|
197
|
+
sdkVersion: "0.1.2"
|
|
198
|
+
});
|
|
199
|
+
|
|
200
|
+
const routePatterns = [
|
|
201
|
+
"/",
|
|
202
|
+
"/projects/[projectId]/settings",
|
|
203
|
+
"/docs/[[...slug]]"
|
|
204
|
+
];
|
|
205
|
+
|
|
206
|
+
export function LogBrewNextNavigationSpans({ traceparent }) {
|
|
207
|
+
const pathname = usePathname();
|
|
208
|
+
|
|
209
|
+
useLogBrewNextNavigation({
|
|
210
|
+
client,
|
|
211
|
+
pathname,
|
|
212
|
+
routePatterns,
|
|
213
|
+
traceparent
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
return null;
|
|
217
|
+
}
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
`useLogBrewNextNavigation` records one `next.route <routeTemplate>` span when `pathname` changes to a route that matches one of your stable `routePatterns`. Use `createNextRouteTemplate` directly when you want to preview how a concrete `pathname` maps to `/projects/[projectId]/settings`, `[...catchAll]`, `[[...optionalCatchAll]]`, or a route-group pattern such as `/(app)/dashboard/[teamId]`.
|
|
221
|
+
|
|
222
|
+
The client helper requires explicit W3C trace context through `traceparent` or `traceId` plus `spanId`. It does not patch `fetch`, `XMLHttpRequest`, browser history, or the Next router. It never records the concrete pathname, query string, hash, headers, cookies, request body, or raw `traceparent` value. If a pathname cannot be matched to a stable route template, it skips the span instead of emitting a high-cardinality URL. Metadata is primitive-only.
|
|
223
|
+
|
|
224
|
+
Use `captureNextNavigation(client, input)` when you want to emit a route span from app-owned navigation callbacks instead of the React hook.
|
|
225
|
+
|
|
226
|
+
## Server Client Helper
|
|
50
227
|
|
|
51
228
|
```js
|
|
52
229
|
import { createLogBrewNextClient } from "@logbrew/next";
|
|
@@ -54,24 +231,10 @@ import { createLogBrewNextClient } from "@logbrew/next";
|
|
|
54
231
|
const client = createLogBrewNextClient({
|
|
55
232
|
serverApiKey: "LOGBREW_SERVER_API_KEY",
|
|
56
233
|
sdkName: "my-next-app",
|
|
57
|
-
sdkVersion: "0.1.
|
|
234
|
+
sdkVersion: "0.1.2"
|
|
58
235
|
});
|
|
59
236
|
```
|
|
60
237
|
|
|
61
|
-
##
|
|
62
|
-
|
|
63
|
-
After install, these commands are available from a consumer app:
|
|
64
|
-
|
|
65
|
-
```bash
|
|
66
|
-
node node_modules/@logbrew/next/examples/index.mjs --help
|
|
67
|
-
node node_modules/@logbrew/next/examples/index.mjs --list
|
|
68
|
-
node node_modules/@logbrew/next/examples/index.mjs readme-example
|
|
69
|
-
node node_modules/@logbrew/next/examples/index.mjs real-user-smoke
|
|
70
|
-
node node_modules/@logbrew/next/examples/index.mjs
|
|
71
|
-
npm --prefix node_modules/@logbrew/next/examples run help
|
|
72
|
-
npm --prefix node_modules/@logbrew/next/examples run list
|
|
73
|
-
npm --prefix node_modules/@logbrew/next/examples run readme-example
|
|
74
|
-
npm --prefix node_modules/@logbrew/next/examples run real-user-smoke
|
|
75
|
-
```
|
|
238
|
+
## Example Source
|
|
76
239
|
|
|
77
|
-
The
|
|
240
|
+
The package includes example source for App Router Route Handlers, server-side client creation, and app-owned responses. The packaged server examples use an explicit `RecordingTransport` so they can run offline and print serialized event batches without sending them. Use the default network-delivery snippets above as the starting point for wiring LogBrew into your Next.js application.
|
package/client.cjs
ADDED
|
@@ -0,0 +1,340 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
|
|
3
|
+
const React = require("react");
|
|
4
|
+
const {
|
|
5
|
+
LogBrewClient,
|
|
6
|
+
SdkError,
|
|
7
|
+
parseTraceparent
|
|
8
|
+
} = require("@logbrew/sdk");
|
|
9
|
+
|
|
10
|
+
const DEFAULT_SDK_NAME = "logbrew-next-client";
|
|
11
|
+
const DEFAULT_SDK_VERSION = "0.1.2";
|
|
12
|
+
|
|
13
|
+
function createLogBrewNextBrowserClient({
|
|
14
|
+
apiKey,
|
|
15
|
+
clientKey,
|
|
16
|
+
eventFilter,
|
|
17
|
+
sdkName = DEFAULT_SDK_NAME,
|
|
18
|
+
sdkVersion = DEFAULT_SDK_VERSION,
|
|
19
|
+
maxQueueSize,
|
|
20
|
+
maxRetries = 2,
|
|
21
|
+
onEventDropped
|
|
22
|
+
} = {}) {
|
|
23
|
+
const authKey = clientKey ?? apiKey;
|
|
24
|
+
if (!authKey) {
|
|
25
|
+
throw new SdkError("configuration_error", "createLogBrewNextBrowserClient requires clientKey or apiKey");
|
|
26
|
+
}
|
|
27
|
+
return LogBrewClient.create({
|
|
28
|
+
apiKey: authKey,
|
|
29
|
+
eventFilter,
|
|
30
|
+
maxQueueSize,
|
|
31
|
+
maxRetries,
|
|
32
|
+
onEventDropped,
|
|
33
|
+
sdkName,
|
|
34
|
+
sdkVersion
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function createNextRouteTemplate({
|
|
39
|
+
pathname,
|
|
40
|
+
routePatterns = [],
|
|
41
|
+
routeTemplate
|
|
42
|
+
} = {}) {
|
|
43
|
+
const safeRouteTemplate = normalizeRouteTemplate(routeTemplate);
|
|
44
|
+
if (safeRouteTemplate) {
|
|
45
|
+
return safeRouteTemplate;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const safePathname = pathnameOnly(pathname);
|
|
49
|
+
if (!safePathname || !Array.isArray(routePatterns)) {
|
|
50
|
+
return undefined;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const matches = routePatterns
|
|
54
|
+
.map((pattern) => normalizeRouteTemplate(pattern))
|
|
55
|
+
.filter((pattern) => pattern && routePatternMatchesPathname(pattern, safePathname));
|
|
56
|
+
|
|
57
|
+
const matched = matches.sort(compareRouteSpecificity)[0];
|
|
58
|
+
return matched;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function createNextNavigationSpanEvent({
|
|
62
|
+
durationMs,
|
|
63
|
+
id,
|
|
64
|
+
idFactory = defaultNextNavigationSpanId,
|
|
65
|
+
metadata = {},
|
|
66
|
+
navigationIndex,
|
|
67
|
+
navigationType,
|
|
68
|
+
now = () => new Date().toISOString(),
|
|
69
|
+
parentSpanId,
|
|
70
|
+
pathname,
|
|
71
|
+
routePatterns,
|
|
72
|
+
routeTemplate,
|
|
73
|
+
spanId,
|
|
74
|
+
spanIdFactory = defaultSpanIdFactory,
|
|
75
|
+
status = "ok",
|
|
76
|
+
timestamp,
|
|
77
|
+
traceId,
|
|
78
|
+
traceparent
|
|
79
|
+
} = {}) {
|
|
80
|
+
const safeRouteTemplate = createNextRouteTemplate({ pathname, routePatterns, routeTemplate });
|
|
81
|
+
if (!safeRouteTemplate) {
|
|
82
|
+
return undefined;
|
|
83
|
+
}
|
|
84
|
+
const trace = traceContextFromInput({ parentSpanId, spanId, spanIdFactory, traceId, traceparent });
|
|
85
|
+
return {
|
|
86
|
+
id: id ?? idFactory({ navigationIndex, navigationType, routeTemplate: safeRouteTemplate }),
|
|
87
|
+
timestamp: timestamp ?? now(),
|
|
88
|
+
type: "span",
|
|
89
|
+
attributes: {
|
|
90
|
+
durationMs,
|
|
91
|
+
name: `next.route ${safeRouteTemplate}`,
|
|
92
|
+
parentSpanId: trace.parentSpanId,
|
|
93
|
+
spanId: trace.spanId,
|
|
94
|
+
status,
|
|
95
|
+
traceId: trace.traceId,
|
|
96
|
+
metadata: compactMetadata({
|
|
97
|
+
framework: "nextjs",
|
|
98
|
+
navigationIndex,
|
|
99
|
+
navigationType,
|
|
100
|
+
routeTemplate: safeRouteTemplate,
|
|
101
|
+
source: "next.client.route",
|
|
102
|
+
...metadata
|
|
103
|
+
})
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function captureNextNavigation(client, input = {}) {
|
|
109
|
+
if (!client) {
|
|
110
|
+
throw new SdkError("configuration_error", "captureNextNavigation requires a client");
|
|
111
|
+
}
|
|
112
|
+
const event = createNextNavigationSpanEvent(input);
|
|
113
|
+
if (!event) {
|
|
114
|
+
return undefined;
|
|
115
|
+
}
|
|
116
|
+
client.span(event.id, event.timestamp, event.attributes);
|
|
117
|
+
return event;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function useLogBrewNextNavigation(options = {}) {
|
|
121
|
+
const lastNavigationKey = React.useRef(null);
|
|
122
|
+
const navigationIndex = React.useRef(0);
|
|
123
|
+
|
|
124
|
+
React.useEffect(() => {
|
|
125
|
+
try {
|
|
126
|
+
if (!options.client) {
|
|
127
|
+
throw new SdkError("configuration_error", "useLogBrewNextNavigation requires client");
|
|
128
|
+
}
|
|
129
|
+
const routeTemplate = createNextRouteTemplate(options);
|
|
130
|
+
if (!routeTemplate) {
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
const navigationKey = nextNavigationKey(options.pathname, routeTemplate);
|
|
134
|
+
if (navigationKey === lastNavigationKey.current) {
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
lastNavigationKey.current = navigationKey;
|
|
138
|
+
navigationIndex.current += 1;
|
|
139
|
+
const event = captureNextNavigation(options.client, {
|
|
140
|
+
...options,
|
|
141
|
+
navigationIndex: navigationIndex.current,
|
|
142
|
+
routeTemplate
|
|
143
|
+
});
|
|
144
|
+
if (event && typeof options.onNavigation === "function") {
|
|
145
|
+
options.onNavigation(event);
|
|
146
|
+
}
|
|
147
|
+
} catch (error) {
|
|
148
|
+
if (typeof options.onCaptureError === "function") {
|
|
149
|
+
options.onCaptureError(error);
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
throw error;
|
|
153
|
+
}
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function compactMetadata(metadata) {
|
|
158
|
+
const compacted = {};
|
|
159
|
+
for (const [key, value] of Object.entries(metadata)) {
|
|
160
|
+
if (value === undefined) {
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean" || value === null) {
|
|
164
|
+
compacted[key] = value;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
return compacted;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function traceContextFromInput({ parentSpanId, spanId, spanIdFactory, traceId, traceparent }) {
|
|
171
|
+
if (typeof traceparent === "string") {
|
|
172
|
+
const parsed = parseTraceparent(traceparent);
|
|
173
|
+
return {
|
|
174
|
+
parentSpanId: parentSpanId ?? parsed.parentSpanId,
|
|
175
|
+
spanId: spanId ?? spanIdFactory(),
|
|
176
|
+
traceId: traceId ?? parsed.traceId
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
if (!traceId || !spanId) {
|
|
180
|
+
throw new SdkError("configuration_error", "Next.js navigation requires traceparent or traceId and spanId");
|
|
181
|
+
}
|
|
182
|
+
return { parentSpanId, spanId, traceId };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function nextNavigationKey(pathname, routeTemplate) {
|
|
186
|
+
return `${routeTemplate}|${pathnameOnly(pathname) ?? ""}`;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function normalizeRouteTemplate(value) {
|
|
190
|
+
const pathname = pathnameOnly(value);
|
|
191
|
+
if (!pathname) {
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
const segments = pathname
|
|
195
|
+
.split("/")
|
|
196
|
+
.filter(Boolean)
|
|
197
|
+
.filter((segment) => !isRouteGroupSegment(segment) && !segment.startsWith("@"));
|
|
198
|
+
if (segments.length === 0) {
|
|
199
|
+
return "/";
|
|
200
|
+
}
|
|
201
|
+
return `/${segments.join("/")}`;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function isRouteGroupSegment(segment) {
|
|
205
|
+
return segment.startsWith("(") && segment.endsWith(")");
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function pathnameOnly(value) {
|
|
209
|
+
if (value === undefined || value === null) {
|
|
210
|
+
return undefined;
|
|
211
|
+
}
|
|
212
|
+
const trimmed = String(value).trim();
|
|
213
|
+
if (trimmed === "") {
|
|
214
|
+
return undefined;
|
|
215
|
+
}
|
|
216
|
+
const withoutQueryOrHash = trimmed.split(/[?#]/u, 1)[0];
|
|
217
|
+
let pathname = withoutQueryOrHash;
|
|
218
|
+
if (hasUrlScheme(withoutQueryOrHash)) {
|
|
219
|
+
try {
|
|
220
|
+
pathname = new URL(withoutQueryOrHash).pathname;
|
|
221
|
+
} catch {
|
|
222
|
+
return undefined;
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
if (!pathname.startsWith("/")) {
|
|
226
|
+
pathname = `/${pathname}`;
|
|
227
|
+
}
|
|
228
|
+
return pathname.length > 1 && pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function hasUrlScheme(url) {
|
|
232
|
+
return /^[a-z][a-z0-9+.-]*:/iu.test(url);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function routePatternMatchesPathname(routePattern, pathname) {
|
|
236
|
+
const patternSegments = routePattern.split("/").filter(Boolean);
|
|
237
|
+
const pathSegments = pathname.split("/").filter(Boolean);
|
|
238
|
+
if (patternSegments.length === 0) {
|
|
239
|
+
return pathSegments.length === 0;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
let pathIndex = 0;
|
|
243
|
+
for (let patternIndex = 0; patternIndex < patternSegments.length; patternIndex += 1) {
|
|
244
|
+
const segment = patternSegments[patternIndex];
|
|
245
|
+
if (isOptionalCatchAllSegment(segment)) {
|
|
246
|
+
return patternIndex === patternSegments.length - 1;
|
|
247
|
+
}
|
|
248
|
+
if (isCatchAllSegment(segment)) {
|
|
249
|
+
return patternIndex === patternSegments.length - 1 && pathIndex < pathSegments.length;
|
|
250
|
+
}
|
|
251
|
+
if (pathIndex >= pathSegments.length) {
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
if (isDynamicSegment(segment)) {
|
|
255
|
+
pathIndex += 1;
|
|
256
|
+
continue;
|
|
257
|
+
}
|
|
258
|
+
if (segment !== pathSegments[pathIndex]) {
|
|
259
|
+
return false;
|
|
260
|
+
}
|
|
261
|
+
pathIndex += 1;
|
|
262
|
+
}
|
|
263
|
+
return pathIndex === pathSegments.length;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function compareRouteSpecificity(left, right) {
|
|
267
|
+
const scoreDelta = routeSpecificityScore(left) - routeSpecificityScore(right);
|
|
268
|
+
if (scoreDelta !== 0) {
|
|
269
|
+
return scoreDelta;
|
|
270
|
+
}
|
|
271
|
+
return right.split("/").length - left.split("/").length;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function routeSpecificityScore(routePattern) {
|
|
275
|
+
return routePattern
|
|
276
|
+
.split("/")
|
|
277
|
+
.filter(Boolean)
|
|
278
|
+
.reduce((score, segment) => {
|
|
279
|
+
if (isOptionalCatchAllSegment(segment)) {
|
|
280
|
+
return score + 1000;
|
|
281
|
+
}
|
|
282
|
+
if (isCatchAllSegment(segment)) {
|
|
283
|
+
return score + 100;
|
|
284
|
+
}
|
|
285
|
+
if (isDynamicSegment(segment)) {
|
|
286
|
+
return score + 10;
|
|
287
|
+
}
|
|
288
|
+
return score;
|
|
289
|
+
}, 0);
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function isDynamicSegment(segment) {
|
|
293
|
+
return /^\[[^[\]]+\]$/u.test(segment);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function isCatchAllSegment(segment) {
|
|
297
|
+
return /^\[\.\.\.[^[\]]+\]$/u.test(segment);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function isOptionalCatchAllSegment(segment) {
|
|
301
|
+
return /^\[\[\.\.\.[^[\]]+\]\]$/u.test(segment);
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function defaultNextNavigationSpanId({ routeTemplate }) {
|
|
305
|
+
return `evt_next_route_${slugify(routeTemplate ?? "route")}`;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function slugify(value) {
|
|
309
|
+
return String(value)
|
|
310
|
+
.toLowerCase()
|
|
311
|
+
.replace(/[^a-z0-9]+/g, "_")
|
|
312
|
+
.replace(/^_+|_+$/g, "") || "event";
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function defaultSpanIdFactory() {
|
|
316
|
+
return randomHex(8);
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function randomHex(bytes) {
|
|
320
|
+
const randomValues = new Uint8Array(bytes);
|
|
321
|
+
if (globalThis.crypto && typeof globalThis.crypto.getRandomValues === "function") {
|
|
322
|
+
globalThis.crypto.getRandomValues(randomValues);
|
|
323
|
+
} else {
|
|
324
|
+
for (let index = 0; index < bytes; index += 1) {
|
|
325
|
+
randomValues[index] = Math.floor(Math.random() * 256);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
return Array.from(randomValues, (value) => value.toString(16).padStart(2, "0")).join("");
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
const api = {
|
|
332
|
+
captureNextNavigation,
|
|
333
|
+
createLogBrewNextBrowserClient,
|
|
334
|
+
createNextNavigationSpanEvent,
|
|
335
|
+
createNextRouteTemplate,
|
|
336
|
+
useLogBrewNextNavigation
|
|
337
|
+
};
|
|
338
|
+
|
|
339
|
+
Object.assign(exports, api);
|
|
340
|
+
exports.default = api;
|
package/client.d.cts
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
DroppedEvent,
|
|
3
|
+
EventFilter,
|
|
4
|
+
LogBrewClient,
|
|
5
|
+
Metadata,
|
|
6
|
+
SpanAttributes
|
|
7
|
+
} from "@logbrew/sdk";
|
|
8
|
+
|
|
9
|
+
export type CreateLogBrewNextBrowserClientConfig = {
|
|
10
|
+
apiKey?: string;
|
|
11
|
+
clientKey?: string;
|
|
12
|
+
sdkName?: string;
|
|
13
|
+
sdkVersion?: string;
|
|
14
|
+
maxRetries?: number;
|
|
15
|
+
eventFilter?: EventFilter;
|
|
16
|
+
maxQueueSize?: number;
|
|
17
|
+
onEventDropped?: (drop: DroppedEvent) => void;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export type NextRoutePattern = string;
|
|
21
|
+
|
|
22
|
+
export type NextRouteTemplateInput = {
|
|
23
|
+
pathname?: string;
|
|
24
|
+
routePatterns?: NextRoutePattern[];
|
|
25
|
+
routeTemplate?: string;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export type NextNavigationSpanIdFactoryContext = {
|
|
29
|
+
navigationIndex?: number;
|
|
30
|
+
navigationType?: string;
|
|
31
|
+
routeTemplate?: string;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
export type NextNavigationSpanInput = NextRouteTemplateInput & {
|
|
35
|
+
durationMs?: number;
|
|
36
|
+
id?: string;
|
|
37
|
+
idFactory?: (context: NextNavigationSpanIdFactoryContext) => string;
|
|
38
|
+
metadata?: Metadata;
|
|
39
|
+
navigationIndex?: number;
|
|
40
|
+
navigationType?: string;
|
|
41
|
+
now?: () => string;
|
|
42
|
+
parentSpanId?: string;
|
|
43
|
+
spanId?: string;
|
|
44
|
+
spanIdFactory?: () => string;
|
|
45
|
+
status?: SpanAttributes["status"];
|
|
46
|
+
timestamp?: string;
|
|
47
|
+
traceId?: string;
|
|
48
|
+
traceparent?: string;
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
export type CaptureNextNavigationInput = NextNavigationSpanInput;
|
|
52
|
+
|
|
53
|
+
export type NextNavigationSpanEvent = {
|
|
54
|
+
id: string;
|
|
55
|
+
timestamp: string;
|
|
56
|
+
type: "span";
|
|
57
|
+
attributes: SpanAttributes;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
export type UseLogBrewNextNavigationOptions = CaptureNextNavigationInput & {
|
|
61
|
+
client: LogBrewClient;
|
|
62
|
+
onCaptureError?: (error: unknown) => void;
|
|
63
|
+
onNavigation?: (event: NextNavigationSpanEvent) => void;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
export declare function createLogBrewNextBrowserClient(
|
|
67
|
+
config: CreateLogBrewNextBrowserClientConfig
|
|
68
|
+
): LogBrewClient;
|
|
69
|
+
|
|
70
|
+
export declare function createNextRouteTemplate(
|
|
71
|
+
input?: NextRouteTemplateInput
|
|
72
|
+
): string | undefined;
|
|
73
|
+
|
|
74
|
+
export declare function createNextNavigationSpanEvent(
|
|
75
|
+
input?: NextNavigationSpanInput
|
|
76
|
+
): NextNavigationSpanEvent | undefined;
|
|
77
|
+
|
|
78
|
+
export declare function captureNextNavigation(
|
|
79
|
+
client: LogBrewClient,
|
|
80
|
+
input?: CaptureNextNavigationInput
|
|
81
|
+
): NextNavigationSpanEvent | undefined;
|
|
82
|
+
|
|
83
|
+
export declare function useLogBrewNextNavigation(
|
|
84
|
+
options: UseLogBrewNextNavigationOptions
|
|
85
|
+
): void;
|
|
86
|
+
|
|
87
|
+
declare const defaultExport: {
|
|
88
|
+
captureNextNavigation: typeof captureNextNavigation;
|
|
89
|
+
createLogBrewNextBrowserClient: typeof createLogBrewNextBrowserClient;
|
|
90
|
+
createNextNavigationSpanEvent: typeof createNextNavigationSpanEvent;
|
|
91
|
+
createNextRouteTemplate: typeof createNextRouteTemplate;
|
|
92
|
+
useLogBrewNextNavigation: typeof useLogBrewNextNavigation;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
export default defaultExport;
|