All files / lib/internal/console constructor.js

99.58% Statements 722/725
100% Branches 167/167
100% Functions 37/37
99.58% Lines 722/725

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 72638x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 271x 271x 271x 271x 271x 1x 1x 270x 271x 229x 229x 229x 229x 229x 229x 270x 270x 270x 270x 270x 270x 270x 270x 270x 270x 271x 1x 1x 271x 1x 1x 268x 271x 271x 262x 271x 11x 11x 11x 252x 271x 12x 12x 12x 12x 3x 3x 3x 3x 3x 243x 243x 243x 4617x 4617x 4617x 4617x 4617x 4617x 4617x 4617x 243x 243x 243x 243x 271x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 6x 6x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 243x 243x 243x 243x 243x 38x 38x 38x 38x 38x 38x 38x 6256x 6256x 6256x 6256x 6256x 6256x 6256x 6256x 192692x 192692x 6256x 6256x 6256x 6256x 6256x 6256x 6256x 6256x 21778x 21778x 6256x 6256x 6256x 6256x 6256x 38x 38x 38x 38x 38x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 6499x 38x 38x 38x 38x 38x 71909x 71909x 71909x 71909x 71909x 71909x 71909x 71909x 71909x 14x 2x 2x 14x 14x 71909x 71909x 71909x 71837x 71837x 71837x 71837x 71837x 71837x 71837x 71837x 71837x 71837x 71837x 71840x 7x 7x 7x 7x 7x 71840x 71837x 71837x 71909x 38x 38x 38x 38x 38x 71994x 71994x 71953x 33x 71953x 71953x 71994x 71994x 71994x 12x 1x 1x 12x 12x 71982x 71994x 71994x 38x 38x 38x 38x 38x 64599x 64599x 64599x 64599x 38x 38x 38x 38x 38x 7298x 7298x 7298x 7298x 38x 38x 38x 38x 12998x 12998x 71291x 71291x 71291x 71291x 71291x 71291x 32x 32x 32x 32x 32x 32x 15x 15x 32x 12998x 12998x 38x 38x 38x 64599x 38x 38x 38x 38x 7295x 38x 38x 38x 38x 15x 15x 15x 15x 15x 38x 38x 38x 25x 25x 25x 2x 2x 2x 23x 23x 38x 38x 38x 25x 25x 25x 25x 25x 23x 23x 38x 38x 38x 8x 8x 8x 8x 38x 38x 38x 4x 4x 4x 4x 4x 4x 38x 38x 38x 7x 2x 2x 2x 2x 38x 38x 38x 38x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 38x 38x 38x 38x 16x 16x 16x 16x 16x 16x 16x 6x 6x 16x 16x 16x 38x 38x 38x 38x 6x 6x 3x 3x 3x 3x 3x 38x 38x 38x 9x 2x 2x 9x 9x 38x 38x 38x 6x 6x 6x 6x 6x 38x 38x 38x 38x 34x 34x 33x 34x 34x 27x 27x 27x 27x 27x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 82x 27x 27x 27x 27x 27x 27x 27x 34x 3x 3x 3x 3x 27x 34x 3x 3x 3x 3x 1x 3x 3x 3x 3x 3x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 3x 3x 24x 24x 24x 34x 24x 34x 34x 4x 4x 4x 12x 12x 12x 4x 4x 20x 20x 20x 20x 20x 20x 34x 39x 39x 39x 39x 22x 22x 39x 17x 17x 26x 26x 26x 26x 21x 21x 26x 17x 39x 20x 20x 20x 34x 10x 10x 10x 20x 20x 20x 20x 38x 38x 38x 38x 33x 33x 33x 4x 4x 4x 29x 29x 29x 29x 29x 33x 23x 31x 6x 6x 29x 33x 38x 7x 7x 7x 38x 37x 37x 37x 37x 37x 37x 6x 4x 3x 3x 3x 4x 4x 4x 6x 6x 37x 37x 4x 4x 4x 4x 4x 4x 4x 33x 37x 2x 2x 31x 31x 37x 38x 38x 38x 38x 38x 38x 38x 38x 15x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 6256x 6256x 6256x 6256x 6256x 6256x 6256x 6256x 6256x 6256x 6255x 6255x 1x 1x 1x 1x 1x 1x 24x 1x 1x 24x 1x 1x 1x       1x 6256x 38x 38x 38x 38x 38x 38x 38x 38x  
'use strict';
 
