text: // Generated by CoffeeScript 1.12.4
  var ApiaryReporter, CONNECTION_ERRORS, clone, generateUuid, http, https, logger, os, packageData, url,
    bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
    hasProp = {}.hasOwnProperty;
  
  http = require('http');
  
  https = require('https');
  
  os = require('os');
  
  url = require('url');
  
  clone = require('clone');
  
  generateUuid = require('uuid').v4;
  
  packageData = require('./../../package.json');
  
  logger = require('./../logger');
  
  CONNECTION_ERRORS = ['ECONNRESET', 'ENOTFOUND', 'ESOCKETTIMEDOUT', 'ETIMEDOUT', 'ECONNREFUSED', 'EHOSTUNREACH', 'EPIPE'];
  
  ApiaryReporter = (function() {
    function ApiaryReporter(emitter, stats, tests, config, runner) {
      this._performRequestAsync = bind(this._performRequestAsync, this);
      this.configureEmitter = bind(this.configureEmitter, this);
      var base;
      this.type = 'apiary';
      this.stats = stats;
      this.tests = tests;
      this.uuid = null;
      this.startedAt = null;
      this.endedAt = null;
      this.remoteId = null;
      this.config = config;
      this.runner = runner;
      this.reportUrl = null;
      this.configureEmitter(emitter);
      this.errors = [];
      this.serverError = false;
      this.configuration = {
        apiUrl: this._get('apiaryApiUrl', 'APIARY_API_URL', 'https://api.apiary.io'),
        apiToken: this._get('apiaryApiKey', 'APIARY_API_KEY', null),
        apiSuite: this._get('apiaryApiName', 'APIARY_API_NAME', null)
      };
      logger.verbose("Using '" + this.type + "' reporter.");
      if (!this.configuration.apiToken && !this.configuration.apiSuite) {
        logger.warn('Apiary API Key or API Project Subdomain were not provided. Configure Dredd to be able to save test reports alongside your Apiary API project: https://dredd.readthedocs.io/en/latest/how-to-guides/#using-apiary-reporter-and-apiary-tests');
      }
      if ((base = this.configuration).apiSuite == null) {
        base.apiSuite = 'public';
      }
    }
  
    ApiaryReporter.prototype._get = function(customProperty, envProperty, defaultVal) {
      var ref, ref1, ref2, ref3, ref4, ref5, ref6, returnVal;
      returnVal = defaultVal;
      if (((ref = this.config.custom) != null ? ref[customProperty] : void 0) != null) {
        returnVal = this.config.custom[customProperty];
      } else if (((ref1 = this.config.options) != null ? (ref2 = ref1.custom) != null ? ref2[customProperty] : void 0 : void 0) != null) {
        returnVal = this.config.options.custom[customProperty];
      } else if (((ref3 = this.config.custom) != null ? (ref4 = ref3.apiaryReporterEnv) != null ? ref4[customProperty] : void 0 : void 0) != null) {
        returnVal = this.config.custom.apiaryReporterEnv[customProperty];
      } else if (((ref5 = this.config.custom) != null ? (ref6 = ref5.apiaryReporterEnv) != null ? ref6[envProperty] : void 0 : void 0) != null) {
        returnVal = this.config.custom.apiaryReporterEnv[envProperty];
      } else if (process.env[envProperty] != null) {
        returnVal = process.env[envProperty];
      }
      return returnVal;
    };
  
    ApiaryReporter.prototype._getKeys = function() {
      var ref, returnKeys;
      returnKeys = [];
      returnKeys = returnKeys.concat(Object.keys(((ref = this.config.custom) != null ? ref.apiaryReporterEnv : void 0) || {}));
      return returnKeys.concat(Object.keys(process.env));
    };
  
    ApiaryReporter.prototype.configureEmitter = function(emitter) {
      var _createStep;
      emitter.on('start', (function(_this) {
        return function(blueprintsData, callback) {
          var blueprints, ciEnvVars, ciVars, data, envVarName, envVarNames, filename, i, len, path;
          if (_this.serverError === true) {
            return callback();
          }
          _this.uuid = generateUuid();
          _this.startedAt = Math.round(new Date().getTime() / 1000);
          ciVars = /^(TRAVIS|CIRCLE|CI|DRONE|BUILD_ID)/;
          envVarNames = _this._getKeys();
          ciEnvVars = {};
          for (i = 0, len = envVarNames.length; i < len; i++) {
            envVarName = envVarNames[i];
            if (envVarName.match(ciVars) != null) {
              ciEnvVars[envVarName] = _this._get(envVarName, envVarName);
            }
          }
          blueprints = (function() {
            var results;
            results = [];
            for (filename in blueprintsData) {
              if (!hasProp.call(blueprintsData, filename)) continue;
              data = blueprintsData[filename];
              results.push(data);
            }
            return results;
          })();
          data = {
            blueprints: blueprints,
            endpoint: _this.config.server,
            agent: _this._get('dreddAgent', 'DREDD_AGENT') || _this._get('user', 'USER'),
            agentRunUuid: _this.uuid,
            hostname: _this._get('dreddHostname', 'DREDD_HOSTNAME') || os.hostname(),
            startedAt: _this.startedAt,
            "public": true,
            status: 'running',
            agentEnvironment: ciEnvVars
          };
          if ((_this.configuration['apiToken'] != null) && (_this.configuration['apiSuite'] != null)) {
            data["public"] = false;
          }
          path = '/apis/' + _this.configuration['apiSuite'] + '/tests/runs';
          return _this._performRequestAsync(path, 'POST', data, function(error, response, parsedBody) {
            if (error) {
              return callback(error);
            } else {
              _this.remoteId = parsedBody['_id'];
              if (parsedBody['reportUrl']) {
                _this.reportUrl = parsedBody['reportUrl'];
              }
              return callback();
            }
          });
        };
      })(this));
      _createStep = (function(_this) {
        return function(test, callback) {
          var data, path;
          if (_this.serverError === true) {
            return callback();
          }
          data = _this._transformTestToReporter(test);
          path = '/apis/' + _this.configuration['apiSuite'] + '/tests/steps?testRunId=' + _this.remoteId;
          return _this._performRequestAsync(path, 'POST', data, function(error, response, parsedBody) {
            if (error) {
              return callback(error);
            }
            return callback();
          });
        };
      })(this);
      emitter.on('test pass', _createStep);
      emitter.on('test fail', _createStep);
      emitter.on('test skip', _createStep);
      emitter.on('test error', (function(_this) {
        return function(error, test, callback) {
          var base, base1, data, path;
          if (_this.serverError === true) {
            return callback();
          }
          data = _this._transformTestToReporter(test);
          if ((base = data.resultData).result == null) {
            base.result = {};
          }
          if ((base1 = data.resultData.result).general == null) {
            base1.general = [];
          }
          if (CONNECTION_ERRORS.indexOf(error.code) > -1) {
            data.resultData.result.general.push({
              severity: 'error',
              message: "Error connecting to server under test!"
            });
          } else {
            data.resultData.result.general.push({
              severity: 'error',
              message: "Unhandled error occured when executing the transaction."
            });
          }
          path = '/apis/' + _this.configuration['apiSuite'] + '/tests/steps?testRunId=' + _this.remoteId;
          return _this._performRequestAsync(path, 'POST', data, function(error, response, parsedBody) {
            if (error) {
              return callback(error);
            }
            return callback();
          });
        };
      })(this));
      return emitter.on('end', (function(_this) {
        return function(callback) {
          var data, path, ref, ref1;
          if (_this.serverError === true) {
            return callback();
          }
          data = {
            endedAt: Math.round(new Date().getTime() / 1000),
            result: _this.stats,
            status: _this.stats['failures'] > 0 || _this.stats['errors'] > 0 ? 'failed' : 'passed',
            logs: ((ref = _this.runner) != null ? (ref1 = ref.logs) != null ? ref1.length : void 0 : void 0) ? _this.runner.logs : void 0
          };
          path = '/apis/' + _this.configuration['apiSuite'] + '/tests/run/' + _this.remoteId;
          return _this._performRequestAsync(path, 'PATCH', data, function(error, response, parsedBody) {
            var reportUrl;
            if (error) {
              return callback(error);
            }
            reportUrl = _this.reportUrl || ("https://app.apiary.io/" + _this.configuration.apiSuite + "/tests/run/" + _this.remoteId);
            logger.complete("See results in Apiary at: " + reportUrl);
            return callback();
          });
        };
      })(this));
    };
  
    ApiaryReporter.prototype._transformTestToReporter = function(test) {
      var data;
      data = {
        testRunId: this.remoteId,
        origin: test['origin'],
        duration: test['duration'],
        result: test['status'],
        startedAt: test['startedAt'],
        resultData: {
          request: test['request'],
          realResponse: test['actual'],
          expectedResponse: test['expected'],
          result: test['results']
        }
      };
      return data;
    };
  
    ApiaryReporter.prototype._performRequestAsync = function(path, method, body, callback) {
      var buffer, handleReqError, handleResponse, options, parsedUrl, postData, ref, req, system;
      logger.debug("Performing " + (method.toUpperCase()) + " request to '" + this.configuration.apiUrl + "' + '" + path + "', " + (body ? 'with' : 'without') + " body.");
      buffer = "";
      handleResponse = function(res) {
        res.setEncoding('utf8');
        res.on('data', function(chunk) {
          logger.verbose('Apiary reporter received HTTP response chunk:', chunk);
          return buffer = buffer + chunk;
        });
        res.on('error', function(error) {
          logger.debug('Apiary reporter got HTTP response error:', error);
          return callback(error, req, res);
        });
        return res.on('end', function() {
          var e, info, parsedBody;
          logger.verbose('Apiary reporter received response from Apiary API.');
          try {
            parsedBody = JSON.parse(buffer);
          } catch (error1) {
            e = error1;
            return callback(new Error("Apiary reporter failed to parse Apiary API response body: " + e.message + "\n" + buffer));
          }
          info = {
            headers: res.headers,
            statusCode: res.statusCode,
            body: parsedBody
          };
          logger.verbose('Apiary reporter response:', JSON.stringify(info, null, 2));
          return callback(void 0, res, parsedBody);
        });
      };
      parsedUrl = url.parse(this.configuration['apiUrl']);
      system = os.type() + ' ' + os.release() + '; ' + os.arch();
      postData = JSON.stringify(body);
      options = {
        host: parsedUrl['hostname'],
        port: parsedUrl['port'],
        path: path,
        method: method,
        headers: {
          'User-Agent': "Dredd Apiary Reporter/" + packageData.version + " (" + system + ")",
          'Content-Type': 'application/json',
          'Content-Length': Buffer.byteLength(postData, 'utf8')
        }
      };
      if (this.configuration['apiToken'] !== null) {
        options.headers['Authentication'] = 'Token ' + this.configuration['apiToken'];
      }
      logger.verbose('Apiary reporter request:', JSON.stringify({
        options: options,
        body: body
      }, null, 2));
      handleReqError = (function(_this) {
        return function(error) {
          _this.serverError = true;
          if (CONNECTION_ERRORS.indexOf(error.code) > -1) {
            return callback("Apiary reporter: Error connecting to Apiary test reporting API.");
          } else {
            return callback(error, req, null);
          }
        };
      })(this);
      logger.verbose('Starting HTTP request from Apiary reporter to Apiary API');
      if ((ref = this.configuration.apiUrl) != null ? ref.match(/^https/) : void 0) {
        logger.debug('Using HTTPS for Apiary reporter request');
        req = https.request(options, handleResponse);
      } else {
        logger.debug('Using unsecured HTTP for Apiary reporter request');
        req = http.request(options, handleResponse);
      }
      req.on('error', handleReqError);
      req.write(postData);
      return req.end();
    };
  
    return ApiaryReporter;
  
  })();
  
  module.exports = ApiaryReporter;
  