import { n as __ΩSecretsInterface, t as __ΩEnvInterface } from "./runtime-C5ukCv3P.mjs";
import { a as __ΩEnvType, i as __ΩEnvPluginUserConfig, n as __ΩEnvPluginOptions, r as __ΩEnvPluginResolvedConfig, t as __ΩEnvPluginContext } from "./plugin-eBjQJP6x.mjs";
import "./types-DyPQho_C.mjs";
import { t as joinPaths } from "./join-paths-BMg51Ddi.mjs";
import { _ as mergeEnvReflections, a as readEnvReflection, b as reflectSecrets, c as resolveRuntimeTypeFile, d as writeEnvTypeReflection, f as BaseEnv, g as createSecretsReflection, h as createEnvReflection, i as getSecretsDefaultTypeDefinition, l as writeEnvReflection, m as __ΩCreateEnvReflectionOptions, n as getEnvReflectionsPath, o as readEnvTypeReflection, p as BaseSecrets, r as getEnvTypeReflectionsPath, s as readSecretsReflection, t as getEnvDefaultTypeDefinition, u as writeEnvReflectionSync, v as mergeSecretsReflections, x as isParentPath, y as reflectEnv } from "./persistence-BsBxs9wt.mjs";
import { t as createTemplateReflection } from "./template-helpers-CCEjhw1B.mjs";
import { n as removeEnvPrefix, t as formatEnvField } from "./source-file-env-Tj-6qobx.mjs";
import { t as defu } from "./defu-DV5Grr85.mjs";
import { n as loadEnvFromContext, t as loadEnv } from "./load-Dr5ybfL7.mjs";
import "./confbox.DA7CpUDY-DShUZ_rW.mjs";
import "./confbox.DnMsyigM-V6Wj0LPC.mjs";
import { t as createReflectionResource } from "./create-reflection-resource-B3friIs9.mjs";
import "./helpers-45e1bvAO.mjs";
import { t as getDocsOutputPath } from "./docs-helper-2fe7M3Th.mjs";
import { t as env } from "./automd-generator-DoKLIMuw.mjs";
import { t as EnvDocsFile } from "./docs-DbRoWmL_.mjs";
import { n as EnvTypeDefinition, t as EnvBuiltin } from "./env-D9oCn-AS.mjs";
import "./components-DDFmImcI.mjs";
import { t as envBabelPlugin } from "./plugin-Vyvy9w9Z.mjs";
import "./babel-DgietUY3.mjs";
import { ReflectionClass, ReflectionKind } from "@powerlines/deepkit/vendor/type";
import { ENV_PREFIXES } from "@stryke/env/types";
import { createComponent } from "@alloy-js/core/jsx-runtime";
import alloy from "@powerlines/plugin-alloy";
import automd from "@powerlines/plugin-automd";
import babel from "@powerlines/plugin-babel";
import { existsSync } from "@stryke/fs/exists";
import { constantCase } from "@stryke/string-format/constant-case";

//#region ../../node_modules/.pnpm/@stryke+convert@0.6.37/node_modules/@stryke/convert/dist/type-checks/src/get-object-tag.mjs
/**
* Gets the `toStringTag` of `obj`.
*
* @param value - The obj to query.
* @returns Returns the `toStringTag`.
*/
const getObjectTag = (value) => {
	if (value == null) return value === void 0 ? "[object Undefined]" : "[object Null]";
	return Object.prototype.toString.call(value);
};

