//#region src/preview/encoding/workerEncoder.ts
/**
* Worker-based canvas encoding.
*/
const WORKER_TASK_TIMEOUT_MS = 3e4;
/**
* Encode a canvas using a worker.
* @param worker - The worker to use for encoding
* @param canvas - The canvas to encode
* @param preserveAlpha - Whether to preserve alpha channel (PNG vs JPEG)
* @returns Promise resolving to the encoded data URL
*/
async function encodeCanvasInWorker(worker, canvas, preserveAlpha) {
	return new Promise((resolve, reject) => {
		const taskId = `task-${Date.now()}-${Math.random()}-${performance.now()}`;
		let timeoutId = null;
		const cleanup = () => {
			if (timeoutId !== null) {
				clearTimeout(timeoutId);
				timeoutId = null;
			}
			worker.removeEventListener("message", messageHandler);
			worker.removeEventListener("messageerror", messageErrorHandler);
		};
		const messageHandler = (event) => {
			const result = event.data;
			if (result.taskId === taskId) {
				cleanup();
				if (result.error) reject(/* @__PURE__ */ new Error(`Worker encoding failed: ${result.error}`));
				else resolve(result.dataUrl);
			}
		};
		const messageErrorHandler = () => {
			cleanup();
			reject(/* @__PURE__ */ new Error("Worker message error"));
		};
		worker.addEventListener("message", messageHandler);
		worker.addEventListener("messageerror", messageErrorHandler);
		timeoutId = window.setTimeout(() => {
			cleanup();
			reject(/* @__PURE__ */ new Error("Worker task timed out"));
		}, WORKER_TASK_TIMEOUT_MS);
		createImageBitmap(canvas).then((bitmap) => {
			worker.postMessage({
				taskId,
				bitmap,
				preserveAlpha
			}, [bitmap]);
		}).catch((error) => {
			cleanup();
			reject(error instanceof Error ? error : new Error(String(error)));
		});
	});
}

//#endregion
export { encodeCanvasInWorker };
//# sourceMappingURL=workerEncoder.js.map