// The Console constructor is not actually used to construct the global
// console. It's exported for backwards compatibility.
 
const {
  ArrayFrom,
  ArrayIsArray,
  ArrayPrototypeForEach,
  ArrayPrototypePush,
  ArrayPrototypeUnshift,
  Boolean,
  ErrorCaptureStackTrace,
  FunctionPrototypeBind,
  MathFloor,
  Number,
  NumberPrototypeToFixed,
  ObjectCreate,
  ObjectDefineProperties,
  ObjectDefineProperty,
  ObjectKeys,
  ObjectPrototypeHasOwnProperty,
  ObjectValues,
  ReflectApply,
  ReflectConstruct,
  ReflectOwnKeys,
  RegExpPrototypeSymbolReplace,
  SafeArrayIterator,
  SafeMap,
  SafeWeakMap,
  SafeSet,
  StringPrototypeIncludes,
  StringPrototypePadStart,
  StringPrototypeRepeat,
  StringPrototypeSlice,
  StringPrototypeSplit,
  Symbol,
  SymbolHasInstance,
  SymbolToStringTag,
} = primordials;
 
const { trace } = internalBinding('trace_events');
const {
  isStackOverflowError,
  codes: {
    ERR_CONSOLE_WRITABLE_STREAM,
    ERR_INVALID_ARG_VALUE,
    ERR_INCOMPATIBLE_OPTION_PAIR,
  },
} = require('internal/errors');
const {
  validateArray,
  validateInteger,
  validateObject,
} = require('internal/validators');
const { previewEntries } = internalBinding('util');
const { Buffer: { isBuffer } } = require('buffer');
const {
  inspect,
  formatWithOptions
} = require('internal/util/inspect');
const {
  isTypedArray, isSet, isMap, isSetIterator, isMapIterator,
} = require('internal/util/types');
const {
  CHAR_LOWERCASE_B: kTraceBegin,
  CHAR_LOWERCASE_E: kTraceEnd,
  CHAR_LOWERCASE_N: kTraceInstant,
  CHAR_UPPERCASE_C: kTraceCount,
} = require('internal/constants');
const kCounts = Symbol('counts');
 
const kTraceConsoleCategory = 'node,node.console';
 
const kSecond = 1000;
const kMinute = 60 * kSecond;
const kHour = 60 * kMinute;
const kMaxGroupIndentation = 1000;
 
// Lazy loaded for startup performance.
let cliTable;
 
// Track amount of indentation required via `console.group()`.
const kGroupIndent = Symbol('kGroupIndent');
const kGroupIndentationWidth = Symbol('kGroupIndentWidth');
const kFormatForStderr = Symbol('kFormatForStderr');
const kFormatForStdout = Symbol('kFormatForStdout');
const kGetInspectOptions = Symbol('kGetInspectOptions');
const kColorMode = Symbol('kColorMode');
const kIsConsole = Symbol('kIsConsole');
const kWriteToConsole = Symbol('kWriteToConsole');
const kBindProperties = Symbol('kBindProperties');
const kBindStreamsEager = Symbol('kBindStreamsEager');
const kBindStreamsLazy = Symbol('kBindStreamsLazy');
const kUseStdout = Symbol('kUseStdout');
const kUseStderr = Symbol('kUseStderr');
 
const optionsMap = new SafeWeakMap();
 
