Wraps the request function for easier testing
Make an http request and invoke a callback
@private
@param {Object} opts options describing the http request to be made
@param {Function} callback the callback to invoke when the http request is completed
487894
function (opts, callback) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      if (this.readyState == 4 ) {
        if (this.status == 204){
          //success
          return callback(null);
        }else {
          return callback(this.statusText);
        }
      }
    };

    xhttp.open(opts.method, opts.host + '/' + opts.path, true);
    for (var header in opts.headers){
      var headerValue = opts.headers[header];
      xhttp.setRequestHeader(header, headerValue)
    }
    xhttp.send(opts.body);
  }
73651
function(options, callback) {
    // Create a promise to defer to later
    var deferred = Bluebird.defer();

    // Fire the request
    request(this._buildRequestOptions(options), function(err, response, body) {
      // Handle Errors
      if (err) {
        // Usually a connection error (server unresponsive)
        err = new MuniError(err.message || 'Internal Server Error', err.code || 500);
      } else if (response.statusCode >= 400) {
        // Usually an intentional error from the server
        err = new MuniError(this._extractError(body), response.statusCode);
      }
      if (err) {
        debug.warn('Adapter Request Error with Code: %d', err.code);
        callback && callback(err);
        return deferred.reject(err);
      }

      // Handle Success
      debug.info('Adapter Request Sent with code: %d', response.statusCode);
      callback && callback(null, body);
      return deferred.resolve(body);
    }.bind(this));

    return deferred.promise;
  }
762569
function callAction(request, response, callback) {
    if (typeof callback == 'function') {
      return Promive.resolve()
        .then(callback.bind(null, request, response));
    }

    try {
      var Action = require(ACTION_PATH + '/' + callback.action + '.js');
    } catch (error) {
      if (error.message == 'Cannot find module \'' + ACTION_PATH + '/' + callback.action + '.js\'') {
        return Promise.reject('Action ' + callback.action + ' does not exist.')
          .catch(this.onPageNotFound.bind(this, request, response));
      }
      return Promise.reject(error)
        .catch(this.onError.bind(this, request, response));
    }

    var instance = new Action(request, response);
    // Test if method exists
    if (!instance[callback.method]) {
      return Promise.reject(new Error('Method "' + callback.method + '" not found in action "' + callback.action + '"'));
    }

    var promise = Promise.resolve();
    if (instance.init && 'function' == typeof instance.init) {
      promise = promise.then(function () {
        return instance.init();
      });
    }

    promise = promise.then(function () {
      return instance[callback.method].apply(instance, callback.arguments);
    });

    if (instance.onError && 'function' == typeof instance.onError) {
      promise = promise.catch(function (error) {
        return instance.onError.call(instance, error)
      });
    }

    promise = promise.catch(this.onError.bind(this, request, response));

    return promise;
  }
690612
function(opts, method) {

      // create function vars
      var cts = this.cts,
          xhr = new XMLHttpRequest(),
          data = u.param(opts.data, opts.json);

      // XMLHttpRequest state change function
      xhr.onreadystatechange = function(){
        if (xhr.readyState === 4) {
          if (xhr.status >= 200 && xhr.status < 400){
            // call success callback
            opts.success(u.parse(xhr.response || xhr.responseText), xhr.statusText);
          }
          else {
            // call error callback
            opts.error(u.parse(xhr.response || xhr.responseText), xhr.statusText);
          }
        }
      };

      if (xhr.upload) {
        // XMLHttpRequest upload progress function
        xhr.upload.onprogress = function(event) {
          if (event.lengthComputable) {
            // call progress callback
            opts.up(event.total, event.loaded);
          }
        };
      }

      // XMLHttpRequest download progress function
      xhr.onprogress = function(event) {
        if (event.lengthComputable) {
          // call progress callback
          opts.down(event.total, event.loaded);
        }
      };

      // open request and set headers
      xhr.open(method, opts.url, opts.async);
      xhr.setRequestHeader('Content-type', (opts.json ? cts.json : cts.form));
      xhr.setRequestHeader('Accept', cts.json);

      opts.headers && u.each(opts.headers, function(header, value) {
        xhr.setRequestHeader(header, value);
      });

      // if set, send authorization header
      if (opts.auth) {
        xhr.setRequestHeader('Authorization', opts.auth);
      }

      // send the request
      xhr.send(data || null);

      return xhr;

    }
