"use strict";

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

var _has = _interopRequireDefault(require("lodash/has"));

var _toposort = _interopRequireDefault(require("toposort"));

var _propertyExpr = require("property-expr");

var _Reference = _interopRequireDefault(require("../Reference"));

var _isSchema = _interopRequireDefault(require("./isSchema"));

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

// @ts-expect-error
function sortFields(fields, excludedEdges = []) {
  let edges = [];
  let nodes = new Set();
  let excludes = new Set(excludedEdges.map(([a, b]) => `${a}-${b}`));

  function addNode(depPath, key) {
    let node = (0, _propertyExpr.split)(depPath)[0];
    nodes.add(node);
    if (!excludes.has(`${key}-${node}`)) edges.push([key, node]);
  }

  for (const key in fields) if ((0, _has.default)(fields, key)) {
    let value = fields[key];
    nodes.add(key);
    if (_Reference.default.isRef(value) && value.isSibling) addNode(value.path, key);else if ((0, _isSchema.default)(value) && 'deps' in value) value.deps.forEach(path => addNode(path, key));
  }

  return _toposort.default.array(Array.from(nodes), edges).reverse();
}