| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | * |
| 7 | * @flow |
| 8 | */ |
| 9 | |
| 10 | // Keep in sync with ReactServerConsoleConfig |
| 11 | const badgeFormat = '[%s]'; |
| 12 | const pad = ' '; |
| 13 | |
| 14 | const bind = Function.prototype.bind; |
| 15 | |
| 16 | export function bindToConsole( |
| 17 | methodName: string, |
| 18 | args: Array<any>, |
| 19 | badgeName: string, |
| 20 | ): () => any { |
| 21 | let offset = 0; |
| 22 | switch (methodName) { |
| 23 | case 'dir': |
| 24 | case 'dirxml': |
| 25 | case 'groupEnd': |
| 26 | case 'table': { |
| 27 | // These methods cannot be colorized because they don't take a formatting string. |
| 28 | // $FlowFixMe[incompatible-type] |
| 29 | return bind.apply(console[methodName], [console].concat(args)); // eslint-disable-line react-internal/no-production-logging |
| 30 | } |
| 31 | case 'assert': { |
| 32 | // assert takes formatting options as the second argument. |
| 33 | offset = 1; |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | const newArgs = args.slice(0); |
| 38 | if (typeof newArgs[offset] === 'string') { |
| 39 | newArgs.splice( |
| 40 | offset, |
| 41 | 1, |
| 42 | badgeFormat + ' ' + newArgs[offset], |
| 43 | pad + badgeName + pad, |
| 44 | ); |
| 45 | } else { |
| 46 | newArgs.splice(offset, 0, badgeFormat, pad + badgeName + pad); |
| 47 | } |
| 48 | |
| 49 | // The "this" binding in the "bind"; |
| 50 | newArgs.unshift(console); |
| 51 | |
| 52 | // $FlowFixMe[incompatible-type] |
| 53 | // $FlowFixMe[invalid-computed-prop] |
| 54 | return bind.apply(console[methodName], newArgs); // eslint-disable-line react-internal/no-production-logging |
| 55 | } |