281354
function _sendRequest(method, uri, options, callback) {

        method(uri, options)
            .on('success', function(data, response) {
                if (data.result) {
                    callback(null, data.result);
                } else {
                    callback(null, data);
                }
            })
            .on('fail', function(err, response) {
                if (err) {
                    callback(err);
                } else {
                    callback(new Error('Request failed'));
                }
            })
            .on('error', function(err, response) {
                if (err) {
                    callback(err);
                } else {
                    callback(new Error('Request error'));
                }
            })
            .on('timeout', function(ms) {
                callback(new Error('Request timed out (' + ms + ')'));
            });
    }
41440
function getRequest(path, options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = {
      method: 'get'
    };
  } else {
    options.method = 'get';
  }

  if (options.params) {
    var uri = url.parse(path, true);
    uri.query = _.merge({}, uri.query, options.params);
    path = url.format(uri);
    delete options.params;
  }

  sendRequest(path, options, callback);
}
1073587
function onComplete(options, callback) {
        return function (req) {
            var resp;
            if (ctype = req.getResponseHeader('Content-Type')) {
                ctype = ctype.split(';')[0];
            }
            if (ctype === 'application/json' || ctype === 'text/json') {
                try {
                    resp = $.parseJSON(req.responseText)
                }
                catch (e) {
                    return callback(e, null, req);
                }
            }
            else {
                var ct = req.getResponseHeader("content-type") || "";
                var xml = ct.indexOf("xml") >= 0;
                resp = xml ? req.responseXML : req.responseText;
            }
            if (req.status == 200 || req.status == 201 || req.status == 202) {
                callback(null, resp, req);
            }
            else if (resp && (resp.error || resp.reason)) {
                var err = new Error(resp.reason || resp.error);
                err.error = resp.error;
                err.reason = resp.reason;
                err.code = resp.code;
                err.status = req.status;
                callback(err, null, req);
            }
            else {
                // TODO: map status code to meaningful error message
                var msg = req.statusText;
                if (!msg || msg === 'error') {
                    msg = 'Returned status code: ' + req.status;
                }
                var err2 = new Error(msg);
                err2.status = req.status;
                callback(err2, null, req);
            }
        };
    }
