"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.getConfigFromFiles = void 0;
var _fs = require("fs");
var _jsYaml = require("js-yaml");
var _saferLodashSet = require("@kbn/safer-lodash-set");
var _lodash = require("lodash");
var _std = require("@kbn/std");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0 and the Server Side Public License, v 1; you may not use this file except
 * in compliance with, at your election, the Elastic License 2.0 or the Server
 * Side Public License, v 1.
 */

const readYaml = path => (0, _jsYaml.safeLoad)((0, _fs.readFileSync)(path, 'utf8'));
function replaceEnvVarRefs(val) {
  return val.replace(/\$\{(\w+)\}/g, (match, envVarName) => {
    const envVarValue = process.env[envVarName];
    if (envVarValue !== undefined) {
      return envVarValue;
    }
    throw new Error(`Unknown environment variable referenced in config : ${envVarName}`);
  });
}
function merge(target, value, key) {
  if ((0, _lodash.isPlainObject)(value) && Object.keys(value).length > 0) {
    for (const [subKey, subVal] of Object.entries(value)) {
      merge(target, subVal, key ? `${key}.${subKey}` : subKey);
    }
  } else if (key !== undefined) {
    (0, _saferLodashSet.set)(target, key, recursiveReplaceEnvVar(value));
  }
  return target;
}
function recursiveReplaceEnvVar(value) {
  if ((0, _lodash.isPlainObject)(value) || Array.isArray(value)) {
    for (const [subKey, subVal] of Object.entries(value)) {
      (0, _saferLodashSet.set)(value, subKey, recursiveReplaceEnvVar(subVal));
    }
  }
  if (typeof value === 'string') {
    return replaceEnvVarRefs(value);
  }
  return value;
}

/** @internal */
const getConfigFromFiles = configFiles => {
  let mergedYaml = {};
  for (const configFile of configFiles) {
    const yaml = readYaml(configFile);
    if (yaml !== null) {
      mergedYaml = merge(mergedYaml, yaml);
    }
  }
  return (0, _std.ensureDeepObject)(mergedYaml);
};
exports.getConfigFromFiles = getConfigFromFiles;