proxyConsole.js 1.23 KB
Newer Older
1
/* @flow */
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

type ReactFrame = {
  fileName: string | null,
  lineNumber: number | null,
  functionName: string | null,
};
const reactFrameStack: Array<ReactFrame[]> = [];

export type { ReactFrame };

const registerReactStack = () => {
  // $FlowFixMe
  console.stack = frames => reactFrameStack.push(frames);
  // $FlowFixMe
  console.stackEnd = frames => reactFrameStack.pop();
};

const unregisterReactStack = () => {
  // $FlowFixMe
  console.stack = undefined;
  // $FlowFixMe
  console.stackEnd = undefined;
};

type ConsoleProxyCallback = (message: string, frames: ReactFrame[]) => void;
27
28
29
30
31
32
const permanentRegister = function proxyConsole(
  type: string,
  callback: ConsoleProxyCallback
) {
  const orig = console[type];
  console[type] = function __stack_frame_overlay_proxy_console__() {
33
34
35
36
37
38
39
40
41
42
43
    try {
      const message = arguments[0];
      if (typeof message === 'string' && reactFrameStack.length > 0) {
        callback(message, reactFrameStack[reactFrameStack.length - 1]);
      }
    } catch (err) {
      // Warnings must never crash. Rethrow with a clean stack.
      setTimeout(function() {
        throw err;
      });
    }
44
45
46
47
    return orig.apply(this, arguments);
  };
};

48
export { permanentRegister, registerReactStack, unregisterReactStack };