function Console(options /* or: stdout, stderr, ignoreErrors = true */) {
  // We have to test new.target here to see if this function is called
  // with new, because we need to define a custom instanceof to accommodate
  // the global console.
  if (new.target === undefined) {
    return ReflectConstruct(Console, arguments);
  }
 
  if (!options || typeof options.write === 'function') {
    options = {
      stdout: options,
      stderr: arguments[1],
      ignoreErrors: arguments[2]
    };
  }
 
  const {
    stdout,
    stderr = stdout,
    ignoreErrors = true,
    colorMode = 'auto',
    inspectOptions,
    groupIndentation,
  } = options;
 
  if (!stdout || typeof stdout.write !== 'function') {
    throw new ERR_CONSOLE_WRITABLE_STREAM('stdout');
  }
  if (!stderr || typeof stderr.write !== 'function') {
    throw new ERR_CONSOLE_WRITABLE_STREAM('stderr');
  }
 
  if (typeof colorMode !== 'boolean' && colorMode !== 'auto')
    throw new ERR_INVALID_ARG_VALUE('colorMode', colorMode);
 
  if (groupIndentation !== undefined) {
    validateInteger(groupIndentation, 'groupIndentation',
                    0, kMaxGroupIndentation);
  }
 
  if (inspectOptions !== undefined) {
    validateObject(inspectOptions, 'options.inspectOptions');
 
    if (inspectOptions.colors !== undefined &&
        options.colorMode !== undefined) {
      throw new ERR_INCOMPATIBLE_OPTION_PAIR(
        'options.inspectOptions.color', 'colorMode');
    }
    optionsMap.set(this, inspectOptions);
  }
 
  // Bind the prototype functions to this Console instance
  ArrayPrototypeForEach(ObjectKeys(Console.prototype), (key) => {
    // We have to bind the methods grabbed from the instance instead of from
    // the prototype so that users extending the Console can override them
    // from the prototype chain of the subclass.
    this[key] = FunctionPrototypeBind(this[key], this);
    ObjectDefineProperty(this[key], 'name', {
      __proto__: null,
      value: key
    });
  });
 
  this[kBindStreamsEager](stdout, stderr);
  this[kBindProperties](ignoreErrors, colorMode, groupIndentation);
}
 
const consolePropAttributes = {
  writable: true,
  enumerable: false,
  configurable: true
};
 
// Fixup global.console instanceof global.console.Console
ObjectDefineProperty(Console, SymbolHasInstance, {
  __proto__: null,
  value(instance) {
    return instance[kIsConsole];
  }
});
 
const kColorInspectOptions = { colors: true };
const kNoColorInspectOptions = {};
 
