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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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
import { cyan, dim, red, yellow } from '../../../lib/picocolors'
import type { Project } from '../../../build/swc/types'
import util from 'util'
import {
  getConsoleLocation,
  getSourceMappedStackFrames,
  withLocation,
  type MappingContext,
} from './source-map'
import {
  type ServerLogEntry,
  type LogMethod,
  type ConsoleEntry,
  UNDEFINED_MARKER,
} from '../../../next-devtools/shared/forward-logs-shared'

export function restoreUndefined(x: any): any {
  if (x === UNDEFINED_MARKER) return undefined
  if (Array.isArray(x)) return x.map(restoreUndefined)
  if (x && typeof x === 'object') {
    for (let k in x) {
      x[k] = restoreUndefined(x[k])
    }
  }
  return x
}

const methods: Array<LogMethod> = [
  'log',
  'info',
  'warn',
  'debug',
  'table',
  'error',
  'assert',
  'dir',
  'dirxml',
  'group',
  'groupCollapsed',
  'groupEnd',
]

const methodsToSkipInspect = new Set([
  'table',
  'dir',
  'dirxml',
  'group',
  'groupCollapsed',
  'groupEnd',
])

// we aren't overriding console, we're just making a (slightly convoluted) helper for replaying user console methods
const forwardConsole: typeof console = {
  ...console,
  ...Object.fromEntries(
    methods.map((method) => [
      method,
      (...args: Array<any>) =>
        (console[method] as any)(
          ...args.map((arg) =>
            methodsToSkipInspect.has(method) ||
            typeof arg !== 'object' ||
            arg === null
              ? arg
              : // we hardcode depth:Infinity to allow the true depth to be configured by the serialization done in the browser (which is controlled by user)
                util.inspect(arg, { depth: Infinity, colors: true })
          )
        ),
    ])
  ),
}

async function deserializeArgData(arg: any) {
  try {
    // we want undefined to be represented as it would be in the browser from the user's perspective (otherwise it would be stripped away/shown as null)
    if (arg === UNDEFINED_MARKER) {
      return restoreUndefined(arg)
    }

    return restoreUndefined(JSON.parse(arg))
  } catch {
    return arg
  }
}

const colorError = (
  mapped: Awaited<ReturnType<typeof getSourceMappedStackFrames>>,
  config?: {
    prefix?: string
    applyColor?: boolean
  }
) => {
  const colorFn =
    config?.applyColor === undefined || config.applyColor ? red : <T>(x: T) => x
  switch (mapped.kind) {
    case 'mapped-stack':
    case 'stack': {
      return (
        (config?.prefix ? colorFn(config?.prefix) : '') +
        `\n${colorFn(mapped.stack)}`
      )
    }
    case 'with-frame-code': {
      return (
        (config?.prefix ? colorFn(config?.prefix) : '') +
        `\n${colorFn(mapped.stack)}\n${mapped.frameCode}`
      )
    }
    // a more sophisticated version of this allows the user to config if they want ignored frames (but we need to be sure to source map them)
    case 'all-ignored': {
      return config?.prefix ? colorFn(config?.prefix) : ''
    }
    default: {
    }
  }
  mapped satisfies never
}

function processConsoleFormatStrings(args: any[]): any[] {
  /**
   * this handles the case formatting is applied to the console log
   * otherwise we will see the format specifier directly in the terminal output
   */
  if (args.length > 0 && typeof args[0] === 'string') {
    const formatString = args[0]
    if (
      formatString.includes('%s') ||
      formatString.includes('%d') ||
      formatString.includes('%i') ||
      formatString.includes('%f') ||
      formatString.includes('%o') ||
      formatString.includes('%O') ||
      formatString.includes('%c')
    ) {
      try {
        const formatted = util.format(...args)
        return [formatted]
      } catch {
        return args
      }
    }
  }
  return args
}

