import { n as logLevelPolicyFactory } from "./LogLevelPolicyFactory-DCUzIN6G.js";
import { o as BootTimer, t as ServerLoggerFactory } from "./ServerLoggerFactory-Ckk52S3w.js";
import { WorkflowEdgePortValidator } from "@codemation/core";
import { access, readdir, stat } from "node:fs/promises";
import path from "node:path";
import { pathToFileURL } from "node:url";

//#region src/presentation/config/CodemationConfigNormalizer.ts
var CodemationConfigNormalizer = class {
	normalize(config) {
		const auth = config.app?.auth ?? config.auth;
		this.assertAuthConfig(auth);
		this.assertManagedModeConstraints(config, auth);
		const collected = this.collectRegistration(config);
		const normalizedRuntime = this.normalizeRuntimeConfig(config);
		const normalizedWorkflowDiscoveryDirectories = [...config.workflowDiscovery?.directories ?? [], ...collected.workflowDirectories];
		return {
			...config,
			auth,
			containerRegistrations: collected.containerRegistrations,
			credentialTypes: [...config.credentialTypes ?? [], ...collected.credentialTypes],
			collections: [...this.unwrapCollections(config.collections), ...collected.collections],
			log: config.app?.log ?? config.log,
			runtime: normalizedRuntime,
			whitelabel: config.app?.whitelabel ?? config.whitelabel,
			workflowDiscovery: normalizedWorkflowDiscoveryDirectories.length > 0 ? { directories: normalizedWorkflowDiscoveryDirectories } : config.workflowDiscovery,
			workflows: this.mergeWorkflows(config.workflows ?? [], collected.workflows)
		};
	}
	/**
	* Enforces managed-mode invariants beyond what `assertAuthConfig` covers:
	* managed-mode workspaces are always Postgres and always require at least one workflow source.
	*/
	assertManagedModeConstraints(config, auth) {
		if (auth?.kind !== "managed") return;
		const hasWorkflows = (config.workflows?.length ?? 0) > 0;
		const hasWorkflowDiscovery = (config.workflowDiscovery?.directories?.length ?? 0) > 0;
		if (!hasWorkflows && !hasWorkflowDiscovery) throw new Error("Managed-mode workspaces require at least one workflow source. Provide \"workflows\" or \"workflowsDir\" (which maps to workflowDiscovery.directories) in defineCodemationApp.");
	}
	collectRegistration(config) {
		if (!config.register) return {
			containerRegistrations: [],
			credentialTypes: [],
			collections: [],
			workflows: [],
			workflowDirectories: []
		};
		const containerRegistrations = [];
		const credentialTypes = [];
		const collections = [];
		const workflows = [];
		const workflowDirectories = [];
		config.register({
			registerCredentialType(type) {
				credentialTypes.push(type);
			},
			registerCollection(definition) {
				collections.push(definition);
			},
			registerNode(token, implementation) {
				containerRegistrations.push({
					token,
					useClass: implementation ?? token
				});
			},
			registerValue(token, value) {
				containerRegistrations.push({
					token,
					useValue: value
				});
			},
			registerClass(token, implementation) {
				containerRegistrations.push({
					token,
					useClass: implementation
				});
			},
			registerFactory(token, factory) {
				containerRegistrations.push({
					token,
					useFactory: factory
				});
			},
			registerWorkflow(workflow) {
				workflows.push(workflow);
			},
			registerWorkflows(nextWorkflows) {
				workflows.push(...nextWorkflows);
			},
			discoverWorkflows(...directories) {
				workflowDirectories.push(...directories);
			}
		});
		return {
			containerRegistrations,
			credentialTypes,
			collections,
			workflows,
			workflowDirectories
		};
	}
	unwrapCollections(entries) {
		if (!entries) return [];
		return entries.map((entry) => this.isDefinedCollection(entry) ? entry.definition : entry);
	}
	isDefinedCollection(entry) {
		return "kind" in entry && entry.kind === "defined-collection";
	}
	normalizeRuntimeConfig(config) {
		if (!config.app) return config.runtime;
		return {
			...config.runtime ?? {},
			frontendPort: config.app.frontendPort ?? config.runtime?.frontendPort,
			database: this.normalizeDatabaseConfig(config),
			eventBus: this.normalizeEventBusConfig(config),
			scheduler: this.normalizeSchedulerConfig(config),
			engineExecutionLimits: config.app.engineExecutionLimits ?? config.runtime?.engineExecutionLimits
		};
	}
	normalizeDatabaseConfig(config) {
		if (!config.app) return config.runtime?.database;
		if (config.app.database) return config.app.database;
		if (!config.app.databaseUrl) return config.runtime?.database;
		return {
			...config.runtime?.database ?? {},
			url: config.app.databaseUrl
		};
	}
	normalizeSchedulerConfig(config) {
		if (!config.app?.scheduler) return config.runtime?.scheduler;
		const scheduler = config.app.scheduler;
		return {
			...config.runtime?.scheduler ?? {},
			kind: scheduler.kind === "queue" ? "bullmq" : scheduler.kind === "inline" ? "local" : config.runtime?.scheduler?.kind,
			queuePrefix: scheduler.queuePrefix ?? config.runtime?.scheduler?.queuePrefix,
			workerQueues: scheduler.workerQueues ?? config.runtime?.scheduler?.workerQueues
		};
	}
	normalizeEventBusConfig(config) {
		if (!config.app?.scheduler) return config.runtime?.eventBus;
		const scheduler = config.app.scheduler;
		const eventBusKind = scheduler.kind === "queue" ? "redis" : scheduler.kind === "inline" ? "memory" : config.runtime?.eventBus?.kind;
		return {
			...config.runtime?.eventBus ?? {},
			kind: eventBusKind,
			queuePrefix: scheduler.queuePrefix ?? config.runtime?.eventBus?.queuePrefix,
			redisUrl: scheduler.redisUrl ?? config.runtime?.eventBus?.redisUrl
		};
	}
	assertAuthConfig(authConfig) {
		if (authConfig?.kind !== "managed") return;
		if (authConfig.oauth && authConfig.oauth.length > 0) throw new Error("auth.kind \"managed\" cannot be combined with oauth providers. Remove the oauth config.");
		if (authConfig.oidc && authConfig.oidc.length > 0) throw new Error("auth.kind \"managed\" cannot be combined with oidc providers. Remove the oidc config.");
		if (authConfig.allowUnauthenticatedInDevelopment === true) throw new Error("auth.kind \"managed\" cannot be combined with allowUnauthenticatedInDevelopment. Remove that flag.");
	}
	mergeWorkflows(configuredWorkflows, registeredWorkflows) {
		if (configuredWorkflows.length === 0 && registeredWorkflows.length === 0) return;
		const workflowsById = /* @__PURE__ */ new Map();
		for (const workflow of registeredWorkflows) workflowsById.set(workflow.id, workflow);
		for (const workflow of configuredWorkflows) workflowsById.set(workflow.id, workflow);
		return [...workflowsById.values()];
	}
};