ObjectDefineProperties(Console.prototype, {
  [kBindStreamsEager]: {
    __proto__: null,
    ...consolePropAttributes,
    // Eager version for the Console constructor
    value: function(stdout, stderr) {
      ObjectDefineProperties(this, {
        '_stdout': { __proto__: null, ...consolePropAttributes, value: stdout },
        '_stderr': { __proto__: null, ...consolePropAttributes, value: stderr },
      });
    }
  },
  [kBindStreamsLazy]: {
    __proto__: null,
    ...consolePropAttributes,
    // Lazily load the stdout and stderr from an object so we don't
    // create the stdio streams when they are not even accessed
    value: function(object) {
      let stdout;
      let stderr;
      ObjectDefineProperties(this, {
        '_stdout': {
          __proto__: null,
          enumerable: false,
          configurable: true,
          get() {
            if (!stdout) stdout = object.stdout;
            return stdout;
          },
          set(value) { stdout = value; }
        },
        '_stderr': {
          __proto__: null,
          enumerable: false,
          configurable: true,
          get() {
            if (!stderr) { stderr = object.stderr; }
            return stderr;
          },
          set(value) { stderr = value; }
        }
      });
    }
  },
  [kBindProperties]: {
    __proto__: null,
    ...consolePropAttributes,
    value: function(ignoreErrors, colorMode, groupIndentation = 2) {
      ObjectDefineProperties(this, {
        '_stdoutErrorHandler': {
          __proto__: null,
          ...consolePropAttributes,
          value: createWriteErrorHandler(this, kUseStdout)
        },
        '_stderrErrorHandler': {
          ...consolePropAttributes,
          __proto__: null,
          value: createWriteErrorHandler(this, kUseStderr)
        },
        '_ignoreErrors': {
          __proto__: null,
          ...consolePropAttributes,
          value: Boolean(ignoreErrors)
        },
        '_times': { __proto__: null, ...consolePropAttributes, value: new SafeMap() },
        // Corresponds to https://console.spec.whatwg.org/#count-map
        [kCounts]: { __proto__: null, ...consolePropAttributes, value: new SafeMap() },
        [kColorMode]: { __proto__: null, ...consolePropAttributes, value: colorMode },
        [kIsConsole]: { __proto__: null, ...consolePropAttributes, value: true },
        [kGroupIndent]: { __proto__: null, ...consolePropAttributes, value: '' },
        [kGroupIndentationWidth]: {
          __proto__: null,
          ...consolePropAttributes,
          value: groupIndentation
        },
        [SymbolToStringTag]: {
          __proto__: null,
          writable: false,
          enumerable: false,
          configurable: true,
          value: 'console'
        }
      });
    }
  },
  [kWriteToConsole]: {
    __proto__: null,
    ...consolePropAttributes,
    value: function(streamSymbol, string) {
      const ignoreErrors = this._ignoreErrors;
      const groupIndent = this[kGroupIndent];
 
      const useStdout = streamSymbol === kUseStdout;
      const stream = useStdout ? this._stdout : this._stderr;
      const errorHandler = useStdout ?
        this._stdoutErrorHandler : this._stderrErrorHandler;
 
      if (groupIndent.length !== 0) {
        if (StringPrototypeIncludes(string, '\n')) {
          string = RegExpPrototypeSymbolReplace(/\n/g, string, `\n${groupIndent}`);
        }
        string = groupIndent + string;
      }
      string += '\n';
 
      if (ignoreErrors === false) return stream.write(string);
 
      // There may be an error occurring synchronously (e.g. for files or TTYs
      // on POSIX systems) or asynchronously (e.g. pipes on POSIX systems), so
      // handle both situations.
      try {
        // Add and later remove a noop error handler to catch synchronous
        // errors.
        if (stream.listenerCount('error') === 0)
          stream.once('error', noop);
 
        stream.write(string, errorHandler);
      } catch (e) {
        // Console is a debugging utility, so it swallowing errors is not
        // desirable even in edge cases such as low stack space.
        if (isStackOverflowError(e))
          throw e;
        // Sorry, there's no proper way to pass along the error here.
      } finally {
        stream.removeListener('error', noop);
      }
    }
  },
  [kGetInspectOptions]: {
    __proto__: null,
    ...consolePropAttributes,
    value: function(stream) {
      let color = this[kColorMode];
      if (color === 'auto') {
        color = stream.isTTY && (
          typeof stream.getColorDepth === 'function' ?
            stream.getColorDepth() > 2 : true);
      }
 
      const options = optionsMap.get(this);
      if (options) {
        if (options.colors === undefined) {
          options.colors = color;
        }
        return options;
      }
 
      return color ? kColorInspectOptions : kNoColorInspectOptions;
    }
  },
  [kFormatForStdout]: {
    __proto__: null,
    ...consolePropAttributes,
    value: function(args) {
      const opts = this[kGetInspectOptions](this._stdout);
      ArrayPrototypeUnshift(args, opts);
      return ReflectApply(formatWithOptions, null, args);
    }
  },
  [kFormatForStderr]: {
    __proto__: null,
    ...consolePropAttributes,
    value: function(args) {
      const opts = this[kGetInspectOptions](this._stderr);
      ArrayPrototypeUnshift(args, opts);
      return ReflectApply(formatWithOptions, null, args);
    }
  },
});
 
