@honeybadger-io/nextjs 5.11.6 → 6.0.1

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