const e = "undefined" != typeof ImageDecoder;
function t(e) {
	if (!e || "object" != typeof e) return !1;
	const t = e;
	return "string" == typeof t.sessionId && "number" == typeof t.seq && "number" == typeof t.width && "number" == typeof t.height && "string" == typeof t.mimeType && ((n = t.data) instanceof Uint8Array || "[object Uint8Array]" === Object.prototype.toString.call(n));
	var n;
}
const n = /* @__PURE__ */ new Map(), s = /* @__PURE__ */ new Map();
let a = null;
function i(i) {
	a?.close(), a = i, i.onmessage = (a) => {
		const i = a.data;
		if (!t(i)) return;
		const o = s.get(i.sessionId);
		if (!o) return;
		const r = n.get(o);
		r && async function(t, n) {
			const s = t;
			if (e) {
				const e = new ImageDecoder({
					type: n,
					data: s,
					transfer: [s.buffer]
				});
				try {
					const { image: t } = await e.decode();
					return t;
				} finally {
					e.close();
				}
			}
			const a = new Blob([s], { type: n });
			return createImageBitmap(a);
		}(i.data, i.mimeType).then((e) => {
			s.get(i.sessionId) !== o || i.seq <= r.paintedSeq || (r.paintedSeq = i.seq, r.canvas.width === i.width && r.canvas.height === i.height || (r.canvas.width = i.width, r.canvas.height = i.height), r.ctx.drawImage(e, 0, 0, i.width, i.height)), e.close();
		}, () => {});
	}, i.start();
}
self.onmessage = (e) => {
	const t = e.data;
	if (t && "string" == typeof t.kind) switch (t.kind) {
		case "port": {
			const t = e.ports[0];
			t && i(t);
			return;
		}
		case "adopt": {
			if ("string" != typeof t.canvasId || !t.canvas) return;
			const e = t.canvas.getContext("2d", { alpha: !1 });
			if (!e) return;
			n.set(t.canvasId, {
				canvas: t.canvas,
				ctx: e,
				paintedSeq: -1
			});
			return;
		}
		case "bind": {
			if ("string" != typeof t.canvasId || "string" != typeof t.sessionId) return;
			const e = n.get(t.canvasId);
			e && (e.paintedSeq = -1), s.set(t.sessionId, t.canvasId);
			return;
		}
		case "unbind":
			if ("string" != typeof t.sessionId) return;
			s.delete(t.sessionId);
			return;
		case "release":
			if ("string" != typeof t.canvasId) return;
			n.delete(t.canvasId);
			for (const [e, n] of s) n === t.canvasId && s.delete(e);
			return;
	}
};