// Make a function that can serve as the callback passed to `stream.write()`.
function createWriteErrorHandler(instance, streamSymbol) {
  return (err) => {
    // This conditional evaluates to true if and only if there was an error
    // that was not already emitted (which happens when the _write callback
    // is invoked asynchronously).
    const stream = streamSymbol === kUseStdout ?
      instance._stdout : instance._stderr;
    if (err !== null && !stream._writableState.errorEmitted) {
      // If there was an error, it will be emitted on `stream` as
      // an `error` event. Adding a `once` listener will keep that error
      // from becoming an uncaught exception, but since the handler is
      // removed after the event, non-console.* writes won't be affected.
      // we are only adding noop if there is no one else listening for 'error'
      if (stream.listenerCount('error') === 0) {
        stream.once('error', noop);
      }
    }
  };
}
 
const consoleMethods = {
  log(...args) {
    this[kWriteToConsole](kUseStdout, this[kFormatForStdout](args));
  },
 
 
  warn(...args) {
    this[kWriteToConsole](kUseStderr, this[kFormatForStderr](args));
  },
 
 
  dir(object, options) {
    this[kWriteToConsole](kUseStdout, inspect(object, {
      customInspect: false,
      ...this[kGetInspectOptions](this._stdout),
      ...options
    }));
  },
 
  time(label = 'default') {
    // Coerces everything other than Symbol to a string
    label = `${label}`;
    if (this._times.has(label)) {
      process.emitWarning(`Label '${label}' already exists for console.time()`);
      return;
    }
    trace(kTraceBegin, kTraceConsoleCategory, `time::${label}`, 0);
    this._times.set(label, process.hrtime());
  },
 
  timeEnd(label = 'default') {
    // Coerces everything other than Symbol to a string
    label = `${label}`;
    const found = timeLogImpl(this, 'timeEnd', label);
    trace(kTraceEnd, kTraceConsoleCategory, `time::${label}`, 0);
    if (found) {
      this._times.delete(label);
    }
  },
 
  timeLog(label = 'default', ...data) {
    // Coerces everything other than Symbol to a string
    label = `${label}`;
    timeLogImpl(this, 'timeLog', label, data);
    trace(kTraceInstant, kTraceConsoleCategory, `time::${label}`, 0);
  },
 
  trace: function trace(...args) {
    const err = {
      name: 'Trace',
      message: this[kFormatForStderr](args)
    };
    ErrorCaptureStackTrace(err, trace);
    this.error(err.stack);
  },
 
  assert(expression, ...args) {
    if (!expression) {
      args[0] = `Assertion failed${args.length === 0 ? '' : `: ${args[0]}`}`;
      // The arguments will be formatted in warn() again
      ReflectApply(this.warn, this, args);
    }
  },
 
  // Defined by: https://console.spec.whatwg.org/#clear
  clear() {
    // It only makes sense to clear if _stdout is a TTY.
    // Otherwise, do nothing.
    if (this._stdout.isTTY && process.env.TERM !== 'dumb') {
      // The require is here intentionally to avoid readline being
      // required too early when console is first loaded.
      const {
        cursorTo,
        clearScreenDown,
      } = require('internal/readline/callbacks');
      cursorTo(this._stdout, 0, 0);
      clearScreenDown(this._stdout);
    }
  },
 
  // Defined by: https://console.spec.whatwg.org/#count
  count(label = 'default') {
    // Ensures that label is a string, and only things that can be
    // coerced to strings. e.g. Symbol is not allowed
    label = `${label}`;
    const counts = this[kCounts];
    let count = counts.get(label);
    if (count === undefined)
      count = 1;
    else
      count++;
    counts.set(label, count);
    trace(kTraceCount, kTraceConsoleCategory, `count::${label}`, 0, count);
    this.log(`${label}: ${count}`);
  },
 
  // Defined by: https://console.spec.whatwg.org/#countreset
  countReset(label = 'default') {
    const counts = this[kCounts];
    if (!counts.has(label)) {
      process.emitWarning(`Count for '${label}' does not exist`);
      return;
    }
    trace(kTraceCount, kTraceConsoleCategory, `count::${label}`, 0, 0);
    counts.delete(`${label}`);
  },
 
  group(...data) {
    if (data.length > 0) {
      ReflectApply(this.log, this, data);
    }
    this[kGroupIndent] +=
      StringPrototypeRepeat(' ', this[kGroupIndentationWidth]);
  },
 
  groupEnd() {
    this[kGroupIndent] = StringPrototypeSlice(
      this[kGroupIndent],
      0,
      this[kGroupIndent].length - this[kGroupIndentationWidth]
    );
  },
 
  // https://console.spec.whatwg.org/#table
  table(tabularData, properties) {
    if (properties !== undefined)
      validateArray(properties, 'properties');
 
    if (tabularData === null || typeof tabularData !== 'object')
      return this.log(tabularData);
 
    cliTable ??= require('internal/cli_table');
    const final = (k, v) => this.log(cliTable(k, v));
 
    const _inspect = (v) => {
      const depth = v !== null &&
                    typeof v === 'object' &&
                    !isArray(v) &&
                    ObjectKeys(v).length > 2 ? -1 : 0;
      const opt = {
        depth,
        maxArrayLength: 3,
        breakLength: Infinity,
        ...this[kGetInspectOptions](this._stdout)
      };
      return inspect(v, opt);
    };
    const getIndexArray = (length) => ArrayFrom(
      { length }, (_, i) => _inspect(i));
 
    const mapIter = isMapIterator(tabularData);
    let isKeyValue = false;
    let i = 0;
    if (mapIter) {
      const res = previewEntries(tabularData, true);
      tabularData = res[0];
      isKeyValue = res[1];
    }
 
    if (isKeyValue || isMap(tabularData)) {
      const keys = [];
      const values = [];
      let length = 0;
      if (mapIter) {
        for (; i < tabularData.length / 2; ++i) {
          ArrayPrototypePush(keys, _inspect(tabularData[i * 2]));
          ArrayPrototypePush(values, _inspect(tabularData[i * 2 + 1]));
          length++;
        }
      } else {
        for (const { 0: k, 1: v } of tabularData) {
          ArrayPrototypePush(keys, _inspect(k));
          ArrayPrototypePush(values, _inspect(v));
          length++;
        }
      }
      return final([
        iterKey, keyKey, valuesKey,
      ], [
        getIndexArray(length),
        keys,
        values,
      ]);
    }
 
    const setIter = isSetIterator(tabularData);
    if (setIter)
      tabularData = previewEntries(tabularData);
 
    const setlike = setIter || mapIter || isSet(tabularData);
    if (setlike) {
      const values = [];
      let length = 0;
      for (const v of tabularData) {
        ArrayPrototypePush(values, _inspect(v));
        length++;
      }
      return final([iterKey, valuesKey], [getIndexArray(length), values]);
    }
 
    const map = ObjectCreate(null);
    let hasPrimitives = false;
    const valuesKeyArray = [];
    const indexKeyArray = ObjectKeys(tabularData);
 
    for (; i < indexKeyArray.length; i++) {
      const item = tabularData[indexKeyArray[i]];
      const primitive = item === null ||
          (typeof item !== 'function' && typeof item !== 'object');
      if (properties === undefined && primitive) {
        hasPrimitives = true;
        valuesKeyArray[i] = _inspect(item);
      } else {
        const keys = properties || ObjectKeys(item);
        for (const key of keys) {
          map[key] ??= [];
          if ((primitive && properties) ||
               !ObjectPrototypeHasOwnProperty(item, key))
            map[key][i] = '';
          else
            map[key][i] = _inspect(item[key]);
        }
      }
    }
 
    const keys = ObjectKeys(map);
    const values = ObjectValues(map);
    if (hasPrimitives) {
      ArrayPrototypePush(keys, valuesKey);
      ArrayPrototypePush(values, valuesKeyArray);
    }
    ArrayPrototypeUnshift(keys, indexKey);
    ArrayPrototypeUnshift(values, indexKeyArray);
 
    return final(keys, values);
  },
};
 