// in the case of logging errors, we want to strip formatting
// modifiers since we apply our own custom coloring to error
// stacks and code blocks, and otherwise it would conflict
// and cause awful output
export function stripFormatSpecifiers(args: any[]): any[] {
  if (args.length === 0 || typeof args[0] !== 'string') return args

  const fmtIn = String(args[0])
  const rest = args.slice(1)

  if (!fmtIn.includes('%')) return args

  let fmtOut = ''
  let argPtr = 0

  for (let i = 0; i < fmtIn.length; i++) {
    if (fmtIn[i] !== '%') {
      fmtOut += fmtIn[i]
      continue
    }

    if (fmtIn[i + 1] === '%') {
      fmtOut += '%'
      i++
      continue
    }

    const token = fmtIn[++i]

    if (!token) {
      fmtOut += '%'
      continue
    }

    if ('csdifoOj'.includes(token) || token === 'O') {
      if (argPtr < rest.length) {
        if (token === 'c') {
          argPtr++
        } else if (token === 'o' || token === 'O' || token === 'j') {
          const obj = rest[argPtr++]
          fmtOut += util.inspect(obj, { depth: 2, colors: false })
        } else {
          // string(...) is safe for remaining specifiers
          fmtOut += String(rest[argPtr++])
        }
      }
      continue
    }

    fmtOut += '%' + token
  }

  const result = [fmtOut]
  if (argPtr < rest.length) {
    result.push(...rest.slice(argPtr))
  }

  return result
}

async function prepareFormattedErrorArgs(
  entry: Extract<ServerLogEntry, { kind: 'formatted-error' }>,
  ctx: MappingContext,
  distDir: string
) {
  const mapped = await getSourceMappedStackFrames(entry.stack, ctx, distDir)
  return [colorError(mapped, { prefix: entry.prefix })]
}

async function prepareConsoleArgs(
  entry: Extract<ServerLogEntry, { kind: 'console' }>,
  ctx: MappingContext,
  distDir: string
) {
  const deserialized = await Promise.all(
    entry.args.map(async (arg) => {
      if (arg.kind === 'arg') {
        const data = await deserializeArgData(arg.data)
        if (entry.method === 'warn' && typeof data === 'string') {
          return yellow(data)
        }
        return data
      }
      if (!arg.stack) return red(arg.prefix)
      const mapped = await getSourceMappedStackFrames(arg.stack, ctx, distDir)
      return colorError(mapped, { prefix: arg.prefix, applyColor: false })
    })
  )

  return processConsoleFormatStrings(deserialized)
}

async function prepareConsoleErrorArgs(
  entry: Extract<ServerLogEntry, { kind: 'any-logged-error' }>,
  ctx: MappingContext,
  distDir: string
) {
  const deserialized = await Promise.all(
    entry.args.map(async (arg) => {
      if (arg.kind === 'arg') {
        if (arg.isRejectionMessage) return red(arg.data)
        return deserializeArgData(arg.data)
      }
      if (!arg.stack) return red(arg.prefix)
      const mapped = await getSourceMappedStackFrames(arg.stack, ctx, distDir)
      return colorError(mapped, { prefix: arg.prefix })
    })
  )

  const mappedStack = await getSourceMappedStackFrames(
    entry.consoleErrorStack,
    ctx,
    distDir
  )

  /**
   * don't show the stack + codeblock when there are errors present, since:
   * - it will look overwhelming to see 2 stacks and 2 code blocks
   * - the user already knows where the console.error is at because we append the location
   */
  const location = getConsoleLocation(mappedStack)
  if (entry.args.some((a) => a.kind === 'formatted-error-arg')) {
    const result = stripFormatSpecifiers(deserialized)
    if (location) {
      result.push(dim(`(${location})`))
    }
    return result
  }
  const result = [
    ...processConsoleFormatStrings(deserialized),
    colorError(mappedStack),
  ]
  if (location) {
    result.push(dim(`(${location})`))
  }
  return result
}

