@honeybadger-io/nextjs 5.11.6 → 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.
Files changed (62) 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/client.d.ts +2 -0
  6. package/dist/copy-config-files.js +106 -34
  7. package/dist/copy-config-files.js.map +1 -1
  8. package/dist/edge.d.ts +2 -1
  9. package/dist/flush.d.ts +24 -0
  10. package/dist/honeybadger-nextjs-client.cjs.js +35 -0
  11. package/dist/honeybadger-nextjs-client.cjs.js.map +1 -0
  12. package/dist/honeybadger-nextjs-client.esm.js +27 -0
  13. package/dist/honeybadger-nextjs-client.esm.js.map +1 -0
  14. package/dist/honeybadger-nextjs-edge.cjs.js +320 -240
  15. package/dist/honeybadger-nextjs-edge.cjs.js.map +1 -1
  16. package/dist/honeybadger-nextjs-edge.esm.js +317 -240
  17. package/dist/honeybadger-nextjs-edge.esm.js.map +1 -1
  18. package/dist/honeybadger-nextjs.cjs.js +835 -387
  19. package/dist/honeybadger-nextjs.cjs.js.map +1 -1
  20. package/dist/honeybadger-nextjs.esm.js +829 -386
  21. package/dist/honeybadger-nextjs.esm.js.map +1 -1
  22. package/dist/index.d.ts +5 -2
  23. package/dist/insights-instrumentation.d.ts +30 -2
  24. package/dist/insights.d.ts +72 -0
  25. package/dist/insights.test.d.ts +2 -0
  26. package/dist/setup.d.ts +11 -0
  27. package/dist/setup.test.d.ts +2 -0
  28. package/dist/source-maps.d.ts +55 -0
  29. package/dist/source-maps.test.d.ts +2 -0
  30. package/dist/types.d.ts +20 -8
  31. package/package.json +33 -11
  32. package/src/capture-request-error.test.ts +245 -0
  33. package/src/capture-request-error.ts +92 -0
  34. package/src/capture-router-transition-start.ts +33 -0
  35. package/src/client.ts +4 -0
  36. package/src/copy-config-files.test.ts +250 -16
  37. package/src/copy-config-files.ts +117 -34
  38. package/src/edge.ts +12 -1
  39. package/src/flush.ts +58 -0
  40. package/src/index.ts +7 -2
  41. package/src/insights-instrumentation.ts +104 -11
  42. package/src/insights.test.ts +192 -0
  43. package/src/insights.ts +225 -0
  44. package/src/setup.test.ts +214 -0
  45. package/src/setup.ts +172 -0
  46. package/src/source-maps.test.ts +803 -0
  47. package/src/source-maps.ts +515 -0
  48. package/src/types.ts +38 -21
  49. package/templates/_error.js +14 -10
  50. package/templates/_error_app_router.js +1 -1
  51. package/templates/_error_app_router.tsx +1 -1
  52. package/templates/honeybadger.server.config.js +5 -16
  53. package/templates/instrumentation-client.js +21 -0
  54. package/templates/instrumentation.js +29 -0
  55. package/dist/webpack.d.ts +0 -3
  56. package/dist/with-honeybadger.d.ts +0 -32
  57. package/dist/with-honeybadger.test.d.ts +0 -2
  58. package/src/webpack.ts +0 -228
  59. package/src/with-honeybadger.test.ts +0 -527
  60. package/src/with-honeybadger.ts +0 -286
  61. package/templates/honeybadger.browser.config.js +0 -13
  62. package/templates/honeybadger.edge.config.js +0 -13
