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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
import { assertNoRedbox, check, retry } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
import { nextTestSetup } from 'e2e-utils'

describe('middleware - development errors', () => {
  const { next, isTurbopack } = nextTestSetup({
    files: __dirname,
    env: { __NEXT_TEST_WITH_DEVTOOL: '1' },
    patchFileDelay: 500,
  })
  beforeEach(async () => {
    await next.stop()
  })

  describe('when middleware throws synchronously', () => {
    beforeEach(async () => {
      await next.patchFile(
        'middleware.js',
        `
      export default function () {
        throw new Error('boom')
      }`
      )

      await next.start()
    })

    it('logs the error correctly', async () => {
      await next.fetch('/')

      await retry(() => {
        expect(stripAnsi(next.cliOutput)).toContain('boom')
      })
      expect(stripAnsi(next.cliOutput)).toContain(
        isTurbopack
          ? '\n ⨯ Error: boom' +
              // TODO(veil): Sourcemap to original name i.e. "default"
              '\n    at __TURBOPACK__default__export__ (middleware.js:3:15)' +
              '\n  1 |'
          : '\n ⨯ Error: boom' +
              '\n    at default (middleware.js:3:15)' +
              '\n  1 |'
      )
      expect(stripAnsi(next.cliOutput)).toContain(
        '' +
          "\n> 3 |         throw new Error('boom')" +
          '\n    |               ^'
      )
    })

    it('renders the error correctly and recovers', async () => {
      const browser = await next.browser('/')

      if (isTurbopack) {
        await expect(browser).toDisplayRedbox(`
         {
           "description": "boom",
           "environmentLabel": null,
           "label": "Runtime Error",
           "source": "middleware.js (3:15) @
         {default export}
         > 3 |         throw new Error('boom')
             |               ^",
           "stack": [
             "{default export} middleware.js (3:15)",
           ],
         }
        `)
      } else {
        await expect(browser).toDisplayRedbox(`
         {
           "description": "boom",
           "environmentLabel": null,
           "label": "Runtime Error",
           "source": "middleware.js (3:15) @ default
         > 3 |         throw new Error('boom')
             |               ^",
           "stack": [
             "default middleware.js (3:15)",
           ],
         }
        `)
      }

      await next.patchFile('middleware.js', `export default function () {}`)

      await assertNoRedbox(browser)
    })
  })

  describe('when middleware contains an unhandled rejection', () => {
    beforeEach(async () => {
      await next.patchFile(
        'middleware.js',
        `
      import { NextResponse } from 'next/server'
      async function throwError() {
        throw new Error('async boom!')
      }
      export default function () {
        throwError()
        return NextResponse.next()
      }`
      )

      await next.start()
    })

    it('logs the error correctly', async () => {
      await next.fetch('/')

      await retry(() => {
        expect(stripAnsi(next.cliOutput)).toContain(
          'unhandledRejection: Error: async boom!'
        )
      })
      expect(stripAnsi(next.cliOutput)).toContain(
        isTurbopack
          ? ' ⨯ unhandledRejection:  Error: async boom!' +
              '\n    at throwError (middleware.js:4:15)' +
              // TODO(veil): Sourcemap to original name i.e. "default"
              '\n    at __TURBOPACK__default__export__ (middleware.js:7:9)' +
              "\n  2 |       import { NextResponse } from 'next/server'"
          : '\n ⨯ unhandledRejection:  Error: async boom!' +
              '\n    at throwError (middleware.js:4:15)' +
              '\n    at default (middleware.js:7:9)' +
              "\n  2 |       import { NextResponse } from 'next/server'"
      )
      expect(stripAnsi(next.cliOutput)).toContain(
        '' +
          "\n> 4 |         throw new Error('async boom!')" +
          '\n    |               ^'
      )
    })

    it('does not render the error', async () => {
      const browser = await next.browser('/')
      await assertNoRedbox(browser)
      expect(await browser.elementByCss('#page-title')).toBeTruthy()
    })
  })

  describe('when running invalid dynamic code with eval', () => {
    beforeEach(async () => {
      await next.patchFile(
        'middleware.js',
        `
      import { NextResponse } from 'next/server'
      export default function () {
        eval('test')
        return NextResponse.next()
      }`
      )

      await next.start()
    })

    it('logs the error correctly', async () => {
      await next.fetch('/')

      await retry(() => {
        expect(stripAnsi(next.cliOutput)).toContain('Dynamic Code Evaluation')
      })
      if (isTurbopack) {
        // Locally, prefixes the "test is not defined".
        // In CI, it prefixes "Dynamic Code Evaluation".
        expect(stripAnsi(next.cliOutput)).toContain(
          // TODO(veil): Should be sourcemapped
          '\n    at __TURBOPACK__default__export__ (.next/'
        )
      }
      expect(stripAnsi(next.cliOutput)).toContain(
        isTurbopack
          ? '\n ⨯ Error [ReferenceError]: test is not defined' +
              '\n    at eval (middleware.js:4:9)' +
              '\n    at <unknown> (middleware.js:4:9)' +
              // TODO(veil): Should be sourcemapped
              '\n    at __TURBOPACK__default__export__ ('
          : '\n ⨯ Error [ReferenceError]: test is not defined' +
              // TODO(veil): Redundant and not clickable
              '\n    at eval (file://webpack-internal:///(middleware)/./middleware.js)' +
              '\n    at eval (middleware.js:4:9)' +
              '\n    at default (middleware.js:4:9)' +
              "\n  2 |       import { NextResponse } from 'next/server'"
      )
      expect(stripAnsi(next.cliOutput)).toContain(
        isTurbopack
          ? "\n ⚠ DynamicCodeEvaluationWarning: Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime" +
              '\nLearn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation' +
              // TODO(veil): Should be sourcemapped
              '\n    at __TURBOPACK__default__export__ ('
          : "\n ⚠ DynamicCodeEvaluationWarning: Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime" +
              '\nLearn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation' +
              '\n    at default (middleware.js:4:9)' +
              "\n  2 |       import { NextResponse } from 'next/server'"
      )
    })

    it('renders the error correctly and recovers', async () => {
      const browser = await next.browser('/')

      if (isTurbopack) {
        await expect(browser).toDisplayRedbox(`
         {
           "description": "test is not defined",
           "environmentLabel": null,
           "label": "Runtime ReferenceError",
           "source": "middleware.js (4:9) @ eval
         > 4 |         eval('test')
             |         ^",
           "stack": [
             "eval middleware.js (4:9)",
             "<unknown> middleware.js (4:9)",
             "{default export} middleware.js (3:22)",
           ],
         }
        `)
      } else {
        await expect(browser).toDisplayRedbox(`
         {
           "description": "test is not defined",
           "environmentLabel": null,
           "label": "Runtime ReferenceError",
           "source": "middleware.js (4:9) @ eval
         > 4 |         eval('test')
             |         ^",
           "stack": [
             "<FIXME-file-protocol>",
             "eval middleware.js (4:9)",
             "default middleware.js (4:9)",
           ],
         }
        `)
      }

      const lengthOfLogs = next.cliOutput.length
      await next.patchFile('middleware.js', `export default function () {}`)

      retry(() => {
        expect(next.cliOutput.slice(lengthOfLogs)).toContain('✓ Compiled')
      }, 10000) // middleware rebuild takes a while in CI

      await assertNoRedbox(browser)
    })
  })

  describe('when throwing while loading the module', () => {
    beforeEach(async () => {
      await next.patchFile(
        'middleware.js',
        `
      import { NextResponse } from 'next/server'
      throw new Error('booooom!')
      export default function () {
        return NextResponse.next()
      }`
      )
      await next.start()
    })

    it('logs the error correctly', async () => {
      await next.fetch('/')

      await retry(() => {
        expect(stripAnsi(next.cliOutput)).toContain(`Error: booooom!`)
      })
      expect(stripAnsi(next.cliOutput)).toContain(
        isTurbopack
          ? '\n ⨯ Error: booooom!' +
              // TODO(veil): Should be sourcemapped
              '\n    at [project]/middleware.js [middleware-edge] (ecmascript)'
          : '\n ⨯ Error: booooom!' +
              // TODO: Should be anonymous method without a method name
              '\n    at <unknown> (middleware.js:3)' +
              // TODO: Should be ignore-listed
              '\n    at eval (middleware.js:3:13)' +
              '\n    at (middleware)/./middleware.js (.next/server/middleware.js:18:1)' +
              '\n    at __webpack_require__ '
      )
    })

    it('renders the error correctly and recovers', async () => {
      const browser = await next.browser('/')

      if (isTurbopack) {
        await expect(browser).toDisplayRedbox(`
         {
           "description": "booooom!",
           "environmentLabel": null,
           "label": "Runtime Error",
           "source": "middleware.js (3:13) @ [project]/middleware.js [middleware-edge] (ecmascript)
         > 3 |       throw new Error('booooom!')
             |             ^",
           "stack": [
             "[project]/middleware.js [middleware-edge] (ecmascript) middleware.js (3:13)",
           ],
         }
        `)
      } else {
        await expect(browser).toDisplayRedbox(`
         {
           "description": "booooom!",
           "environmentLabel": null,
           "label": "Runtime Error",
           "source": "middleware.js (3:13) @ eval
         > 3 |       throw new Error('booooom!')
             |             ^",
           "stack": [
             "<unknown> middleware.js (3)",
             "eval middleware.js (3:13)",
             "<FIXME-next-dist-dir>",
             "<FIXME-next-dist-dir>",
             "<FIXME-next-dist-dir>",
             "<FIXME-next-dist-dir>",
             "<FIXME-next-dist-dir>",
             "<FIXME-next-dist-dir>",
             "<FIXME-next-dist-dir>",
             "<FIXME-next-dist-dir>",
           ],
         }
        `)
      }

      await next.patchFile('middleware.js', `export default function () {}`)

      await assertNoRedbox(browser)
    })
  })

  describe('when there is an unhandled rejection while loading the module', () => {
    beforeEach(async () => {
      await next.patchFile(
        'middleware.js',
        `
      import { NextResponse } from 'next/server'
      (async function(){
        throw new Error('you shall see me')
      })()

      export default function () {
        return NextResponse.next()
      }`
      )

      await next.start()
    })

    it('logs the error correctly', async () => {
      await next.fetch('/')
      await check(
        () => stripAnsi(next.cliOutput),
        new RegExp(`unhandledRejection: Error: you shall see me`, 'm')
      )
      // expect(output).not.toContain(
      //   'webpack-internal:///(middleware)/./middleware.js'
      // )
    })

    it('does not render the error', async () => {
      const browser = await next.browser('/')
      await assertNoRedbox(browser)
      expect(await browser.elementByCss('#page-title')).toBeTruthy()
    })
  })

  describe('when there is an unhandled rejection while loading a dependency', () => {
    beforeEach(async () => {
      await next.patchFile(
        'middleware.js',
        `
      import { NextResponse } from 'next/server'
      import './lib/unhandled'

      export default function () {
        return NextResponse.next()
      }`
      )

      await next.start()
    })

    it('logs the error correctly', async () => {
      await next.fetch('/')
      const output = stripAnsi(next.cliOutput)
      await check(
        () => stripAnsi(next.cliOutput),
        new RegExp(
          ` uncaughtException: Error: This file asynchronously fails while loading`,
          'm'
        )
      )
      expect(output).not.toContain(
        'webpack-internal:///(middleware)/./middleware.js'
      )
    })

    it('does not render the error', async () => {
      const browser = await next.browser('/')
      await assertNoRedbox(browser)
      expect(await browser.elementByCss('#page-title')).toBeTruthy()
    })
  })

  describe('when there is a compilation error from boot', () => {
    beforeEach(async () => {
      await next.patchFile('middleware.js', `export default function () }`)

      await next.start()
    })

    it('logs the error correctly', async () => {
      await next.fetch('/')
      await check(async () => {
        expect(next.cliOutput).toContain(`Expected '{', got '}'`)
        expect(
          next.cliOutput.split(`Expected '{', got '}'`).length
        ).toBeGreaterThanOrEqual(2)

        return 'success'
      }, 'success')
    })

    it('renders the error correctly and recovers', async () => {
      const browser = await next.browser('/')

      if (isTurbopack) {
        await expect(browser).toDisplayRedbox(`
         {
           "description": "Parsing ecmascript source code failed",
           "environmentLabel": null,
           "label": "Build Error",
           "source": "./middleware.js (1:28)
         Parsing ecmascript source code failed
         > 1 | export default function () }
             |                            ^",
           "stack": [],
         }
        `)
      } else {
        await expect(browser).toDisplayRedbox(`
         {
           "description": "  x Expected '{', got '}'",
           "environmentLabel": null,
           "label": "Build Error",
           "source": "./middleware.js
         Error:   x Expected '{', got '}'
            ,----
          1 | export default function () }
            :                            ^
            \`----
         Caused by:
             Syntax Error",
           "stack": [],
         }
        `)
      }

      await next.patchFile('middleware.js', `export default function () {}`)

      await assertNoRedbox(browser)
      expect(await browser.elementByCss('#page-title')).toBeTruthy()
    })
  })

  describe('when there is a compilation error after boot', () => {
    beforeEach(async () => {
      await next.patchFile('middleware.js', `export default function () {}`)

      await next.start()
    })

    it('logs the error correctly', async () => {
      await next.patchFile('middleware.js', `export default function () }`)
      await next.fetch('/')

      await check(() => {
        expect(next.cliOutput).toContain(`Expected '{', got '}'`)
        expect(
          next.cliOutput.split(`Expected '{', got '}'`).length
        ).toBeGreaterThanOrEqual(2)
        return 'success'
      }, 'success')
    })

    it('renders the error correctly and recovers', async () => {
      const browser = await next.browser('/')

      await assertNoRedbox(browser)

      await next.patchFile('middleware.js', `export default function () }`)

      if (isTurbopack) {
        await expect(browser).toDisplayRedbox(`
         {
           "description": "Parsing ecmascript source code failed",
           "environmentLabel": null,
           "label": "Build Error",
           "source": "./middleware.js (1:28)
         Parsing ecmascript source code failed
         > 1 | export default function () }
             |                            ^",
           "stack": [],
         }
        `)
      } else {
        await expect(browser).toDisplayRedbox(`
         {
           "description": "  x Expected '{', got '}'",
           "environmentLabel": null,
           "label": "Build Error",
           "source": "./middleware.js
         Error:   x Expected '{', got '}'
            ,----
          1 | export default function () }
            :                            ^
            \`----
         Caused by:
             Syntax Error",
           "stack": [],
         }
        `)
      }

      await next.patchFile('middleware.js', `export default function () {}`)

      await assertNoRedbox(browser)
      expect(await browser.elementByCss('#page-title')).toBeTruthy()
    })
  })
})