//#endregion
//#region ../../node_modules/.pnpm/@stryke+convert@0.6.37/node_modules/@stryke/convert/dist/type-checks/src/is-plain-object.mjs
/**
* Checks if `value` is object-like. A value is object-like if it's not `null`
* and has a `typeof` result of "object".
*
* @example
* ```typescript
* isObjectLike({})
* // => true
*
* isObjectLike([1, 2, 3])
* // => true
*
* isObjectLike(Function)
* // => false
*
* isObjectLike(null)
* // => false
* ```
*
* @param value - The value to check.
* @returns Returns `true` if `value` is object-like, else `false`.
*/
const isObjectLike = (obj) => {
	return typeof obj === "object" && obj !== null;
};
/**
* Checks if `obj` is a plain object, that is, an object created by the `Object` constructor or one with a `[[Prototype]]` of `null`.
*
* @example
* ```typescript
* function Foo() {
*   this.a = 1
* }
*
* isPlainObject(new Foo)
* // => false
*
* isPlainObject([1, 2, 3])
* // => false
*
* isPlainObject({ 'x': 0, 'y': 0 })
* // => true
*
* isPlainObject(Object.create(null))
* // => true
* ```
*
* @param obj - The value to check.
* @returns Returns `true` if `obj` is a plain object, else `false`.
*/
const isPlainObject = (obj) => {
	if (!isObjectLike(obj) || getObjectTag(obj) !== "[object Object]") return false;
	if (Object.getPrototypeOf(obj) === null) return true;
	let proto = obj;
	while (Object.getPrototypeOf(proto) !== null) proto = Object.getPrototypeOf(proto);
	return Object.getPrototypeOf(obj) === proto;
};

//#endregion
//#region ../../node_modules/.pnpm/@stryke+convert@0.6.37/node_modules/@stryke/convert/dist/type-checks/src/is-object.mjs
/**
* Check if the provided value's type is `Object`
*
* @param value - The value to type check
* @returns An indicator specifying if the value provided is of type `Object`
*/
const isObject = (value) => {
	try {
		return typeof value === "object" || Boolean(value) && value?.constructor === Object || isPlainObject(value);
	} catch {
		return false;
	}
};

//#endregion
//#region ../../node_modules/.pnpm/@stryke+convert@0.6.37/node_modules/@stryke/convert/dist/type-checks/src/is-string.mjs
const isString = (value) => {
	try {
		return typeof value === "string";
	} catch {
		return false;
	}
};

//#endregion
//#region ../../node_modules/.pnpm/@stryke+convert@0.6.37/node_modules/@stryke/convert/dist/type-checks/src/is-buffer.mjs
const isBufferExists = typeof Buffer !== "undefined";
isBufferExists && Buffer.isBuffer.bind(Buffer);

//#endregion
//#region ../../node_modules/.pnpm/@stryke+convert@0.6.37/node_modules/@stryke/convert/dist/type-checks/src/type-detect.mjs
((Obj) => {
	if (typeof globalThis === "object") return globalThis;
	Object.defineProperty(Obj, "typeDetectGlobalObject", {
		get() {
			return this;
		},
		configurable: true
	});
	return globalThis;
})(Object.prototype);

//#endregion
//#region ../../node_modules/.pnpm/@stryke+convert@0.6.37/node_modules/@stryke/convert/dist/parse-type-definition.mjs
/**
* Parse a type definition parameter into a {@link TypeDefinition} object
*
* @param param - The parameter to parse
* @returns The parsed type definition
*/
const parseTypeDefinition = (param) => {
	if (isString(param)) {
		if (param.includes(":")) {
			const params = param.split(":");
			if (params.length > 1 && params[0]) return {
				file: params[0],
				name: params[1]
			};
		}
		if (param.includes("#")) {
			const params = param.split("#");
			if (params.length > 1 && params[0]) return {
				file: params[0],
				name: params[1]
			};
		}
		return { file: param };
	}
	if (isObject(param)) return {
		file: param.file,
		name: param.name
	};
};

//#endregion
//#region ../../node_modules/.pnpm/@stryke+convert@0.6.37/node_modules/@stryke/convert/dist/to-array.mjs
/**
* Convert `Arrayable<T>` to `Array<T>`
*
* @param array - The `Arrayable<T>` to convert
* @returns An `Array<T>` containing the elements of the input
*/
function toArray(array) {
	array = array ?? [];
	return Array.isArray(array) ? array : [array];
}