@@ -0,0 +1,803 @@
1
+ import fs from 'fs'
2
+ import mock from 'mock-fs'
3
+ import { collectSourcemaps, resolveUploadOptions, uploadSourceMapsAfterBuild } from './source-maps'
4
+
5
+ const MAP_WITH_SOURCES = JSON.stringify({ version: 3, sources: ['a.ts'], sourcesContent: ['const a = 1'] })
6
+ const MAP_WITHOUT_SOURCES = JSON.stringify({ version: 3, sources: ['a.ts'], sourcesContent: [] })
7
+
8
+ // `next`'s type augmentation marks process.env.NODE_ENV readonly, so the tests set it
9
+ // through a mutable view rather than assigning to the typed property.
10
+ function setNodeEnv(value: string | undefined): void {
11
+ const env = process.env as Record<string, string | undefined>
12
+ if (value === undefined) {
13
+ delete env.NODE_ENV
14
+ } else {
15
+ env.NODE_ENV = value
16
+ }
17
+ }
18
+
19
+ // A built file declares its map with a sourceMappingURL comment, which is how the collector
20
+ // pairs the two. Turbopack does not name the map after the chunk, so the comment is the only
21
+ // reliable link.
22
+ const js = (mapName: string) => `code\n//# sourceMappingURL=${mapName}`
23
+
24
+ const uploadSourcemaps = jest.fn()
25
+ const sendDeployNotification = jest.fn()
26
+ // Set to make option resolution blow up, standing in for `cleanOptions` throwing or
27
+ // plugin-core failing to load at all.
28
+ let cleanOptionsError: Error | null = null
29
+ jest.mock('@honeybadger-io/plugin-core', () => {
30
+ const actual = jest.requireActual('@honeybadger-io/plugin-core')
31
+ return {
32
+ ...actual,
33
+ cleanOptions: (...args: unknown[]) => {
34
+ if (cleanOptionsError) {
35
+ throw cleanOptionsError
36
+ }
37
+ return (actual as { cleanOptions: (...a: unknown[]) => unknown }).cleanOptions(...args)
38
+ },
39
+ uploadSourcemaps: (...args: unknown[]) => uploadSourcemaps(...args),
40
+ sendDeployNotification: (...args: unknown[]) => sendDeployNotification(...args),
41
+ }
42
+ })
43
+
44
+ // `source-maps.ts` loads plugin-core through a dynamic import, which reads from disk the
45
+ // first time it runs. Resolve it up front, or whichever test happens to trigger it first
46
+ // does so while mock-fs is in control and gets ENOENT for plugin-core's own dist.
47
+ beforeAll(async () => {
48
+ await import('@honeybadger-io/plugin-core')
49
+ })
50
+
51
+ describe('collectSourcemaps', () => {
52
+ afterEach(() => mock.restore())
53
+
54
+ it('pairs each map with its js file, relative to distDir', async () => {
55
+ mock({
56
+ '.next': {
57
+ 'static': { 'chunks': { 'main.js': js('main.js.map'), 'main.js.map': MAP_WITH_SOURCES } },
58
+ },
59
+ })
60
+
61
+ const collected = await collectSourcemaps('.next')
62
+
63
+ expect(collected).toHaveLength(1)
64
+ expect(collected[0]).toMatchObject({
65
+ // assetsUrl points at <origin>/_next, and .next/static/... is served at
66
+ // /_next/static/..., so the name must be relative to distDir.
67
+ jsFilename: 'static/chunks/main.js',
68
+ sourcemapFilename: 'static/chunks/main.js.map',
69
+ })
70
+ })
71
+
72
+ it('walks nested directories and both output roots', async () => {
73
+ mock({
74
+ '.next': {
75
+ 'static': { 'chunks': { 'app': { 'page.js': js('page.js.map'), 'page.js.map': MAP_WITH_SOURCES } } },
76
+ 'server': { 'chunks': { 'handler.js': js('handler.js.map'), 'handler.js.map': MAP_WITH_SOURCES } },
77
+ },
78
+ })
79
+
80
+ const names = (await collectSourcemaps('.next')).map((s) => s.jsFilename).sort()
81
+
82
+ // Server chunks are included: not uploading them is exactly why server frames stay
83
+ // minified today (#1602).
84
+ expect(names).toEqual(['server/chunks/handler.js', 'static/chunks/app/page.js'])
85
+ })
86
+
87
+ // Turbopack gives the map its own hash, so the sibling convention finds nothing and every
88
+ // browser map was silently skipped — uploaded zero, deleted twelve.
89
+ it('pairs a chunk with a map that is not named after it', async () => {
90
+ mock({
91
+ '.next': {
92
+ 'static': {
93
+ 'chunks': {
94
+ '1mfl5gjk9763d.js': js('33ri1p-shrphb.js.map'),
95
+ '33ri1p-shrphb.js.map': MAP_WITH_SOURCES,
96
+ },
97
+ },
98
+ },
99
+ })
100
+
101
+ const collected = await collectSourcemaps('.next')
102
+
103
+ expect(collected).toHaveLength(1)
104
+ expect(collected[0]).toMatchObject({
105
+ // the minified_url is built from this, so it must be the chunk, not the map
106
+ jsFilename: 'static/chunks/1mfl5gjk9763d.js',
107
+ sourcemapFilename: 'static/chunks/33ri1p-shrphb.js.map',
108
+ })
109
+ })
110
+
111
+ it('skips a chunk whose sourceMappingURL points at a missing file', async () => {
112
+ mock({ '.next': { 'static': { 'a.js': js('gone.js.map') } } })
113
+
114
+ await expect(collectSourcemaps('.next')).resolves.toEqual([])
115
+ })
116
+
117
+ it('skips a chunk with an inline data: map, which has nothing to upload', async () => {
118
+ mock({ '.next': { 'static': { 'a.js': js('data:application/json;base64,e30=') } } })
119
+
120
+ await expect(collectSourcemaps('.next')).resolves.toEqual([])
121
+ })
122
+
123
+ // `decodeURIComponent` throws on a malformed escape, and an uncaught throw here would
124
+ // lose every other map in the build, not just this one.
125
+ it('skips a chunk whose sourceMappingURL is malformed, and keeps the rest', async () => {
126
+ mock({
127
+ '.next': {
128
+ 'static': {
129
+ 'bad.js': js('bad%.map'),
130
+ 'good.js': js('good.js.map'),
131
+ 'good.js.map': MAP_WITH_SOURCES,
132
+ },
133
+ },
134
+ })
135
+
136
+ const collected = await collectSourcemaps('.next')
137
+
138
+ expect(collected.map((s) => s.jsFilename)).toEqual(['static/good.js'])
139
+ })
140
+
141
+ it('skips a chunk that declares no map at all', async () => {
142
+ mock({ '.next': { 'static': { 'a.js': 'code with no comment' } } })
143
+
144
+ await expect(collectSourcemaps('.next')).resolves.toEqual([])
145
+ })
146
+
147
+ // `distDir` also holds build tooling and, in standalone mode, a second copy of the
148
+ // server. None of it is served, so a map found there would upload under a minified_url
149
+ // no request can produce.
150
+ it('ignores JavaScript outside the served output roots', async () => {
151
+ mock({
152
+ '.next': {
153
+ 'static': { 'a.js': js('a.js.map'), 'a.js.map': MAP_WITH_SOURCES },
154
+ 'server': { 'b.js': js('b.js.map'), 'b.js.map': MAP_WITH_SOURCES },
155
+ 'build': { 'chunks': { 'tooling.js': js('tooling.js.map'), 'tooling.js.map': MAP_WITH_SOURCES } },
156
+ 'cache': { 'cached.js': js('cached.js.map'), 'cached.js.map': MAP_WITH_SOURCES },
157
+ 'standalone': { 'server.js': js('server.js.map'), 'server.js.map': MAP_WITH_SOURCES },
158
+ 'required-server-files.js': js('required-server-files.js.map'),
159
+ 'required-server-files.js.map': MAP_WITH_SOURCES,
160
+ },
161
+ })
162
+
163
+ const collected = (await collectSourcemaps('.next')).map((s) => s.jsFilename).sort()
164
+
165
+ expect(collected).toEqual(['server/b.js', 'static/a.js'])
166
+ })
167
+
168
+ it('skips maps with no sourcesContent', async () => {
169
+ mock({
170
+ '.next': {
171
+ 'static': {
172
+ 'useful.js': js('useful.js.map'),
173
+ 'useful.js.map': MAP_WITH_SOURCES,
174
+ 'empty.js': js('empty.js.map'),
175
+ 'empty.js.map': MAP_WITHOUT_SOURCES,
176
+ },
177
+ },
178
+ })
179
+
180
+ const names = (await collectSourcemaps('.next')).map((s) => s.jsFilename)
181
+
182
+ expect(names).toEqual(['static/useful.js'])
183
+ })
184
+
185
+ it('skips a map whose js file is missing', async () => {
186
+ mock({ '.next': { 'static': { 'orphan.js.map': MAP_WITH_SOURCES } } })
187
+
188
+ expect(await collectSourcemaps('.next')).toHaveLength(0)
189
+ })
190
+
191
+ it('skips unparseable maps rather than failing the build', async () => {
192
+ mock({ '.next': { 'static': { 'broken.js': js('broken.js.map'), 'broken.js.map': 'not json' } } })
193
+
194
+ expect(await collectSourcemaps('.next')).toHaveLength(0)
195
+ })
196
+
197
+ it('honours ignorePaths', async () => {
198
+ mock({
199
+ '.next': {
200
+ 'static': { 'keep.js': js('keep.js.map'), 'keep.js.map': MAP_WITH_SOURCES },
201
+ 'server': { 'skip.js': js('skip.js.map'), 'skip.js.map': MAP_WITH_SOURCES },
202
+ },
203
+ })
204
+
205
+ const names = (await collectSourcemaps('.next', ['skip.js'])).map((s) => s.jsFilename)
206
+
207
+ expect(names).toEqual(['static/keep.js'])
208
+ })
209
+
210
+ it('returns nothing when the build directory is absent', async () => {
211
+ mock({})
212
+
213
+ expect(await collectSourcemaps('.next')).toHaveLength(0)
214
+ })
215
+
216
+ it('ignores files that are not source maps', async () => {
217
+ mock({
218
+ '.next': {
219
+ 'static': { 'main.js': js('main.js.map'), 'main.js.map': MAP_WITH_SOURCES, 'styles.css': 'css', 'BUILD_ID': 'x' },
220
+ },
221
+ })
222
+
223
+ expect(await collectSourcemaps('.next')).toHaveLength(1)
224
+ })
225
+ })
226
+
227
+ describe('resolveUploadOptions', () => {
228
+ const envKeys = [
229
+ 'NEXT_PUBLIC_HONEYBADGER_API_KEY',
230
+ 'NEXT_PUBLIC_HONEYBADGER_ASSETS_URL',
231
+ 'NEXT_PUBLIC_HONEYBADGER_REVISION',
232
+ ]
233
+ const saved: Record<string, string | undefined> = {}
234
+
235
+ beforeEach(() => {
236
+ envKeys.forEach((key) => { saved[key] = process.env[key]; delete process.env[key] })
237
+ // The unconfigured cases warn by design; keep the test output readable.
238
+ jest.spyOn(console, 'warn').mockImplementation(() => undefined)
239
+ })
240
+
241
+ afterEach(() => {
242
+ jest.restoreAllMocks()
243
+ envKeys.forEach((key) => {
244
+ if (saved[key] === undefined) { delete process.env[key] } else { process.env[key] = saved[key] }
245
+ })
246
+ })
247
+
248
+ it('returns null when nothing is configured', async () => {
249
+ // cleanOptions throws on a missing apiKey, and Next re-throws whatever this hook
250
+ // throws — so an unconfigured project must not reach it.
251
+ await expect(resolveUploadOptions({})).resolves.toBeNull()
252
+ })
253
+
254
+ it('returns null when upload is disabled', async () => {
255
+ await expect(resolveUploadOptions({
256
+ disableSourceMapUpload: true,
257
+ apiKey: 'k',
258
+ assetsUrl: 'https://example.com/_next',
259
+ })).resolves.toBeNull()
260
+ })
261
+
262
+ it('falls back to the environment variables the templates use', async () => {
263
+ process.env.NEXT_PUBLIC_HONEYBADGER_API_KEY = 'env-key'
264
+ process.env.NEXT_PUBLIC_HONEYBADGER_ASSETS_URL = 'https://example.com/_next'
265
+ process.env.NEXT_PUBLIC_HONEYBADGER_REVISION = 'abc123'
266
+
267
+ await expect(resolveUploadOptions({})).resolves.toMatchObject({
268
+ apiKey: 'env-key',
269
+ assetsUrl: 'https://example.com/_next',
270
+ revision: 'abc123',
271
+ })
272
+ })
273
+
274
+ it('prefers explicit options over the environment', async () => {
275
+ process.env.NEXT_PUBLIC_HONEYBADGER_API_KEY = 'env-key'
276
+ process.env.NEXT_PUBLIC_HONEYBADGER_ASSETS_URL = 'https://example.com/_next'
277
+
278
+ await expect(resolveUploadOptions({
279
+ apiKey: 'explicit',
280
+ assetsUrl: 'https://cdn.example.com/_next',
281
+ })).resolves.toMatchObject({ apiKey: 'explicit', assetsUrl: 'https://cdn.example.com/_next' })
282
+ })
283
+
284
+ it('leaves the default revision alone when none is configured', async () => {
285
+ process.env.NEXT_PUBLIC_HONEYBADGER_API_KEY = 'env-key'
286
+ process.env.NEXT_PUBLIC_HONEYBADGER_ASSETS_URL = 'https://example.com/_next'
287
+
288
+ // cleanOptions merges as { ...defaults, ...options }, so passing revision: undefined
289
+ // would overwrite the default rather than fall back to it — and a fault whose
290
+ // revision does not match its source map never symbolicates.
291
+ expect((await resolveUploadOptions({}))?.revision).toBe('main')
292
+ })
293
+
294
+ it('does not let other unset options clobber their defaults', async () => {
295
+ process.env.NEXT_PUBLIC_HONEYBADGER_API_KEY = 'env-key'
296
+ process.env.NEXT_PUBLIC_HONEYBADGER_ASSETS_URL = 'https://example.com/_next'
297
+
298
+ const options = await resolveUploadOptions({
299
+ apiKey: 'k', assetsUrl: 'u', endpoint: undefined, retries: undefined,
300
+ })
301
+
302
+ expect(options?.endpoint).toBe('https://api.honeybadger.io/v1/source_maps')
303
+ expect(options?.retries).toBe(3)
304
+ })
305
+
306
+ it('returns null when only one of the two required values is present', async () => {
307
+ process.env.NEXT_PUBLIC_HONEYBADGER_API_KEY = 'env-key'
308
+
309
+ await expect(resolveUploadOptions({})).resolves.toBeNull()
310
+ })
311
+ })
312
+
313
+ describe('uploadSourceMapsAfterBuild', () => {
314
+ const configured = {
315
+ apiKey: 'k',
316
+ assetsUrl: 'https://example.com/_next',
317
+ }
318
+ let nodeEnv: string | undefined
319
+ // A developer with these exported would otherwise see different behaviour from CI, and a
320
+ // test that clears them would leak that into the ones after it.
321
+ const envKeys = ['NEXT_PUBLIC_HONEYBADGER_API_KEY', 'NEXT_PUBLIC_HONEYBADGER_ASSETS_URL']
322
+ const savedEnv: Record<string, string | undefined> = {}
323
+
324
+ beforeEach(() => {
325
+ cleanOptionsError = null
326
+ nodeEnv = process.env.NODE_ENV
327
+ envKeys.forEach((key) => { savedEnv[key] = process.env[key] })
328
+ jest.spyOn(console, 'warn').mockImplementation(() => undefined)
329
+ uploadSourcemaps.mockReset().mockResolvedValue(undefined)
330
+ sendDeployNotification.mockReset().mockResolvedValue(undefined)
331
+ })
332
+
333
+ afterEach(() => {
334
+ mock.restore()
335
+ jest.restoreAllMocks()
336
+ setNodeEnv(nodeEnv)
337
+ envKeys.forEach((key) => {
338
+ if (savedEnv[key] === undefined) { delete process.env[key] } else { process.env[key] = savedEnv[key] }
339
+ })
340
+ })
341
+
342
+ // `production` is required for this to test anything: jest runs with NODE_ENV=test, which
343
+ // is a development environment, so the dev guard would return before the configuration
344
+ // check was ever reached. The env vars are cleared for the same reason — the fallback
345
+ // would otherwise make an empty config look configured.
346
+ it('does nothing when upload is not configured', async () => {
347
+ setNodeEnv('production')
348
+ envKeys.forEach((key) => delete process.env[key])
349
+ mock({ '.next': { 'static': { 'a.js': js('a.js.map'), 'a.js.map': MAP_WITH_SOURCES } } })
350
+
351
+ await uploadSourceMapsAfterBuild({}, { distDir: '.next', projectDir: '.' })
352
+
353
+ expect(uploadSourcemaps).not.toHaveBeenCalled()
354
+ })
355
+
356
+ it('uploads the collected maps', async () => {
357
+ setNodeEnv('production')
358
+ mock({ '.next': { 'static': { 'a.js': js('a.js.map'), 'a.js.map': MAP_WITH_SOURCES } } })
359
+
360
+ await uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' })
361
+
362
+ expect(uploadSourcemaps).toHaveBeenCalledTimes(1)
363
+ expect(uploadSourcemaps.mock.calls[0][0]).toHaveLength(1)
364
+ })
365
+
366
+ it('skips a development build', async () => {
367
+ setNodeEnv('development')
368
+ mock({ '.next': { 'static': { 'a.js': js('a.js.map'), 'a.js.map': MAP_WITH_SOURCES } } })
369
+
370
+ await uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' })
371
+
372
+ expect(uploadSourcemaps).not.toHaveBeenCalled()
373
+ })
374
+
375
+ it('sends a deploy notification only when asked', async () => {
376
+ setNodeEnv('production')
377
+ mock({ '.next': { 'static': { 'a.js': js('a.js.map'), 'a.js.map': MAP_WITH_SOURCES } } })
378
+
379
+ await uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' })
380
+ expect(sendDeployNotification).not.toHaveBeenCalled()
381
+
382
+ await uploadSourceMapsAfterBuild(
383
+ { ...configured, deploy: { environment: 'production' } },
384
+ { distDir: '.next', projectDir: '.' }
385
+ )
386
+ expect(sendDeployNotification).toHaveBeenCalledTimes(1)
387
+ })
388
+
389
+ // Honeybadger tests the resolved source against the notice's projectRoot to decide whether
390
+ // a frame is the user's code. A source still carrying its bundler scheme never matches, so
391
+ // the fault surfaces an unmapped framework frame instead of the throw site.
392
+ describe('normalizing the source paths', () => {
393
+ beforeEach(() => { setNodeEnv('production') })
394
+
395
+ // The rewritten copy is deleted as soon as the upload returns, so read it inside the
396
+ // upload rather than afterwards.
397
+ let sentSources: string[] = []
398
+ let sentPaths: string[] = []
399
+ beforeEach(() => {
400
+ sentSources = []
401
+ sentPaths = []
402
+ uploadSourcemaps.mockImplementation(async (maps: Array<{ sourcemapFilePath: string }>) => {
403
+ sentPaths = maps.map((m) => m.sourcemapFilePath)
404
+ sentSources = maps.flatMap((m) =>
405
+ JSON.parse(fs.readFileSync(m.sourcemapFilePath, 'utf8')).sources as string[])
406
+ })
407
+ })
408
+
409
+ const uploaded = () => sentPaths
410
+ const uploadedSources = () => sentSources
411
+
412
+ it('strips the Turbopack scheme', async () => {
413
+ mock({ '.next': { 'static': { 'a.js': js('a.js.map'), 'a.js.map': JSON.stringify({
414
+ version: 3, sources: ['turbopack:///[project]/app/page.tsx'], sourcesContent: ['x'],
415
+ }) } } })
416
+
417
+ await uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' })
418
+
419
+ expect(uploadedSources()).toEqual(['app/page.tsx'])
420
+ })
421
+
422
+ it.each([
423
+ ['webpack://_N_E/./app/page.tsx', 'app/page.tsx'],
424
+ ['webpack:///./app/page.tsx', 'app/page.tsx'],
425
+ ])('strips the webpack scheme from %s', async (source, expected) => {
426
+ mock({ '.next': { 'static': { 'a.js': js('a.js.map'), 'a.js.map': JSON.stringify({
427
+ version: 3, sources: [source], sourcesContent: ['x'],
428
+ }) } } })
429
+
430
+ await uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' })
431
+
432
+ expect(uploadedSources()).toEqual([expected])
433
+ })
434
+
435
+ // The map on disk is Next.js's own: it reads the server maps to format stack traces.
436
+ it('rewrites a copy and leaves the original alone', async () => {
437
+ const original = JSON.stringify({
438
+ version: 3, sources: ['turbopack:///[project]/app/page.tsx'], sourcesContent: ['x'],
439
+ })
440
+ mock({ '.next': { 'static': { 'a.js': js('a.js.map'), 'a.js.map': original } } })
441
+
442
+ await uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' })
443
+
444
+ expect(uploaded()[0]).not.toContain('.next/static/a.js.map')
445
+ expect(fs.readFileSync('.next/static/a.js.map', 'utf8')).toBe(original)
446
+ })
447
+
448
+ it('leaves an already-relative source untouched', async () => {
449
+ mock({ '.next': { 'static': { 'a.js': js('a.js.map'), 'a.js.map': JSON.stringify({
450
+ version: 3, sources: ['app/page.tsx'], sourcesContent: ['x'],
451
+ }) } } })
452
+
453
+ await uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' })
454
+
455
+ // Nothing to rewrite, so the original file is uploaded rather than a copy.
456
+ expect(uploaded()[0]).toContain('.next/static/a.js.map')
457
+ })
458
+ })
459
+
460
+ describe('deleting the maps after upload', () => {
461
+ beforeEach(() => {
462
+ setNodeEnv('production')
463
+ mock({ '.next': { 'static': { 'a.js': js('a.js.map'), 'a.js.map': MAP_WITH_SOURCES } } })
464
+ })
465
+
466
+ // We turn on productionBrowserSourceMaps to have something to upload, and that also
467
+ // serves them. Deleting afterwards restores what hidden-source-map used to give us.
468
+ it('removes them when asked', async () => {
469
+ await uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' }, {
470
+ deleteBrowserSourcemaps: true,
471
+ })
472
+
473
+ expect(fs.existsSync('.next/static/a.js.map')).toBe(false)
474
+ // the JavaScript itself is untouched
475
+ expect(fs.existsSync('.next/static/a.js')).toBe(true)
476
+ })
477
+
478
+ it('leaves them when not asked', async () => {
479
+ await uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' })
480
+
481
+ expect(fs.existsSync('.next/static/a.js.map')).toBe(true)
482
+ })
483
+
484
+ // Cleanup exists because we enabled `productionBrowserSourceMaps`, which serves what
485
+ // it generates. A map we declined to upload is still served, so scoping deletion to
486
+ // successful uploads would leak exactly the maps that failed the collection filters.
487
+ it('removes browser maps that were never uploaded', async () => {
488
+ mock({
489
+ '.next': {
490
+ 'static': {
491
+ 'good.js': js('good.js.map'), 'good.js.map': MAP_WITH_SOURCES,
492
+ // rejected by collectSourcemaps: no sourcesContent
493
+ 'empty.js': js('empty.js.map'), 'empty.js.map': MAP_WITHOUT_SOURCES,
494
+ // rejected by collectSourcemaps: unparseable
495
+ 'broken.js': js('broken.js.map'), 'broken.js.map': 'not json',
496
+ // rejected by collectSourcemaps: no sibling .js
497
+ 'orphan.js.map': MAP_WITH_SOURCES,
498
+ // rejected by ignorePaths below
499
+ 'vendor.js': js('vendor.js.map'), 'vendor.js.map': MAP_WITH_SOURCES,
500
+ },
501
+ },
502
+ })
503
+
504
+ await uploadSourceMapsAfterBuild(
505
+ {
506
+ ...configured,
507
+ ignorePaths: ['**/vendor.js'],
508
+ },
509
+ { distDir: '.next', projectDir: '.' },
510
+ { deleteBrowserSourcemaps: true }
511
+ )
512
+
513
+ // Only `good.js.map` was uploadable...
514
+ expect(uploadSourcemaps).toHaveBeenCalledTimes(1)
515
+ expect(uploadSourcemaps.mock.calls[0][0].map((s: { jsFilename: string }) => s.jsFilename))
516
+ .toEqual(['static/good.js'])
517
+ // ...but every one of them is gone from the served output.
518
+ expect(fs.readdirSync('.next/static').filter((f) => f.endsWith('.js.map'))).toEqual([])
519
+ })
520
+
521
+ // Failing to delete means a map this package caused to be served stays served, so it
522
+ // must not hide behind the default `silent: true`.
523
+ it('warns loudly, and does not fail the build, when a map cannot be deleted', async () => {
524
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined)
525
+ const unlink = jest.spyOn(fs.promises, 'unlink')
526
+ .mockRejectedValue(Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' }))
527
+
528
+ await expect(
529
+ uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' }, {
530
+ deleteBrowserSourcemaps: true,
531
+ })
532
+ ).resolves.toBeUndefined()
533
+
534
+ expect(warn).toHaveBeenCalledWith(
535
+ '[HoneybadgerNextJs]',
536
+ expect.stringContaining('will be served')
537
+ )
538
+ unlink.mockRestore()
539
+ warn.mockRestore()
540
+ })
541
+
542
+ // `.next/server` is never served, so there is no exposure to undo — and Next.js reads
543
+ // these maps itself to format server-side stack traces.
544
+ it('never removes server maps, even when asked', async () => {
545
+ mock({
546
+ '.next': {
547
+ 'static': { 'a.js': js('a.js.map'), 'a.js.map': MAP_WITH_SOURCES },
548
+ 'server': { 'b.js': js('b.js.map'), 'b.js.map': MAP_WITH_SOURCES },
549
+ },
550
+ })
551
+
552
+ await uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' }, {
553
+ deleteBrowserSourcemaps: true,
554
+ })
555
+
556
+ expect(fs.existsSync('.next/static/a.js.map')).toBe(false)
557
+ expect(fs.existsSync('.next/server/b.js.map')).toBe(true)
558
+ })
559
+
560
+ // The maps are regenerated by the next build; a deploy that served them is not
561
+ // recallable. So exposure wins over keeping "the only copy".
562
+ it('removes them even when the upload failed', async () => {
563
+ uploadSourcemaps.mockRejectedValue(new Error('honeybadger is down'))
564
+
565
+ await expect(
566
+ uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' }, {
567
+ deleteBrowserSourcemaps: true,
568
+ })
569
+ ).rejects.toThrow('honeybadger is down')
570
+
571
+ expect(fs.existsSync('.next/static/a.js.map')).toBe(false)
572
+ })
573
+
574
+ // The dangerous combination: `ignoreErrors` is what the docs recommend so a Honeybadger
575
+ // outage cannot block a deploy, which means a failed upload produces a *successful*
576
+ // build. Skipping cleanup there would publish the source of every such build.
577
+ it('removes them when a failed upload is ignored', async () => {
578
+ const error = jest.spyOn(console, 'error').mockImplementation(() => undefined)
579
+ uploadSourcemaps.mockRejectedValue(new Error('honeybadger is down'))
580
+
581
+ await expect(
582
+ uploadSourceMapsAfterBuild(
583
+ { ...configured, ignoreErrors: true },
584
+ { distDir: '.next', projectDir: '.' },
585
+ { deleteBrowserSourcemaps: true }
586
+ )
587
+ ).resolves.toBeUndefined()
588
+
589
+ expect(fs.existsSync('.next/static/a.js.map')).toBe(false)
590
+ error.mockRestore()
591
+ })
592
+
593
+ // Collection runs before upload, so its failures take the same path.
594
+ it('removes them when collection itself failed', async () => {
595
+ const error = jest.spyOn(console, 'error').mockImplementation(() => undefined)
596
+ const readdir = jest.spyOn(fs.promises, 'readdir')
597
+ readdir.mockRejectedValueOnce(Object.assign(new Error('EACCES'), { code: 'EACCES' }))
598
+
599
+ await expect(
600
+ uploadSourceMapsAfterBuild(
601
+ { ...configured, ignoreErrors: true },
602
+ { distDir: '.next', projectDir: '.' },
603
+ { deleteBrowserSourcemaps: true }
604
+ )
605
+ ).resolves.toBeUndefined()
606
+
607
+ expect(fs.existsSync('.next/static/a.js.map')).toBe(false)
608
+ readdir.mockRestore()
609
+ error.mockRestore()
610
+ })
611
+
612
+ // Resolving the options is itself fallible — cleanOptions can throw, and plugin-core
613
+ // can fail to load. Doing that outside the error handling meant such a failure ignored
614
+ // ignoreErrors and skipped cleanup, leaving the maps served.
615
+ it('removes them when resolving the options failed', async () => {
616
+ const error = jest.spyOn(console, 'error').mockImplementation(() => undefined)
617
+ cleanOptionsError = new Error('plugin-core exploded')
618
+
619
+ await expect(
620
+ uploadSourceMapsAfterBuild(
621
+ { ...configured, ignoreErrors: true },
622
+ { distDir: '.next', projectDir: '.' },
623
+ { deleteBrowserSourcemaps: true }
624
+ )
625
+ ).resolves.toBeUndefined()
626
+
627
+ expect(fs.existsSync('.next/static/a.js.map')).toBe(false)
628
+ error.mockRestore()
629
+ })
630
+
631
+ it('still fails the build for that failure when ignoreErrors is off', async () => {
632
+ cleanOptionsError = new Error('plugin-core exploded')
633
+
634
+ await expect(
635
+ uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' }, {
636
+ deleteBrowserSourcemaps: true,
637
+ })
638
+ ).rejects.toThrow('plugin-core exploded')
639
+
640
+ expect(fs.existsSync('.next/static/a.js.map')).toBe(false)
641
+ })
642
+
643
+ // A dev/test build never uploads, so it never enabled the maps either — leave the
644
+ // developer's build output alone.
645
+ it('leaves them alone in a development build', async () => {
646
+ setNodeEnv('development')
647
+
648
+ await uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' }, {
649
+ deleteBrowserSourcemaps: true,
650
+ })
651
+
652
+ expect(fs.existsSync('.next/static/a.js.map')).toBe(true)
653
+ })
654
+
655
+ // Cleanup must not replace the error the caller is about to see. Collection walks the
656
+ // same directories as cleanup, so the failure has to start only once upload has run —
657
+ // otherwise collection throws first and the scenario never happens.
658
+ it('does not let a cleanup failure mask the upload failure', async () => {
659
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined)
660
+ const realReaddir = fs.promises.readdir
661
+ let cleanupPhase = false
662
+
663
+ uploadSourcemaps.mockImplementation(async () => {
664
+ cleanupPhase = true
665
+ throw new Error('honeybadger is down')
666
+ })
667
+ const readdir = jest.spyOn(fs.promises, 'readdir').mockImplementation(((...args: unknown[]) => {
668
+ if (cleanupPhase) {
669
+ return Promise.reject(Object.assign(new Error('EACCES'), { code: 'EACCES' }))
670
+ }
671
+ return (realReaddir as (...a: unknown[]) => unknown)(...args)
672
+ }) as never)
673
+
674
+ await expect(
675
+ uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' }, {
676
+ deleteBrowserSourcemaps: true,
677
+ })
678
+ ).rejects.toThrow('honeybadger is down')
679
+
680
+ expect(warn).toHaveBeenCalledWith(
681
+ '[HoneybadgerNextJs]',
682
+ expect.stringContaining('could not clean up browser source maps')
683
+ )
684
+ readdir.mockRestore()
685
+ warn.mockRestore()
686
+ })
687
+ })
688
+
689
+ // A configured upload that finds nothing looks identical to success in the build log,
690
+ // which is how a moved distDir or an over-broad ignorePaths goes unnoticed.
691
+ describe('when there is nothing to upload', () => {
692
+ beforeEach(() => {
693
+ setNodeEnv('production')
694
+ })
695
+
696
+ it('warns instead of reporting a silent success', async () => {
697
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined)
698
+ mock({ '.next': { 'static': {} } })
699
+
700
+ await uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' })
701
+
702
+ expect(uploadSourcemaps).not.toHaveBeenCalled()
703
+ expect(warn).toHaveBeenCalledWith(
704
+ '[HoneybadgerNextJs]',
705
+ expect.stringContaining('found no source maps to upload')
706
+ )
707
+ warn.mockRestore()
708
+ })
709
+
710
+ // A directory that does not exist is normal: `.next/server` is absent unless
711
+ // experimental.serverSourceMaps is on.
712
+ // The deploy notification reads as "the maps for this revision are in place". A failed
713
+ // upload already skips it by throwing; a build that uploaded nothing must too.
714
+ it('does not announce a deploy when nothing was uploaded', async () => {
715
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined)
716
+ mock({ '.next': { 'static': {} } })
717
+
718
+ await uploadSourceMapsAfterBuild(
719
+ { ...configured, deploy: { environment: 'production' } },
720
+ { distDir: '.next', projectDir: '.' }
721
+ )
722
+
723
+ expect(sendDeployNotification).not.toHaveBeenCalled()
724
+ warn.mockRestore()
725
+ })
726
+
727
+ // Bailing out early must not skip the cleanup: the maps are on disk and served whether
728
+ // or not any of them were worth uploading.
729
+ it('still removes browser maps when there was nothing to upload', async () => {
730
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => undefined)
731
+ // Present on disk, but rejected by collectSourcemaps for having no sourcesContent.
732
+ mock({ '.next': { 'static': { 'a.js': js('a.js.map'), 'a.js.map': MAP_WITHOUT_SOURCES } } })
733
+
734
+ await uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' }, {
735
+ deleteBrowserSourcemaps: true,
736
+ })
737
+
738
+ expect(uploadSourcemaps).not.toHaveBeenCalled()
739
+ expect(fs.existsSync('.next/static/a.js.map')).toBe(false)
740
+ warn.mockRestore()
741
+ })
742
+
743
+ it('treats a missing distDir as empty rather than an error', async () => {
744
+ mock({})
745
+
746
+ await expect(collectSourcemaps('.next')).resolves.toEqual([])
747
+ })
748
+
749
+ // Anything other than ENOENT would silently shrink the upload to whatever happened to
750
+ // be readable, which is worse than failing.
751
+ it('propagates a readdir failure that is not a missing directory', async () => {
752
+ const readdir = jest.spyOn(fs.promises, 'readdir')
753
+ .mockRejectedValue(Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' }))
754
+
755
+ await expect(collectSourcemaps('.next')).rejects.toThrow('EACCES')
756
+
757
+ readdir.mockRestore()
758
+ })
759
+
760
+ it('lets ignoreErrors govern that failure like any other', async () => {
761
+ const error = jest.spyOn(console, 'error').mockImplementation(() => undefined)
762
+ const readdir = jest.spyOn(fs.promises, 'readdir')
763
+ .mockRejectedValue(Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' }))
764
+
765
+ await expect(
766
+ uploadSourceMapsAfterBuild(
767
+ { ...configured, ignoreErrors: true },
768
+ { distDir: '.next', projectDir: '.' }
769
+ )
770
+ ).resolves.toBeUndefined()
771
+
772
+ readdir.mockRestore()
773
+ error.mockRestore()
774
+ })
775
+ })
776
+
777
+ describe('when the upload fails', () => {
778
+ beforeEach(() => {
779
+ setNodeEnv('production')
780
+ mock({ '.next': { 'static': { 'a.js': js('a.js.map'), 'a.js.map': MAP_WITH_SOURCES } } })
781
+ uploadSourcemaps.mockRejectedValue(new Error('honeybadger is down'))
782
+ })
783
+
784
+ it('fails the build by default, because Next re-throws this hook', async () => {
785
+ await expect(
786
+ uploadSourceMapsAfterBuild(configured, { distDir: '.next', projectDir: '.' })
787
+ ).rejects.toThrow('honeybadger is down')
788
+ })
789
+
790
+ it('does not fail the build when ignoreErrors is set', async () => {
791
+ jest.spyOn(console, 'error').mockImplementation(() => undefined)
792
+
793
+ await expect(
794
+ uploadSourceMapsAfterBuild(
795
+ { ...configured, ignoreErrors: true },
796
+ { distDir: '.next', projectDir: '.' }
797
+ )
798
+ ).resolves.toBeUndefined()
799
+
800
+ expect(uploadSourcemaps).toHaveBeenCalled()
801
+ })
802
+ })
803
+ })