"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
Object.defineProperty(exports, "getEnabledFeatureFlagKeys", {
  enumerable: true,
  get: function get() {
    return _getEnabledFeatureFlagKeys.getEnabledFeatureFlagKeys;
  }
});
exports.normalizeFeatureFlags = normalizeFeatureFlags;
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var _typeof2 = _interopRequireDefault(require("@babel/runtime/helpers/typeof"));
var _camelCase = _interopRequireDefault(require("lodash/camelCase"));
var _kebabCase = _interopRequireDefault(require("lodash/kebabCase"));
var _getEnabledFeatureFlagKeys = require("./getEnabledFeatureFlagKeys");
var EMPTY = {};
function isObjectFlagKey(key,
// Ignored via go/ees005
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value, objectFlagKeys) {
  return Boolean(typeof value === 'string' && (objectFlagKeys === null || objectFlagKeys === void 0 ? void 0 : objectFlagKeys.includes(key)));
}
function isValidJSONObject(value) {
  try {
    var result = JSON.parse(value);
    if ((0, _typeof2.default)(result) === 'object' && result !== null) {
      return true;
    }
    return false;
  } catch (err) {
    return false;
  }
}

/**
 * Normalise and filter a free Record<string, unknown> to match
 * the rules for feature flags in editor and renderer
 *
 * Input has to match to not be filtered output:
 * 1. cased in kebab-case (match [a-z-])
 * 2. has any value
 *
 * Output matches
 * 1. cased in camelCase (match [a-zA-Z])
 * 2. has boolean value or object {} value
 *
 * @param rawFeatureFlags
 */
function normalizeFeatureFlags(rawFeatureFlags, options) {
  if (!rawFeatureFlags) {
    return EMPTY;
  }
  return Object.entries(rawFeatureFlags).filter(function (e) {
    if (typeof e[1] === 'boolean') {
      return true;
    }
    if (isObjectFlagKey((0, _camelCase.default)(e[0]), e[1], options === null || options === void 0 ? void 0 : options.objectFlagKeys) && isValidJSONObject(e[1])) {
      return true;
    }
    return false;
  }).filter(function (_ref) {
    var _ref2 = (0, _slicedToArray2.default)(_ref, 1),
      key = _ref2[0];
    return (0, _kebabCase.default)(key) === key;
  }).map(function (_ref3) {
    var _ref4 = (0, _slicedToArray2.default)(_ref3, 2),
      key = _ref4[0],
      value = _ref4[1];
    return [(0, _camelCase.default)(key), value];
  }).reduce(function (flags, _ref5) {
    var _ref6 = (0, _slicedToArray2.default)(_ref5, 2),
      key = _ref6[0],
      value = _ref6[1];
    if (isObjectFlagKey(key, value, options === null || options === void 0 ? void 0 : options.objectFlagKeys)) {
      flags[key] = JSON.parse(value);
    }
    if (typeof value === 'boolean') {
      flags[key] = value;
    }
    return flags;
  }, {});
}
// eslint-disable-next-line @atlaskit/editor/no-re-export