@honeybadger-io/nextjs 5.11.5 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -42
- package/dist/capture-request-error.d.ts +35 -0
- package/dist/capture-request-error.test.d.ts +2 -0
- package/dist/capture-router-transition-start.d.ts +21 -0
- package/dist/client.d.ts +2 -0
- package/dist/copy-config-files.js +106 -34
- package/dist/copy-config-files.js.map +1 -1
- package/dist/edge.d.ts +2 -1
- package/dist/flush.d.ts +24 -0
- package/dist/honeybadger-nextjs-client.cjs.js +35 -0
- package/dist/honeybadger-nextjs-client.cjs.js.map +1 -0
- package/dist/honeybadger-nextjs-client.esm.js +27 -0
- package/dist/honeybadger-nextjs-client.esm.js.map +1 -0
- package/dist/honeybadger-nextjs-edge.cjs.js +320 -240
- package/dist/honeybadger-nextjs-edge.cjs.js.map +1 -1
- package/dist/honeybadger-nextjs-edge.esm.js +317 -240
- package/dist/honeybadger-nextjs-edge.esm.js.map +1 -1
- package/dist/honeybadger-nextjs.cjs.js +835 -387
- package/dist/honeybadger-nextjs.cjs.js.map +1 -1
- package/dist/honeybadger-nextjs.esm.js +829 -386
- package/dist/honeybadger-nextjs.esm.js.map +1 -1
- package/dist/index.d.ts +5 -2
- package/dist/insights-instrumentation.d.ts +30 -2
- package/dist/insights.d.ts +72 -0
- package/dist/insights.test.d.ts +2 -0
- package/dist/setup.d.ts +11 -0
- package/dist/setup.test.d.ts +2 -0
- package/dist/source-maps.d.ts +55 -0
- package/dist/source-maps.test.d.ts +2 -0
- package/dist/types.d.ts +20 -8
- package/package.json +34 -12
- package/src/capture-request-error.test.ts +245 -0
- package/src/capture-request-error.ts +92 -0
- package/src/capture-router-transition-start.ts +33 -0
- package/src/client.ts +4 -0
- package/src/copy-config-files.test.ts +250 -16
- package/src/copy-config-files.ts +117 -34
- package/src/edge.ts +12 -1
- package/src/flush.ts +58 -0
- package/src/index.ts +7 -2
- package/src/insights-instrumentation.ts +104 -11
- package/src/insights.test.ts +192 -0
- package/src/insights.ts +225 -0
- package/src/setup.test.ts +214 -0
- package/src/setup.ts +172 -0
- package/src/source-maps.test.ts +803 -0
- package/src/source-maps.ts +515 -0
- package/src/types.ts +38 -21
- package/templates/_error.js +14 -10
- package/templates/_error_app_router.js +1 -1
- package/templates/_error_app_router.tsx +1 -1
- package/templates/honeybadger.server.config.js +5 -16
- package/templates/instrumentation-client.js +21 -0
- package/templates/instrumentation.js +29 -0
- package/dist/webpack.d.ts +0 -3
- package/dist/with-honeybadger.d.ts +0 -32
- package/dist/with-honeybadger.test.d.ts +0 -2
- package/src/webpack.ts +0 -228
- package/src/with-honeybadger.test.ts +0 -527
- package/src/with-honeybadger.ts +0 -286
- package/templates/honeybadger.browser.config.js +0 -13
- package/templates/honeybadger.edge.config.js +0 -13
|
@@ -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
|
|
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
|
|
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
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
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
|
-
|
|
45
|
-
|
|
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
|
-
|
|
50
|
-
|
|
51
|
-
|
|
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
|
-
|
|
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
|
|
134
|
+
return developmentEnvironments.includes(process.env.NODE_ENV);
|
|
57
135
|
}
|
|
58
|
-
function
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
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
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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
|
-
|
|
94
|
-
|
|
95
|
-
|
|
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
|
-
|
|
98
|
-
|
|
172
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
173
|
+
catch (error) {
|
|
174
|
+
return false;
|
|
99
175
|
}
|
|
100
|
-
return result;
|
|
101
176
|
}
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
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
|
-
|
|
131
|
-
|
|
200
|
+
finally {
|
|
201
|
+
await handle.close();
|
|
132
202
|
}
|
|
133
|
-
newEntryPoint = {
|
|
134
|
-
...currentEntryPoint,
|
|
135
|
-
import: newImportValue,
|
|
136
|
-
};
|
|
137
203
|
}
|
|
138
|
-
|
|
139
|
-
|
|
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
|
-
|
|
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
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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
|
-
|
|
151
|
-
return null;
|
|
275
|
+
return collected;
|
|
152
276
|
}
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
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
|
-
|
|
170
|
-
|
|
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
|
-
|
|
319
|
+
tempDir = await fs__default["default"].promises.mkdtemp(path__default["default"].join(os__default["default"].tmpdir(), 'honeybadger-sourcemaps-'));
|
|
173
320
|
}
|
|
174
|
-
|
|
175
|
-
|
|
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
|
-
*
|
|
180
|
-
*
|
|
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
|
-
*
|
|
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
|
|
185
|
-
|
|
186
|
-
//
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
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
|
-
|
|
193
|
-
|
|
194
|
-
|
|
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
|
-
|
|
198
|
-
|
|
199
|
-
if (
|
|
200
|
-
|
|
201
|
-
|
|
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
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
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
|
-
|
|
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
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
function
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
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 (
|
|
330
|
-
|
|
698
|
+
if (span.spanId) {
|
|
699
|
+
ids.span_id = span.spanId;
|
|
331
700
|
}
|
|
332
|
-
|
|
701
|
+
return ids;
|
|
333
702
|
}
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
366
|
-
|
|
367
|
-
|
|
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
|
-
*
|
|
375
|
-
*
|
|
376
|
-
*
|
|
377
|
-
*
|
|
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
|
-
*
|
|
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
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
return;
|
|
398
|
-
}
|
|
399
|
-
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
400
|
-
catch (error) {
|
|
401
|
-
// try waitUntil / blocking flush below
|
|
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();
|
|
402
756
|
}
|
|
403
757
|
}
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
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
|
-
}
|
|
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
|
|
452
|
-
*
|
|
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,249 @@ function isNextControlFlowError(error) {
|
|
|
462
782
|
return typeof digest === 'string' && digest.startsWith('NEXT_');
|
|
463
783
|
}
|
|
464
784
|
/**
|
|
465
|
-
*
|
|
466
|
-
*
|
|
467
|
-
*
|
|
468
|
-
*
|
|
785
|
+
* Reports errors passed to Next.js's `onRequestError` instrumentation hook.
|
|
786
|
+
*
|
|
787
|
+
* Wire it up in `instrumentation.ts`:
|
|
788
|
+
*
|
|
789
|
+
* ```ts
|
|
790
|
+
* export const onRequestError = captureRequestError
|
|
791
|
+
* ```
|
|
792
|
+
*
|
|
793
|
+
* Reaches Server Components, Route Handlers, Server Actions and middleware, and receives
|
|
794
|
+
* the real error rather than the generic message Next.js hands to an error component.
|
|
469
795
|
*/
|
|
470
|
-
function
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
796
|
+
async function captureRequestError(error, request, context) {
|
|
797
|
+
if (isNextControlFlowError(error)) {
|
|
798
|
+
return;
|
|
799
|
+
}
|
|
800
|
+
// Same header precedence *and* the same span as the Insights path, so a fault and the
|
|
801
|
+
// events from the request it failed in carry matching ids. Next.js still has the request
|
|
802
|
+
// span active when it calls this hook, and it is the very span the Insights processor
|
|
803
|
+
// maps to `request.handled` — so with no id headers present all four ids are identical on
|
|
804
|
+
// both, and the fault joins its request's events and trace.
|
|
805
|
+
//
|
|
806
|
+
// Deliberately not written to the event context: outside a `Honeybadger.run()` that
|
|
807
|
+
// lands on a store shared by the whole process or isolate, so the ids would leak into
|
|
808
|
+
// later requests' events. `onRequestError` also fires after the request has already
|
|
809
|
+
// failed, so it is too late to decorate that request's own events anyway.
|
|
810
|
+
const ids = seedNodeRequestEventContext(request.headers, await activeSpanIds());
|
|
811
|
+
await Honeybadger__default["default"].notifyAsync(error, {
|
|
812
|
+
context: {
|
|
813
|
+
...ids,
|
|
814
|
+
path: request.path,
|
|
815
|
+
method: request.method,
|
|
816
|
+
router_kind: context.routerKind,
|
|
817
|
+
route_path: context.routePath,
|
|
818
|
+
route_type: context.routeType,
|
|
819
|
+
},
|
|
820
|
+
});
|
|
821
|
+
await scheduleFlush({ useAfter: true });
|
|
475
822
|
}
|
|
823
|
+
|
|
824
|
+
// Deliberately @honeybadger-io/js, not @honeybadger-io/react. The react package re-exports
|
|
476
825
|
/**
|
|
477
|
-
* App Router
|
|
478
|
-
*
|
|
826
|
+
* Records App Router navigations as breadcrumbs, so a fault carries the trail of routes
|
|
827
|
+
* the user visited before it.
|
|
479
828
|
*
|
|
480
|
-
*
|
|
481
|
-
*
|
|
829
|
+
* Wire it up in `instrumentation-client.ts`:
|
|
830
|
+
*
|
|
831
|
+
* ```ts
|
|
832
|
+
* export const onRouterTransitionStart = captureRouterTransitionStart
|
|
833
|
+
* ```
|
|
834
|
+
*
|
|
835
|
+
* Exported as a ready-made handler rather than left as a function for the template to
|
|
836
|
+
* declare, so the generated file works unchanged as both `.js` and `.ts` — an assignment
|
|
837
|
+
* has no parameters to annotate, so there is no implicit `any` for `noImplicitAny` to
|
|
838
|
+
* reject.
|
|
482
839
|
*/
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
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;
|
|
507
|
-
}
|
|
840
|
+
function captureRouterTransitionStart(url, navigationType) {
|
|
841
|
+
Honeybadger__default["default"].addBreadcrumb(`Navigated to ${url}`, {
|
|
842
|
+
category: 'navigation',
|
|
843
|
+
metadata: { url, navigationType },
|
|
844
|
+
});
|
|
508
845
|
}
|
|
846
|
+
|
|
509
847
|
/**
|
|
510
|
-
*
|
|
511
|
-
*
|
|
512
|
-
*
|
|
848
|
+
* Next.js instruments itself with OpenTelemetry and emits one root span per request,
|
|
849
|
+
* `[http.method] [next.route]`, tagged `next.span_type: BaseServer.handleRequest`. Its
|
|
850
|
+
* attributes carry the method, route, target and status, so mapping that span to a
|
|
851
|
+
* `request.handled` event reports every request without wrapping any handler.
|
|
852
|
+
*
|
|
853
|
+
* Next instruments but does not export: spans only reach us once a tracer provider with
|
|
854
|
+
* this processor is registered. See `registerHoneybadgerInsights`.
|
|
513
855
|
*/
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
856
|
+
const NEXT_REQUEST_SPAN_TYPE = 'BaseServer.handleRequest';
|
|
857
|
+
/**
|
|
858
|
+
* Request headers to copy onto the root span, so `request_id` and `correlation_id` can be
|
|
859
|
+
* reused from an inbound request instead of falling back to the span and trace ids.
|
|
860
|
+
*
|
|
861
|
+
* Header values are not span attributes by default. `@vercel/otel` applies this map when
|
|
862
|
+
* it creates the root span, which is the span this processor reads — and, unlike Node's
|
|
863
|
+
* HTTP instrumentation, it works on serverless platforms too.
|
|
864
|
+
*
|
|
865
|
+
* Spread it into your own `registerOTel` call if you register OpenTelemetry yourself:
|
|
866
|
+
*
|
|
867
|
+
* ```ts
|
|
868
|
+
* registerOTel({
|
|
869
|
+
* attributesFromHeaders: { ...HONEYBADGER_HEADER_ATTRIBUTES },
|
|
870
|
+
* spanProcessors: [honeybadgerSpanProcessor()],
|
|
871
|
+
* })
|
|
872
|
+
* ```
|
|
873
|
+
*
|
|
874
|
+
* Keep the header names in sync with `seedIds` in ./insights-instrumentation.
|
|
875
|
+
*/
|
|
876
|
+
const HONEYBADGER_HEADER_ATTRIBUTES = {
|
|
877
|
+
'http.request.header.x-request-id': 'x-request-id',
|
|
878
|
+
'http.request.header.request-id': 'request-id',
|
|
879
|
+
'http.request.header.x-correlation-id': 'x-correlation-id',
|
|
880
|
+
'http.request.header.x-amzn-trace-id': 'x-amzn-trace-id',
|
|
881
|
+
};
|
|
882
|
+
function readString(attributes, ...names) {
|
|
883
|
+
for (const name of names) {
|
|
884
|
+
const value = attributes[name];
|
|
885
|
+
if (typeof value === 'string' && value.length) {
|
|
886
|
+
return value;
|
|
527
887
|
}
|
|
528
|
-
return result;
|
|
529
888
|
}
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
889
|
+
return undefined;
|
|
890
|
+
}
|
|
891
|
+
function readNumber(attributes, ...names) {
|
|
892
|
+
for (const name of names) {
|
|
893
|
+
const value = attributes[name];
|
|
894
|
+
if (typeof value === 'number') {
|
|
895
|
+
return value;
|
|
533
896
|
}
|
|
534
|
-
if (
|
|
535
|
-
|
|
536
|
-
await scheduleFlush({ useAfter: false });
|
|
897
|
+
if (typeof value === 'string' && value.trim().length && Number.isFinite(Number(value))) {
|
|
898
|
+
return Number(value);
|
|
537
899
|
}
|
|
538
|
-
await Honeybadger__default["default"].notifyAsync(error);
|
|
539
|
-
throw error;
|
|
540
900
|
}
|
|
901
|
+
return undefined;
|
|
902
|
+
}
|
|
903
|
+
function durationMs(duration) {
|
|
904
|
+
if (!Array.isArray(duration) || duration.length !== 2) {
|
|
905
|
+
return 0;
|
|
906
|
+
}
|
|
907
|
+
const [seconds, nanos] = duration;
|
|
908
|
+
return Math.round(seconds * 1000 + nanos / 1e6);
|
|
909
|
+
}
|
|
910
|
+
/**
|
|
911
|
+
* Path without the query string. `http.target` includes the query under the older
|
|
912
|
+
* semantic conventions; `url.path` is already bare under the stable ones.
|
|
913
|
+
*/
|
|
914
|
+
function readPath(attributes) {
|
|
915
|
+
const target = readString(attributes, 'url.path', 'http.target');
|
|
916
|
+
return typeof target === 'string' ? target.split('?')[0] : undefined;
|
|
917
|
+
}
|
|
918
|
+
/**
|
|
919
|
+
* Maps Next.js's per-request span to a Honeybadger `request.handled` Insights event.
|
|
920
|
+
*
|
|
921
|
+
* Pass it to whatever registers OpenTelemetry in your `instrumentation.ts`:
|
|
922
|
+
*
|
|
923
|
+
* ```ts
|
|
924
|
+
* import { registerOTel } from '@vercel/otel'
|
|
925
|
+
* import { honeybadgerSpanProcessor } from '@honeybadger-io/nextjs'
|
|
926
|
+
*
|
|
927
|
+
* export function register() {
|
|
928
|
+
* registerOTel({ serviceName: 'my-app', spanProcessors: [honeybadgerSpanProcessor()] })
|
|
929
|
+
* }
|
|
930
|
+
* ```
|
|
931
|
+
*
|
|
932
|
+
* `registerHoneybadgerInsights()` is the one-line equivalent when you have no other
|
|
933
|
+
* OpenTelemetry setup of your own.
|
|
934
|
+
*/
|
|
935
|
+
function honeybadgerSpanProcessor() {
|
|
936
|
+
return {
|
|
937
|
+
onStart() {
|
|
938
|
+
// Nothing to do: the event is emitted once the request span is complete, which is
|
|
939
|
+
// when the status and duration are known.
|
|
940
|
+
},
|
|
941
|
+
onEnd(span) {
|
|
942
|
+
var _a;
|
|
943
|
+
const attributes = (_a = span.attributes) !== null && _a !== void 0 ? _a : {};
|
|
944
|
+
if (attributes['next.span_type'] !== NEXT_REQUEST_SPAN_TYPE) {
|
|
945
|
+
return;
|
|
946
|
+
}
|
|
947
|
+
// Checked per event rather than at registration: configuration is loaded by
|
|
948
|
+
// `register()` importing the honeybadger config files, which may happen after the
|
|
949
|
+
// processor is constructed.
|
|
950
|
+
if (!insightsHttpEnabled()) {
|
|
951
|
+
return;
|
|
952
|
+
}
|
|
953
|
+
const spanContext = typeof span.spanContext === 'function' ? span.spanContext() : {};
|
|
954
|
+
const ids = seedSpanEventContext(attributes, spanContext !== null && spanContext !== void 0 ? spanContext : {});
|
|
955
|
+
const payload = {
|
|
956
|
+
method: readString(attributes, 'http.request.method', 'http.method'),
|
|
957
|
+
duration: durationMs(span.duration),
|
|
958
|
+
...ids,
|
|
959
|
+
};
|
|
960
|
+
const path = readPath(attributes);
|
|
961
|
+
if (path) {
|
|
962
|
+
payload.path = path;
|
|
963
|
+
}
|
|
964
|
+
const status = readNumber(attributes, 'http.response.status_code', 'http.status_code');
|
|
965
|
+
if (typeof status === 'number') {
|
|
966
|
+
payload.status = status;
|
|
967
|
+
}
|
|
968
|
+
// Emitted alongside the ids rather than replacing them, so an event can be joined
|
|
969
|
+
// to a trace in another tool without changing what existing consumers read.
|
|
970
|
+
if (spanContext === null || spanContext === void 0 ? void 0 : spanContext.traceId) {
|
|
971
|
+
payload.trace_id = spanContext.traceId;
|
|
972
|
+
}
|
|
973
|
+
if (spanContext === null || spanContext === void 0 ? void 0 : spanContext.spanId) {
|
|
974
|
+
payload.span_id = spanContext.spanId;
|
|
975
|
+
}
|
|
976
|
+
Honeybadger__default["default"].event('request.handled', payload);
|
|
977
|
+
// A span processor batches on its own lifecycle, which is not enough on a platform
|
|
978
|
+
// that can freeze the invocation as soon as the response is sent.
|
|
979
|
+
scheduleFlush({ useAfter: true });
|
|
980
|
+
},
|
|
981
|
+
async forceFlush() {
|
|
982
|
+
await Honeybadger__default["default"].flushAsync().catch(() => { });
|
|
983
|
+
},
|
|
984
|
+
async shutdown() {
|
|
985
|
+
await Honeybadger__default["default"].flushAsync().catch(() => { });
|
|
986
|
+
},
|
|
987
|
+
};
|
|
541
988
|
}
|
|
542
989
|
/**
|
|
543
|
-
*
|
|
544
|
-
*
|
|
990
|
+
* Registers OpenTelemetry with only Honeybadger's span processor attached, for apps that
|
|
991
|
+
* have no OpenTelemetry setup of their own. Call it from `register()` in
|
|
992
|
+
* `instrumentation.ts`.
|
|
993
|
+
*
|
|
994
|
+
* `@vercel/otel` is an optional peer dependency: it is only needed for Insights, and it
|
|
995
|
+
* loads where the full Node SDK cannot, such as serverless platforms. If you
|
|
996
|
+
* already call `registerOTel` yourself, add `honeybadgerSpanProcessor()` to your
|
|
997
|
+
* `spanProcessors` instead of calling this — registering twice would compete for the
|
|
998
|
+
* global provider.
|
|
545
999
|
*/
|
|
546
|
-
async function
|
|
1000
|
+
async function registerHoneybadgerInsights(options = {}) {
|
|
1001
|
+
var _a, _b;
|
|
1002
|
+
let registerOTel;
|
|
547
1003
|
try {
|
|
548
|
-
|
|
1004
|
+
({ registerOTel } = await Promise.resolve().then(function () { return /*#__PURE__*/_interopNamespace(require('@vercel/otel')); }));
|
|
549
1005
|
}
|
|
1006
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
550
1007
|
catch (error) {
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
await Honeybadger__default["default"].notifyAsync(error);
|
|
555
|
-
throw error;
|
|
1008
|
+
Honeybadger__default["default"].logger.error('[Honeybadger] Insights request events need @vercel/otel. Install it, or drop the ' +
|
|
1009
|
+
'registerHoneybadgerInsights() call — error reporting works without it.');
|
|
1010
|
+
return;
|
|
556
1011
|
}
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
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();
|
|
1012
|
+
registerOTel({
|
|
1013
|
+
serviceName: (_b = (_a = options.serviceName) !== null && _a !== void 0 ? _a : process.env.NEXT_PUBLIC_HONEYBADGER_SERVICE_NAME) !== null && _b !== void 0 ? _b : 'nextjs-app',
|
|
1014
|
+
// Without this the id headers never reach the span, so request_id and
|
|
1015
|
+
// correlation_id would always fall back to the span and trace ids.
|
|
1016
|
+
attributesFromHeaders: {
|
|
1017
|
+
...HONEYBADGER_HEADER_ATTRIBUTES,
|
|
1018
|
+
...options.attributesFromHeaders,
|
|
576
1019
|
},
|
|
1020
|
+
spanProcessors: [honeybadgerSpanProcessor()],
|
|
577
1021
|
});
|
|
578
1022
|
}
|
|
579
1023
|
|
|
580
|
-
exports.
|
|
581
|
-
exports.
|
|
1024
|
+
exports.HONEYBADGER_HEADER_ATTRIBUTES = HONEYBADGER_HEADER_ATTRIBUTES;
|
|
1025
|
+
exports.captureRequestError = captureRequestError;
|
|
1026
|
+
exports.captureRouterTransitionStart = captureRouterTransitionStart;
|
|
1027
|
+
exports.honeybadgerSpanProcessor = honeybadgerSpanProcessor;
|
|
1028
|
+
exports.registerHoneybadgerInsights = registerHoneybadgerInsights;
|
|
1029
|
+
exports.withHoneybadgerConfig = withHoneybadgerConfig;
|
|
582
1030
|
//# sourceMappingURL=honeybadger-nextjs.cjs.js.map
|