@honeybadger-io/nextjs 5.11.5 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -42
- package/dist/capture-request-error.d.ts +35 -0
- package/dist/capture-request-error.test.d.ts +2 -0
- package/dist/capture-router-transition-start.d.ts +21 -0
- package/dist/client.d.ts +2 -0
- package/dist/copy-config-files.js +106 -34
- package/dist/copy-config-files.js.map +1 -1
- package/dist/edge.d.ts +2 -1
- package/dist/flush.d.ts +24 -0
- package/dist/honeybadger-nextjs-client.cjs.js +35 -0
- package/dist/honeybadger-nextjs-client.cjs.js.map +1 -0
- package/dist/honeybadger-nextjs-client.esm.js +27 -0
- package/dist/honeybadger-nextjs-client.esm.js.map +1 -0
- package/dist/honeybadger-nextjs-edge.cjs.js +320 -240
- package/dist/honeybadger-nextjs-edge.cjs.js.map +1 -1
- package/dist/honeybadger-nextjs-edge.esm.js +317 -240
- package/dist/honeybadger-nextjs-edge.esm.js.map +1 -1
- package/dist/honeybadger-nextjs.cjs.js +835 -387
- package/dist/honeybadger-nextjs.cjs.js.map +1 -1
- package/dist/honeybadger-nextjs.esm.js +829 -386
- package/dist/honeybadger-nextjs.esm.js.map +1 -1
- package/dist/index.d.ts +5 -2
- package/dist/insights-instrumentation.d.ts +30 -2
- package/dist/insights.d.ts +72 -0
- package/dist/insights.test.d.ts +2 -0
- package/dist/setup.d.ts +11 -0
- package/dist/setup.test.d.ts +2 -0
- package/dist/source-maps.d.ts +55 -0
- package/dist/source-maps.test.d.ts +2 -0
- package/dist/types.d.ts +20 -8
- package/package.json +34 -12
- package/src/capture-request-error.test.ts +245 -0
- package/src/capture-request-error.ts +92 -0
- package/src/capture-router-transition-start.ts +33 -0
- package/src/client.ts +4 -0
- package/src/copy-config-files.test.ts +250 -16
- package/src/copy-config-files.ts +117 -34
- package/src/edge.ts +12 -1
- package/src/flush.ts +58 -0
- package/src/index.ts +7 -2
- package/src/insights-instrumentation.ts +104 -11
- package/src/insights.test.ts +192 -0
- package/src/insights.ts +225 -0
- package/src/setup.test.ts +214 -0
- package/src/setup.ts +172 -0
- package/src/source-maps.test.ts +803 -0
- package/src/source-maps.ts +515 -0
- package/src/types.ts +38 -21
- package/templates/_error.js +14 -10
- package/templates/_error_app_router.js +1 -1
- package/templates/_error_app_router.tsx +1 -1
- package/templates/honeybadger.server.config.js +5 -16
- package/templates/instrumentation-client.js +21 -0
- package/templates/instrumentation.js +29 -0
- package/dist/webpack.d.ts +0 -3
- package/dist/with-honeybadger.d.ts +0 -32
- package/dist/with-honeybadger.test.d.ts +0 -2
- package/src/webpack.ts +0 -228
- package/src/with-honeybadger.test.ts +0 -527
- package/src/with-honeybadger.ts +0 -286
- package/templates/honeybadger.browser.config.js +0 -13
- package/templates/honeybadger.edge.config.js +0 -13
|
@@ -1,204 +1,597 @@
|
|
|
1
1
|
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
2
3
|
import path from 'path';
|
|
3
|
-
import
|
|
4
|
+
import picomatch from 'picomatch';
|
|
4
5
|
import Honeybadger from '@honeybadger-io/js';
|
|
5
6
|
import * as nextServer from 'next/server';
|
|
6
7
|
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
8
|
+
/**
|
|
9
|
+
* Loads plugin-core on demand, never at module scope.
|
|
10
|
+
*
|
|
11
|
+
* Its module body runs `fetchRetry(require('node-fetch'))` as a side effect, which throws
|
|
12
|
+
* `ArgumentError: fetch must be a function` inside the Next.js server runtime. This module
|
|
13
|
+
* shares a barrel with the runtime instrumentation exports, so a top-level import here
|
|
14
|
+
* would break `instrumentation.ts` for every app. plugin-core is a rollup external, so this
|
|
15
|
+
* stays a real deferred require in both the CJS and ESM bundles.
|
|
16
|
+
*/
|
|
17
|
+
function loadPluginCore() {
|
|
18
|
+
return import('@honeybadger-io/plugin-core');
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* The build output directory Next.js serves over HTTP, relative to `distDir`. `.next/static`
|
|
22
|
+
* is published at `/_next/static`; everything else in `distDir` is not served.
|
|
23
|
+
*/
|
|
24
|
+
const BROWSER_OUTPUT_DIR = 'static';
|
|
25
|
+
/**
|
|
26
|
+
* The directories inside `distDir` whose JavaScript is actually shipped, and so the only
|
|
27
|
+
* ones worth collecting maps from. `distDir` also holds build tooling — `build/chunks`,
|
|
28
|
+
* `cache`, `required-server-files.js` — and a `standalone` copy of the server when that
|
|
29
|
+
* output mode is on. Walking all of it uploads maps under a `minified_url` no request can
|
|
30
|
+
* ever produce.
|
|
31
|
+
*/
|
|
32
|
+
const OUTPUT_DIRS = [BROWSER_OUTPUT_DIR, 'server'];
|
|
33
|
+
function log$1(type, silent, msg) {
|
|
34
|
+
if (['error', 'warn'].includes(type) || !silent) {
|
|
11
35
|
console[type]('[HoneybadgerNextJs]', msg);
|
|
12
36
|
}
|
|
13
37
|
}
|
|
14
|
-
|
|
15
|
-
|
|
38
|
+
/**
|
|
39
|
+
* Whether the project has configured source map upload.
|
|
40
|
+
*
|
|
41
|
+
* Separate from `resolveUploadOptions` because `withHoneybadgerConfig` needs the answer
|
|
42
|
+
* while building the config, and must not emit the "not configured" warning there — the
|
|
43
|
+
* hook will do that once, at build time.
|
|
44
|
+
*/
|
|
45
|
+
function isSourceMapUploadConfigured(honeybadgerNextJsConfig = {}) {
|
|
16
46
|
if (honeybadgerNextJsConfig.disableSourceMapUpload) {
|
|
17
47
|
return false;
|
|
18
48
|
}
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
49
|
+
const apiKey = honeybadgerNextJsConfig.apiKey || process.env.NEXT_PUBLIC_HONEYBADGER_API_KEY;
|
|
50
|
+
const assetsUrl = honeybadgerNextJsConfig.assetsUrl || process.env.NEXT_PUBLIC_HONEYBADGER_ASSETS_URL;
|
|
51
|
+
return Boolean(apiKey && assetsUrl);
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Resolves the upload options, falling back to the same environment variables the
|
|
55
|
+
* configuration templates use.
|
|
56
|
+
*
|
|
57
|
+
* Returns `null` rather than throwing when the project has not configured source map
|
|
58
|
+
* upload. `cleanOptions` throws on a missing `apiKey`/`assetsUrl`, and Next.js re-throws
|
|
59
|
+
* whatever this hook throws — so validating eagerly would fail the build of every app
|
|
60
|
+
* that simply does not use this feature.
|
|
61
|
+
*/
|
|
62
|
+
async function resolveUploadOptions(honeybadgerNextJsConfig = {}) {
|
|
63
|
+
var _a;
|
|
64
|
+
const silent = (_a = honeybadgerNextJsConfig.silent) !== null && _a !== void 0 ? _a : true;
|
|
65
|
+
if (honeybadgerNextJsConfig.disableSourceMapUpload) {
|
|
66
|
+
log$1('debug', silent, 'source map upload disabled');
|
|
67
|
+
return null;
|
|
22
68
|
}
|
|
23
|
-
|
|
69
|
+
// `disableSourceMapUpload` is this package's own switch, handled above; everything else
|
|
70
|
+
// on the config is a plugin-core option and passes straight through.
|
|
71
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
72
|
+
const { disableSourceMapUpload, ...provided } = honeybadgerNextJsConfig;
|
|
73
|
+
const apiKey = provided.apiKey || process.env.NEXT_PUBLIC_HONEYBADGER_API_KEY;
|
|
74
|
+
const assetsUrl = provided.assetsUrl || process.env.NEXT_PUBLIC_HONEYBADGER_ASSETS_URL;
|
|
75
|
+
if (!apiKey || !assetsUrl) {
|
|
76
|
+
log$1('warn', silent, 'skipping source map upload; set apiKey and assetsUrl to enable it');
|
|
77
|
+
return null;
|
|
78
|
+
}
|
|
79
|
+
// `cleanOptions` merges as `{ ...defaults, ...options }`, so a key present with an
|
|
80
|
+
// `undefined` value overwrites the default rather than falling back to it. An unset
|
|
81
|
+
// revision would upload as `undefined` instead of `main`, and a fault whose revision
|
|
82
|
+
// does not match its source map is never symbolicated — so drop empty values instead
|
|
83
|
+
// of passing them through.
|
|
84
|
+
const { cleanOptions } = await loadPluginCore();
|
|
85
|
+
return cleanOptions(withoutUndefined({
|
|
86
|
+
...provided,
|
|
87
|
+
apiKey,
|
|
88
|
+
assetsUrl,
|
|
89
|
+
revision: provided.revision || process.env.NEXT_PUBLIC_HONEYBADGER_REVISION,
|
|
90
|
+
silent,
|
|
91
|
+
}));
|
|
92
|
+
}
|
|
93
|
+
function withoutUndefined(options) {
|
|
94
|
+
return Object.fromEntries(Object.entries(options).filter(([, value]) => value !== undefined));
|
|
95
|
+
}
|
|
96
|
+
// Mirrors plugin-core's DEFAULT_DEVELOPMENT_ENVIRONMENTS. Duplicated so a development
|
|
97
|
+
// build can be recognised before plugin-core is loaded — see uploadSourceMapsAfterBuild.
|
|
98
|
+
const DEFAULT_DEVELOPMENT_ENVIRONMENTS = ['dev', 'development', 'test'];
|
|
99
|
+
function isDevEnv(developmentEnvironments) {
|
|
100
|
+
if (!process.env.NODE_ENV) {
|
|
24
101
|
return false;
|
|
25
102
|
}
|
|
26
|
-
return
|
|
103
|
+
return developmentEnvironments.includes(process.env.NODE_ENV);
|
|
27
104
|
}
|
|
28
|
-
function
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
105
|
+
async function walk(dir, onFile) {
|
|
106
|
+
let entries;
|
|
107
|
+
try {
|
|
108
|
+
entries = await fs.promises.readdir(dir, { withFileTypes: true });
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
// A build output directory that isn't there is not an error worth failing on — the
|
|
112
|
+
// server tree does not exist unless `experimental.serverSourceMaps` is on. Anything
|
|
113
|
+
// else (permissions, I/O) would silently shrink the upload to whatever happened to be
|
|
114
|
+
// readable, so let it propagate and be governed by `ignoreErrors`.
|
|
115
|
+
if (error.code === 'ENOENT') {
|
|
116
|
+
return;
|
|
36
117
|
}
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
if (!result.plugins) {
|
|
47
|
-
result.plugins = [];
|
|
48
|
-
}
|
|
49
|
-
const options = getWebpackPluginOptions(honeybadgerNextJsConfig);
|
|
50
|
-
if (options) {
|
|
51
|
-
result.plugins.push(new HoneybadgerSourceMapPlugin(options));
|
|
52
|
-
}
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
for (const entry of entries) {
|
|
121
|
+
const entryPath = path.join(dir, entry.name);
|
|
122
|
+
if (entry.isDirectory()) {
|
|
123
|
+
await walk(entryPath, onFile);
|
|
124
|
+
}
|
|
125
|
+
else if (entry.isFile()) {
|
|
126
|
+
onFile(entryPath);
|
|
53
127
|
}
|
|
54
|
-
return result;
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
async function injectHoneybadgerConfigToEntry(originalEntry, projectDir, configType) {
|
|
58
|
-
const result = typeof originalEntry === 'function' ? await originalEntry() : { ...originalEntry };
|
|
59
|
-
const hbConfigFile = getHoneybadgerConfigFile(projectDir, configType);
|
|
60
|
-
if (!hbConfigFile) {
|
|
61
|
-
return result;
|
|
62
128
|
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* A source map is only worth uploading when it carries the original sources. Next.js
|
|
132
|
+
* emits maps without `sourcesContent` for some outputs, and those symbolicate to
|
|
133
|
+
* nothing. Same check the rollup and esbuild plugins apply.
|
|
134
|
+
*/
|
|
135
|
+
async function hasSourcesContent(sourcemapFilePath) {
|
|
136
|
+
try {
|
|
137
|
+
const contents = await fs.promises.readFile(sourcemapFilePath, 'utf8');
|
|
138
|
+
const parsed = JSON.parse(contents);
|
|
139
|
+
return Array.isArray(parsed.sourcesContent) && parsed.sourcesContent.length > 0;
|
|
66
140
|
}
|
|
67
|
-
|
|
68
|
-
|
|
141
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
142
|
+
catch (error) {
|
|
143
|
+
return false;
|
|
69
144
|
}
|
|
70
|
-
return result;
|
|
71
145
|
}
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
else if (typeof currentEntryPoint === 'object' && currentEntryPoint && 'import' in currentEntryPoint) {
|
|
95
|
-
const currentImportValue = currentEntryPoint['import'];
|
|
96
|
-
const newImportValue = [hbConfigFile];
|
|
97
|
-
if (typeof currentImportValue === 'string') {
|
|
98
|
-
newImportValue.push(currentImportValue);
|
|
146
|
+
// Enough to reach the `sourceMappingURL` comment, which is the last line of a built file.
|
|
147
|
+
const SOURCE_MAPPING_URL_TAIL_BYTES = 2048;
|
|
148
|
+
/**
|
|
149
|
+
* The source map a built JavaScript file points at, or `null` when it has none.
|
|
150
|
+
*
|
|
151
|
+
* Resolved from the file's own `sourceMappingURL` comment rather than by assuming the map
|
|
152
|
+
* sits beside it as `<name>.js.map`. That sibling convention is webpack's; Turbopack gives
|
|
153
|
+
* the map an independent hash — `1mfl5gjk9763d.js` points at `33ri1p-shrphb.js.map`.
|
|
154
|
+
*
|
|
155
|
+
* Only the tail of the file is read, since the comment is always its last line.
|
|
156
|
+
*/
|
|
157
|
+
async function locateSourcemap(jsFilePath) {
|
|
158
|
+
var _a;
|
|
159
|
+
let tail;
|
|
160
|
+
try {
|
|
161
|
+
const handle = await fs.promises.open(jsFilePath, 'r');
|
|
162
|
+
try {
|
|
163
|
+
const { size } = await handle.stat();
|
|
164
|
+
const length = Math.min(size, SOURCE_MAPPING_URL_TAIL_BYTES);
|
|
165
|
+
const buffer = Buffer.alloc(length);
|
|
166
|
+
await handle.read(buffer, 0, length, size - length);
|
|
167
|
+
tail = buffer.toString('utf8');
|
|
99
168
|
}
|
|
100
|
-
|
|
101
|
-
|
|
169
|
+
finally {
|
|
170
|
+
await handle.close();
|
|
102
171
|
}
|
|
103
|
-
newEntryPoint = {
|
|
104
|
-
...currentEntryPoint,
|
|
105
|
-
import: newImportValue,
|
|
106
|
-
};
|
|
107
172
|
}
|
|
108
|
-
|
|
109
|
-
|
|
173
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
174
|
+
catch (error) {
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
// The last comment wins, per the source map spec. No Next.js chunk currently carries
|
|
178
|
+
// two, but a bundled library that mentions `sourceMappingURL` in its tail would
|
|
179
|
+
// otherwise mispair the map.
|
|
180
|
+
const matches = [...tail.matchAll(/[#@]\s*sourceMappingURL=(\S+)/g)];
|
|
181
|
+
const url = (_a = matches.at(-1)) === null || _a === void 0 ? void 0 : _a[1];
|
|
182
|
+
// No map, or an inline `data:` map, which there is nothing to upload for.
|
|
183
|
+
if (!url || url.startsWith('data:')) {
|
|
184
|
+
return null;
|
|
185
|
+
}
|
|
186
|
+
// `decodeURIComponent` throws on malformed escapes such as `bad%.map`. Scoped to just
|
|
187
|
+
// the decode, because letting it escape would abandon the whole build's upload over one
|
|
188
|
+
// unreadable footer rather than skipping that single file.
|
|
189
|
+
let decodedUrl;
|
|
190
|
+
try {
|
|
191
|
+
decodedUrl = decodeURIComponent(url);
|
|
192
|
+
}
|
|
193
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
194
|
+
catch (error) {
|
|
195
|
+
return null;
|
|
110
196
|
}
|
|
111
|
-
|
|
197
|
+
const sourcemapFilePath = path.resolve(path.dirname(jsFilePath), decodedUrl);
|
|
198
|
+
return fs.existsSync(sourcemapFilePath) ? sourcemapFilePath : null;
|
|
112
199
|
}
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
200
|
+
/**
|
|
201
|
+
* Pairs each built `.js` file with the source map it declares.
|
|
202
|
+
*
|
|
203
|
+
* `jsFilename` is the path relative to `distDir`, because that is what `assetsUrl`
|
|
204
|
+
* addresses: the configuration templates point it at `<origin>/_next`, and `.next/x`
|
|
205
|
+
* is served at `/_next/x`. `uploadSourcemap` builds `minified_url` by joining the two.
|
|
206
|
+
*
|
|
207
|
+
* Only `static/` and `server/` are walked — see `OUTPUT_DIRS`. Server maps exist only when
|
|
208
|
+
* `experimental.serverSourceMaps` is on, which `withHoneybadgerConfig` enables alongside
|
|
209
|
+
* upload. Server chunks are not served over HTTP, so whether their frames match the
|
|
210
|
+
* uploaded `minified_url` depends on the runtime path rewriting tracked in #1602 — but
|
|
211
|
+
* not uploading them at all guarantees server frames stay minified, which is the defect
|
|
212
|
+
* that issue reports.
|
|
213
|
+
*/
|
|
214
|
+
async function collectSourcemaps(distDir, ignorePaths = []) {
|
|
215
|
+
const jsFilePaths = [];
|
|
216
|
+
for (const outputDir of OUTPUT_DIRS) {
|
|
217
|
+
await walk(path.join(distDir, outputDir), (filePath) => {
|
|
218
|
+
if (filePath.endsWith('.js')) {
|
|
219
|
+
jsFilePaths.push(filePath);
|
|
220
|
+
}
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
const collected = [];
|
|
224
|
+
for (const jsFilePath of jsFilePaths) {
|
|
225
|
+
if (picomatch.isMatch(jsFilePath, ignorePaths, { basename: true })) {
|
|
226
|
+
continue;
|
|
118
227
|
}
|
|
228
|
+
const sourcemapFilePath = await locateSourcemap(jsFilePath);
|
|
229
|
+
if (!sourcemapFilePath) {
|
|
230
|
+
continue;
|
|
231
|
+
}
|
|
232
|
+
if (!await hasSourcesContent(sourcemapFilePath)) {
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
// Posix separators: these become URL paths.
|
|
236
|
+
const jsFilename = path.relative(distDir, jsFilePath).split(path.sep).join('/');
|
|
237
|
+
collected.push({
|
|
238
|
+
sourcemapFilename: path.relative(distDir, sourcemapFilePath).split(path.sep).join('/'),
|
|
239
|
+
sourcemapFilePath,
|
|
240
|
+
jsFilename,
|
|
241
|
+
jsFilePath,
|
|
242
|
+
});
|
|
119
243
|
}
|
|
120
|
-
|
|
121
|
-
return null;
|
|
244
|
+
return collected;
|
|
122
245
|
}
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
246
|
+
/**
|
|
247
|
+
* Bundler URL schemes that appear in a map's `sources`.
|
|
248
|
+
*
|
|
249
|
+
* Turbopack writes `turbopack:///[project]/app/page.tsx`; webpack writes
|
|
250
|
+
* `webpack://_N_E/./app/page.tsx` or `webpack:///./app/page.tsx`.
|
|
251
|
+
*/
|
|
252
|
+
const SOURCE_SCHEME_PREFIXES = [
|
|
253
|
+
/^turbopack:\/\/\/\[[^\]]+\]\//,
|
|
254
|
+
/^webpack:\/\/[^/]*\/(\.\/)?/,
|
|
255
|
+
];
|
|
256
|
+
function normalizeSource(source) {
|
|
257
|
+
for (const prefix of SOURCE_SCHEME_PREFIXES) {
|
|
258
|
+
const normalized = source.replace(prefix, '');
|
|
259
|
+
if (normalized !== source) {
|
|
260
|
+
return normalized;
|
|
261
|
+
}
|
|
130
262
|
}
|
|
131
|
-
return
|
|
132
|
-
...honeybadgerNextJsConfig.webpackPluginOptions,
|
|
133
|
-
apiKey,
|
|
134
|
-
assetsUrl,
|
|
135
|
-
revision: ((_c = honeybadgerNextJsConfig.webpackPluginOptions) === null || _c === void 0 ? void 0 : _c.revision) || process.env.NEXT_PUBLIC_HONEYBADGER_REVISION,
|
|
136
|
-
silent: _silent,
|
|
137
|
-
};
|
|
263
|
+
return source;
|
|
138
264
|
}
|
|
139
|
-
|
|
140
|
-
|
|
265
|
+
/**
|
|
266
|
+
* Rewrites each map's `sources` to project-relative paths, in a throwaway copy.
|
|
267
|
+
*
|
|
268
|
+
* Honeybadger decides whether a mapped frame is *your* code by testing the resolved source
|
|
269
|
+
* against the notice's `projectRoot`, which the browser client defaults to the page origin.
|
|
270
|
+
* A source still carrying its bundler scheme never matches, so the frame is treated as
|
|
271
|
+
* library code and the fault surfaces the next frame instead — for a React app, an unmapped
|
|
272
|
+
* framework chunk. Stripping the scheme leaves a relative path, which Honeybadger resolves
|
|
273
|
+
* against the minified URL and therefore under the origin.
|
|
274
|
+
*
|
|
275
|
+
* Done here rather than by asking users to set `projectRoot` to a bundler-specific prefix,
|
|
276
|
+
* because that value differs between Turbopack and webpack and cannot be chosen correctly
|
|
277
|
+
* from client config.
|
|
278
|
+
*
|
|
279
|
+
* The originals on disk are untouched: Next.js reads the server maps itself.
|
|
280
|
+
*/
|
|
281
|
+
async function withNormalizedSources(sourcemaps) {
|
|
282
|
+
const unchanged = { sourcemaps, cleanup: async () => undefined };
|
|
283
|
+
if (sourcemaps.length === 0) {
|
|
284
|
+
return unchanged;
|
|
285
|
+
}
|
|
286
|
+
let tempDir;
|
|
141
287
|
try {
|
|
142
|
-
|
|
288
|
+
tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'honeybadger-sourcemaps-'));
|
|
143
289
|
}
|
|
144
|
-
|
|
145
|
-
|
|
290
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
291
|
+
catch (error) {
|
|
292
|
+
// Uploading unnormalized maps beats not uploading at all.
|
|
293
|
+
return unchanged;
|
|
294
|
+
}
|
|
295
|
+
const cleanup = () => fs.promises.rm(tempDir, { recursive: true, force: true });
|
|
296
|
+
const normalized = [];
|
|
297
|
+
for (const [index, sourcemap] of sourcemaps.entries()) {
|
|
298
|
+
try {
|
|
299
|
+
const parsed = JSON.parse(await fs.promises.readFile(sourcemap.sourcemapFilePath, 'utf8'));
|
|
300
|
+
const sources = parsed.sources;
|
|
301
|
+
if (!Array.isArray(sources) || !sources.some((source) => normalizeSource(String(source)) !== source)) {
|
|
302
|
+
normalized.push(sourcemap);
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
parsed.sources = sources.map((source) => normalizeSource(String(source)));
|
|
306
|
+
// Named by position, so two maps can never collide in the temp directory.
|
|
307
|
+
const copyPath = path.join(tempDir, `${index}.js.map`);
|
|
308
|
+
await fs.promises.writeFile(copyPath, JSON.stringify(parsed));
|
|
309
|
+
normalized.push({ ...sourcemap, sourcemapFilePath: copyPath });
|
|
310
|
+
}
|
|
311
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
312
|
+
catch (error) {
|
|
313
|
+
// A map we cannot rewrite is still worth uploading as it is.
|
|
314
|
+
normalized.push(sourcemap);
|
|
315
|
+
}
|
|
146
316
|
}
|
|
317
|
+
return { sourcemaps: normalized, cleanup };
|
|
147
318
|
}
|
|
148
319
|
/**
|
|
149
|
-
*
|
|
150
|
-
*
|
|
320
|
+
* Removes the *browser* source map files after they have been uploaded.
|
|
321
|
+
*
|
|
322
|
+
* Only for maps this package caused to be generated. `productionBrowserSourceMaps`
|
|
323
|
+
* publishes what it generates and Next.js has no hidden-source-map equivalent, so deleting
|
|
324
|
+
* after upload is what keeps them out of visitors' hands.
|
|
151
325
|
*
|
|
152
|
-
*
|
|
326
|
+
* Server maps are deliberately left alone. `.next/server` is not served, so there is no
|
|
327
|
+
* exposure to undo, and Next.js reads those maps itself when it formats server-side stack
|
|
328
|
+
* traces — deleting them would degrade the project's own logs for no benefit.
|
|
329
|
+
*
|
|
330
|
+
* The `sourceMappingURL` comments in the emitted JavaScript are left behind, so a browser
|
|
331
|
+
* that goes looking will get a 404 rather than the source.
|
|
153
332
|
*/
|
|
154
|
-
function
|
|
155
|
-
|
|
156
|
-
//
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
333
|
+
async function deleteBrowserSourcemapFiles(distDir, silent) {
|
|
334
|
+
// Deliberately every `.js.map` under `static`, not just the ones that were uploaded.
|
|
335
|
+
// `collectSourcemaps` drops maps that are ignored, malformed, unpaired, or missing
|
|
336
|
+
// `sourcesContent` — all of which Next.js still serves. Deleting only what we uploaded
|
|
337
|
+
// would leave exactly those behind, publicly readable, because of an option we turned on.
|
|
338
|
+
const mapFilePaths = [];
|
|
339
|
+
await walk(path.join(distDir, BROWSER_OUTPUT_DIR), (filePath) => {
|
|
340
|
+
if (filePath.endsWith('.js.map')) {
|
|
341
|
+
mapFilePaths.push(filePath);
|
|
342
|
+
}
|
|
343
|
+
});
|
|
344
|
+
let deleted = 0;
|
|
345
|
+
for (const mapFilePath of mapFilePaths) {
|
|
346
|
+
try {
|
|
347
|
+
await fs.promises.unlink(mapFilePath);
|
|
348
|
+
deleted++;
|
|
349
|
+
}
|
|
350
|
+
catch (error) {
|
|
351
|
+
// Loud, and not gated behind `silent`: a map we failed to remove is one this package
|
|
352
|
+
// caused to be served. That is exposure, not cleanup noise.
|
|
353
|
+
log$1('warn', silent, `could not delete ${path.relative(distDir, mapFilePath)}, so it will be served ` +
|
|
354
|
+
`publicly: ${error.message}`);
|
|
355
|
+
}
|
|
161
356
|
}
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
357
|
+
log$1('debug', silent, `deleted ${deleted} browser source map file(s) from the build output`);
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Uploads the build's source maps to Honeybadger.
|
|
361
|
+
*
|
|
362
|
+
* Registered by `withHoneybadgerConfig` on Next.js's `compiler.runAfterProductionCompile`
|
|
363
|
+
* hook, which runs for both Turbopack and webpack builds.
|
|
364
|
+
*
|
|
365
|
+
* Next.js re-throws whatever this hook throws, which would fail the user's build, so a
|
|
366
|
+
* failed upload is only allowed to propagate when `ignoreErrors` is off.
|
|
367
|
+
*/
|
|
368
|
+
async function uploadSourceMapsAfterBuild(honeybadgerNextJsConfig, metadata, options = {}) {
|
|
369
|
+
var _a, _b, _c;
|
|
370
|
+
// Read from the raw config rather than the resolved options, because the error handling
|
|
371
|
+
// below has to cover resolving them at all: `cleanOptions` can throw, and loading
|
|
372
|
+
// plugin-core can fail outright. Doing that outside the try meant a failure there ignored
|
|
373
|
+
// `ignoreErrors` and skipped the cleanup that keeps browser maps off the wire.
|
|
374
|
+
const silent = (_a = honeybadgerNextJsConfig === null || honeybadgerNextJsConfig === void 0 ? void 0 : honeybadgerNextJsConfig.silent) !== null && _a !== void 0 ? _a : true;
|
|
375
|
+
const ignoreErrors = (_b = honeybadgerNextJsConfig === null || honeybadgerNextJsConfig === void 0 ? void 0 : honeybadgerNextJsConfig.ignoreErrors) !== null && _b !== void 0 ? _b : false;
|
|
376
|
+
// Outside the try/finally below: a build that never intended to upload also never enabled
|
|
377
|
+
// the browser maps, so there is nothing of ours to clean up. Decided from the raw config
|
|
378
|
+
// so it needs no plugin-core.
|
|
379
|
+
const developmentEnvironments = (_c = honeybadgerNextJsConfig === null || honeybadgerNextJsConfig === void 0 ? void 0 : honeybadgerNextJsConfig.developmentEnvironments) !== null && _c !== void 0 ? _c : DEFAULT_DEVELOPMENT_ENVIRONMENTS;
|
|
380
|
+
if (isDevEnv(developmentEnvironments)) {
|
|
381
|
+
log$1('debug', silent, `skipping source map upload in ${process.env.NODE_ENV}`);
|
|
165
382
|
return;
|
|
166
383
|
}
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
if (
|
|
170
|
-
|
|
171
|
-
|
|
384
|
+
try {
|
|
385
|
+
const uploadOptions = await resolveUploadOptions(honeybadgerNextJsConfig);
|
|
386
|
+
if (!uploadOptions) {
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
const { uploadSourcemaps, sendDeployNotification } = await loadPluginCore();
|
|
390
|
+
const sourcemaps = await collectSourcemaps(metadata.distDir, uploadOptions.ignorePaths);
|
|
391
|
+
if (sourcemaps.length === 0) {
|
|
392
|
+
// Upload is configured, so finding nothing means something is wrong — a `distDir`
|
|
393
|
+
// that moved, or an `ignorePaths` that matches everything. Silence here would look
|
|
394
|
+
// exactly like success.
|
|
395
|
+
log$1('warn', silent, `found no source maps to upload in ${metadata.distDir}`);
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
const normalized = await withNormalizedSources(sourcemaps);
|
|
399
|
+
try {
|
|
400
|
+
await uploadSourcemaps(normalized.sourcemaps, uploadOptions);
|
|
172
401
|
}
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
402
|
+
finally {
|
|
403
|
+
await normalized.cleanup();
|
|
404
|
+
}
|
|
405
|
+
// Only after maps actually went up. A failed upload already skips this by throwing, so
|
|
406
|
+
// announcing a deploy for a build that uploaded nothing was the one inconsistent case —
|
|
407
|
+
// and it reads as "the maps for this revision are in place" when they are not.
|
|
408
|
+
if (uploadOptions.deploy) {
|
|
409
|
+
await sendDeployNotification(uploadOptions);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
catch (error) {
|
|
413
|
+
if (!ignoreErrors) {
|
|
414
|
+
throw error;
|
|
415
|
+
}
|
|
416
|
+
log$1('error', silent, `source map upload failed: ${error.message}`);
|
|
417
|
+
}
|
|
418
|
+
finally {
|
|
419
|
+
// Unconditionally, including after a failed upload. We enabled
|
|
420
|
+
// `productionBrowserSourceMaps`, so these maps ship publicly unless something removes
|
|
421
|
+
// them — and `ignoreErrors: true`, which the docs recommend so an outage cannot block a
|
|
422
|
+
// deploy, would otherwise turn every failed upload into published source. Keeping them
|
|
423
|
+
// to preserve "the only copy" is not worth that: a rebuild regenerates them, whereas a
|
|
424
|
+
// deploy that served them cannot be recalled.
|
|
425
|
+
if (options.deleteBrowserSourcemaps) {
|
|
426
|
+
try {
|
|
427
|
+
await deleteBrowserSourcemapFiles(metadata.distDir, silent);
|
|
428
|
+
}
|
|
429
|
+
catch (error) {
|
|
430
|
+
// Never let cleanup mask the upload failure that is already propagating.
|
|
431
|
+
log$1('warn', silent, `could not clean up browser source maps: ${error.message}`);
|
|
177
432
|
}
|
|
178
|
-
config.experimental.serverComponentsExternalPackages = ['@honeybadger-io/js'];
|
|
179
433
|
}
|
|
180
434
|
}
|
|
181
435
|
}
|
|
182
|
-
|
|
436
|
+
|
|
437
|
+
const HONEYBADGER_JS_PACKAGE = '@honeybadger-io/js';
|
|
438
|
+
let _silent = true;
|
|
439
|
+
function log(type, msg) {
|
|
440
|
+
if (['error', 'warn'].includes(type) || !_silent) {
|
|
441
|
+
console[type]('[HoneybadgerNextJs]', msg);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
/**
|
|
445
|
+
* Next.js warns when a package that requires files dynamically is bundled into the
|
|
446
|
+
* server build. @honeybadger-io/js does exactly that, so it has to be listed as an
|
|
447
|
+
* external package.
|
|
448
|
+
*
|
|
449
|
+
* First reported in https://github.com/honeybadger-io/honeybadger-js/issues/1351,
|
|
450
|
+
* caused by https://github.com/honeybadger-io/honeybadger-js/pull/1268.
|
|
451
|
+
*
|
|
452
|
+
* `serverExternalPackages` is unconditionally available from Next 15 onwards, which is
|
|
453
|
+
* this package's minimum supported version, so the older
|
|
454
|
+
* `experimental.serverComponentsExternalPackages` fallback is gone.
|
|
455
|
+
*/
|
|
456
|
+
function withHoneybadgerExternalized(serverExternalPackages) {
|
|
457
|
+
if (!Array.isArray(serverExternalPackages)) {
|
|
458
|
+
log('debug', `adding serverExternalPackages option with value ["${HONEYBADGER_JS_PACKAGE}"]`);
|
|
459
|
+
return [HONEYBADGER_JS_PACKAGE];
|
|
460
|
+
}
|
|
461
|
+
if (serverExternalPackages.includes(HONEYBADGER_JS_PACKAGE)) {
|
|
462
|
+
return serverExternalPackages;
|
|
463
|
+
}
|
|
464
|
+
log('debug', `adding ${HONEYBADGER_JS_PACKAGE} to serverExternalPackages`);
|
|
465
|
+
return [...serverExternalPackages, HONEYBADGER_JS_PACKAGE];
|
|
466
|
+
}
|
|
467
|
+
/**
|
|
468
|
+
* Registers the source map upload on Next.js's post-compile hook, composing with any hook
|
|
469
|
+
* the project already declares rather than replacing it.
|
|
470
|
+
*
|
|
471
|
+
* The hook is invoked from Next.js's generic build pipeline, so it runs for both Turbopack
|
|
472
|
+
* and webpack builds. Next.js documents it as being "useful for third-party tools to
|
|
473
|
+
* collect build outputs like sourcemaps".
|
|
474
|
+
*/
|
|
475
|
+
function withSourceMapUpload(compiler, honeybadgerNextJsConfig, deleteBrowserSourcemaps) {
|
|
476
|
+
const existingHook = compiler === null || compiler === void 0 ? void 0 : compiler.runAfterProductionCompile;
|
|
477
|
+
return {
|
|
478
|
+
...compiler,
|
|
479
|
+
runAfterProductionCompile: async (metadata) => {
|
|
480
|
+
// The project's own hook runs first, and is not swallowed: if it throws, that is
|
|
481
|
+
// its build failing, not ours.
|
|
482
|
+
if (typeof existingHook === 'function') {
|
|
483
|
+
await existingHook(metadata);
|
|
484
|
+
}
|
|
485
|
+
await uploadSourceMapsAfterBuild(honeybadgerNextJsConfig, metadata, { deleteBrowserSourcemaps });
|
|
486
|
+
},
|
|
487
|
+
};
|
|
488
|
+
}
|
|
489
|
+
/**
|
|
490
|
+
* Opts into server source maps, so frames from `.next/server` can be symbolicated too.
|
|
491
|
+
*
|
|
492
|
+
* `productionBrowserSourceMaps` covers only the browser build, so without this option
|
|
493
|
+
* there are no server maps to collect at all. Whether the uploaded server maps actually
|
|
494
|
+
* match the frames reported at runtime is tracked in
|
|
495
|
+
* https://github.com/honeybadger-io/honeybadger-js/issues/1602.
|
|
496
|
+
*
|
|
497
|
+
* Unlike the browser maps, these are never published: `.next/server` is not served, so
|
|
498
|
+
* they are left in place after upload rather than deleted.
|
|
499
|
+
*/
|
|
500
|
+
function withServerSourceMaps(experimental, enable) {
|
|
501
|
+
// An explicit setting is the project's call, either way.
|
|
502
|
+
if (!enable || (experimental === null || experimental === void 0 ? void 0 : experimental.serverSourceMaps) !== undefined) {
|
|
503
|
+
return experimental;
|
|
504
|
+
}
|
|
505
|
+
log('debug', 'enabling experimental.serverSourceMaps so server frames can be symbolicated');
|
|
506
|
+
return { ...experimental, serverSourceMaps: true };
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* Wraps a Next.js config so Honeybadger's build-time requirements are applied: the
|
|
510
|
+
* `@honeybadger-io/js` externalization, and source map upload after a production build.
|
|
511
|
+
*
|
|
512
|
+
* Instrumentation itself is not set up here — that moved to the bundler-agnostic
|
|
513
|
+
* `instrumentation.ts` / `instrumentation-client.ts` conventions, so it works under both
|
|
514
|
+
* Turbopack and webpack. See https://github.com/honeybadger-io/honeybadger-js/issues/1434.
|
|
515
|
+
*/
|
|
516
|
+
function withHoneybadgerConfig(config = {}, honeybadgerNextJsConfig) {
|
|
183
517
|
var _a;
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
518
|
+
_silent = (_a = honeybadgerNextJsConfig === null || honeybadgerNextJsConfig === void 0 ? void 0 : honeybadgerNextJsConfig.silent) !== null && _a !== void 0 ? _a : true;
|
|
519
|
+
const given = config;
|
|
520
|
+
const uploadConfigured = isSourceMapUploadConfigured(honeybadgerNextJsConfig);
|
|
521
|
+
// Next.js does not emit production browser source maps unless asked, so upload would
|
|
522
|
+
// find nothing to send. `productionBrowserSourceMaps` is the only switch, and it also
|
|
523
|
+
// serves the maps it generates.
|
|
524
|
+
//
|
|
525
|
+
// So turn it on when upload is configured, and have the post-build step delete the maps
|
|
526
|
+
// once they are uploaded. An explicit setting is always respected: a project that asked
|
|
527
|
+
// for served source maps keeps them, and keeps them served.
|
|
528
|
+
const enableBrowserSourceMaps = given.productionBrowserSourceMaps === undefined && uploadConfigured;
|
|
529
|
+
const experimental = withServerSourceMaps(given.experimental, uploadConfigured);
|
|
192
530
|
return {
|
|
193
531
|
...config,
|
|
194
|
-
|
|
532
|
+
serverExternalPackages: withHoneybadgerExternalized(given.serverExternalPackages),
|
|
533
|
+
productionBrowserSourceMaps: enableBrowserSourceMaps ? true : given.productionBrowserSourceMaps,
|
|
534
|
+
// Only introduce the key when there is something to put in it, so a config that never
|
|
535
|
+
// mentioned `experimental` does not suddenly grow the field.
|
|
536
|
+
...(experimental ? { experimental } : {}),
|
|
537
|
+
compiler: withSourceMapUpload(given.compiler, honeybadgerNextJsConfig, enableBrowserSourceMaps),
|
|
195
538
|
};
|
|
196
539
|
}
|
|
197
540
|
|
|
541
|
+
/**
|
|
542
|
+
* The `waitUntil` primitive the hosting platform injects per request. Next.js
|
|
543
|
+
* resolves `after()` through this same accessor, and it is the only channel
|
|
544
|
+
* available in Pages Router API routes, which are invoked as `(req, res)` with
|
|
545
|
+
* no context argument to read it from.
|
|
546
|
+
*/
|
|
547
|
+
function requestContextWaitUntil() {
|
|
548
|
+
var _a, _b;
|
|
549
|
+
const context = globalThis[Symbol.for('@next/request-context')];
|
|
550
|
+
const waitUntil = (_b = (_a = context === null || context === void 0 ? void 0 : context.get) === null || _a === void 0 ? void 0 : _a.call(context)) === null || _b === void 0 ? void 0 : _b.waitUntil;
|
|
551
|
+
return typeof waitUntil === 'function' ? waitUntil : undefined;
|
|
552
|
+
}
|
|
553
|
+
/**
|
|
554
|
+
* Ensure events are delivered before a serverless runtime freezes, without
|
|
555
|
+
* delaying the response where the runtime lets us avoid it.
|
|
556
|
+
*
|
|
557
|
+
* In order of preference: Next.js `after()` (App Router only — it needs App Router
|
|
558
|
+
* request context, so Pages Router must not call it), then a `waitUntil` from the
|
|
559
|
+
* platform request context, then a blocking `flushAsync()` when the runtime offers
|
|
560
|
+
* neither.
|
|
561
|
+
*
|
|
562
|
+
* Delivery failures are logged by the events worker and must not break the handler.
|
|
563
|
+
*/
|
|
564
|
+
function scheduleFlush(options = {}) {
|
|
565
|
+
var _a;
|
|
566
|
+
const flush = () => Honeybadger.flushAsync().catch(() => { });
|
|
567
|
+
if (options.useAfter) {
|
|
568
|
+
const after = nextServer.after;
|
|
569
|
+
if (typeof after === 'function') {
|
|
570
|
+
// Exported but still refusable: `after()` throws outside a supported
|
|
571
|
+
// context. Fall through to the remaining strategies rather than failing
|
|
572
|
+
// the request.
|
|
573
|
+
try {
|
|
574
|
+
after(flush);
|
|
575
|
+
return;
|
|
576
|
+
}
|
|
577
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
578
|
+
catch (error) {
|
|
579
|
+
// try waitUntil / blocking flush below
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
const waitUntil = (_a = options.waitUntil) !== null && _a !== void 0 ? _a : requestContextWaitUntil();
|
|
584
|
+
if (waitUntil) {
|
|
585
|
+
waitUntil(flush());
|
|
586
|
+
return;
|
|
587
|
+
}
|
|
588
|
+
return flush();
|
|
589
|
+
}
|
|
590
|
+
|
|
198
591
|
/**
|
|
199
592
|
* Edge-safe equivalents of the inbound instrumentation helpers in
|
|
200
593
|
* `@honeybadger-io/js` (src/server/instrumentation/http_event.ts). They are
|
|
201
|
-
* duplicated here because this module must
|
|
594
|
+
* duplicated here because this module must load in every runtime where
|
|
202
595
|
* Node builtins (the `crypto` module, `process.hrtime`) are unavailable. Keep
|
|
203
596
|
* the header names and the `request_id` / `correlation_id` contract in sync
|
|
204
597
|
* with that file.
|
|
@@ -227,14 +620,6 @@ function generateId() {
|
|
|
227
620
|
return v.toString(16);
|
|
228
621
|
});
|
|
229
622
|
}
|
|
230
|
-
function readHeader(headers, name) {
|
|
231
|
-
const value = headers.get(name);
|
|
232
|
-
if (typeof value !== 'string') {
|
|
233
|
-
return undefined;
|
|
234
|
-
}
|
|
235
|
-
const trimmed = value.trim();
|
|
236
|
-
return trimmed.length ? trimmed : undefined;
|
|
237
|
-
}
|
|
238
623
|
function readNodeHeader(headers, name) {
|
|
239
624
|
if (!headers) {
|
|
240
625
|
return undefined;
|
|
@@ -258,24 +643,57 @@ function readNodeHeader(headers, name) {
|
|
|
258
643
|
const trimmed = value.trim();
|
|
259
644
|
return trimmed.length ? trimmed : undefined;
|
|
260
645
|
}
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
646
|
+
/**
|
|
647
|
+
* Shared id precedence. Kept in one place (rather than once per request shape)
|
|
648
|
+
* so the header-name contract documented above is only spelled out once.
|
|
649
|
+
*
|
|
650
|
+
* The span ids do double duty. They are emitted as `trace_id` / `span_id`, and they also
|
|
651
|
+
* back-fill `request_id` / `correlation_id` when no header supplied them — a trace id
|
|
652
|
+
* already has exactly the semantics we want for a correlation id, since W3C trace context
|
|
653
|
+
* reuses an inbound `traceparent` and mints a new one when there is none.
|
|
654
|
+
*
|
|
655
|
+
* That double duty is what makes a fault joinable to its request's events: both paths seed
|
|
656
|
+
* from the same span, so with no id headers present a fault and its `request.handled` event
|
|
657
|
+
* carry identical values for all four.
|
|
658
|
+
*/
|
|
659
|
+
function seedIds(read, span = {}) {
|
|
660
|
+
var _a, _b, _c, _d, _e, _f;
|
|
661
|
+
const requestId = (_c = (_b = (_a = read('x-request-id')) !== null && _a !== void 0 ? _a : read('request-id')) !== null && _b !== void 0 ? _b : span.spanId) !== null && _c !== void 0 ? _c : generateId();
|
|
662
|
+
const correlationId = (_f = (_e = (_d = read('x-correlation-id')) !== null && _d !== void 0 ? _d : read('x-amzn-trace-id')) !== null && _e !== void 0 ? _e : span.traceId) !== null && _f !== void 0 ? _f : requestId;
|
|
663
|
+
const ids = { request_id: requestId, correlation_id: correlationId };
|
|
664
|
+
if (span.traceId) {
|
|
665
|
+
ids.trace_id = span.traceId;
|
|
666
|
+
}
|
|
667
|
+
if (span.spanId) {
|
|
668
|
+
ids.span_id = span.spanId;
|
|
669
|
+
}
|
|
670
|
+
return ids;
|
|
268
671
|
}
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
672
|
+
/**
|
|
673
|
+
* The active span's ids, or an empty object when OpenTelemetry is not in play.
|
|
674
|
+
*
|
|
675
|
+
* `@opentelemetry/api` is an optional peer dependency, and this module is reachable from
|
|
676
|
+
* every runtime entry point, so it is loaded on demand and any failure to resolve it is
|
|
677
|
+
* treated as "no tracing configured" rather than an error.
|
|
678
|
+
*/
|
|
679
|
+
async function activeSpanIds() {
|
|
680
|
+
var _a;
|
|
681
|
+
try {
|
|
682
|
+
const { trace } = await import('@opentelemetry/api');
|
|
683
|
+
const spanContext = (_a = trace.getActiveSpan()) === null || _a === void 0 ? void 0 : _a.spanContext();
|
|
684
|
+
if (!spanContext) {
|
|
685
|
+
return {};
|
|
686
|
+
}
|
|
687
|
+
return { traceId: spanContext.traceId, spanId: spanContext.spanId };
|
|
688
|
+
}
|
|
689
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
690
|
+
catch (error) {
|
|
691
|
+
return {};
|
|
692
|
+
}
|
|
272
693
|
}
|
|
273
694
|
// Pages Router: headers are a Node bag (Pages routes are Node-only, never edge).
|
|
274
|
-
function seedNodeRequestEventContext(headers) {
|
|
275
|
-
return seedIds((name) => readNodeHeader(headers, name));
|
|
276
|
-
}
|
|
277
|
-
function now() {
|
|
278
|
-
return typeof performance !== 'undefined' ? performance.now() : Date.now();
|
|
695
|
+
function seedNodeRequestEventContext(headers, span = {}) {
|
|
696
|
+
return seedIds((name) => readNodeHeader(headers, name), span);
|
|
279
697
|
}
|
|
280
698
|
// Mirrors Util.resolveInsights from @honeybadger-io/core: the master gate and
|
|
281
699
|
// the per-source flag must both be on.
|
|
@@ -283,143 +701,44 @@ function insightsHttpEnabled() {
|
|
|
283
701
|
const insights = Honeybadger.config.insights;
|
|
284
702
|
return (insights === null || insights === void 0 ? void 0 : insights.enabled) === true && (insights === null || insights === void 0 ? void 0 : insights.http) === true;
|
|
285
703
|
}
|
|
286
|
-
// The ids are embedded directly in the payload (instead of relying on the
|
|
287
|
-
// store's eventContext merge) so the event carries them even on the edge
|
|
288
|
-
// runtime, where there is no per-request store isolation. On the Node.js
|
|
289
|
-
// runtime they match the seeded event context, so embedding is a no-op.
|
|
290
|
-
function emitHandledEvent(method, path, status, start, ids) {
|
|
291
|
-
const payload = {
|
|
292
|
-
method,
|
|
293
|
-
duration: Math.round(now() - start),
|
|
294
|
-
...ids,
|
|
295
|
-
};
|
|
296
|
-
if (typeof path === 'string') {
|
|
297
|
-
payload.path = path;
|
|
298
|
-
}
|
|
299
|
-
if (typeof status === 'number') {
|
|
300
|
-
payload.status = status;
|
|
301
|
-
}
|
|
302
|
-
Honeybadger.event('request.handled', payload);
|
|
303
|
-
}
|
|
304
|
-
// App Router / middleware: `req.url` is absolute, so parse out the pathname.
|
|
305
|
-
function emitRequestEvent(req, status, start, ids) {
|
|
306
|
-
let path;
|
|
307
|
-
try {
|
|
308
|
-
path = new URL(req.url).pathname;
|
|
309
|
-
}
|
|
310
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
311
|
-
catch (error) {
|
|
312
|
-
// relative or malformed URL — leave path unset
|
|
313
|
-
}
|
|
314
|
-
emitHandledEvent(req.method, path, status, start, ids);
|
|
315
|
-
}
|
|
316
|
-
// Pages Router: `req.url` is a relative path that may carry a query string.
|
|
317
|
-
function emitNodeRequestEvent(req, status, start, ids) {
|
|
318
|
-
const path = typeof req.url === 'string' ? req.url.split('?')[0] : undefined;
|
|
319
|
-
emitHandledEvent(req.method, path, status, start, ids);
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
/**
|
|
323
|
-
* The `waitUntil` primitive the hosting platform injects per request. Next.js
|
|
324
|
-
* resolves `after()` through this same accessor, and it is the only channel
|
|
325
|
-
* available in Pages Router API routes, which are invoked as `(req, res)` with
|
|
326
|
-
* no context argument to read it from.
|
|
327
|
-
*/
|
|
328
|
-
function requestContextWaitUntil() {
|
|
329
|
-
var _a, _b;
|
|
330
|
-
const context = globalThis[Symbol.for('@next/request-context')];
|
|
331
|
-
const waitUntil = (_b = (_a = context === null || context === void 0 ? void 0 : context.get) === null || _a === void 0 ? void 0 : _a.call(context)) === null || _b === void 0 ? void 0 : _b.waitUntil;
|
|
332
|
-
return typeof waitUntil === 'function' ? waitUntil : undefined;
|
|
333
|
-
}
|
|
334
|
-
/**
|
|
335
|
-
* Middleware receives a `NextFetchEvent` as its second argument. Duck-typed
|
|
336
|
-
* rather than `instanceof` so the edge bundle needs no runtime import, and
|
|
337
|
-
* bound because `waitUntil` is a class method that collects into the event.
|
|
338
|
-
*/
|
|
339
|
-
function eventWaitUntil(event) {
|
|
340
|
-
const waitUntil = event === null || event === void 0 ? void 0 : event.waitUntil;
|
|
341
|
-
return typeof waitUntil === 'function' ? waitUntil.bind(event) : undefined;
|
|
342
|
-
}
|
|
343
704
|
/**
|
|
344
|
-
*
|
|
345
|
-
*
|
|
346
|
-
*
|
|
347
|
-
*
|
|
348
|
-
* it needs App Router request context, so Pages Router must not call it), then
|
|
349
|
-
* a `waitUntil` from the middleware event or the platform request context,
|
|
350
|
-
* then a blocking `flushAsync()` when the runtime offers neither. Blocking is
|
|
351
|
-
* correct in that last case: no `waitUntil` means nothing is going to freeze
|
|
352
|
-
* the invocation out from under us.
|
|
705
|
+
* OpenTelemetry path. Header values are not on the span by default; they arrive as
|
|
706
|
+
* `http.request.header.*` attributes when the HTTP instrumentation is configured with
|
|
707
|
+
* `headersToSpanAttributes`. Hyphens become underscores under the older semantic
|
|
708
|
+
* conventions and are preserved under the stable ones, so both spellings are read.
|
|
353
709
|
*
|
|
354
|
-
*
|
|
710
|
+
* When no header is present the span and trace ids are used, so the ids stay
|
|
711
|
+
* meaningful — and joinable to a trace — on platforms where the HTTP layer is not
|
|
712
|
+
* visible, such as serverless platforms.
|
|
355
713
|
*/
|
|
356
|
-
function
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
return;
|
|
368
|
-
}
|
|
369
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
370
|
-
catch (error) {
|
|
371
|
-
// try waitUntil / blocking flush below
|
|
714
|
+
function seedSpanEventContext(attributes, spanContext) {
|
|
715
|
+
const read = (name) => {
|
|
716
|
+
const lower = name.toLowerCase();
|
|
717
|
+
for (const key of [
|
|
718
|
+
`http.request.header.${lower}`,
|
|
719
|
+
`http.request.header.${lower.replace(/-/g, '_')}`,
|
|
720
|
+
]) {
|
|
721
|
+
const value = attributes[key];
|
|
722
|
+
const first = Array.isArray(value) ? value[0] : value;
|
|
723
|
+
if (typeof first === 'string' && first.trim().length) {
|
|
724
|
+
return first.trim();
|
|
372
725
|
}
|
|
373
726
|
}
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
}
|
|
380
|
-
return flush();
|
|
381
|
-
}
|
|
382
|
-
function configure(overrides) {
|
|
383
|
-
var _a;
|
|
384
|
-
if (((_a = Honeybadger.config.apiKey) === null || _a === void 0 ? void 0 : _a.length) > 0) {
|
|
385
|
-
return;
|
|
386
|
-
}
|
|
387
|
-
let projectRoot = undefined;
|
|
388
|
-
try {
|
|
389
|
-
// not available on edge runtime
|
|
390
|
-
projectRoot = process.cwd();
|
|
391
|
-
}
|
|
392
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
393
|
-
catch (error) {
|
|
394
|
-
// do nothing
|
|
395
|
-
}
|
|
396
|
-
Honeybadger
|
|
397
|
-
.configure({
|
|
398
|
-
apiKey: process.env.NEXT_PUBLIC_HONEYBADGER_API_KEY,
|
|
399
|
-
environment: process.env.NEXT_PUBLIC_VERCEL_ENV || process.env.VERCEL_ENV || process.env.NODE_ENV,
|
|
400
|
-
revision: process.env.NEXT_PUBLIC_HONEYBADGER_REVISION,
|
|
401
|
-
projectRoot: 'webpack://_N_E/./',
|
|
402
|
-
...overrides,
|
|
403
|
-
})
|
|
404
|
-
.beforeNotify((notice) => {
|
|
405
|
-
if (!projectRoot) {
|
|
406
|
-
return;
|
|
407
|
-
}
|
|
408
|
-
notice === null || notice === void 0 ? void 0 : notice.backtrace.forEach((line) => {
|
|
409
|
-
if (line.file) {
|
|
410
|
-
line.file = line.file.replace(`${projectRoot}/.next/server`, `${process.env.NEXT_PUBLIC_HONEYBADGER_ASSETS_URL}/..`);
|
|
411
|
-
}
|
|
412
|
-
return line;
|
|
413
|
-
});
|
|
727
|
+
return undefined;
|
|
728
|
+
};
|
|
729
|
+
return seedIds(read, {
|
|
730
|
+
traceId: spanContext.traceId || undefined,
|
|
731
|
+
spanId: spanContext.spanId || undefined,
|
|
414
732
|
});
|
|
415
733
|
}
|
|
734
|
+
|
|
416
735
|
/**
|
|
417
736
|
* Next.js uses thrown errors for control flow: `redirect()`, `notFound()`,
|
|
418
737
|
* `forbidden()` and `unauthorized()` all throw an error carrying a `digest`
|
|
419
738
|
* string (`NEXT_REDIRECT;...`, `NEXT_NOT_FOUND`, `NEXT_HTTP_ERROR_FALLBACK;...`).
|
|
420
739
|
* These are not real failures — the framework catches them upstream to produce
|
|
421
|
-
* the redirect/404/etc. — so we must let them
|
|
422
|
-
*
|
|
740
|
+
* the redirect/404/etc. — so we must let them pass without reporting, otherwise
|
|
741
|
+
* every redirect shows up as an error in Honeybadger.
|
|
423
742
|
*
|
|
424
743
|
* We match on the `NEXT_` prefix rather than an exhaustive list so that any
|
|
425
744
|
* present or future framework control-flow digest is covered. This is safe:
|
|
@@ -432,120 +751,244 @@ function isNextControlFlowError(error) {
|
|
|
432
751
|
return typeof digest === 'string' && digest.startsWith('NEXT_');
|
|
433
752
|
}
|
|
434
753
|
/**
|
|
435
|
-
*
|
|
436
|
-
*
|
|
437
|
-
*
|
|
438
|
-
*
|
|
754
|
+
* Reports errors passed to Next.js's `onRequestError` instrumentation hook.
|
|
755
|
+
*
|
|
756
|
+
* Wire it up in `instrumentation.ts`:
|
|
757
|
+
*
|
|
758
|
+
* ```ts
|
|
759
|
+
* export const onRequestError = captureRequestError
|
|
760
|
+
* ```
|
|
761
|
+
*
|
|
762
|
+
* Reaches Server Components, Route Handlers, Server Actions and middleware, and receives
|
|
763
|
+
* the real error rather than the generic message Next.js hands to an error component.
|
|
439
764
|
*/
|
|
440
|
-
function
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
765
|
+
async function captureRequestError(error, request, context) {
|
|
766
|
+
if (isNextControlFlowError(error)) {
|
|
767
|
+
return;
|
|
768
|
+
}
|
|
769
|
+
// Same header precedence *and* the same span as the Insights path, so a fault and the
|
|
770
|
+
// events from the request it failed in carry matching ids. Next.js still has the request
|
|
771
|
+
// span active when it calls this hook, and it is the very span the Insights processor
|
|
772
|
+
// maps to `request.handled` — so with no id headers present all four ids are identical on
|
|
773
|
+
// both, and the fault joins its request's events and trace.
|
|
774
|
+
//
|
|
775
|
+
// Deliberately not written to the event context: outside a `Honeybadger.run()` that
|
|
776
|
+
// lands on a store shared by the whole process or isolate, so the ids would leak into
|
|
777
|
+
// later requests' events. `onRequestError` also fires after the request has already
|
|
778
|
+
// failed, so it is too late to decorate that request's own events anyway.
|
|
779
|
+
const ids = seedNodeRequestEventContext(request.headers, await activeSpanIds());
|
|
780
|
+
await Honeybadger.notifyAsync(error, {
|
|
781
|
+
context: {
|
|
782
|
+
...ids,
|
|
783
|
+
path: request.path,
|
|
784
|
+
method: request.method,
|
|
785
|
+
router_kind: context.routerKind,
|
|
786
|
+
route_path: context.routePath,
|
|
787
|
+
route_type: context.routeType,
|
|
788
|
+
},
|
|
789
|
+
});
|
|
790
|
+
await scheduleFlush({ useAfter: true });
|
|
445
791
|
}
|
|
792
|
+
|
|
793
|
+
// Deliberately @honeybadger-io/js, not @honeybadger-io/react. The react package re-exports
|
|
446
794
|
/**
|
|
447
|
-
* App Router
|
|
448
|
-
*
|
|
795
|
+
* Records App Router navigations as breadcrumbs, so a fault carries the trail of routes
|
|
796
|
+
* the user visited before it.
|
|
449
797
|
*
|
|
450
|
-
*
|
|
451
|
-
*
|
|
798
|
+
* Wire it up in `instrumentation-client.ts`:
|
|
799
|
+
*
|
|
800
|
+
* ```ts
|
|
801
|
+
* export const onRouterTransitionStart = captureRouterTransitionStart
|
|
802
|
+
* ```
|
|
803
|
+
*
|
|
804
|
+
* Exported as a ready-made handler rather than left as a function for the template to
|
|
805
|
+
* declare, so the generated file works unchanged as both `.js` and `.ts` — an assignment
|
|
806
|
+
* has no parameters to annotate, so there is no implicit `any` for `noImplicitAny` to
|
|
807
|
+
* reject.
|
|
452
808
|
*/
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
}
|
|
458
|
-
const start = insightsHttpEnabled() ? now() : null;
|
|
459
|
-
try {
|
|
460
|
-
const response = await call();
|
|
461
|
-
if (start !== null) {
|
|
462
|
-
emitRequestEvent(req, response === null || response === void 0 ? void 0 : response.status, start, ids);
|
|
463
|
-
await scheduleFlush({ useAfter: true, waitUntil });
|
|
464
|
-
}
|
|
465
|
-
return response;
|
|
466
|
-
}
|
|
467
|
-
catch (error) {
|
|
468
|
-
if (isNextControlFlowError(error)) {
|
|
469
|
-
throw error;
|
|
470
|
-
}
|
|
471
|
-
if (start !== null) {
|
|
472
|
-
emitRequestEvent(req, 500, start, ids);
|
|
473
|
-
await scheduleFlush({ useAfter: true, waitUntil });
|
|
474
|
-
}
|
|
475
|
-
await Honeybadger.notifyAsync(error);
|
|
476
|
-
throw error;
|
|
477
|
-
}
|
|
809
|
+
function captureRouterTransitionStart(url, navigationType) {
|
|
810
|
+
Honeybadger.addBreadcrumb(`Navigated to ${url}`, {
|
|
811
|
+
category: 'navigation',
|
|
812
|
+
metadata: { url, navigationType },
|
|
813
|
+
});
|
|
478
814
|
}
|
|
815
|
+
|
|
479
816
|
/**
|
|
480
|
-
*
|
|
481
|
-
*
|
|
482
|
-
*
|
|
817
|
+
* Next.js instruments itself with OpenTelemetry and emits one root span per request,
|
|
818
|
+
* `[http.method] [next.route]`, tagged `next.span_type: BaseServer.handleRequest`. Its
|
|
819
|
+
* attributes carry the method, route, target and status, so mapping that span to a
|
|
820
|
+
* `request.handled` event reports every request without wrapping any handler.
|
|
821
|
+
*
|
|
822
|
+
* Next instruments but does not export: spans only reach us once a tracer provider with
|
|
823
|
+
* this processor is registered. See `registerHoneybadgerInsights`.
|
|
483
824
|
*/
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
825
|
+
const NEXT_REQUEST_SPAN_TYPE = 'BaseServer.handleRequest';
|
|
826
|
+
/**
|
|
827
|
+
* Request headers to copy onto the root span, so `request_id` and `correlation_id` can be
|
|
828
|
+
* reused from an inbound request instead of falling back to the span and trace ids.
|
|
829
|
+
*
|
|
830
|
+
* Header values are not span attributes by default. `@vercel/otel` applies this map when
|
|
831
|
+
* it creates the root span, which is the span this processor reads — and, unlike Node's
|
|
832
|
+
* HTTP instrumentation, it works on serverless platforms too.
|
|
833
|
+
*
|
|
834
|
+
* Spread it into your own `registerOTel` call if you register OpenTelemetry yourself:
|
|
835
|
+
*
|
|
836
|
+
* ```ts
|
|
837
|
+
* registerOTel({
|
|
838
|
+
* attributesFromHeaders: { ...HONEYBADGER_HEADER_ATTRIBUTES },
|
|
839
|
+
* spanProcessors: [honeybadgerSpanProcessor()],
|
|
840
|
+
* })
|
|
841
|
+
* ```
|
|
842
|
+
*
|
|
843
|
+
* Keep the header names in sync with `seedIds` in ./insights-instrumentation.
|
|
844
|
+
*/
|
|
845
|
+
const HONEYBADGER_HEADER_ATTRIBUTES = {
|
|
846
|
+
'http.request.header.x-request-id': 'x-request-id',
|
|
847
|
+
'http.request.header.request-id': 'request-id',
|
|
848
|
+
'http.request.header.x-correlation-id': 'x-correlation-id',
|
|
849
|
+
'http.request.header.x-amzn-trace-id': 'x-amzn-trace-id',
|
|
850
|
+
};
|
|
851
|
+
function readString(attributes, ...names) {
|
|
852
|
+
for (const name of names) {
|
|
853
|
+
const value = attributes[name];
|
|
854
|
+
if (typeof value === 'string' && value.length) {
|
|
855
|
+
return value;
|
|
497
856
|
}
|
|
498
|
-
return result;
|
|
499
857
|
}
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
858
|
+
return undefined;
|
|
859
|
+
}
|
|
860
|
+
function readNumber(attributes, ...names) {
|
|
861
|
+
for (const name of names) {
|
|
862
|
+
const value = attributes[name];
|
|
863
|
+
if (typeof value === 'number') {
|
|
864
|
+
return value;
|
|
503
865
|
}
|
|
504
|
-
if (
|
|
505
|
-
|
|
506
|
-
await scheduleFlush({ useAfter: false });
|
|
866
|
+
if (typeof value === 'string' && value.trim().length && Number.isFinite(Number(value))) {
|
|
867
|
+
return Number(value);
|
|
507
868
|
}
|
|
508
|
-
await Honeybadger.notifyAsync(error);
|
|
509
|
-
throw error;
|
|
510
869
|
}
|
|
870
|
+
return undefined;
|
|
871
|
+
}
|
|
872
|
+
function durationMs(duration) {
|
|
873
|
+
if (!Array.isArray(duration) || duration.length !== 2) {
|
|
874
|
+
return 0;
|
|
875
|
+
}
|
|
876
|
+
const [seconds, nanos] = duration;
|
|
877
|
+
return Math.round(seconds * 1000 + nanos / 1e6);
|
|
878
|
+
}
|
|
879
|
+
/**
|
|
880
|
+
* Path without the query string. `http.target` includes the query under the older
|
|
881
|
+
* semantic conventions; `url.path` is already bare under the stable ones.
|
|
882
|
+
*/
|
|
883
|
+
function readPath(attributes) {
|
|
884
|
+
const target = readString(attributes, 'url.path', 'http.target');
|
|
885
|
+
return typeof target === 'string' ? target.split('?')[0] : undefined;
|
|
886
|
+
}
|
|
887
|
+
/**
|
|
888
|
+
* Maps Next.js's per-request span to a Honeybadger `request.handled` Insights event.
|
|
889
|
+
*
|
|
890
|
+
* Pass it to whatever registers OpenTelemetry in your `instrumentation.ts`:
|
|
891
|
+
*
|
|
892
|
+
* ```ts
|
|
893
|
+
* import { registerOTel } from '@vercel/otel'
|
|
894
|
+
* import { honeybadgerSpanProcessor } from '@honeybadger-io/nextjs'
|
|
895
|
+
*
|
|
896
|
+
* export function register() {
|
|
897
|
+
* registerOTel({ serviceName: 'my-app', spanProcessors: [honeybadgerSpanProcessor()] })
|
|
898
|
+
* }
|
|
899
|
+
* ```
|
|
900
|
+
*
|
|
901
|
+
* `registerHoneybadgerInsights()` is the one-line equivalent when you have no other
|
|
902
|
+
* OpenTelemetry setup of your own.
|
|
903
|
+
*/
|
|
904
|
+
function honeybadgerSpanProcessor() {
|
|
905
|
+
return {
|
|
906
|
+
onStart() {
|
|
907
|
+
// Nothing to do: the event is emitted once the request span is complete, which is
|
|
908
|
+
// when the status and duration are known.
|
|
909
|
+
},
|
|
910
|
+
onEnd(span) {
|
|
911
|
+
var _a;
|
|
912
|
+
const attributes = (_a = span.attributes) !== null && _a !== void 0 ? _a : {};
|
|
913
|
+
if (attributes['next.span_type'] !== NEXT_REQUEST_SPAN_TYPE) {
|
|
914
|
+
return;
|
|
915
|
+
}
|
|
916
|
+
// Checked per event rather than at registration: configuration is loaded by
|
|
917
|
+
// `register()` importing the honeybadger config files, which may happen after the
|
|
918
|
+
// processor is constructed.
|
|
919
|
+
if (!insightsHttpEnabled()) {
|
|
920
|
+
return;
|
|
921
|
+
}
|
|
922
|
+
const spanContext = typeof span.spanContext === 'function' ? span.spanContext() : {};
|
|
923
|
+
const ids = seedSpanEventContext(attributes, spanContext !== null && spanContext !== void 0 ? spanContext : {});
|
|
924
|
+
const payload = {
|
|
925
|
+
method: readString(attributes, 'http.request.method', 'http.method'),
|
|
926
|
+
duration: durationMs(span.duration),
|
|
927
|
+
...ids,
|
|
928
|
+
};
|
|
929
|
+
const path = readPath(attributes);
|
|
930
|
+
if (path) {
|
|
931
|
+
payload.path = path;
|
|
932
|
+
}
|
|
933
|
+
const status = readNumber(attributes, 'http.response.status_code', 'http.status_code');
|
|
934
|
+
if (typeof status === 'number') {
|
|
935
|
+
payload.status = status;
|
|
936
|
+
}
|
|
937
|
+
// Emitted alongside the ids rather than replacing them, so an event can be joined
|
|
938
|
+
// to a trace in another tool without changing what existing consumers read.
|
|
939
|
+
if (spanContext === null || spanContext === void 0 ? void 0 : spanContext.traceId) {
|
|
940
|
+
payload.trace_id = spanContext.traceId;
|
|
941
|
+
}
|
|
942
|
+
if (spanContext === null || spanContext === void 0 ? void 0 : spanContext.spanId) {
|
|
943
|
+
payload.span_id = spanContext.spanId;
|
|
944
|
+
}
|
|
945
|
+
Honeybadger.event('request.handled', payload);
|
|
946
|
+
// A span processor batches on its own lifecycle, which is not enough on a platform
|
|
947
|
+
// that can freeze the invocation as soon as the response is sent.
|
|
948
|
+
scheduleFlush({ useAfter: true });
|
|
949
|
+
},
|
|
950
|
+
async forceFlush() {
|
|
951
|
+
await Honeybadger.flushAsync().catch(() => { });
|
|
952
|
+
},
|
|
953
|
+
async shutdown() {
|
|
954
|
+
await Honeybadger.flushAsync().catch(() => { });
|
|
955
|
+
},
|
|
956
|
+
};
|
|
511
957
|
}
|
|
512
958
|
/**
|
|
513
|
-
*
|
|
514
|
-
*
|
|
959
|
+
* Registers OpenTelemetry with only Honeybadger's span processor attached, for apps that
|
|
960
|
+
* have no OpenTelemetry setup of their own. Call it from `register()` in
|
|
961
|
+
* `instrumentation.ts`.
|
|
962
|
+
*
|
|
963
|
+
* `@vercel/otel` is an optional peer dependency: it is only needed for Insights, and it
|
|
964
|
+
* loads where the full Node SDK cannot, such as serverless platforms. If you
|
|
965
|
+
* already call `registerOTel` yourself, add `honeybadgerSpanProcessor()` to your
|
|
966
|
+
* `spanProcessors` instead of calling this — registering twice would compete for the
|
|
967
|
+
* global provider.
|
|
515
968
|
*/
|
|
516
|
-
async function
|
|
969
|
+
async function registerHoneybadgerInsights(options = {}) {
|
|
970
|
+
var _a, _b;
|
|
971
|
+
let registerOTel;
|
|
517
972
|
try {
|
|
518
|
-
|
|
973
|
+
({ registerOTel } = await import('@vercel/otel'));
|
|
519
974
|
}
|
|
975
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
520
976
|
catch (error) {
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
await Honeybadger.notifyAsync(error);
|
|
525
|
-
throw error;
|
|
977
|
+
Honeybadger.logger.error('[Honeybadger] Insights request events need @vercel/otel. Install it, or drop the ' +
|
|
978
|
+
'registerHoneybadgerInsights() call — error reporting works without it.');
|
|
979
|
+
return;
|
|
526
980
|
}
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
const invoke = () => {
|
|
535
|
-
// App Router / middleware first: a web Request as the first argument.
|
|
536
|
-
if (typeof Request !== 'undefined' && args[0] instanceof Request) {
|
|
537
|
-
return handleAppRouterRequest(call, args[0], canIsolate, eventWaitUntil(args[1]));
|
|
538
|
-
}
|
|
539
|
-
// Pages Router API route: a Node req/res pair.
|
|
540
|
-
if (isPagesApiInvocation(args)) {
|
|
541
|
-
return handlePagesApiRequest(call, args[0], args[1], canIsolate);
|
|
542
|
-
}
|
|
543
|
-
return handleUninstrumented(call);
|
|
544
|
-
};
|
|
545
|
-
return canIsolate ? Honeybadger.run(invoke) : invoke();
|
|
981
|
+
registerOTel({
|
|
982
|
+
serviceName: (_b = (_a = options.serviceName) !== null && _a !== void 0 ? _a : process.env.NEXT_PUBLIC_HONEYBADGER_SERVICE_NAME) !== null && _b !== void 0 ? _b : 'nextjs-app',
|
|
983
|
+
// Without this the id headers never reach the span, so request_id and
|
|
984
|
+
// correlation_id would always fall back to the span and trace ids.
|
|
985
|
+
attributesFromHeaders: {
|
|
986
|
+
...HONEYBADGER_HEADER_ATTRIBUTES,
|
|
987
|
+
...options.attributesFromHeaders,
|
|
546
988
|
},
|
|
989
|
+
spanProcessors: [honeybadgerSpanProcessor()],
|
|
547
990
|
});
|
|
548
991
|
}
|
|
549
992
|
|
|
550
|
-
export {
|
|
993
|
+
export { HONEYBADGER_HEADER_ATTRIBUTES, captureRequestError, captureRouterTransitionStart, honeybadgerSpanProcessor, registerHoneybadgerInsights, withHoneybadgerConfig };
|
|
551
994
|
//# sourceMappingURL=honeybadger-nextjs.esm.js.map
|