// Returns true if label was found
function timeLogImpl(self, name, label, data) {
  const time = self._times.get(label);
  if (time === undefined) {
    process.emitWarning(`No such label '${label}' for console.${name}()`);
    return false;
  }
  const duration = process.hrtime(time);
  const ms = duration[0] * 1000 + duration[1] / 1e6;
 
  const formatted = formatTime(ms);
 
  if (data === undefined) {
    self.log('%s: %s', label, formatted);
  } else {
    self.log('%s: %s', label, formatted, ...new SafeArrayIterator(data));
  }
  return true;
}
 
function pad(value) {
  return StringPrototypePadStart(`${value}`, 2, '0');
}
 
function formatTime(ms) {
  let hours = 0;
  let minutes = 0;
  let seconds = 0;
 
  if (ms >= kSecond) {
    if (ms >= kMinute) {
      if (ms >= kHour) {
        hours = MathFloor(ms / kHour);
        ms = ms % kHour;
      }
      minutes = MathFloor(ms / kMinute);
      ms = ms % kMinute;
    }
    seconds = ms / kSecond;
  }
 
  if (hours !== 0 || minutes !== 0) {
    ({ 0: seconds, 1: ms } = StringPrototypeSplit(
      NumberPrototypeToFixed(seconds, 3),
      '.'
    ));
    const res = hours !== 0 ? `${hours}:${pad(minutes)}` : minutes;
    return `${res}:${pad(seconds)}.${ms} (${hours !== 0 ? 'h:m' : ''}m:ss.mmm)`;
  }
 
  if (seconds !== 0) {
    return `${NumberPrototypeToFixed(seconds, 3)}s`;
  }
 
  return `${Number(NumberPrototypeToFixed(ms, 3))}ms`;
}
 
