"use strict";
(() => {
  var __defProp = Object.defineProperty;
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);

  // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/utils/utf8.mjs
  var sharedTextEncoder = new TextEncoder();
  var CHUNK_SIZE = 4096;
  function utf8DecodeJs(bytes, inputOffset, byteLength) {
    let offset = inputOffset;
    const end = offset + byteLength;
    const units = [];
    let result = "";
    while (offset < end) {
      const byte1 = bytes[offset++];
      if ((byte1 & 128) === 0) {
        units.push(byte1);
      } else if ((byte1 & 224) === 192) {
        const byte2 = bytes[offset++] & 63;
        units.push((byte1 & 31) << 6 | byte2);
      } else if ((byte1 & 240) === 224) {
        const byte2 = bytes[offset++] & 63;
        const byte3 = bytes[offset++] & 63;
        units.push((byte1 & 31) << 12 | byte2 << 6 | byte3);
      } else if ((byte1 & 248) === 240) {
        const byte2 = bytes[offset++] & 63;
        const byte3 = bytes[offset++] & 63;
        const byte4 = bytes[offset++] & 63;
        let 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(...units);
        units.length = 0;
      }
    }
    if (units.length > 0) {
      result += String.fromCharCode(...units);
    }
    return result;
  }
  var sharedTextDecoder = new TextDecoder();
  var TEXT_DECODER_THRESHOLD = 200;
  function utf8DecodeTD(bytes, inputOffset, byteLength) {
    const stringBytes = bytes.subarray(inputOffset, inputOffset + byteLength);
    return sharedTextDecoder.decode(stringBytes);
  }
  function utf8Decode(bytes, inputOffset, byteLength) {
    if (byteLength > TEXT_DECODER_THRESHOLD) {
      return utf8DecodeTD(bytes, inputOffset, byteLength);
    } else {
      return utf8DecodeJs(bytes, inputOffset, byteLength);
    }
  }

  // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/ExtData.mjs
  var ExtData = class {
    constructor(type, data) {
      __publicField(this, "type");
      __publicField(this, "data");
      this.type = type;
      this.data = data;
    }
  };

  // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/DecodeError.mjs
  var DecodeError = class _DecodeError extends Error {
    constructor(message) {
      super(message);
      const proto = Object.create(_DecodeError.prototype);
      Object.setPrototypeOf(this, proto);
      Object.defineProperty(this, "name", {
        configurable: true,
        enumerable: false,
        value: _DecodeError.name
      });
    }
  };

  // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/utils/int.mjs
  var UINT32_MAX = 4294967295;
  function setInt64(view, offset, value) {
    const high = Math.floor(value / 4294967296);
    const low = value;
    view.setUint32(offset, high);
    view.setUint32(offset + 4, low);
  }
  function getInt64(view, offset) {
    const high = view.getInt32(offset);
    const low = view.getUint32(offset + 4);
    return high * 4294967296 + low;
  }
  function getUint64(view, offset) {
    const high = view.getUint32(offset);
    const low = view.getUint32(offset + 4);
    return high * 4294967296 + low;
  }

  // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/timestamp.mjs
  var EXT_TIMESTAMP = -1;
  var TIMESTAMP32_MAX_SEC = 4294967296 - 1;
  var TIMESTAMP64_MAX_SEC = 17179869184 - 1;
  function encodeTimeSpecToTimestamp({ sec, nsec }) {
    if (sec >= 0 && nsec >= 0 && sec <= TIMESTAMP64_MAX_SEC) {
      if (nsec === 0 && sec <= TIMESTAMP32_MAX_SEC) {
        const rv = new Uint8Array(4);
        const view = new DataView(rv.buffer);
        view.setUint32(0, sec);
        return rv;
      } else {
        const secHigh = sec / 4294967296;
        const secLow = sec & 4294967295;
        const rv = new Uint8Array(8);
        const view = new DataView(rv.buffer);
        view.setUint32(0, nsec << 2 | secHigh & 3);
        view.setUint32(4, secLow);
        return rv;
      }
    } else {
      const rv = new Uint8Array(12);
      const view = new DataView(rv.buffer);
      view.setUint32(0, nsec);
      setInt64(view, 4, sec);
      return rv;
    }
  }
  function encodeDateToTimeSpec(date) {
    const msec = date.getTime();
    const sec = Math.floor(msec / 1e3);
    const nsec = (msec - sec * 1e3) * 1e6;
    const nsecInSec = Math.floor(nsec / 1e9);
    return {
      sec: sec + nsecInSec,
      nsec: nsec - nsecInSec * 1e9
    };
  }
  function encodeTimestampExtension(object) {
    if (object instanceof Date) {
      const timeSpec = encodeDateToTimeSpec(object);
      return encodeTimeSpecToTimestamp(timeSpec);
    } else {
      return null;
    }
  }
  function decodeTimestampToTimeSpec(data) {
    const view = new DataView(data.buffer, data.byteOffset, data.byteLength);
    switch (data.byteLength) {
      case 4: {
        const sec = view.getUint32(0);
        const nsec = 0;
        return { sec, nsec };
      }
      case 8: {
        const nsec30AndSecHigh2 = view.getUint32(0);
        const secLow32 = view.getUint32(4);
        const sec = (nsec30AndSecHigh2 & 3) * 4294967296 + secLow32;
        const nsec = nsec30AndSecHigh2 >>> 2;
        return { sec, nsec };
      }
      case 12: {
        const sec = getInt64(view, 4);
        const nsec = view.getUint32(0);
        return { sec, nsec };
      }
      default:
        throw new DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${data.length}`);
    }
  }
  function decodeTimestampExtension(data) {
    const timeSpec = decodeTimestampToTimeSpec(data);
    return new Date(timeSpec.sec * 1e3 + timeSpec.nsec / 1e6);
  }
  var timestampExtension = {
    type: EXT_TIMESTAMP,
    encode: encodeTimestampExtension,
    decode: decodeTimestampExtension
  };

  // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/ExtensionCodec.mjs
  var _ExtensionCodec = class _ExtensionCodec {
    constructor() {
      // ensures ExtensionCodecType<X> matches ExtensionCodec<X>
      // this will make type errors a lot more clear
      // eslint-disable-next-line @typescript-eslint/naming-convention
      __publicField(this, "__brand");
      // built-in extensions
      __publicField(this, "builtInEncoders", []);
      __publicField(this, "builtInDecoders", []);
      // custom extensions
      __publicField(this, "encoders", []);
      __publicField(this, "decoders", []);
      this.register(timestampExtension);
    }
    register({ type, encode, decode: decode2 }) {
      if (type >= 0) {
        this.encoders[type] = encode;
        this.decoders[type] = decode2;
      } else {
        const index = -1 - type;
        this.builtInEncoders[index] = encode;
        this.builtInDecoders[index] = decode2;
      }
    }
    tryToEncode(object, context) {
      for (let i = 0; i < this.builtInEncoders.length; i++) {
        const encodeExt = this.builtInEncoders[i];
        if (encodeExt != null) {
          const data = encodeExt(object, context);
          if (data != null) {
            const type = -1 - i;
            return new ExtData(type, data);
          }
        }
      }
      for (let i = 0; i < this.encoders.length; i++) {
        const encodeExt = this.encoders[i];
        if (encodeExt != null) {
          const data = encodeExt(object, context);
          if (data != null) {
            const type = i;
            return new ExtData(type, data);
          }
        }
      }
      if (object instanceof ExtData) {
        return object;
      }
      return null;
    }
    decode(data, type, context) {
      const decodeExt = type < 0 ? this.builtInDecoders[-1 - type] : this.decoders[type];
      if (decodeExt) {
        return decodeExt(data, type, context);
      } else {
        return new ExtData(type, data);
      }
    }
  };
  __publicField(_ExtensionCodec, "defaultCodec", new _ExtensionCodec());
  var ExtensionCodec = _ExtensionCodec;

  // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/utils/typedArrays.mjs
  function isArrayBufferLike(buffer) {
    return buffer instanceof ArrayBuffer || typeof SharedArrayBuffer !== "undefined" && buffer instanceof SharedArrayBuffer;
  }
  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 (isArrayBufferLike(buffer)) {
      return new Uint8Array(buffer);
    } else {
      return Uint8Array.from(buffer);
    }
  }

  // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/utils/prettyByte.mjs
  function prettyByte(byte) {
    return `${byte < 0 ? "-" : ""}0x${Math.abs(byte).toString(16).padStart(2, "0")}`;
  }

  // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/CachedKeyDecoder.mjs
  var DEFAULT_MAX_KEY_LENGTH = 16;
  var DEFAULT_MAX_LENGTH_PER_KEY = 16;
  var CachedKeyDecoder = class {
    constructor(maxKeyLength = DEFAULT_MAX_KEY_LENGTH, maxLengthPerKey = DEFAULT_MAX_LENGTH_PER_KEY) {
      __publicField(this, "hit", 0);
      __publicField(this, "miss", 0);
      __publicField(this, "caches");
      __publicField(this, "maxKeyLength");
      __publicField(this, "maxLengthPerKey");
      this.maxKeyLength = maxKeyLength;
      this.maxLengthPerKey = maxLengthPerKey;
      this.caches = [];
      for (let i = 0; i < this.maxKeyLength; i++) {
        this.caches.push([]);
      }
    }
    canBeCached(byteLength) {
      return byteLength > 0 && byteLength <= this.maxKeyLength;
    }
    find(bytes, inputOffset, byteLength) {
      const records = this.caches[byteLength - 1];
      FIND_CHUNK: for (const record of records) {
        const recordBytes = record.bytes;
        for (let j = 0; j < byteLength; j++) {
          if (recordBytes[j] !== bytes[inputOffset + j]) {
            continue FIND_CHUNK;
          }
        }
        return record.str;
      }
      return null;
    }
    store(bytes, value) {
      const records = this.caches[bytes.length - 1];
      const record = { bytes, str: value };
      if (records.length >= this.maxLengthPerKey) {
        records[Math.random() * records.length | 0] = record;
      } else {
        records.push(record);
      }
    }
    decode(bytes, inputOffset, byteLength) {
      const cachedValue = this.find(bytes, inputOffset, byteLength);
      if (cachedValue != null) {
        this.hit++;
        return cachedValue;
      }
      this.miss++;
      const str = utf8DecodeJs(bytes, inputOffset, byteLength);
      const slicedCopyOfBytes = Uint8Array.prototype.slice.call(bytes, inputOffset, inputOffset + byteLength);
      this.store(slicedCopyOfBytes, str);
      return str;
    }
  };

  // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/Decoder.mjs
  var STATE_ARRAY = "array";
  var STATE_MAP_KEY = "map_key";
  var STATE_MAP_VALUE = "map_value";
  var mapKeyConverter = (key) => {
    if (typeof key === "string" || typeof key === "number") {
      return key;
    }
    throw new DecodeError("The type of key must be string or number but " + typeof key);
  };
  var StackPool = class {
    constructor() {
      __publicField(this, "stack", []);
      __publicField(this, "stackHeadPosition", -1);
    }
    get length() {
      return this.stackHeadPosition + 1;
    }
    top() {
      return this.stack[this.stackHeadPosition];
    }
    pushArrayState(size) {
      const state = this.getUninitializedStateFromPool();
      state.type = STATE_ARRAY;
      state.position = 0;
      state.size = size;
      state.array = new Array(size);
    }
    pushMapState(size) {
      const state = this.getUninitializedStateFromPool();
      state.type = STATE_MAP_KEY;
      state.readCount = 0;
      state.size = size;
      state.map = {};
    }
    getUninitializedStateFromPool() {
      this.stackHeadPosition++;
      if (this.stackHeadPosition === this.stack.length) {
        const partialState = {
          type: void 0,
          size: 0,
          array: void 0,
          position: 0,
          readCount: 0,
          map: void 0,
          key: null
        };
        this.stack.push(partialState);
      }
      return this.stack[this.stackHeadPosition];
    }
    release(state) {
      const topStackState = this.stack[this.stackHeadPosition];
      if (topStackState !== state) {
        throw new Error("Invalid stack state. Released state is not on top of the stack.");
      }
      if (state.type === STATE_ARRAY) {
        const partialState = state;
        partialState.size = 0;
        partialState.array = void 0;
        partialState.position = 0;
        partialState.type = void 0;
      }
      if (state.type === STATE_MAP_KEY || state.type === STATE_MAP_VALUE) {
        const partialState = state;
        partialState.size = 0;
        partialState.map = void 0;
        partialState.readCount = 0;
        partialState.type = void 0;
      }
      this.stackHeadPosition--;
    }
    reset() {
      this.stack.length = 0;
      this.stackHeadPosition = -1;
    }
  };
  var HEAD_BYTE_REQUIRED = -1;
  var EMPTY_VIEW = new DataView(new ArrayBuffer(0));
  var EMPTY_BYTES = new Uint8Array(EMPTY_VIEW.buffer);
  try {
    EMPTY_VIEW.getInt8(0);
  } catch (e) {
    if (!(e instanceof RangeError)) {
      throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access");
    }
  }
  var MORE_DATA = new RangeError("Insufficient data");
  var sharedCachedKeyDecoder = new CachedKeyDecoder();
  var Decoder = class _Decoder {
    constructor(options) {
      __publicField(this, "extensionCodec");
      __publicField(this, "context");
      __publicField(this, "useBigInt64");
      __publicField(this, "rawStrings");
      __publicField(this, "maxStrLength");
      __publicField(this, "maxBinLength");
      __publicField(this, "maxArrayLength");
      __publicField(this, "maxMapLength");
      __publicField(this, "maxExtLength");
      __publicField(this, "keyDecoder");
      __publicField(this, "mapKeyConverter");
      __publicField(this, "totalPos", 0);
      __publicField(this, "pos", 0);
      __publicField(this, "view", EMPTY_VIEW);
      __publicField(this, "bytes", EMPTY_BYTES);
      __publicField(this, "headByte", HEAD_BYTE_REQUIRED);
      __publicField(this, "stack", new StackPool());
      __publicField(this, "entered", false);
      this.extensionCodec = options?.extensionCodec ?? ExtensionCodec.defaultCodec;
      this.context = options?.context;
      this.useBigInt64 = options?.useBigInt64 ?? false;
      this.rawStrings = options?.rawStrings ?? false;
      this.maxStrLength = options?.maxStrLength ?? UINT32_MAX;
      this.maxBinLength = options?.maxBinLength ?? UINT32_MAX;
      this.maxArrayLength = options?.maxArrayLength ?? UINT32_MAX;
      this.maxMapLength = options?.maxMapLength ?? UINT32_MAX;
      this.maxExtLength = options?.maxExtLength ?? UINT32_MAX;
      this.keyDecoder = options?.keyDecoder !== void 0 ? options.keyDecoder : sharedCachedKeyDecoder;
      this.mapKeyConverter = options?.mapKeyConverter ?? mapKeyConverter;
    }
    clone() {
      return new _Decoder({
        extensionCodec: this.extensionCodec,
        context: this.context,
        useBigInt64: this.useBigInt64,
        rawStrings: this.rawStrings,
        maxStrLength: this.maxStrLength,
        maxBinLength: this.maxBinLength,
        maxArrayLength: this.maxArrayLength,
        maxMapLength: this.maxMapLength,
        maxExtLength: this.maxExtLength,
        keyDecoder: this.keyDecoder
      });
    }
    reinitializeState() {
      this.totalPos = 0;
      this.headByte = HEAD_BYTE_REQUIRED;
      this.stack.reset();
    }
    setBuffer(buffer) {
      const bytes = ensureUint8Array(buffer);
      this.bytes = bytes;
      this.view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
      this.pos = 0;
    }
    appendBuffer(buffer) {
      if (this.headByte === HEAD_BYTE_REQUIRED && !this.hasRemaining(1)) {
        this.setBuffer(buffer);
      } else {
        const remainingData = this.bytes.subarray(this.pos);
        const newData = ensureUint8Array(buffer);
        const newBuffer = new Uint8Array(remainingData.length + newData.length);
        newBuffer.set(remainingData);
        newBuffer.set(newData, remainingData.length);
        this.setBuffer(newBuffer);
      }
    }
    hasRemaining(size) {
      return this.view.byteLength - this.pos >= size;
    }
    createExtraByteError(posToShow) {
      const { view, pos } = this;
      return new RangeError(`Extra ${view.byteLength - pos} of ${view.byteLength} byte(s) found at buffer[${posToShow}]`);
    }
    /**
     * @throws {@link DecodeError}
     * @throws {@link RangeError}
     */
    decode(buffer) {
      if (this.entered) {
        const instance = this.clone();
        return instance.decode(buffer);
      }
      try {
        this.entered = true;
        this.reinitializeState();
        this.setBuffer(buffer);
        const object = this.doDecodeSync();
        if (this.hasRemaining(1)) {
          throw this.createExtraByteError(this.pos);
        }
        return object;
      } finally {
        this.entered = false;
      }
    }
    *decodeMulti(buffer) {
      if (this.entered) {
        const instance = this.clone();
        yield* instance.decodeMulti(buffer);
        return;
      }
      try {
        this.entered = true;
        this.reinitializeState();
        this.setBuffer(buffer);
        while (this.hasRemaining(1)) {
          yield this.doDecodeSync();
        }
      } finally {
        this.entered = false;
      }
    }
    async decodeAsync(stream) {
      if (this.entered) {
        const instance = this.clone();
        return instance.decodeAsync(stream);
      }
      try {
        this.entered = true;
        let decoded = false;
        let object;
        for await (const buffer of stream) {
          if (decoded) {
            this.entered = false;
            throw this.createExtraByteError(this.totalPos);
          }
          this.appendBuffer(buffer);
          try {
            object = this.doDecodeSync();
            decoded = true;
          } catch (e) {
            if (!(e instanceof RangeError)) {
              throw e;
            }
          }
          this.totalPos += this.pos;
        }
        if (decoded) {
          if (this.hasRemaining(1)) {
            throw this.createExtraByteError(this.totalPos);
          }
          return object;
        }
        const { headByte, pos, totalPos } = this;
        throw new RangeError(`Insufficient data in parsing ${prettyByte(headByte)} at ${totalPos} (${pos} in the current buffer)`);
      } finally {
        this.entered = false;
      }
    }
    decodeArrayStream(stream) {
      return this.decodeMultiAsync(stream, true);
    }
    decodeStream(stream) {
      return this.decodeMultiAsync(stream, false);
    }
    async *decodeMultiAsync(stream, isArray) {
      if (this.entered) {
        const instance = this.clone();
        yield* instance.decodeMultiAsync(stream, isArray);
        return;
      }
      try {
        this.entered = true;
        let isArrayHeaderRequired = isArray;
        let arrayItemsLeft = -1;
        for await (const buffer of stream) {
          if (isArray && arrayItemsLeft === 0) {
            throw this.createExtraByteError(this.totalPos);
          }
          this.appendBuffer(buffer);
          if (isArrayHeaderRequired) {
            arrayItemsLeft = this.readArraySize();
            isArrayHeaderRequired = false;
            this.complete();
          }
          try {
            while (true) {
              yield this.doDecodeSync();
              if (--arrayItemsLeft === 0) {
                break;
              }
            }
          } catch (e) {
            if (!(e instanceof RangeError)) {
              throw e;
            }
          }
          this.totalPos += this.pos;
        }
      } finally {
        this.entered = false;
      }
    }
    doDecodeSync() {
      DECODE: while (true) {
        const headByte = this.readHeadByte();
        let object;
        if (headByte >= 224) {
          object = headByte - 256;
        } else if (headByte < 192) {
          if (headByte < 128) {
            object = headByte;
          } else if (headByte < 144) {
            const size = headByte - 128;
            if (size !== 0) {
              this.pushMapState(size);
              this.complete();
              continue DECODE;
            } else {
              object = {};
            }
          } else if (headByte < 160) {
            const size = headByte - 144;
            if (size !== 0) {
              this.pushArrayState(size);
              this.complete();
              continue DECODE;
            } else {
              object = [];
            }
          } else {
            const byteLength = headByte - 160;
            object = this.decodeString(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) {
          if (this.useBigInt64) {
            object = this.readU64AsBigInt();
          } else {
            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) {
          if (this.useBigInt64) {
            object = this.readI64AsBigInt();
          } else {
            object = this.readI64();
          }
        } else if (headByte === 217) {
          const byteLength = this.lookU8();
          object = this.decodeString(byteLength, 1);
        } else if (headByte === 218) {
          const byteLength = this.lookU16();
          object = this.decodeString(byteLength, 2);
        } else if (headByte === 219) {
          const byteLength = this.lookU32();
          object = this.decodeString(byteLength, 4);
        } else if (headByte === 220) {
          const size = this.readU16();
          if (size !== 0) {
            this.pushArrayState(size);
            this.complete();
            continue DECODE;
          } else {
            object = [];
          }
        } else if (headByte === 221) {
          const size = this.readU32();
          if (size !== 0) {
            this.pushArrayState(size);
            this.complete();
            continue DECODE;
          } else {
            object = [];
          }
        } else if (headByte === 222) {
          const size = this.readU16();
          if (size !== 0) {
            this.pushMapState(size);
            this.complete();
            continue DECODE;
          } else {
            object = {};
          }
        } else if (headByte === 223) {
          const size = this.readU32();
          if (size !== 0) {
            this.pushMapState(size);
            this.complete();
            continue DECODE;
          } else {
            object = {};
          }
        } else if (headByte === 196) {
          const size = this.lookU8();
          object = this.decodeBinary(size, 1);
        } else if (headByte === 197) {
          const size = this.lookU16();
          object = this.decodeBinary(size, 2);
        } else if (headByte === 198) {
          const 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) {
          const size = this.lookU8();
          object = this.decodeExtension(size, 1);
        } else if (headByte === 200) {
          const size = this.lookU16();
          object = this.decodeExtension(size, 2);
        } else if (headByte === 201) {
          const size = this.lookU32();
          object = this.decodeExtension(size, 4);
        } else {
          throw new DecodeError(`Unrecognized type byte: ${prettyByte(headByte)}`);
        }
        this.complete();
        const stack = this.stack;
        while (stack.length > 0) {
          const state = stack.top();
          if (state.type === STATE_ARRAY) {
            state.array[state.position] = object;
            state.position++;
            if (state.position === state.size) {
              object = state.array;
              stack.release(state);
            } else {
              continue DECODE;
            }
          } else if (state.type === STATE_MAP_KEY) {
            if (object === "__proto__") {
              throw new DecodeError("The key __proto__ is not allowed");
            }
            state.key = this.mapKeyConverter(object);
            state.type = STATE_MAP_VALUE;
            continue DECODE;
          } else {
            state.map[state.key] = object;
            state.readCount++;
            if (state.readCount === state.size) {
              object = state.map;
              stack.release(state);
            } else {
              state.key = null;
              state.type = STATE_MAP_KEY;
              continue DECODE;
            }
          }
        }
        return object;
      }
    }
    readHeadByte() {
      if (this.headByte === HEAD_BYTE_REQUIRED) {
        this.headByte = this.readU8();
      }
      return this.headByte;
    }
    complete() {
      this.headByte = HEAD_BYTE_REQUIRED;
    }
    readArraySize() {
      const 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: ${prettyByte(headByte)}`);
          }
        }
      }
    }
    pushMapState(size) {
      if (size > this.maxMapLength) {
        throw new DecodeError(`Max length exceeded: map length (${size}) > maxMapLengthLength (${this.maxMapLength})`);
      }
      this.stack.pushMapState(size);
    }
    pushArrayState(size) {
      if (size > this.maxArrayLength) {
        throw new DecodeError(`Max length exceeded: array length (${size}) > maxArrayLength (${this.maxArrayLength})`);
      }
      this.stack.pushArrayState(size);
    }
    decodeString(byteLength, headerOffset) {
      if (!this.rawStrings || this.stateIsMapKey()) {
        return this.decodeUtf8String(byteLength, headerOffset);
      }
      return this.decodeBinary(byteLength, headerOffset);
    }
    /**
     * @throws {@link RangeError}
     */
    decodeUtf8String(byteLength, headerOffset) {
      if (byteLength > this.maxStrLength) {
        throw new DecodeError(`Max length exceeded: UTF-8 byte length (${byteLength}) > maxStrLength (${this.maxStrLength})`);
      }
      if (this.bytes.byteLength < this.pos + headerOffset + byteLength) {
        throw MORE_DATA;
      }
      const offset = this.pos + headerOffset;
      let object;
      if (this.stateIsMapKey() && this.keyDecoder?.canBeCached(byteLength)) {
        object = this.keyDecoder.decode(this.bytes, offset, byteLength);
      } else {
        object = utf8Decode(this.bytes, offset, byteLength);
      }
      this.pos += headerOffset + byteLength;
      return object;
    }
    stateIsMapKey() {
      if (this.stack.length > 0) {
        const state = this.stack.top();
        return state.type === STATE_MAP_KEY;
      }
      return false;
    }
    /**
     * @throws {@link RangeError}
     */
    decodeBinary(byteLength, headOffset) {
      if (byteLength > this.maxBinLength) {
        throw new DecodeError(`Max length exceeded: bin length (${byteLength}) > maxBinLength (${this.maxBinLength})`);
      }
      if (!this.hasRemaining(byteLength + headOffset)) {
        throw MORE_DATA;
      }
      const offset = this.pos + headOffset;
      const object = this.bytes.subarray(offset, offset + byteLength);
      this.pos += headOffset + byteLength;
      return object;
    }
    decodeExtension(size, headOffset) {
      if (size > this.maxExtLength) {
        throw new DecodeError(`Max length exceeded: ext length (${size}) > maxExtLength (${this.maxExtLength})`);
      }
      const extType = this.view.getInt8(this.pos + headOffset);
      const data = this.decodeBinary(
        size,
        headOffset + 1
        /* extType */
      );
      return this.extensionCodec.decode(data, extType, this.context);
    }
    lookU8() {
      return this.view.getUint8(this.pos);
    }
    lookU16() {
      return this.view.getUint16(this.pos);
    }
    lookU32() {
      return this.view.getUint32(this.pos);
    }
    readU8() {
      const value = this.view.getUint8(this.pos);
      this.pos++;
      return value;
    }
    readI8() {
      const value = this.view.getInt8(this.pos);
      this.pos++;
      return value;
    }
    readU16() {
      const value = this.view.getUint16(this.pos);
      this.pos += 2;
      return value;
    }
    readI16() {
      const value = this.view.getInt16(this.pos);
      this.pos += 2;
      return value;
    }
    readU32() {
      const value = this.view.getUint32(this.pos);
      this.pos += 4;
      return value;
    }
    readI32() {
      const value = this.view.getInt32(this.pos);
      this.pos += 4;
      return value;
    }
    readU64() {
      const value = getUint64(this.view, this.pos);
      this.pos += 8;
      return value;
    }
    readI64() {
      const value = getInt64(this.view, this.pos);
      this.pos += 8;
      return value;
    }
    readU64AsBigInt() {
      const value = this.view.getBigUint64(this.pos);
      this.pos += 8;
      return value;
    }
    readI64AsBigInt() {
      const value = this.view.getBigInt64(this.pos);
      this.pos += 8;
      return value;
    }
    readF32() {
      const value = this.view.getFloat32(this.pos);
      this.pos += 4;
      return value;
    }
    readF64() {
      const value = this.view.getFloat64(this.pos);
      this.pos += 8;
      return value;
    }
  };

  // node_modules/.pnpm/@msgpack+msgpack@3.1.3/node_modules/@msgpack/msgpack/dist.esm/decode.mjs
  function decode(buffer, options) {
    const decoder = new Decoder(options);
    return decoder.decode(buffer);
  }

  // src/viser4d/client/binary.ts
  var DTYPE_CONSTRUCTORS = {
    "<f2": { ctor: Uint16Array, bytes: 2 },
    "<f4": { ctor: Float32Array, bytes: 4 },
    "<f8": { ctor: Float64Array, bytes: 8 },
    "|u1": { ctor: Uint8Array, bytes: 1 },
    "<u2": { ctor: Uint16Array, bytes: 2 },
    "<u4": { ctor: Uint32Array, bytes: 4 },
    "|i1": { ctor: Int8Array, bytes: 1 },
    "<i2": { ctor: Int16Array, bytes: 2 },
    "<i4": { ctor: Int32Array, bytes: 4 }
  };
  function decodeBase64Bytes(base64Text) {
    const binary = atob(base64Text);
    const bytes = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i += 1) {
      bytes[i] = binary.charCodeAt(i);
    }
    return bytes;
  }
  function asBinaryView(value) {
    if (value instanceof ArrayBuffer) {
      return new Uint8Array(value);
    }
    if (!ArrayBuffer.isView(value)) {
      return null;
    }
    return value;
  }
  function computeBinaryOffsets(bufferLengths, baseOffset) {
    const offsets = [];
    let offset = baseOffset;
    for (const length of bufferLengths) {
      offset += (8 - offset % 8) % 8;
      offsets.push(offset);
      offset += length;
    }
    return offsets;
  }
  function replaceBinaryPlaceholders(obj, buffer, binaryOffsets, bufferLengths) {
    if (obj === null || obj === void 0) {
      return obj;
    }
    if (Array.isArray(obj)) {
      for (let i = 0; i < obj.length; i += 1) {
        obj[i] = replaceBinaryPlaceholders(
          obj[i],
          buffer,
          binaryOffsets,
          bufferLengths
        );
      }
      return obj;
    }
    if (typeof obj !== "object" || ArrayBuffer.isView(obj)) {
      return obj;
    }
    const record = obj;
    const idx = record.__binary_index;
    const dtype = record.dtype;
    if (typeof idx === "number" && typeof dtype === "string") {
      const offset = binaryOffsets[idx];
      const byteLength = bufferLengths[idx];
      const dtypeInfo = DTYPE_CONSTRUCTORS[dtype];
      if (dtypeInfo) {
        return new dtypeInfo.ctor(buffer, offset, byteLength / dtypeInfo.bytes);
      }
      return new Uint8Array(buffer, offset, byteLength);
    }
    for (const [key, inner] of Object.entries(record)) {
      record[key] = replaceBinaryPlaceholders(
        inner,
        buffer,
        binaryOffsets,
        bufferLengths
      );
    }
    return record;
  }
  function decodeHybridPayloadBase64(base64Text) {
    const bytes = decodeBase64Bytes(base64Text);
    const buffer = bytes.buffer;
    const baseOffset = bytes.byteOffset;
    const msgpackLength = Number(
      new DataView(buffer, baseOffset, 8).getBigUint64(0, true)
    );
    const msgpackData = new Uint8Array(buffer, baseOffset + 8, msgpackLength);
    const payload = decode(msgpackData);
    const bufferLengths = payload.binaryBufferLengths;
    if (bufferLengths && bufferLengths.length > 0) {
      const binaryOffsets = computeBinaryOffsets(
        bufferLengths,
        baseOffset + 8 + msgpackLength
      );
      replaceBinaryPlaceholders(payload, buffer, binaryOffsets, bufferLengths);
      delete payload.binaryBufferLengths;
    }
    return payload;
  }
  function normalizeTransportValue(value) {
    if (Array.isArray(value)) {
      return value.map((item) => normalizeTransportValue(item));
    }
    if (!value || typeof value !== "object") {
      return value;
    }
    const binaryView = asBinaryView(value);
    if (binaryView) {
      return binaryView;
    }
    const out = {};
    for (const [key, inner] of Object.entries(value)) {
      out[key] = inner === void 0 ? void 0 : normalizeTransportValue(inner);
    }
    return out;
  }
  function normalizeTransportMessage(message) {
    return normalizeTransportValue(message);
  }
  function decodeAudioArray(payload) {
    const buffer = decodeBase64Bytes(payload.data).buffer;
    switch (payload.dtype) {
      case "int16":
        return new Int16Array(buffer);
      case "int32":
        return new Int32Array(buffer);
      case "float64":
        return new Float64Array(buffer);
      case "float32":
        return new Float32Array(buffer);
      case "uint8":
        return new Uint8Array(buffer);
      default:
        return new Int16Array(buffer);
    }
  }
  function samplesToFloat32(samples) {
    if (samples instanceof Float32Array) {
      return samples;
    }
    if (samples instanceof Float64Array) {
      return Float32Array.from(samples);
    }
    if (samples instanceof Int16Array) {
      const out = new Float32Array(samples.length);
      for (let i = 0; i < samples.length; i += 1) {
        out[i] = (samples[i] ?? 0) / 32768;
      }
      return out;
    }
    if (samples instanceof Int32Array) {
      const out = new Float32Array(samples.length);
      for (let i = 0; i < samples.length; i += 1) {
        out[i] = (samples[i] ?? 0) / 2147483648;
      }
      return out;
    }
    if (samples instanceof Uint8Array) {
      const out = new Float32Array(samples.length);
      for (let i = 0; i < samples.length; i += 1) {
        out[i] = ((samples[i] ?? 128) - 128) / 128;
      }
      return out;
    }
    return Float32Array.from(samples);
  }
  function decodeAudioWaveform(payload) {
    const flat = samplesToFloat32(decodeAudioArray(payload));
    const channels = [];
    for (let channel = 0; channel < payload.numChannels; channel += 1) {
      const out = new Float32Array(payload.numFrames);
      for (let frame = 0; frame < payload.numFrames; frame += 1) {
        out[frame] = flat[frame * payload.numChannels + channel] ?? 0;
      }
      channels.push(out);
    }
    return channels;
  }

  // src/viser4d/client/bridge/protocol.ts
  function isObjectRecord(value) {
    return !!value && typeof value === "object";
  }
  function isViewerLike(value) {
    return isObjectRecord(value) && isObjectRecord(value.mutable) && "useGuiConfig" in value && "guiActions" in value && "useSceneTree" in value;
  }
  function getReactRoot() {
    const root = document.getElementById("root");
    if (!root) {
      throw new Error("[viser4d] Could not find #root while locating the viewer.");
    }
    const rootRecord = root;
    if (!isObjectRecord(rootRecord)) {
      throw new Error("[viser4d] React root is not an object while locating the viewer.");
    }
    const containerKey = Object.keys(rootRecord).find(
      (key) => key.startsWith("__reactContainer$")
    );
    const reactRoot = containerKey ? rootRecord[containerKey] : null;
    if (!isObjectRecord(reactRoot)) {
      throw new Error("[viser4d] Could not find the React container while locating the viewer.");
    }
    return reactRoot;
  }
  function findFiber(predicate) {
    const seen = /* @__PURE__ */ new Set();
    const stack = [getReactRoot()];
    while (stack.length) {
      const fiber = stack.pop();
      if (!fiber || seen.has(fiber)) {
        continue;
      }
      seen.add(fiber);
      if (predicate(fiber)) {
        return fiber;
      }
      if (fiber.child) {
        stack.push(fiber.child);
      }
      if (fiber.sibling) {
        stack.push(fiber.sibling);
      }
    }
    return null;
  }
  function getWindow() {
    return window;
  }
  function findViewer() {
    const fiber = findFiber((candidate) => isViewerLike(candidate.memoizedProps?.value));
    if (fiber) {
      return fiber.memoizedProps.value;
    }
    throw new Error("[viser4d] Could not locate the viewer in the React fiber tree.");
  }
  function findPlaybackTimeSlider() {
    return document.querySelector("[role='slider'][aria-valuenow]");
  }

  // src/viser4d/client/audio/runtime.ts
  function makeTrackState(step, sampleRate = 44100) {
    return {
      channels: 1,
      sampleRate,
      waveform: [new Float32Array(0)],
      volume: 1,
      startStep: step,
      removed: false
    };
  }
  function getMessageSampleRate(message) {
    return message.type === "AddAudioMessage" ? message.sampleRate : void 0;
  }
  function mergeTrackState(base, override) {
    if (!base && !override) {
      return null;
    }
    if (!base) {
      if (!override?.waveform || override.sampleRate == null) {
        return null;
      }
      return {
        channels: override.channels ?? override.waveform.length,
        sampleRate: override.sampleRate,
        waveform: override.waveform,
        volume: override.volume ?? 1,
        startStep: override.startStep ?? 0,
        removed: override.removed ?? false
      };
    }
    if (!override) {
      return base;
    }
    return {
      channels: override.channels ?? base.channels,
      sampleRate: override.sampleRate ?? base.sampleRate,
      waveform: override.waveform ?? base.waveform,
      volume: override.volume ?? base.volume,
      startStep: override.startStep ?? base.startStep,
      removed: override.removed ?? base.removed
    };
  }
  function appendWaveforms(head, tail) {
    return head.map((samples, channel) => {
      const merged = new Float32Array(samples.length + (tail[channel]?.length ?? 0));
      merged.set(samples, 0);
      merged.set(tail[channel] ?? new Float32Array(0), samples.length);
      return merged;
    });
  }
  function trackFrameCount(track) {
    return track.waveform[0]?.length ?? 0;
  }
  var AudioRuntime = class {
    constructor(getTransportStep, debugPush) {
      this.getTransportStep = getTransportStep;
      this.debugPush = debugPush;
      this.ctx = null;
      this.timelineTracks = /* @__PURE__ */ new Map();
      this.liveOverrides = /* @__PURE__ */ new Map();
      this.runtimeTracks = /* @__PURE__ */ new Map();
      this.playing = false;
      this.currentStep = 0;
      this.fps = 30;
      this.stepRate = 30;
      this.nextSourceToken = 1;
    }
    ensureContext() {
      if (!this.ctx) {
        const AudioContextClass = getWindow().AudioContext || getWindow().webkitAudioContext;
        this.ctx = AudioContextClass ? new AudioContextClass() : null;
      }
      return this.ctx;
    }
    getPlaybackStep() {
      return this.playing ? this.getTransportStep() : this.currentStep;
    }
    getTrackNames() {
      return /* @__PURE__ */ new Set([
        ...this.timelineTracks.keys(),
        ...this.liveOverrides.keys(),
        ...this.runtimeTracks.keys()
      ]);
    }
    getEffectiveTrack(name) {
      const timelineTrack = this.timelineTracks.get(name);
      const liveOverride = this.liveOverrides.get(name);
      return mergeTrackState(timelineTrack, liveOverride);
    }
    getRuntimeTrack(name) {
      const runtimeTrack = this.runtimeTracks.get(name);
      if (runtimeTrack) {
        return runtimeTrack;
      }
      const created = {
        source: null,
        gain: null,
        buffer: null,
        bufferWaveform: null,
        bufferSampleRate: null,
        token: 0
      };
      this.runtimeTracks.set(name, created);
      return created;
    }
    setStepRate(stepRate) {
      this.stepRate = Math.max(1e-6, stepRate || this.stepRate || 30);
    }
    buildBuffer(track, runtimeTrack) {
      const ctx = this.ensureContext();
      if (!ctx) {
        return null;
      }
      if (runtimeTrack.buffer && runtimeTrack.bufferWaveform === track.waveform && runtimeTrack.bufferSampleRate === track.sampleRate) {
        return runtimeTrack.buffer;
      }
      const buffer = ctx.createBuffer(track.channels, trackFrameCount(track), track.sampleRate);
      for (let channel = 0; channel < track.channels; channel += 1) {
        buffer.copyToChannel(
          new Float32Array(track.waveform[channel] ?? new Float32Array(0)),
          channel
        );
      }
      runtimeTrack.buffer = buffer;
      runtimeTrack.bufferWaveform = track.waveform;
      runtimeTrack.bufferSampleRate = track.sampleRate;
      return buffer;
    }
    applyOp(target, step, message, partial) {
      const next = target ?? (partial ? {} : makeTrackState(step, getMessageSampleRate(message)));
      let effect = "none";
      switch (message.type) {
        case "AddAudioMessage":
          next.sampleRate = message.sampleRate;
          next.channels = message.waveform.numChannels;
          next.waveform = decodeAudioWaveform(message.waveform);
          next.volume = message.volume;
          next.startStep = step;
          next.removed = false;
          effect = "reschedule";
          break;
        case "SetAudioVolumeMessage":
          next.volume = message.volume;
          effect = "volume";
          break;
        case "SetAudioWaveformMessage":
          next.channels = message.waveform.numChannels;
          next.waveform = decodeAudioWaveform(message.waveform);
          next.removed = false;
          effect = "reschedule";
          break;
        case "AppendAudioMessage": {
          const tail = decodeAudioWaveform(message.waveform);
          next.channels = message.waveform.numChannels;
          next.waveform = next.waveform ? appendWaveforms(next.waveform, tail) : tail;
          effect = "reschedule";
          break;
        }
        case "RemoveAudioMessage":
          next.removed = true;
          effect = "reschedule";
          break;
      }
      return { track: next, effect };
    }
    applyOps(targetMap, step, messages, eventName, partial) {
      for (const message of messages) {
        const current = targetMap.get(message.name);
        const hasWaveform = current && "waveform" in current && current.waveform;
        const target = partial || hasWaveform ? current || null : makeTrackState(step, getMessageSampleRate(message));
        const result = this.applyOp(target, step, message, partial);
        targetMap.set(message.name, result.track);
        this.debugPush(eventName, {
          name: message.name,
          step,
          type: message.type,
          effect: result.effect
        });
        if (result.effect === "volume") {
          this.updateTrackVolume(message.name);
        } else if (result.effect === "reschedule") {
          this.reconcileTrack(message.name);
        }
      }
    }
    applyTimelineMessages(step, messages) {
      this.applyOps(
        this.timelineTracks,
        step,
        messages,
        "audio.timeline_message",
        false
      );
    }
    applyLiveMessages(step, messages) {
      this.applyOps(
        this.liveOverrides,
        step,
        messages,
        "audio.live_message",
        true
      );
    }
    updateTrackVolume(name) {
      const runtimeTrack = this.runtimeTracks.get(name);
      const effective = this.getEffectiveTrack(name);
      if (runtimeTrack?.gain && effective) {
        runtimeTrack.gain.gain.value = effective.volume;
      }
    }
    stopRuntimeTrack(runtimeTrack) {
      runtimeTrack.token += 1;
      if (runtimeTrack.source) {
        try {
          runtimeTrack.source.stop();
        } catch (error) {
          this.debugPush("audio.stop_error", {
            error: error instanceof Error ? error.message : String(error)
          });
        }
        runtimeTrack.source.disconnect();
        runtimeTrack.source = null;
      }
      if (runtimeTrack.gain) {
        runtimeTrack.gain.disconnect();
        runtimeTrack.gain = null;
      }
    }
    stopAllNodes() {
      for (const runtimeTrack of this.runtimeTracks.values()) {
        this.stopRuntimeTrack(runtimeTrack);
      }
    }
    getClipDurationSteps(track) {
      return trackFrameCount(track) / track.sampleRate * this.stepRate;
    }
    isTrackActiveAtStep(track, playbackStep) {
      return playbackStep >= track.startStep && playbackStep < track.startStep + this.getClipDurationSteps(track);
    }
    reconcileTrack(name) {
      const ctx = this.ensureContext();
      if (!ctx) {
        return;
      }
      const runtimeTrack = this.getRuntimeTrack(name);
      this.stopRuntimeTrack(runtimeTrack);
      if (!this.playing) {
        return;
      }
      if (typeof ctx.resume === "function" && ctx.state === "suspended") {
        ctx.resume().catch(() => {
        });
      }
      const track = this.getEffectiveTrack(name);
      if (!track || track.removed || !trackFrameCount(track)) {
        return;
      }
      const playbackStep = this.getPlaybackStep();
      const endStep = track.startStep + this.getClipDurationSteps(track);
      if (playbackStep >= endStep) {
        return;
      }
      const source = ctx.createBufferSource();
      const gain = ctx.createGain();
      source.buffer = this.buildBuffer(track, runtimeTrack);
      if (!source.buffer) {
        return;
      }
      gain.gain.value = track.volume;
      source.playbackRate.value = this.fps / this.stepRate;
      source.connect(gain);
      gain.connect(ctx.destination);
      const token = ++this.nextSourceToken;
      runtimeTrack.token = token;
      source.onended = () => {
        if (runtimeTrack.token !== token) {
          return;
        }
        runtimeTrack.source = null;
        if (runtimeTrack.gain === gain) {
          runtimeTrack.gain.disconnect();
          runtimeTrack.gain = null;
        }
        const effective = this.getEffectiveTrack(name);
        if (this.playing && effective && !effective.removed && trackFrameCount(effective) && this.isTrackActiveAtStep(effective, this.getPlaybackStep())) {
          this.reconcileTrack(name);
        }
      };
      source.start(
        ctx.currentTime + Math.max(0, (track.startStep - playbackStep) / this.fps),
        Math.max(0, (playbackStep - track.startStep) / this.stepRate)
      );
      runtimeTrack.source = source;
      runtimeTrack.gain = gain;
    }
    rescheduleAll() {
      for (const name of this.getTrackNames()) {
        this.reconcileTrack(name);
      }
    }
    play(step, fps) {
      this.currentStep = step;
      this.fps = fps;
      this.playing = true;
      this.rescheduleAll();
    }
    pause(step, fps) {
      this.currentStep = step;
      this.fps = fps;
      this.playing = false;
      this.stopAllNodes();
    }
    seek(step, fps, playing) {
      this.currentStep = step;
      this.fps = fps;
      this.playing = playing;
      if (playing) {
        this.rescheduleAll();
        return;
      }
      this.stopAllNodes();
    }
    setFps(step, fps, playing) {
      this.currentStep = step;
      this.fps = fps;
      if (playing) {
        this.playing = true;
        this.rescheduleAll();
        return;
      }
      this.playing = false;
      this.stopAllNodes();
    }
    resetTimeline() {
      this.stopAllNodes();
      this.timelineTracks.clear();
      this.currentStep = 0;
    }
  };

  // src/viser4d/client/audio/messages.ts
  function isAudioMessage(message) {
    return message.type === "AddAudioMessage" || message.type === "SetAudioVolumeMessage" || message.type === "SetAudioWaveformMessage" || message.type === "AppendAudioMessage" || message.type === "RemoveAudioMessage";
  }

  // src/viser4d/client/bridge/blockCache.ts
  var BlockCache = class {
    constructor(sendGuiUpdate) {
      this.sendGuiUpdate = sendGuiUpdate;
      this.blockSize = 64;
      this.blockRequestSyncUuid = null;
      this.pendingStep = null;
      this.blocks = /* @__PURE__ */ new Map();
      this.requestedBlocks = /* @__PURE__ */ new Set();
    }
    getBlock(step) {
      return this.blocks.get(Math.floor(step / this.blockSize)) ?? null;
    }
    blockIndexOf(step) {
      return Math.floor(step / this.blockSize);
    }
    blockStartStep(blockIndex) {
      return blockIndex * this.blockSize;
    }
    loadBlock(blockIndex, block) {
      this.requestedBlocks.delete(blockIndex);
      this.blocks.set(blockIndex, block);
    }
    evictBlock(blockIndex, appliedBlock) {
      if (blockIndex === appliedBlock) {
        return;
      }
      this.blocks.delete(blockIndex);
      this.requestedBlocks.delete(blockIndex);
    }
    /**
     * Returns true if the step's block is loaded. If not, records it as pending
     * and sends a request to the server.
     */
    ensureStepLoaded(step) {
      if (this.getBlock(step)) {
        return true;
      }
      this.pendingStep = step;
      const blockIndex = this.blockIndexOf(step);
      if (!this.requestedBlocks.has(blockIndex) && this.blockRequestSyncUuid) {
        this.requestedBlocks.add(blockIndex);
        this.sendGuiUpdate(this.blockRequestSyncUuid, step);
      }
      return false;
    }
  };

  // src/viser4d/client/bridge/sceneApplicator.ts
  var SceneApplicator = class {
    constructor(pushMessages, audio, blocks, renderedTimelineNodes) {
      this.pushMessages = pushMessages;
      this.audio = audio;
      this.blocks = blocks;
      this.renderedTimelineNodes = renderedTimelineNodes;
      this.appliedStep = -1;
      this.appliedBlock = -1;
    }
    applyStepMessages(step, messages) {
      const sceneMessages = [];
      const audioMessages = [];
      for (const message of messages) {
        if (isAudioMessage(message)) {
          audioMessages.push(message);
        } else {
          this.trackTimelineNode(message);
          sceneMessages.push(message);
        }
      }
      if (sceneMessages.length) {
        this.pushMessages(sceneMessages);
      }
      if (audioMessages.length) {
        this.audio.applyTimelineMessages(step, audioMessages);
      }
    }
    resetState() {
      this.removeRenderedTimelineNodes();
      this.audio.resetTimeline();
      this.appliedStep = -1;
      this.appliedBlock = -1;
    }
    rebuildThrough(step) {
      if (!this.blocks.ensureStepLoaded(step)) {
        return;
      }
      this.resetState();
      this.applyThrough(step);
    }
    applyThrough(step) {
      const blockIndex = this.blocks.blockIndexOf(step);
      if (this.appliedStep >= 0 && (blockIndex !== this.appliedBlock || step < this.appliedStep)) {
        this.rebuildThrough(step);
        return;
      }
      this.advanceThrough(step);
    }
    advanceThrough(step) {
      if (!this.blocks.ensureStepLoaded(step)) {
        return;
      }
      if (this.appliedStep < 0) {
        const block = this.blocks.getBlock(step);
        if (!block) {
          return;
        }
        const blockIndex = this.blocks.blockIndexOf(step);
        this.applyBlockCheckpoint(blockIndex, block);
        this.appliedBlock = blockIndex;
        this.appliedStep = this.blocks.blockStartStep(blockIndex) - 1;
      }
      let nextStep = this.appliedStep + 1;
      while (nextStep <= step) {
        if (!this.blocks.ensureStepLoaded(nextStep)) {
          return;
        }
        const block = this.blocks.getBlock(nextStep);
        if (!block) {
          return;
        }
        const blockIndex = this.blocks.blockIndexOf(nextStep);
        const blockStart = this.blocks.blockStartStep(blockIndex);
        const blockEnd = Math.min(
          step,
          blockStart + block.stepMessages.length - 1
        );
        for (let index = nextStep; index <= blockEnd; index += 1) {
          const messages = block.stepMessages[index - blockStart] ?? [];
          if (messages.length) {
            this.applyStepMessages(index, messages);
          }
        }
        this.appliedBlock = blockIndex;
        this.appliedStep = blockEnd;
        nextStep = blockEnd + 1;
      }
    }
    applyBlockCheckpoint(blockIndex, block) {
      if (block.checkpointMessages.length) {
        this.applyStepMessages(
          this.blocks.blockStartStep(blockIndex),
          block.checkpointMessages
        );
      }
    }
    removeRenderedTimelineNodes() {
      if (!this.renderedTimelineNodes.size) {
        return;
      }
      this.pushMessages(
        Array.from(this.renderedTimelineNodes).map((name) => ({
          type: "RemoveSceneNodeMessage",
          name
        }))
      );
      this.renderedTimelineNodes.clear();
    }
    trackTimelineNode(message) {
      const name = typeof message.name === "string" ? message.name : null;
      if (!name) {
        return;
      }
      if (message.type === "RemoveSceneNodeMessage") {
        const prefix = `${name}/`;
        for (const nodeName of Array.from(this.renderedTimelineNodes)) {
          if (nodeName === name || nodeName.startsWith(prefix)) {
            this.renderedTimelineNodes.delete(nodeName);
          }
        }
        return;
      }
      this.renderedTimelineNodes.add(name);
    }
  };

  // src/viser4d/client/bridge/playbackEngine.ts
  var PlaybackEngine = class {
    constructor(config, scene, blocks, audio, callbacks) {
      this.config = config;
      this.scene = scene;
      this.blocks = blocks;
      this.audio = audio;
      this.callbacks = callbacks;
      this.playing = false;
      this.currentStep = 0;
      this.playStartStep = 0;
      this.playStartPerfTime = 0;
      this.rafId = null;
    }
    updateConfig(config) {
      this.config = config;
    }
    getTransportStep(timestamp = performance.now()) {
      if (!this.playing) {
        return this.currentStep;
      }
      return this.playStartStep + (timestamp - this.playStartPerfTime) / 1e3 * this.getPlaybackFps();
    }
    play(payload) {
      const step = this.getTransportStep();
      this.config.speed = payload.speed;
      this.config.loop = payload.loop;
      this.playing = true;
      this.anchorTransport(step);
      this.audio.play(step, this.getPlaybackFps());
      if (this.rafId !== null) {
        getWindow().cancelAnimationFrame(this.rafId);
      }
      this.callbacks.sendSpeedToServer(payload.speed);
      this.callbacks.sendPlaybackStateToServer(true);
      this.callbacks.syncPlaybackButtons();
      this.rafId = getWindow().requestAnimationFrame((ts) => this.tick(ts));
    }
    pause() {
      const step = this.getTransportStep();
      this.currentStep = step;
      this.playing = false;
      if (this.rafId !== null) {
        getWindow().cancelAnimationFrame(this.rafId);
        this.rafId = null;
      }
      this.audio.pause(step, this.getPlaybackFps());
      this.callbacks.sendPlaybackStateToServer(false);
      this.callbacks.syncTimestepToServer(Math.floor(this.currentStep), true);
      this.callbacks.syncPlaybackButtons();
    }
    seek(payload) {
      const step = Math.max(
        0,
        Math.min(this.config.numSteps - 1, payload.step)
      );
      this.currentStep = step;
      if (this.playing) {
        this.anchorTransport(step);
      }
      if (!this.blocks.ensureStepLoaded(step)) {
        return;
      }
      this.scene.applyThrough(step);
      this.audio.seek(step, this.getPlaybackFps(), this.playing);
      this.callbacks.syncTimestepToServer(step, true);
    }
    refresh() {
      this.scene.rebuildThrough(Math.floor(this.currentStep));
    }
    setSpeed(payload) {
      const step = this.getTransportStep();
      this.config.speed = payload.speed;
      this.config.loop = payload.loop;
      this.anchorTransport(step);
      this.audio.setFps(step, this.getPlaybackFps(), this.playing);
      this.callbacks.sendSpeedToServer(payload.speed);
    }
    syncAudioTransport() {
      this.audio.seek(this.currentStep, this.getPlaybackFps(), this.playing);
    }
    getPlaybackFps() {
      return this.config.timelineFps * this.config.speed;
    }
    anchorTransport(step, timestamp = performance.now()) {
      this.currentStep = step;
      this.playStartStep = step;
      this.playStartPerfTime = timestamp;
    }
    tick(timestamp) {
      if (!this.playing) {
        return;
      }
      const previousStep = this.currentStep;
      const next = this.getTransportStep(timestamp);
      if (next >= this.config.numSteps) {
        if (!this.config.loop) {
          this.currentStep = this.config.numSteps - 1;
          this.playing = false;
          this.audio.pause(this.currentStep, this.getPlaybackFps());
          this.callbacks.syncAdvancedTimesteps(
            previousStep,
            this.currentStep,
            true
          );
          this.callbacks.sendPlaybackStateToServer(false);
          this.callbacks.syncPlaybackButtons();
          return;
        }
        this.anchorTransport(0, timestamp);
        this.scene.rebuildThrough(0);
        this.audio.play(0, this.getPlaybackFps());
        this.callbacks.syncAdvancedTimesteps(previousStep, 0, true);
      } else {
        this.currentStep = next;
        this.scene.advanceThrough(Math.floor(this.currentStep));
        this.callbacks.syncAdvancedTimesteps(previousStep, this.currentStep);
      }
      this.rafId = getWindow().requestAnimationFrame((ts) => this.tick(ts));
    }
  };

  // src/viser4d/client/bridge/runtime.ts
  var debugState = {
    enabled: false,
    logs: [],
    maxLogs: 400,
    push(event, payload) {
      this.logs.push({
        time: Number(performance.now().toFixed(1)),
        event,
        payload
      });
      if (this.logs.length > this.maxLogs) {
        this.logs.shift();
      }
      if (this.enabled) {
        console.debug("[viser4d]", event, payload);
      }
    },
    clear() {
      this.logs.length = 0;
    },
    setEnabled(enabled) {
      this.enabled = !!enabled;
    }
  };
  var TimelineRuntime = class {
    constructor() {
      this.debug = debugState;
      this.viewer = null;
      this.playbackTimeSlider = null;
      this.config = {
        numSteps: 1,
        blockSize: 64,
        timelineFps: 30,
        speed: 1,
        loop: false,
        blockRequestSyncUuid: null,
        timelineSliderUuid: null,
        speedSliderUuid: null,
        stepButtonsUuid: null,
        playButtonUuid: null,
        pauseButtonUuid: null,
        speedSyncUuid: null,
        playbackStateSyncUuid: null,
        timestepSyncUuid: null
      };
      this.lastLocalSliderStep = -1;
      this.lastSyncedStep = -1;
      this.audio = new AudioRuntime(
        () => this.engine.getTransportStep(),
        (event, payload) => debugState.push(event, payload)
      );
      this.blocks = new BlockCache(
        (uuid, value) => this.sendGuiUpdate(uuid, value)
      );
      this.scene = new SceneApplicator(
        (messages) => this.pushMessages(messages),
        this.audio,
        this.blocks,
        /* @__PURE__ */ new Set()
      );
      this.engine = new PlaybackEngine(
        this.config,
        this.scene,
        this.blocks,
        this.audio,
        {
          syncAdvancedTimesteps: (prev, next, force) => this.syncAdvancedTimesteps(prev, next, force),
          syncTimestepToServer: (step, force) => this.syncTimestepToServer(step, force),
          syncPlaybackButtons: () => this.syncPlaybackButtons(),
          sendPlaybackStateToServer: (p) => this.sendPlaybackStateToServer(p),
          sendSpeedToServer: (s) => this.sendSpeedToServer(s)
        }
      );
      // File/embed playback audio
      this.playbackAudio = new AudioRuntime(
        () => this.playbackTime,
        (event, payload) => debugState.push(event, payload)
      );
      this.playbackTime = 0;
      this.playbackPlaying = false;
      this.playbackObserved = false;
      this.playbackLastAppliedMessageTime = -1;
      // Browser integration state
      this.queueIngressConfigured = false;
      this.guiMessageInterceptorInstalled = false;
      this.queuePush = null;
      this.playbackMonitor = null;
      this.playbackAudio.setStepRate(1);
      this.installWhenReady();
    }
    get appliedStep() {
      return this.scene.appliedStep;
    }
    // --- Public API (called from Python runtime messages) ---
    invokeRuntimeCall(method, encodedPayload) {
      const target = this[method];
      if (typeof target !== "function") {
        throw new Error(`[viser4d] Unknown runtime method: ${method}`);
      }
      const payload = decodeHybridPayloadBase64(
        encodedPayload
      );
      target.call(this, payload);
    }
    configure(config) {
      this.config = { ...this.config, ...config };
      this.blocks.blockSize = this.config.blockSize;
      this.blocks.blockRequestSyncUuid = this.config.blockRequestSyncUuid;
      this.engine.updateConfig(this.config);
      this.audio.setStepRate(this.config.timelineFps);
      debugState.push("runtime.configure", this.config);
      this.engine.syncAudioTransport();
      this.syncPlaybackButtons();
    }
    loadBlock(payload) {
      this.blocks.loadBlock(payload.block, {
        checkpointMessages: payload.checkpointMessages,
        stepMessages: payload.stepMessages
      });
      const activeBlock = this.blocks.blockIndexOf(
        Math.floor(this.engine.currentStep)
      );
      if (payload.block === activeBlock && this.scene.appliedBlock === activeBlock) {
        this.scene.rebuildThrough(Math.floor(this.engine.currentStep));
        return;
      }
      if (this.blocks.pendingStep !== null && this.blocks.getBlock(this.blocks.pendingStep)) {
        const step = this.blocks.pendingStep;
        this.blocks.pendingStep = null;
        this.engine.seek({ step });
      }
    }
    evictBlock(payload) {
      this.blocks.evictBlock(payload.block, this.scene.appliedBlock);
    }
    seek(payload) {
      this.engine.seek(payload);
    }
    refresh() {
      this.engine.refresh();
    }
    play(payload) {
      this.engine.play(payload);
    }
    pause() {
      this.engine.pause();
    }
    setSpeed(payload) {
      this.engine.setSpeed(payload);
    }
    applyMessageUpdate(message) {
      const name = typeof message.name === "string" ? message.name : null;
      debugState.push("runtime.apply_message_update", {
        type: message.type,
        name,
        step: Math.floor(this.engine.currentStep)
      });
      if (isAudioMessage(message)) {
        this.audio.applyLiveMessages(Math.floor(this.engine.currentStep), [
          message
        ]);
        return;
      }
      this.pushMessages([message]);
    }
    // --- Browser integration ---
    getViewer() {
      if (!this.viewer) {
        this.viewer = findViewer();
      }
      return this.viewer;
    }
    getPlaybackTimeSlider() {
      if (!this.playbackTimeSlider || !this.playbackTimeSlider.isConnected) {
        this.playbackTimeSlider = findPlaybackTimeSlider();
      }
      return this.playbackTimeSlider;
    }
    installWhenReady() {
      try {
        this.configureQueueIngress();
        this.installGuiMessageInterceptor();
        if (this.getViewer().messageSource !== "websocket") {
          this.installPlaybackMonitor();
        }
      } catch {
        getWindow().requestAnimationFrame(() => this.installWhenReady());
      }
    }
    configureQueueIngress() {
      if (this.queueIngressConfigured) {
        return;
      }
      const queue = this.getViewer().mutable.current.messageQueue;
      const originalPush = queue.push.bind(queue);
      this.queuePush = originalPush;
      queue.push = (...messages) => {
        const forwarded = [];
        for (const message of messages) {
          const normalized = normalizeTransportMessage(message);
          if (this.handleQueuedMessage(normalized)) {
            continue;
          }
          forwarded.push(normalized);
        }
        return originalPush(...forwarded);
      };
      this.queueIngressConfigured = true;
    }
    installPlaybackMonitor() {
      if (this.playbackMonitor) {
        return;
      }
      const slider = this.getPlaybackTimeSlider();
      if (!slider) {
        throw new Error("[viser4d] Could not find the playback slider.");
      }
      this.playbackMonitor = new MutationObserver(() => {
        this.syncPlaybackState();
      });
      this.playbackMonitor.observe(slider, {
        attributes: true,
        attributeFilter: ["aria-valuenow"]
      });
      this.syncPlaybackState();
    }
    installGuiMessageInterceptor() {
      if (this.guiMessageInterceptorInstalled) {
        return;
      }
      const mutable = this.getViewer().mutable.current;
      let rawSendMessage = mutable.sendMessage;
      const wrappedSendMessage = (message) => {
        if (message.type === "GuiUpdateMessage" && this.handleLocalPlaybackGuiMessage(message)) {
          return;
        }
        rawSendMessage(message);
      };
      Object.defineProperty(mutable, "sendMessage", {
        configurable: true,
        enumerable: true,
        get: () => wrappedSendMessage,
        set: (value) => {
          rawSendMessage = value;
        }
      });
      this.guiMessageInterceptorInstalled = true;
    }
    handleLocalPlaybackGuiMessage(message) {
      const value = message.updates.value;
      if (message.uuid === this.config.timelineSliderUuid) {
        const step = Number(value);
        if (!Number.isFinite(step)) {
          return true;
        }
        this.engine.seek({ step });
        return true;
      }
      if (message.uuid === this.config.speedSliderUuid) {
        const speed = Number(value);
        if (!Number.isFinite(speed)) {
          return true;
        }
        this.engine.setSpeed({ speed, loop: this.config.loop });
        return true;
      }
      if (message.uuid === this.config.stepButtonsUuid) {
        if (value === "Prev") {
          this.engine.seek({ step: Math.floor(this.engine.currentStep) - 1 });
        } else if (value === "Next") {
          this.engine.seek({ step: Math.floor(this.engine.currentStep) + 1 });
        }
        return true;
      }
      if (message.uuid === this.config.playButtonUuid) {
        this.engine.play({ speed: this.config.speed, loop: this.config.loop });
        return true;
      }
      if (message.uuid === this.config.pauseButtonUuid) {
        this.engine.pause();
        return true;
      }
      return false;
    }
    handleQueuedMessage(message) {
      if (!isAudioMessage(message)) {
        return false;
      }
      if (this.getViewer().messageSource === "websocket") {
        return false;
      }
      const playbackTime = getPlaybackMessageTime(message);
      if (playbackTime !== null && playbackTime < this.playbackLastAppliedMessageTime) {
        this.resetPlaybackAudio();
      }
      if (playbackTime !== null) {
        this.playbackLastAppliedMessageTime = playbackTime;
        this.playbackAudio.applyLiveMessages(playbackTime, [message]);
      } else {
        this.playbackAudio.applyLiveMessages(this.playbackTime, [message]);
      }
      return true;
    }
    // --- File/embed playback sync ---
    syncPlaybackState() {
      const nextTime = this.readPlaybackTime();
      if (nextTime === null) {
        return;
      }
      const delta = nextTime - this.playbackTime;
      const jumped = Math.abs(delta) > 0.2;
      const playing = delta > 1e-4;
      if (!this.playbackObserved) {
        this.playbackObserved = true;
        this.playbackTime = nextTime;
        this.playbackAudio.seek(nextTime, 1, false);
        return;
      }
      if (delta < -1e-4) {
        this.resetPlaybackAudio();
      }
      if (jumped) {
        this.playbackAudio.seek(nextTime, 1, playing);
      } else if (playing !== this.playbackPlaying) {
        if (playing) {
          this.playbackAudio.play(nextTime, 1);
        } else {
          this.playbackAudio.pause(nextTime, 1);
        }
      } else if (!playing && Math.abs(delta) > 1e-4) {
        this.playbackAudio.seek(nextTime, 1, false);
      }
      this.playbackTime = nextTime;
      this.playbackPlaying = playing;
    }
    resetPlaybackAudio() {
      this.playbackAudio.resetTimeline();
      this.playbackLastAppliedMessageTime = -1;
    }
    readPlaybackTime() {
      const slider = this.getPlaybackTimeSlider();
      if (!slider) {
        return null;
      }
      const value = slider.getAttribute("aria-valuenow");
      if (value === null) {
        return null;
      }
      const parsed = Number(value);
      return Number.isFinite(parsed) ? parsed : null;
    }
    // --- Server sync helpers ---
    pushMessages(messages) {
      if (this.queuePush) {
        this.queuePush(...messages);
        return;
      }
      this.getViewer().mutable.current.messageQueue.push(...messages);
    }
    sendGuiUpdate(uuid, value) {
      this.getViewer().mutable.current.sendMessage({
        type: "GuiUpdateMessage",
        uuid,
        updates: { value }
      });
    }
    syncPlaybackButtons() {
      const viewer = this.getViewer();
      const sync = (uuid, visible) => {
        if (!uuid || viewer.useGuiConfig.get(uuid) === void 0) {
          return;
        }
        viewer.guiActions.updateGuiProps(uuid, { visible });
      };
      sync(this.config.playButtonUuid, !this.engine.playing);
      sync(this.config.pauseButtonUuid, this.engine.playing);
    }
    syncTimelineSlider(step, force = false) {
      const clampedStep = Math.max(0, Math.min(this.config.numSteps - 1, step));
      if (this.config.timelineSliderUuid && (force || clampedStep !== this.lastLocalSliderStep)) {
        this.lastLocalSliderStep = clampedStep;
        this.pushMessages([
          {
            type: "GuiUpdateMessage",
            uuid: this.config.timelineSliderUuid,
            updates: { value: clampedStep }
          }
        ]);
      }
    }
    sendTimestepToServer(step, force = false) {
      const clampedStep = Math.max(0, Math.min(this.config.numSteps - 1, step));
      if (!this.config.timestepSyncUuid) {
        return;
      }
      if (!force && clampedStep === this.lastSyncedStep) {
        return;
      }
      this.lastSyncedStep = clampedStep;
      this.sendGuiUpdate(this.config.timestepSyncUuid, clampedStep);
    }
    syncTimestepToServer(step, force = false) {
      this.syncTimelineSlider(step, force);
      this.sendTimestepToServer(step, force);
    }
    syncAdvancedTimesteps(previousStep, nextStep, forceFinal = false) {
      const previousDiscrete = Math.floor(previousStep);
      const nextDiscrete = Math.floor(nextStep);
      this.syncTimelineSlider(nextDiscrete, forceFinal);
      if (nextDiscrete === previousDiscrete) {
        if (forceFinal) {
          this.sendTimestepToServer(nextDiscrete, true);
        }
        return;
      }
      if (nextDiscrete > previousDiscrete) {
        for (let step = previousDiscrete + 1; step <= nextDiscrete; step += 1) {
          this.sendTimestepToServer(step);
        }
        return;
      }
      for (let step = previousDiscrete + 1; step < this.config.numSteps; step += 1) {
        this.sendTimestepToServer(step);
      }
      for (let step = 0; step <= nextDiscrete; step += 1) {
        this.sendTimestepToServer(step);
      }
    }
    sendSpeedToServer(speed) {
      if (this.config.speedSyncUuid) {
        this.sendGuiUpdate(this.config.speedSyncUuid, speed);
      }
    }
    sendPlaybackStateToServer(isPlaying) {
      if (this.config.playbackStateSyncUuid) {
        this.sendGuiUpdate(this.config.playbackStateSyncUuid, isPlaying);
      }
    }
  };
  function getPlaybackMessageTime(message) {
    const playbackTime = message.__viserPlaybackTime;
    return typeof playbackTime === "number" ? playbackTime : null;
  }

  // src/viser4d/client/index.ts
  var windowRef = window;
  if (!windowRef.__VISER4D__) {
    windowRef.__VISER4D__ = new TimelineRuntime();
  }
})();