//#endregion
//#region src/presentation/server/CodemationConsumerConfigExportsResolver.ts
var CodemationConsumerConfigExportsResolver = class {
	resolveConfig(moduleExports) {
		const defaultExport = moduleExports.default;
		if (this.isConfig(defaultExport)) return defaultExport;
		const namedConfig = moduleExports.codemationHost ?? moduleExports.config;
		if (this.isConfig(namedConfig)) return namedConfig;
		return null;
	}
	isConfig(value) {
		if (!value || typeof value !== "object") return false;
		return "app" in value || "register" in value || "credentials" in value || "runtime" in value || "workflows" in value || "workflowDiscovery" in value || "plugins" in value || "whitelabel" in value || "auth" in value || "log" in value;
	}
};

//#endregion
//#region src/presentation/server/DiscoveredWorkflowsEmptyMessageFactory.ts
var DiscoveredWorkflowsEmptyMessageFactory = class {
	create(discoveredPaths) {
		const lines = discoveredPaths.map((p) => `  - ${p}`).join("\n");
		return [
			`Discovered ${discoveredPaths.length} file(s) under workflow discovery, but none export a WorkflowDefinition.`,
			lines,
			"",
			"Move shared helpers outside the discovery directories (for example src/lib), or export at least one object with id, name, nodes, and edges from a workflow module."
		].join("\n");
	}
};

