all files / dist/ utils.js

72.83% Statements 134/184
61.11% Branches 66/108
76.32% Functions 29/38
72.12% Lines 119/165
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          27834×   19×                                             27×   27× 495× 495×   495× 495×       27×                           162×   162× 126×   162× 162× 162×     162× 126× 621× 621×   612× 612× 612× 36× 36× 72×   576×           576× 576× 576× 576× 378×             162×                             4698× 4698×     4698× 5094× 1674×   3420×               3420×       4698× 26856× 2358×   24498× 342× 342× 306×   36×     24156×       4698×                         32292× 32292× 32292× 32292×   32292× 2970×   29322× 20412×   8910× 65052× 1962×     6948× 27792×       6948× 720×   6228×                         30× 30×     30×                         37× 37× 37× 28×                                                                 21× 441×     21×         42×         41×         42×                                                                               63× 63×   36×     27×                                                                                                                                                                         234× 1170×           18× 18×   18×     18×                                                                                
'use strict';
 
Object.defineProperty(exports, "__esModule", {
  value: true
});
 
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
 
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; Eif ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { Iif (protoProps) defineProperties(Constructor.prototype, protoProps); Eif (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
 
var _os = require('os');
 
var _os2 = _interopRequireDefault(_os);
 
var _fs = require('fs');
 
var _fs2 = _interopRequireDefault(_fs);
 
var _path = require('path');
 
var _path2 = _interopRequireDefault(_path);
 
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
 
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
 
var Utils = function () {
  function Utils() {
    _classCallCheck(this, Utils);
  }
 
  _createClass(Utils, null, [{
    key: 'getFiles',
 
 
    /**
     * Read all files from the given directory.
     *
     * @param dir         Folder path to search.
     * @returns {Array}   Array with the files paths.
     */
    value: function getFiles(dir) {
      var results = [];
 
      _fs2.default.readdirSync(dir).forEach(function (file) {
        file = dir + '/' + file;
        var stat = _fs2.default.statSync(file);
 
        Eif (stat && !stat.isDirectory()) {
          results.push(file);
        }
      });
 
      return results;
    }
 
    /**
     * Get all .js files in a directory.
     *
     * @param dir
     * @param extension
     * @returns {Array.<T>}
     */
 
  }, {
    key: 'recursiveDirectoryGlob',
    value: function recursiveDirectoryGlob(dir, extension) {
      var results = [];
 
      if (!extension) {
        extension = 'js';
      }
      extension = extension.replace('.', '');
      Eif (dir[dir.length - 1] !== '/') {
        dir += '/';
      }
 
      if (_fs2.default.existsSync(dir)) {
        _fs2.default.readdirSync(dir).forEach(function (file) {
          var fullFilePath = _path2.default.normalize(dir + file);
          if (file[0] !== '.') {
            // ignore 'system' files
            var stats = _fs2.default.statSync(fullFilePath);
            var child;
            if (stats.isDirectory()) {
              child = Utils.recursiveDirectoryGlob(fullFilePath, extension);
              child.forEach(function (c) {
                results.push(c);
              });
            } else Iif (stats.isSymbolicLink()) {
              var realPath = _fs2.default.readlinkSync(fullFilePath);
              child = Utils.recursiveDirectoryGlob(realPath);
              child.forEach(function (c) {
                results.push(c);
              });
            } else Eif (stats.isFile()) {
              var fileParts = file.split('.');
              var ext = fileParts[fileParts.length - 1];
              if (ext === extension) {
                results.push(fullFilePath);
              }
            }
          }
        });
      }
 
      return results.sort();
    }
 
    /**
     * Merge two hashes recursively.
     *
     * @param a
     * @param b
     * @param arg
     * @returns {{}}
     */
 
  }, {
    key: 'hashMerge',
    value: function hashMerge(a, b, arg) {
      var c = {};
      var i = void 0,
          response = void 0;
 
      for (i in a) {
        if (Utils.isPlainObject(a[i]) && Object.keys(a[i]).length > 0) {
          c[i] = Utils.hashMerge(c[i], a[i], arg);
        } else {
          Iif (typeof a[i] === 'function') {
            response = a[i](arg);
            if (Utils.isPlainObject(response)) {
              c[i] = Utils.hashMerge(c[i], response, arg);
            } else {
              c[i] = response;
            }
          } else {
            c[i] = a[i];
          }
        }
      }
      for (i in b) {
        if (Utils.isPlainObject(b[i]) && Object.keys(b[i]).length > 0) {
          c[i] = Utils.hashMerge(c[i], b[i], arg);
        } else {
          if (typeof b[i] === 'function') {
            response = b[i](arg);
            if (Utils.isPlainObject(response)) {
              c[i] = Utils.hashMerge(c[i], response, arg);
            } else {
              c[i] = response;
            }
          } else {
            c[i] = b[i];
          }
        }
      }
      return c;
    }
 
    /**
     * Check if the passed argument is a plain object.
     *
     * @param o
     * @returns {boolean}
     */
 
  }, {
    key: 'isPlainObject',
    value: function isPlainObject(o) {
      var safeTypes = [Boolean, Number, String, Function, Array, Date, RegExp, Buffer];
      var safeInstances = ['boolean', 'number', 'string', 'function'];
      var expandPreventMatchKey = '_toExpand'; // set `_toExpand = false` within an object if you don't want to expand it
      var i;
 
      if (!o) {
        return false;
      }
      if (o instanceof Object === false) {
        return false;
      }
      for (i in safeTypes) {
        if (o instanceof safeTypes[i]) {
          return false;
        }
      }
      for (i in safeInstances) {
        Iif ((typeof o === 'undefined' ? 'undefined' : _typeof(o)) === safeInstances[i]) {
          return false;
        }
      }
      if (o[expandPreventMatchKey] === false) {
        return false;
      }
      return o.toString() === '[object Object]';
    }
 
    /**
     * Cookie parse from headers of http(s) requests.
     *
     * @param req
     * @returns {{}}
     */
 
  }, {
    key: 'parseCookies',
    value: function parseCookies(req) {
      var cookies = {};
      if (req.headers.cookie) {
        req.headers.cookie.split(';').forEach(function (cookie) {
          var parts = cookie.split('=');
          cookies[parts[0].trim()] = (parts[1] || '').trim();
        });
      }
      return cookies;
    }
 
    /**
     * Collapse this object to an array.
     *
     * @param obj
     * @returns {*}
     */
 
  }, {
    key: 'collapseObjectToArray',
    value: function collapseObjectToArray(obj) {
      try {
        var keys = Object.keys(obj);
        if (keys.length < 1) {
          return false;
        }
        Eif (keys[0] !== '0') {
          return false;
        }
        if (keys[keys.length - 1] !== String(keys.length - 1)) {
          return false;
        }
 
        var arr = [];
        for (var i in keys) {
          var key = keys[i];
          if (String(parseInt(key)) !== key) {
            return false;
          } else {
            arr.push(obj[key]);
          }
        }
 
        return arr;
      } catch (e) {
        return false;
      }
    }
 
    /**
     * Unique-ify an array.
     *
     * @param array Array to be uniquefied.
     * @returns {Array} New array.
     */
 
  }, {
    key: 'arrayUniqueify',
    value: function arrayUniqueify(array) {
      array.filter(function (value, index, self) {
        return self.indexOf(value) === index;
      });
 
      return array;
    }
  }, {
    key: 'isObject',
    value: function isObject(arg) {
      return (typeof arg === 'undefined' ? 'undefined' : _typeof(arg)) === 'object' && arg !== null;
    }
  }, {
    key: 'objectToString',
    value: function objectToString(o) {
      return Object.prototype.toString.call(o);
    }
  }, {
    key: 'isError',
    value: function isError(e) {
      return Utils.isObject(e) && (Utils.objectToString(e) === '[object Error]' || e instanceof Error);
    }
 
    /**
     * Remove a directory.
     *
     * @param dir   Directory path.
     */
 
  }, {
    key: 'removeDirectory',
    value: function removeDirectory(dir) {
      var filesList = void 0;
 
      // get directory files
      try {
        filesList = _fs2.default.readdirSync(dir);
      } catch (e) {
        return;
      }
 
      // iterate all folders and files on the directory
      filesList.forEach(function (file) {
        // get full file path
        var filePath = dir + '/' + file;
 
        // check if it's a file
        Eif (_fs2.default.statSync(filePath).isFile()) {
          _fs2.default.unlinkSync(filePath);
        } else {
          Utils.removeDirectory(filePath);
        }
      });
 
      // remove current directory
      _fs2.default.rmdirSync(dir);
    }
 
    /**
     * Check if the directory exists.
     *
     * @param dir           Directory path.
     * @returns {boolean}   True if exists, false if not or the given path isn't a directory.
     */
 
  }, {
    key: 'directoryExists',
    value: function directoryExists(dir) {
      try {
        _fs2.default.statSync(dir).isDirectory();
      } catch (er) {
        return false;
      }
 
      return true;
    }
 
    /**
     * Check if a file exists.
     *
     * @param path          Path to check.
     * @returns {boolean}   True if the file exists, false otherwise.
     */
 
  }, {
    key: 'fileExists',
    value: function fileExists(path) {
      try {
        _fs2.default.statSync(path).isFile();
      } catch (error) {
        return false;
      }
 
      return true;
    }
 
    /**
     * Create a new directory.
     *
     * @param path Path there the directory must be created.
     */
 
  }, {
    key: 'createFolder',
    value: function createFolder(path) {
      try {
        _fs2.default.mkdirSync(path);
      } catch (e) {
        if (e.code != 'EEXIST') {
          throw e;
        }
      }
    }
 
    /**
     * Copy a file.
     *
     * This only work with files.
     *
     * @param source        Source path.
     * @param destination   Destination path.
     */
 
  }, {
    key: 'copyFile',
    value: function copyFile(source, destination) {
      _fs2.default.createReadStream(source).pipe(_fs2.default.createWriteStream(destination));
    }
 
    /**
     * Get this servers external interface.
     *
     * @returns {String} Server external IP or false if not founded.
     */
 
  }, {
    key: 'getExternalIPAddress',
    value: function getExternalIPAddress() {
      var ifaces = _os2.default.networkInterfaces();
      var ip = false;
 
      for (var dev in ifaces) {
        ifaces[dev].forEach(function (details) {
          if (details.family === 'IPv4' && details.address !== '127.0.0.1') {
            ip = details.address;
          }
        });
      }
 
      return ip;
    }
 
    /**
     * Make a clone of an object.
     *
     * @param obj         Object to be cloned.
     * @returns {Object}  New object reference.
     */
 
  }, {
    key: 'objClone',
    value: function objClone(obj) {
      return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyNames(obj).reduce(function (memo, name) {
        return (memo[name] = Object.getOwnPropertyDescriptor(obj, name)) && memo;
      }, {}));
    }
  }, {
    key: 'stringToHash',
    value: function stringToHash(api, path, object) {
      Eif (!object) {
        object = api;
      }
      function _index(obj, i) {
        return obj[i];
      }
 
      return path.split('.').reduce(_index, object);
    }
 
    /**
     * Parse an IPv6 address.
     *
     * @param address   Address to be parsed.
     * @returns {{host: string, port: Number}}
     */
 
  }, {
    key: 'parseIPv6URI',
    value: function parseIPv6URI(address) {
      var host = '::1';
      var port = 80;
      var regexp = new RegExp(/\[([0-9a-f:]+)\]:([0-9]{1,5})/);
 
      // if we have brackets parse them and find a port
      if (address.indexOf('[') > -1 && address.indexOf(']') > -1) {
        // execute the regular expression
        var res = regexp.exec(address);
 
        // if null this isn't a valid IPv6 address
        if (res === null) {
          throw new Error('failed to parse address');
        }
 
        host = res[1];
        port = res[2];
      } else {
        host = address;
      }
 
      return { host: host, port: parseInt(port, 10) };
    }
  }]);
 
  return Utils;
}();
 
exports.default = Utils;
//# sourceMappingURL=utils.js.map