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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
import { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path'
import { createSandbox } from 'development-sandbox'
import { outdent } from 'outdent'

describe('Error overlay - RSC build errors', () => {
  const { next, isTurbopack } = nextTestSetup({
    files: new FileRef(path.join(__dirname, 'fixtures', 'rsc-build-errors')),
    skipStart: true,
  })

  it('should throw an error when getServerSideProps is used', async () => {
    await using sandbox = await createSandbox(
      next,
      undefined,
      '/client-with-errors/get-server-side-props'
    )
    const { session } = sandbox
    const pageFile = 'app/client-with-errors/get-server-side-props/page.js'
    const content = await next.readFile(pageFile)
    const uncomment = content.replace(
      '// export function getServerSideProps',
      'export function getServerSideProps'
    )
    await session.patch(pageFile, uncomment)

    await session.assertHasRedbox()
    expect(await session.getRedboxSource()).toInclude(
      '"getServerSideProps" is not supported in app/'
    )
  })

  it('should throw an error when metadata export is used in client components', async () => {
    await using sandbox = await createSandbox(
      next,
      undefined,
      '/client-with-errors/metadata-export'
    )
    const { session } = sandbox
    const pageFile = 'app/client-with-errors/metadata-export/page.js'
    const content = await next.readFile(pageFile)

    // Add `metadata` error
    let uncomment = content.replace(
      '// export const metadata',
      'export const metadata'
    )
    await session.patch(pageFile, uncomment)
    await session.assertHasRedbox()
    expect(await session.getRedboxSource()).toInclude(
      'You are attempting to export "metadata" from a component marked with "use client", which is disallowed.'
    )

    // Restore file
    await session.patch(pageFile, content)
    await session.assertNoRedbox()

    // Add `generateMetadata` error
    uncomment = content.replace(
      '// export async function generateMetadata',
      'export async function generateMetadata'
    )
    await session.patch(pageFile, uncomment)
    await session.assertHasRedbox()
    expect(await session.getRedboxSource()).toInclude(
      'You are attempting to export "generateMetadata" from a component marked with "use client", which is disallowed.'
    )

    // Fix the error again to test error overlay works with hmr rebuild
    await session.patch(pageFile, content)
    await session.assertNoRedbox()
  })

  it('should throw an error when metadata exports are used together in server components', async () => {
    await using sandbox = await createSandbox(
      next,
      undefined,
      '/server-with-errors/metadata-export'
    )
    const { session } = sandbox
    const pageFile = 'app/server-with-errors/metadata-export/page.js'
    const content = await next.readFile(pageFile)
    const uncomment = content.replace(
      '// export async function generateMetadata',
      'export async function generateMetadata'
    )

    await session.patch(pageFile, uncomment)
    await session.assertHasRedbox()
    expect(await session.getRedboxSource()).toInclude(
      '"metadata" and "generateMetadata" cannot be exported at the same time, please keep one of them.'
    )
  })

  // TODO: investigate flakey test case
  it.skip('should throw an error when getStaticProps is used', async () => {
    await using sandbox = await createSandbox(
      next,
      undefined,
      '/client-with-errors/get-static-props'
    )
    const { session } = sandbox
    const pageFile = 'app/client-with-errors/get-static-props/page.js'
    const content = await next.readFile(pageFile)
    const uncomment = content.replace(
      '// export function getStaticProps',
      'export function getStaticProps'
    )
    await session.patch(pageFile, uncomment)
    await next.patchFile(pageFile, content)

    await session.assertHasRedbox()
    expect(await session.getRedboxSource()).toInclude(
      '"getStaticProps" is not supported in app/'
    )
  })

  it('should throw an error when "use client" is on the top level but after other expressions', async () => {
    await using sandbox = await createSandbox(
      next,
      undefined,
      '/swc/use-client'
    )
    const { session } = sandbox
    const pageFile = 'app/swc/use-client/page.js'
    const content = await next.readFile(pageFile)
    const uncomment = content.replace("// 'use client'", "'use client'")
    await next.patchFile(pageFile, uncomment)

    await session.assertHasRedbox()
    expect(await session.getRedboxSource()).toInclude(
      'directive must be placed before other expressions'
    )
  })

  it('should throw an error when "Component" is imported in server components', async () => {
    await using sandbox = await createSandbox(
      next,
      undefined,
      '/server-with-errors/class-component'
    )
    const { session } = sandbox
    const pageFile = 'app/server-with-errors/class-component/page.js'
    const content = await next.readFile(pageFile)
    const uncomment = content.replace(
      "// import { Component } from 'react'",
      "import { Component } from 'react'"
    )
    await session.patch(pageFile, uncomment)

    await session.assertHasRedbox()
    expect(await session.getRedboxSource()).toInclude(
      `You’re importing a class component. It only works in a Client Component`
    )
  })

  it('should allow to use and handle rsc poisoning client-only', async () => {
    await using sandbox = await createSandbox(
      next,
      undefined,
      '/server-with-errors/client-only-in-server'
    )
    const { session } = sandbox
    const file =
      'app/server-with-errors/client-only-in-server/client-only-lib.js'
    const content = await next.readFile(file)
    const uncomment = content.replace(
      "// import 'client-only'",
      "import 'client-only'"
    )
    await next.patchFile(file, uncomment)

    await session.assertHasRedbox()
    if (isTurbopack) {
      // TODO: fix the issue ordering.
      // turbopack emits the resolve issue first instead of the transform issue.
      expect(await session.getRedboxSource()).toMatchInlineSnapshot(`
       "./app/server-with-errors/client-only-in-server/client-only-lib.js (1:1)
       Ecmascript file had an error
       > 1 | import 'client-only'
           | ^^^^^^^^^^^^^^^^^^^^
         2 |
         3 | export default function ClientOnlyLib() {
         4 |   return 'client-only-lib'

       You're importing a component that imports client-only. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.
       Learn more: https://nextjs.org/docs/app/building-your-application/rendering

       Import trace:
         Server Component:
           ./app/server-with-errors/client-only-in-server/client-only-lib.js
           ./app/server-with-errors/client-only-in-server/page.js"
      `)
    } else {
      expect(await session.getRedboxSource()).toInclude(
        `You're importing a component that imports client-only. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.`
      )
    }
  })

  const invalidReactServerApis = [
    'Component',
    'createContext',
    'createFactory',
    'PureComponent',
    'useDeferredValue',
    'useEffect',
    'useImperativeHandle',
    'useInsertionEffect',
    'useLayoutEffect',
    'useReducer',
    'useRef',
    'useState',
    'useSyncExternalStore',
    'useTransition',
    'useOptimistic',
    'useActionState',
  ]
  for (const api of invalidReactServerApis) {
    it(`should error when ${api} from react is used in server component`, async () => {
      await using sandbox = await createSandbox(
        next,
        undefined,
        `/server-with-errors/react-apis/${api.toLowerCase()}`
      )
      const { session } = sandbox
      await session.assertHasRedbox()
      expect(await session.getRedboxSource()).toInclude(
        // `Component` has a custom error message
        api === 'Component'
          ? `You’re importing a class component. It only works in a Client Component but none of its parents are marked with "use client", so they're Server Components by default.`
          : `You're importing a component that needs \`${api}\`. This React Hook only works in a Client Component. To fix, mark the file (or its parent) with the \`"use client"\` directive.`
      )
    })
  }

  const invalidReactDomServerApis = [
    'flushSync',
    'unstable_batchedUpdates',
    'useFormStatus',
    'useFormState',
  ]
  for (const api of invalidReactDomServerApis) {
    it(`should error when ${api} from react-dom is used in server component`, async () => {
      await using sandbox = await createSandbox(
        next,
        undefined,
        `/server-with-errors/react-dom-apis/${api.toLowerCase()}`
      )
      const { session } = sandbox
      await session.assertHasRedbox()
      expect(await session.getRedboxSource()).toInclude(
        `You're importing a component that needs \`${api}\`. This React Hook only works in a Client Component. To fix, mark the file (or its parent) with the \`"use client"\` directive.`
      )
    })
  }

  it('should allow to use and handle rsc poisoning server-only', async () => {
    await using sandbox = await createSandbox(
      next,
      undefined,
      '/client-with-errors/server-only-in-client'
    )
    const { session } = sandbox
    const file =
      'app/client-with-errors/server-only-in-client/server-only-lib.js'
    const content = await next.readFile(file)
    const uncomment = content.replace(
      "// import 'server-only'",
      "import 'server-only'"
    )

    await session.patch(file, uncomment)

    await session.assertHasRedbox()
    expect(await session.getRedboxSource()).toInclude(
      `You're importing a component that needs "server-only". That only works in a Server Component but one of its parents is marked with "use client", so it's a Client Component.`
    )
  })

  describe("importing 'next/cache' APIs in a client component", () => {
    test.each([
      'revalidatePath',
      'revalidateTag',
      'unstable_cacheLife',
      'unstable_cacheTag',
      'unstable_expirePath',
      'unstable_expireTag',
    ])('%s is not allowed', async (api) => {
      await using sandbox = await createSandbox(
        next,
        undefined,
        `/server-with-errors/next-cache-in-client/${api.toLowerCase()}`
      )
      const { session } = sandbox
      await session.assertHasRedbox()
      expect(await session.getRedboxSource()).toInclude(
        `You're importing a component that needs "${api}". That only works in a Server Component but one of its parents is marked with "use client", so it's a Client Component.`
      )
    })

    test.each([
      'unstable_cache', // useless in client, but doesn't technically error
      'unstable_noStore', // no-op in client, but allowed for legacy reasons
    ])('%s is allowed', async (api) => {
      await using sandbox = await createSandbox(
        next,
        undefined,
        `/server-with-errors/next-cache-in-client/${api.toLowerCase()}`
      )
      const { session } = sandbox
      await session.assertNoRedbox()
    })
  })

  it('should error for invalid undefined module retuning from next dynamic', async () => {
    await using sandbox = await createSandbox(
      next,
      undefined,
      '/client-with-errors/dynamic'
    )
    const { session } = sandbox
    const file = 'app/client-with-errors/dynamic/page.js'
    const content = await next.readFile(file)
    await session.patch(
      file,
      content.replace('() => <p>hello dynamic world</p>', 'undefined')
    )

    await session.assertHasRedbox()
    expect(await session.getRedboxDescription()).toInclude(
      `Element type is invalid. Received a promise that resolves to: undefined. Lazy element type must resolve to a class or function.`
    )
  })

  it('should throw an error when error file is a server component', async () => {
    await using sandbox = await createSandbox(
      next,
      undefined,
      '/server-with-errors/error-file'
    )
    const { session } = sandbox
    // Remove "use client"
    await session.patch(
      'app/server-with-errors/error-file/error.js',
      'export default function Error() {}'
    )

    await session.assertHasRedbox()
    await expect(session.getRedboxSource()).resolves.toMatch(
      /must be a Client \n| Component/
    )
    if (process.env.IS_TURBOPACK_TEST) {
      expect(next.normalizeTestDirContent(await session.getRedboxSource()))
        .toMatchInlineSnapshot(`
       "./app/server-with-errors/error-file/error.js (1:1)
       Ecmascript file had an error
       > 1 | export default function Error() {}
           | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

       app/server-with-errors/error-file/error.js must be a Client Component. Add the "use client" directive the top of the file to resolve this issue.
       Learn more: https://nextjs.org/docs/app/api-reference/directives/use-client"
      `)
    } else {
      await expect(session.getRedboxSource()).resolves.toMatch(
        /Add the "use client"/
      )

      // TODO: investigate flakey snapshot due to spacing below
      // expect(next.normalizeTestDirContent(await session.getRedboxSource()))
      //   .toMatchInlineSnapshot(`
      //   "./app/server-with-errors/error-file/error.js
      //   Error:   x TEST_DIR/app/server-with-errors/error-file/error.js must be a Client
      //     | Component. Add the "use client" directive the top of the file to resolve this issue.
      //     | Learn more: https://nextjs.org/docs/app/api-reference/directives/use-client
      //     |
      //     |
      //      ,----
      //    1 | export default function Error() {}
      //      : ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      //      \`----

      //   Import trace for requested module:
      //   ./app/server-with-errors/error-file/error.js"
      // `)
    }
  })

  it('should throw an error when error file is a server component with empty error file', async () => {
    await using sandbox = await createSandbox(
      next,
      undefined,
      '/server-with-errors/error-file'
    )
    const { session } = sandbox
    // Empty file
    await session.patch('app/server-with-errors/error-file/error.js', '')

    await session.assertHasRedbox()
    await expect(session.getRedboxSource()).resolves.toMatch(
      /Add the "use client"/
    )

    // TODO: investigate flakey snapshot due to spacing below
    // expect(next.normalizeTestDirContent(await session.getRedboxSource()))
    //   .toMatchInlineSnapshot(n`
    //   "./app/server-with-errors/error-file/error.js
    //   ReactServerComponentsError:

    //   ./app/server-with-errors/error-file/error.js must be a Client Component. Add the "use client" directive the top of the file to resolve this issue.

    //      ,-[TEST_DIR/app/server-with-errors/error-file/error.js:1:1]
    //    1 |
    //      : ^
    //      \`----

    //   Import path:
    //   ./app/server-with-errors/error-file/error.js"
    // `)
  })

  it('should freeze parent resolved metadata to avoid mutating in generateMetadata', async () => {
    const pagePath = 'app/metadata/mutate/page.js'
    const content = outdent`
      export default function page(props) {
        return <p>mutate</p>
      }

      export async function generateMetadata(props, parent) {
        const parentMetadata = await parent
        parentMetadata.x = 1
        return {
          ...parentMetadata,
        }
      }
    `

    await using sandbox = await createSandbox(
      next,
      undefined,
      '/metadata/mutate'
    )
    const { session } = sandbox
    await session.patch(pagePath, content)

    await session.assertHasRedbox()

    expect(await session.getRedboxDescription()).toContain(
      'Cannot add property x, object is not extensible'
    )
  })
})