MCPcopy
hub / github.com/vitest-dev/vitest / createCustomConsole

Function createCustomConsole

packages/vitest/src/runtime/console.ts:35–220  ·  view source on GitHub ↗
(defaultState?: WorkerGlobalState)

Source from the content-addressed store, hash-verified

33}
34
35export function createCustomConsole(defaultState?: WorkerGlobalState): Console {
36 const stdoutBuffer = new Map<string, any[]>()
37 const stderrBuffer = new Map<string, any[]>()
38 const timers = new Map<
39 string,
40 { stdoutTime: number; stderrTime: number; cancel?: () => void }
41 >()
42
43 const { queueMicrotask } = getSafeTimers()
44
45 function queueCancelableMicrotask(callback: () => void) {
46 let canceled = false
47 queueMicrotask(() => {
48 if (!canceled) {
49 callback()
50 }
51 })
52 return () => {
53 canceled = true
54 }
55 }
56
57 const state = () => defaultState || getWorkerState()
58
59 // group sync console.log calls with micro task
60 function schedule(taskId: string) {
61 const timer = timers.get(taskId)!
62 const { stdoutTime, stderrTime } = timer
63 timer.cancel?.()
64 timer.cancel = queueCancelableMicrotask(() => {
65 if (stderrTime < stdoutTime) {
66 sendStderr(taskId)
67 sendStdout(taskId)
68 }
69 else {
70 sendStdout(taskId)
71 sendStderr(taskId)
72 }
73 })
74 }
75 function sendStdout(taskId: string) {
76 sendBuffer('stdout', taskId)
77 }
78
79 function sendStderr(taskId: string) {
80 sendBuffer('stderr', taskId)
81 }
82
83 function sendBuffer(type: 'stdout' | 'stderr', taskId: string) {
84 const buffers = type === 'stdout' ? stdoutBuffer : stderrBuffer
85 const buffer = buffers.get(taskId)
86 if (!buffer) {
87 return
88 }
89 if (state().config.printConsoleTrace) {
90 buffer.forEach(([buffer, origin]) => {
91 sendLog(type, taskId, String(buffer), buffer.length, origin)
92 })

Callers 2

runVmTestsFunction · 0.90
setupConsoleLogSpyFunction · 0.85

Calls 1

getSafeTimersFunction · 0.90

Tested by

no test coverage detected