(defaultState?: WorkerGlobalState)
| 33 | } |
| 34 | |
| 35 | export 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 | }) |
no test coverage detected