"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.InvalidConfigEnvTemplateError = exports.EmptyConfigEnvTemplateValueError = exports.MissingConfigEnvTemplateValueError = void 0;
exports.resolveConfigEnvTemplate = resolveConfigEnvTemplate;
exports.collectConfigEnvTemplateNames = collectConfigEnvTemplateNames;
class MissingConfigEnvTemplateValueError extends Error {
    envName;
    constructor(envName) {
        super(`Environment variable is not set: ${envName}`);
        this.name = "MissingConfigEnvTemplateValueError";
        this.envName = envName;
    }
}
exports.MissingConfigEnvTemplateValueError = MissingConfigEnvTemplateValueError;
class EmptyConfigEnvTemplateValueError extends Error {
    envName;
    constructor(envName) {
        super(`Environment variable is empty: ${envName}`);
        this.name = "EmptyConfigEnvTemplateValueError";
        this.envName = envName;
    }
}
exports.EmptyConfigEnvTemplateValueError = EmptyConfigEnvTemplateValueError;
class InvalidConfigEnvTemplateError extends Error {
    expression;
    constructor(expression) {
        super(`Invalid environment variable template: ${expression}`);
        this.name = "InvalidConfigEnvTemplateError";
        this.expression = expression;
    }
}
exports.InvalidConfigEnvTemplateError = InvalidConfigEnvTemplateError;
const CONFIG_ENV_TEMPLATE_EXPRESSION_PATTERN = /\$\{([^}]*)\}/gu;
const CONFIG_ENV_TEMPLATE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/u;
function resolveConfigEnvTemplate(value, env) {
    validateConfigEnvTemplate(value);
    return value.replace(CONFIG_ENV_TEMPLATE_EXPRESSION_PATTERN, (match, key) => {
        if (!CONFIG_ENV_TEMPLATE_NAME_PATTERN.test(key)) {
            throw new InvalidConfigEnvTemplateError(match);
        }
        const replacement = env[key];
        if (replacement === undefined) {
            throw new MissingConfigEnvTemplateValueError(key);
        }
        if (replacement.length === 0) {
            throw new EmptyConfigEnvTemplateValueError(key);
        }
        return replacement;
    });
}
function collectConfigEnvTemplateNames(value) {
    validateConfigEnvTemplate(value);
    const names = new Set();
    for (const match of value.matchAll(CONFIG_ENV_TEMPLATE_EXPRESSION_PATTERN)) {
        const expression = match[0] ?? "";
        const key = match[1] ?? "";
        if (!CONFIG_ENV_TEMPLATE_NAME_PATTERN.test(key)) {
            throw new InvalidConfigEnvTemplateError(expression);
        }
        names.add(key);
    }
    return [...names];
}
function validateConfigEnvTemplate(value) {
    const unresolvedRemainder = value.replace(CONFIG_ENV_TEMPLATE_EXPRESSION_PATTERN, "");
    if (unresolvedRemainder.includes("${")) {
        throw new InvalidConfigEnvTemplateError("${");
    }
}
