const require_chunk = require('./chunk-CUT6urMc.cjs');
const require_workspace = require('./workspace-4SP3Gx4Y.cjs');
const node_fs = require_chunk.__toESM(require("node:fs"));
const node_path = require_chunk.__toESM(require("node:path"));

//#region src/config.ts
/**
* Define GKM configuration with full TypeScript support.
* This is an identity function that provides type safety and autocomplete.
*
* @example
* ```ts
* // gkm.config.ts
* import { defineConfig } from '@geekmidas/cli/config';
*
* export default defineConfig({
*   routes: './src/endpoints/**\/*.ts',
*   envParser: './src/config/env',
*   logger: './src/config/logger',
*   telescope: true,
* });
* ```
*/
function defineConfig(config) {
	return config;
}
/**
* Parse a module config string into path and import pattern.
*
* @param configString - Config string in format "./path/to/module" or "./path/to/module#exportName"
* @param defaultAlias - The default alias name to use if no export name specified
* @returns Object with path and import pattern
*
* @example
* parseModuleConfig('./src/config/env', 'envParser')
* // { path: './src/config/env', importPattern: 'envParser' }
*
* parseModuleConfig('./src/config/env#envParser', 'envParser')
* // { path: './src/config/env', importPattern: '{ envParser }' }
*
* parseModuleConfig('./src/config/env#myEnv', 'envParser')
* // { path: './src/config/env', importPattern: '{ myEnv as envParser }' }
*/
function parseModuleConfig(configString, defaultAlias) {
	const parts = configString.split("#");
	const path = parts[0] ?? configString;
	const exportName = parts[1];
	const importPattern = !exportName ? defaultAlias : exportName === defaultAlias ? `{ ${defaultAlias} }` : `{ ${exportName} as ${defaultAlias} }`;
	return {
		path,
		importPattern
	};
}
/**
* Find and return the path to the config file.
*
* Resolution order:
* 1. GKM_CONFIG_PATH env var (set by workspace dev command)
* 2. Walk up directory tree from cwd
*/
function findConfigPath(cwd) {
	const files = [
		"gkm.config.json",
		"gkm.config.ts",
		"gkm.config.js"
	];
	const envConfigPath = process.env.GKM_CONFIG_PATH;
	if (envConfigPath && (0, node_fs.existsSync)(envConfigPath)) return {
		configPath: envConfigPath,
		workspaceRoot: (0, node_path.dirname)(envConfigPath)
	};
	let currentDir = cwd;
	const { root } = (0, node_path.parse)(currentDir);
	while (currentDir !== root) {
		for (const file of files) {
			const configPath = (0, node_path.join)(currentDir, file);
			if ((0, node_fs.existsSync)(configPath)) return {
				configPath,
				workspaceRoot: currentDir
			};
		}
		currentDir = (0, node_path.dirname)(currentDir);
	}
	throw new Error("Configuration file not found. Please create gkm.config.json, gkm.config.ts, or gkm.config.js in the project root.");
}
/**
* Get app name from package.json in the given directory.
* Handles scoped packages by extracting the name after the scope.
*
* @example
* getAppNameFromCwd('/path/to/apps/api')
* // package.json: { "name": "@myorg/api" }
* // Returns: 'api'
*/
function getAppNameFromCwd(cwd = process.cwd()) {
	const packageJsonPath = (0, node_path.join)(cwd, "package.json");
	if (!(0, node_fs.existsSync)(packageJsonPath)) return null;
	try {
		const packageJson = JSON.parse((0, node_fs.readFileSync)(packageJsonPath, "utf-8"));
		const name = packageJson.name;
		if (!name) return null;
		if (name.startsWith("@") && name.includes("/")) return name.split("/")[1] ?? null;
		return name;
	} catch {
		return null;
	}
}
/**
* Load raw configuration from file.
*/
async function loadRawConfig(cwd) {
	const { configPath, workspaceRoot } = findConfigPath(cwd);
	try {
		const config = await import(configPath);
		return {
			config: config.default,
			workspaceRoot
		};
	} catch (error) {
		throw new Error(`Failed to load config: ${error.message}`);
	}
}
/**
* Load configuration file (single-app format).
* For backwards compatibility with existing code.
*
* @deprecated Use loadWorkspaceConfig for new code
*/
async function loadConfig(cwd = process.cwd()) {
	const { config } = await loadRawConfig(cwd);
	if (require_workspace.isWorkspaceConfig(config)) throw new Error("Workspace configuration detected. Use loadWorkspaceConfig() instead.");
	return config;
}
/**
* Load configuration file and process it as a workspace.
* Works with both single-app and workspace configurations.
*
* Single-app configs are automatically wrapped as a workspace with one app.
*
* @example
* ```ts
* const { type, workspace } = await loadWorkspaceConfig();
*
* if (type === 'workspace') {
*   console.log('Multi-app workspace:', workspace.apps);
* } else {
*   console.log('Single app wrapped as workspace');
* }
* ```
*/
async function loadWorkspaceConfig(cwd = process.cwd()) {
	const { config, workspaceRoot } = await loadRawConfig(cwd);
	return require_workspace.processConfig(config, workspaceRoot);
}
/**
* Load app-specific configuration from workspace.
* Uses the app name from package.json to find the correct app config.
*
* @example
* ```ts
* // From apps/api directory with package.json: { "name": "@myorg/api" }
* const { app, workspace, workspaceRoot } = await loadAppConfig();
* console.log(app.routes); // './src/endpoints/**\/*.ts'
* ```
*/
async function loadAppConfig(cwd = process.cwd()) {
	const appName = getAppNameFromCwd(cwd);
	if (!appName) throw new Error("Could not determine app name. Ensure package.json exists with a \"name\" field.");
	const { config, workspaceRoot } = await loadRawConfig(cwd);
	const loadedConfig = require_workspace.processConfig(config, workspaceRoot);
	const app = loadedConfig.workspace.apps[appName];
	if (!app) {
		const availableApps = Object.keys(loadedConfig.workspace.apps).join(", ");
		throw new Error(`App "${appName}" not found in workspace config. Available apps: ${availableApps}. Ensure the package.json name matches the app key in gkm.config.ts.`);
	}
	const gkmConfig = require_workspace.getAppGkmConfig(loadedConfig.workspace, appName);
	if (!gkmConfig) throw new Error(`App "${appName}" is not a backend app and cannot be run with gkm dev.`);
	return {
		appName,
		app,
		gkmConfig,
		workspace: loadedConfig.workspace,
		workspaceRoot,
		appRoot: (0, node_path.join)(workspaceRoot, app.path)
	};
}
/**
* Load workspace info for any app (frontend or backend).
* Unlike loadAppConfig, this does NOT require the app to have a gkm config
* (routes, entry, etc.), making it suitable for gkm exec/test from frontend apps.
*/
async function loadWorkspaceAppInfo(cwd = process.cwd()) {
	const appName = getAppNameFromCwd(cwd);
	if (!appName) throw new Error("Could not determine app name. Ensure package.json exists with a \"name\" field.");
	const { config, workspaceRoot } = await loadRawConfig(cwd);
	const loadedConfig = require_workspace.processConfig(config, workspaceRoot);
	const app = loadedConfig.workspace.apps[appName];
	if (!app) {
		const availableApps = Object.keys(loadedConfig.workspace.apps).join(", ");
		throw new Error(`App "${appName}" not found in workspace config. Available apps: ${availableApps}. Ensure the package.json name matches the app key in gkm.config.ts.`);
	}
	return {
		appName,
		app,
		workspace: loadedConfig.workspace,
		workspaceRoot
	};
}

//#endregion
Object.defineProperty(exports, 'defineConfig', {
  enumerable: true,
  get: function () {
    return defineConfig;
  }
});
Object.defineProperty(exports, 'getAppNameFromCwd', {
  enumerable: true,
  get: function () {
    return getAppNameFromCwd;
  }
});
Object.defineProperty(exports, 'loadAppConfig', {
  enumerable: true,
  get: function () {
    return loadAppConfig;
  }
});
Object.defineProperty(exports, 'loadConfig', {
  enumerable: true,
  get: function () {
    return loadConfig;
  }
});
Object.defineProperty(exports, 'loadWorkspaceAppInfo', {
  enumerable: true,
  get: function () {
    return loadWorkspaceAppInfo;
  }
});
Object.defineProperty(exports, 'loadWorkspaceConfig', {
  enumerable: true,
  get: function () {
    return loadWorkspaceConfig;
  }
});
Object.defineProperty(exports, 'parseModuleConfig', {
  enumerable: true,
  get: function () {
    return parseModuleConfig;
  }
});
//# sourceMappingURL=config-D3ORuiUs.cjs.map