Object.defineProperty(exports, '__esModule', { value: true });

const currentScopes = require('../currentScopes.js');
const exports$1 = require('../exports.js');
const integration = require('../integration.js');
const console = require('../utils-hoist/instrument/console.js');
const logger = require('../utils-hoist/logger.js');
const misc = require('../utils-hoist/misc.js');
const severity = require('../utils-hoist/severity.js');
const string = require('../utils-hoist/string.js');
const worldwide = require('../utils-hoist/worldwide.js');

const INTEGRATION_NAME = 'CaptureConsole';

const _captureConsoleIntegration = ((options = {}) => {
  const levels = options.levels || logger.CONSOLE_LEVELS;
  // TODO(v9): Flip default value to `true`
  const handled = !!options.handled;

  return {
    name: INTEGRATION_NAME,
    setup(client) {
      if (!('console' in worldwide.GLOBAL_OBJ)) {
        return;
      }

      console.addConsoleInstrumentationHandler(({ args, level }) => {
        if (currentScopes.getClient() !== client || !levels.includes(level)) {
          return;
        }

        consoleHandler(args, level, handled);
      });
    },
  };
}) ;

/**
 * Send Console API calls as Sentry Events.
 */
const captureConsoleIntegration = integration.defineIntegration(_captureConsoleIntegration);

function consoleHandler(args, level, handled) {
  const captureContext = {
    level: severity.severityLevelFromString(level),
    extra: {
      arguments: args,
    },
  };

  currentScopes.withScope(scope => {
    scope.addEventProcessor(event => {
      event.logger = 'console';

      misc.addExceptionMechanism(event, {
        handled,
        type: 'console',
      });

      return event;
    });

    if (level === 'assert') {
      if (!args[0]) {
        const message = `Assertion failed: ${string.safeJoin(args.slice(1), ' ') || 'console.assert'}`;
        scope.setExtra('arguments', args.slice(1));
        exports$1.captureMessage(message, captureContext);
      }
      return;
    }

    const error = args.find(arg => arg instanceof Error);
    if (error) {
      exports$1.captureException(error, captureContext);
      return;
    }

    const message = string.safeJoin(args, ' ');
    exports$1.captureMessage(message, captureContext);
  });
}

exports.captureConsoleIntegration = captureConsoleIntegration;
//# sourceMappingURL=captureconsole.js.map