async function handleTable(
  entry: ConsoleEntry<string>,
  browserPrefix: string,
  ctx: MappingContext,
  distDir: string
) {
  const deserializedArgs = await Promise.all(
    entry.args.map(async (arg: any) => {
      if (arg.kind === 'formatted-error-arg') {
        return { stack: arg.stack }
      }
      return deserializeArgData(arg.data)
    })
  )

  const location = await (async () => {
    if (!entry.consoleMethodStack) {
      return
    }
    const frames = await getSourceMappedStackFrames(
      entry.consoleMethodStack,
      ctx,
      distDir
    )
    return getConsoleLocation(frames)
  })()

  // we can't inline pass browser prefix, but it looks better multiline for table anyways
  forwardConsole.log(browserPrefix)
  forwardConsole.table(...deserializedArgs)
  if (location) {
    forwardConsole.log(dim(`(${location})`))
  }
}

async function handleTrace(
  entry: ConsoleEntry<string>,
  browserPrefix: string,
  ctx: MappingContext,
  distDir: string
) {
  const deserializedArgs = await Promise.all(
    entry.args.map(async (arg: any) => {
      if (arg.kind === 'formatted-error-arg') {
        if (!arg.stack) return red(arg.prefix)
        const mapped = await getSourceMappedStackFrames(arg.stack, ctx, distDir)
        return colorError(mapped, { prefix: arg.prefix })
      }
      return deserializeArgData(arg.data)
    })
  )

  if (!entry.consoleMethodStack) {
    forwardConsole.log(
      browserPrefix,
      ...deserializedArgs,
      '[Trace unavailable]'
    )
    return
  }

  // TODO(rob): refactor so we can re-use result and not re-run the entire source map to avoid trivial post processing
  const [mapped, mappedIgnored] = await Promise.all([
    getSourceMappedStackFrames(entry.consoleMethodStack, ctx, distDir, false),
    getSourceMappedStackFrames(entry.consoleMethodStack, ctx, distDir),
  ])

  const location = getConsoleLocation(mappedIgnored)
  forwardConsole.log(
    browserPrefix,
    ...deserializedArgs,
    `\n${mapped.stack}`,
    ...(location ? [`\n${dim(`(${location})`)}`] : [])
  )
}

async function handleDir(
  entry: ConsoleEntry<string>,
  browserPrefix: string,
  ctx: MappingContext,
  distDir: string
) {
  const loggableEntry = await prepareConsoleArgs(entry, ctx, distDir)
  const consoleMethod =
    (forwardConsole as any)[entry.method] || forwardConsole.log

  if (entry.consoleMethodStack) {
    const mapped = await getSourceMappedStackFrames(
      entry.consoleMethodStack,
      ctx,
      distDir
    )
    const location = dim(`(${getConsoleLocation(mapped)})`)
    const originalWrite = process.stdout.write.bind(process.stdout)
    let captured = ''
    process.stdout.write = (chunk) => {
      captured += chunk
      return true
    }
    try {
      consoleMethod(...loggableEntry)
    } finally {
      process.stdout.write = originalWrite
    }
    const preserved = captured.replace(/\r?\n$/, '')
    originalWrite(`${browserPrefix}${preserved} ${location}\n`)
    return
  }
  consoleMethod(browserPrefix, ...loggableEntry)
}

async function handleDefaultConsole(
  entry: ConsoleEntry<string>,
  browserPrefix: string,
  ctx: MappingContext,
  distDir: string,
  config: boolean | { logDepth?: number; showSourceLocation?: boolean }
) {
  const loggableEntry = await prepareConsoleArgs(entry, ctx, distDir)
  const withStackEntry = await withLocation(
    {
      original: loggableEntry,
      stack: (entry as any).consoleMethodStack || null,
    },
    ctx,
    distDir,
    config
  )
  const consoleMethod = forwardConsole[entry.method] || forwardConsole.log
  ;(consoleMethod as (...args: any[]) => void)(browserPrefix, ...withStackEntry)
}

