import { REGEX, isDefined } from "@scalar/oas-utils/helpers";
//#region src/libs/string-template.ts
/**
* Get the nested value from a context object
*
*/
function getDotPathValue(path, context) {
	const result = path.split(".").reduce((nested, currentKey) => nested?.[currentKey], context);
	return typeof result === "string" ? result : JSON.stringify(result);
}
/**
* Replace all variables with values from a context object
*
* - {{ double curly }}
* - { single curly }
* - :colon
*
* @deprecated Use replaceVariables from @scalar/helpers/regex/replace-variables instead
*/
function replaceTemplateVariables(templateString, context) {
	let substitutedString = templateString;
	const usedKeys = /* @__PURE__ */ new Set();
	substitutedString = substitutedString.replace(REGEX.VARIABLES, (_, variable) => {
		const key = variable.trim();
		usedKeys.add(key);
		const value = getDotPathValue(key, context);
		return isDefined(value) && value !== "" ? value : `{{${key}}}`;
	});
	substitutedString = substitutedString.replace(REGEX.PATH, (_, variable) => {
		const key = variable.trim();
		if (usedKeys.has(key)) return `{${key}}`;
		const value = getDotPathValue(key, context);
		return isDefined(value) && value !== "" ? value : `{${key}}`;
	});
	substitutedString = substitutedString.replace(/:\b[\w.]+\b/g, (match) => {
		const key = match.slice(1);
		if (usedKeys.has(key)) return match;
		const value = getDotPathValue(key, context);
		return isDefined(value) && value !== "" ? value : match;
	});
	return substitutedString;
}
/**
* Return a list of key/value pairs for the environment
* Nested values will be dot-path referenced
*/
function flattenEnvVars(environment) {
	/** Recursively get all nested paths string */
	function getNestedKeyValues(item, prefix) {
		const keys = Object.keys(item);
		const values = [];
		keys.forEach((k) => {
			const prefixedKey = prefix ? `${prefix}.${k}` : k;
			if (typeof item[k] === "object") values.push(...getNestedKeyValues(item[k], prefixedKey));
			else values.push([prefixedKey, String(item[k])]);
		});
		return values;
	}
	return getNestedKeyValues(environment);
}
//#endregion
export { flattenEnvVars, replaceTemplateVariables };

//# sourceMappingURL=string-template.js.map