@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
@@ -1,204 +1,597 @@
1
1
  import fs from 'fs';
2
+ import os from 'os';
2
3
  import path from 'path';
3
- import HoneybadgerSourceMapPlugin from '@honeybadger-io/webpack';
4
+ import picomatch from 'picomatch';
4
5
  import Honeybadger from '@honeybadger-io/js';
5
6
  import * as nextServer from 'next/server';
6
7
 
7
- const URL_DOCS_SOURCE_MAPS_UPLOAD = 'https://docs.honeybadger.io/lib/javascript/integration/nextjs/#source-map-upload-and-tracking-deploys';
8
- let _silent = true;
9
- function log(type, msg) {
10
- if (['error', 'warn'].includes(type) || !_silent) {
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
- function shouldUploadSourceMaps(honeybadgerNextJsConfig, context) {
15
- const { dev } = context;
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
- if (!honeybadgerNextJsConfig.webpackPluginOptions || !honeybadgerNextJsConfig.webpackPluginOptions.apiKey) {
20
- log('warn', `skipping source map upload; here's how to enable: ${URL_DOCS_SOURCE_MAPS_UPLOAD}`);
21
- return false;
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
- if (dev || process.env.NODE_ENV === 'development') {
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 true;
103
+ return developmentEnvironments.includes(process.env.NODE_ENV);
27
104
  }
28
- function mergeWithExistingWebpackConfig(nextJsWebpackConfig, honeybadgerNextJsConfig) {
29
- return function webpackFunctionMergedWithHb(webpackConfig, context) {
30
- const { isServer, dir: projectDir, nextRuntime } = context;
31
- const configType = isServer ? (nextRuntime === 'edge' ? 'edge' : 'server') : 'browser';
32
- log('debug', `reached webpackFunctionMergedWithHb isServer[${isServer}] configType[${configType}]`);
33
- let result = { ...webpackConfig };
34
- if (typeof nextJsWebpackConfig === 'function') {
35
- result = nextJsWebpackConfig(result, context);
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
- const originalEntry = result.entry;
38
- result.entry = async () => injectHoneybadgerConfigToEntry(originalEntry, projectDir, configType);
39
- if (shouldUploadSourceMaps(honeybadgerNextJsConfig, context)) {
40
- // `result.devtool` must be 'hidden-source-map' or 'source-map' to properly pass sourcemaps.
41
- // Next.js uses regular `source-map` which doesnt pass its sourcemaps to Webpack.
42
- // https://github.com/vercel/next.js/blob/89ec21ed686dd79a5770b5c669abaff8f55d8fef/packages/next/build/webpack/config/blocks/base.ts#L40
43
- // Use the hidden-source-map option when you don't want the source maps to be
44
- // publicly available on the servers, only to the error reporting
45
- result.devtool = 'hidden-source-map';
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
- const hbConfigFileRelativePath = `./${hbConfigFile}`;
64
- if (!Object.keys(result).length) {
65
- log('debug', `no entry points for configType[${configType}]`);
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
- for (const entryName in result) {
68
- addHoneybadgerConfigToEntry(result, entryName, hbConfigFileRelativePath, configType);
141
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
142
+ catch (error) {
143
+ return false;
69
144
  }
70
- return result;
71
145
  }
72
- function addHoneybadgerConfigToEntry(entry, entryName, hbConfigFile, configType) {
73
- log('debug', `adding entry[${entryName}] to configType[${configType}]`);
74
- switch (configType) {
75
- case 'server':
76
- if (!entryName.startsWith('pages/')) {
77
- return;
78
- }
79
- break;
80
- case 'browser':
81
- if (!['pages/_app', 'main-app'].includes(entryName)) {
82
- return;
83
- }
84
- break;
85
- }
86
- const currentEntryPoint = entry[entryName];
87
- let newEntryPoint = currentEntryPoint;
88
- if (typeof currentEntryPoint === 'string') {
89
- newEntryPoint = [hbConfigFile, currentEntryPoint];
90
- }
91
- else if (Array.isArray(currentEntryPoint)) {
92
- newEntryPoint = [hbConfigFile, ...currentEntryPoint];
93
- } // descriptor object (webpack 5+)
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
- else {
101
- newImportValue.push(...(currentImportValue));
169
+ finally {
170
+ await handle.close();
102
171
  }
103
- newEntryPoint = {
104
- ...currentEntryPoint,
105
- import: newImportValue,
106
- };
107
172
  }
108
- else {
109
- log('error', 'Could not inject Honeybadger config to entry point: ' + JSON.stringify(currentEntryPoint, null, 2));
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
- entry[entryName] = newEntryPoint;
197
+ const sourcemapFilePath = path.resolve(path.dirname(jsFilePath), decodedUrl);
198
+ return fs.existsSync(sourcemapFilePath) ? sourcemapFilePath : null;
112
199
  }
113
- function getHoneybadgerConfigFile(projectDir, configType) {
114
- const possibilities = [`honeybadger.${configType}.config.ts`, `honeybadger.${configType}.config.js`];
115
- for (const filename of possibilities) {
116
- if (fs.existsSync(path.resolve(projectDir, filename))) {
117
- return filename;
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
- log('debug', `could not find config file in ${projectDir} for ${configType}`);
121
- return null;
244
+ return collected;
122
245
  }
123
- function getWebpackPluginOptions(honeybadgerNextJsConfig) {
124
- var _a, _b, _c;
125
- const apiKey = ((_a = honeybadgerNextJsConfig.webpackPluginOptions) === null || _a === void 0 ? void 0 : _a.apiKey) || process.env.NEXT_PUBLIC_HONEYBADGER_API_KEY;
126
- const assetsUrl = ((_b = honeybadgerNextJsConfig.webpackPluginOptions) === null || _b === void 0 ? void 0 : _b.assetsUrl) || process.env.NEXT_PUBLIC_HONEYBADGER_ASSETS_URL;
127
- if (!apiKey || !assetsUrl) {
128
- log('error', 'Missing Honeybadger required configuration for webpack plugin. Source maps will not be uploaded to Honeybadger.');
129
- return null;
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
- function getNextJsVersionInstalled() {
140
- var _a;
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
- return (_a = require('next/package.json').version) === null || _a === void 0 ? void 0 : _a.split('.');
288
+ tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'honeybadger-sourcemaps-'));
143
289
  }
144
- catch (e) {
145
- return null;
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
- * NextJs will report a warning if the `serverExternalPackages` option is not present.
150
- * This is because @honeybadger-io/js will try to require configuration files dynamically (https://github.com/honeybadger-io/honeybadger-js/pull/1268).
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
- * First reported here: https://github.com/honeybadger-io/honeybadger-js/issues/1351
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 addServerExternalPackagesOption(config) {
155
- var _a, _b;
156
- // this should be available in the upcoming version of Next.js (14.3.0)
157
- if (config.serverExternalPackages && Array.isArray(config.serverExternalPackages)) {
158
- log('debug', 'adding @honeybadger-io/js to serverExternalPackages');
159
- config.serverExternalPackages.push('@honeybadger-io/js');
160
- return;
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
- 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)) {
163
- log('debug', 'adding @honeybadger-io/js to experimental.serverComponentsExternalPackages');
164
- config.experimental.serverComponentsExternalPackages.push('@honeybadger-io/js');
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
- const nextJsVersion = getNextJsVersionInstalled();
168
- if (nextJsVersion) {
169
- if ((+nextJsVersion[0] === 14 && +nextJsVersion[1] >= 3) || +nextJsVersion[0] > 14) {
170
- log('debug', 'adding serverExternalPackages option with value ["@honeybadger-io/js"]');
171
- config.serverExternalPackages = ['@honeybadger-io/js'];
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
- else {
174
- log('debug', 'adding experimental.serverComponentsExternalPackages option with value ["@honeybadger-io/js"]');
175
- if (!config.experimental) {
176
- config.experimental = {};
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
- function setupHoneybadger(config, honeybadgerNextJsConfig) {
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
- if (!honeybadgerNextJsConfig) {
185
- honeybadgerNextJsConfig = {
186
- silent: true,
187
- disableSourceMapUpload: false,
188
- };
189
- }
190
- _silent = (_a = honeybadgerNextJsConfig.silent) !== null && _a !== void 0 ? _a : true;
191
- addServerExternalPackagesOption(config);
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
- webpack: mergeWithExistingWebpackConfig(config.webpack, honeybadgerNextJsConfig)
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 also load on the edge runtime where
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
- // Shared id precedence. Kept in one place (rather than once per request shape)
262
- // so the header-name contract documented above is only spelled out once.
263
- function seedIds(read) {
264
- var _a, _b, _c, _d;
265
- const requestId = (_b = (_a = read('x-request-id')) !== null && _a !== void 0 ? _a : read('request-id')) !== null && _b !== void 0 ? _b : generateId();
266
- const correlationId = (_d = (_c = read('x-correlation-id')) !== null && _c !== void 0 ? _c : read('x-amzn-trace-id')) !== null && _d !== void 0 ? _d : requestId;
267
- return { request_id: requestId, correlation_id: correlationId };
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
- // App Router / middleware: headers are a web `Headers` instance.
270
- function seedRequestEventContext(headers) {
271
- return seedIds((name) => readHeader(headers, name));
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
704
  /**
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
- /**
344
- * Ensure Insights events are delivered before the serverless/edge runtime
345
- * freezes, without delaying the response where the runtime lets us avoid it.
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.
346
709
  *
347
- * In order of preference: Next.js `after()` (stable in 15.1, App Router only —
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.
353
- *
354
- * Delivery failures are logged by the events worker and must not break the handler.
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 scheduleFlush(options = {}) {
357
- var _a;
358
- const flush = () => Honeybadger.flushAsync().catch(() => { });
359
- if (options.useAfter) {
360
- const after = nextServer.after;
361
- if (typeof after === 'function') {
362
- // Exported but still refusable: `after()` throws outside a supported
363
- // context. Fall through to the remaining strategies rather than failing
364
- // the request.
365
- try {
366
- after(flush);
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
- const waitUntil = (_a = options.waitUntil) !== null && _a !== void 0 ? _a : requestContextWaitUntil();
376
- if (waitUntil) {
377
- waitUntil(flush());
378
- return;
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 propagate without reporting them,
422
- * otherwise every redirect shows up as an error in Honeybadger.
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,262 @@ function isNextControlFlowError(error) {
432
751
  return typeof digest === 'string' && digest.startsWith('NEXT_');
433
752
  }
434
753
  /**
435
- * Detects a Pages Router API invocation: `(req, res)` where `res` is a Node
436
- * `ServerResponse`. We branch on this structurally because — unlike an App
437
- * Router route handler — there is no returned `Response` to read the status
438
- * from; it lives on `res.statusCode`.
754
+ * The path with any query string removed.
755
+ *
756
+ * Next.js reports `path` with the query attached (`/blog?name=foo`), and this value is
757
+ * written to the user's context, which `filters` never touch.
439
758
  */
440
- function isPagesApiInvocation(args) {
441
- const req = args[0];
442
- const res = args[1];
443
- return (!!req && typeof req.headers === 'object' && req.headers !== null &&
444
- !!res && typeof res.statusCode === 'number' && typeof res.end === 'function');
759
+ function requestPath(path) {
760
+ return typeof path === 'string' ? path.split('?')[0] : path;
445
761
  }
446
762
  /**
447
- * App Router route handlers and middleware: a web `Request`/`NextRequest` in, a
448
- * `Response`/`NextResponse` out. The status comes from the returned response.
763
+ * Reports errors passed to Next.js's `onRequestError` instrumentation hook.
449
764
  *
450
- * `waitUntil` is present for middleware (from its `NextFetchEvent`); route
451
- * handlers get `{ params }` as their second argument and rely on `after()`.
765
+ * Wire it up in `instrumentation.ts`:
766
+ *
767
+ * ```ts
768
+ * export const onRequestError = captureRequestError
769
+ * ```
770
+ *
771
+ * Reaches Server Components, Route Handlers, Server Actions and middleware, and receives
772
+ * the real error rather than the generic message Next.js hands to an error component.
452
773
  */
453
- async function handleAppRouterRequest(call, req, canIsolate, waitUntil) {
454
- const ids = seedRequestEventContext(req.headers);
455
- if (canIsolate) {
456
- Honeybadger.setEventContext(ids);
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;
774
+ async function captureRequestError(error, request, context) {
775
+ if (isNextControlFlowError(error)) {
776
+ return;
477
777
  }
778
+ // Same header precedence *and* the same span as the Insights path, so a fault and the
779
+ // events from the request it failed in carry matching ids. Next.js still has the request
780
+ // span active when it calls this hook, and it is the very span the Insights processor
781
+ // maps to `request.handled` — so with no id headers present all four ids are identical on
782
+ // both, and the fault joins its request's events and trace.
783
+ //
784
+ // Deliberately not written to the event context: outside a `Honeybadger.run()` that
785
+ // lands on a store shared by the whole process or isolate, so the ids would leak into
786
+ // later requests' events. `onRequestError` also fires after the request has already
787
+ // failed, so it is too late to decorate that request's own events anyway.
788
+ const ids = seedNodeRequestEventContext(request.headers, await activeSpanIds());
789
+ await Honeybadger.notifyAsync(error, {
790
+ // The full path, query string included, goes on `url` so the configured `filters` are
791
+ // applied to it -- `filterUrl` runs over this field when the payload is built. Context
792
+ // is deliberately never filtered, since it is the user's own bag, so the copy below is
793
+ // reduced to the bare path rather than repeating an unfiltered query string there.
794
+ url: request.path,
795
+ context: {
796
+ ...ids,
797
+ path: requestPath(request.path),
798
+ method: request.method,
799
+ router_kind: context.routerKind,
800
+ route_path: context.routePath,
801
+ route_type: context.routeType,
802
+ },
803
+ });
804
+ await scheduleFlush({ useAfter: true });
478
805
  }
806
+
807
+ // Deliberately @honeybadger-io/js, not @honeybadger-io/react. The react package re-exports
479
808
  /**
480
- * Pages Router API routes: a Node `req`/`res` pair. The handler writes to `res`
481
- * and returns nothing meaningful, so the final status is read from
482
- * `res.statusCode` once it resolves.
809
+ * Records App Router navigations as breadcrumbs, so a fault carries the trail of routes
810
+ * the user visited before it.
811
+ *
812
+ * Wire it up in `instrumentation-client.ts`:
813
+ *
814
+ * ```ts
815
+ * export const onRouterTransitionStart = captureRouterTransitionStart
816
+ * ```
817
+ *
818
+ * Exported as a ready-made handler rather than left as a function for the template to
819
+ * declare, so the generated file works unchanged as both `.js` and `.ts` — an assignment
820
+ * has no parameters to annotate, so there is no implicit `any` for `noImplicitAny` to
821
+ * reject.
483
822
  */
484
- async function handlePagesApiRequest(call, req, res, canIsolate) {
485
- const ids = seedNodeRequestEventContext(req.headers);
486
- if (canIsolate) {
487
- Honeybadger.setEventContext(ids);
488
- }
489
- const start = insightsHttpEnabled() ? now() : null;
490
- try {
491
- const result = await call();
492
- if (start !== null) {
493
- emitNodeRequestEvent(req, res.statusCode, start, ids);
494
- // No after() here: Pages Router lacks the App Router request context it
495
- // needs. scheduleFlush falls through to the platform waitUntil instead.
496
- await scheduleFlush({ useAfter: false });
823
+ function captureRouterTransitionStart(url, navigationType) {
824
+ // The message carries the path alone and the full URL goes in the metadata, where the
825
+ // configured `filters` are applied to its query string when the payload is built. This is
826
+ // the same split the browser integration already uses for its XHR and fetch breadcrumbs,
827
+ // whose messages are built from `localURLPathname`.
828
+ Honeybadger.addBreadcrumb(`Navigated to ${url.split('?')[0]}`, {
829
+ category: 'navigation',
830
+ metadata: { url, navigationType },
831
+ });
832
+ }
833
+
834
+ /**
835
+ * Next.js instruments itself with OpenTelemetry and emits one root span per request,
836
+ * `[http.method] [next.route]`, tagged `next.span_type: BaseServer.handleRequest`. Its
837
+ * attributes carry the method, route, target and status, so mapping that span to a
838
+ * `request.handled` event reports every request without wrapping any handler.
839
+ *
840
+ * Next instruments but does not export: spans only reach us once a tracer provider with
841
+ * this processor is registered. See `registerHoneybadgerInsights`.
842
+ */
843
+ const NEXT_REQUEST_SPAN_TYPE = 'BaseServer.handleRequest';
844
+ /**
845
+ * Request headers to copy onto the root span, so `request_id` and `correlation_id` can be
846
+ * reused from an inbound request instead of falling back to the span and trace ids.
847
+ *
848
+ * Header values are not span attributes by default. `@vercel/otel` applies this map when
849
+ * it creates the root span, which is the span this processor reads — and, unlike Node's
850
+ * HTTP instrumentation, it works on serverless platforms too.
851
+ *
852
+ * Spread it into your own `registerOTel` call if you register OpenTelemetry yourself:
853
+ *
854
+ * ```ts
855
+ * registerOTel({
856
+ * attributesFromHeaders: { ...HONEYBADGER_HEADER_ATTRIBUTES },
857
+ * spanProcessors: [honeybadgerSpanProcessor()],
858
+ * })
859
+ * ```
860
+ *
861
+ * Keep the header names in sync with `seedIds` in ./insights-instrumentation.
862
+ */
863
+ const HONEYBADGER_HEADER_ATTRIBUTES = {
864
+ 'http.request.header.x-request-id': 'x-request-id',
865
+ 'http.request.header.request-id': 'request-id',
866
+ 'http.request.header.x-correlation-id': 'x-correlation-id',
867
+ 'http.request.header.x-amzn-trace-id': 'x-amzn-trace-id',
868
+ };
869
+ function readString(attributes, ...names) {
870
+ for (const name of names) {
871
+ const value = attributes[name];
872
+ if (typeof value === 'string' && value.length) {
873
+ return value;
497
874
  }
498
- return result;
499
875
  }
500
- catch (error) {
501
- if (isNextControlFlowError(error)) {
502
- throw error;
876
+ return undefined;
877
+ }
878
+ function readNumber(attributes, ...names) {
879
+ for (const name of names) {
880
+ const value = attributes[name];
881
+ if (typeof value === 'number') {
882
+ return value;
503
883
  }
504
- if (start !== null) {
505
- emitNodeRequestEvent(req, 500, start, ids);
506
- await scheduleFlush({ useAfter: false });
884
+ if (typeof value === 'string' && value.trim().length && Number.isFinite(Number(value))) {
885
+ return Number(value);
507
886
  }
508
- await Honeybadger.notifyAsync(error);
509
- throw error;
510
887
  }
888
+ return undefined;
889
+ }
890
+ function durationMs(duration) {
891
+ if (!Array.isArray(duration) || duration.length !== 2) {
892
+ return 0;
893
+ }
894
+ const [seconds, nanos] = duration;
895
+ return Math.round(seconds * 1000 + nanos / 1e6);
896
+ }
897
+ /**
898
+ * Path without the query string. `http.target` includes the query under the older
899
+ * semantic conventions; `url.path` is already bare under the stable ones.
900
+ */
901
+ function readPath(attributes) {
902
+ const target = readString(attributes, 'url.path', 'http.target');
903
+ return typeof target === 'string' ? target.split('?')[0] : undefined;
904
+ }
905
+ /**
906
+ * Maps Next.js's per-request span to a Honeybadger `request.handled` Insights event.
907
+ *
908
+ * Pass it to whatever registers OpenTelemetry in your `instrumentation.ts`:
909
+ *
910
+ * ```ts
911
+ * import { registerOTel } from '@vercel/otel'
912
+ * import { honeybadgerSpanProcessor } from '@honeybadger-io/nextjs'
913
+ *
914
+ * export function register() {
915
+ * registerOTel({ serviceName: 'my-app', spanProcessors: [honeybadgerSpanProcessor()] })
916
+ * }
917
+ * ```
918
+ *
919
+ * `registerHoneybadgerInsights()` is the one-line equivalent when you have no other
920
+ * OpenTelemetry setup of your own.
921
+ */
922
+ function honeybadgerSpanProcessor() {
923
+ return {
924
+ onStart() {
925
+ // Nothing to do: the event is emitted once the request span is complete, which is
926
+ // when the status and duration are known.
927
+ },
928
+ onEnd(span) {
929
+ var _a;
930
+ const attributes = (_a = span.attributes) !== null && _a !== void 0 ? _a : {};
931
+ if (attributes['next.span_type'] !== NEXT_REQUEST_SPAN_TYPE) {
932
+ return;
933
+ }
934
+ // Checked per event rather than at registration: configuration is loaded by
935
+ // `register()` importing the honeybadger config files, which may happen after the
936
+ // processor is constructed.
937
+ if (!insightsHttpEnabled()) {
938
+ return;
939
+ }
940
+ const spanContext = typeof span.spanContext === 'function' ? span.spanContext() : {};
941
+ const ids = seedSpanEventContext(attributes, spanContext !== null && spanContext !== void 0 ? spanContext : {});
942
+ const payload = {
943
+ method: readString(attributes, 'http.request.method', 'http.method'),
944
+ duration: durationMs(span.duration),
945
+ ...ids,
946
+ };
947
+ const path = readPath(attributes);
948
+ if (path) {
949
+ payload.path = path;
950
+ }
951
+ const status = readNumber(attributes, 'http.response.status_code', 'http.status_code');
952
+ if (typeof status === 'number') {
953
+ payload.status = status;
954
+ }
955
+ // Emitted alongside the ids rather than replacing them, so an event can be joined
956
+ // to a trace in another tool without changing what existing consumers read.
957
+ if (spanContext === null || spanContext === void 0 ? void 0 : spanContext.traceId) {
958
+ payload.trace_id = spanContext.traceId;
959
+ }
960
+ if (spanContext === null || spanContext === void 0 ? void 0 : spanContext.spanId) {
961
+ payload.span_id = spanContext.spanId;
962
+ }
963
+ Honeybadger.event('request.handled', payload);
964
+ // A span processor batches on its own lifecycle, which is not enough on a platform
965
+ // that can freeze the invocation as soon as the response is sent.
966
+ scheduleFlush({ useAfter: true });
967
+ },
968
+ async forceFlush() {
969
+ await Honeybadger.flushAsync().catch(() => { });
970
+ },
971
+ async shutdown() {
972
+ await Honeybadger.flushAsync().catch(() => { });
973
+ },
974
+ };
511
975
  }
512
976
  /**
513
- * Unrecognised invocation shape: still report errors, but emit no insights
514
- * event since we can't reliably read the request.
977
+ * Registers OpenTelemetry with only Honeybadger's span processor attached, for apps that
978
+ * have no OpenTelemetry setup of their own. Call it from `register()` in
979
+ * `instrumentation.ts`.
980
+ *
981
+ * `@vercel/otel` is an optional peer dependency: it is only needed for Insights, and it
982
+ * loads where the full Node SDK cannot, such as serverless platforms. If you
983
+ * already call `registerOTel` yourself, add `honeybadgerSpanProcessor()` to your
984
+ * `spanProcessors` instead of calling this — registering twice would compete for the
985
+ * global provider.
515
986
  */
516
- async function handleUninstrumented(call) {
987
+ async function registerHoneybadgerInsights(options = {}) {
988
+ var _a, _b;
989
+ let registerOTel;
517
990
  try {
518
- return await call();
991
+ ({ registerOTel } = await import('@vercel/otel'));
519
992
  }
993
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
520
994
  catch (error) {
521
- if (isNextControlFlowError(error)) {
522
- throw error;
523
- }
524
- await Honeybadger.notifyAsync(error);
525
- throw error;
995
+ Honeybadger.logger.error('[Honeybadger] Insights request events need @vercel/otel. Install it, or drop the ' +
996
+ 'registerHoneybadgerInsights() call — error reporting works without it.');
997
+ return;
526
998
  }
527
- }
528
- function withHoneybadger(handler, config) {
529
- configure(config);
530
- return new Proxy(handler, {
531
- apply: (target, thisArg, args) => {
532
- const canIsolate = typeof Honeybadger.run === 'function';
533
- const call = () => Reflect.apply(target, thisArg, args);
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();
999
+ registerOTel({
1000
+ serviceName: (_b = (_a = options.serviceName) !== null && _a !== void 0 ? _a : process.env.NEXT_PUBLIC_HONEYBADGER_SERVICE_NAME) !== null && _b !== void 0 ? _b : 'nextjs-app',
1001
+ // Without this the id headers never reach the span, so request_id and
1002
+ // correlation_id would always fall back to the span and trace ids.
1003
+ attributesFromHeaders: {
1004
+ ...HONEYBADGER_HEADER_ATTRIBUTES,
1005
+ ...options.attributesFromHeaders,
546
1006
  },
1007
+ spanProcessors: [honeybadgerSpanProcessor()],
547
1008
  });
548
1009
  }
549
1010
 
550
- export { setupHoneybadger, withHoneybadger };
1011
+ export { HONEYBADGER_HEADER_ATTRIBUTES, captureRequestError, captureRouterTransitionStart, honeybadgerSpanProcessor, registerHoneybadgerInsights, withHoneybadgerConfig };
551
1012
  //# sourceMappingURL=honeybadger-nextjs.esm.js.map