export async function handleLog(
  entries: ServerLogEntry[],
  ctx: MappingContext,
  distDir: string,
  config: boolean | { logDepth?: number; showSourceLocation?: boolean }
): Promise<void> {
  const browserPrefix = cyan('[browser]')

  for (const entry of entries) {
    try {
      switch (entry.kind) {
        case 'console': {
          switch (entry.method) {
            case 'table': {
              // timeout based abort on source mapping result
              await handleTable(entry, browserPrefix, ctx, distDir)
              break
            }
            // ignore frames
            case 'trace': {
              await handleTrace(entry, browserPrefix, ctx, distDir)
              break
            }
            case 'dir': {
              await handleDir(entry, browserPrefix, ctx, distDir)
              break
            }
            case 'dirxml': {
              // xml log thing maybe needs an impl
              // fallthrough
            }
            case 'group':
            case 'groupCollapsed':
            case 'groupEnd': {
              // [browser] undefined (app/page.tsx:8:11) console.group
              // fallthrough
            }
            case 'assert': {
              // check console assert
              // fallthrough
            }
            case 'log':
            case 'info':
            case 'debug':
            case 'error':
            case 'warn': {
              await handleDefaultConsole(
                entry,
                browserPrefix,
                ctx,
                distDir,
                config
              )
              break
            }
            default: {
              entry satisfies never
            }
          }
          break
        }
        // any logged errors are anything that are logged as "red" in the browser but aren't only an Error (console.error, Promise.reject(100))
        case 'any-logged-error': {
          const consoleArgs = await prepareConsoleErrorArgs(entry, ctx, distDir)
          forwardConsole.error(browserPrefix, ...consoleArgs)
          break
        }
        // formatted error is an explicit error event (rejections, uncaught errors)
        case 'formatted-error': {
          const formattedArgs = await prepareFormattedErrorArgs(
            entry,
            ctx,
            distDir
          )
          forwardConsole.error(browserPrefix, ...formattedArgs)
          break
        }
        default: {
        }
      }
    } catch {
      switch (entry.kind) {
        case 'any-logged-error': {
          const consoleArgs = await prepareConsoleErrorArgs(entry, ctx, distDir)
          forwardConsole.error(browserPrefix, ...consoleArgs)
          break
        }
        case 'console': {
          const consoleMethod =
            forwardConsole[entry.method] || forwardConsole.log
          const consoleArgs = await prepareConsoleArgs(entry, ctx, distDir)
          ;(consoleMethod as (...args: any[]) => void)(
            browserPrefix,
            ...consoleArgs
          )
          break
        }
        case 'formatted-error': {
          forwardConsole.error(browserPrefix, `${entry.prefix}\n`, entry.stack)
          break
        }
        default: {
        }
      }
    }
  }
}

// the data is used later when we need to get sourcemaps for error stacks
export async function receiveBrowserLogsWebpack(opts: {
  entries: ServerLogEntry[]
  router: 'app' | 'pages'
  sourceType?: 'server' | 'edge-server'
  clientStats: () => any
  serverStats: () => any
  edgeServerStats: () => any
  rootDirectory: string
  distDir: string
  config: boolean | { logDepth?: number; showSourceLocation?: boolean }
}): Promise<void> {
  const {
    entries,
    router,
    sourceType,
    clientStats,
    serverStats,
    edgeServerStats,
    rootDirectory,
    distDir,
  } = opts

  const isAppDirectory = router === 'app'
  const isServer = sourceType === 'server'
  const isEdgeServer = sourceType === 'edge-server'

  const ctx: MappingContext = {
    bundler: 'webpack',
    isServer,
    isEdgeServer,
    isAppDirectory,
    clientStats,
    serverStats,
    edgeServerStats,
    rootDirectory,
  }

  await handleLog(entries, ctx, distDir, opts.config)
}

export async function receiveBrowserLogsTurbopack(opts: {
  entries: ServerLogEntry[]
  router: 'app' | 'pages'
  sourceType?: 'server' | 'edge-server'
  project: Project
  projectPath: string
  distDir: string
  config: boolean | { logDepth?: number; showSourceLocation?: boolean }
}): Promise<void> {
  const { entries, router, sourceType, project, projectPath, distDir } = opts

  const isAppDirectory = router === 'app'
  const isServer = sourceType === 'server'
  const isEdgeServer = sourceType === 'edge-server'

  const ctx: MappingContext = {
    bundler: 'turbopack',
    project,
    projectPath,
    isServer,
    isEdgeServer,
    isAppDirectory,
  }

  await handleLog(entries, ctx, distDir, opts.config)
}