# all files / raven-node/lib/ client.js

80.73% Statements 222/275
76.67% Branches 115/150
73.91% Functions 34/46
82.4% Lines 220/267

    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

    1×
    1×
    1×
    1×
    1×
    1×
    1×
    1×
    1×
    1×

    1×

    1×
    82×

    1×

    1×

    81×

    2×
    2×

    81×

    1×
    1×

    81×

    81×
    81×
    81×
    81×
    81×
    81×
    81×

    81×

    81×
    81×
    81×
    5×
    15×
    15×

    15×
    4×

    81×
    81×
    81×
    81×

    81×
    2×

    81×

    79×

    81×

    81×
    81×
    1×

    81×
    1×

    81×
    4×

    81×

    8×

    8×
    1×

    8×
    8×
    1×

    8×
    24×
    24×

    8×

    8×

    6×

    6×

    6×
    6×

    6×

    6×

    30×

    30×
    12×
    12×
    12×

    30×
    30×
    30×
    30×
    30×

    30×
    30×

    30×

    30×
    30×
    30×
    30×
    30×
    30×

    30×
    2×

    30×
    2×

    30×
    30×
    30×

    30×
    28×

    2×
    2×

    25×
    25×
    25×

    25×
    24×

    24×

    5×

    5×

    5×
    5×

    5×

    13×

    1×

    13×
    2×
    2×

    11×

    13×
    13×
    13×
    13×

    13×

    6×
    6×
    6×

    6×

    6×

    6×

    6×

    6×
    6×
    6×

    6×
    6×

    6×

    6×
    6×
    6×

    6×

    6×

    3×
    2×
    2×

    3×
    3×
    3×
    3×
    2×

    1×

    3×

    3×
    3×
    3×

    3×

    7×
    5×

    2×

    7×

    9×
    9×

    9×

    4×
    4×
    4×
    4×

    4×

    2×

    2×

    4×

    4×

    4×
    4×
    4×
    4×

    4×

    1×

    1×
    1×

    4×
    4×

    4×
    4×
    4×

    1×

    1×
    81×
    81×
    81×

    1×

    1×
    1×
    1×
    1×
    1×

    1×

    1×
    12×
    12×
    4×
    3×
    1×
    1×

    3×

    3×
    1×
    1×
    1×

    2×
    2×

    2×

    3×
    3×

    1×
    1×
    1×
    1×

    1×

    1×

     'use strict';

    var stringify = require('json-stringify-safe');
    var parsers = require('./parsers');
    var zlib = require('zlib');
    var utils = require('./utils');
    var uuid = require('uuid');
    var transports = require('./transports');
    var nodeUtil = require('util'); // nodeUtil to avoid confusion with "utils"
    var events = require('events');
    var domain = require('domain');
    var autoBreadcrumbs = require('./breadcrumbs');

    var extend = utils.extend;

    function Raven() {
      this.breadcrumbs = {
        record: this.captureBreadcrumb.bind(this)
      };
    }

    nodeUtil.inherits(Raven, events.EventEmitter);

    extend(Raven.prototype, {
      config: function config(dsn, options) {
        if (arguments.length === 0) {
          // no arguments, use default from environment
          dsn = process.env.SENTRY_DSN;
          options = {};
        }
        if (typeof dsn === 'object') {
          // They must only be passing through options
          options = dsn;
          dsn = process.env.SENTRY_DSN;
        }
        options = options || {};

        this.raw_dsn = dsn;
        this.dsn = utils.parseDSN(dsn);
        this.name = options.name || process.env.SENTRY_NAME || require('os').hostname();
        this.root = options.root || process.cwd();
        this.transport = options.transport || transports[this.dsn.protocol];
        this.release = options.release || process.env.SENTRY_RELEASE || '';
        this.environment = options.environment || process.env.SENTRY_ENVIRONMENT || '';

        // autoBreadcrumbs: true enables all, autoBreadcrumbs: false disables all
        // autoBreadcrumbs: { http: true } enables a single type
        // this procedure will ensure that this.autoBreadcrumbs is an object populated
        // with keys -> bools reflecting actual status of all breadcrumb types
        var autoBreadcrumbDefaults = {
          console: false,
          http: false,
          pg: false
        };
        // default to 30, don't allow higher than 100
        this.maxBreadcrumbs = Math.max(0, Math.min(options.maxBreadcrumbs || 30, 100));
        this.autoBreadcrumbs = extend({}, autoBreadcrumbDefaults);
        if (typeof options.autoBreadcrumbs !== 'undefined') {
          for (var key in autoBreadcrumbDefaults) {
            Eif (autoBreadcrumbDefaults.hasOwnProperty(key)) {
              Iif (typeof options.autoBreadcrumbs === 'boolean') {
                this.autoBreadcrumbs[key] = options.autoBreadcrumbs;
              } else if (typeof options.autoBreadcrumbs[key] === 'boolean') {
                this.autoBreadcrumbs[key] = options.autoBreadcrumbs[key];
              }
            }
          }
        }

        this.captureUnhandledRejections = options.captureUnhandledRejections;
        this.loggerName = options.logger || '';
        this.dataCallback = options.dataCallback;
        this.shouldSendCallback = options.shouldSendCallback;

        if (!this.dsn) {
          utils.consoleAlert('no DSN provided, error reporting disabled');
        }

        if (this.dsn.protocol === 'https') {
          // In case we want to provide our own SSL certificates / keys
          this.ca = options.ca || null;
        }

        // enabled if a dsn is set
        this._enabled = !!this.dsn;

        var globalContext = this._globalContext = {};
        if (options.tags) {
          globalContext.tags = options.tags;
        }
        if (options.extra) {
          globalContext.extra = options.extra;
        }

        this.on('error', function (err) {
          utils.consoleAlert('failed to send exception to sentry: ' + err.message);
        });

        return this;
      },

      install: function install(opts, cb) {
        Iif (this.installed) return this;

        if (typeof opts === 'function') {
          cb = opts;
        }

        registerExceptionHandler(this, cb);
        if (this.captureUnhandledRejections) {
          registerRejectionHandler(this, cb);
        }

        for (var key in this.autoBreadcrumbs) {
          Eif (this.autoBreadcrumbs.hasOwnProperty(key)) {
            this.autoBreadcrumbs[key] && autoBreadcrumbs.instrument(key, this);
          }
        }

        this.installed = true;

        return this;
      },

      uninstall: function uninstall() {
        Iif (!this.installed) return this;

        autoBreadcrumbs.restoreOriginals();

        // todo: this works for tests for now, but isn't what we ultimately want to be doing
        process.removeAllListeners('uncaughtException');
        process.removeAllListeners('unhandledRejection');

        this.installed = false;

        return this;
      },

      generateEventId: function generateEventId() {
        return uuid().replace(/-/g, '');
      },

      process: function process(eventId, kwargs, cb) {
        // prod codepaths shouldn't hit this branch, for testing
        if (typeof eventId === 'object') {
          cb = kwargs;
          kwargs = eventId;
          eventId = this.generateEventId();
        }

        var domainContext = domain.active && domain.active.sentryContext || {};
        kwargs.user = extend({}, this._globalContext.user, domainContext.user, kwargs.user);
        kwargs.tags = extend({}, this._globalContext.tags, domainContext.tags, kwargs.tags);
        kwargs.extra = extend({}, this._globalContext.extra, domainContext.extra, kwargs.extra);
        kwargs.breadcrumbs = {
          values: domainContext.breadcrumbs || []
        };

        kwargs.modules = utils.getModules();
        kwargs.server_name = kwargs.server_name || this.name;

        Iif (typeof process.version !== 'undefined') {
          kwargs.extra.node = process.version;
        }

        kwargs.environment = kwargs.environment || this.environment;
        kwargs.logger = kwargs.logger || this.loggerName;
        kwargs.event_id = eventId;
        kwargs.timestamp = new Date().toISOString().split('.')[0];
        kwargs.project = this.dsn.project_id;
        kwargs.platform = 'node';

        // Only include release information if it is set
        if (this.release) {
          kwargs.release = this.release;
        }

        if (this.dataCallback) {
          kwargs = this.dataCallback(kwargs);
        }

        var shouldSend = true;
        Iif (!this._enabled) shouldSend = false;
        if (this.shouldSendCallback && !this.shouldSendCallback()) shouldSend = false;

        if (shouldSend) {
          this.send(kwargs, cb);
        } else {
          // wish there was a good way to communicate to cb why we didn't send; worth considering cb api change?
          // avoiding setImmediate here because node 0.8
          cb && setTimeout(function () {
            cb(null, eventId);
          }, 0);
        }
      },

      send: function send(kwargs, cb) {
        var self = this;
        var skwargs = stringify(kwargs);
        var eventId = kwargs.event_id;

        zlib.deflate(skwargs, function (err, buff) {
          var message = buff.toString('base64'),
              timestamp = new Date().getTime(),
              headers = {
                'X-Sentry-Auth': utils.getAuthHeader(timestamp, self.dsn.public_key, self.dsn.private_key),
                'Content-Type': 'application/octet-stream',
                'Content-Length': message.length
              };

          self.transport.send(self, message, headers, eventId, cb);
        });
      },

      captureMessage: function captureMessage(message, kwargs, cb) {
        Iif (!cb && typeof kwargs === 'function') {
          cb = kwargs;
          kwargs = {};
        } else {
          kwargs = kwargs || {};
        }
        var eventId = this.generateEventId();
        this.process(eventId, parsers.parseText(message, kwargs), cb);

        return eventId;
      },

      captureException: function captureException(err, kwargs, cb) {
        if (!(err instanceof Error)) {
          // This handles when someone does:
          //   throw "something awesome";
          // We synthesize an Error here so we can extract a (rough) stack trace.
          err = new Error(err);
        }

        if (!cb && typeof kwargs === 'function') {
          cb = kwargs;
          kwargs = {};
        } else {
          kwargs = kwargs || {};
        }

        var self = this;
        var eventId = this.generateEventId();
        parsers.parseError(err, kwargs, function (kw) {
          self.process(eventId, kw, cb);
        });

        return eventId;
      },

      /* The onErr param here is sort of ugly and won't typically be used
       * but it lets us write the requestHandler middleware in terms of this function.
       * We could consider getting rid of it and just duplicating the domain
       * instantiation etc logic in the requestHandler middleware
       */
      context: function (ctx, func, onErr) {
        Eif (!func && typeof ctx === 'function') {
          func = ctx;
          ctx = {};
        }

        // todo/note: raven-js takes an args param to do apply(this, args)
        // i don't think it's correct/necessary to bind this to the wrap call
        // and i don't know if we need to support the args param; it's undocumented
        return this.wrap(ctx, func, onErr).apply(null);
      },

      wrap: function (options, func, onErr) {
        Iif (!func && typeof options === 'function') {
          func = options;
          options = {};
        }

        var wrapDomain = domain.create();
        // todo: better property name than sentryContext, maybe __raven__ or sth?
        wrapDomain.sentryContext = options;

        var self = this;
        Eif (typeof onErr !== 'function') {
          onErr = function (err) {
            self.captureException(err);
          };
        }

        wrapDomain.on('error', onErr);
        var wrapped = wrapDomain.bind(func);

        for (var property in func) {
          if ({}.hasOwnProperty.call(func, property)) {
            wrapped[property] = func[property];
          }
        }
        wrapped.prototype = func.prototype;
        wrapped.__raven__ = true;
        wrapped.__inner__ = func;
        // note: domain.bind sets wrapped.domain, but it's not documented, unsure if we should rely on that
        wrapped.__domain__ = wrapDomain;

        return wrapped;
      },

      interceptErr: function (options, func) {
        if (!func && typeof options === 'function') {
          func = options;
          options = {};
        }
        var self = this;
        var wrapped = function () {
          var err = arguments[0];
          if (err instanceof Error) {
            self.captureException(err, options);
          } else {
            func.apply(null, arguments);
          }
        };

        // repetitive with wrap
        for (var property in func) {
          if ({}.hasOwnProperty.call(func, property)) {
            wrapped[property] = func[property];
          }
        }
        wrapped.prototype = func.prototype;
        wrapped.__raven__ = true;
        wrapped.__inner__ = func;

        return wrapped;
      },

      setContext: function setContext(ctx) {
        if (domain.active) {
          domain.active.sentryContext = ctx;
        } else {
          this._globalContext = ctx;
        }
        return this;
      },

      mergeContext: function mergeContext(ctx) {
        extend(this.getContext(), ctx);
        return this;
      },

      getContext: function getContext() {
        Eif (domain.active) {
          Iif (!domain.active.sentryContext) {
            domain.active.sentryContext = {};
            utils.consoleAlert('sentry context not found on active domain');
          }
          return domain.active.sentryContext;
        }
        utils.consoleAlert('getContext called without context; this may indicate incorrect setup - refer to docs on contexts');
        return this._globalContext;
      },

      setCallbackHelper: function (propertyName, callback) {
        var original = this[propertyName];
        Eif (typeof callback === 'function') {
          this[propertyName] = function (data) {
            return callback(data, original);
          };
        } else {
          this[propertyName] = callback;
        }

        return this;
      },

      /*
       * Set the dataCallback option
       *
       * @param {function} callback The callback to run which allows the
       *                            data blob to be mutated before sending
       * @return {Raven}
       */
      setDataCallback: function (callback) {
        return this.setCallbackHelper('dataCallback', callback);
      },

      /*
       * Set the shouldSendCallback option
       *
       * @param {function} callback The callback to run which allows
       *                            introspecting the blob before sending
       * @return {Raven}
       */
      setShouldSendCallback: function (callback) {
        return this.setCallbackHelper('shouldSendCallback', callback);
      },

      requestHandler: function () {
        var self = this;
        return function (req, res, next) {
          self.context({}, next, next);
        };
      },

      errorHandler: function () {
        var self = this;
        return function (err, req, res, next) {
          var status = err.status || err.statusCode || err.status_code || 500;

          // skip anything not marked as an internal server error
          if (status < 500) return next(err);

          var kwargs = parsers.parseRequest(req);
          var eventId = self.captureException(err, kwargs);
          res.sentry = eventId;
          return next(err);
        };
      },

      captureBreadcrumb: function (breadcrumb) {
        // Avoid capturing global-scoped breadcrumbs before instrumentation finishes
        Iif (!this.installed) return;

        breadcrumb = extend({
          timestamp: +new Date / 1000
        }, breadcrumb);

        var currCtx = this.getContext();
        Eif (!currCtx.breadcrumbs) currCtx.breadcrumbs = [];
        currCtx.breadcrumbs.push(breadcrumb);
        Iif (currCtx.breadcrumbs.length > this.maxBreadcrumbs) {
          currCtx.breadcrumbs.shift();
        }

        this.setContext(currCtx);
      }
    });

    // Deprecations
    extend(Raven.prototype, {
      getIdent: function getIdent(result) {
        utils.consoleAlert('getIdent has been deprecated and will be removed in v2.0');
        return result;
      },
      captureError: function captureError() {
        utils.consoleAlert('captureError has been deprecated and will be removed in v2.0; use captureException instead');
        return this.captureException.apply(this, arguments);
      },
      captureQuery: function captureQuery() {
        utils.consoleAlert('captureQuery has been deprecated and will be removed in v2.0');
        return this;
      },
      patchGlobal: function (cb) {
        utils.consoleAlert('patchGlobal has been deprecated and will be removed in v2.0; use install instead');
        registerExceptionHandler(this, cb);
        return this;
      },
      setUserContext: function setUserContext() {
        utils.consoleAlert('setUserContext has been deprecated and will be removed in v2.0; use setContext instead');
        return this;
      },
      setExtraContext: function setExtraContext() {
        utils.consoleAlert('setExtraContext has been deprecated and will be removed in v2.0; use setContext instead');
        return this;
      },
      setTagsContext: function setTagsContext() {
        utils.consoleAlert('setTagsContext has been deprecated and will be removed in v2.0; use setContext instead');
        return this;
      },
    });
    Raven.prototype.get_ident = Raven.prototype.getIdent;

    // Maintain old API compat, need to make sure arguments length is preserved
    function Client(dsn, options) {
      Iif (dsn instanceof Client) return dsn;
      var ravenInstance = new Raven();
      return ravenInstance.config.apply(ravenInstance, arguments);
    }
    nodeUtil.inherits(Client, Raven);

    // Singleton-by-default but not strictly enforced
    // todo these extra export props are sort of an adhoc mess, better way to manage?
    var defaultInstance = new Raven();
    defaultInstance.Client = Client;
    defaultInstance.patchGlobal = patchGlobal;
    defaultInstance.version = require('../package.json').version;
    defaultInstance.disableConsoleAlerts = utils.disableConsoleAlerts;

    module.exports = defaultInstance;

    function registerExceptionHandler(client, cb) {
      var called = false;
      process.on('uncaughtException', function (err) {
        if (cb) { // bind event listeners only if a callback was supplied
          var onLogged = function onLogged() {
            called = false;
            cb(true, err);
          };

          var onError = function onError() {
            called = false;
            cb(false, err);
          };

          if (called) {
            client.removeListener('logged', onLogged);
            client.removeListener('error', onError);
            return cb(false, err);
          }

          client.once('logged', onLogged);
          client.once('error', onError);

          called = true;
        }

        var eventId = client.captureException(err);
        return utils.consoleAlert('uncaughtException: ' + eventId);
      });
    }

    function registerRejectionHandler(client, cb) {
      process.on('unhandledRejection', function (reason) {
        var eventId = client.captureException(reason, function (sendErr) {
          cb && cb(!sendErr, reason);
        });
        return utils.consoleAlert('unhandledRejection: ' + eventId);
      });
    }

    function patchGlobal(client, cb) {
      // handle when the first argument is the callback, with no client specified
      if (typeof client === 'function') {
        cb = client;
        client = new Client();
        // first argument is a string DSN
      } else if (typeof client === 'string') {
        client = new Client(client);
      }
      // at the end, if we still don't have a Client, let's make one!
      !(client instanceof Raven) && (client = new Client());

      registerExceptionHandler(client, cb);
    }