const keyKey = 'Key';
const valuesKey = 'Values';
const indexKey = '(index)';
const iterKey = '(iteration index)';
 
const isArray = (v) => ArrayIsArray(v) || isTypedArray(v) || isBuffer(v);
 
function noop() {}
 
for (const method of ReflectOwnKeys(consoleMethods))
  Console.prototype[method] = consoleMethods[method];
 
Console.prototype.debug = Console.prototype.log;
Console.prototype.info = Console.prototype.log;
Console.prototype.dirxml = Console.prototype.log;
Console.prototype.error = Console.prototype.warn;
Console.prototype.groupCollapsed = Console.prototype.group;
 
function initializeGlobalConsole(globalConsole) {
  globalConsole[kBindStreamsLazy](process);
  globalConsole[kBindProperties](true, 'auto');
 
  const {
    addSerializeCallback,
    isBuildingSnapshot,
  } = require('v8').startupSnapshot;
 
  if (!internalBinding('config').hasInspector || !isBuildingSnapshot()) {
    return;
  }
  const { console: consoleFromVM } = internalBinding('inspector');
  const nodeConsoleKeys = ObjectKeys(Console.prototype);
  const vmConsoleKeys = ObjectKeys(consoleFromVM);
  const originalKeys = new SafeSet(vmConsoleKeys.concat(nodeConsoleKeys));
  const inspectorConsoleKeys = new SafeSet();
  for (const key of ObjectKeys(globalConsole)) {
    if (!originalKeys.has(key)) {
      inspectorConsoleKeys.add(key);
    }
  }
  // During deserialization these should be reinstalled to console by
  // V8 when the inspector client is created.
  addSerializeCallback(() => {
    for (const key of inspectorConsoleKeys) {
      globalConsole[key] = undefined;
    }
  });
}
 
module.exports = {
  Console,
  kBindStreamsLazy,
  kBindProperties,
  initializeGlobalConsole,
  formatTime // exported for tests
};