/*! © 2026 Yahoo, Inc. UDS Tailwind and Purger v0.0.0-development */
require("../_virtual/_rolldown/runtime.cjs");
let node_os = require("node:os");
let node_worker_threads = require("node:worker_threads");
//#region src/css/workerPool.ts
const createWorkerPool = async (config, numWorkers) => {
	const workerCount = numWorkers ?? Math.max(1, (0, node_os.cpus)().length - 1);
	const workerUrl = new URL("./purgeWorker.js", require("url").pathToFileURL(__filename).href);
	const workers = [];
	const available = [];
	const pending = /* @__PURE__ */ new Map();
	const queue = [];
	let nextId = 0;
	await Promise.all(Array.from({ length: workerCount }, () => {
		return new Promise((resolve, reject) => {
			const worker = new node_worker_threads.Worker(workerUrl);
			let initialized = false;
			worker.on("message", (msg) => {
				if (msg.type === "ready") {
					initialized = true;
					workers.push(worker);
					available.push(worker);
					resolve();
					return;
				}
				if (msg.type === "result" || msg.type === "error") {
					const task = msg.id != null ? pending.get(msg.id) : void 0;
					if (task) {
						pending.delete(msg.id);
						if (msg.type === "result") task.resolve(msg.result);
						else task.reject(new Error(msg.error ?? "Unknown worker error"));
					}
					available.push(worker);
					if (queue.length > 0 && available.length > 0) {
						const next = queue.shift();
						const nextWorker = available.pop();
						pending.set(next.msg.id, next.task);
						nextWorker.postMessage(next.msg);
					}
				}
			});
			worker.on("error", (err) => {
				if (!initialized) reject(err);
			});
			worker.postMessage({
				type: "init",
				config: JSON.parse(JSON.stringify(config))
			});
		});
	}));
	const processFile = (options) => {
		return new Promise((resolve, reject) => {
			const id = nextId++;
			const msg = {
				type: "task",
				id,
				code: options.code,
				filePath: options.filePath,
				colorModes: options.colorModes,
				variantDefaults: options.variantDefaults,
				runtimeConfigValues: options.runtimeConfigValues,
				includeAllClassNamePrimitives: options.includeAllClassNamePrimitives
			};
			const task = {
				resolve,
				reject
			};
			if (available.length > 0) {
				const worker = available.pop();
				pending.set(id, task);
				worker.postMessage(msg);
			} else queue.push({
				msg,
				task
			});
		});
	};
	const destroy = async () => {
		for (const worker of workers) worker.postMessage({ type: "done" });
		await Promise.all(workers.map((w) => new Promise((res) => w.on("exit", () => res()))));
	};
	return {
		processFile,
		destroy,
		workerCount
	};
};
//#endregion
exports.createWorkerPool = createWorkerPool;
