import { i as ONNXRuntimeWebBackend, r as createFactory, t as AniraWeb } from "./AniraWeb-BUQ7qNoG.js";
//#region src/workers/inferenceWorkerHandler.ts
/**
* Set up the inference worker message handler.
*
* Call this at the top level of your worker file, passing any custom
* processor subclasses the worker should know about:
*
* ```ts
* // my-inference-worker.ts
* import { setupInferenceWorker } from './inferenceWorkerHandler'
* import { CustomJSBackend } from '../custom-js-backend'
*
* setupInferenceWorker({ CustomJSBackend })
* ```
*/
var setupInferenceWorker = (customProcessorClasses = {}, createAnira = (config, memory) => AniraWeb.create(config, memory)) => {
	const processorClasses = {
		ONNXRuntimeWebBackend,
		...customProcessorClasses
	};
	let aniraWeb;
	let thread;
	const processorRegistry = /* @__PURE__ */ new Map();
	self.onmessage = async (e) => {
		switch (e.data.type) {
			case "initInferenceWorker": {
				const { threadPtr, wasmMemory, stackPtr } = e.data;
				aniraWeb = await createAnira({ processBuffers: (processorPtr, inputPtr, outputPtr) => {
					const processor = processorRegistry.get(processorPtr);
					if (!processor) throw new Error(`JSProcessor with pointer ${processorPtr} is not registered in this worker. Call registerProcessor() before starting inference.`);
					processor.process(inputPtr, outputPtr);
				} }, wasmMemory);
				aniraWeb.stackRestore(stackPtr);
				const t = aniraWeb.InferenceThread.fromPointer(threadPtr);
				if (!t) return;
				thread = t;
				postMessage({ type: "ready" });
				break;
			}
			case "registerProcessor": {
				const { processorPtr, className, inferenceConfigPtr } = e.data;
				if (!processorRegistry.has(processorPtr)) {
					let instance;
					if (className && processorClasses[className]) instance = createFactory(aniraWeb.getWasmInstance(), processorClasses[className]).fromPointer(processorPtr);
					else instance = aniraWeb.JSBackendBase.fromPointer(processorPtr);
					if (inferenceConfigPtr) instance.inferenceConfigPtr = inferenceConfigPtr;
					await instance.init();
					processorRegistry.set(processorPtr, instance);
				}
				postMessage({ type: "processorRegistered" });
				break;
			}
			case "unregisterProcessor": {
				const { processorPtr } = e.data;
				const instance = processorRegistry.get(processorPtr);
				if (instance) {
					instance.destroy();
					processorRegistry.delete(processorPtr);
				}
				postMessage({ type: "processorUnregistered" });
				break;
			}
			case "start":
				thread.runLoop();
				postMessage({ type: "stopped" });
				break;
			case "destroy":
				close();
				break;
		}
	};
};
//#endregion
export { setupInferenceWorker as t };
