File size: 10,879 Bytes
b91e262
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Testing console patching in Jest requires isolation since console methods are heavily used
 * by the test runner itself. We use the same worker thread strategy as unhandled-rejection.test.ts
 * to ensure our patches don't interfere with Jest's own console usage.
 *
 * @jest-environment node
 */

/* eslint-disable @next/internal/typechecked-require */

type ReportableResult =
  | ConsoleCallReport
  | ErrorReport
  | OutputReport
  | SerializableDataReport

type ConsoleCallReport = {
  type: 'console-call'
  method: string
  input: string
}

type ErrorReport = { type: 'error'; message: string }
type OutputReport = { type: 'output'; message: string }
type SerializableDataReport = {
  type: 'serialized'
  key: string
  data: string | number | boolean
}

declare global {
  function reportResult(result: ReportableResult): void
}

import { Worker } from 'node:worker_threads'

type WorkerResult = {
  exitCode: number
  stderr: string
  consoleCalls: Array<{ method: string; input: string }>
  data: Record<string, unknown>
  messages: Array<ReportableResult>
}

export function runWorkerCode(fn: Function): Promise<WorkerResult> {
  return new Promise((resolve, reject) => {
    const script = `
      const { parentPort } = require('node:worker_threads');
      (async () => {
        const { AsyncLocalStorage } = require('node:async_hooks');
        // We need to put this on the global because Next.js does not import it
        // from node directly to be compatible with edge runtimes.
        globalThis.AsyncLocalStorage = AsyncLocalStorage;

        global.reportResult = (value) => {
          parentPort?.postMessage(value);
        };

        const fn = (${fn.toString()});
        try {
          const out = await fn();
          await new Promise(r => setImmediate(r));
          reportResult({ type: 'result', out });
        } catch (e) {
          reportResult({ type: 'error', message: String(e && e.message || e) });
        }
      })();
    `

    const w = new Worker(script, {
      eval: true,
      workerData: null,
      argv: [],
      execArgv: ['--conditions=react-server'],
      stderr: true,
      stdout: false,
      env: {
        FORCE_COLOR: '1',
      },
    })

    const messages: Array<ReportableResult> = []
    const consoleCalls: Array<{ method: string; input: string }> = []
    const data = {} as Record<string, unknown>
    let stderr = ''

    w.on('message', (m) => {
      messages.push(m)
      switch (m.type) {
        case 'console-call':
          consoleCalls.push({
            method: m.method,
            input: m.input,
          })
          break
        case 'serialized':
          data[m.key] = JSON.parse(m.data)
          break
        default:
          break
      }
    })
    w.on('error', (err) => console.error('Worker error', err))
    w.on('error', reject)
    w.stderr?.on('data', (b) => (stderr += String(b)))
    w.on('exit', (code) =>
      resolve({
        exitCode: code ?? -1,
        consoleCalls,
        data,
        messages,
        stderr,
      })
    )
  })
}