//#endregion
//#region src/presentation/server/WorkflowDefinitionExportsResolver.ts
/**
* Collects exported values that match the {@link WorkflowDefinition} shape.
* Other exports (helpers, constants, type-only re-exports) are ignored.
*
* Throws if any workflow's edges reference output ports not declared by the
* source node config. All violations are reported at once so an agent can
* self-correct in a single pass.
*/
var WorkflowDefinitionExportsResolver = class {
	portValidator = new WorkflowEdgePortValidator();
	resolve(moduleExports) {
		const workflows = [];
		for (const exportedValue of Object.values(moduleExports)) if (this.isWorkflowDefinition(exportedValue)) {
			this.validatePorts(exportedValue);
			workflows.push(exportedValue);
		}
		return workflows;
	}
	validatePorts(workflow) {
		const result = this.portValidator.validate(workflow);
		if (!result.valid) {
			const lines = result.errors.map((e) => `  - ${e.message}`).join("\n");
			throw new Error(`Workflow "${workflow.id}" ("${workflow.name}") has ${result.errors.length} invalid edge port(s):\n${lines}`);
		}
	}
	isWorkflowDefinition(value) {
		if (!value || typeof value !== "object") return false;
		return "id" in value && "name" in value && "nodes" in value && "edges" in value;
	}
};

//#endregion
//#region src/presentation/server/CodemationConsumerAppResolver.ts
var CodemationConsumerAppResolver = class {
	configExportsResolver = new CodemationConsumerConfigExportsResolver();
	configNormalizer = new CodemationConfigNormalizer();
	workflowDefinitionExportsResolver = new WorkflowDefinitionExportsResolver();
	discoveredWorkflowsEmptyMessageFactory = new DiscoveredWorkflowsEmptyMessageFactory();
	resolve(args) {
		const rawConfig = this.configExportsResolver.resolveConfig(args.configModule);
		if (!rawConfig) throw new Error("Consumer app module does not export a Codemation config object.");
		const config = this.configNormalizer.normalize(rawConfig);
		const discoveredWorkflows = this.resolveDiscoveredWorkflows(args.workflowModules, args.workflowSourcePaths, args.workflowDiscoveryPathSegmentsList);
		return {
			config: {
				...config,
				workflows: this.mergeWorkflows(config.workflows ?? [], discoveredWorkflows)
			},
			workflowSources: args.workflowSourcePaths
		};
	}
	resolveDiscoveredWorkflows(workflowModules, workflowSourcePaths, workflowDiscoveryPathSegmentsList) {
		const workflowsById = /* @__PURE__ */ new Map();
		workflowModules.forEach((workflowModule, index) => {
			const pathSegments = workflowDiscoveryPathSegmentsList?.[index];
			this.workflowDefinitionExportsResolver.resolve(workflowModule).forEach((workflow) => {
				const enriched = pathSegments && pathSegments.length > 0 ? {
					...workflow,
					discoveryPathSegments: pathSegments
				} : workflow;
				workflowsById.set(workflow.id, enriched);
			});
		});
		if (workflowsById.size === 0 && workflowSourcePaths.length > 0) throw new Error(this.discoveredWorkflowsEmptyMessageFactory.create(workflowSourcePaths));
		return [...workflowsById.values()];
	}
	mergeWorkflows(configuredWorkflows, discoveredWorkflows) {
		const workflowsById = /* @__PURE__ */ new Map();
		for (const workflow of discoveredWorkflows) workflowsById.set(workflow.id, workflow);
		for (const workflow of configuredWorkflows) workflowsById.set(workflow.id, workflow);
		return [...workflowsById.values()];
	}
};