118819
function makeRequest(apiKey, path, opts, callback) {
    var 
        key,
        req,
        dataStr = '';
        
    if(callback === undefined) {
        throw 'No callback defined';
        return;
    }

    path = '/plus/v1/' + path + '?key=' + apiKey;
    for(key in opts) {
        path += '&' + key + '=' + opts[key];
    }

    req = https.request({
        host: 'www.googleapis.com',
        port: 443,
        path: path,
        method: 'GET'
    }, function(res) {
        res.on('data', function(data) {
            dataStr += data;
        });
        
        res.on('end', function() {
            if(opts.alt === undefined || opts.alt.toLowerCase() == 'json') {
                try {
                    callback(null, JSON.parse(dataStr));
                } catch(err) {
                    callback(null, dataStr);
                }
            }
            else {
                callback(null, dataStr);
            }
        });
        
        res.on('close', function () {
            res.emit('end');
        });
    });
    req.end();
    
    req.on('error', function(err) {
        callback(err);
    });

    return req;
}
1201797
function request(uri, opt, callback) {
    if (typeof opt === 'function') {
        callback = opt;
        opt = {};
    }
    return hyperquest(uri, opt, callback);
}
1332749
function () {
  /**
   * Renders an error view from a template and sends data to client
   * @param  {Object}   opts Configurable options (see periodicjs.core.responder for more details)
   * @param {string|Object} opts.err Error details for response
   * @param {Object} opts.req Express request object
   * @param {Object} opts.res Express response object
   * @param  {Function} [callback]   Optional callback function
   * @return {Object}      If callback is not defined returns a Promise which resolves after response has been sent
   */
  let fn = function handleDocumentQueryErrorResponse (opts = {}, callback) {
    let { err, req, res } = opts;
    if (opts.use_warning) this.protocol.warn(req, res, { err });
    else this.protocol.error(req, res, { err });
    if (req.query.format === 'json' || req.params.ext === 'json' || path.extname(req.originalUrl) === '.json' || req.is('json') || req.params.callback || req.is('application/json')) {
      return this.protocol.respond(req, res, { err });
    }
    else if (typeof callback === 'function') {
      return this.responder.error(err)
        .then(result => callback(null, result))
        .catch(callback);
    }
    else if (req.redirecturl) {
      req.redirectpath = (!req.redirectpath && req.redirecturl) ? req.redirecturl : req.redirectpath;
      return this.protocol.redirect(req, res);
    }
    else {
      return this._utility_responder.error(err, {})
        .then(result => {
          return this.protocol.respond(req, res, { responder_override: result });
        }, err => {
          return this.protocol.exception(req, res, { err });
        });
    }
  };
  let message = 'CoreController.handleDocumentQueryErrorResponse: Use CoreController.responder.error with an HTML adapter or CoreController._utility_responder.error instead';
  return wrapWithDeprecationWarning.call(this, fn, message);
}
94903
function connect (req, opts, fn) {

  var proxy = this.proxy;

  // create a socket connection to the proxy server
  var socket;
  if (this.secureProxy) {
    socket = tls.connect(proxy);
  } else {
    socket = net.connect(proxy);
  }

  // we need to buffer any HTTP traffic that happens with the proxy before we get
  // the CONNECT response, so that if the response is anything other than an "200"
  // response code, then we can re-play the "data" events on the socket once the
  // HTTP parser is hooked up...
  var buffers = [];
  var buffersLength = 0;

  function read () {
    var b = socket.read();
    if (b) ondata(b);
    else socket.once('readable', read);
  }

  function cleanup () {
    socket.removeListener('data', ondata);
    socket.removeListener('end', onend);
    socket.removeListener('error', onerror);
    socket.removeListener('close', onclose);
    socket.removeListener('readable', read);
  }

  function onclose (err) {
    debug('onclose had error %o', err);
  }

  function onend () {
    debug('onend');
  }

  function onerror (err) {
    cleanup();
    fn(err);
  }

  function ondata (b) {
    buffers.push(b);
    buffersLength += b.length;
    var buffered = Buffer.concat(buffers, buffersLength);
    var str = buffered.toString('ascii');

    if (!~str.indexOf('\r\n\r\n')) {
      // keep buffering
      debug('have not received end of HTTP headers yet...');
      if (socket.read) {
        read();
      } else {
        socket.once('data', ondata);
      }
      return;
    }

    var firstLine = str.substring(0, str.indexOf('\r\n'));
    var statusCode = +firstLine.split(' ')[1];
    debug('got proxy server response: %o', firstLine);

    if (200 == statusCode) {
      // 200 Connected status code!
      var sock = socket;

      // nullify the buffered data since we won't be needing it
      buffers = buffered = null;

      if (opts.secureEndpoint) {
        var host = opts.host;
        // since the proxy is connecting to an SSL server, we have
        // to upgrade this socket connection to an SSL connection
        debug('upgrading proxy-connected socket to TLS connection: %o', opts.host);
        opts.socket = socket;
        opts.servername = opts.host;
        opts.host = null;
        opts.hostname = null;
        opts.port = null;
        sock = tls.connect(opts);
        SocketUtil.secureSocket(sock, host);
      }

      cleanup();
      fn(null, sock);
    } else {
      // some other status code that's not 200... need to re-play the HTTP header
      // "data" events onto the socket once the HTTP machinery is attached so that
      // the user can parse and handle the error status code
      cleanup();

      // save a reference to the concat'd Buffer for the `onsocket` callback
      buffers = buffered;

      // need to wait for the "socket" event to re-play the "data" events
      req.once('socket', onsocket);
      fn(null, socket);
    }
  }

  function onsocket (socket) {
    // replay the "buffers" Buffer onto the `socket`, since at this point
    // the HTTP module machinery has been hooked up for the user
    if ('function' == typeof socket.ondata) {
      // node <= v0.11.3, the `ondata` function is set on the socket
      socket.ondata(buffers, 0, buffers.length);
    } else if (socket.listeners('data').length > 0) {
      // node > v0.11.3, the "data" event is listened for directly
      socket.emit('data', buffers);
    } else {
      // never?
      throw new Error('should not happen...');
    }

    // nullify the cached Buffer instance
    buffers = null;
  }

  socket.on('error', onerror);
  socket.on('close', onclose);
  socket.on('end', onend);

  if (socket.read) {
    read();
  } else {
    socket.once('data', ondata);
  }

  var hostname = opts.host + ':' + opts.port;
  var msg = 'CONNECT ' + hostname + ' HTTP/1.1\r\n';
  var auth = proxy.auth;
  if (auth) {
    msg += 'Proxy-Authorization: Basic ' + Buffer.from(auth, 'utf8').toString('base64') + '\r\n';
  }
  msg += 'Host: ' + hostname + '\r\n' +
      'Connection: close\r\n' +
      '\r\n';
  socket.write(msg);
}
329302
function CallFunc (opts) {
    CallFunc.superclass.constructor.call(this, opts)

    // Save target & method so that copy() can recreate callback
    this.target = opts.target
    this.method = (typeof opts.method == 'function') ? opts.method : this.target[opts.method]
    this.callback = this.method.bind(this.target)
}
1254993
function(callbacks) {
        callbacks = callbacks || {};
        var onTrue = callbacks.onTrue || angular.noop;
        var onFalse = callbacks.onFalse || angular.noop;
        var onString = callbacks.onString || angular.noop;
        var onWait = callbacks.onWait || angular.noop;

        var self = this;

        if (this.promises.length) {
          onWait(true);
          $q.all(this.promises).then(
            //all resolved       
            function(results) {
              onWait(false);
              //check all results via same `when` method (without checking promises)
              angular.forEach(results, function(result) {
                self.when(result, true);  
              });
              applyCallback();
            },
            //some rejected
            function(error) { 
              onWait(false);
              onString();
            }
            );
        } else {
          applyCallback();
        }

        function applyCallback() {
          if (!self.hasString && !self.hasFalse) {
            onTrue();
          } else if (!self.hasString && self.hasFalse) {
            onFalse();
          } else {
            onString();
          }
        }

      }