describe('console-exit patches', () => {
  describe('basic functionality', () => {
    it('should patch console methods to dim when instructed', async () => {
      async function testForWorker() {
        const {
          consoleAsyncStorage,
        } = require('next/dist/server/app-render/console-async-storage.external')

        // First, replace console.log to track what storage context it runs in
        console.log = function (...args) {
          let dimmed = false
          if (
            args.find((a) =>
              typeof a === 'string' ? a.includes('color:') : false
            )
          ) {
            dimmed = true
          }
          reportResult({
            type: 'console-call',
            method: 'log',
            input: `${dimmed ? '[DIM]' : '[BRIGHT]'}: ${args.join(' ')}`,
          })
        }

        // Install patches - this wraps the current console.log
        require('next/dist/server/node-environment-extensions/console-dim.external')

        // Test outside storage context
        console.log('outside')

        consoleAsyncStorage.run({ dim: true }, () => {
          console.log('inside')
        })
      }

      const { consoleCalls, exitCode } = await runWorkerCode(testForWorker)

      expect(exitCode).toBe(0)
      // Both should show [No Store] because the wrapped console.log exits storage
      expect(consoleCalls).toEqual([
        { method: 'log', input: '[BRIGHT]: outside' },
        // can't match the formatting characters easily
        { method: 'log', input: expect.stringMatching(/\[DIM\].*inside/) },
      ])
    })

    it('should not wrap console methods assigned after patching', async () => {
      async function testForWorker() {
        const {
          consoleAsyncStorage,
        } = require('next/dist/server/app-render/console-async-storage.external')

        // Install patches first
        require('next/dist/server/node-environment-extensions/console-dim.external')

        // Assign a new console.log after patching - this will NOT be wrapped
        console.log = function (...args) {
          let dimmed = false
          if (
            args.find((a) =>
              typeof a === 'string' ? a.includes('color:') : false
            )
          ) {
            dimmed = true
          }
          reportResult({
            type: 'console-call',
            method: 'log',
            input: `${dimmed ? '[DIM]' : '[BRIGHT]'}: ${args.join(' ')}`,
          })
        }

        // Test outside storage context
        console.log('outside')

        consoleAsyncStorage.run({ dim: true }, () => {
          console.log('inside')
        })
      }

      const { consoleCalls, exitCode } = await runWorkerCode(testForWorker)

      expect(exitCode).toBe(0)
      // New assignments after patching are NOT wrapped, so they preserve storage context
      expect(consoleCalls).toEqual([
        { method: 'log', input: '[BRIGHT]: outside' },
        { method: 'log', input: '[BRIGHT]: inside' },
      ])
    })

    it('should preserve function properties and behavior', async () => {
      async function testForWorker() {
        reportResult({
          type: 'serialized',
          key: 'originalName',
          data: JSON.stringify(console.log.name),
        })

        reportResult({
          type: 'serialized',
          key: 'originalLength',
          data: JSON.stringify(console.log.length),
        })

        // install patch
        require('next/dist/server/node-environment-extensions/console-dim.external')

        // Test that patched methods preserve name and other properties
        reportResult({
          type: 'serialized',
          key: 'patchedName',
          data: JSON.stringify(console.log.name),
        })

        reportResult({
          type: 'serialized',
          key: 'patchedLength',
          data: JSON.stringify(console.log.length),
        })
      }

      const { data, exitCode } = await runWorkerCode(testForWorker)

      expect(exitCode).toBe(0)
      expect(data.patchedName).toBe('log')
      expect(data.patchedName).toBe(data.originalName)
      expect(data.patchedLength).toBe(data.originalLength)
    })

    it('should enter a dimming context when a prerender store exists with an aborted renderSignal', async () => {
      async function testForWorker() {
        const {
          workUnitAsyncStorage,
        } = require('next/dist/server/app-render/work-unit-async-storage.external')

        // First, replace console.log to track what storage context it runs in
        console.log = function (...args) {
          let dimmed = false
          if (
            args.find((a) =>
              typeof a === 'string' ? a.includes('color:') : false
            )
          ) {
            dimmed = true
          }
          reportResult({
            type: 'console-call',
            method: 'log',
            input: `${dimmed ? '[DIM]' : '[BRIGHT]'}: ${args.join(' ')}`,
          })
        }

        // Install patches - this wraps the current console.log
        require('next/dist/server/node-environment-extensions/console-dim.external')

        // Test outside storage context
        console.log('outside')

        const controller = new AbortController()

        workUnitAsyncStorage.run(
          { type: 'prerender', renderSignal: controller.signal },
          () => {
            console.log('before abort')
            controller.abort()
            console.log('after abort')
          }
        )
      }

      const { consoleCalls, exitCode } = await runWorkerCode(testForWorker)

      expect(exitCode).toBe(0)
      // Both should show [No Store] because the wrapped console.log exits storage
      expect(consoleCalls).toEqual([
        { method: 'log', input: '[BRIGHT]: outside' },
        { method: 'log', input: '[BRIGHT]: before abort' },
        { method: 'log', input: expect.stringMatching(/\[DIM\].*after abort/) },
      ])
    })

    it('should enter a dimming context when a react cacheSignal exists and is aborted', async () => {
      async function testForWorker() {
        const originalLog = console.log
        let controller: null | AbortController = new AbortController()

        // First, replace console.log to track what storage context it runs in
        console.log = function (...args) {
          originalLog(...args)
          let dimmed = false
          if (
            args.find((a) =>
              typeof a === 'string' ? a.includes('color:') : false
            )
          ) {
            dimmed = true
          }
          reportResult({
            type: 'console-call',
            method: 'log',
            input: `${dimmed ? '[DIM]' : '[BRIGHT]'}: ${args.join(' ')}`,
          })
        }

        // Install patches - this wraps the current console.log
        require('next/dist/server/node-environment-extensions/console-dim.external')

        const {
          registerServerReact,
          registerClientReact,
        } = require('next/dist/server/runtime-reacts.external')

        registerServerReact({
          cacheSignal() {
            return controller?.signal
          },
        })
        registerClientReact({
          cacheSignal() {
            return null
          },
        })

        console.log('before abort')
        controller.abort()
        console.log('after abort')

        controller = null
        console.log('with null signal')
      }

      const { consoleCalls, exitCode } = await runWorkerCode(testForWorker)

      expect(exitCode).toBe(0)
      expect(consoleCalls).toEqual([
        { method: 'log', input: '[BRIGHT]: before abort' },
        { method: 'log', input: expect.stringMatching(/\[DIM\].*after abort/) },
        { method: 'log', input: '[BRIGHT]: with null signal' },
      ])
    })
  })
})