//#endregion
//#region src/presentation/server/WorkflowModulePathFinder.ts
var WorkflowModulePathFinder = class WorkflowModulePathFinder {
	static defaultWorkflowDirectories = ["src/workflows", "workflows"];
	workflowExtensions = new Set([
		".ts",
		".js",
		".mts",
		".mjs"
	]);
	async discoverModulePaths(args) {
		const directories = args.workflowDirectories ?? WorkflowModulePathFinder.defaultWorkflowDirectories;
		const workflowModulePaths = [];
		for (const directory of directories) {
			const absoluteDirectory = path.resolve(args.consumerRoot, directory);
			if (!await args.exists(absoluteDirectory)) continue;
			workflowModulePaths.push(...await this.collectWorkflowModulePaths(absoluteDirectory));
		}
		return workflowModulePaths;
	}
	async collectWorkflowModulePaths(directoryPath) {
		const entries = await readdir(directoryPath, { withFileTypes: true });
		const workflowModulePaths = [];
		for (const entry of entries) {
			const entryPath = path.resolve(directoryPath, entry.name);
			if (entry.isDirectory()) {
				workflowModulePaths.push(...await this.collectWorkflowModulePaths(entryPath));
				continue;
			}
			if (this.isWorkflowModulePath(entryPath)) workflowModulePaths.push(entryPath);
		}
		return workflowModulePaths;
	}
	isWorkflowModulePath(modulePath) {
		const extension = path.extname(modulePath);
		if (!this.workflowExtensions.has(extension)) return false;
		const basename = path.basename(modulePath);
		if (basename.endsWith(".d.ts") || basename.endsWith(".d.mts")) return false;
		const withoutExt = basename.slice(0, -extension.length);
		if (withoutExt.endsWith(".test") || withoutExt.endsWith(".spec")) return false;
		return true;
	}
};

//#endregion
//#region src/presentation/server/WorkflowDiscoveryPathSegmentsComputer.ts
var WorkflowDiscoveryPathSegmentsComputer = class {
	compute(args) {
		const normalizedConsumer = path.resolve(args.consumerRoot);
		const normalizedWorkflowPath = path.resolve(args.absoluteWorkflowModulePath);
		const directories = args.workflowDiscoveryDirectories.length > 0 ? args.workflowDiscoveryDirectories : [...WorkflowModulePathFinder.defaultWorkflowDirectories];
		let bestRoot = null;
		for (const directory of directories) {
			const absoluteDirectory = path.resolve(normalizedConsumer, directory);
			if (!(normalizedWorkflowPath === absoluteDirectory || normalizedWorkflowPath.startsWith(`${absoluteDirectory}${path.sep}`))) continue;
			if (!bestRoot || absoluteDirectory.length > bestRoot.length) bestRoot = absoluteDirectory;
		}
		if (!bestRoot) return;
		const relative = path.relative(bestRoot, normalizedWorkflowPath);
		if (relative.startsWith("..") || path.isAbsolute(relative)) return;
		if (relative.length === 0) return;
		const parts = relative.split(path.sep).filter((segment) => segment.length > 0);
		if (parts.length === 0) return;
		const lastIndex = parts.length - 1;
		const last = parts[lastIndex] ?? "";
		const ext = path.extname(last);
		parts[lastIndex] = ext ? last.slice(0, -ext.length) : last;
		return parts;
	}
};

