//#region \0rolldown/runtime.js
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
var __copyProps = (to, from, except, desc) => {
	if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
		key = keys[i];
		if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
			get: ((k) => from[k]).bind(null, key),
			enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
		});
	}
	return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
	value: mod,
	enumerable: true
}) : target, mod));
//#endregion
//#region \0vite/modulepreload-polyfill.js
(function polyfill() {
	const relList = document.createElement("link").relList;
	if (relList && relList.supports && relList.supports("modulepreload")) return;
	for (const link of document.querySelectorAll("link[rel=\"modulepreload\"]")) processPreload(link);
	new MutationObserver((mutations) => {
		for (const mutation of mutations) {
			if (mutation.type !== "childList") continue;
			for (const node of mutation.addedNodes) if (node.tagName === "LINK" && node.rel === "modulepreload") processPreload(node);
		}
	}).observe(document, {
		childList: true,
		subtree: true
	});
	function getFetchOpts(link) {
		const fetchOpts = {};
		if (link.integrity) fetchOpts.integrity = link.integrity;
		if (link.referrerPolicy) fetchOpts.referrerPolicy = link.referrerPolicy;
		if (link.crossOrigin === "use-credentials") fetchOpts.credentials = "include";
		else if (link.crossOrigin === "anonymous") fetchOpts.credentials = "omit";
		else fetchOpts.credentials = "same-origin";
		return fetchOpts;
	}
	function processPreload(link) {
		if (link.ep) return;
		link.ep = true;
		const fetchOpts = getFetchOpts(link);
		fetch(link.href, fetchOpts);
	}
})();
//#endregion
//#region node_modules/@kitware/vtk.js/Common/Core/URLExtract.js
function identity(i) {
	return i;
}
function toNativeType(str) {
	if (str === null || str === "null") return null;
	if (str === "true") return true;
	if (str === "false") return false;
	if (str === void 0 || str === "undefined") return;
	if (str[0] === "[" && str[str.length - 1] === "]") return str.substring(1, str.length - 1).split(",").map((s) => toNativeType(s.trim()));
	if (str === "" || Number.isNaN(Number(str))) return str;
	return Number(str);
}
function extractURLParameters(castToNativeType = true, query = window.location.search) {
	const summary = {};
	const convert = castToNativeType ? toNativeType : identity;
	new URLSearchParams(query).forEach((value, key) => {
		if (key) summary[key] = value ? convert(value) : true;
	});
	return summary;
}
var vtkURLExtract = {
	toNativeType,
	extractURLParameters
};
//#endregion
//#region node_modules/wslink/src/CompositeClosureHelper/index.js
function capitalize$1(str) {
	return str.charAt(0).toUpperCase() + str.slice(1);
}
function isA(publicAPI, model = {}, name = null) {
	if (!model.isA) model.isA = [];
	if (name) model.isA.push(name);
	if (!publicAPI.isA) publicAPI.isA = (className) => model.isA.indexOf(className) !== -1;
}
function set$1(publicAPI, model = {}, names = []) {
	names.forEach((name) => {
		publicAPI[`set${capitalize$1(name)}`] = (value) => {
			model[name] = value;
		};
	});
}
function get$2(publicAPI, model = {}, names = []) {
	names.forEach((name) => {
		publicAPI[`get${capitalize$1(name)}`] = () => model[name];
	});
}
function destroy(publicAPI, model = {}) {
	const previousDestroy = publicAPI.destroy;
	if (!model.subscriptions) model.subscriptions = [];
	publicAPI.destroy = () => {
		if (previousDestroy) previousDestroy();
		while (model.subscriptions && model.subscriptions.length) model.subscriptions.pop().unsubscribe();
		Object.keys(model).forEach((field) => {
			delete model[field];
		});
		model.deleted = true;
	};
}
function event$2(publicAPI, model, eventName, asynchrounous = true) {
	const callbacks = [];
	const previousDestroy = publicAPI.destroy;
	function off(index) {
		callbacks[index] = null;
	}
	function on(index) {
		function unsubscribe() {
			off(index);
		}
		return Object.freeze({ unsubscribe });
	}
	publicAPI[`fire${capitalize$1(eventName)}`] = (...args) => {
		if (model.deleted) {
			console.log("instance deleted - can not call any method");
			return;
		}
		function processCallbacks() {
			callbacks.forEach((callback) => {
				if (callback) try {
					callback.apply(publicAPI, args);
				} catch (errObj) {
					console.log("Error event:", eventName, errObj);
				}
			});
		}
		if (asynchrounous) setTimeout(processCallbacks, 0);
		else processCallbacks();
	};
	publicAPI[`on${capitalize$1(eventName)}`] = (callback) => {
		if (model.deleted) {
			console.log("instance deleted - can not call any method");
			return null;
		}
		const index = callbacks.length;
		callbacks.push(callback);
		return on(index);
	};
	publicAPI.destroy = () => {
		previousDestroy();
		callbacks.forEach((el, index) => off(index));
	};
}
function chain$1(...fn) {
	return (...args) => fn.filter((i) => !!i).forEach((i) => i(...args));
}
function newInstance$8(extend) {
	return (initialValues = {}) => {
		const model = {};
		const publicAPI = {};
		extend(publicAPI, model, initialValues);
		return Object.freeze(publicAPI);
	};
}
var CompositeClosureHelper_default = {
	chain: chain$1,
	destroy,
	event: event$2,
	get: get$2,
	isA,
	newInstance: newInstance$8,
	set: set$1
};
//#endregion
//#region node_modules/wslink/src/ProcessLauncher/index.js
var connections = [];
function ProcessLauncher(publicAPI, model) {
	publicAPI.start = (config) => {
		const xhr = new XMLHttpRequest();
		const url = model.endPoint;
		if (!model._retry) model._retry = config.launcherRetry || [];
		xhr.open("POST", url, true);
		if (config.headers) {
			model._headers = config.headers;
			delete config.headers;
		}
		if (model._headers) Object.entries(model._headers).forEach(([key, value]) => xhr.setRequestHeader(key, value));
		xhr.responseType = "json";
		const supportsJson = "response" in xhr && xhr.responseType === "json";
		xhr.onload = (e) => {
			const response = supportsJson ? xhr.response : JSON.parse(xhr.response);
			if (xhr.status === 200 && response && !response.error) {
				connections.push(response);
				publicAPI.fireProcessReady(response);
				return;
			} else if (xhr.status === 503 && model._retry.length > 0) {
				const timeout = model._retry.shift();
				setTimeout(publicAPI.start, timeout, config);
			} else publicAPI.fireError(xhr);
		};
		xhr.onerror = (e) => {
			publicAPI.fireError(xhr);
		};
		xhr.send(JSON.stringify(config));
	};
	publicAPI.fetchConnection = (sessionId) => {
		var xhr = new XMLHttpRequest(), url = [model.endPoint, sessionId].join("/");
		xhr.open("GET", url, true);
		xhr.responseType = "json";
		const supportsJson = "response" in xhr && xhr.responseType === "json";
		xhr.onload = (e) => {
			if (this.status === 200) {
				publicAPI.fireFetch(supportsJson ? xhr.response : JSON.parse(xhr.response));
				return;
			}
			publicAPI.fireError(xhr);
		};
		xhr.onerror = (e) => {
			publicAPI.fireError(xhr);
		};
		xhr.send();
	};
	publicAPI.stop = (connection) => {
		var xhr = new XMLHttpRequest(), url = [model.endPoint, connection.id].join("/");
		xhr.open("DELETE", url, true);
		xhr.responseType = "json";
		const supportsJson = "response" in xhr && xhr.responseType === "json";
		xhr.onload = (e) => {
			if (this.status === 200) {
				const response = supportsJson ? xhr.response : JSON.parse(xhr.response);
				publicAPI.fireProcessStopped(response);
				return;
			}
			publicAPI.fireError(xhr);
		};
		xhr.onerror = (e) => {
			publicAPI.fireError(xhr);
		};
		xhr.send();
	};
	publicAPI.listConnections = () => {
		return connections;
	};
}
var DEFAULT_VALUES$6 = { endPoint: null };
function extend$6(publicAPI, model, initialValues = {}) {
	Object.assign(model, DEFAULT_VALUES$6, initialValues);
	CompositeClosureHelper_default.destroy(publicAPI, model);
	CompositeClosureHelper_default.event(publicAPI, model, "ProcessReady");
	CompositeClosureHelper_default.event(publicAPI, model, "ProcessStopped");
	CompositeClosureHelper_default.event(publicAPI, model, "Fetch");
	CompositeClosureHelper_default.event(publicAPI, model, "Error");
	CompositeClosureHelper_default.isA(publicAPI, model, "ProcessLauncher");
	ProcessLauncher(publicAPI, model);
}
var ProcessLauncher_default = {
	newInstance: CompositeClosureHelper_default.newInstance(extend$6),
	extend: extend$6
};
//#endregion
//#region node_modules/wslink/src/WebsocketConnection/chunking.js
var UINT32_LENGTH = 4;
var ID_LOCATION = 0;
var ID_LENGTH = UINT32_LENGTH;
var MESSAGE_OFFSET_LOCATION = ID_LOCATION + ID_LENGTH;
var MESSAGE_OFFSET_LENGTH = UINT32_LENGTH;
var MESSAGE_SIZE_LOCATION = MESSAGE_OFFSET_LOCATION + MESSAGE_OFFSET_LENGTH;
var MESSAGE_SIZE_LENGTH = UINT32_LENGTH;
var HEADER_LENGTH = ID_LENGTH + MESSAGE_OFFSET_LENGTH + MESSAGE_SIZE_LENGTH;
function encodeHeader(id, offset, size) {
	const buffer = new ArrayBuffer(HEADER_LENGTH);
	const header = new Uint8Array(buffer);
	const view = new DataView(buffer);
	view.setUint32(ID_LOCATION, id, true);
	view.setUint32(MESSAGE_OFFSET_LOCATION, offset, true);
	view.setUint32(MESSAGE_SIZE_LOCATION, size, true);
	return header;
}
function decodeHeader(header) {
	const view = new DataView(header.buffer);
	return {
		id: view.getUint32(ID_LOCATION, true),
		offset: view.getUint32(MESSAGE_OFFSET_LOCATION, true),
		size: view.getUint32(MESSAGE_SIZE_LOCATION, true)
	};
}
function* generateChunks(message, maxSize) {
	const totalSize = message.byteLength;
	let maxContentSize;
	if (maxSize === 0) maxContentSize = totalSize;
	else maxContentSize = Math.max(maxSize - HEADER_LENGTH, 1);
	const id = new Uint32Array(1);
	crypto.getRandomValues(id);
	let offset = 0;
	while (offset < totalSize) {
		const contentSize = Math.min(maxContentSize, totalSize - offset);
		const chunk = new Uint8Array(new ArrayBuffer(HEADER_LENGTH + contentSize));
		const header = encodeHeader(id[0], offset, totalSize);
		chunk.set(new Uint8Array(header.buffer), 0);
		chunk.set(message.subarray(offset, offset + contentSize), HEADER_LENGTH);
		yield chunk;
		offset += contentSize;
	}
}
var UnChunker = class {
	pendingMessages;
	constructor() {
		this.pendingMessages = {};
	}
	releasePendingMessages() {
		this.pendingMessages = {};
	}
	async processChunk(chunk, decoderFactory) {
		const headerBlob = chunk.slice(0, HEADER_LENGTH);
		const contentBlob = chunk.slice(HEADER_LENGTH);
		const { id, offset, size: totalSize } = decodeHeader(new Uint8Array(await headerBlob.arrayBuffer()));
		let pendingMessage = this.pendingMessages[id];
		if (!pendingMessage) {
			pendingMessage = {
				receivedSize: 0,
				content: new Uint8Array(totalSize),
				decoder: decoderFactory()
			};
			this.pendingMessages[id] = pendingMessage;
		}
		if (totalSize !== pendingMessage.content.byteLength) {
			delete this.pendingMessages[id];
			throw new Error(`Total size in chunk header for message ${id} does not match total size declared by previous chunk.`);
		}
		const chunkContent = new Uint8Array(await contentBlob.arrayBuffer());
		const content = pendingMessage.content;
		content.set(chunkContent, offset);
		pendingMessage.receivedSize += chunkContent.byteLength;
		if (pendingMessage.receivedSize >= totalSize) {
			delete this.pendingMessages[id];
			try {
				return pendingMessage["decoder"].decode(content);
			} catch (e) {
				console.error("Malformed message: ", content.slice(0, 100));
			}
		}
	}
};
//#endregion
//#region node_modules/@msgpack/msgpack/dist.es5+esm/utils/int.mjs
var UINT32_MAX = 4294967295;
function setUint64(view, offset, value) {
	var high = value / 4294967296;
	var low = value;
	view.setUint32(offset, high);
	view.setUint32(offset + 4, low);
}
function setInt64(view, offset, value) {
	var high = Math.floor(value / 4294967296);
	var low = value;
	view.setUint32(offset, high);
	view.setUint32(offset + 4, low);
}
function getInt64(view, offset) {
	var high = view.getInt32(offset);
	var low = view.getUint32(offset + 4);
	return high * 4294967296 + low;
}
function getUint64(view, offset) {
	var high = view.getUint32(offset);
	var low = view.getUint32(offset + 4);
	return high * 4294967296 + low;
}
//#endregion
//#region node_modules/@msgpack/msgpack/dist.es5+esm/utils/utf8.mjs
var _a, _b, _c;
var TEXT_ENCODING_AVAILABLE = (typeof process === "undefined" || ((_a = process === null || process === void 0 ? void 0 : {}) === null || _a === void 0 ? void 0 : _a["TEXT_ENCODING"]) !== "never") && typeof TextEncoder !== "undefined" && typeof TextDecoder !== "undefined";
function utf8Count(str) {
	var strLength = str.length;
	var byteLength = 0;
	var pos = 0;
	while (pos < strLength) {
		var value = str.charCodeAt(pos++);
		if ((value & 4294967168) === 0) {
			byteLength++;
			continue;
		} else if ((value & 4294965248) === 0) byteLength += 2;
		else {
			if (value >= 55296 && value <= 56319) {
				if (pos < strLength) {
					var extra = str.charCodeAt(pos);
					if ((extra & 64512) === 56320) {
						++pos;
						value = ((value & 1023) << 10) + (extra & 1023) + 65536;
					}
				}
			}
			if ((value & 4294901760) === 0) byteLength += 3;
			else byteLength += 4;
		}
	}
	return byteLength;
}
function utf8EncodeJs(str, output, outputOffset) {
	var strLength = str.length;
	var offset = outputOffset;
	var pos = 0;
	while (pos < strLength) {
		var value = str.charCodeAt(pos++);
		if ((value & 4294967168) === 0) {
			output[offset++] = value;
			continue;
		} else if ((value & 4294965248) === 0) output[offset++] = value >> 6 & 31 | 192;
		else {
			if (value >= 55296 && value <= 56319) {
				if (pos < strLength) {
					var extra = str.charCodeAt(pos);
					if ((extra & 64512) === 56320) {
						++pos;
						value = ((value & 1023) << 10) + (extra & 1023) + 65536;
					}
				}
			}
			if ((value & 4294901760) === 0) {
				output[offset++] = value >> 12 & 15 | 224;
				output[offset++] = value >> 6 & 63 | 128;
			} else {
				output[offset++] = value >> 18 & 7 | 240;
				output[offset++] = value >> 12 & 63 | 128;
				output[offset++] = value >> 6 & 63 | 128;
			}
		}
		output[offset++] = value & 63 | 128;
	}
}
var sharedTextEncoder = TEXT_ENCODING_AVAILABLE ? new TextEncoder() : void 0;
var TEXT_ENCODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE ? UINT32_MAX : typeof process !== "undefined" && ((_b = process === null || process === void 0 ? void 0 : {}) === null || _b === void 0 ? void 0 : _b["TEXT_ENCODING"]) !== "force" ? 200 : 0;
function utf8EncodeTEencode(str, output, outputOffset) {
	output.set(sharedTextEncoder.encode(str), outputOffset);
}
function utf8EncodeTEencodeInto(str, output, outputOffset) {
	sharedTextEncoder.encodeInto(str, output.subarray(outputOffset));
}
var utf8EncodeTE = (sharedTextEncoder === null || sharedTextEncoder === void 0 ? void 0 : sharedTextEncoder.encodeInto) ? utf8EncodeTEencodeInto : utf8EncodeTEencode;
var CHUNK_SIZE = 4096;
function utf8DecodeJs(bytes, inputOffset, byteLength) {
	var offset = inputOffset;
	var end = offset + byteLength;
	var units = [];
	var result = "";
	while (offset < end) {
		var byte1 = bytes[offset++];
		if ((byte1 & 128) === 0) units.push(byte1);
		else if ((byte1 & 224) === 192) {
			var byte2 = bytes[offset++] & 63;
			units.push((byte1 & 31) << 6 | byte2);
		} else if ((byte1 & 240) === 224) {
			var byte2 = bytes[offset++] & 63;
			var byte3 = bytes[offset++] & 63;
			units.push((byte1 & 31) << 12 | byte2 << 6 | byte3);
		} else if ((byte1 & 248) === 240) {
			var byte2 = bytes[offset++] & 63;
			var byte3 = bytes[offset++] & 63;
			var byte4 = bytes[offset++] & 63;
			var unit = (byte1 & 7) << 18 | byte2 << 12 | byte3 << 6 | byte4;
			if (unit > 65535) {
				unit -= 65536;
				units.push(unit >>> 10 & 1023 | 55296);
				unit = 56320 | unit & 1023;
			}
			units.push(unit);
		} else units.push(byte1);
		if (units.length >= CHUNK_SIZE) {
			result += String.fromCharCode.apply(String, units);
			units.length = 0;
		}
	}
	if (units.length > 0) result += String.fromCharCode.apply(String, units);
	return result;
}
var sharedTextDecoder = TEXT_ENCODING_AVAILABLE ? new TextDecoder() : null;
var TEXT_DECODER_THRESHOLD = !TEXT_ENCODING_AVAILABLE ? UINT32_MAX : typeof process !== "undefined" && ((_c = process === null || process === void 0 ? void 0 : {}) === null || _c === void 0 ? void 0 : _c["TEXT_DECODER"]) !== "force" ? 200 : 0;
function utf8DecodeTD(bytes, inputOffset, byteLength) {
	var stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);
	return sharedTextDecoder.decode(stringBytes);
}
//#endregion
//#region node_modules/@msgpack/msgpack/dist.es5+esm/ExtData.mjs
/**
* ExtData is used to handle Extension Types that are not registered to ExtensionCodec.
*/
var ExtData = function() {
	function ExtData(type, data) {
		this.type = type;
		this.data = data;
	}
	return ExtData;
}();
//#endregion
//#region node_modules/@msgpack/msgpack/dist.es5+esm/DecodeError.mjs
var __extends = (function() {
	var extendStatics = function(d, b) {
		extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d, b) {
			d.__proto__ = b;
		} || function(d, b) {
			for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];
		};
		return extendStatics(d, b);
	};
	return function(d, b) {
		if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
		extendStatics(d, b);
		function __() {
			this.constructor = d;
		}
		d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
	};
})();
var DecodeError = function(_super) {
	__extends(DecodeError, _super);
	function DecodeError(message) {
		var _this = _super.call(this, message) || this;
		var proto = Object.create(DecodeError.prototype);
		Object.setPrototypeOf(_this, proto);
		Object.defineProperty(_this, "name", {
			configurable: true,
			enumerable: false,
			value: DecodeError.name
		});
		return _this;
	}
	return DecodeError;
}(Error);
var TIMESTAMP32_MAX_SEC = 4294967295;
var TIMESTAMP64_MAX_SEC = 17179869183;
function encodeTimeSpecToTimestamp(_a) {
	var sec = _a.sec, nsec = _a.nsec;
	if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {
		var rv = new Uint8Array(4);
		var view = new DataView(rv.buffer);
		view.setUint32(0, sec);
		return rv;
	} else {
		var secHigh = sec / 4294967296;
		var secLow = sec & 4294967295;
		var rv = new Uint8Array(8);
		var view = new DataView(rv.buffer);
		view.setUint32(0, nsec << 2 | secHigh & 3);
		view.setUint32(4, secLow);
		return rv;
	}
	else {
		var rv = new Uint8Array(12);
		var view = new DataView(rv.buffer);
		view.setUint32(0, nsec);
		setInt64(view, 4, sec);
		return rv;
	}
}
function encodeDateToTimeSpec(date) {
	var msec = date.getTime();
	var sec = Math.floor(msec / 1e3);
	var nsec = (msec - sec * 1e3) * 1e6;
	var nsecInSec = Math.floor(nsec / 1e9);
	return {
		sec: sec + nsecInSec,
		nsec: nsec - nsecInSec * 1e9
	};
}
function encodeTimestampExtension(object) {
	if (object instanceof Date) return encodeTimeSpecToTimestamp(encodeDateToTimeSpec(object));
	else return null;
}
function decodeTimestampToTimeSpec(data) {
	var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
	switch (data.byteLength) {
		case 4:
			var sec = view.getUint32(0);
			var nsec = 0;
			return {
				sec,
				nsec
			};
		case 8:
			var nsec30AndSecHigh2 = view.getUint32(0);
			var secLow32 = view.getUint32(4);
			var sec = (nsec30AndSecHigh2 & 3) * 4294967296 + secLow32;
			var nsec = nsec30AndSecHigh2 >>> 2;
			return {
				sec,
				nsec
			};
		case 12:
			var sec = getInt64(view, 4);
			var nsec = view.getUint32(0);
			return {
				sec,
				nsec
			};
		default: throw new DecodeError("Unrecognized data size for timestamp (expected 4, 8, or 12): ".concat(data.length));
	}
}
function decodeTimestampExtension(data) {
	var timeSpec = decodeTimestampToTimeSpec(data);
	return /* @__PURE__ */ new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);
}
var timestampExtension = {
	type: -1,
	encode: encodeTimestampExtension,
	decode: decodeTimestampExtension
};
//#endregion
//#region node_modules/@msgpack/msgpack/dist.es5+esm/ExtensionCodec.mjs
var ExtensionCodec = function() {
	function ExtensionCodec() {
		this.builtInEncoders = [];
		this.builtInDecoders = [];
		this.encoders = [];
		this.decoders = [];
		this.register(timestampExtension);
	}
	ExtensionCodec.prototype.register = function(_a) {
		var type = _a.type, encode = _a.encode, decode = _a.decode;
		if (type >= 0) {
			this.encoders[type] = encode;
			this.decoders[type] = decode;
		} else {
			var index = 1 + type;
			this.builtInEncoders[index] = encode;
			this.builtInDecoders[index] = decode;
		}
	};
	ExtensionCodec.prototype.tryToEncode = function(object, context) {
		for (var i = 0; i < this.builtInEncoders.length; i++) {
			var encodeExt = this.builtInEncoders[i];
			if (encodeExt != null) {
				var data = encodeExt(object, context);
				if (data != null) {
					var type = -1 - i;
					return new ExtData(type, data);
				}
			}
		}
		for (var i = 0; i < this.encoders.length; i++) {
			var encodeExt = this.encoders[i];
			if (encodeExt != null) {
				var data = encodeExt(object, context);
				if (data != null) {
					var type = i;
					return new ExtData(type, data);
				}
			}
		}
		if (object instanceof ExtData) return object;
		return null;
	};
	ExtensionCodec.prototype.decode = function(data, type, context) {
		var decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];
		if (decodeExt) return decodeExt(data, type, context);
		else return new ExtData(type, data);
	};
	ExtensionCodec.defaultCodec = new ExtensionCodec();
	return ExtensionCodec;
}();
//#endregion
//#region node_modules/@msgpack/msgpack/dist.es5+esm/utils/typedArrays.mjs
function ensureUint8Array(buffer) {
	if (buffer instanceof Uint8Array) return buffer;
	else if (ArrayBuffer.isView(buffer)) return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
	else if (buffer instanceof ArrayBuffer) return new Uint8Array(buffer);
	else return Uint8Array.from(buffer);
}
function createDataView(buffer) {
	if (buffer instanceof ArrayBuffer) return new DataView(buffer);
	var bufferView = ensureUint8Array(buffer);
	return new DataView(bufferView.buffer, bufferView.byteOffset, bufferView.byteLength);
}
var DEFAULT_INITIAL_BUFFER_SIZE = 2048;
var Encoder = function() {
	function Encoder(extensionCodec, context, maxDepth, initialBufferSize, sortKeys, forceFloat32, ignoreUndefined, forceIntegerToFloat) {
		if (extensionCodec === void 0) extensionCodec = ExtensionCodec.defaultCodec;
		if (context === void 0) context = void 0;
		if (maxDepth === void 0) maxDepth = 100;
		if (initialBufferSize === void 0) initialBufferSize = DEFAULT_INITIAL_BUFFER_SIZE;
		if (sortKeys === void 0) sortKeys = false;
		if (forceFloat32 === void 0) forceFloat32 = false;
		if (ignoreUndefined === void 0) ignoreUndefined = false;
		if (forceIntegerToFloat === void 0) forceIntegerToFloat = false;
		this.extensionCodec = extensionCodec;
		this.context = context;
		this.maxDepth = maxDepth;
		this.initialBufferSize = initialBufferSize;
		this.sortKeys = sortKeys;
		this.forceFloat32 = forceFloat32;
		this.ignoreUndefined = ignoreUndefined;
		this.forceIntegerToFloat = forceIntegerToFloat;
		this.pos = 0;
		this.view = new DataView(new ArrayBuffer(this.initialBufferSize));
		this.bytes = new Uint8Array(this.view.buffer);
	}
	Encoder.prototype.reinitializeState = function() {
		this.pos = 0;
	};
	/**
	* This is almost equivalent to {@link Encoder#encode}, but it returns an reference of the encoder's internal buffer and thus much faster than {@link Encoder#encode}.
	*
	* @returns Encodes the object and returns a shared reference the encoder's internal buffer.
	*/
	Encoder.prototype.encodeSharedRef = function(object) {
		this.reinitializeState();
		this.doEncode(object, 1);
		return this.bytes.subarray(0, this.pos);
	};
	/**
	* @returns Encodes the object and returns a copy of the encoder's internal buffer.
	*/
	Encoder.prototype.encode = function(object) {
		this.reinitializeState();
		this.doEncode(object, 1);
		return this.bytes.slice(0, this.pos);
	};
	Encoder.prototype.doEncode = function(object, depth) {
		if (depth > this.maxDepth) throw new Error("Too deep objects in depth ".concat(depth));
		if (object == null) this.encodeNil();
		else if (typeof object === "boolean") this.encodeBoolean(object);
		else if (typeof object === "number") this.encodeNumber(object);
		else if (typeof object === "string") this.encodeString(object);
		else this.encodeObject(object, depth);
	};
	Encoder.prototype.ensureBufferSizeToWrite = function(sizeToWrite) {
		var requiredSize = this.pos + sizeToWrite;
		if (this.view.byteLength < requiredSize) this.resizeBuffer(requiredSize * 2);
	};
	Encoder.prototype.resizeBuffer = function(newSize) {
		var newBuffer = new ArrayBuffer(newSize);
		var newBytes = new Uint8Array(newBuffer);
		var newView = new DataView(newBuffer);
		newBytes.set(this.bytes);
		this.view = newView;
		this.bytes = newBytes;
	};
	Encoder.prototype.encodeNil = function() {
		this.writeU8(192);
	};
	Encoder.prototype.encodeBoolean = function(object) {
		if (object === false) this.writeU8(194);
		else this.writeU8(195);
	};
	Encoder.prototype.encodeNumber = function(object) {
		if (Number.isSafeInteger(object) && !this.forceIntegerToFloat) if (object >= 0) if (object < 128) this.writeU8(object);
		else if (object < 256) {
			this.writeU8(204);
			this.writeU8(object);
		} else if (object < 65536) {
			this.writeU8(205);
			this.writeU16(object);
		} else if (object < 4294967296) {
			this.writeU8(206);
			this.writeU32(object);
		} else {
			this.writeU8(207);
			this.writeU64(object);
		}
		else if (object >= -32) this.writeU8(224 | object + 32);
		else if (object >= -128) {
			this.writeU8(208);
			this.writeI8(object);
		} else if (object >= -32768) {
			this.writeU8(209);
			this.writeI16(object);
		} else if (object >= -2147483648) {
			this.writeU8(210);
			this.writeI32(object);
		} else {
			this.writeU8(211);
			this.writeI64(object);
		}
		else if (this.forceFloat32) {
			this.writeU8(202);
			this.writeF32(object);
		} else {
			this.writeU8(203);
			this.writeF64(object);
		}
	};
	Encoder.prototype.writeStringHeader = function(byteLength) {
		if (byteLength < 32) this.writeU8(160 + byteLength);
		else if (byteLength < 256) {
			this.writeU8(217);
			this.writeU8(byteLength);
		} else if (byteLength < 65536) {
			this.writeU8(218);
			this.writeU16(byteLength);
		} else if (byteLength < 4294967296) {
			this.writeU8(219);
			this.writeU32(byteLength);
		} else throw new Error("Too long string: ".concat(byteLength, " bytes in UTF-8"));
	};
	Encoder.prototype.encodeString = function(object) {
		var maxHeaderSize = 5;
		if (object.length > TEXT_ENCODER_THRESHOLD) {
			var byteLength = utf8Count(object);
			this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
			this.writeStringHeader(byteLength);
			utf8EncodeTE(object, this.bytes, this.pos);
			this.pos += byteLength;
		} else {
			var byteLength = utf8Count(object);
			this.ensureBufferSizeToWrite(maxHeaderSize + byteLength);
			this.writeStringHeader(byteLength);
			utf8EncodeJs(object, this.bytes, this.pos);
			this.pos += byteLength;
		}
	};
	Encoder.prototype.encodeObject = function(object, depth) {
		var ext = this.extensionCodec.tryToEncode(object, this.context);
		if (ext != null) this.encodeExtension(ext);
		else if (Array.isArray(object)) this.encodeArray(object, depth);
		else if (ArrayBuffer.isView(object)) this.encodeBinary(object);
		else if (typeof object === "object") this.encodeMap(object, depth);
		else throw new Error("Unrecognized object: ".concat(Object.prototype.toString.apply(object)));
	};
	Encoder.prototype.encodeBinary = function(object) {
		var size = object.byteLength;
		if (size < 256) {
			this.writeU8(196);
			this.writeU8(size);
		} else if (size < 65536) {
			this.writeU8(197);
			this.writeU16(size);
		} else if (size < 4294967296) {
			this.writeU8(198);
			this.writeU32(size);
		} else throw new Error("Too large binary: ".concat(size));
		var bytes = ensureUint8Array(object);
		this.writeU8a(bytes);
	};
	Encoder.prototype.encodeArray = function(object, depth) {
		var size = object.length;
		if (size < 16) this.writeU8(144 + size);
		else if (size < 65536) {
			this.writeU8(220);
			this.writeU16(size);
		} else if (size < 4294967296) {
			this.writeU8(221);
			this.writeU32(size);
		} else throw new Error("Too large array: ".concat(size));
		for (var _i = 0, object_1 = object; _i < object_1.length; _i++) {
			var item = object_1[_i];
			this.doEncode(item, depth + 1);
		}
	};
	Encoder.prototype.countWithoutUndefined = function(object, keys) {
		var count = 0;
		for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) if (object[keys_1[_i]] !== void 0) count++;
		return count;
	};
	Encoder.prototype.encodeMap = function(object, depth) {
		var keys = Object.keys(object);
		if (this.sortKeys) keys.sort();
		var size = this.ignoreUndefined ? this.countWithoutUndefined(object, keys) : keys.length;
		if (size < 16) this.writeU8(128 + size);
		else if (size < 65536) {
			this.writeU8(222);
			this.writeU16(size);
		} else if (size < 4294967296) {
			this.writeU8(223);
			this.writeU32(size);
		} else throw new Error("Too large map object: ".concat(size));
		for (var _i = 0, keys_2 = keys; _i < keys_2.length; _i++) {
			var key = keys_2[_i];
			var value = object[key];
			if (!(this.ignoreUndefined && value === void 0)) {
				this.encodeString(key);
				this.doEncode(value, depth + 1);
			}
		}
	};
	Encoder.prototype.encodeExtension = function(ext) {
		var size = ext.data.length;
		if (size === 1) this.writeU8(212);
		else if (size === 2) this.writeU8(213);
		else if (size === 4) this.writeU8(214);
		else if (size === 8) this.writeU8(215);
		else if (size === 16) this.writeU8(216);
		else if (size < 256) {
			this.writeU8(199);
			this.writeU8(size);
		} else if (size < 65536) {
			this.writeU8(200);
			this.writeU16(size);
		} else if (size < 4294967296) {
			this.writeU8(201);
			this.writeU32(size);
		} else throw new Error("Too large extension object: ".concat(size));
		this.writeI8(ext.type);
		this.writeU8a(ext.data);
	};
	Encoder.prototype.writeU8 = function(value) {
		this.ensureBufferSizeToWrite(1);
		this.view.setUint8(this.pos, value);
		this.pos++;
	};
	Encoder.prototype.writeU8a = function(values) {
		var size = values.length;
		this.ensureBufferSizeToWrite(size);
		this.bytes.set(values, this.pos);
		this.pos += size;
	};
	Encoder.prototype.writeI8 = function(value) {
		this.ensureBufferSizeToWrite(1);
		this.view.setInt8(this.pos, value);
		this.pos++;
	};
	Encoder.prototype.writeU16 = function(value) {
		this.ensureBufferSizeToWrite(2);
		this.view.setUint16(this.pos, value);
		this.pos += 2;
	};
	Encoder.prototype.writeI16 = function(value) {
		this.ensureBufferSizeToWrite(2);
		this.view.setInt16(this.pos, value);
		this.pos += 2;
	};
	Encoder.prototype.writeU32 = function(value) {
		this.ensureBufferSizeToWrite(4);
		this.view.setUint32(this.pos, value);
		this.pos += 4;
	};
	Encoder.prototype.writeI32 = function(value) {
		this.ensureBufferSizeToWrite(4);
		this.view.setInt32(this.pos, value);
		this.pos += 4;
	};
	Encoder.prototype.writeF32 = function(value) {
		this.ensureBufferSizeToWrite(4);
		this.view.setFloat32(this.pos, value);
		this.pos += 4;
	};
	Encoder.prototype.writeF64 = function(value) {
		this.ensureBufferSizeToWrite(8);
		this.view.setFloat64(this.pos, value);
		this.pos += 8;
	};
	Encoder.prototype.writeU64 = function(value) {
		this.ensureBufferSizeToWrite(8);
		setUint64(this.view, this.pos, value);
		this.pos += 8;
	};
	Encoder.prototype.writeI64 = function(value) {
		this.ensureBufferSizeToWrite(8);
		setInt64(this.view, this.pos, value);
		this.pos += 8;
	};
	return Encoder;
}();
//#endregion
//#region node_modules/@msgpack/msgpack/dist.es5+esm/utils/prettyByte.mjs
function prettyByte(byte) {
	return "".concat(byte < 0 ? "-" : "", "0x").concat(Math.abs(byte).toString(16).padStart(2, "0"));
}
//#endregion
//#region node_modules/@msgpack/msgpack/dist.es5+esm/CachedKeyDecoder.mjs
var DEFAULT_MAX_KEY_LENGTH = 16;
var DEFAULT_MAX_LENGTH_PER_KEY = 16;
var CachedKeyDecoder = function() {
	function CachedKeyDecoder(maxKeyLength, maxLengthPerKey) {
		if (maxKeyLength === void 0) maxKeyLength = DEFAULT_MAX_KEY_LENGTH;
		if (maxLengthPerKey === void 0) maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY;
		this.maxKeyLength = maxKeyLength;
		this.maxLengthPerKey = maxLengthPerKey;
		this.hit = 0;
		this.miss = 0;
		this.caches = [];
		for (var i = 0; i < this.maxKeyLength; i++) this.caches.push([]);
	}
	CachedKeyDecoder.prototype.canBeCached = function(byteLength) {
		return byteLength > 0 && byteLength <= this.maxKeyLength;
	};
	CachedKeyDecoder.prototype.find = function(bytes, inputOffset, byteLength) {
		var records = this.caches[byteLength - 1];
		FIND_CHUNK: for (var _i = 0, records_1 = records; _i < records_1.length; _i++) {
			var record = records_1[_i];
			var recordBytes = record.bytes;
			for (var j = 0; j < byteLength; j++) if (recordBytes[j] !== bytes[inputOffset + j]) continue FIND_CHUNK;
			return record.str;
		}
		return null;
	};
	CachedKeyDecoder.prototype.store = function(bytes, value) {
		var records = this.caches[bytes.length - 1];
		var record = {
			bytes,
			str: value
		};
		if (records.length >= this.maxLengthPerKey) records[Math.random() * records.length | 0] = record;
		else records.push(record);
	};
	CachedKeyDecoder.prototype.decode = function(bytes, inputOffset, byteLength) {
		var cachedValue = this.find(bytes, inputOffset, byteLength);
		if (cachedValue != null) {
			this.hit++;
			return cachedValue;
		}
		this.miss++;
		var str = utf8DecodeJs(bytes, inputOffset, byteLength);
		var slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);
		this.store(slicedCopyOfBytes, str);
		return str;
	};
	return CachedKeyDecoder;
}();
//#endregion
//#region node_modules/@msgpack/msgpack/dist.es5+esm/Decoder.mjs
var __awaiter = function(thisArg, _arguments, P, generator) {
	function adopt(value) {
		return value instanceof P ? value : new P(function(resolve) {
			resolve(value);
		});
	}
	return new (P || (P = Promise))(function(resolve, reject) {
		function fulfilled(value) {
			try {
				step(generator.next(value));
			} catch (e) {
				reject(e);
			}
		}
		function rejected(value) {
			try {
				step(generator["throw"](value));
			} catch (e) {
				reject(e);
			}
		}
		function step(result) {
			result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
		}
		step((generator = generator.apply(thisArg, _arguments || [])).next());
	});
};
var __generator = function(thisArg, body) {
	var _ = {
		label: 0,
		sent: function() {
			if (t[0] & 1) throw t[1];
			return t[1];
		},
		trys: [],
		ops: []
	}, f, y, t, g;
	return g = {
		next: verb(0),
		"throw": verb(1),
		"return": verb(2)
	}, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
		return this;
	}), g;
	function verb(n) {
		return function(v) {
			return step([n, v]);
		};
	}
	function step(op) {
		if (f) throw new TypeError("Generator is already executing.");
		while (_) try {
			if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
			if (y = 0, t) op = [op[0] & 2, t.value];
			switch (op[0]) {
				case 0:
				case 1:
					t = op;
					break;
				case 4:
					_.label++;
					return {
						value: op[1],
						done: false
					};
				case 5:
					_.label++;
					y = op[1];
					op = [0];
					continue;
				case 7:
					op = _.ops.pop();
					_.trys.pop();
					continue;
				default:
					if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
						_ = 0;
						continue;
					}
					if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
						_.label = op[1];
						break;
					}
					if (op[0] === 6 && _.label < t[1]) {
						_.label = t[1];
						t = op;
						break;
					}
					if (t && _.label < t[2]) {
						_.label = t[2];
						_.ops.push(op);
						break;
					}
					if (t[2]) _.ops.pop();
					_.trys.pop();
					continue;
			}
			op = body.call(thisArg, _);
		} catch (e) {
			op = [6, e];
			y = 0;
		} finally {
			f = t = 0;
		}
		if (op[0] & 5) throw op[1];
		return {
			value: op[0] ? op[1] : void 0,
			done: true
		};
	}
};
var __asyncValues = function(o) {
	if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
	var m = o[Symbol.asyncIterator], i;
	return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
		return this;
	}, i);
	function verb(n) {
		i[n] = o[n] && function(v) {
			return new Promise(function(resolve, reject) {
				v = o[n](v), settle(resolve, reject, v.done, v.value);
			});
		};
	}
	function settle(resolve, reject, d, v) {
		Promise.resolve(v).then(function(v) {
			resolve({
				value: v,
				done: d
			});
		}, reject);
	}
};
var __await = function(v) {
	return this instanceof __await ? (this.v = v, this) : new __await(v);
};
var __asyncGenerator = function(thisArg, _arguments, generator) {
	if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
	var g = generator.apply(thisArg, _arguments || []), i, q = [];
	return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function() {
		return this;
	}, i;
	function verb(n) {
		if (g[n]) i[n] = function(v) {
			return new Promise(function(a, b) {
				q.push([
					n,
					v,
					a,
					b
				]) > 1 || resume(n, v);
			});
		};
	}
	function resume(n, v) {
		try {
			step(g[n](v));
		} catch (e) {
			settle(q[0][3], e);
		}
	}
	function step(r) {
		r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r);
	}
	function fulfill(value) {
		resume("next", value);
	}
	function reject(value) {
		resume("throw", value);
	}
	function settle(f, v) {
		if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]);
	}
};
var isValidMapKeyType = function(key) {
	var keyType = typeof key;
	return keyType === "string" || keyType === "number";
};
var HEAD_BYTE_REQUIRED = -1;
var EMPTY_VIEW = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(0));
var EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);
var DataViewIndexOutOfBoundsError = (function() {
	try {
		EMPTY_VIEW.getInt8(0);
	} catch (e) {
		return e.constructor;
	}
	throw new Error("never reached");
})();
var MORE_DATA = new DataViewIndexOutOfBoundsError("Insufficient data");
var sharedCachedKeyDecoder = new CachedKeyDecoder();
var Decoder = function() {
	function Decoder(extensionCodec, context, maxStrLength, maxBinLength, maxArrayLength, maxMapLength, maxExtLength, keyDecoder) {
		if (extensionCodec === void 0) extensionCodec = ExtensionCodec.defaultCodec;
		if (context === void 0) context = void 0;
		if (maxStrLength === void 0) maxStrLength = UINT32_MAX;
		if (maxBinLength === void 0) maxBinLength = UINT32_MAX;
		if (maxArrayLength === void 0) maxArrayLength = UINT32_MAX;
		if (maxMapLength === void 0) maxMapLength = UINT32_MAX;
		if (maxExtLength === void 0) maxExtLength = UINT32_MAX;
		if (keyDecoder === void 0) keyDecoder = sharedCachedKeyDecoder;
		this.extensionCodec = extensionCodec;
		this.context = context;
		this.maxStrLength = maxStrLength;
		this.maxBinLength = maxBinLength;
		this.maxArrayLength = maxArrayLength;
		this.maxMapLength = maxMapLength;
		this.maxExtLength = maxExtLength;
		this.keyDecoder = keyDecoder;
		this.totalPos = 0;
		this.pos = 0;
		this.view = EMPTY_VIEW;
		this.bytes = EMPTY_BYTES;
		this.headByte = HEAD_BYTE_REQUIRED;
		this.stack = [];
	}
	Decoder.prototype.reinitializeState = function() {
		this.totalPos = 0;
		this.headByte = HEAD_BYTE_REQUIRED;
		this.stack.length = 0;
	};
	Decoder.prototype.setBuffer = function(buffer) {
		this.bytes = ensureUint8Array(buffer);
		this.view = createDataView(this.bytes);
		this.pos = 0;
	};
	Decoder.prototype.appendBuffer = function(buffer) {
		if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) this.setBuffer(buffer);
		else {
			var remainingData = this.bytes.subarray(this.pos);
			var newData = ensureUint8Array(buffer);
			var newBuffer = new Uint8Array(remainingData.length + newData.length);
			newBuffer.set(remainingData);
			newBuffer.set(newData, remainingData.length);
			this.setBuffer(newBuffer);
		}
	};
	Decoder.prototype.hasRemaining = function(size) {
		return this.view.byteLength - this.pos >= size;
	};
	Decoder.prototype.createExtraByteError = function(posToShow) {
		var _a = this, view = _a.view, pos = _a.pos;
		return new RangeError("Extra ".concat(view.byteLength - pos, " of ").concat(view.byteLength, " byte(s) found at buffer[").concat(posToShow, "]"));
	};
	/**
	* @throws {@link DecodeError}
	* @throws {@link RangeError}
	*/
	Decoder.prototype.decode = function(buffer) {
		this.reinitializeState();
		this.setBuffer(buffer);
		var object = this.doDecodeSync();
		if (this.hasRemaining(1)) throw this.createExtraByteError(this.pos);
		return object;
	};
	Decoder.prototype.decodeMulti = function(buffer) {
		return __generator(this, function(_a) {
			switch (_a.label) {
				case 0:
					this.reinitializeState();
					this.setBuffer(buffer);
					_a.label = 1;
				case 1:
					if (!this.hasRemaining(1)) return [3, 3];
					return [4, this.doDecodeSync()];
				case 2:
					_a.sent();
					return [3, 1];
				case 3: return [2];
			}
		});
	};
	Decoder.prototype.decodeAsync = function(stream) {
		var stream_1, stream_1_1;
		var e_1, _a;
		return __awaiter(this, void 0, void 0, function() {
			var decoded, object, buffer, e_1_1, _b, headByte, pos, totalPos;
			return __generator(this, function(_c) {
				switch (_c.label) {
					case 0:
						decoded = false;
						_c.label = 1;
					case 1:
						_c.trys.push([
							1,
							6,
							7,
							12
						]);
						stream_1 = __asyncValues(stream);
						_c.label = 2;
					case 2: return [4, stream_1.next()];
					case 3:
						if (!(stream_1_1 = _c.sent(), !stream_1_1.done)) return [3, 5];
						buffer = stream_1_1.value;
						if (decoded) throw this.createExtraByteError(this.totalPos);
						this.appendBuffer(buffer);
						try {
							object = this.doDecodeSync();
							decoded = true;
						} catch (e) {
							if (!(e instanceof DataViewIndexOutOfBoundsError)) throw e;
						}
						this.totalPos += this.pos;
						_c.label = 4;
					case 4: return [3, 2];
					case 5: return [3, 12];
					case 6:
						e_1_1 = _c.sent();
						e_1 = { error: e_1_1 };
						return [3, 12];
					case 7:
						_c.trys.push([
							7,
							,
							10,
							11
						]);
						if (!(stream_1_1 && !stream_1_1.done && (_a = stream_1.return))) return [3, 9];
						return [4, _a.call(stream_1)];
					case 8:
						_c.sent();
						_c.label = 9;
					case 9: return [3, 11];
					case 10:
						if (e_1) throw e_1.error;
						return [7];
					case 11: return [7];
					case 12:
						if (decoded) {
							if (this.hasRemaining(1)) throw this.createExtraByteError(this.totalPos);
							return [2, object];
						}
						_b = this, headByte = _b.headByte, pos = _b.pos, totalPos = _b.totalPos;
						throw new RangeError("Insufficient data in parsing ".concat(prettyByte(headByte), " at ").concat(totalPos, " (").concat(pos, " in the current buffer)"));
				}
			});
		});
	};
	Decoder.prototype.decodeArrayStream = function(stream) {
		return this.decodeMultiAsync(stream, true);
	};
	Decoder.prototype.decodeStream = function(stream) {
		return this.decodeMultiAsync(stream, false);
	};
	Decoder.prototype.decodeMultiAsync = function(stream, isArray) {
		return __asyncGenerator(this, arguments, function decodeMultiAsync_1() {
			var isArrayHeaderRequired, arrayItemsLeft, stream_2, stream_2_1, buffer, e_2, e_3_1;
			var e_3, _a;
			return __generator(this, function(_b) {
				switch (_b.label) {
					case 0:
						isArrayHeaderRequired = isArray;
						arrayItemsLeft = -1;
						_b.label = 1;
					case 1:
						_b.trys.push([
							1,
							13,
							14,
							19
						]);
						stream_2 = __asyncValues(stream);
						_b.label = 2;
					case 2: return [4, __await(stream_2.next())];
					case 3:
						if (!(stream_2_1 = _b.sent(), !stream_2_1.done)) return [3, 12];
						buffer = stream_2_1.value;
						if (isArray && arrayItemsLeft === 0) throw this.createExtraByteError(this.totalPos);
						this.appendBuffer(buffer);
						if (isArrayHeaderRequired) {
							arrayItemsLeft = this.readArraySize();
							isArrayHeaderRequired = false;
							this.complete();
						}
						_b.label = 4;
					case 4:
						_b.trys.push([
							4,
							9,
							,
							10
						]);
						_b.label = 5;
					case 5: return [4, __await(this.doDecodeSync())];
					case 6: return [4, _b.sent()];
					case 7:
						_b.sent();
						if (--arrayItemsLeft === 0) return [3, 8];
						return [3, 5];
					case 8: return [3, 10];
					case 9:
						e_2 = _b.sent();
						if (!(e_2 instanceof DataViewIndexOutOfBoundsError)) throw e_2;
						return [3, 10];
					case 10:
						this.totalPos += this.pos;
						_b.label = 11;
					case 11: return [3, 2];
					case 12: return [3, 19];
					case 13:
						e_3_1 = _b.sent();
						e_3 = { error: e_3_1 };
						return [3, 19];
					case 14:
						_b.trys.push([
							14,
							,
							17,
							18
						]);
						if (!(stream_2_1 && !stream_2_1.done && (_a = stream_2.return))) return [3, 16];
						return [4, __await(_a.call(stream_2))];
					case 15:
						_b.sent();
						_b.label = 16;
					case 16: return [3, 18];
					case 17:
						if (e_3) throw e_3.error;
						return [7];
					case 18: return [7];
					case 19: return [2];
				}
			});
		});
	};
	Decoder.prototype.doDecodeSync = function() {
		DECODE: while (true) {
			var headByte = this.readHeadByte();
			var object = void 0;
			if (headByte >= 224) object = headByte - 256;
			else if (headByte < 192) if (headByte < 128) object = headByte;
			else if (headByte < 144) {
				var size = headByte - 128;
				if (size !== 0) {
					this.pushMapState(size);
					this.complete();
					continue DECODE;
				} else object = {};
			} else if (headByte < 160) {
				var size = headByte - 144;
				if (size !== 0) {
					this.pushArrayState(size);
					this.complete();
					continue DECODE;
				} else object = [];
			} else {
				var byteLength = headByte - 160;
				object = this.decodeUtf8String(byteLength, 0);
			}
			else if (headByte === 192) object = null;
			else if (headByte === 194) object = false;
			else if (headByte === 195) object = true;
			else if (headByte === 202) object = this.readF32();
			else if (headByte === 203) object = this.readF64();
			else if (headByte === 204) object = this.readU8();
			else if (headByte === 205) object = this.readU16();
			else if (headByte === 206) object = this.readU32();
			else if (headByte === 207) object = this.readU64();
			else if (headByte === 208) object = this.readI8();
			else if (headByte === 209) object = this.readI16();
			else if (headByte === 210) object = this.readI32();
			else if (headByte === 211) object = this.readI64();
			else if (headByte === 217) {
				var byteLength = this.lookU8();
				object = this.decodeUtf8String(byteLength, 1);
			} else if (headByte === 218) {
				var byteLength = this.lookU16();
				object = this.decodeUtf8String(byteLength, 2);
			} else if (headByte === 219) {
				var byteLength = this.lookU32();
				object = this.decodeUtf8String(byteLength, 4);
			} else if (headByte === 220) {
				var size = this.readU16();
				if (size !== 0) {
					this.pushArrayState(size);
					this.complete();
					continue DECODE;
				} else object = [];
			} else if (headByte === 221) {
				var size = this.readU32();
				if (size !== 0) {
					this.pushArrayState(size);
					this.complete();
					continue DECODE;
				} else object = [];
			} else if (headByte === 222) {
				var size = this.readU16();
				if (size !== 0) {
					this.pushMapState(size);
					this.complete();
					continue DECODE;
				} else object = {};
			} else if (headByte === 223) {
				var size = this.readU32();
				if (size !== 0) {
					this.pushMapState(size);
					this.complete();
					continue DECODE;
				} else object = {};
			} else if (headByte === 196) {
				var size = this.lookU8();
				object = this.decodeBinary(size, 1);
			} else if (headByte === 197) {
				var size = this.lookU16();
				object = this.decodeBinary(size, 2);
			} else if (headByte === 198) {
				var size = this.lookU32();
				object = this.decodeBinary(size, 4);
			} else if (headByte === 212) object = this.decodeExtension(1, 0);
			else if (headByte === 213) object = this.decodeExtension(2, 0);
			else if (headByte === 214) object = this.decodeExtension(4, 0);
			else if (headByte === 215) object = this.decodeExtension(8, 0);
			else if (headByte === 216) object = this.decodeExtension(16, 0);
			else if (headByte === 199) {
				var size = this.lookU8();
				object = this.decodeExtension(size, 1);
			} else if (headByte === 200) {
				var size = this.lookU16();
				object = this.decodeExtension(size, 2);
			} else if (headByte === 201) {
				var size = this.lookU32();
				object = this.decodeExtension(size, 4);
			} else throw new DecodeError("Unrecognized type byte: ".concat(prettyByte(headByte)));
			this.complete();
			var stack = this.stack;
			while (stack.length > 0) {
				var state = stack[stack.length - 1];
				if (state.type === 0) {
					state.array[state.position] = object;
					state.position++;
					if (state.position === state.size) {
						stack.pop();
						object = state.array;
					} else continue DECODE;
				} else if (state.type === 1) {
					if (!isValidMapKeyType(object)) throw new DecodeError("The type of key must be string or number but " + typeof object);
					if (object === "__proto__") throw new DecodeError("The key __proto__ is not allowed");
					state.key = object;
					state.type = 2;
					continue DECODE;
				} else {
					state.map[state.key] = object;
					state.readCount++;
					if (state.readCount === state.size) {
						stack.pop();
						object = state.map;
					} else {
						state.key = null;
						state.type = 1;
						continue DECODE;
					}
				}
			}
			return object;
		}
	};
	Decoder.prototype.readHeadByte = function() {
		if (this.headByte === HEAD_BYTE_REQUIRED) this.headByte = this.readU8();
		return this.headByte;
	};
	Decoder.prototype.complete = function() {
		this.headByte = HEAD_BYTE_REQUIRED;
	};
	Decoder.prototype.readArraySize = function() {
		var headByte = this.readHeadByte();
		switch (headByte) {
			case 220: return this.readU16();
			case 221: return this.readU32();
			default: if (headByte < 160) return headByte - 144;
			else throw new DecodeError("Unrecognized array type byte: ".concat(prettyByte(headByte)));
		}
	};
	Decoder.prototype.pushMapState = function(size) {
		if (size > this.maxMapLength) throw new DecodeError("Max length exceeded: map length (".concat(size, ") > maxMapLengthLength (").concat(this.maxMapLength, ")"));
		this.stack.push({
			type: 1,
			size,
			key: null,
			readCount: 0,
			map: {}
		});
	};
	Decoder.prototype.pushArrayState = function(size) {
		if (size > this.maxArrayLength) throw new DecodeError("Max length exceeded: array length (".concat(size, ") > maxArrayLength (").concat(this.maxArrayLength, ")"));
		this.stack.push({
			type: 0,
			size,
			array: new Array(size),
			position: 0
		});
	};
	Decoder.prototype.decodeUtf8String = function(byteLength, headerOffset) {
		var _a;
		if (byteLength > this.maxStrLength) throw new DecodeError("Max length exceeded: UTF-8 byte length (".concat(byteLength, ") > maxStrLength (").concat(this.maxStrLength, ")"));
		if (this.bytes.byteLength < this.pos + headerOffset + byteLength) throw MORE_DATA;
		var offset = this.pos + headerOffset;
		var object;
		if (this.stateIsMapKey() && ((_a = this.keyDecoder) === null || _a === void 0 ? void 0 : _a.canBeCached(byteLength))) object = this.keyDecoder.decode(this.bytes, offset, byteLength);
		else if (byteLength > TEXT_DECODER_THRESHOLD) object = utf8DecodeTD(this.bytes, offset, byteLength);
		else object = utf8DecodeJs(this.bytes, offset, byteLength);
		this.pos += headerOffset + byteLength;
		return object;
	};
	Decoder.prototype.stateIsMapKey = function() {
		if (this.stack.length > 0) return this.stack[this.stack.length - 1].type === 1;
		return false;
	};
	Decoder.prototype.decodeBinary = function(byteLength, headOffset) {
		if (byteLength > this.maxBinLength) throw new DecodeError("Max length exceeded: bin length (".concat(byteLength, ") > maxBinLength (").concat(this.maxBinLength, ")"));
		if (!this.hasRemaining(byteLength + headOffset)) throw MORE_DATA;
		var offset = this.pos + headOffset;
		var object = this.bytes.subarray(offset, offset + byteLength);
		this.pos += headOffset + byteLength;
		return object;
	};
	Decoder.prototype.decodeExtension = function(size, headOffset) {
		if (size > this.maxExtLength) throw new DecodeError("Max length exceeded: ext length (".concat(size, ") > maxExtLength (").concat(this.maxExtLength, ")"));
		var extType = this.view.getInt8(this.pos + headOffset);
		var data = this.decodeBinary(size, headOffset + 1);
		return this.extensionCodec.decode(data, extType, this.context);
	};
	Decoder.prototype.lookU8 = function() {
		return this.view.getUint8(this.pos);
	};
	Decoder.prototype.lookU16 = function() {
		return this.view.getUint16(this.pos);
	};
	Decoder.prototype.lookU32 = function() {
		return this.view.getUint32(this.pos);
	};
	Decoder.prototype.readU8 = function() {
		var value = this.view.getUint8(this.pos);
		this.pos++;
		return value;
	};
	Decoder.prototype.readI8 = function() {
		var value = this.view.getInt8(this.pos);
		this.pos++;
		return value;
	};
	Decoder.prototype.readU16 = function() {
		var value = this.view.getUint16(this.pos);
		this.pos += 2;
		return value;
	};
	Decoder.prototype.readI16 = function() {
		var value = this.view.getInt16(this.pos);
		this.pos += 2;
		return value;
	};
	Decoder.prototype.readU32 = function() {
		var value = this.view.getUint32(this.pos);
		this.pos += 4;
		return value;
	};
	Decoder.prototype.readI32 = function() {
		var value = this.view.getInt32(this.pos);
		this.pos += 4;
		return value;
	};
	Decoder.prototype.readU64 = function() {
		var value = getUint64(this.view, this.pos);
		this.pos += 8;
		return value;
	};
	Decoder.prototype.readI64 = function() {
		var value = getInt64(this.view, this.pos);
		this.pos += 8;
		return value;
	};
	Decoder.prototype.readF32 = function() {
		var value = this.view.getFloat32(this.pos);
		this.pos += 4;
		return value;
	};
	Decoder.prototype.readF64 = function() {
		var value = this.view.getFloat64(this.pos);
		this.pos += 8;
		return value;
	};
	return Decoder;
}();
//#endregion
//#region node_modules/wslink/src/WebsocketConnection/session.js
function defer() {
	const deferred = {};
	deferred.promise = new Promise(function(resolve, reject) {
		deferred.resolve = resolve;
		deferred.reject = reject;
	});
	return deferred;
}
function Session(publicAPI, model) {
	const CLIENT_ERROR = -32099;
	let msgCount = 0;
	const inFlightRpc = {};
	const regexRPC = /^(rpc|publish|system):(\w+(?:\.\w+)*):(?:\d+)$/;
	const subscriptions = {};
	let clientID = null;
	let MAX_MSG_SIZE = 512 * 1024;
	const unchunker = new UnChunker();
	function onCompleteMessage(payload) {
		if (!payload) return;
		if (!payload.id) return;
		if (payload.error) {
			const deferred = inFlightRpc[payload.id];
			if (deferred) deferred.reject(payload.error);
			else console.error("Server error:", payload.error);
		} else {
			const match = regexRPC.exec(payload.id);
			if (match) {
				const type = match[1];
				if (type === "rpc") {
					const deferred = inFlightRpc[payload.id];
					if (!deferred) {
						console.log("session message id without matching call, dropped", payload);
						return;
					}
					deferred.resolve(payload.result);
				} else if (type == "publish") {
					console.assert(inFlightRpc[payload.id] === void 0, "publish message received matching in-flight rpc call");
					const topic = match[2];
					if (!subscriptions[topic]) return;
					subscriptions[topic].forEach((callback) => callback([payload.result]));
				} else if (type == "system") {
					const deferred = inFlightRpc[payload.id];
					if (payload.id === "system:c0:0") {
						clientID = payload.result.clientID;
						MAX_MSG_SIZE = payload.result.maxMsgSize || MAX_MSG_SIZE;
						if (deferred) deferred.resolve(clientID);
					} else {
						console.error("Unknown system message", payload.id);
						if (deferred) deferred.reject({
							code: CLIENT_ERROR,
							message: `Unknown system message ${payload.id}`
						});
					}
				} else console.error("Unknown rpc id format", payload.id);
			}
		}
		delete inFlightRpc[payload.id];
	}
	publicAPI.onconnect = (event) => {
		const deferred = defer();
		const id = "system:c0:0";
		inFlightRpc[id] = deferred;
		const wrapper = {
			wslink: "1.0",
			id,
			method: "wslink.hello",
			args: [{ secret: model.secret }],
			kwargs: {}
		};
		const packedWrapper = new CustomEncoder().encode(wrapper);
		for (let chunk of generateChunks(packedWrapper, MAX_MSG_SIZE)) model.ws.send(chunk, { binary: true });
		return deferred.promise;
	};
	publicAPI.call = (method, args = [], kwargs = {}) => {
		const deferred = defer();
		if (model.ws && clientID && model.ws.readyState === 1) {
			const id = `rpc:${clientID}:${msgCount++}`;
			inFlightRpc[id] = deferred;
			const wrapper = {
				wslink: "1.0",
				id,
				method,
				args,
				kwargs
			};
			const packedWrapper = new CustomEncoder().encode(wrapper);
			for (let chunk of generateChunks(packedWrapper, MAX_MSG_SIZE)) model.ws.send(chunk, { binary: true });
		} else deferred.reject({
			code: CLIENT_ERROR,
			message: `RPC call ${method} unsuccessful: connection not open`
		});
		return deferred.promise;
	};
	publicAPI.subscribe = (topic, callback) => {
		const deferred = defer();
		if (model.ws && clientID) {
			if (!subscriptions[topic]) subscriptions[topic] = [];
			subscriptions[topic].push(callback);
			deferred.resolve({
				topic,
				callback
			});
		} else deferred.reject({
			code: CLIENT_ERROR,
			message: `Subscribe call ${topic} unsuccessful: connection not open`
		});
		return {
			topic,
			callback,
			promise: deferred.promise,
			unsubscribe: () => publicAPI.unsubscribe({
				topic,
				callback
			})
		};
	};
	publicAPI.unsubscribe = (info) => {
		const deferred = defer();
		const { topic, callback } = info;
		if (!subscriptions[topic]) {
			deferred.reject({
				code: CLIENT_ERROR,
				message: `Unsubscribe call ${topic} unsuccessful: not subscribed`
			});
			return deferred.promise;
		}
		const index = subscriptions[topic].indexOf(callback);
		if (index !== -1) {
			subscriptions[topic].splice(index, 1);
			deferred.resolve();
		} else deferred.reject({
			code: CLIENT_ERROR,
			message: `Unsubscribe call ${topic} unsuccessful: callback not found`
		});
		return deferred.promise;
	};
	publicAPI.close = () => {
		const deferred = defer();
		model.ws.close();
		unchunker.releasePendingMessages();
		deferred.resolve();
		return deferred.promise;
	};
	function createDecoder() {
		return new Decoder();
	}
	publicAPI.onmessage = async (event) => {
		const message = await unchunker.processChunk(event.data, createDecoder);
		if (message) onCompleteMessage(message);
	};
	publicAPI.addAttachment = (payload) => {
		if (payload instanceof ArrayBuffer) return new DataView(payload);
		return payload;
	};
}
var DEFAULT_VALUES$5 = {
	secret: "wslink-secret",
	ws: null
};
function extend$5(publicAPI, model, initialValues = {}) {
	Object.assign(model, DEFAULT_VALUES$5, initialValues);
	CompositeClosureHelper_default.destroy(publicAPI, model);
	CompositeClosureHelper_default.isA(publicAPI, model, "Session");
	Session(publicAPI, model);
}
var session_default = {
	newInstance: CompositeClosureHelper_default.newInstance(extend$5),
	extend: extend$5
};
var CustomEncoder = class extends Encoder {
	encodeObject(object, depth) {
		if (object instanceof ArrayBuffer) object = new DataView(object);
		return super.encodeObject.call(this, object, depth);
	}
};
//#endregion
//#region node_modules/wslink/src/WebsocketConnection/index.js
var DEFAULT_SECRET = "wslink-secret";
function getTransportObject(url) {
	var idx = url.indexOf(":"), protocol = url.substring(0, idx);
	if (protocol === "ws" || protocol === "wss") return {
		type: "websocket",
		url
	};
	throw new Error(`Unknown protocol (${protocol}) for url (${url}).  Unable to create transport object.`);
}
function WebsocketConnection(publicAPI, model) {
	publicAPI.connect = () => {
		if (!model.urls) return null;
		var uriList = [].concat(model.urls), transports = [];
		for (let i = 0; i < uriList.length; i += 1) {
			const url = uriList[i];
			try {
				const transport = getTransportObject(url);
				transports.push(transport);
			} catch (transportCreateError) {
				console.error(transportCreateError);
				publicAPI.fireConnectionError(publicAPI, transportCreateError);
				return null;
			}
		}
		if (model.connection) {
			if (model.connection.url !== transports[0].url) model.connection.close();
			else if (model.connection.readyState === 0 || model.connection.readyState === 1) return model.session;
		}
		try {
			if (model.wsProxy) model.connection = WSLINK.createWebSocket(transports[0].url);
			else model.connection = new WebSocket(transports[0].url);
		} catch (err) {
			console.error(err);
			publicAPI.fireConnectionError(publicAPI, err);
			return null;
		}
		model.connection.binaryType = "blob";
		if (!model.secret) model.secret = DEFAULT_SECRET;
		model.session = session_default.newInstance({
			ws: model.connection,
			secret: model.secret
		});
		model.connection.onopen = (event) => {
			if (model.session) model.session.onconnect(event).then(() => {
				publicAPI.fireConnectionReady(publicAPI);
			}, (err) => {
				console.error("Connection error", err);
				publicAPI.fireConnectionError(publicAPI, err);
			});
		};
		model.connection.onclose = (event) => {
			publicAPI.fireConnectionClose(publicAPI, event);
			model.connection = null;
		};
		model.connection.onerror = (event) => {
			publicAPI.fireConnectionError(publicAPI, event);
		};
		model.connection.onmessage = (event) => {
			model.session.onmessage(event);
		};
		return model.session;
	};
	publicAPI.getSession = () => model.session;
	publicAPI.getUrl = () => model.connection ? model.connection.url : void 0;
	function cleanUp(timeout = 10) {
		if (model.connection && model.connection.readyState === 1 && model.session && timeout > 0) model.session.call("application.exit.later", [timeout]);
		if (model.connection) model.connection.close();
		model.connection = null;
	}
	publicAPI.destroy = CompositeClosureHelper_default.chain(cleanUp, publicAPI.destroy);
}
var DEFAULT_VALUES$4 = {
	secret: DEFAULT_SECRET,
	connection: null,
	session: null,
	retry: false,
	wsProxy: false
};
function extend$4(publicAPI, model, initialValues = {}) {
	Object.assign(model, DEFAULT_VALUES$4, initialValues);
	CompositeClosureHelper_default.destroy(publicAPI, model);
	CompositeClosureHelper_default.event(publicAPI, model, "ConnectionReady");
	CompositeClosureHelper_default.event(publicAPI, model, "ConnectionClose");
	CompositeClosureHelper_default.event(publicAPI, model, "ConnectionError");
	CompositeClosureHelper_default.isA(publicAPI, model, "WebsocketConnection");
	WebsocketConnection(publicAPI, model);
}
var WebsocketConnection_default = {
	newInstance: CompositeClosureHelper_default.newInstance(extend$4),
	extend: extend$4
};
//#endregion
//#region node_modules/wslink/src/SmartConnect/index.js
function DEFAULT_CONFIG_DECORATOR(config) {
	if (config.sessionURL) {
		config.sessionURL = config.sessionURL.replaceAll("USE_HOSTNAME", window.location.hostname);
		config.sessionURL = config.sessionURL.replaceAll("USE_HOST", window.location.host);
	}
	return config;
}
function extractPathName(addOn, pathName = window.location.pathname) {
	if (pathName.endsWith(".html") || pathName.endsWith(".htm")) {
		const tokens = pathName.split("/");
		tokens.pop();
		pathName = tokens.join("/");
	}
	while (pathName.length > 0 && pathName[pathName.length - 1] === "/") pathName = pathName.substring(0, pathName.length - 1);
	if (pathName.length === 0) return addOn;
	return `${pathName}${addOn}`;
}
var DEFAULT_SESSION_MANAGER_URL = `${document.baseURI}paraview/`;
var DEFAULT_SESSION_URL = `${window.location.protocol === "https:" ? "wss:" : "ws:"}//${window.location.hostname}:${window.location.port}${extractPathName("/ws")}`;
function wsConnect(publicAPI, model) {
	const wsConnection = WebsocketConnection_default.newInstance({
		urls: model.config.sessionURL,
		secret: model.config.secret,
		retry: model.config.retry,
		wsProxy: model.config.iframe || model.config.wsProxy
	});
	model.subscriptions.push(wsConnection.onConnectionReady(publicAPI.readyForwarder));
	model.subscriptions.push(wsConnection.onConnectionError(publicAPI.errorForwarder));
	model.subscriptions.push(wsConnection.onConnectionClose(publicAPI.closeForwarder));
	model.gc.push(wsConnection);
	return wsConnection.connect();
}
function smartConnect(publicAPI, model) {
	let session = null;
	model.gc = [];
	publicAPI.readyForwarder = (data) => {
		session = data.getSession();
		publicAPI.fireConnectionReady(data);
	};
	publicAPI.errorForwarder = (data, err) => {
		publicAPI.fireConnectionError(data, err);
	};
	publicAPI.closeForwarder = (data, err) => {
		publicAPI.fireConnectionClose(data, err);
	};
	publicAPI.connect = () => {
		if (model.configDecorator) model.config = model.configDecorator(model.config);
		model.config = DEFAULT_CONFIG_DECORATOR(model.config);
		if (model.config.sessionURL) session = wsConnect(publicAPI, model);
		else if (model.config.wsProxy) {
			model.config.sessionURL = model.config.sessionURL || "wss://proxy/";
			session = wsConnect(publicAPI, model);
		} else {
			const launcher = ProcessLauncher_default.newInstance({ endPoint: model.config.sessionManagerURL || DEFAULT_SESSION_MANAGER_URL });
			model.subscriptions.push(launcher.onProcessReady((data) => {
				if (model.configDecorator) model.config = model.configDecorator(Object.assign({}, model.config, data));
				else model.config = Object.assign({}, model.config, data);
				model.config = DEFAULT_CONFIG_DECORATOR(model.config);
				session = wsConnect(publicAPI, model);
			}));
			model.subscriptions.push(launcher.onError((data) => {
				if (data && data.response && data.response.error) publicAPI.errorForwarder(data, data.response.error);
				else {
					model.config.sessionURL = DEFAULT_SESSION_URL;
					model.config = DEFAULT_CONFIG_DECORATOR(model.config);
					session = wsConnect(publicAPI, model);
				}
			}));
			launcher.start(model.config);
			model.gc.push(launcher);
		}
	};
	publicAPI.getSession = () => {
		return session;
	};
	function cleanUp(timeout) {
		if (session) {
			if (timeout > 0) session.call("application.exit.later", [timeout]);
			session.close();
		}
		session = null;
		while (model.gc.length) model.gc.pop().destroy();
	}
	publicAPI.destroy = CompositeClosureHelper_default.chain(cleanUp, publicAPI.destroy);
}
var DEFAULT_VALUES$3 = { config: {} };
function extend$3(publicAPI, model, initialValues = {}) {
	Object.assign(model, DEFAULT_VALUES$3, initialValues);
	CompositeClosureHelper_default.destroy(publicAPI, model);
	CompositeClosureHelper_default.event(publicAPI, model, "ConnectionReady");
	CompositeClosureHelper_default.event(publicAPI, model, "ConnectionClose");
	CompositeClosureHelper_default.event(publicAPI, model, "ConnectionError");
	CompositeClosureHelper_default.isA(publicAPI, model, "SmartConnect");
	CompositeClosureHelper_default.get(publicAPI, model, ["config", "configDecorator"]);
	CompositeClosureHelper_default.set(publicAPI, model, ["configDecorator"]);
	smartConnect(publicAPI, model);
}
var SmartConnect_default = {
	newInstance: CompositeClosureHelper_default.newInstance(extend$3),
	extend: extend$3
};
//#endregion
//#region node_modules/fast-deep-equal/index.js
var require_fast_deep_equal = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	module.exports = function equal(a, b) {
		if (a === b) return true;
		if (a && b && typeof a == "object" && typeof b == "object") {
			if (a.constructor !== b.constructor) return false;
			var length, i, keys;
			if (Array.isArray(a)) {
				length = a.length;
				if (length != b.length) return false;
				for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false;
				return true;
			}
			if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
			if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
			if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
			keys = Object.keys(a);
			length = keys.length;
			if (length !== Object.keys(b).length) return false;
			for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
			for (i = length; i-- !== 0;) {
				var key = keys[i];
				if (!equal(a[key], b[key])) return false;
			}
			return true;
		}
		return a !== a && b !== b;
	};
}));
//#endregion
//#region node_modules/object-keys/isArguments.js
var require_isArguments = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var toStr = Object.prototype.toString;
	module.exports = function isArguments(value) {
		var str = toStr.call(value);
		var isArgs = str === "[object Arguments]";
		if (!isArgs) isArgs = str !== "[object Array]" && value !== null && typeof value === "object" && typeof value.length === "number" && value.length >= 0 && toStr.call(value.callee) === "[object Function]";
		return isArgs;
	};
}));
//#endregion
//#region node_modules/object-keys/implementation.js
var require_implementation = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var keysShim;
	if (!Object.keys) {
		var has = Object.prototype.hasOwnProperty;
		var toStr = Object.prototype.toString;
		var isArgs = require_isArguments();
		var isEnumerable = Object.prototype.propertyIsEnumerable;
		var hasDontEnumBug = !isEnumerable.call({ toString: null }, "toString");
		var hasProtoEnumBug = isEnumerable.call(function() {}, "prototype");
		var dontEnums = [
			"toString",
			"toLocaleString",
			"valueOf",
			"hasOwnProperty",
			"isPrototypeOf",
			"propertyIsEnumerable",
			"constructor"
		];
		var equalsConstructorPrototype = function(o) {
			var ctor = o.constructor;
			return ctor && ctor.prototype === o;
		};
		var excludedKeys = {
			$applicationCache: true,
			$console: true,
			$external: true,
			$frame: true,
			$frameElement: true,
			$frames: true,
			$innerHeight: true,
			$innerWidth: true,
			$onmozfullscreenchange: true,
			$onmozfullscreenerror: true,
			$outerHeight: true,
			$outerWidth: true,
			$pageXOffset: true,
			$pageYOffset: true,
			$parent: true,
			$scrollLeft: true,
			$scrollTop: true,
			$scrollX: true,
			$scrollY: true,
			$self: true,
			$webkitIndexedDB: true,
			$webkitStorageInfo: true,
			$window: true
		};
		var hasAutomationEqualityBug = function() {
			if (typeof window === "undefined") return false;
			for (var k in window) try {
				if (!excludedKeys["$" + k] && has.call(window, k) && window[k] !== null && typeof window[k] === "object") try {
					equalsConstructorPrototype(window[k]);
				} catch (e) {
					return true;
				}
			} catch (e) {
				return true;
			}
			return false;
		}();
		var equalsConstructorPrototypeIfNotBuggy = function(o) {
			if (typeof window === "undefined" || !hasAutomationEqualityBug) return equalsConstructorPrototype(o);
			try {
				return equalsConstructorPrototype(o);
			} catch (e) {
				return false;
			}
		};
		keysShim = function keys(object) {
			var isObject = object !== null && typeof object === "object";
			var isFunction = toStr.call(object) === "[object Function]";
			var isArguments = isArgs(object);
			var isString = isObject && toStr.call(object) === "[object String]";
			var theKeys = [];
			if (!isObject && !isFunction && !isArguments) throw new TypeError("Object.keys called on a non-object");
			var skipProto = hasProtoEnumBug && isFunction;
			if (isString && object.length > 0 && !has.call(object, 0)) for (var i = 0; i < object.length; ++i) theKeys.push(String(i));
			if (isArguments && object.length > 0) for (var j = 0; j < object.length; ++j) theKeys.push(String(j));
			else for (var name in object) if (!(skipProto && name === "prototype") && has.call(object, name)) theKeys.push(String(name));
			if (hasDontEnumBug) {
				var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
				for (var k = 0; k < dontEnums.length; ++k) if (!(skipConstructor && dontEnums[k] === "constructor") && has.call(object, dontEnums[k])) theKeys.push(dontEnums[k]);
			}
			return theKeys;
		};
	}
	module.exports = keysShim;
}));
//#endregion
//#region node_modules/object-keys/index.js
var require_object_keys = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var slice = Array.prototype.slice;
	var isArgs = require_isArguments();
	var origKeys = Object.keys;
	var keysShim = origKeys ? function keys(o) {
		return origKeys(o);
	} : require_implementation();
	var originalKeys = Object.keys;
	keysShim.shim = function shimObjectKeys() {
		if (Object.keys) {
			if (!function() {
				var args = Object.keys(arguments);
				return args && args.length === arguments.length;
			}(1, 2)) Object.keys = function keys(object) {
				if (isArgs(object)) return originalKeys(slice.call(object));
				return originalKeys(object);
			};
		} else Object.keys = keysShim;
		return Object.keys || keysShim;
	};
	module.exports = keysShim;
}));
//#endregion
//#region node_modules/es-define-property/index.js
var require_es_define_property = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/** @type {import('.')} */
	var $defineProperty = Object.defineProperty || false;
	if ($defineProperty) try {
		$defineProperty({}, "a", { value: 1 });
	} catch (e) {
		$defineProperty = false;
	}
	module.exports = $defineProperty;
}));
//#endregion
//#region node_modules/es-errors/syntax.js
var require_syntax = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/** @type {import('./syntax')} */
	module.exports = SyntaxError;
}));
//#endregion
//#region node_modules/es-errors/type.js
var require_type = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/** @type {import('./type')} */
	module.exports = TypeError;
}));
//#endregion
//#region node_modules/gopd/gOPD.js
var require_gOPD = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/** @type {import('./gOPD')} */
	module.exports = Object.getOwnPropertyDescriptor;
}));
//#endregion
//#region node_modules/gopd/index.js
var require_gopd = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	/** @type {import('.')} */
	var $gOPD = require_gOPD();
	if ($gOPD) try {
		$gOPD([], "length");
	} catch (e) {
		$gOPD = null;
	}
	module.exports = $gOPD;
}));
//#endregion
//#region node_modules/define-data-property/index.js
var require_define_data_property = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var $defineProperty = require_es_define_property();
	var $SyntaxError = require_syntax();
	var $TypeError = require_type();
	var gopd = require_gopd();
	/** @type {import('.')} */
	module.exports = function defineDataProperty(obj, property, value) {
		if (!obj || typeof obj !== "object" && typeof obj !== "function") throw new $TypeError("`obj` must be an object or a function`");
		if (typeof property !== "string" && typeof property !== "symbol") throw new $TypeError("`property` must be a string or a symbol`");
		if (arguments.length > 3 && typeof arguments[3] !== "boolean" && arguments[3] !== null) throw new $TypeError("`nonEnumerable`, if provided, must be a boolean or null");
		if (arguments.length > 4 && typeof arguments[4] !== "boolean" && arguments[4] !== null) throw new $TypeError("`nonWritable`, if provided, must be a boolean or null");
		if (arguments.length > 5 && typeof arguments[5] !== "boolean" && arguments[5] !== null) throw new $TypeError("`nonConfigurable`, if provided, must be a boolean or null");
		if (arguments.length > 6 && typeof arguments[6] !== "boolean") throw new $TypeError("`loose`, if provided, must be a boolean");
		var nonEnumerable = arguments.length > 3 ? arguments[3] : null;
		var nonWritable = arguments.length > 4 ? arguments[4] : null;
		var nonConfigurable = arguments.length > 5 ? arguments[5] : null;
		var loose = arguments.length > 6 ? arguments[6] : false;
		var desc = !!gopd && gopd(obj, property);
		if ($defineProperty) $defineProperty(obj, property, {
			configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable,
			enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable,
			value,
			writable: nonWritable === null && desc ? desc.writable : !nonWritable
		});
		else if (loose || !nonEnumerable && !nonWritable && !nonConfigurable) obj[property] = value;
		else throw new $SyntaxError("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");
	};
}));
//#endregion
//#region node_modules/has-property-descriptors/index.js
var require_has_property_descriptors = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var $defineProperty = require_es_define_property();
	var hasPropertyDescriptors = function hasPropertyDescriptors() {
		return !!$defineProperty;
	};
	hasPropertyDescriptors.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() {
		if (!$defineProperty) return null;
		try {
			return $defineProperty([], "length", { value: 1 }).length !== 1;
		} catch (e) {
			return true;
		}
	};
	module.exports = hasPropertyDescriptors;
}));
//#endregion
//#region node_modules/define-properties/index.js
var require_define_properties = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var keys = require_object_keys();
	var hasSymbols = typeof Symbol === "function" && typeof Symbol("foo") === "symbol";
	var toStr = Object.prototype.toString;
	var concat = Array.prototype.concat;
	var defineDataProperty = require_define_data_property();
	var isFunction = function(fn) {
		return typeof fn === "function" && toStr.call(fn) === "[object Function]";
	};
	var supportsDescriptors = require_has_property_descriptors()();
	var defineProperty = function(object, name, value, predicate) {
		if (name in object) {
			if (predicate === true) {
				if (object[name] === value) return;
			} else if (!isFunction(predicate) || !predicate()) return;
		}
		if (supportsDescriptors) defineDataProperty(object, name, value, true);
		else defineDataProperty(object, name, value);
	};
	var defineProperties = function(object, map) {
		var predicates = arguments.length > 2 ? arguments[2] : {};
		var props = keys(map);
		if (hasSymbols) props = concat.call(props, Object.getOwnPropertySymbols(map));
		for (var i = 0; i < props.length; i += 1) defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
	};
	defineProperties.supportsDescriptors = !!supportsDescriptors;
	module.exports = defineProperties;
}));
//#endregion
//#region node_modules/globalthis/implementation.browser.js
var require_implementation_browser = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	if (typeof self !== "undefined") module.exports = self;
	else if (typeof window !== "undefined") module.exports = window;
	else module.exports = Function("return this")();
}));
//#endregion
//#region node_modules/globalthis/polyfill.js
var require_polyfill = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var implementation = require_implementation_browser();
	module.exports = function getPolyfill() {
		if (typeof global !== "object" || !global || global.Math !== Math || global.Array !== Array) return implementation;
		return global;
	};
}));
//#endregion
//#region node_modules/globalthis/shim.js
var require_shim = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var define = require_define_properties();
	var getPolyfill = require_polyfill();
	module.exports = function shimGlobal() {
		var polyfill = getPolyfill();
		if (define.supportsDescriptors) {
			var descriptor = Object.getOwnPropertyDescriptor(polyfill, "globalThis");
			if (!descriptor || descriptor.configurable && (descriptor.enumerable || !descriptor.writable || globalThis !== polyfill)) Object.defineProperty(polyfill, "globalThis", {
				configurable: true,
				enumerable: false,
				value: polyfill,
				writable: true
			});
		} else if (typeof globalThis !== "object" || globalThis !== polyfill) polyfill.globalThis = polyfill;
		return polyfill;
	};
}));
//#endregion
//#region node_modules/globalthis/index.js
var require_globalthis = /* @__PURE__ */ __commonJSMin(((exports, module) => {
	var defineProperties = require_define_properties();
	var implementation = require_implementation_browser();
	var getPolyfill = require_polyfill();
	var shim = require_shim();
	var polyfill = getPolyfill();
	var getGlobal = function() {
		return polyfill;
	};
	defineProperties(getGlobal, {
		getPolyfill,
		implementation,
		shim
	});
	module.exports = getGlobal;
}));
//#endregion
//#region node_modules/@kitware/vtk.js/vtk.js
var import_fast_deep_equal = /* @__PURE__ */ __toESM(require_fast_deep_equal(), 1);
var vtkGlobal = (0, (/* @__PURE__ */ __toESM(require_globalthis(), 1)).default)();
var factoryMapping = { vtkObject: () => null };
function vtk(obj) {
	if (obj === null || obj === void 0) return obj;
	if (obj.isA) return obj;
	if (!obj.vtkClass) {
		if (vtkGlobal.console && vtkGlobal.console.error) vtkGlobal.console.error("Invalid VTK object");
		return null;
	}
	const constructor = factoryMapping[obj.vtkClass];
	if (!constructor) {
		if (vtkGlobal.console && vtkGlobal.console.error) vtkGlobal.console.error(`No vtk class found for Object of type ${obj.vtkClass}`);
		return null;
	}
	const model = { ...obj };
	Object.keys(model).forEach((keyName) => {
		if (model[keyName] && typeof model[keyName] === "object" && model[keyName].vtkClass) model[keyName] = vtk(model[keyName]);
	});
	const newInst = constructor(model);
	if (newInst && newInst.modified) newInst.modified();
	return newInst;
}
function register(vtkClassName, constructor) {
	factoryMapping[vtkClassName] = constructor;
}
vtk.register = register;
//#endregion
//#region node_modules/@kitware/vtk.js/Common/Core/ClassHierarchy.js
var ClassHierarchy = class extends Array {
	push() {
		for (let i = 0; i < arguments.length; i++) if (!this.includes(arguments[i])) super.push(arguments[i]);
		return this.length;
	}
};
//#endregion
//#region node_modules/@kitware/vtk.js/macros2.js
/**
* macros.js is the old macro.js.
* The name change is so we do not get eaten by babel-plugin-macros.
*/
var globalMTime = 0;
var requiredParam = (name) => {
	throw new Error(`Named parameter '${name}' is missing`);
};
var VOID = Symbol("void");
function getCurrentGlobalMTime() {
	return globalMTime;
}
var fakeConsole = {};
function noOp() {}
[
	"log",
	"debug",
	"info",
	"warn",
	"error",
	"time",
	"timeEnd",
	"group",
	"groupEnd"
].forEach((methodName) => {
	fakeConsole[methodName] = noOp;
});
vtkGlobal.console = console.hasOwnProperty("log") ? console : fakeConsole;
var loggerFunctions = {
	debug: noOp,
	error: vtkGlobal.console.error || noOp,
	info: vtkGlobal.console.info || noOp,
	log: vtkGlobal.console.log || noOp,
	warn: vtkGlobal.console.warn || noOp
};
function setLoggerFunction(name, fn) {
	if (loggerFunctions[name]) loggerFunctions[name] = fn || noOp;
}
function vtkLogMacro(...args) {
	loggerFunctions.log(...args);
}
function vtkInfoMacro(...args) {
	loggerFunctions.info(...args);
}
function vtkDebugMacro(...args) {
	loggerFunctions.debug(...args);
}
function vtkErrorMacro(...args) {
	loggerFunctions.error(...args);
}
function vtkWarningMacro(...args) {
	loggerFunctions.warn(...args);
}
var ERROR_ONCE_MAP = {};
function vtkOnceErrorMacro(str) {
	if (!ERROR_ONCE_MAP[str]) {
		loggerFunctions.error(str);
		ERROR_ONCE_MAP[str] = true;
	}
}
var TYPED_ARRAYS = Object.create(null);
TYPED_ARRAYS.Float32Array = Float32Array;
TYPED_ARRAYS.Float64Array = Float64Array;
TYPED_ARRAYS.Uint8Array = Uint8Array;
TYPED_ARRAYS.Int8Array = Int8Array;
TYPED_ARRAYS.Uint16Array = Uint16Array;
TYPED_ARRAYS.Int16Array = Int16Array;
TYPED_ARRAYS.Uint32Array = Uint32Array;
TYPED_ARRAYS.Int32Array = Int32Array;
TYPED_ARRAYS.Uint8ClampedArray = Uint8ClampedArray;
try {
	TYPED_ARRAYS.BigInt64Array = BigInt64Array;
	TYPED_ARRAYS.BigUint64Array = BigUint64Array;
} catch {}
function newTypedArray(type, ...args) {
	return new (TYPED_ARRAYS[type] || Float64Array)(...args);
}
function newTypedArrayFrom(type, ...args) {
	return (TYPED_ARRAYS[type] || Float64Array).from(...args);
}
function capitalize(str) {
	return str.charAt(0).toUpperCase() + str.slice(1);
}
function _capitalize(str) {
	return capitalize(str[0] === "_" ? str.slice(1) : str);
}
function uncapitalize(str) {
	return str.charAt(0).toLowerCase() + str.slice(1);
}
function formatBytesToProperUnit(size, precision = 2, chunkSize = 1e3) {
	const units = [
		"TB",
		"GB",
		"MB",
		"KB"
	];
	let value = Number(size);
	let currentUnit = "B";
	while (value > chunkSize) {
		value /= chunkSize;
		currentUnit = units.pop();
	}
	return `${value.toFixed(precision)} ${currentUnit}`;
}
function formatNumbersWithThousandSeparator(n, separator = " ") {
	const sections = [];
	let size = n;
	while (size > 1e3) {
		sections.push(`000${size % 1e3}`.slice(-3));
		size = Math.floor(size / 1e3);
	}
	if (size > 0) sections.push(size);
	sections.reverse();
	return sections.join(separator);
}
function safeArrays(model) {
	Object.keys(model).forEach((key) => {
		if (Array.isArray(model[key])) model[key] = [].concat(model[key]);
	});
}
function isTypedArray(value) {
	return Object.values(TYPED_ARRAYS).some((ctor) => value instanceof ctor);
}
function shallowEquals(a, b) {
	if (a === b) return true;
	if (Array.isArray(a) && Array.isArray(b)) {
		if (a.length !== b.length) return false;
		for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
		return true;
	}
	return false;
}
function enumToString(e, value) {
	return Object.keys(e).find((key) => e[key] === value);
}
function getStateArrayMapFunc(item) {
	if (item && item.isA) return item.getState();
	return item;
}
function setImmediateVTK(fn) {
	setTimeout(fn, 0);
}
function measurePromiseExecution(promise, callback) {
	const start = performance.now();
	promise.finally(() => {
		callback(performance.now() - start);
	});
}
function obj(publicAPI = {}, model = {}) {
	safeArrays(model);
	const callbacks = [];
	if (!Number.isInteger(model.mtime)) model.mtime = ++globalMTime;
	if (!("classHierarchy" in model)) model.classHierarchy = new ClassHierarchy("vtkObject");
	else if (!(model.classHierarchy instanceof ClassHierarchy)) {
		const hierarchy = new ClassHierarchy();
		for (let i = 0; i < model.classHierarchy.length; i++) hierarchy.push(model.classHierarchy[i]);
		model.classHierarchy = hierarchy;
	}
	function off(index) {
		callbacks[index] = null;
	}
	function on(index) {
		function unsubscribe() {
			off(index);
		}
		return Object.freeze({ unsubscribe });
	}
	publicAPI.isDeleted = () => !!model.deleted;
	publicAPI.modified = (otherMTime) => {
		if (model.deleted) {
			vtkErrorMacro("instance deleted - cannot call any method");
			return;
		}
		if (otherMTime && otherMTime < publicAPI.getMTime()) return;
		model.mtime = ++globalMTime;
		callbacks.forEach((callback) => callback && callback(publicAPI));
	};
	publicAPI.onModified = (callback) => {
		if (model.deleted) {
			vtkErrorMacro("instance deleted - cannot call any method");
			return null;
		}
		const index = callbacks.length;
		callbacks.push(callback);
		return on(index);
	};
	publicAPI.getMTime = () => model.mtime;
	publicAPI.isA = (className) => {
		let count = model.classHierarchy.length;
		while (count--) if (model.classHierarchy[count] === className) return true;
		return false;
	};
	publicAPI.getClassName = (depth = 0) => model.classHierarchy[model.classHierarchy.length - 1 - depth];
	publicAPI.set = (map = {}, noWarning = false, noFunction = false) => {
		let ret = false;
		Object.keys(map).forEach((name) => {
			const fn = noFunction ? null : publicAPI[`set${capitalize(name)}`];
			if (fn && Array.isArray(map[name]) && fn.length > 1) ret = fn(...map[name]) || ret;
			else if (fn) ret = fn(map[name]) || ret;
			else {
				if (["mtime"].indexOf(name) === -1 && !noWarning) vtkWarningMacro(`Warning: Set value to model directly ${name}, ${map[name]}`);
				ret = model[name] !== map[name] || ret;
				model[name] = map[name];
			}
		});
		return ret;
	};
	publicAPI.get = (...list) => {
		if (!list.length) return model;
		const subset = {};
		list.forEach((name) => {
			subset[name] = model[name];
		});
		return subset;
	};
	publicAPI.getReferenceByName = (val) => model[val];
	publicAPI.delete = () => {
		Object.keys(model).forEach((field) => delete model[field]);
		callbacks.forEach((el, index) => off(index));
		model.deleted = true;
	};
	publicAPI.getState = ({ preserveTypedArrays = false } = {}) => {
		if (model.deleted) return null;
		const options = { preserveTypedArrays };
		const jsonArchive = {
			...model,
			vtkClass: publicAPI.getClassName()
		};
		Object.keys(jsonArchive).forEach((keyName) => {
			if (jsonArchive[keyName] === null || jsonArchive[keyName] === void 0 || keyName[0] === "_") delete jsonArchive[keyName];
			else if (jsonArchive[keyName].isA) jsonArchive[keyName] = jsonArchive[keyName].getState(options);
			else if (Array.isArray(jsonArchive[keyName])) jsonArchive[keyName] = jsonArchive[keyName].map((item) => item && item.isA ? item.getState(options) : item);
			else if (isTypedArray(jsonArchive[keyName])) {
				if (!preserveTypedArrays) jsonArchive[keyName] = Array.from(jsonArchive[keyName]);
			}
		});
		const sortedObj = {};
		Object.keys(jsonArchive).sort().forEach((name) => {
			sortedObj[name] = jsonArchive[name];
		});
		if (sortedObj.mtime) delete sortedObj.mtime;
		return sortedObj;
	};
	publicAPI.shallowCopy = (other, debug = false) => {
		if (other.getClassName() !== publicAPI.getClassName()) throw new Error(`Cannot ShallowCopy ${other.getClassName()} into ${publicAPI.getClassName()}`);
		const otherModel = other.get();
		const keyList = Object.keys(model).sort();
		Object.keys(otherModel).sort().forEach((key) => {
			const keyIdx = keyList.indexOf(key);
			if (keyIdx === -1) {
				if (debug) vtkDebugMacro(`add ${key} in shallowCopy`);
			} else keyList.splice(keyIdx, 1);
			model[key] = otherModel[key];
		});
		if (keyList.length && debug) vtkDebugMacro(`Untouched keys: ${keyList.join(", ")}`);
		publicAPI.modified();
	};
	publicAPI.toJSON = function vtkObjToJSON() {
		return publicAPI.getState();
	};
	return publicAPI;
}
var objectGetterMap = { object(publicAPI, model, field) {
	return function getter() {
		return { ...model[field.name] };
	};
} };
function get$1(publicAPI, model, fieldNames) {
	fieldNames.forEach((field) => {
		if (typeof field === "object") {
			const getter = objectGetterMap[field.type];
			if (getter) publicAPI[`get${_capitalize(field.name)}`] = getter(publicAPI, model, field);
			else publicAPI[`get${_capitalize(field.name)}`] = () => model[field.name];
		} else publicAPI[`get${_capitalize(field)}`] = () => model[field];
	});
}
var objectSetterMap = {
	enum(publicAPI, model, field) {
		const onChanged = `_on${_capitalize(field.name)}Changed`;
		return (value) => {
			if (typeof value === "string") {
				if (field.enum[value] !== void 0) {
					if (model[field.name] !== field.enum[value]) {
						model[field.name] = field.enum[value];
						publicAPI.modified();
						return true;
					}
					return false;
				}
				vtkErrorMacro(`Set Enum with invalid argument ${field}, ${value}`);
				throw new RangeError("Set Enum with invalid string argument");
			}
			if (typeof value === "number") {
				if (model[field.name] !== value) {
					if (Object.keys(field.enum).map((key) => field.enum[key]).indexOf(value) !== -1) {
						const previousValue = model[field.name];
						model[field.name] = value;
						model[onChanged]?.(publicAPI, model, value, previousValue);
						publicAPI.modified();
						return true;
					}
					vtkErrorMacro(`Set Enum outside numeric range ${field}, ${value}`);
					throw new RangeError("Set Enum outside numeric range");
				}
				return false;
			}
			vtkErrorMacro(`Set Enum with invalid argument (String/Number) ${field}, ${value}`);
			throw new TypeError("Set Enum with invalid argument (String/Number)");
		};
	},
	object(publicAPI, model, field) {
		if (field.params?.length === 1) vtkWarningMacro("Setter of type \"object\" with a single \"param\" field is not supported");
		const onChanged = `_on${_capitalize(field.name)}Changed`;
		return (...args) => {
			let value;
			if (args.length > 1 && field.params?.length) value = field.params.reduce((acc, prop, idx) => Object.assign(acc, { [prop]: args[idx] }), {});
			else value = args[0];
			if (!(0, import_fast_deep_equal.default)(model[field.name], value)) {
				const previousValue = model[field.name];
				model[field.name] = value;
				model[onChanged]?.(publicAPI, model, value, previousValue);
				publicAPI.modified();
				return true;
			}
			return false;
		};
	}
};
function findSetter(field) {
	if (typeof field === "object") {
		const fn = objectSetterMap[field.type];
		if (fn) return (publicAPI, model) => fn(publicAPI, model, field);
		vtkErrorMacro(`No setter for field ${field}`);
		throw new TypeError("No setter for field");
	}
	return function getSetter(publicAPI, model) {
		const onChanged = `_on${_capitalize(field)}Changed`;
		return function setter(value) {
			if (model.deleted) {
				vtkErrorMacro("instance deleted - cannot call any method");
				return false;
			}
			if (model[field] !== value) {
				const previousValue = model[field.name];
				model[field] = value;
				model[onChanged]?.(publicAPI, model, value, previousValue);
				publicAPI.modified();
				return true;
			}
			return false;
		};
	};
}
function set(publicAPI, model, fields) {
	fields.forEach((field) => {
		if (typeof field === "object") publicAPI[`set${_capitalize(field.name)}`] = findSetter(field)(publicAPI, model);
		else publicAPI[`set${_capitalize(field)}`] = findSetter(field)(publicAPI, model);
	});
}
function setGet(publicAPI, model, fieldNames) {
	get$1(publicAPI, model, fieldNames);
	set(publicAPI, model, fieldNames);
}
function getArray(publicAPI, model, fieldNames) {
	fieldNames.forEach((field) => {
		publicAPI[`get${_capitalize(field)}`] = () => model[field] ? Array.from(model[field]) : model[field];
		publicAPI[`get${_capitalize(field)}ByReference`] = () => model[field];
	});
}
function setArray(publicAPI, model, fieldNames, size, defaultVal = void 0) {
	fieldNames.forEach((field) => {
		if (model[field] && size && model[field].length !== size) throw new RangeError(`Invalid initial number of values for array (${field})`);
		const onChanged = `_on${_capitalize(field)}Changed`;
		publicAPI[`set${_capitalize(field)}`] = (...args) => {
			if (model.deleted) {
				vtkErrorMacro("instance deleted - cannot call any method");
				return false;
			}
			let array = args;
			let changeDetected;
			let needCopy = false;
			if (array.length === 1 && (array[0] == null || array[0].length >= 0)) {
				array = array[0];
				needCopy = true;
			}
			if (array == null) changeDetected = model[field] !== array;
			else {
				if (size && array.length !== size) if (array.length < size && defaultVal !== void 0) {
					array = Array.from(array);
					needCopy = false;
					while (array.length < size) array.push(defaultVal);
				} else throw new RangeError(`Invalid number of values for array setter (${field})`);
				changeDetected = model[field] == null || model[field].length !== array.length;
				for (let i = 0; !changeDetected && i < array.length; ++i) changeDetected = model[field][i] !== array[i];
				if (changeDetected && needCopy) array = Array.from(array);
			}
			if (changeDetected) {
				const previousValue = model[field.name];
				model[field] = array;
				model[onChanged]?.(publicAPI, model, array, previousValue);
				publicAPI.modified();
			}
			return changeDetected;
		};
		publicAPI[`set${_capitalize(field)}From`] = (otherArray) => {
			const target = model[field];
			otherArray.forEach((v, i) => {
				target[i] = v;
			});
		};
	});
}
function setGetArray(publicAPI, model, fieldNames, size, defaultVal = void 0) {
	getArray(publicAPI, model, fieldNames);
	setArray(publicAPI, model, fieldNames, size, defaultVal);
}
function moveToProtected(publicAPI, model, fieldNames) {
	for (let i = 0; i < fieldNames.length; i++) {
		const fieldName = fieldNames[i];
		if (model[fieldName] !== void 0) {
			model[`_${fieldName}`] = model[fieldName];
			delete model[fieldName];
		}
	}
}
function algo(publicAPI, model, numberOfInputs, numberOfOutputs) {
	if (model.inputData) model.inputData = model.inputData.map(vtk);
	else model.inputData = [];
	if (model.inputConnection) model.inputConnection = model.inputConnection.map(vtk);
	else model.inputConnection = [];
	if (model.output) model.output = model.output.map(vtk);
	else model.output = [];
	if (model.inputArrayToProcess) model.inputArrayToProcess = model.inputArrayToProcess.map(vtk);
	else model.inputArrayToProcess = [];
	model.numberOfInputs = numberOfInputs;
	function setInputData(dataset, port = 0) {
		if (model.deleted) {
			vtkErrorMacro("instance deleted - cannot call any method");
			return;
		}
		if (port >= model.numberOfInputs) {
			vtkErrorMacro(`algorithm ${publicAPI.getClassName()} only has ${model.numberOfInputs} input ports. To add more input ports, use addInputData()`);
			return;
		}
		if (model.inputData[port] !== dataset || model.inputConnection[port]) {
			model.inputData[port] = dataset;
			model.inputConnection[port] = null;
			if (publicAPI.modified) publicAPI.modified();
		}
	}
	function getInputData(port = 0) {
		if (model.inputConnection[port]) model.inputData[port] = model.inputConnection[port]();
		return model.inputData[port];
	}
	function setInputConnection(outputPort, port = 0) {
		if (model.deleted) {
			vtkErrorMacro("instance deleted - cannot call any method");
			return;
		}
		if (port >= model.numberOfInputs) {
			let msg = `algorithm ${publicAPI.getClassName()} only has `;
			msg += `${model.numberOfInputs}`;
			msg += " input ports. To add more input ports, use addInputConnection()";
			vtkErrorMacro(msg);
			return;
		}
		model.inputData[port] = null;
		model.inputConnection[port] = outputPort;
	}
	function getInputConnection(port = 0) {
		return model.inputConnection[port];
	}
	function getPortToFill() {
		let portToFill = model.numberOfInputs;
		while (portToFill && !model.inputData[portToFill - 1] && !model.inputConnection[portToFill - 1]) portToFill--;
		if (portToFill === model.numberOfInputs) model.numberOfInputs++;
		return portToFill;
	}
	function addInputConnection(outputPort) {
		if (model.deleted) {
			vtkErrorMacro("instance deleted - cannot call any method");
			return;
		}
		setInputConnection(outputPort, getPortToFill());
	}
	function addInputData(dataset) {
		if (model.deleted) {
			vtkErrorMacro("instance deleted - cannot call any method");
			return;
		}
		setInputData(dataset, getPortToFill());
	}
	function getOutputData(port = 0) {
		if (model.deleted) {
			vtkErrorMacro("instance deleted - cannot call any method");
			return null;
		}
		if (publicAPI.shouldUpdate()) publicAPI.update();
		return model.output[port];
	}
	publicAPI.shouldUpdate = () => {
		const localMTime = publicAPI.getMTime();
		let minOutputMTime = Infinity;
		let count = numberOfOutputs;
		while (count--) {
			if (!model.output[count] || model.output[count].isDeleted()) return true;
			const mt = model.output[count].getMTime();
			if (mt < localMTime) return true;
			if (mt < minOutputMTime) minOutputMTime = mt;
		}
		count = model.numberOfInputs;
		while (count--) if (model.inputConnection[count]?.filter.shouldUpdate() || publicAPI.getInputData(count)?.getMTime() > minOutputMTime) return true;
		return false;
	};
	function getOutputPort(port = 0) {
		const outputPortAccess = () => getOutputData(port);
		outputPortAccess.filter = publicAPI;
		return outputPortAccess;
	}
	if (model.numberOfInputs) {
		let count = model.numberOfInputs;
		while (count--) {
			model.inputData.push(null);
			model.inputConnection.push(null);
		}
		publicAPI.setInputData = setInputData;
		publicAPI.setInputConnection = setInputConnection;
		publicAPI.addInputData = addInputData;
		publicAPI.addInputConnection = addInputConnection;
		publicAPI.getInputData = getInputData;
		publicAPI.getInputConnection = getInputConnection;
	}
	if (numberOfOutputs) {
		publicAPI.getOutputData = getOutputData;
		publicAPI.getOutputPort = getOutputPort;
	}
	publicAPI.update = () => {
		const ins = [];
		if (model.numberOfInputs) {
			let count = 0;
			while (count < model.numberOfInputs) {
				ins[count] = publicAPI.getInputData(count);
				count++;
			}
		}
		if (publicAPI.requestData && !publicAPI.isDeleted() && publicAPI.shouldUpdate()) publicAPI.requestData(ins, model.output);
	};
	publicAPI.getNumberOfInputPorts = () => model.numberOfInputs;
	publicAPI.getNumberOfOutputPorts = () => numberOfOutputs || model.output.length;
	publicAPI.getInputArrayToProcess = (inputPort) => {
		const arrayDesc = model.inputArrayToProcess[inputPort];
		const ds = model.inputData[inputPort];
		if (arrayDesc && ds) return ds[`get${arrayDesc.fieldAssociation}`]().getArray(arrayDesc.arrayName);
		return null;
	};
	publicAPI.setInputArrayToProcess = (inputPort, arrayName, fieldAssociation, attributeType = "Scalars") => {
		while (model.inputArrayToProcess.length < inputPort) model.inputArrayToProcess.push(null);
		model.inputArrayToProcess[inputPort] = {
			arrayName,
			fieldAssociation,
			attributeType
		};
	};
}
var EVENT_ABORT = Symbol("Event abort");
function event$1(publicAPI, model, eventName) {
	const callbacks = [];
	const previousDelete = publicAPI.delete;
	let curCallbackID = 1;
	function off(callbackID) {
		for (let i = 0; i < callbacks.length; ++i) {
			const [cbID] = callbacks[i];
			if (cbID === callbackID) {
				callbacks.splice(i, 1);
				return;
			}
		}
	}
	function on(callbackID) {
		function unsubscribe() {
			off(callbackID);
		}
		return Object.freeze({ unsubscribe });
	}
	function invoke() {
		if (model.deleted) {
			vtkErrorMacro("instance deleted - cannot call any method");
			return;
		}
		const currentCallbacks = callbacks.slice();
		for (let index = 0; index < currentCallbacks.length; ++index) {
			const [, cb, priority] = currentCallbacks[index];
			if (!cb) continue;
			if (priority < 0) setTimeout(() => cb.apply(publicAPI, arguments), 1 - priority);
			else if (cb.apply(publicAPI, arguments) === EVENT_ABORT) break;
		}
	}
	publicAPI[`invoke${_capitalize(eventName)}`] = invoke;
	publicAPI[`on${_capitalize(eventName)}`] = (callback, priority = 0) => {
		if (!callback.apply) {
			console.error(`Invalid callback for event ${eventName}`);
			return null;
		}
		if (model.deleted) {
			vtkErrorMacro("instance deleted - cannot call any method");
			return null;
		}
		const callbackID = curCallbackID++;
		callbacks.push([
			callbackID,
			callback,
			priority
		]);
		callbacks.sort((cb1, cb2) => cb2[2] - cb1[2]);
		return on(callbackID);
	};
	publicAPI.delete = () => {
		previousDelete();
		callbacks.forEach(([cbID]) => off(cbID));
	};
}
function newInstance$3(extend, className) {
	const constructor = (initialValues = {}) => {
		const model = {};
		const publicAPI = {};
		extend(publicAPI, model, initialValues);
		return Object.freeze(publicAPI);
	};
	if (className) vtk.register(className, constructor);
	return constructor;
}
function chain(...fn) {
	return (...args) => fn.filter((i) => !!i).map((i) => i(...args));
}
function isVtkObject(instance) {
	return instance && instance.isA && instance.isA("vtkObject");
}
function traverseInstanceTree(instance, extractFunction, accumulator = [], visitedInstances = []) {
	if (isVtkObject(instance)) {
		if (visitedInstances.indexOf(instance) >= 0) return accumulator;
		visitedInstances.push(instance);
		const result = extractFunction(instance);
		if (result !== void 0) accumulator.push(result);
		const model = instance.get();
		Object.keys(model).forEach((key) => {
			const modelObj = model[key];
			if (Array.isArray(modelObj)) modelObj.forEach((subObj) => {
				traverseInstanceTree(subObj, extractFunction, accumulator, visitedInstances);
			});
			else traverseInstanceTree(modelObj, extractFunction, accumulator, visitedInstances);
		});
	}
	return accumulator;
}
function debounce(func, wait, immediate) {
	let timeout;
	const debounced = (...args) => {
		const context = this;
		const later = () => {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		const callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
	debounced.cancel = () => clearTimeout(timeout);
	return debounced;
}
function throttle(callback, delay) {
	let isThrottled = false;
	let argsToUse = null;
	function next() {
		isThrottled = false;
		if (argsToUse !== null) {
			wrapper(...argsToUse);
			argsToUse = null;
		}
	}
	function wrapper(...args) {
		if (isThrottled) {
			argsToUse = args;
			return;
		}
		isThrottled = true;
		callback(...args);
		setTimeout(next, delay);
	}
	return wrapper;
}
function keystore(publicAPI, model, initialKeystore = {}) {
	model.keystore = Object.assign(model.keystore || {}, initialKeystore);
	publicAPI.setKey = (key, value) => {
		model.keystore[key] = value;
	};
	publicAPI.getKey = (key) => model.keystore[key];
	publicAPI.getAllKeys = () => Object.keys(model.keystore);
	publicAPI.deleteKey = (key) => delete model.keystore[key];
	publicAPI.clearKeystore = () => publicAPI.getAllKeys().forEach((key) => delete model.keystore[key]);
}
var nextProxyId = 1;
var ROOT_GROUP_NAME = "__root__";
function proxy(publicAPI, model) {
	keystore(publicAPI, model);
	const parentDelete = publicAPI.delete;
	model.proxyId = `${nextProxyId++}`;
	model.ui = JSON.parse(JSON.stringify(model.ui || []));
	get$1(publicAPI, model, [
		"proxyId",
		"proxyGroup",
		"proxyName"
	]);
	setGet(publicAPI, model, ["proxyManager"]);
	const propertyMap = {};
	const groupChildrenNames = {};
	function registerProperties(descriptionList, currentGroupName) {
		if (!groupChildrenNames[currentGroupName]) groupChildrenNames[currentGroupName] = [];
		const childrenNames = groupChildrenNames[currentGroupName];
		for (let i = 0; i < descriptionList.length; i++) {
			childrenNames.push(descriptionList[i].name);
			propertyMap[descriptionList[i].name] = descriptionList[i];
			if (descriptionList[i].children && descriptionList[i].children.length) registerProperties(descriptionList[i].children, descriptionList[i].name);
		}
	}
	registerProperties(model.ui, ROOT_GROUP_NAME);
	publicAPI.updateUI = (ui) => {
		model.ui = JSON.parse(JSON.stringify(ui || []));
		Object.keys(propertyMap).forEach((k) => delete propertyMap[k]);
		Object.keys(groupChildrenNames).forEach((k) => delete groupChildrenNames[k]);
		registerProperties(model.ui, ROOT_GROUP_NAME);
		publicAPI.modified();
	};
	function listProxyProperties(gName = ROOT_GROUP_NAME) {
		return groupChildrenNames[gName];
	}
	publicAPI.updateProxyProperty = (propertyName, propUI) => {
		const prop = propertyMap[propertyName];
		if (prop) Object.assign(prop, propUI);
		else propertyMap[propertyName] = { ...propUI };
	};
	publicAPI.activate = () => {
		if (model.proxyManager) {
			const setActiveMethod = `setActive${_capitalize(publicAPI.getProxyGroup().slice(0, -1))}`;
			if (model.proxyManager[setActiveMethod]) model.proxyManager[setActiveMethod](publicAPI);
		}
	};
	model.propertyLinkSubscribers = {};
	publicAPI.registerPropertyLinkForGC = (otherLink, type) => {
		if (!(type in model.propertyLinkSubscribers)) model.propertyLinkSubscribers[type] = [];
		model.propertyLinkSubscribers[type].push(otherLink);
	};
	publicAPI.gcPropertyLinks = (type) => {
		const subscribers = model.propertyLinkSubscribers[type] || [];
		while (subscribers.length) subscribers.pop().unbind(publicAPI);
	};
	model.propertyLinkMap = {};
	publicAPI.getPropertyLink = (id, persistent = false) => {
		if (model.propertyLinkMap[id]) return model.propertyLinkMap[id];
		let value = null;
		const links = [];
		let count = 0;
		let updateInProgress = false;
		function update(source, force = false) {
			if (updateInProgress) return null;
			const needUpdate = [];
			let sourceLink = null;
			count = links.length;
			while (count--) {
				const link = links[count];
				if (link.instance === source) sourceLink = link;
				else needUpdate.push(link);
			}
			if (!sourceLink) return null;
			const newValue = sourceLink.instance[`get${_capitalize(sourceLink.propertyName)}`]();
			if (!shallowEquals(newValue, value) || force) {
				value = newValue;
				updateInProgress = true;
				while (needUpdate.length) {
					const linkToUpdate = needUpdate.pop();
					linkToUpdate.instance.set({ [linkToUpdate.propertyName]: value });
				}
				updateInProgress = false;
			}
			if (model.propertyLinkMap[id].persistent) model.propertyLinkMap[id].value = newValue;
			return newValue;
		}
		function unbind(instance, propertyName) {
			const indexToDelete = [];
			count = links.length;
			while (count--) {
				const link = links[count];
				if (link.instance === instance && (link.propertyName === propertyName || propertyName === void 0)) {
					link.subscription.unsubscribe();
					indexToDelete.push(count);
				}
			}
			while (indexToDelete.length) links.splice(indexToDelete.pop(), 1);
		}
		function bind(instance, propertyName, updateMe = false) {
			const subscription = instance.onModified(update);
			const other = links[0];
			links.push({
				instance,
				propertyName,
				subscription
			});
			if (updateMe) {
				if (model.propertyLinkMap[id].persistent && model.propertyLinkMap[id].value !== void 0) instance.set({ [propertyName]: model.propertyLinkMap[id].value });
				else if (other) update(other.instance, true);
			}
			return { unsubscribe: () => unbind(instance, propertyName) };
		}
		function unsubscribe() {
			while (links.length) links.pop().subscription.unsubscribe();
		}
		const linkHandler = {
			bind,
			unbind,
			unsubscribe,
			persistent
		};
		model.propertyLinkMap[id] = linkHandler;
		return linkHandler;
	};
	function getProperties(groupName = ROOT_GROUP_NAME) {
		const values = [];
		const id = model.proxyId;
		const propertyNames = listProxyProperties(groupName) || [];
		for (let i = 0; i < propertyNames.length; i++) {
			const name = propertyNames[i];
			const method = publicAPI[`get${_capitalize(name)}`];
			const prop = {
				id,
				name,
				value: method ? method() : void 0
			};
			const children = getProperties(name);
			if (children.length) prop.children = children;
			values.push(prop);
		}
		return values;
	}
	publicAPI.listPropertyNames = () => getProperties().map((p) => p.name);
	publicAPI.getPropertyByName = (name) => getProperties().find((p) => p.name === name);
	publicAPI.getPropertyDomainByName = (name) => (propertyMap[name] || {}).domain;
	publicAPI.getProxySection = () => ({
		id: model.proxyId,
		name: model.proxyGroup,
		ui: model.ui,
		properties: getProperties()
	});
	publicAPI.delete = () => {
		const list = Object.keys(model.propertyLinkMap);
		let count = list.length;
		while (count--) model.propertyLinkMap[list[count]].unsubscribe();
		Object.keys(model.propertyLinkSubscribers).forEach(publicAPI.gcPropertyLinks);
		parentDelete();
	};
	publicAPI.getState = () => null;
	function registerLinks() {
		if (model.links) for (let i = 0; i < model.links.length; i++) {
			const { link, property, persistent, updateOnBind, type } = model.links[i];
			if (type === "application") {
				const sLink = model.proxyManager.getPropertyLink(link, persistent);
				publicAPI.registerPropertyLinkForGC(sLink, "application");
				sLink.bind(publicAPI, property, updateOnBind);
			}
		}
	}
	setImmediateVTK(registerLinks);
}
function proxyPropertyMapping(publicAPI, model, map) {
	const parentDelete = publicAPI.delete;
	const subscriptions = [];
	const propertyNames = Object.keys(map);
	let count = propertyNames.length;
	while (count--) {
		const propertyName = propertyNames[count];
		const { modelKey, property, modified = true } = map[propertyName];
		const methodSrc = _capitalize(property);
		const methodDst = _capitalize(propertyName);
		publicAPI[`get${methodDst}`] = model[modelKey][`get${methodSrc}`];
		publicAPI[`set${methodDst}`] = model[modelKey][`set${methodSrc}`];
		if (modified) subscriptions.push(model[modelKey].onModified(publicAPI.modified));
	}
	publicAPI.delete = () => {
		while (subscriptions.length) subscriptions.pop().unsubscribe();
		parentDelete();
	};
}
function proxyPropertyState(publicAPI, model, state = {}, defaults = {}) {
	model.this = publicAPI;
	function applyState(map) {
		const modelKeys = Object.keys(map);
		let count = modelKeys.length;
		while (count--) {
			const modelKey = modelKeys[count];
			model[modelKey].set(map[modelKey]);
		}
	}
	const modelKeys = Object.keys(defaults);
	let count = modelKeys.length;
	while (count--) {
		const key = modelKeys[count];
		model[key] = defaults[key];
		const mapping = state[key];
		publicAPI[`set${_capitalize(key)}`] = (value) => {
			if (value !== model[key]) {
				model[key] = value;
				const propValues = mapping[value];
				applyState(propValues);
				publicAPI.modified();
			}
		};
	}
	if (modelKeys.length) get$1(publicAPI, model, modelKeys);
}
var PIXEL_STEP = 10;
var LINE_HEIGHT = 40;
var PAGE_HEIGHT = 800;
function normalizeWheel(wheelEvent) {
	let sX = 0;
	let sY = 0;
	let pX = 0;
	let pY = 0;
	if ("detail" in wheelEvent) sY = wheelEvent.detail;
	if ("wheelDelta" in wheelEvent) sY = -wheelEvent.wheelDelta / 120;
	if ("wheelDeltaY" in wheelEvent) sY = -wheelEvent.wheelDeltaY / 120;
	if ("wheelDeltaX" in wheelEvent) sX = -wheelEvent.wheelDeltaX / 120;
	if ("axis" in wheelEvent && wheelEvent.axis === wheelEvent.HORIZONTAL_AXIS) {
		sX = sY;
		sY = 0;
	}
	pX = sX * PIXEL_STEP;
	pY = sY * PIXEL_STEP;
	if ("deltaY" in wheelEvent) pY = wheelEvent.deltaY;
	if ("deltaX" in wheelEvent) pX = wheelEvent.deltaX;
	if ((pX || pY) && wheelEvent.deltaMode) if (wheelEvent.deltaMode === 1) {
		pX *= LINE_HEIGHT;
		pY *= LINE_HEIGHT;
	} else {
		pX *= PAGE_HEIGHT;
		pY *= PAGE_HEIGHT;
	}
	if (pX && !sX) sX = pX < 1 ? -1 : 1;
	if (pY && !sY) sY = pY < 1 ? -1 : 1;
	return {
		spinX: sX,
		spinY: sY || sX,
		pixelX: pX,
		pixelY: pY || pX
	};
}
var macro = {
	algo,
	capitalize,
	chain,
	debounce,
	enumToString,
	event: event$1,
	EVENT_ABORT,
	formatBytesToProperUnit,
	formatNumbersWithThousandSeparator,
	get: get$1,
	getArray,
	getCurrentGlobalMTime,
	getStateArrayMapFunc,
	isVtkObject,
	keystore,
	measurePromiseExecution,
	moveToProtected,
	newInstance: newInstance$3,
	newTypedArray,
	newTypedArrayFrom,
	normalizeWheel,
	obj,
	proxy,
	proxyPropertyMapping,
	proxyPropertyState,
	safeArrays,
	set,
	setArray,
	setGet,
	setGetArray,
	setImmediate: setImmediateVTK,
	setLoggerFunction,
	throttle,
	traverseInstanceTree,
	TYPED_ARRAYS,
	uncapitalize,
	VOID,
	vtkDebugMacro,
	vtkErrorMacro,
	vtkInfoMacro,
	vtkLogMacro,
	vtkOnceErrorMacro,
	vtkWarningMacro,
	objectSetterMap,
	requiredParam
};
//#endregion
//#region node_modules/@kitware/vtk.js/IO/Core/ImageStream/DefaultProtocol.js
function createMethods(session) {
	return {
		subscribeToImageStream: (callback) => session.subscribe("viewport.image.push.subscription", callback),
		unsubscribeToImageStream: (subscription) => session.unsubscribe(subscription),
		registerView: (viewId) => session.call("viewport.image.push.observer.add", [viewId]),
		unregisterView: (viewId) => session.call("viewport.image.push.observer.remove", [viewId]),
		enableView: (viewId, enabled) => session.call("viewport.image.push.enabled", [viewId, enabled]),
		render: (options = {
			size: [400, 400],
			view: -1
		}) => session.call("viewport.image.push", [options]),
		resetCamera: (view = -1) => session.call("viewport.camera.reset", [view]),
		invalidateCache: (viewId) => session.call("viewport.image.push.invalidate.cache", [viewId]),
		setQuality: (viewId, quality, ratio = 1) => session.call("viewport.image.push.quality", [
			viewId,
			quality,
			ratio
		]),
		setSize: (viewId, width = 400, height = 400) => session.call("viewport.image.push.original.size", [
			viewId,
			width,
			height
		]),
		setServerAnimationFPS: (fps = 30) => session.call("viewport.image.animation.fps.max", [fps]),
		getServerAnimationFPS: () => session.call("viewport.image.animation.fps.get", []),
		startAnimation: (viewId = -1) => session.call("viewport.image.animation.start", [viewId]),
		stopAnimation: (viewId = -1) => session.call("viewport.image.animation.stop", [viewId]),
		updateCamera: (viewId, focalPoint, viewUp, position, forceUpdate = true) => session.call("viewport.camera.update", [
			viewId ?? -1,
			focalPoint,
			viewUp,
			position,
			forceUpdate
		]),
		updateCameraParameters: (viewId = -1, parameters = {}, forceUpdate = true) => session.call("viewport.camera.update.params", [
			viewId,
			parameters,
			forceUpdate
		])
	};
}
//#endregion
//#region node_modules/@kitware/vtk.js/IO/Core/ImageStream/ViewStream.js
function vtkViewStream(publicAPI, model) {
	model.classHierarchy.push("vtkViewStream");
	model.imageDecodingPool = [new Image(), new Image()];
	model.eventPool = [];
	model.nextPoolImageIndex = 0;
	model.urlToRevoke = [];
	model.activeURL = null;
	model.fps = [];
	model.lastTime = Date.now();
	model.lastImageEvent = null;
	function imageLoaded(e) {
		if (model.deleted) return;
		const id = Number(this.dataset.id);
		publicAPI.invokeImageReady(model.eventPool[id]);
	}
	function prepareDecodingPool(size = 2) {
		while (model.imageDecodingPool.length < size) model.imageDecodingPool.push(new Image());
		for (let i = 0; i < model.imageDecodingPool.length; i++) {
			model.imageDecodingPool[i].dataset.id = i;
			model.imageDecodingPool[i].onload = imageLoaded;
		}
	}
	function decodeImage(event) {
		model.eventPool[model.nextPoolImageIndex] = event;
		event.image = model.imageDecodingPool[model.nextPoolImageIndex++];
		model.nextPoolImageIndex %= model.imageDecodingPool.length;
		event.image.src = event.url;
	}
	publicAPI.pushCamera = () => {
		const focalPoint = model.camera.getReferenceByName("focalPoint");
		const viewUp = model.camera.getReferenceByName("viewUp");
		const position = model.camera.getReferenceByName("position");
		const parallelProjection = model.camera.getParallelProjection();
		const viewAngle = model.camera.getViewAngle();
		const parallelScale = model.camera.getParallelScale();
		let promise = null;
		if (model.useCameraParameters) promise = model.protocol.updateCameraParameters(model.viewId, {
			focalPoint,
			viewUp,
			position,
			parallelProjection,
			viewAngle,
			parallelScale
		}, false);
		else promise = model.protocol.updateCamera(model.viewId, focalPoint, viewUp, position, false);
		if (model.isAnimating) setTimeout(publicAPI.pushCamera, 1e3 / model.cameraUpdateRate);
		return promise;
	};
	publicAPI.invalidateCache = () => model.protocol.invalidateCache(model.viewId);
	publicAPI.render = () => model.protocol.render({
		view: model.viewId,
		size: model.size
	});
	publicAPI.resetCamera = () => model.protocol.resetCamera(model.viewId);
	publicAPI.startAnimation = () => model.protocol.startAnimation(model.viewId);
	publicAPI.stopAnimation = () => model.protocol.stopAnimation(model.viewId);
	publicAPI.setSize = (width, height) => {
		let changeDetected = false;
		if (model.size[0] !== width || model.size[1] !== height) {
			model.size = [width, height];
			changeDetected = true;
		}
		if (changeDetected) {
			publicAPI.modified();
			if (model.protocol) return model.protocol.setSize(model.viewId, width, height);
		}
		return Promise.resolve(false);
	};
	publicAPI.startInteraction = () => {
		const promises = [model.protocol.setQuality(model.viewId, model.interactiveQuality, model.interactiveRatio)];
		if (model.camera) {
			promises.push(publicAPI.startAnimation());
			model.isAnimating = true;
			promises.push(publicAPI.pushCamera());
		}
		return Promise.all(promises);
	};
	publicAPI.endInteraction = () => {
		const promises = [];
		promises.push(model.protocol.setQuality(model.viewId, model.stillQuality, model.stillRatio));
		if (model.camera) {
			promises.push(publicAPI.stopAnimation());
			model.isAnimating = false;
			promises.push(publicAPI.pushCamera());
		} else promises.push(publicAPI.render());
		return Promise.all(promises);
	};
	publicAPI.setViewId = (id) => {
		if (model.viewId === id || !model.protocol) return false;
		if (model.viewId) model.protocol.unregisterView(model.viewId);
		model.viewId = id;
		if (model.viewId) model.protocol.registerView(model.viewId).then(({ viewId }) => {
			model.viewId = viewId;
		});
		return true;
	};
	publicAPI.processMessage = (msg) => {
		if (msg.id != model.viewId) return;
		const imgBlob = new Blob([msg.image], { type: model.mimeType });
		if (model.activeURL) {
			model.urlToRevoke.push(model.activeURL);
			model.activeURL = null;
			while (model.urlToRevoke.length > 60) {
				const url = model.urlToRevoke.shift();
				window.URL.revokeObjectURL(url);
			}
		}
		model.activeURL = URL.createObjectURL(imgBlob);
		const time = Date.now();
		const fps = Math.floor(1e4 / (time - model.lastTime)) / 10;
		model.fps.push(fps);
		model.lastTime = time;
		model.lastImageEvent = {
			url: model.activeURL,
			fps,
			metadata: {
				size: msg.size,
				id: msg.id,
				memory: msg.memsize,
				workTime: msg.workTime
			}
		};
		if (model.decodeImage) decodeImage(model.lastImageEvent);
		else publicAPI.invokeImageReady(model.lastImageEvent);
		while (model.fps.length > model.fpsWindowSize) model.fps.shift();
	};
	publicAPI.delete = macro.chain(() => {
		model.unregisterViewStream(publicAPI);
		publicAPI.setViewId(null);
		while (model.urlToRevoke.length) window.URL.revokeObjectURL(model.urlToRevoke.pop());
	}, publicAPI.delete);
	prepareDecodingPool();
}
var DEFAULT_VALUES$2 = {
	cameraUpdateRate: 30,
	decodeImage: true,
	fpsWindowSize: 250,
	interactiveQuality: 80,
	interactiveRatio: 1,
	isAnimating: false,
	mimeType: "image/jpeg",
	size: [-1, -1],
	stillQuality: 100,
	stillRatio: 1,
	useCameraParameters: false,
	viewId: null
};
function extend$2(publicAPI, model, initialValues = {}) {
	Object.assign(model, DEFAULT_VALUES$2, initialValues);
	macro.obj(publicAPI, model);
	macro.event(publicAPI, model, "ImageReady");
	macro.get(publicAPI, model, [
		"viewId",
		"size",
		"fps",
		"lastImageEvent"
	]);
	macro.setGet(publicAPI, model, [
		"camera",
		"cameraUpdateRate",
		"decodeImage",
		"fpsWindowSize",
		"interactiveQuality",
		"interactiveRatio",
		"stillQuality",
		"stillRatio",
		"useCameraParameters"
	]);
	vtkViewStream(publicAPI, model);
	Object.assign(publicAPI, model.sharedAPI);
}
var ViewStream = {
	newInstance: macro.newInstance(extend$2, "vtkViewStream"),
	extend: extend$2
};
//#endregion
//#region node_modules/@kitware/vtk.js/IO/Core/ImageStream.js
function vtkImageStream(publicAPI, model) {
	model.classHierarchy.push("vtkImageStream");
	function onImage(data) {
		const message = data[0];
		if (!message || !message.image) return;
		for (let i = 0; i < model.viewStreams.length; i++) model.viewStreams[i].processMessage(message);
	}
	publicAPI.setServerAnimationFPS = (maxFPS = 30) => {
		let changeDetected = false;
		if (model.serverAnimationFPS !== maxFPS) {
			model.serverAnimationFPS = maxFPS;
			changeDetected = true;
		}
		if (!model.protocol) return Promise.resolve(true);
		if (changeDetected) publicAPI.modified();
		return model.protocol.setServerAnimationFPS(maxFPS);
	};
	publicAPI.connect = (session, protocol = createMethods) => {
		if (model.connected || !session || !protocol) return;
		model.protocol = protocol(session);
		model.protocol.subscribeToImageStream(onImage).promise.then((subscription) => {
			model.renderTopicSubscription = subscription;
			model.connected = true;
		}).catch((e) => {
			model.connected = false;
			console.error(e);
		});
	};
	publicAPI.disconnect = () => {
		if (model.protocol && model.connected && model.renderTopicSubscription) {
			model.protocol.unsubscribeToImageStream(model.renderTopicSubscription);
			model.renderTopicSubscription = null;
		}
		model.connected = false;
	};
	publicAPI.registerViewStream = (view) => {
		model.viewStreams.push(view);
	};
	publicAPI.unregisterViewStream = (view) => {
		model.viewStreams = model.viewStreams.filter((v) => v !== view);
	};
	publicAPI.createViewStream = (viewId = "-1", size = [400, 400]) => {
		const { setServerAnimationFPS, getServerAnimationFPS, unregisterViewStream } = publicAPI;
		const viewStream = ViewStream.newInstance({
			protocol: model.protocol,
			unregisterViewStream,
			sharedAPI: {
				setServerAnimationFPS,
				getServerAnimationFPS
			}
		});
		viewStream.setViewId(viewId);
		viewStream.setSize(size[0], size[1]);
		publicAPI.registerViewStream(viewStream);
		return viewStream;
	};
	publicAPI.delete = macro.chain(() => {
		while (model.viewStreams.length) model.viewStreams.pop().delete();
		publicAPI.disconnect();
	}, publicAPI.delete);
}
var DEFAULT_VALUES$1 = {
	viewStreams: [],
	serverAnimationFPS: -1
};
function extend$1(publicAPI, model, initialValues = {}) {
	Object.assign(model, DEFAULT_VALUES$1, initialValues);
	macro.obj(publicAPI, model);
	macro.get(publicAPI, model, ["serverAnimationFPS", "protocol"]);
	vtkImageStream(publicAPI, model);
}
var vtkImageStream$1 = {
	newInstance: macro.newInstance(extend$1, "vtkImageStream"),
	extend: extend$1
};
//#endregion
//#region node_modules/@kitware/vtk.js/IO/Core/WSLinkClient.js
var SMART_CONNECT_CLASS = null;
function setSmartConnectClass(klass) {
	SMART_CONNECT_CLASS = klass;
}
function busy(fn, update) {
	return (...args) => new Promise((resolve, reject) => {
		update(1);
		fn(...args).then((response) => {
			update(-1);
			resolve(response);
		}, (error) => {
			update(-1);
			reject(error);
		});
	});
}
function busyWrap(methodMap, update, skipList = []) {
	const busyContainer = {};
	Object.keys(methodMap).forEach((methodName) => {
		if (skipList.indexOf(methodName) === -1) busyContainer[methodName] = busy(methodMap[methodName], update);
		else busyContainer[methodName] = methodMap[methodName];
	});
	return busyContainer;
}
function vtkWSLinkClient(publicAPI, model) {
	model.classHierarchy.push("vtkWSLinkClient");
	function notifyBusy() {
		publicAPI.invokeBusyChange(model.busyCount);
	}
	function updateBusy(delta = 0) {
		model.busyCount += delta;
		if (model.timeoutId) {
			clearTimeout(model.timeoutId);
			model.timeoutId = 0;
		}
		if (model.busyCount) notifyBusy();
		else model.timeoutId = setTimeout(notifyBusy, model.notificationTimeout);
	}
	publicAPI.beginBusy = () => updateBusy(1);
	publicAPI.endBusy = () => updateBusy(-1);
	publicAPI.isBusy = () => !!model.busyCount;
	publicAPI.isConnected = () => !!model.connection;
	publicAPI.connect = (config = {}, configDecorator = null) => {
		if (!SMART_CONNECT_CLASS) return Promise.reject(/* @__PURE__ */ new Error("Need to provide SmartConnect"));
		if (model.connection) return Promise.reject(/* @__PURE__ */ new Error("Need to disconnect first"));
		model.config = config;
		model.configDecorator = configDecorator || model.configDecorator;
		return new Promise((resolve, reject) => {
			model.smartConnect = SMART_CONNECT_CLASS.newInstance({
				config,
				configDecorator: model.configDecorator
			});
			model.smartConnect.onConnectionReady((connection) => {
				model.connection = connection;
				model.remote = {};
				model.config = model.smartConnect.getConfig();
				const session = connection.getSession();
				model.protocols = model.protocols || {};
				Object.keys(model.protocols).forEach((name) => {
					model.remote[name] = busyWrap(model.protocols[name](session), updateBusy, model.notBusyList);
				});
				if (model.createImageStream) {
					model.imageStream = vtkImageStream$1.newInstance();
					model.imageStream.connect(session);
				}
				publicAPI.invokeConnectionReady(publicAPI);
				resolve(publicAPI);
			});
			model.smartConnect.onConnectionError((error) => {
				publicAPI.invokeConnectionError(error);
				reject(error);
			});
			model.smartConnect.onConnectionClose((close) => {
				publicAPI.invokeConnectionClose(close);
				reject(close);
			});
			model.smartConnect.connect();
		});
	};
	publicAPI.disconnect = (timeout = 60) => {
		if (model.connection) {
			model.connection.destroy(timeout);
			model.connection = null;
		}
	};
	publicAPI.registerProtocol = (name, protocol) => {
		model.remote[name] = busyWrap(protocol(model.connection.getSession()), updateBusy, model.notBusyList);
	};
	publicAPI.unregisterProtocol = (name) => {
		delete model.remote[name];
	};
}
var DEFAULT_VALUES = {
	notBusyList: [],
	busyCount: 0,
	timeoutId: 0,
	notificationTimeout: 50,
	createImageStream: true
};
function extend(publicAPI, model, initialValues = {}) {
	Object.assign(model, DEFAULT_VALUES, initialValues);
	macro.obj(publicAPI, model);
	macro.setGet(publicAPI, model, [
		"protocols",
		"notBusyList",
		"createImageStream",
		"configDecorator"
	]);
	macro.get(publicAPI, model, [
		"connection",
		"config",
		"remote",
		"imageStream"
	]);
	macro.event(publicAPI, model, "BusyChange");
	macro.event(publicAPI, model, "ConnectionReady");
	macro.event(publicAPI, model, "ConnectionError");
	macro.event(publicAPI, model, "ConnectionClose");
	vtkWSLinkClient(publicAPI, model);
}
var vtkWSLinkClient$1 = {
	newInstance: macro.newInstance(extend, "vtkWSLinkClient"),
	extend,
	setSmartConnectClass
};
//#endregion
//#region src/core/wslink/protocols/SyncView.js
var SyncView_default = (session) => ({
	getArray(hash, binary = true) {
		return session.call("viewport.geometry.array.get", [hash, binary]).then((res) => {
			if (res.buffer) return new Blob([res]);
			return res;
		});
	},
	getViewState(viewId, newSubscription = false) {
		return session.call("viewport.geometry.view.get.state", [viewId, newSubscription]);
	},
	addViewObserver(viewId) {
		return session.call("viewport.geometry.view.observer.add", [viewId]);
	},
	removeViewObserver(viewId) {
		return session.call("viewport.geometry.view.observer.remove", [viewId]);
	},
	subscribeToViewChange(callback) {
		return session.subscribe("viewport.geometry.view.subscription", callback);
	},
	unsubscribe(subscription) {
		return session.unsubscribe(subscription);
	}
});
//#endregion
//#region src/core/wslink/protocols/Trame.js
var Trame_default = (session) => ({
	lifeCycleUpdate(phaseName) {
		return session.call("trame.lifecycle.update", [phaseName]);
	},
	sendError(message) {
		return session.call("trame.error.client", [message]);
	},
	getState() {
		return session.call("trame.state.get", []);
	},
	trigger(name, args = [], kwargs = {}) {
		return session.call("trame.trigger", [
			name,
			args,
			kwargs
		]);
	},
	updateState(changes) {
		return session.call("trame.state.update", [changes]);
	},
	subscribeToStateUpdate(callback) {
		return session.subscribe("trame.state.topic", callback);
	},
	subscribeToActions(callback) {
		return session.subscribe("trame.actions.topic", callback);
	},
	unsubscribe(subscription) {
		return session.unsubscribe(subscription);
	}
});
//#endregion
//#region src/core/wslink/protocols/index.js
var protocols_default = {
	SyncView: SyncView_default,
	Trame: Trame_default
};
//#endregion
//#region src/core/wslink/index.js
vtkWSLinkClient$1.setSmartConnectClass(SmartConnect_default);
var WS_PROTOCOL = {
	"http:": "ws:",
	"https:": "wss:",
	"ws:": "ws:",
	"wss:": "wss:"
};
var NOT_BUSY_LIST = [
	"unsubscribe",
	"subscribeToViewChange",
	"subscribeToStateUpdate",
	"subscribeToActions",
	"subscribeToViewChange"
];
function configDecorator(config) {
	const outputConfig = { ...config };
	if (outputConfig.sessionURL) {
		let sessionURL = outputConfig.sessionURL.toLowerCase();
		const httpURL = window.location;
		if (sessionURL.includes("use_")) {
			const wsURL = new URL(sessionURL);
			wsURL.protocol = WS_PROTOCOL[httpURL.protocol];
			sessionURL = wsURL.toString();
		}
		const use_mapping = {
			use_hostname: httpURL.hostname,
			use_host: httpURL.host
		};
		for (const [key, value] of Object.entries(use_mapping)) sessionURL = sessionURL.replaceAll(key, value);
		outputConfig.sessionURL = sessionURL;
	}
	outputConfig.application = document.querySelector("html").dataset.appName || outputConfig.application;
	outputConfig.launcherRetry = JSON.parse(document.querySelector("html").dataset.launcherRetry || "[]");
	const sessionManagerURL = document.querySelector("html").dataset.sessionManagerUrl || outputConfig.sessionManagerURL;
	if (sessionManagerURL) outputConfig.sessionManagerURL = sessionManagerURL;
	if (outputConfig.useUrl) return {
		...outputConfig,
		...vtkURLExtract.extractURLParameters()
	};
	return outputConfig;
}
function createClient() {
	return vtkWSLinkClient$1.newInstance({
		protocols: protocols_default,
		configDecorator,
		notBusyList: NOT_BUSY_LIST
	});
}
var wslink_default = {
	configDecorator,
	createClient
};
//#endregion
//#region src/core/trame/setup.js
var LOADED_URLS = [];
function resolveWithError(resolve, msg) {
	return () => {
		console.error(msg);
		resolve(false);
	};
}
function loadScript(url) {
	return new Promise(function(resolve, reject) {
		if (LOADED_URLS.indexOf(url) === -1) {
			LOADED_URLS.push(url);
			var newScriptTag = document.createElement("script");
			newScriptTag.type = "text/javascript";
			newScriptTag.src = url;
			newScriptTag.onload = resolve;
			newScriptTag.onerror = resolveWithError(resolve, `Failed loading script ${url}`);
			document.body.appendChild(newScriptTag);
		} else resolve(false);
	});
}
function loadScriptAsModule(url) {
	return new Promise(function(resolve, reject) {
		if (LOADED_URLS.indexOf(url) === -1) {
			LOADED_URLS.push(url);
			var newScriptTag = document.createElement("script");
			newScriptTag.type = "module";
			newScriptTag.src = url;
			newScriptTag.onload = resolve;
			newScriptTag.onerror = resolveWithError(resolve, `Failed loading script module ${url}`);
			document.body.appendChild(newScriptTag);
		} else resolve(false);
	});
}
function loadCSS(url) {
	return new Promise(function(resolve, reject) {
		if (LOADED_URLS.indexOf(url) === -1) {
			LOADED_URLS.push(url);
			var newScriptTag = document.createElement("link");
			newScriptTag.rel = "stylesheet";
			newScriptTag.href = url;
			newScriptTag.onload = resolve;
			newScriptTag.onerror = resolveWithError(resolve, `Failed loading css ${url}`);
			document.head.appendChild(newScriptTag);
		} else resolve(false);
	});
}
async function serialLoad(urls, loadFn) {
	for (let i = 0; i < urls.length; i++) await loadFn(urls[i]);
}
function loadURLs(urls, loadFn) {
	const mainGroup = [];
	const serialGroups = {};
	for (let i = 0; i < urls.length; i++) {
		let container = mainGroup;
		let url = urls[i];
		if (Array.isArray(url)) {
			const groupName = url[1].serial;
			if (groupName) {
				if (!serialGroups[groupName]) serialGroups[groupName] = [];
				container = serialGroups[groupName];
			}
			[url] = url;
		}
		container.push(url);
	}
	const waitList = mainGroup.map(loadFn);
	const serialScripts = Object.values(serialGroups);
	for (let i = 0; i < serialScripts.length; i++) waitList.push(serialLoad(serialScripts[i], loadFn));
	return Promise.all(waitList);
}
async function handlePageResources(state) {
	await loadURLs(state.trame__styles, loadCSS);
	await loadURLs(state.trame__scripts, loadScript);
	await loadURLs(state.trame__module_scripts, loadScriptAsModule);
	if (state.trame__favicon) document.querySelector("link[rel=icon]").href = state.trame__favicon;
	if (state.trame__title) document.title = state.trame__title;
	return state.trame__vue_use.map((libUseEntry) => {
		let libKey = libUseEntry;
		let libOptions = [];
		if (Array.isArray(libUseEntry)) [libKey, ...libOptions] = libUseEntry;
		let lib = window.eval(libKey);
		for (let i = 0; i < libOptions.length; i++) {
			const arg = libOptions[i];
			if (arg.js_eval) libOptions[i] = window.eval(arg.js_eval);
		}
		if (!lib) {
			console.error(`Lookup error: Vue.use(${libKey}, ${JSON.stringify(libOptions)})`);
			return;
		}
		return [lib, ...libOptions];
	});
}
//#endregion
//#region src/core/trame/decorators.js
var CTX = {};
function compareDecorator(a, b) {
	return a.priority - b.priority;
}
function setAddAttachment(fn) {
	CTX.addAttachement = fn;
}
var fileHandler = {
	priority: 0,
	async decorate(value) {
		if (value === null || value === void 0) return value;
		if (value.constructor && value.constructor === File) {
			const { name, lastModified, size, type } = value;
			let content = null;
			let error = null;
			try {
				const arrayBuffer = await new Promise((resolve, reject) => {
					const reader = new FileReader();
					reader.addEventListener("loadend", () => {
						resolve(reader.result);
					});
					reader.addEventListener("error", () => {
						reject(reader.error);
					});
					reader.readAsArrayBuffer(value);
				});
				content = new DataView(arrayBuffer);
			} catch (e) {
				error = e?.message ?? String(e);
			}
			return {
				name,
				lastModified,
				size,
				type,
				content,
				error,
				_filter: ["content"]
			};
		}
		return value;
	}
};
var fileListHandler = {
	priority: 0,
	async decorate(value) {
		if (value === null || value === void 0) return value;
		if (typeof value === "string") return value;
		if (value.constructor && value.constructor === FileList || value.length) return (await Promise.allSettled(Array.from(value).map((file) => fileHandler.decorate(file)))).map((result) => result.value);
		return value;
	}
};
var STATE_DECORATORS = [
	fileHandler,
	fileListHandler,
	{
		priority: 0,
		async decorate(value) {
			if (value === null || value === void 0) return value;
			if (typeof value === "string") return value;
			if (value.constructor && value.constructor === Object) {
				const newValue = {};
				const names = Object.keys(value);
				for (let i = 0; i < names.length; i++) {
					const name = names[i];
					newValue[name] = value[name];
					newValue[name] = await fileListHandler.decorate(newValue[name]);
					newValue[name] = await fileHandler.decorate(newValue[name]);
				}
				return newValue;
			}
			return value;
		}
	}
];
function registerDecorator(decorator) {
	STATE_DECORATORS.push(decorator);
	STATE_DECORATORS.sort(compareDecorator);
}
async function decorate(value) {
	let result = value;
	for (let i = 0; i < STATE_DECORATORS.length; i++) {
		if (result === null || result === void 0) return result;
		result = await STATE_DECORATORS[i].decorate(result);
	}
	return result;
}
//#endregion
//#region src/core/trame/state.js
var WatcherManager = class {
	constructor() {
		this.nextId = 1;
		this.listeners = {};
	}
	watch(dependencies, callback) {
		const key = `${this.nextId++}`;
		this.listeners[key] = {
			key,
			dependencies,
			callback
		};
		const unsubscribe = () => delete this.listeners[key];
		return unsubscribe;
	}
	notifyWatchers(changedKeys, fullState) {
		const watchers = Object.values(this.listeners);
		const keys = new Set(changedKeys);
		for (let i = 0; i < watchers.length; i++) {
			const { dependencies, callback } = watchers[i];
			if (keys.intersection(new Set(dependencies)).size) {
				const args = dependencies.map((v) => fullState[v]);
				try {
					callback(...args);
				} catch (e) {
					console.error(`Watcher error with dependencies: ${dependencies}`, e);
				}
			}
		}
	}
	getWatchers() {
		return Object.values(this.listeners);
	}
};
var SharedState = class {
	constructor(client) {
		this.name = "Default trame application";
		this.client = client;
		this.subscriptions = [];
		this.dirtyKeys = /* @__PURE__ */ new Set();
		this.state = {};
		this.keyTS = {};
		this.mtime = 0;
		this.listeners = [];
		this.ready = false;
		this._watchers = new WatcherManager();
		this.registerDecorator = registerDecorator;
		const updateFromServer = async (serverState) => {
			const updatedKeys = [];
			const allKeys = Object.keys(serverState);
			for (let i = 0; i < allKeys.length; i++) {
				let modified = true;
				const key = allKeys[i];
				const value = serverState[key];
				if (value?._filter?.length) {
					modified = false;
					const prevValue = this.state[key];
					const objKeys = Object.keys(value);
					for (let j = 0; !modified && j < objKeys.length; j++) {
						const subKey = objKeys[j];
						if (subKey[0] === "_") continue;
						if (prevValue === void 0 || prevValue[subKey] !== value[subKey]) modified = true;
					}
				}
				if (modified) {
					updatedKeys.push(key);
					this.state[key] = value;
				}
			}
			this.mtime += 1;
			const newKeys = [];
			for (let i = 0; i < updatedKeys.length; i++) {
				const key = updatedKeys[i];
				if (this.keyTS[key] === void 0) newKeys.push(key);
				this.keyTS[key] = this.mtime;
			}
			if (newKeys.length > 0) this.notifyListeners({
				type: "new-keys",
				keys: newKeys
			});
			this.notifyListeners({
				type: "dirty-state",
				keys: updatedKeys
			});
		};
		this.subscriptions.push(this.client.getRemote().Trame.subscribeToStateUpdate(([serverState]) => updateFromServer(serverState)));
		this.subscriptions.push(this.addListener(({ type, keys }) => {
			if (type === "dirty-state") this._watchers.notifyWatchers(keys, this.state);
		}));
		this._updateFromServer = updateFromServer;
	}
	async loadState() {
		const { state, name } = await this.client.getRemote().Trame.getState();
		this.name = name;
		this._updateFromServer(state);
		this.notifyListeners({ type: "ready" });
		this.ready = true;
	}
	notifyListeners(even) {
		for (let i = 0; i < this.listeners.length; i++) this.listeners[i](even);
	}
	addListener(listener) {
		this.listeners.push(listener);
	}
	removeListener(listener) {
		this.listeners = this.listeners.filter((l) => l !== listener);
	}
	getAllKeys() {
		return Object.keys(this.state);
	}
	getMutableStateKeys() {
		const keysToRemove = new Set(this.state.trame__disable_mutation || []);
		return this.getAllKeys().filter((v) => !keysToRemove.has(v));
	}
	delete() {
		while (this.subscriptions.length) this.client.getRemote().Trame.unsubscribe(this.subscriptions.pop());
	}
	get(key) {
		if (key === void 0) return this.state;
		return this.state[key];
	}
	watch(keys, fn) {
		const unsubscribe = this._watchers.watch(keys, fn);
		fn(...keys.map((v) => this.state[v]));
		return unsubscribe;
	}
	async set(key, value) {
		if (this.state[key] === value) return;
		this.ts += 1;
		this.state[key] = value;
		this.keyTS[key] = this.ts;
		this.dirty(key);
		await this.flush();
	}
	async update(obj) {
		this.ts += 1;
		for (const [key, value] of Object.entries(obj)) if (this.state[key] !== value) {
			this.state[key] = value;
			this.keyTS[key] = this.ts;
			this.dirty(key);
		}
		await this.flush();
	}
	canDirty(name) {
		return !this.state.trame__client_only.includes(name);
	}
	dirty(...keys) {
		keys.forEach((key) => {
			if (this.canDirty(key)) this.dirtyKeys.add(key);
		});
		this.notifyListeners({
			type: "dirty-state",
			keys
		});
	}
	async flush(...keys) {
		if (keys.length) keys.forEach((key) => {
			if (Array.isArray(key)) this.dirty(...key);
			else this.dirty(key);
		});
		if (this.dirtyKeys.size && !this.client.isBusy()) {
			const waitOn = [];
			const keys = [];
			this.dirtyKeys.forEach((key) => {
				waitOn.push(decorate(this.state[key]));
				keys.push(key);
			});
			this.dirtyKeys.clear();
			const values = await Promise.all(waitOn);
			const deltaState = keys.map((key, i) => ({
				key,
				value: values[i]
			}));
			if (this.client.isConnected()) await this.client.getRemote().Trame.updateState(deltaState);
			if (this.dirtyKeys.size) this.flush();
		}
		if (!this.client.isConnected()) this._updateFromServer(this.state);
	}
};
//#endregion
//#region src/utils/vtk/index.js
var VTK_EVENT_KEYS = [
	"type",
	"key",
	"keyCode",
	"controlKey",
	"altKey",
	"shiftKey",
	"position",
	"spinX",
	"spinY",
	"pixelX",
	"pixelY"
];
function event(e) {
	const result = {};
	for (let i = 0; i < VTK_EVENT_KEYS.length; i++) {
		const key = VTK_EVENT_KEYS[i];
		if (key in e) result[key] = e[key];
	}
	return result;
}
var vtk_default = { event };
//#endregion
//#region src/utils/fmt/index.js
function number(value, units = [], steps = 1e3, fixed = 2) {
	if (value === null) return null;
	for (let i = 0; i < units.length; i++) {
		const step = Array.isArray(steps) ? steps[i] : steps;
		const unit = units[i];
		if (value > step) value /= step;
		else return `${value.toFixed(fixed)} ${unit}`;
	}
	return `${value.toFixed(fixed)} ${steps[steps.length - 1]}`;
}
function bytes(v, fixed = 2) {
	return number(v, [
		"B",
		"KB",
		"MB",
		"GB",
		"TB",
		"PB"
	], 1024, fixed);
}
var fmt_default = {
	number,
	bytes
};
//#endregion
//#region src/utils/index.js
async function download(filename, contentOrPromise, type = "application/octet-stream") {
	const content = await Promise.resolve(contentOrPromise);
	const blob = new Blob([content], { type });
	const url = URL.createObjectURL(blob);
	const anchor = document.createElement("a");
	anchor.setAttribute("href", url);
	anchor.setAttribute("download", filename);
	document.body.appendChild(anchor);
	anchor.click();
	document.body.removeChild(anchor);
	setTimeout(() => URL.revokeObjectURL(url), 1e3);
}
function get(path, obj = window) {
	let current = obj;
	const exec = path.endsWith("()");
	const steps = (exec ? path.slice(0, -2) : path).split(".");
	for (let i = 0; i < steps.length; i++) current = current[steps[i]];
	if (exec) return current();
	return current;
}
function safe(obj) {
	try {
		JSON.stringify(obj);
		return obj;
	} catch (e) {}
	const safeObj = {};
	const keys = Object.keys(obj);
	for (let i = 0; i < keys.length; i++) {
		const key = keys[i];
		const value = obj[key];
		if (Array.isArray(value)) safeObj[key] = value.map(safe);
		else try {
			JSON.stringify(value);
			safeObj[key] = value;
		} catch (e) {
			continue;
		}
	}
	return safeObj;
}
function toNode(id, key, value) {
	const node = { id };
	const prefix = key ? `${key}: ` : "";
	if (Array.isArray(value)) {
		node.name = `${prefix}[]`;
		if (value.length) node.children = [];
		return node;
	}
	if (value === null || !value) {
		node.name = `${prefix}${value}`;
		return node;
	}
	if (typeof value === "function") {
		node.name = `${prefix}function`;
		return node;
	}
	if (typeof value === "object") {
		node.name = `${prefix}{}`;
		if (Object.keys(value).length) node.children = [];
		return node;
	}
	node.name = `${prefix}${value}`;
	return node;
}
function registerItem(container, id, key, value) {
	const node = toNode(id, key, value);
	container.push(node);
	if (node.children) registerList(id, node.children, value);
}
function registerList(parentId, container, obj) {
	if (Array.isArray(obj)) {
		const key = null;
		for (let i = 0; i < obj.length; i++) registerItem(container, `${parentId}_${i}`, key, obj[i]);
	} else {
		const keys = Object.keys(obj);
		for (let i = 0; i < keys.length; i++) {
			const key = keys[i];
			registerItem(container, `${parentId}_${i}`, key, obj[key]);
		}
	}
}
function tree(obj) {
	const result = [];
	registerList("", result, obj);
	return result;
}
var utils_default = {
	download,
	get,
	safe,
	tree,
	vtk: vtk_default,
	fmt: fmt_default
};
//#endregion
//#region src/core/trame/index.js
function createTrameInstance(app) {
	const trame = {
		app,
		client: null,
		state: null,
		config: null,
		utils: utils_default,
		refs: {}
	};
	let listeners = [];
	let initialized = false;
	function isConnected() {
		return initialized && trame?.client?.isConnected();
	}
	function notifyConnection() {
		for (let i = 0; i < listeners.length; i++) listeners[i]();
	}
	trame.addConnectListener = function addConnectListener(listener) {
		listeners.push(listener);
		if (isConnected()) listener();
	};
	trame.removeConnectListener = function removeConnectListener(listener) {
		listeners = listeners.filter((l) => l !== listener);
	};
	trame.connect = async function connect(config) {
		if (!trame.client) trame.client = wslink_default.createClient();
		if (trame.state) {
			trame.state.delete();
			trame.client = wslink_default.createClient();
		}
		if (!trame.client.isConnected()) await trame.client.connect(config);
		setAddAttachment(trame.client.getConnection().getSession().addAttachment);
		trame.state = new SharedState(trame.client);
		trame.config = trame.client.getConfig();
		await trame.state.loadState();
		initialized = true;
		notifyConnection();
		return trame.config;
	};
	trame.trigger = async function trigger(name, args = [], kwargs = {}) {
		let decoratedArgs = [];
		const decoratedKwargs = {};
		if (args) {
			const decorateArgs = args.map((arg) => decorate(arg));
			decoratedArgs = await Promise.all(decorateArgs);
		}
		if (kwargs) {
			const keys = [];
			const values = [];
			Object.entries(kwargs).forEach((entry) => {
				keys.push(entry[0]);
				values.push(decorate(entry[1]));
			});
			const resolvedValues = await Promise.all(values);
			for (let i = 0; i < keys.length; i++) decoratedKwargs[keys[i]] = resolvedValues[i];
		}
		return await trame.client.getRemote().Trame.trigger(name, decoratedArgs, decoratedKwargs);
	};
	window.trame = trame;
	return trame;
}
//#endregion
//#region \0vite/preload-helper.js
var scriptRel = "modulepreload";
var assetsURL = function(dep, importerUrl) {
	return new URL(dep, importerUrl).href;
};
var seen = {};
var __vitePreload = function preload(baseModule, deps, importerUrl) {
	let promise = Promise.resolve();
	if (deps && deps.length > 0) {
		const links = document.getElementsByTagName("link");
		const cspNonceMeta = document.querySelector("meta[property=csp-nonce]");
		const cspNonce = cspNonceMeta?.nonce || cspNonceMeta?.getAttribute("nonce");
		function allSettled(promises) {
			return Promise.all(promises.map((p) => Promise.resolve(p).then((value) => ({
				status: "fulfilled",
				value
			}), (reason) => ({
				status: "rejected",
				reason
			}))));
		}
		promise = allSettled(deps.map((dep) => {
			dep = assetsURL(dep, importerUrl);
			if (dep in seen) return;
			seen[dep] = true;
			const isCss = dep.endsWith(".css");
			const cssSelector = isCss ? "[rel=\"stylesheet\"]" : "";
			if (!!importerUrl) for (let i = links.length - 1; i >= 0; i--) {
				const link = links[i];
				if (link.href === dep && (!isCss || link.rel === "stylesheet")) return;
			}
			else if (document.querySelector(`link[href="${dep}"]${cssSelector}`)) return;
			const link = document.createElement("link");
			link.rel = isCss ? "stylesheet" : scriptRel;
			if (!isCss) link.as = "script";
			link.crossOrigin = "";
			link.href = dep;
			if (cspNonce) link.setAttribute("nonce", cspNonce);
			document.head.appendChild(link);
			if (isCss) return new Promise((res, rej) => {
				link.addEventListener("load", res);
				link.addEventListener("error", () => rej(/* @__PURE__ */ new Error(`Unable to preload CSS for ${dep}`)));
			});
		}));
	}
	function handlePreloadError(err) {
		const e = new Event("vite:preloadError", { cancelable: true });
		e.payload = err;
		window.dispatchEvent(e);
		if (!e.defaultPrevented) throw err;
	}
	return promise.then((res) => {
		for (const item of res || []) {
			if (item.status !== "rejected") continue;
			handlePreloadError(item.reason);
		}
		return baseModule().catch(handlePreloadError);
	});
};
//#endregion
//#region src/user_script_handler.js
async function loadEsModule(path) {
	try {
		return await __vitePreload(() => import(path), [], import.meta.url);
	} catch (e) {
		if (e instanceof TypeError) return await __vitePreload(() => import("/" + path), [], import.meta.url);
		else throw e;
	}
}
function lookupUmdModule(global_var_name) {
	const module = window[global_var_name];
	if (module) return Promise.resolve(module);
	const module_not_found_error = /* @__PURE__ */ new ReferenceError(`UMD module not found at window.${global_var_name}`);
	return Promise.reject(module_not_found_error);
}
function register_handle({ module, module_path }, function_name, handle_id) {
	const func = module[function_name];
	if (!func) throw new ReferenceError(`Could not find function ${function_name} on module ${module_path}. Did you pass the correct function identifier?`);
	window.TRAME_EXTERNAL_SCRIPTS[handle_id] = { func };
}
async function registerUserScripts() {
	window.TRAME_EXTERNAL_SCRIPTS = {};
	const external_scripts = window.trame.state.state.trame__client_external_scripts || [];
	const module_registration_promises = [];
	for (const external_script of external_scripts) {
		console.debug("registering external_script ", external_script);
		const registering_module = (external_script.module_type === "es" ? loadEsModule : lookupUmdModule)(external_script.path).catch((e) => {
			throw new Error(`Could not load module ${external_script.path}. Did you pass the correct module path?`, { cause: e });
		}).then((module) => {
			register_handle({
				module,
				module_path: external_script.path
			}, external_script.function, external_script.id);
		});
		module_registration_promises.push(registering_module);
	}
	const failures = (await Promise.allSettled(module_registration_promises)).filter((result) => result.status === "rejected");
	if (failures.length > 0) {
		const errors = failures.map((f) => f.reason);
		console.error(errors);
		throw new AggregateError(errors);
	}
}
//#endregion
//#region src/messageChannel.js
var MessageChannelWebSocket = class {
	constructor(port) {
		console.log("create MessageChannelWebSocket");
		this._channel_port = port;
		this.onmessage = null;
		this.onclose = null;
		this.onerror = null;
		this._channel_port.onmessage = (e) => {
			if (!this.onmessage) return;
			const { a, b, t } = e.data;
			if (a === "s") {
				this.onmessage({ data: b || t });
				return;
			}
			if (a === "c" && this.onclose) {
				this.onclose(e.data.c);
				return;
			}
			if (a === "e" && this.onerror) {
				this.onerror(e.data.e);
				return;
			}
		};
	}
	set onopen(callback) {
		setTimeout(callback, 0);
	}
	send(data) {
		console.log("send", data);
		if (data.buffer) {
			if (data.buffer.byteLength !== data.length) {
				const tmp = new Uint8Array(data.length);
				tmp.set(data);
				self._channel_port.postMessage({
					a: "s",
					b: tmp.buffer
				}, [tmp.buffer]);
				return;
			}
			self._channel_port.postMessage({
				a: "s",
				b: data.buffer
			}, [data.buffer]);
			return;
		}
		self._channel_port.postMessage({
			a: "s",
			t: data
		});
	}
	close() {
		self._channel_port.postMessage({
			a: "c",
			c: "Closing from client"
		});
		self._channel_port.close();
	}
};
function createMessageChannelWSFactory(port) {
	return () => new MessageChannelWebSocket(port);
}
//#endregion
//#region src/components/TrameTemplate.js
var { inject: inject$5, ref: ref$3, computed, onMounted: onMounted$4, onBeforeUnmount: onBeforeUnmount$7, nextTick: nextTick$1, customRef } = window.Vue;
function toRef(trame, name, triggers) {
	return customRef((track, trigger) => {
		triggers[name] = trigger;
		return {
			get() {
				track();
				return trame.state.get(name);
			},
			set(value) {
				trame.state.set(name, value);
				trigger();
			}
		};
	});
}
function setup() {
	const trame = inject$5("trame");
	const tts = ref$3(0);
	const modifiedState = {};
	const publicAPI = {
		trame,
		window,
		utils: utils_default,
		tts
	};
	trame.state.getAllKeys().forEach((name) => {
		publicAPI[name] = toRef(trame, name, modifiedState);
	});
	const onDirty = ({ type, keys }) => {
		if (type === "new-keys") for (let i = 0; i < keys.length; i++) {
			const name = keys[i];
			if (publicAPI[name] === void 0) publicAPI[name] = toRef(trame, name, modifiedState);
		}
		if (type === "dirty-state") {
			for (let i = 0; i < keys.length; i++) modifiedState[keys[i]]();
			if (keys.includes("trame__favicon") && trame.state.get("trame__favicon")) document.querySelector("link[rel=icon]").href = trame.state.get("trame__favicon");
			if (keys.includes("trame__title") && trame.state.get("trame__title")) document.title = trame.state.get("trame__title");
		}
	};
	onMounted$4(() => {
		trame.state.addListener(onDirty);
	});
	onBeforeUnmount$7(() => {
		trame.state.removeListener(onDirty);
	});
	publicAPI.trigger = (...args) => trame.trigger(...args);
	publicAPI.set = (name, value) => trame.state.set(name, value);
	publicAPI.get = (name) => publicAPI[name];
	publicAPI.setAll = (obj) => trame.state.update(obj);
	publicAPI.flushState = (...keys) => trame.state.flush(...keys);
	publicAPI.registerDecorator = (...args) => trame.state.registerDecorator(...args);
	return publicAPI;
}
var TrameTemplate_default = {
	props: {
		templateName: {
			type: String,
			default: "main"
		},
		urlKey: {
			type: String,
			default: "ui"
		},
		useUrl: {
			type: Boolean,
			default: false
		}
	},
	setup(props) {
		const trame = inject$5("trame");
		const tts = ref$3(0);
		const componentName = computed(() => {
			let templateName = props.templateName;
			if (props.useUrl && vtkURLExtract.extractURLParameters()[props.urlKey]) templateName = vtkURLExtract.extractURLParameters()[props.urlKey];
			return `trame-template-${templateName.toLowerCase()}`.replaceAll("_", "-").replaceAll("--", "-");
		});
		async function updateTemplate() {
			await nextTick$1();
			tts.value++;
		}
		const onDirty = ({ type, keys }) => {
			if (type === "dirty-state") {
				for (let i = 0; i < keys.length; i++) if (keys[i].toLowerCase().replaceAll("_", "-").replaceAll("--", "-") === componentName.value) updateTemplate();
			}
		};
		onMounted$4(() => {
			trame.state.addListener(onDirty);
		});
		onBeforeUnmount$7(() => {
			trame.state.removeListener(onDirty);
		});
		return {
			tts,
			componentName
		};
	},
	template: "<component :key=\"tts\" :is=\"componentName\" :name=\"componentName\" />"
};
//#endregion
//#region src/components/TrameApp.js
var { inject: inject$4, ref: ref$2, onBeforeMount: onBeforeMount$3, onBeforeUnmount: onBeforeUnmount$6 } = window.Vue;
var TrameApp_default = {
	props: { useUrl: {
		type: Boolean,
		default: false
	} },
	setup() {
		const trame = inject$4("trame");
		const connected = ref$2(false);
		const ready = ref$2(false);
		const busy = ref$2(1);
		const refreshTS = ref$2(1);
		const subscriptions = [];
		function registerComponent(name) {
			const templateName = `trame-template-${name.toLowerCase().substring(16)}`.replaceAll("_", "-").replaceAll("--", "-");
			const template = trame.state.get(name);
			trame.app.component(templateName, {
				props: ["name"],
				setup,
				template
			});
		}
		const stateListener = ({ type, keys }) => {
			if (type === "dirty-state") for (let i = 0; i < keys.length; i++) {
				const dirtyName = keys[i];
				if (dirtyName.startsWith("trame__template_")) registerComponent(dirtyName);
			}
			else if (type === "refresh") refreshTS.value++;
			else if (type === "ready") {
				ready.value = true;
				refreshTS.value++;
			}
		};
		function onBusy(count) {
			busy.value = count;
			if (trame.state) trame.state.set("trame__busy", count);
			if (count === 0) trame.state.flush();
		}
		function onConnect() {
			while (subscriptions.length) subscriptions.pop()();
			subscriptions.push(trame.client.onBusyChange(onBusy).unsubscribe);
			connected.value = trame.client.isConnected();
			trame.state.addListener(stateListener);
			subscriptions.push(() => trame.state.removeListener(stateListener));
			if (trame.state.ready) {
				const keys = trame.state.getAllKeys();
				for (let i = 0; i < keys.length; i++) {
					const key = keys[i];
					if (key.startsWith("trame__template_")) registerComponent(key);
				}
				ready.value = true;
				connected.value = true;
			}
			function execAction(action) {
				const { ref, type } = action;
				const elem = trame.refs[ref];
				if (elem && type === "method") {
					const { method, args } = action;
					elem[method](...args);
				}
				if (elem && type === "property") {
					const { property, value } = action;
					elem[property] = value;
				}
			}
			const wslinkSub = trame.client.getRemote().Trame.subscribeToActions(([actions]) => actions.map(execAction));
			subscriptions.push(() => trame?.client?.getRemote()?.Trame?.unsubscribe(wslinkSub));
			trame.client?.getRemote()?.Trame?.lifeCycleUpdate("client_connected");
			window.addEventListener("beforeunload", () => {
				trame.client?.getRemote()?.Trame?.lifeCycleUpdate("client_exited");
				trame.client?.getConnection()?.getSession()?.close();
			});
			const router = window.trame.utils.router;
			const routes = trame.state.get("trame__routes");
			if (routes?.length && router) routes.forEach((route) => {
				router.addRoute(route);
			});
		}
		onBeforeMount$3(() => {
			trame.addConnectListener(onConnect);
		});
		onBeforeUnmount$6(() => {
			trame.removeConnectListener(onConnect);
			trame.client?.getRemote()?.Trame?.lifeCycleUpdate("client_unmounted");
			while (subscriptions.length) subscriptions.pop()();
		});
		return {
			connected,
			ready,
			busy,
			refreshTS
		};
	},
	template: `<trame-template v-if="ready" :key="refreshTS" :use-url="useUrl" />`
};
//#endregion
//#region src/components/TrameExec.js
var { unref: unref$2 } = window.Vue;
var TrameExec_default = {
	props: ["event"],
	emits: ["exec"],
	setup(props, { emit }) {
		function exec(arg) {
			if (arg === void 0) emit("exec", unref$2(props.event));
			else emit("exec", arg);
		}
		return { exec };
	},
	template: `<slot />`
};
//#endregion
//#region src/components/TrameGetter.js
var { inject: inject$3, ref: ref$1, onBeforeMount: onBeforeMount$2, onBeforeUnmount: onBeforeUnmount$5, watch: watch$3 } = window.Vue;
var TrameGetter_default = {
	props: ["name"],
	setup(props) {
		const trame = inject$3("trame");
		const computedValue = ref$1(null);
		const computedName = ref$1(null);
		function updateNested(key, value) {
			const newData = JSON.parse(JSON.stringify(trame.state.get(props.name)));
			let current = newData;
			const steps = String(key).split(".");
			for (let i = 0; i < steps.length - 1; i++) current = current[steps[i]];
			current[steps.at(-1)] = value;
			trame.state.set(props.name, newData);
		}
		function update(value) {
			trame.state.set(props.name, value);
		}
		function updateState() {
			const newValue = trame.state.get(props.name);
			if (computedName.value !== props.name) computedName.value = props.name;
			if (newValue !== computedValue.value) computedValue.value = newValue;
		}
		watch$3(() => props.name, updateState);
		onBeforeMount$2(() => {
			trame.state.addListener(updateState);
			updateState();
		});
		onBeforeUnmount$5(() => {
			trame.state.removeListener(updateState);
		});
		return {
			computedValue,
			computedName,
			updateNested,
			update
		};
	},
	template: "<slot :keyName=\"computedName\" :update=\"update\" :updateNested=\"updateNested\" :value=\"computedValue\"></slot>"
};
//#endregion
//#region src/components/TrameLoading.js
var TrameLoading_default = {
	props: { message: {
		type: String,
		default: "Loading..."
	} },
	template: `
        <div style="position:absolute;top:0;left:0;width:100%;height:100%;z-index:1000;">
            <div class="trame__loader"></div>
            <div class="trame__message">{{ message }}</div>
        </div>
    `
};
//#endregion
//#region src/components/TrameReconnect.js
var { inject: inject$2, onMounted: onMounted$3, onBeforeUnmount: onBeforeUnmount$4 } = window.Vue;
var TrameReconnect_default = {
	props: {
		message: {
			type: String,
			default: "Click to reconnect..."
		},
		maxRetry: {
			type: Number,
			default: 10
		},
		delay: {
			type: Number,
			default: 500
		}
	},
	setup(props) {
		const trame = inject$2("trame");
		let interval = null;
		let retryCount = 0;
		async function connect() {
			await trame.connect();
		}
		function resetRetry() {
			if (interval) {
				clearInterval(interval);
				interval = null;
			}
		}
		onMounted$3(() => {
			retryCount = 0;
			const reconnect = vtkURLExtract.extractURLParameters().reconnect;
			if (reconnect) {
				console.log("reconnect", reconnect);
				if (reconnect === "auto") interval = setInterval(() => {
					if (retryCount++ < props.maxRetry) connect();
					else resetRetry();
				}, props.delay);
			}
		});
		onBeforeUnmount$4(() => {
			resetRetry();
		});
		return { connect };
	},
	template: `
    <div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1000;">
      <div style="position: relative;top: 50%;left: 50%;transform: translate(-50%, -50%);-ms-transform: translate(-50%, -50%);width: 80%;text-align: center;">
        <div style="display: flex;justify-content: space-around;text-align: center;user-select: none;background-color: #f1f1f1;color: black;font-size: 16px;padding: 10px 20px;border: none;cursor: pointer;border-radius: 5px;text-align: center;width: 200px;margin: 10px auto;" @click="connect">
          <svg
            style="width: 24px"
            xmlns="http://www.w3.org/2000/svg"
            viewBox="0 0 24 24"
          >
            <path
              d="M4,1C2.89,1 2,1.89 2,3V7C2,8.11 2.89,9 4,9H1V11H13V9H10C11.11,9 12,8.11 12,7V3C12,1.89 11.11,1 10,1H4M4,3H10V7H4V3M14,13C12.89,13 12,13.89 12,15V19C12,20.11 12.89,21 14,21H11V23H23V21H20C21.11,21 22,20.11 22,19V15C22,13.89 21.11,13 20,13H14M3.88,13.46L2.46,14.88L4.59,17L2.46,19.12L3.88,20.54L6,18.41L8.12,20.54L9.54,19.12L7.41,17L9.54,14.88L8.12,13.46L6,15.59L3.88,13.46M14,15H20V19H14V15Z"
            />
          </svg>
          {{ message }}
        </div>
      </div>
    </div>
      `
};
//#endregion
//#region src/components/TrameScript.js
var { unref: unref$1 } = window.Vue;
var ID$1 = 1;
function getNextId$1() {
	return `trame_script_elem_${ID$1++}`;
}
var TrameScript_default = {
	props: {
		script: {
			type: String,
			default: ""
		},
		module: {
			type: Boolean,
			default: false
		}
	},
	watch: { script(scriptContent) {
		this.updateContent(scriptContent);
	} },
	created() {
		this.elemId = getNextId$1();
		this.updateContent(this.script);
	},
	beforeUnmount() {
		this.removeScript();
	},
	methods: {
		updateContent(scriptContent) {
			scriptContent = unref$1(scriptContent);
			let elem = document.querySelector(`#${this.elemId}`);
			if (scriptContent) {
				if (!elem) {
					elem = document.createElement("script");
					elem.id = this.elemId;
					elem.type = this.module ? "module" : "text/javascript";
					document.head.appendChild(elem);
				}
				elem.innerHTML = scriptContent;
			} else this.removeScript();
		},
		removeScript() {
			const elem = document.querySelector(`#${this.elemId}`);
			if (elem) elem.parentNode.removeChild(elem);
		}
	},
	template: `<slot />`
};
//#endregion
//#region src/components/TrameStyle.js
var { unref } = window.Vue;
var ID = 1;
function getNextId() {
	return `trame_style_elem_${ID++}`;
}
var TrameStyle_default = {
	props: { css: {
		type: String,
		default: ""
	} },
	watch: { css(cssContent) {
		this.updateStyle(cssContent);
	} },
	created() {
		this.elemId = getNextId();
		this.updateStyle(this.css);
	},
	beforeUnmount() {
		this.removeStyle();
	},
	methods: {
		updateStyle(cssContent) {
			cssContent = unref(cssContent);
			let elem = document.querySelector(`#${this.elemId}`);
			if (cssContent) {
				if (!elem) {
					elem = document.createElement("style");
					elem.id = this.elemId;
					document.head.appendChild(elem);
				}
				elem.innerHTML = cssContent;
			} else this.removeStyle();
		},
		removeStyle() {
			const elem = document.querySelector(`#${this.elemId}`);
			if (elem) elem.parentNode.removeChild(elem);
		}
	},
	template: `<slot />`
};
//#endregion
//#region src/components/TrameClientStateChange.js
var { watch: watch$2, nextTick } = window.Vue;
var TrameClientStateChange_default = {
	props: {
		value: { type: String },
		immediate: {
			type: Boolean,
			default: false
		},
		triggerChangeOnCreate: {
			type: Boolean,
			default: false
		}
	},
	emits: ["change"],
	setup(props, { emit }) {
		watch$2(() => props.value, (v) => {
			if (props.immediate) emit("change", v);
			else nextTick(() => {
				emit("change", v);
			});
		});
		if (props.triggerChangeOnCreate) emit("change", props.value);
	},
	template: `<slot />`
};
//#endregion
//#region src/components/TrameClientTriggers.js
var { onMounted: onMounted$2, onBeforeUnmount: onBeforeUnmount$3 } = window.Vue;
var TrameClientTriggers_default = {
	emits: [
		"mounted",
		"created",
		"beforeDestroy",
		"beforeUnmount",
		"exit"
	],
	setup(props, { emit, expose }) {
		function emitTopic(topic, event) {
			emit(topic, event);
		}
		onMounted$2(() => emit("mounted"));
		onBeforeUnmount$3(() => {
			emit("beforeDestroy");
			emit("beforeUnmount");
		});
		window.addEventListener("beforeunload", () => {
			emit("exit");
		});
		expose({ emit: emitTopic });
		emit("created");
		return { emit: emitTopic };
	},
	template: `<slot />`
};
//#endregion
//#region src/components/TrameDeepReactive.js
var { inject: inject$1, reactive: reactive$1, onBeforeMount: onBeforeMount$1, onBeforeUnmount: onBeforeUnmount$2, watch: watch$1 } = window.Vue;
var TrameDeepReactive_default = {
	props: ["name"],
	setup(props) {
		const trame = inject$1("trame");
		const value = reactive$1({});
		let trameStr = null;
		let refStr = null;
		function pushChange() {
			refStr = JSON.stringify(value);
			if (refStr !== trameStr) trame.state.set(props.name, JSON.parse(refStr));
		}
		function fetchValue() {
			trameStr = JSON.stringify(trame.state.get(props.name));
			if (trameStr !== refStr) {
				const updatedValue = JSON.parse(trameStr);
				Object.assign(value, updatedValue);
				const keyToDelete = Object.keys(value).filter((name) => !(name in updatedValue));
				for (let i = 0; i < keyToDelete.length; i++) delete value[keyToDelete[i]];
			}
		}
		function updateState({ type, keys }) {
			if (type === "dirty-state" && keys.includes(props.name)) fetchValue();
		}
		onBeforeMount$1(() => {
			trame.state.addListener(updateState);
			fetchValue();
		});
		onBeforeUnmount$2(() => {
			trame.state.removeListener(updateState);
		});
		watch$1(value, pushChange);
		return { value };
	},
	template: "<slot :value=\"value\"></slot>"
};
//#endregion
//#region src/components/TrameLifeCycleMonitor.js
var { onMounted: onMounted$1, onUpdated, onUnmounted, onBeforeMount, onBeforeUpdate, onBeforeUnmount: onBeforeUnmount$1 } = window.Vue;
function runNow(fn) {
	fn();
}
var NAME_TO_LIFE_CYCLE = {
	created: runNow,
	beforeMount: onBeforeMount,
	mounted: onMounted$1,
	beforeUpdate: onBeforeUpdate,
	updated: onUpdated,
	beforeDestroy: onBeforeUnmount$1,
	destroyed: onUnmounted
};
var TrameLifeCycleMonitor_default = {
	props: {
		name: {
			type: String,
			default: "LifeCycleMonitor"
		},
		type: {
			type: String,
			default: "log"
		},
		value: {
			type: String,
			default: "value"
		},
		events: {
			type: Array,
			default: () => [
				"created",
				"beforeMount",
				"mounted",
				"beforeUpdate",
				"updated",
				"beforeDestroy",
				"destroyed"
			]
		}
	},
	emits: Object.keys(NAME_TO_LIFE_CYCLE),
	setup(props, { emit }) {
		for (let i = 0; i < props.events.length; i++) {
			const name = props.events[i];
			const fn = NAME_TO_LIFE_CYCLE[name];
			fn(() => {
				if (props.type === "emit") emit(name, {
					name: props.name,
					value: props.value
				});
				else console[props.type](props.name, name, props.value);
			});
		}
	},
	template: `<slot />`
};
//#endregion
//#region src/components/TrameSizeObserver.js
var { inject, ref, onMounted, onBeforeUnmount } = window.Vue;
var TrameSizeObserver_default = {
	props: { name: { type: String } },
	emits: ["change"],
	setup(props, { emit }) {
		const trame = inject("trame");
		const elem = ref(null);
		function resize() {
			const { x, y, width, height } = elem.value.getBoundingClientRect();
			const size = {
				x,
				y,
				width,
				height
			};
			const pixelRatio = window.devicePixelRatio;
			const event = {
				size,
				pixelRatio,
				dpi: 96 * pixelRatio
			};
			if (props.name) event.name = props.name;
			if (trame) trame.state.set(props.name, event);
			emit("change", event);
		}
		const sizeObserver = new ResizeObserver(resize);
		onMounted(() => {
			sizeObserver.observe(elem.value);
		});
		onBeforeUnmount(() => {
			sizeObserver.unobserve(elem.value);
		});
		return {
			elem,
			resize
		};
	},
	template: "<div ref=\"elem\" style=\"overflow: hidden; position: relative; width: 100%; height: 100%; margin: 0; padding: 0;\"><slot></slot></div>"
};
//#endregion
//#region src/components/TrameHandler.js
var { reactive, watch } = window.Vue;
//#endregion
//#region src/components/index.js
var components_default = {
	TrameApp: TrameApp_default,
	TrameExec: TrameExec_default,
	TrameGetter: TrameGetter_default,
	TrameLoading: TrameLoading_default,
	TrameReconnect: TrameReconnect_default,
	TrameScript: TrameScript_default,
	TrameStyle: TrameStyle_default,
	TrameTemplate: TrameTemplate_default,
	TrameClientStateChange: TrameClientStateChange_default,
	TrameClientTriggers: TrameClientTriggers_default,
	TrameDeepReactive: TrameDeepReactive_default,
	TrameLifeCycleMonitor: TrameLifeCycleMonitor_default,
	TrameSizeObserver: TrameSizeObserver_default,
	TrameHandler: {
		emits: [
			"success",
			"failure",
			"error",
			"completed"
		],
		props: {
			functionKey: { type: String },
			triggerOnChange: {
				type: Boolean,
				default: true
			},
			inputs: { type: Object }
		},
		setup(props, { emit }) {
			const input_data = reactive({ value: null });
			watch(input_data, () => {
				if (props.triggerOnChange) run();
			});
			const run = async function run(input_override, inputs) {
				let input = input_data.value;
				let additional_inputs = props.inputs;
				if (input_override) input = input_override;
				if (inputs) additional_inputs = inputs;
				const user_logic_handle = window.TRAME_EXTERNAL_SCRIPTS[props.functionKey];
				if (!user_logic_handle) {
					const message = `Could not find user script function ${props.functionKey}`;
					console.error(message);
					emit("error", message);
					return;
				}
				const function_handle = user_logic_handle.func;
				try {
					const result = await function_handle(input, additional_inputs);
					const event_type = result.status ?? true ? "success" : "failure";
					emit("completed", {
						type: event_type,
						outputs: result.outputs ?? result
					});
					emit(event_type, result.outputs);
				} catch (error) {
					console.error(error);
					emit("error", error);
				}
			};
			return {
				run,
				input_data
			};
		},
		template: `<slot :run="run" :input_data="input_data" />`
	}
};
//#endregion
//#region src/use.js
var use_default = { install(app) {
	Object.keys(components_default).forEach((name) => {
		app.component(name, components_default[name]);
	});
} };
//#endregion
//#region src/main.js
var { createApp } = window.Vue;
async function start() {
	try {
		if (!window.WSLINK && window?.parent?.trameJupyter?.init) window.WSLINK = window.parent.trameJupyter.init(window);
	} catch (e) {}
	const app = createApp({ template: `<trame-app use-url />` });
	let trame = createTrameInstance(app);
	let config = wslink_default.configDecorator({
		application: "trame",
		useUrl: true
	});
	const params = new URL(window.location).searchParams;
	[
		"sessionURL",
		"sessionManagerURL",
		"secret",
		"application",
		"remove"
	].concat(params.get("remove")?.split(",") || []).forEach((v) => params.delete(v));
	const cleanURL = `${window.location.pathname}${params.size ? "?" : ""}${params.toString()}${window.location.hash}`;
	window.history.replaceState({}, document.title, cleanURL);
	trame.addConnectListener(() => {
		trame.client.onConnectionError((httpReq) => {
			reportWsError(httpReq?.response?.error || "Connection error");
		});
		trame.client.onConnectionClose((httpReq) => {
			reportWsError(httpReq?.response?.error || "Connection closed");
		});
	});
	function reportWsError(message) {
		if (trame && trame.state) {
			console.log("about to replace template", message);
			trame.state.set("trame_error_report_msg", message);
			let templateName = "trame__template_main";
			if (vtkURLExtract.extractURLParameters().ui) templateName = `trame__template_${vtkURLExtract.extractURLParameters().ui}`;
			if (config.reconnect) trame.state.set(templateName, trame.state.get("trame__template_error_reconnect") || `<trame-reconnect message="${message}"/>`);
			else trame.state.set(templateName, trame.state.get("trame__template_error") || `<trame-loading message="${message}"/>`);
			console.log("template replaced", trame.state.get(templateName));
		} else {
			app.unmount();
			document.querySelector("#app").innerHTML = message;
		}
	}
	try {
		config = await trame.connect(config);
	} catch (e) {
		reportWsError(e?.response?.error || "try/catch on connect()");
		return;
	}
	const _error = console.error;
	console.error = (...args) => {
		try {
			if (trame.client.isConnected()) trame.client.getRemote().Trame.sendError(args.join(" "));
		} catch (e) {
			_error(e);
		} finally {
			_error(...args);
		}
	};
	window.addEventListener("error", (event) => console.error(`${event.type}: ${event.message}`));
	app.use(use_default);
	app.provide("trame", trame);
	const uses = await handlePageResources(trame.state.state);
	for (let i = 0; i < uses.length; i++) {
		app.use(...uses[i]);
		console.info(`Vue.use(${uses[i]})`);
	}
	app.mount("#app");
	registerUserScripts();
}
var urlParams = vtkURLExtract.extractURLParameters();
if (urlParams.enableSharedArrayBufferServiceWorker) loadScript("coi-serviceworker.js");
if (urlParams.wsChannel) window.addEventListener("message", (event) => {
	if (event.data !== "trame-ws-channel-init") return;
	window.WSLINK = { createWebSocket: createMessageChannelWSFactory(event.ports[0]) };
	start();
});
else start();
//#endregion
