"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.findPackageData = findPackageData;

function _path() {
  var data = _interopRequireDefault(require("path"));

  _path = function _path() {
    return data;
  };

  return data;
}

var _utils = require("./utils");

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var PACKAGE_FILENAME = "package.json";

function findPackageData(filepath) {
  var pkg = null;
  var directories = [];
  var isPackage = true;

  var dirname = _path().default.dirname(filepath);

  while (!pkg && _path().default.basename(dirname) !== "node_modules") {
    directories.push(dirname);
    pkg = readConfigPackage(_path().default.join(dirname, PACKAGE_FILENAME));

    var nextLoc = _path().default.dirname(dirname);

    if (dirname === nextLoc) {
      isPackage = false;
      break;
    }

    dirname = nextLoc;
  }

  return {
    filepath: filepath,
    directories: directories,
    pkg: pkg,
    isPackage: isPackage
  };
}

var readConfigPackage = (0, _utils.makeStaticFileCache)(function (filepath, content) {
  var options;

  try {
    options = JSON.parse(content);
  } catch (err) {
    err.message = filepath + ": Error while parsing JSON - " + err.message;
    throw err;
  }

  if (typeof options !== "object") {
    throw new Error(filepath + ": Config returned typeof " + typeof options);
  }

  if (Array.isArray(options)) {
    throw new Error(filepath + ": Expected config object but found array");
  }

  return {
    filepath: filepath,
    dirname: _path().default.dirname(filepath),
    options: options
  };
});