//#endregion
//#region src/presentation/server/CodemationConsumerConfigLoader.ts
var CodemationConsumerConfigLoader = class CodemationConsumerConfigLoader {
	static importerRegistrationsByTsconfig = /* @__PURE__ */ new Map();
	static importerNamespaceVersionByTsconfig = /* @__PURE__ */ new Map();
	configExportsResolver = new CodemationConsumerConfigExportsResolver();
	configNormalizer = new CodemationConfigNormalizer();
	workflowModulePathFinder = new WorkflowModulePathFinder();
	workflowDefinitionExportsResolver = new WorkflowDefinitionExportsResolver();
	discoveredWorkflowsEmptyMessageFactory = new DiscoveredWorkflowsEmptyMessageFactory();
	pathSegmentsComputer = new WorkflowDiscoveryPathSegmentsComputer();
	performanceDiagnosticsLogger = new ServerLoggerFactory(logLevelPolicyFactory).createPerformanceDiagnostics("codemation-config-loader.timing");
	bootLogger = new ServerLoggerFactory(logLevelPolicyFactory).create("codemation.boot");
	/**
	* In-flight + completed load promises keyed by `${consumerRoot}|${configPathOverride}`. The
	* boot path constructs MULTIPLE CodemationConsumerConfigLoader instances (one inside the CLI's
	* DatabaseMigrationsApplyService, another inside NextHostEdgeSeedLoader, another inside
	* AppConfigLoader for the disposable runtime) and each independently calls `load(...)`. Without
	* a cache shared across instances, the same `${consumerRoot}` ends up importing
	* codemation.config.ts + discovered workflow modules ~3 times for a single dev boot. The cache
	* has to be static so it spans every loader instance in the process.
	*
	* Callers MUST invoke `invalidateAll()` on a source-change reload — the dev source watcher
	* already tears the runtime down and reboots; it just needs to clear this map first.
	*/
	static resolutionCache = /* @__PURE__ */ new Map();
	static invalidateAll() {
		this.resolutionCache.clear();
	}
	async load(args) {
		const cacheKey = `${args.consumerRoot}|${args.configPathOverride ?? ""}`;
		const cached = CodemationConsumerConfigLoader.resolutionCache.get(cacheKey);
		if (cached) return cached;
		const promise = this.loadUncached(args);
		CodemationConsumerConfigLoader.resolutionCache.set(cacheKey, promise);
		try {
			return await promise;
		} catch (error) {
			CodemationConsumerConfigLoader.resolutionCache.delete(cacheKey);
			throw error;
		}
	}
	async loadUncached(args) {
		const loadStarted = performance.now();
		let mark = loadStarted;
		const importSession = this.createImportSession();
		const phaseDurations = /* @__PURE__ */ new Map();
		const phaseMs = (label) => {
			const now = performance.now();
			const delta = now - mark;
			mark = now;
			phaseDurations.set(label, delta);
			this.performanceDiagnosticsLogger.info(`load.${label} +${delta.toFixed(1)}ms (cumulative ${(now - loadStarted).toFixed(1)}ms)`);
		};
		const bootstrapSource = await BootTimer.measureAsync("config.resolveConfigPath", () => this.resolveConfigPath(args.consumerRoot, args.configPathOverride));
		phaseMs("resolveConfigPath");
		if (!bootstrapSource) throw new Error("Codemation config not found. Expected \"codemation.config.ts\" in the consumer project root or \"src/\".");
		const moduleExports = await BootTimer.measureAsync("config.importConfigModule", () => this.importModule(bootstrapSource, importSession));
		phaseMs("importConfigModule");
		const rawConfig = this.configExportsResolver.resolveConfig(moduleExports);
		if (!rawConfig) throw new Error(`Config file does not export a Codemation config object: ${bootstrapSource}`);
		const config = this.configNormalizer.normalize(rawConfig);
		if (rawConfig.codemationVersion) this.bootLogger.info(`codemationVersion: ${rawConfig.codemationVersion}`);
		const workflowSources = await BootTimer.measureAsync("config.resolveWorkflowSources", () => this.resolveWorkflowSources(args.consumerRoot, config));
		phaseMs("resolveWorkflowSources");
		const workflows = await BootTimer.measureAsync("config.loadDiscoveredWorkflows", async () => this.mergeWorkflows(config.workflows ?? [], await this.loadDiscoveredWorkflows(args.consumerRoot, config, workflowSources, importSession)));
		phaseMs("loadDiscoveredWorkflows");
		const resolvedConfig = {
			...config,
			workflows
		};
		logLevelPolicyFactory.create().applyCodemationLogConfig(resolvedConfig.log);
		return {
			config: resolvedConfig,
			bootstrapSource,
			workflowSources
		};
	}
	async resolveConfigPath(consumerRoot, configPathOverride) {
		if (configPathOverride) {
			const explicitPath = path.isAbsolute(configPathOverride) ? configPathOverride : path.resolve(consumerRoot, configPathOverride);
			if (!await this.exists(explicitPath)) throw new Error(`Config file not found: ${explicitPath}`);
			return explicitPath;
		}
		for (const candidate of this.getConventionCandidates(consumerRoot)) if (await this.exists(candidate)) return candidate;
		return null;
	}
	getConventionCandidates(consumerRoot) {
		return [
			path.resolve(consumerRoot, "codemation.config.ts"),
			path.resolve(consumerRoot, "codemation.config.js"),
			path.resolve(consumerRoot, "src", "codemation.config.ts"),
			path.resolve(consumerRoot, "src", "codemation.config.js")
		];
	}
	async resolveWorkflowSources(consumerRoot, config) {
		if ((config.workflowDiscovery?.directories?.length ?? 0) === 0) return [];
		return [...await this.workflowModulePathFinder.discoverModulePaths({
			consumerRoot,
			workflowDirectories: config.workflowDiscovery?.directories,
			exists: (absolutePath) => this.exists(absolutePath)
		})].sort((left, right) => left.localeCompare(right));
	}
	async loadDiscoveredWorkflows(consumerRoot, config, workflowSources, importSession) {
		const workflowDiscoveryDirectories = config.workflowDiscovery?.directories ?? [];
		const workflowsById = /* @__PURE__ */ new Map();
		const loadedWorkflowModules = await Promise.all(workflowSources.map(async (workflowSource) => ({
			workflowSource,
			segments: this.pathSegmentsComputer.compute({
				consumerRoot,
				workflowDiscoveryDirectories,
				absoluteWorkflowModulePath: workflowSource
			}),
			moduleExports: await BootTimer.measureAsync(`workflow.${path.basename(workflowSource).replace(/\.tsx?$/, "")}`, () => this.importModule(workflowSource, importSession))
		})));
		for (const loadedWorkflowModule of loadedWorkflowModules) for (const workflow of this.workflowDefinitionExportsResolver.resolve(loadedWorkflowModule.moduleExports)) {
			const enriched = loadedWorkflowModule.segments && loadedWorkflowModule.segments.length > 0 ? {
				...workflow,
				discoveryPathSegments: loadedWorkflowModule.segments
			} : workflow;
			workflowsById.set(workflow.id, enriched);
		}
		if (workflowsById.size === 0 && workflowSources.length > 0) throw new Error(this.discoveredWorkflowsEmptyMessageFactory.create(workflowSources));
		return [...workflowsById.values()];
	}
	mergeWorkflows(configuredWorkflows, discoveredWorkflows) {
		const workflowsById = /* @__PURE__ */ new Map();
		for (const workflow of discoveredWorkflows) workflowsById.set(workflow.id, workflow);
		for (const workflow of configuredWorkflows) workflowsById.set(workflow.id, workflow);
		return [...workflowsById.values()];
	}
	async importModule(modulePath, importSession) {
		if (this.shouldUseNativeRuntimeImport()) return await this.importModuleWithNativeRuntime(modulePath);
		const tsconfigPath = await this.resolveTsconfigPath(modulePath);
		const cacheKey = tsconfigPath || "default";
		if (importSession.shouldResetImporter && !importSession.resetCacheKeys.has(cacheKey)) {
			await this.resetImporter(tsconfigPath);
			importSession.resetCacheKeys.add(cacheKey);
		}
		const importSpecifier = await this.createImportSpecifier(modulePath);
		for (let attempt = 0; attempt < 3; attempt += 1) try {
			return await (await this.getOrCreateImporter(tsconfigPath)).import(importSpecifier, import.meta.url);
		} catch (error) {
			if (!this.isStoppedTransformServiceError(error) || attempt === 2) throw error;
			await this.resetImporter(tsconfigPath);
		}
		throw new Error(`Failed to import consumer module after retries: ${modulePath}`);
	}
	async importModuleWithNativeRuntime(modulePath) {
		return await import(await this.createImportSpecifier(modulePath));
	}
	async resolveTsconfigPath(modulePath) {
		const overridePath = process.env.CODEMATION_TSCONFIG_PATH;
		if (overridePath && await this.exists(overridePath)) return overridePath;
		return await this.findNearestTsconfig(modulePath) ?? false;
	}
	async getOrCreateImporter(tsconfigPath) {
		const cacheKey = tsconfigPath || "default";
		const existingImporter = CodemationConsumerConfigLoader.importerRegistrationsByTsconfig.get(cacheKey);
		if (existingImporter) return existingImporter;
		const { register } = await import(
			/* webpackIgnore: true */
			this.resolveTsxImporterModuleSpecifier()
);
		const namespaceVersion = this.nextNamespaceVersion(cacheKey);
		const nextImporter = register({
			namespace: this.toNamespace(cacheKey, namespaceVersion),
			tsconfig: tsconfigPath
		});
		CodemationConsumerConfigLoader.importerRegistrationsByTsconfig.set(cacheKey, nextImporter);
		return nextImporter;
	}
	async resetImporter(tsconfigPath) {
		const cacheKey = tsconfigPath || "default";
		const existingImporter = CodemationConsumerConfigLoader.importerRegistrationsByTsconfig.get(cacheKey);
		if (!existingImporter) return;
		CodemationConsumerConfigLoader.importerRegistrationsByTsconfig.delete(cacheKey);
		await existingImporter.unregister().catch(() => null);
	}
	nextNamespaceVersion(cacheKey) {
		const nextVersion = (CodemationConsumerConfigLoader.importerNamespaceVersionByTsconfig.get(cacheKey) ?? 0) + 1;
		CodemationConsumerConfigLoader.importerNamespaceVersionByTsconfig.set(cacheKey, nextVersion);
		return nextVersion;
	}
	toNamespace(cacheKey, namespaceVersion) {
		return `codemation_consumer_${cacheKey.replace(/[^a-zA-Z0-9_-]+/g, "_")}_${namespaceVersion}`;
	}
	resolveTsxImporterModuleSpecifier() {
		return [
			"tsx",
			"esm",
			"api"
		].join("/");
	}
	async findNearestTsconfig(modulePath) {
		let currentDirectory = path.dirname(modulePath);
		while (true) {
			const candidate = path.resolve(currentDirectory, "tsconfig.json");
			if (await this.exists(candidate)) return candidate;
			const parentDirectory = path.dirname(currentDirectory);
			if (parentDirectory === currentDirectory) return null;
			currentDirectory = parentDirectory;
		}
	}
	async createImportSpecifier(modulePath) {
		const moduleUrl = pathToFileURL(modulePath);
		const moduleStats = await stat(modulePath);
		moduleUrl.searchParams.set("t", String(moduleStats.mtimeMs));
		return moduleUrl.href;
	}
	shouldUseNativeRuntimeImport() {
		return process.env.CODEMATION_TS_RUNTIME === "ts-node";
	}
	shouldResetImporterBeforeImport() {
		return (process.env.CODEMATION_DEV_SERVER_TOKEN?.trim().length ?? 0) > 0;
	}
	createImportSession() {
		return {
			resetCacheKeys: /* @__PURE__ */ new Set(),
			shouldResetImporter: this.shouldResetImporterBeforeImport()
		};
	}
	isStoppedTransformServiceError(error) {
		return error instanceof Error && error.message.includes("The service is no longer running");
	}
	async exists(filePath) {
		try {
			await access(filePath);
			return true;
		} catch {
			return false;
		}
	}
};

//#endregion
export { CodemationConfigNormalizer as a, CodemationConsumerAppResolver as i, WorkflowDiscoveryPathSegmentsComputer as n, WorkflowModulePathFinder as r, CodemationConsumerConfigLoader as t };
//# sourceMappingURL=CodemationConsumerConfigLoader-By-6tuGc.js.map