1161890
function do_js(url, opts) {
	opts = opts || {};
	if(is.object(opts) && is['function'](opts.body)) {
		opts.body = FUNCTION(opts.body).stringify();
	} else if(is.object(opts) && is.string(opts.body)) {
	} else {
		throw new TypeError('opts.body is not function nor string');
	}
	opts.headers = opts.headers || {};
	if(opts.body) {
		opts.headers['Content-Type'] = 'application/javascript;charset=utf8';
	}

	// Default method should be POST since JavaScript code usually might change something.
	if(!opts.method) {
		opts.method = 'post';
	}

	opts.headers.Accept = 'application/json';
	return do_plain(url, opts).then(function(buffer) {
		return JSON.parse(buffer);
	});
}
297574
function stringify(opts, callback) {
    assert.object(opts, 'opts');
    assert.func(callback, 'callback');

    let stringified = '';
    const stringifyStream = createStringifyStream(opts);
    const passthroughStream = new stream.PassThrough();
    const cb = once(callback);

    // setup the passthrough stream as a sink
    passthroughStream.on('data', function(chunk) {
        stringified += chunk;
    });

    passthroughStream.on('end', function() {
        return cb(null, stringified);
    });

    // don't know what errors stringify stream may emit, but pass them back
    // up.
    stringifyStream.on('error', function(err) {
        return cb(err);
    });

    stringifyStream.pipe(passthroughStream);
}
1037921
function _request(requestOptions, userOptions, successCallback, errorCallback) {
    var successCb = successCallback,
      errorCb = errorCallback,
      request;

    // This verification allows not to pass any options, and have callbacks in
    // its place. It also allows passing *null* if there is no success callback.
    if (Utils.isFunction(userOptions) || userOptions === null) {

      successCb = userOptions;
      errorCb = successCallback;

    } else if (Utils.isObject(userOptions)) {

      // If options is an object, merge it with the request options. Callbacks
      // can be included in this object or as separate parameters (same as
      // `EVT.api()`).
      requestOptions = Utils.extend(requestOptions, userOptions);

    }

    // Use current scope's API key to perform the request.
    requestOptions.authorization = this.scope.apiKey;

    // If parentScope is set to operator scope, use the operator API key.
    if (EVT.Operator && this.scope.parentScope instanceof EVT.Operator) {
      requestOptions.authorization = this.scope.parentScope.apiKey;

      // If we're working in application scope as an operator,
      // we need to send the application id as a parameter.
      if (this.scope instanceof EVT.App) {
        requestOptions.params = requestOptions.params || {};
        requestOptions.params.project = this.scope.project;
      }
    }

    // Actually make the request and handle its response, by forwarding to
    // the raw `EVT.api()` method.
    request = EVT.api(requestOptions, successCb, errorCb);

    return _handleResponse.call(this, request);
  }
1339611
function _wrapCalls(options){
            return function(){
                var api;

                options.func.apply(options.context, Array.prototype.slice.call(arguments, 0));

                for (var i = 0; i < externalAPIS.length; i++) {
                    api = externalAPIS[i];
                    if (api[options.triggerType]) {
                        try {
                            api[options.triggerType].apply(api.context,Array.prototype.slice.call(arguments, 0));
                        }
                        catch (exc) {}
                    }
                }
            };
        }