//#endregion
//#region src/index.tsx
/**
* A Powerlines plugin to inject environment variables into the source code.
*/
const plugin = (options = {}) => {
	return [
		alloy(options.alloy),
		babel(options.babel),
		{
			name: "env",
			async config() {
				this.debug("Providing default configuration for the Powerlines `env` build plugin.");
				const config = {
					env: defu(options, {
						types: {},
						prefix: []
					}),
					transform: { babel: { plugins: [envBabelPlugin] } }
				};
				if (config.env.types) config.env.types = parseTypeDefinition(config.env.types);
				else {
					this.warn("The `env.types` configuration parameter was not provided. Please ensure this is expected.");
					const envDefaultTypeDefinition = await getEnvDefaultTypeDefinition(this);
					config.env.types = parseTypeDefinition(`${envDefaultTypeDefinition.file}#${envDefaultTypeDefinition.name}`);
				}
				if (config.env.secrets) config.env.secrets = parseTypeDefinition(config.env.secrets);
				else {
					const secretsDefaultTypeDefinition = await getSecretsDefaultTypeDefinition(this);
					config.env.secrets = parseTypeDefinition(`${secretsDefaultTypeDefinition.file}#${secretsDefaultTypeDefinition.name}`);
				}
				config.env.prefix = toArray(config.env.prefix ?? []).reduce((ret, prefix) => {
					const formattedPrefix = constantCase(prefix);
					if (!ret.includes(formattedPrefix)) ret.push(formattedPrefix);
					return ret;
				}, [
					...ENV_PREFIXES,
					"POWERLINES_",
					this.config.framework && this.config.framework !== "powerlines" && `${constantCase(this.config.framework)}_`
				].filter(Boolean));
				config.env.prefix = toArray(config.env.prefix).reduce((ret, prefix) => {
					if (!ret.includes(prefix.replace(/_$/g, ""))) ret.push(prefix.replace(/_$/g, ""));
					return ret;
				}, []);
				return config;
			},
			async configResolved() {
				this.debug(`Environment plugin configuration has been resolved for the Powerlines project.`);
				this.env = defu({ parsed: await loadEnv(this, this.config.env) }, this.env ?? {}, {
					types: { env: {} },
					used: {
						env: {},
						secrets: {}
					},
					parsed: {},
					injected: {}
				});
				if (this.config.command !== "prepare" && !this.config.skipCache && this.persistedMeta?.checksum === this.meta.checksum && existsSync(getEnvTypeReflectionsPath(this, "env"))) {
					this.debug(`Skipping reflection initialization as the meta checksum has not changed.`);
					this.env.types.env = await readEnvTypeReflection(this, "env");
					if (existsSync(getEnvReflectionsPath(this, "env"))) this.env.used.env = await readEnvReflection(this);
					if (existsSync(getEnvTypeReflectionsPath(this, "secrets"))) this.env.types.secrets = await readEnvTypeReflection(this, "secrets");
					if (existsSync(getEnvReflectionsPath(this, "secrets"))) this.env.used.secrets = await readSecretsReflection(this);
				} else {
					this.debug(`Starting environment configuration reflection initialization.`);
					this.env.types.env = await reflectEnv(this, this.config.env.types?.file ? isParentPath(this.config.env.types?.file, this.workspaceConfig.workspaceRoot) ? this.config.env.types?.file : joinPaths(this.config.projectRoot, this.config.env.types?.file) : void 0, this.config.env.types?.name);
					if (!this.env.types.env) throw new Error("Failed to find the environment configuration type reflection in the context.");
					await writeEnvTypeReflection(this, this.env.types.env, "env");
					this.env.types.secrets = await reflectSecrets(this, this.config.env.secrets?.file ? isParentPath(this.config.env.secrets?.file, this.workspaceConfig.workspaceRoot) ? this.config.env.secrets?.file : joinPaths(this.config.projectRoot, this.config.env.secrets?.file) : void 0, this.config.env.secrets?.name);
					if (!this.env.types.secrets) throw new Error("Failed to find the secrets configuration type reflection in the context.");
					await writeEnvTypeReflection(this, this.env.types.secrets, "secrets");
					this.debug(`Resolved ${this.env.types.env.getProperties().length ?? 0} environment configuration parameters and ${this.env.types.secrets?.getProperties().length ?? 0} secret configuration parameters`);
					const envWithAlias = this.env.types.env.getProperties().filter((prop) => prop.getAlias().length > 0);
					Object.entries(await loadEnv(this, this.config.env)).forEach(([key, value]) => {
						const unprefixedKey = this.config.env.prefix.reduce((ret, prefix) => {
							if (key.replace(/_$/g, "").startsWith(prefix)) return key.replace(/_$/g, "").slice(prefix.length);
							return ret;
						}, key);
						const aliasKey = envWithAlias.find((prop) => prop?.getAlias().reverse().includes(unprefixedKey));
						if (this.env.types.env?.hasProperty(unprefixedKey) || aliasKey) this.env.types.env.getProperty(unprefixedKey).setDefaultValue(value);
					});
					this.env.used.env = new ReflectionClass({
						kind: ReflectionKind.objectLiteral,
						typeName: "Env",
						description: `An object containing the environment configuration parameters used by the ${this.config.name ? `${this.config.name} application` : "application"}.`,
						types: []
					}, this.env.types.env);
					await writeEnvReflection(this, this.env.used.env, "env");
					if (this.env.types.secrets) {
						await writeEnvTypeReflection(this, this.env.types.secrets, "secrets");
						this.env.used.secrets = new ReflectionClass({
							kind: ReflectionKind.objectLiteral,
							typeName: "Secrets",
							description: `An object containing the secret configuration parameters used by the ${this.config.name ? `${this.config.name} application` : "application"}.`,
							types: []
						}, this.env.types.secrets);
						await writeEnvReflection(this, this.env.used.secrets, "secrets");
					}
				}
			},
			async prepare() {
				const _self$ = this;
				this.debug(`Preparing the Environment runtime artifacts for the Powerlines project.`);
				return this.render(createComponent(EnvBuiltin, { get defaultConfig() {
					return _self$.config.env.defaultConfig;
				} }));
			},
			transform: {
				order: "post",
				async handler() {
					if (this.env.used.env.getProperties().length > 0) {
						this.trace(`Persisting used environment configuration reflections to ${getEnvReflectionsPath(this, "env")}.`);
						await writeEnvReflection(this, this.env.used.env, "env");
					}
					if (this.env.used.secrets.getProperties().length > 0) {
						this.trace(`Persisting used secret configuration reflections to ${getEnvReflectionsPath(this, "secrets")}.`);
						await writeEnvReflection(this, this.env.used.secrets, "secrets");
					}
				}
			},
			async docs() {
				this.debug(`Documenting environment variables configuration values in "${joinPaths(getDocsOutputPath(this), "env.md")}"`);
				return this.render(createComponent(EnvDocsFile, { levelOffset: 0 }));
			},
			async buildEnd() {
				const reflectionPath = getEnvReflectionsPath(this, "env");
				this.debug(`Writing env reflection types to ${reflectionPath}.`);
				await writeEnvReflection(this, this.env.used.env, "env");
			}
		},
		{
			name: "env:automd-generator",
			config() {
				return { automd: defu(options.automd ?? {}, { generators: { "env": env(this) } }) };
			}
		},
		{
			name: "env:vite",
			vite: { configResolved() {
				return { envPrefix: this.config?.env?.prefix };
			} }
		},
		automd(options.automd)
	];
};
var src_default = plugin;

//#endregion
export { BaseEnv, BaseSecrets, EnvBuiltin, EnvDocsFile, EnvTypeDefinition, __ΩCreateEnvReflectionOptions, __ΩEnvInterface, __ΩEnvPluginContext, __ΩEnvPluginOptions, __ΩEnvPluginResolvedConfig, __ΩEnvPluginUserConfig, __ΩEnvType, __ΩSecretsInterface, createEnvReflection, createReflectionResource, createSecretsReflection, createTemplateReflection, src_default as default, envBabelPlugin, formatEnvField, getEnvDefaultTypeDefinition, getEnvReflectionsPath, getEnvTypeReflectionsPath, getSecretsDefaultTypeDefinition, loadEnv, loadEnvFromContext, mergeEnvReflections, mergeSecretsReflections, plugin, readEnvReflection, readEnvTypeReflection, readSecretsReflection, reflectEnv, reflectSecrets, removeEnvPrefix, resolveRuntimeTypeFile, writeEnvReflection, writeEnvReflectionSync, writeEnvTypeReflection };
//# sourceMappingURL=index.mjs.map