const normalizeLine = line => {
  if (line.startsWith('Error: ')) {
    return line.slice('Error: '.length);
  }
  if (line.startsWith('VError: ')) {
    return line.slice('VError: '.length);
  }
  return line;
};
const getCombinedMessage = (error, message) => {
  const stringifiedError = normalizeLine(`${error}`);
  if (message) {
    return `${message}: ${stringifiedError}`;
  }
  return stringifiedError;
};
const NewLine$2 = '\n';
const getNewLineIndex$1 = (string, startIndex = undefined) => {
  return string.indexOf(NewLine$2, startIndex);
};
const mergeStacks = (parent, child) => {
  if (!child) {
    return parent;
  }
  const parentNewLineIndex = getNewLineIndex$1(parent);
  const childNewLineIndex = getNewLineIndex$1(child);
  if (childNewLineIndex === -1) {
    return parent;
  }
  const parentFirstLine = parent.slice(0, parentNewLineIndex);
  const childRest = child.slice(childNewLineIndex);
  const childFirstLine = normalizeLine(child.slice(0, childNewLineIndex));
  if (parentFirstLine.includes(childFirstLine)) {
    return parentFirstLine + childRest;
  }
  return child;
};
class VError extends Error {
  constructor(error, message) {
    const combinedMessage = getCombinedMessage(error, message);
    super(combinedMessage);
    this.name = 'VError';
    if (error instanceof Error) {
      this.stack = mergeStacks(this.stack, error.stack);
    }
    if (error.codeFrame) {
      // @ts-ignore
      this.codeFrame = error.codeFrame;
    }
    if (error.code) {
      // @ts-ignore
      this.code = error.code;
    }
  }
}

const isMessagePort = value => {
  return value && value instanceof MessagePort;
};
const isMessagePortMain = value => {
  return value && value.constructor && value.constructor.name === 'MessagePortMain';
};
const isOffscreenCanvas = value => {
  return typeof OffscreenCanvas !== 'undefined' && value instanceof OffscreenCanvas;
};
const isInstanceOf = (value, constructorName) => {
  return value?.constructor?.name === constructorName;
};
const isSocket = value => {
  return isInstanceOf(value, 'Socket');
};
const transferrables = [isMessagePort, isMessagePortMain, isOffscreenCanvas, isSocket];
const isTransferrable = value => {
  for (const fn of transferrables) {
    if (fn(value)) {
      return true;
    }
  }
  return false;
};
const walkValue = (value, transferrables, isTransferrable) => {
  if (!value) {
    return;
  }
  if (isTransferrable(value)) {
    transferrables.push(value);
    return;
  }
  if (Array.isArray(value)) {
    for (const item of value) {
      walkValue(item, transferrables, isTransferrable);
    }
    return;
  }
  if (typeof value === 'object') {
    for (const property of Object.values(value)) {
      walkValue(property, transferrables, isTransferrable);
    }
    return;
  }
};
const getTransferrables = value => {
  const transferrables = [];
  walkValue(value, transferrables, isTransferrable);
  return transferrables;
};
const attachEvents = that => {
  const handleMessage = (...args) => {
    const data = that.getData(...args);
    that.dispatchEvent(new MessageEvent('message', {
      data
    }));
  };
  that.onMessage(handleMessage);
  const handleClose = event => {
    that.dispatchEvent(new Event('close'));
  };
  that.onClose(handleClose);
};
class Ipc extends EventTarget {
  constructor(rawIpc) {
    super();
    this._rawIpc = rawIpc;
    attachEvents(this);
  }
}
const E_INCOMPATIBLE_NATIVE_MODULE = 'E_INCOMPATIBLE_NATIVE_MODULE';
const E_MODULES_NOT_SUPPORTED_IN_ELECTRON = 'E_MODULES_NOT_SUPPORTED_IN_ELECTRON';
const ERR_MODULE_NOT_FOUND = 'ERR_MODULE_NOT_FOUND';
const NewLine$1 = '\n';
const joinLines$1 = lines => {
  return lines.join(NewLine$1);
};
const RE_AT = /^\s+at/;
const RE_AT_PROMISE_INDEX = /^\s*at async Promise.all \(index \d+\)$/;
const isNormalStackLine = line => {
  return RE_AT.test(line) && !RE_AT_PROMISE_INDEX.test(line);
};
const getDetails = lines => {
  const index = lines.findIndex(isNormalStackLine);
  if (index === -1) {
    return {
      actualMessage: joinLines$1(lines),
      rest: []
    };
  }
  let lastIndex = index - 1;
  while (++lastIndex < lines.length) {
    if (!isNormalStackLine(lines[lastIndex])) {
      break;
    }
  }
  return {
    actualMessage: lines[index - 1],
    rest: lines.slice(index, lastIndex)
  };
};
const splitLines$1 = lines => {
  return lines.split(NewLine$1);
};
const RE_MESSAGE_CODE_BLOCK_START = /^Error: The module '.*'$/;
const RE_MESSAGE_CODE_BLOCK_END = /^\s* at/;
const isMessageCodeBlockStartIndex = line => {
  return RE_MESSAGE_CODE_BLOCK_START.test(line);
};
const isMessageCodeBlockEndIndex = line => {
  return RE_MESSAGE_CODE_BLOCK_END.test(line);
};
const getMessageCodeBlock = stderr => {
  const lines = splitLines$1(stderr);
  const startIndex = lines.findIndex(isMessageCodeBlockStartIndex);
  const endIndex = startIndex + lines.slice(startIndex).findIndex(isMessageCodeBlockEndIndex, startIndex);
  const relevantLines = lines.slice(startIndex, endIndex);
  const relevantMessage = relevantLines.join(' ').slice('Error: '.length);
  return relevantMessage;
};
const isModuleNotFoundMessage = line => {
  return line.includes('[ERR_MODULE_NOT_FOUND]');
};
const getModuleNotFoundError = stderr => {
  const lines = splitLines$1(stderr);
  const messageIndex = lines.findIndex(isModuleNotFoundMessage);
  const message = lines[messageIndex];
  return {
    code: ERR_MODULE_NOT_FOUND,
    message
  };
};
const isModuleNotFoundError = stderr => {
  if (!stderr) {
    return false;
  }
  return stderr.includes('ERR_MODULE_NOT_FOUND');
};
const isModulesSyntaxError = stderr => {
  if (!stderr) {
    return false;
  }
  return stderr.includes('SyntaxError: Cannot use import statement outside a module');
};
const RE_NATIVE_MODULE_ERROR = /^innerError Error: Cannot find module '.*.node'/;
const RE_NATIVE_MODULE_ERROR_2 = /was compiled against a different Node.js version/;
const isUnhelpfulNativeModuleError = stderr => {
  return RE_NATIVE_MODULE_ERROR.test(stderr) && RE_NATIVE_MODULE_ERROR_2.test(stderr);
};
const getNativeModuleErrorMessage = stderr => {
  const message = getMessageCodeBlock(stderr);
  return {
    code: E_INCOMPATIBLE_NATIVE_MODULE,
    message: `Incompatible native node module: ${message}`
  };
};
const getModuleSyntaxError = () => {
  return {
    code: E_MODULES_NOT_SUPPORTED_IN_ELECTRON,
    message: `ES Modules are not supported in electron`
  };
};
const getHelpfulChildProcessError = (stdout, stderr) => {
  if (isUnhelpfulNativeModuleError(stderr)) {
    return getNativeModuleErrorMessage(stderr);
  }
  if (isModulesSyntaxError(stderr)) {
    return getModuleSyntaxError();
  }
  if (isModuleNotFoundError(stderr)) {
    return getModuleNotFoundError(stderr);
  }
  const lines = splitLines$1(stderr);
  const {
    actualMessage,
    rest
  } = getDetails(lines);
  return {
    code: '',
    message: actualMessage,
    stack: rest
  };
};
class IpcError extends VError {
  // @ts-ignore
  constructor(betterMessage, stdout = '', stderr = '') {
    if (stdout || stderr) {
      // @ts-ignore
      const {
        code,
        message,
        stack
      } = getHelpfulChildProcessError(stdout, stderr);
      const cause = new Error(message);
      // @ts-ignore
      cause.code = code;
      cause.stack = stack;
      super(cause, betterMessage);
    } else {
      super(betterMessage);
    }
    // @ts-ignore
    this.name = 'IpcError';
    // @ts-ignore
    this.stdout = stdout;
    // @ts-ignore
    this.stderr = stderr;
  }
}
const readyMessage = 'ready';
const getData$2 = event => {
  return event.data;
};
const listen$7 = () => {
  // @ts-ignore
  if (typeof WorkerGlobalScope === 'undefined') {
    throw new TypeError('module is not in web worker scope');
  }
  return globalThis;
};
const signal$8 = global => {
  global.postMessage(readyMessage);
};
class IpcChildWithModuleWorker extends Ipc {
  getData(event) {
    return getData$2(event);
  }
  send(message) {
    // @ts-ignore
    this._rawIpc.postMessage(message);
  }
  sendAndTransfer(message) {
    const transfer = getTransferrables(message);
    // @ts-ignore
    this._rawIpc.postMessage(message, transfer);
  }
  dispose() {
    // ignore
  }
  onClose(callback) {
    // ignore
  }
  onMessage(callback) {
    this._rawIpc.addEventListener('message', callback);
  }
}
const wrap$f = global => {
  return new IpcChildWithModuleWorker(global);
};
const waitForFirstMessage = async port => {
  const {
    promise,
    resolve
  } = Promise.withResolvers();
  port.addEventListener('message', resolve, {
    once: true
  });
  const event = await promise;
  // @ts-ignore
  return event.data;
};
const listen$6 = async () => {
  const parentIpcRaw = listen$7();
  signal$8(parentIpcRaw);
  const parentIpc = wrap$f(parentIpcRaw);
  const firstMessage = await waitForFirstMessage(parentIpc);
  if (firstMessage.method !== 'initialize') {
    throw new IpcError('unexpected first message');
  }
  const type = firstMessage.params[0];
  if (type === 'message-port') {
    parentIpc.send({
      id: firstMessage.id,
      jsonrpc: '2.0',
      result: null
    });
    parentIpc.dispose();
    const port = firstMessage.params[1];
    return port;
  }
  return globalThis;
};
class IpcChildWithModuleWorkerAndMessagePort extends Ipc {
  getData(event) {
    return getData$2(event);
  }
  send(message) {
    this._rawIpc.postMessage(message);
  }
  sendAndTransfer(message) {
    const transfer = getTransferrables(message);
    this._rawIpc.postMessage(message, transfer);
  }
  dispose() {
    if (this._rawIpc.close) {
      this._rawIpc.close();
    }
  }
  onClose(callback) {
    // ignore
  }
  onMessage(callback) {
    this._rawIpc.addEventListener('message', callback);
    this._rawIpc.start();
  }
}
const wrap$e = port => {
  return new IpcChildWithModuleWorkerAndMessagePort(port);
};
const IpcChildWithModuleWorkerAndMessagePort$1 = {
  __proto__: null,
  listen: listen$6,
  wrap: wrap$e
};

class CommandNotFoundError extends Error {
  constructor(command) {
    super(`Command not found ${command}`);
    this.name = 'CommandNotFoundError';
  }
}
const commands = Object.create(null);
const register = commandMap => {
  Object.assign(commands, commandMap);
};
const getCommand = key => {
  return commands[key];
};
const execute = (command, ...args) => {
  const fn = getCommand(command);
  if (!fn) {
    throw new CommandNotFoundError(command);
  }
  return fn(...args);
};

const Two$1 = '2.0';
const callbacks = Object.create(null);
const get$1 = id => {
  return callbacks[id];
};
const remove = id => {
  delete callbacks[id];
};
class JsonRpcError extends Error {
  constructor(message) {
    super(message);
    this.name = 'JsonRpcError';
  }
}
const NewLine = '\n';
const DomException = 'DOMException';
const ReferenceError$1 = 'ReferenceError';
const SyntaxError$1 = 'SyntaxError';
const TypeError$1 = 'TypeError';
const getErrorConstructor = (message, type) => {
  if (type) {
    switch (type) {
      case DomException:
        return DOMException;
      case ReferenceError$1:
        return ReferenceError;
      case SyntaxError$1:
        return SyntaxError;
      case TypeError$1:
        return TypeError;
      default:
        return Error;
    }
  }
  if (message.startsWith('TypeError: ')) {
    return TypeError;
  }
  if (message.startsWith('SyntaxError: ')) {
    return SyntaxError;
  }
  if (message.startsWith('ReferenceError: ')) {
    return ReferenceError;
  }
  return Error;
};
const constructError = (message, type, name) => {
  const ErrorConstructor = getErrorConstructor(message, type);
  if (ErrorConstructor === DOMException && name) {
    return new ErrorConstructor(message, name);
  }
  if (ErrorConstructor === Error) {
    const error = new Error(message);
    if (name && name !== 'VError') {
      error.name = name;
    }
    return error;
  }
  return new ErrorConstructor(message);
};
const joinLines = lines => {
  return lines.join(NewLine);
};
const splitLines = lines => {
  return lines.split(NewLine);
};
const getCurrentStack = () => {
  const stackLinesToSkip = 3;
  const currentStack = joinLines(splitLines(new Error().stack || '').slice(stackLinesToSkip));
  return currentStack;
};
const getNewLineIndex = (string, startIndex = undefined) => {
  return string.indexOf(NewLine, startIndex);
};
const getParentStack = error => {
  let parentStack = error.stack || error.data || error.message || '';
  if (parentStack.startsWith('    at')) {
    parentStack = error.message + NewLine + parentStack;
  }
  return parentStack;
};
const MethodNotFound = -32601;
const Custom = -32001;
const restoreJsonRpcError = error => {
  const currentStack = getCurrentStack();
  if (error && error instanceof Error) {
    if (typeof error.stack === 'string') {
      error.stack = error.stack + NewLine + currentStack;
    }
    return error;
  }
  if (error && error.code && error.code === MethodNotFound) {
    const restoredError = new JsonRpcError(error.message);
    const parentStack = getParentStack(error);
    restoredError.stack = parentStack + NewLine + currentStack;
    return restoredError;
  }
  if (error && error.message) {
    const restoredError = constructError(error.message, error.type, error.name);
    if (error.data) {
      if (error.data.stack && error.data.type && error.message) {
        restoredError.stack = error.data.type + ': ' + error.message + NewLine + error.data.stack + NewLine + currentStack;
      } else if (error.data.stack) {
        restoredError.stack = error.data.stack;
      }
      if (error.data.codeFrame) {
        // @ts-ignore
        restoredError.codeFrame = error.data.codeFrame;
      }
      if (error.data.code) {
        // @ts-ignore
        restoredError.code = error.data.code;
      }
      if (error.data.type) {
        // @ts-ignore
        restoredError.name = error.data.type;
      }
    } else {
      if (error.stack) {
        const lowerStack = restoredError.stack || '';
        // @ts-ignore
        const indexNewLine = getNewLineIndex(lowerStack);
        const parentStack = getParentStack(error);
        // @ts-ignore
        restoredError.stack = parentStack + lowerStack.slice(indexNewLine);
      }
      if (error.codeFrame) {
        // @ts-ignore
        restoredError.codeFrame = error.codeFrame;
      }
    }
    return restoredError;
  }
  if (typeof error === 'string') {
    return new Error(`JsonRpc Error: ${error}`);
  }
  return new Error(`JsonRpc Error: ${error}`);
};
const unwrapJsonRpcResult = responseMessage => {
  if ('error' in responseMessage) {
    const restoredError = restoreJsonRpcError(responseMessage.error);
    throw restoredError;
  }
  if ('result' in responseMessage) {
    return responseMessage.result;
  }
  throw new JsonRpcError('unexpected response message');
};
const warn = (...args) => {
  console.warn(...args);
};
const resolve = (id, response) => {
  const fn = get$1(id);
  if (!fn) {
    console.log(response);
    warn(`callback ${id} may already be disposed`);
    return;
  }
  fn(response);
  remove(id);
};
const E_COMMAND_NOT_FOUND = 'E_COMMAND_NOT_FOUND';
const getErrorType = prettyError => {
  if (prettyError && prettyError.type) {
    return prettyError.type;
  }
  if (prettyError && prettyError.constructor && prettyError.constructor.name) {
    return prettyError.constructor.name;
  }
  return undefined;
};
const isAlreadyStack = line => {
  return line.trim().startsWith('at ');
};
const getStack = prettyError => {
  const stackString = prettyError.stack || '';
  const newLineIndex = stackString.indexOf('\n');
  if (newLineIndex !== -1 && !isAlreadyStack(stackString.slice(0, newLineIndex))) {
    return stackString.slice(newLineIndex + 1);
  }
  return stackString;
};
const getErrorProperty = (error, prettyError) => {
  if (error && error.code === E_COMMAND_NOT_FOUND) {
    return {
      code: MethodNotFound,
      data: error.stack,
      message: error.message
    };
  }
  return {
    code: Custom,
    data: {
      code: prettyError.code,
      codeFrame: prettyError.codeFrame,
      name: prettyError.name,
      stack: getStack(prettyError),
      type: getErrorType(prettyError)
    },
    message: prettyError.message
  };
};
const create$1$1 = (id, error) => {
  return {
    error,
    id,
    jsonrpc: Two$1
  };
};
const getErrorResponse = (id, error, preparePrettyError, logError) => {
  const prettyError = preparePrettyError(error);
  logError(error, prettyError);
  const errorProperty = getErrorProperty(error, prettyError);
  return create$1$1(id, errorProperty);
};
const create$6 = (message, result) => {
  return {
    id: message.id,
    jsonrpc: Two$1,
    result: result ?? null
  };
};
const getSuccessResponse = (message, result) => {
  const resultProperty = result ?? null;
  return create$6(message, resultProperty);
};
const getErrorResponseSimple = (id, error) => {
  return {
    error: {
      code: Custom,
      data: error,
      // @ts-ignore
      message: error.message
    },
    id,
    jsonrpc: Two$1
  };
};
const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
  try {
    const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
    return getSuccessResponse(message, result);
  } catch (error) {
    if (ipc.canUseSimpleErrorResponse) {
      return getErrorResponseSimple(message.id, error);
    }
    return getErrorResponse(message.id, error, preparePrettyError, logError);
  }
};
const defaultPreparePrettyError = error => {
  return error;
};
const defaultLogError = () => {
  // ignore
};
const defaultRequiresSocket = () => {
  return false;
};
const defaultResolve = resolve;

// TODO maybe remove this in v6 or v7, only accept options object to simplify the code
const normalizeParams = args => {
  if (args.length === 1) {
    const options = args[0];
    return {
      execute: options.execute,
      ipc: options.ipc,
      logError: options.logError || defaultLogError,
      message: options.message,
      preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
      requiresSocket: options.requiresSocket || defaultRequiresSocket,
      resolve: options.resolve || defaultResolve
    };
  }
  return {
    execute: args[2],
    ipc: args[0],
    logError: args[5],
    message: args[1],
    preparePrettyError: args[4],
    requiresSocket: args[6],
    resolve: args[3]
  };
};
const handleJsonRpcMessage = async (...args) => {
  const options = normalizeParams(args);
  const {
    execute,
    ipc,
    logError,
    message,
    preparePrettyError,
    requiresSocket,
    resolve
  } = options;
  if ('id' in message) {
    if ('method' in message) {
      const response = await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
      try {
        ipc.send(response);
      } catch (error) {
        const errorResponse = getErrorResponse(message.id, error, preparePrettyError, logError);
        ipc.send(errorResponse);
      }
      return;
    }
    resolve(message.id, message);
    return;
  }
  if ('method' in message) {
    await getResponse(message, ipc, execute, preparePrettyError, logError, requiresSocket);
    return;
  }
  throw new JsonRpcError('unexpected message');
};

const Two = '2.0';

const create$5 = (method, params) => {
  return {
    jsonrpc: Two,
    method,
    params
  };
};

const create$4 = (id, method, params) => {
  const message = {
    id,
    jsonrpc: Two,
    method,
    params
  };
  return message;
};

let id = 0;
const create$3 = () => {
  return ++id;
};

const registerPromise = map => {
  const id = create$3();
  const {
    promise,
    resolve
  } = Promise.withResolvers();
  map[id] = resolve;
  return {
    id,
    promise
  };
};

const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
  const {
    id,
    promise
  } = registerPromise(callbacks);
  const message = create$4(id, method, params);
  if (useSendAndTransfer && ipc.sendAndTransfer) {
    ipc.sendAndTransfer(message);
  } else {
    ipc.send(message);
  }
  const responseMessage = await promise;
  return unwrapJsonRpcResult(responseMessage);
};
const createRpc = ipc => {
  const callbacks = Object.create(null);
  ipc._resolve = (id, response) => {
    const fn = callbacks[id];
    if (!fn) {
      console.warn(`callback ${id} may already be disposed`);
      return;
    }
    fn(response);
    delete callbacks[id];
  };
  const rpc = {
    async dispose() {
      await ipc?.dispose();
    },
    invoke(method, ...params) {
      return invokeHelper(callbacks, ipc, method, params, false);
    },
    invokeAndTransfer(method, ...params) {
      return invokeHelper(callbacks, ipc, method, params, true);
    },
    // @ts-ignore
    ipc,
    /**
     * @deprecated
     */
    send(method, ...params) {
      const message = create$5(method, params);
      ipc.send(message);
    }
  };
  return rpc;
};

const requiresSocket = () => {
  return false;
};
const preparePrettyError = error => {
  return error;
};
const logError = () => {
  // handled by renderer worker
};
const handleMessage = event => {
  const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
  const actualExecute = event?.target?.execute || execute;
  return handleJsonRpcMessage(event.target, event.data, actualExecute, event.target._resolve, preparePrettyError, logError, actualRequiresSocket);
};

const handleIpc = ipc => {
  if ('addEventListener' in ipc) {
    ipc.addEventListener('message', handleMessage);
  } else if ('on' in ipc) {
    // deprecated
    ipc.on('message', handleMessage);
  }
};

const listen$1 = async (module, options) => {
  const rawIpc = await module.listen(options);
  if (module.signal) {
    module.signal(rawIpc);
  }
  const ipc = module.wrap(rawIpc);
  return ipc;
};

const create$2 = async ({
  commandMap
}) => {
  // TODO create a commandMap per rpc instance
  register(commandMap);
  const ipc = await listen$1(IpcChildWithModuleWorkerAndMessagePort$1);
  handleIpc(ipc);
  const rpc = createRpc(ipc);
  return rpc;
};

const toCommandId = key => {
  const dotIndex = key.indexOf('.');
  return key.slice(dotIndex + 1);
};
const create$1 = () => {
  const states = Object.create(null);
  const commandMapRef = {};
  return {
    clear() {
      for (const key of Object.keys(states)) {
        delete states[key];
      }
    },
    diff(uid, modules, numbers) {
      const {
        newState,
        oldState
      } = states[uid];
      const diffResult = [];
      for (let i = 0; i < modules.length; i++) {
        const fn = modules[i];
        if (!fn(oldState, newState)) {
          diffResult.push(numbers[i]);
        }
      }
      return diffResult;
    },
    dispose(uid) {
      delete states[uid];
    },
    get(uid) {
      return states[uid];
    },
    getCommandIds() {
      const keys = Object.keys(commandMapRef);
      const ids = keys.map(toCommandId);
      return ids;
    },
    getKeys() {
      return Object.keys(states).map(key => {
        return Number.parseFloat(key);
      });
    },
    registerCommands(commandMap) {
      Object.assign(commandMapRef, commandMap);
    },
    set(uid, oldState, newState) {
      states[uid] = {
        newState,
        oldState
      };
    },
    wrapCommand(fn) {
      const wrapped = async (uid, ...args) => {
        const {
          newState,
          oldState
        } = states[uid];
        const newerState = await fn(newState, ...args);
        if (oldState === newerState || newState === newerState) {
          return;
        }
        const latestOld = states[uid];
        const latestNew = {
          ...latestOld.newState,
          ...newerState
        };
        states[uid] = {
          newState: latestNew,
          oldState: latestOld.oldState
        };
      };
      return wrapped;
    },
    wrapGetter(fn) {
      const wrapped = (uid, ...args) => {
        const {
          newState
        } = states[uid];
        return fn(newState, ...args);
      };
      return wrapped;
    },
    wrapLoadContent(fn) {
      const wrapped = async (uid, ...args) => {
        const {
          newState,
          oldState
        } = states[uid];
        const result = await fn(newState, ...args);
        const {
          error,
          state
        } = result;
        if (oldState === state || newState === state) {
          return {
            error
          };
        }
        const latestOld = states[uid];
        const latestNew = {
          ...latestOld.newState,
          ...state
        };
        states[uid] = {
          newState: latestNew,
          oldState: latestOld.oldState
        };
        return {
          error
        };
      };
      return wrapped;
    }
  };
};
const terminate = () => {
  globalThis.close();
};

const {
  get,
  getCommandIds,
  registerCommands,
  set,
  wrapCommand,
  wrapGetter
} = create$1();

const createDefaultState = () => {
  return {
    assetDir: '',
    databaseName: 'lvce-chat-view-sessions',
    dataBaseVersion: 2,
    errorMessage: '',
    events: [],
    eventStoreName: 'chat-view-events',
    filterValue: '',
    height: 0,
    initial: true,
    platform: 0,
    sessionId: '',
    sessionIdIndexName: 'sessionId',
    showInputEvents: false,
    uid: 0,
    uri: '',
    width: 0,
    x: 0,
    y: 0
  };
};

const create = (uid, uri, x, y, width, height, platform, assetDir, sessionId = '', databaseName = 'lvce-chat-view-sessions', dataBaseVersion = 2, eventStoreName = 'chat-view-events', sessionIdIndexName = 'sessionId') => {
  const state = {
    ...createDefaultState(),
    assetDir,
    databaseName,
    dataBaseVersion,
    eventStoreName,
    height,
    platform,
    sessionId,
    sessionIdIndexName,
    uid,
    uri,
    width,
    x,
    y
  };
  set(uid, state, state);
};

const RenderItems = 1;
const RenderCss = 2;

const diff = (oldState, newState) => {
  if (oldState.initial !== newState.initial) {
    return [RenderCss, RenderItems];
  }
  if (oldState.errorMessage !== newState.errorMessage || oldState.events !== newState.events || oldState.filterValue !== newState.filterValue || oldState.sessionId !== newState.sessionId || oldState.showInputEvents !== newState.showInputEvents || oldState.uid !== newState.uid) {
    return [RenderItems];
  }
  return [];
};

const diff2 = uid => {
  const {
    newState,
    oldState
  } = get(uid);
  return diff(oldState, newState);
};

const getBoolean = value => {
  return value === true || value === 'true' || value === 'on' || value === '1';
};

const Filter = 'filter';
const ShowInputEvents = 'showInputEvents';

const handleInput = (state, name, value, checked) => {
  if (name === Filter) {
    return {
      ...state,
      filterValue: value
    };
  }
  if (name === ShowInputEvents) {
    return {
      ...state,
      showInputEvents: getBoolean(checked)
    };
  }
  return state;
};

const requestToPromise = async createRequest => {
  const request = createRequest();
  const {
    promise,
    reject,
    resolve
  } = Promise.withResolvers();
  request.addEventListener('success', () => {
    resolve(request.result);
  });
  request.addEventListener('error', () => {
    reject(request.error || new Error('IndexedDB request failed'));
  });
  return promise;
};

/* eslint-disable @typescript-eslint/prefer-readonly-parameter-types */

const openDatabase = async (databaseName, dataBaseVersion) => {
  const request = indexedDB.open(databaseName, dataBaseVersion);
  return requestToPromise(() => request);
};
const getAllEvents = async store => {
  const all = await requestToPromise(() => store.getAll());
  return all;
};
const filterEventsBySessionId = (events, sessionId) => {
  return events.filter(event => event.sessionId === sessionId);
};
const getEventsBySessionId = async (store, sessionId, sessionIdIndexName) => {
  if (store.indexNames.contains(sessionIdIndexName)) {
    const index = store.index(sessionIdIndexName);
    const events = await requestToPromise(() => index.getAll(IDBKeyRange.only(sessionId)));
    return filterEventsBySessionId(events, sessionId);
  }
  const all = await getAllEvents(store);
  return filterEventsBySessionId(all, sessionId);
};
const listChatViewEvents = async (sessionId, databaseName, dataBaseVersion, eventStoreName, sessionIdIndexName) => {
  if (typeof indexedDB === 'undefined') {
    return [];
  }
  const database = await openDatabase(databaseName, dataBaseVersion);
  try {
    if (!database.objectStoreNames.contains(eventStoreName)) {
      return [];
    }
    const transaction = database.transaction(eventStoreName, 'readonly');
    const store = transaction.objectStore(eventStoreName);
    if (!sessionId) {
      return [];
    }
    return getEventsBySessionId(store, sessionId, sessionIdIndexName);
  } finally {
    database.close();
  }
};

const chatDebugUriPattern = /^chat-debug:\/\/([^/?#]+)$/;
const parseChatDebugUri = uri => {
  if (!uri) {
    throw new Error('Missing URI');
  }
  const match = uri.match(chatDebugUriPattern);
  if (!match) {
    throw new Error('Invalid URI format');
  }
  const encodedSessionId = match[1];
  let sessionId;
  try {
    sessionId = decodeURIComponent(encodedSessionId);
  } catch {
    throw new Error('Invalid URI encoding');
  }
  if (!sessionId || /[/?#]/.test(sessionId)) {
    throw new Error('Invalid session id');
  }
  return sessionId;
};

const getInvalidUriMessage = uri => {
  if (!uri) {
    return 'Unable to load debug session: missing URI. Expected format: chat-debug://<sessionId>.';
  }
  return `Unable to load debug session: invalid URI "${uri}". Expected format: chat-debug://<sessionId>.`;
};
const getSessionNotFoundMessage = sessionId => {
  return `No chat session found for sessionId "${sessionId}".`;
};
const getFailedToLoadMessage = sessionId => {
  return `Failed to load chat debug session "${sessionId}". Please try again.`;
};
const loadContent = async state => {
  const {
    databaseName,
    dataBaseVersion,
    eventStoreName,
    sessionIdIndexName,
    uri
  } = state;
  let sessionId = '';
  try {
    sessionId = parseChatDebugUri(uri);
  } catch {
    return {
      ...state,
      errorMessage: getInvalidUriMessage(uri),
      events: [],
      initial: false,
      sessionId
    };
  }
  try {
    const events = await listChatViewEvents(sessionId, databaseName, dataBaseVersion, eventStoreName, sessionIdIndexName);
    if (events.length === 0) {
      return {
        ...state,
        errorMessage: getSessionNotFoundMessage(sessionId),
        events: [],
        initial: false,
        sessionId
      };
    }
    return {
      ...state,
      errorMessage: '',
      events,
      initial: false,
      sessionId
    };
  } catch {
    return {
      ...state,
      errorMessage: getFailedToLoadMessage(sessionId),
      events: [],
      initial: false,
      sessionId
    };
  }
};

const refresh = async state => {
  const events = await listChatViewEvents(state.sessionId, state.databaseName, state.dataBaseVersion, state.eventStoreName, state.sessionIdIndexName);
  return {
    ...state,
    errorMessage: '',
    events,
    initial: false
  };
};

const TargetChecked = 'event.target.checked';
const TargetName = 'event.target.name';
const TargetValue = 'event.target.value';

const SetCss = 'Viewlet.setCss';
const SetDom2 = 'Viewlet.setDom2';

const getCss = () => {
  return `
.ChatDebugView {
  padding: 8px;
  display: grid;
  grid-template-rows: auto auto 1fr;
  height: 100%;
  box-sizing: border-box;
  gap: 8px;
}

.ChatDebugViewTop {
  display: flex;
  align-items: center;
  gap: 12px;
}

.ChatDebugViewTop .InputBox {
  flex: 1;
}

.ChatDebugViewToggle {
  display: flex;
  align-items: center;
  gap: 6px;
  white-space: nowrap;
}

.ChatDebugViewSession {
  font-size: 12px;
  opacity: 0.8;
}

.ChatDebugViewEventCount {
  font-size: 12px;
  opacity: 0.8;
}

.ChatDebugViewEvents {
  overflow: auto;
  scrollbar-width: thin;
  scrollbar-color: var(--vscode-scrollbarSlider-background, rgba(121, 121, 121, 0.4)) transparent;
}

.ChatDebugViewEvents::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

.ChatDebugViewEvents::-webkit-scrollbar-track {
  background: transparent;
}

.ChatDebugViewEvents::-webkit-scrollbar-thumb {
  background: var(--vscode-scrollbarSlider-background, rgba(121, 121, 121, 0.4));
  border-radius: 999px;
  border: 2px solid transparent;
  background-clip: content-box;
}

.ChatDebugViewEvents::-webkit-scrollbar-thumb:hover {
  background: var(--vscode-scrollbarSlider-hoverBackground, rgba(100, 100, 100, 0.7));
}

.ChatDebugViewEvents::-webkit-scrollbar-thumb:active {
  background: var(--vscode-scrollbarSlider-activeBackground, rgba(191, 191, 191, 0.4));
}

.ChatDebugViewEvent {
  margin: 0;
  padding: 8px;
  border: 1px solid var(--vscode-editorWidget-border, #454545);
  border-radius: 6px;
  margin-bottom: 8px;
  white-space: pre-wrap;
  word-break: break-word;
  font-family: var(--vscode-editor-font-family, monospace);
  font-size: 12px;
  user-select: text;
}

.ChatDebugViewEmpty {
  opacity: 0.8;
}

.ChatDebugViewError {
  color: var(--vscode-errorForeground, #f14c4c);
  white-space: normal;
}

.TokenText {
  color: var(--vscode-editor-foreground, inherit);
}

.TokenKey {
  color: var(--vscode-symbolIcon-propertyForeground, var(--vscode-editor-foreground, inherit));
}

.TokenString {
  color: var(--vscode-debugTokenExpression-string, var(--vscode-charts-green, #89d185));
}

.TokenNumeric {
  color: var(--vscode-debugTokenExpression-number, var(--vscode-charts-blue, #75beff));
}

.TokenBoolean {
  color: var(--vscode-debugTokenExpression-boolean, var(--vscode-charts-yellow, #dcdcaa));
}
`;
};

const renderCss = (oldState, newState) => {
  const css = getCss();
  return [SetCss, newState.uid, css];
};

const Div = 4;
const Input = 6;
const Span = 8;
const Text = 12;
const Pre = 51;

const text = data => {
  return {
    childCount: 0,
    text: data,
    type: Text
  };
};

const HandleInput = 4;

const numberRegex = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/;
const getTokenSegments = json => {
  const segments = [];
  const pushToken = (className, value) => {
    if (!value) {
      return;
    }
    const lastSegment = segments.at(-1);
    if (lastSegment && lastSegment.className === className) {
      const merged = {
        className,
        value: lastSegment.value + value
      };
      segments[segments.length - 1] = merged;
      return;
    }
    segments.push({
      className,
      value
    });
  };
  let i = 0;
  while (i < json.length) {
    const character = json[i];
    if (character === '"') {
      const start = i;
      i++;
      while (i < json.length) {
        const currentCharacter = json[i];
        if (currentCharacter === '\\') {
          i += 2;
          continue;
        }
        if (currentCharacter === '"') {
          i++;
          break;
        }
        i++;
      }
      const tokenValue = json.slice(start, i);
      let lookAheadIndex = i;
      while (lookAheadIndex < json.length && /\s/u.test(json[lookAheadIndex])) {
        lookAheadIndex++;
      }
      const className = json[lookAheadIndex] === ':' ? 'TokenKey' : 'TokenString';
      pushToken(className, tokenValue);
      continue;
    }
    const numberMatch = numberRegex.exec(json.slice(i));
    if (numberMatch) {
      pushToken('TokenNumeric', numberMatch[0]);
      i += numberMatch[0].length;
      continue;
    }
    if (json.startsWith('true', i)) {
      pushToken('TokenBoolean', 'true');
      i += 4;
      continue;
    }
    if (json.startsWith('false', i)) {
      pushToken('TokenBoolean', 'false');
      i += 5;
      continue;
    }
    if (json.startsWith('null', i)) {
      pushToken('TokenBoolean', 'null');
      i += 4;
      continue;
    }
    pushToken('TokenText', character);
    i++;
  }
  return segments;
};
const getJsonTokenNodes = value => {
  const json = JSON.stringify(value, null, 2);
  if (!json) {
    return [{
      childCount: 1,
      className: 'TokenText',
      type: Span
    }, text(String(json))];
  }
  const segments = getTokenSegments(json);
  return segments.flatMap(segment => {
    return [{
      childCount: 1,
      className: segment.className,
      type: Span
    }, text(segment.value)];
  });
};

const getEventNode = event => {
  const tokenNodes = getJsonTokenNodes(event);
  return [{
    childCount: tokenNodes.length / 2,
    className: 'ChatDebugViewEvent',
    type: Pre
  }, ...tokenNodes];
};
const getChatDebugViewDom = (sessionId, errorMessage, filterValue, showInputEvents, events) => {
  if (errorMessage) {
    return [{
      childCount: 1,
      className: 'ChatDebugView',
      type: Div
    }, {
      childCount: 1,
      className: 'ChatDebugViewError',
      type: Div
    }, text(errorMessage)];
  }
  const eventNodes = events.flatMap(getEventNode);
  const eventCountText = `${events.length} event${events.length === 1 ? '' : 's'}`;
  return [{
    childCount: 4,
    className: 'ChatDebugView',
    type: Div
  }, {
    childCount: 2,
    className: 'ChatDebugViewTop',
    type: Div
  }, {
    childCount: 0,
    className: 'InputBox',
    name: Filter,
    onInput: HandleInput,
    placeholder: 'Filter events',
    type: Input,
    value: filterValue
  }, {
    childCount: 2,
    className: 'ChatDebugViewToggle',
    type: Div
  }, {
    checked: showInputEvents,
    childCount: 0,
    inputType: 'checkbox',
    name: ShowInputEvents,
    onChange: HandleInput,
    type: Input
  }, text('Show input events'), {
    childCount: 1,
    className: 'ChatDebugViewEventCount',
    type: Div
  }, text(eventCountText), {
    childCount: 1,
    className: 'ChatDebugViewSession',
    type: Div
  }, text(`sessionId: ${sessionId || '(none)'}`), {
    childCount: eventNodes.length === 0 ? 1 : eventNodes.length,
    className: 'ChatDebugViewEvents',
    type: Div
  }, ...(eventNodes.length === 0 ? [{
    childCount: 1,
    className: errorMessage ? 'ChatDebugViewError' : 'ChatDebugViewEmpty',
    type: Div
  }, text(errorMessage || 'No events')] : eventNodes)];
};

const getVisibleEvents = (events, showInputEvents) => {
  if (showInputEvents) {
    return events;
  }
  return events.filter(event => event.type !== 'handle-input');
};
const getFilteredEvents = (events, filterValue, showInputEvents) => {
  const visibleEvents = getVisibleEvents(events, showInputEvents);
  const normalizedFilter = filterValue.trim().toLowerCase();
  if (!normalizedFilter) {
    return visibleEvents;
  }
  return visibleEvents.filter(event => JSON.stringify(event).toLowerCase().includes(normalizedFilter));
};

const withSessionEventIds = events => {
  return events.map((event, index) => {
    return {
      ...event,
      eventId: index + 1
    };
  });
};
const renderItems = (oldState, newState) => {
  const eventsWithIds = withSessionEventIds(newState.events);
  const filteredEvents = getFilteredEvents(eventsWithIds, newState.filterValue, newState.showInputEvents);
  const dom = getChatDebugViewDom(newState.sessionId, newState.errorMessage, newState.filterValue, newState.showInputEvents, filteredEvents);
  return [SetDom2, newState.uid, dom];
};

const getRenderer = diffType => {
  switch (diffType) {
    case RenderCss:
      return renderCss;
    case RenderItems:
      return renderItems;
    default:
      throw new Error('unknown renderer');
  }
};

const applyRender = (oldState, newState, diffResult) => {
  const commands = [];
  for (const item of diffResult) {
    const fn = getRenderer(item);
    const result = fn(oldState, newState);
    if (result.length > 0) {
      commands.push(result);
    }
  }
  return commands;
};

const render2 = (uid, diffResult) => {
  const {
    newState,
    oldState
  } = get(uid);
  set(uid, newState, newState);
  return applyRender(oldState, newState, diffResult);
};

const renderEventListeners = () => {
  return [{
    name: HandleInput,
    params: ['handleInput', TargetName, TargetValue, TargetChecked]
  }];
};

const rerender = state => {
  return structuredClone(state);
};

const resize = (state, dimensions) => {
  return {
    ...state,
    ...dimensions
  };
};

const saveState = state => {
  const {
    filterValue,
    height,
    sessionId,
    showInputEvents,
    width,
    x,
    y
  } = state;
  return {
    filterValue,
    height,
    sessionId,
    showInputEvents,
    width,
    x,
    y
  };
};

const setEvents = (state, events) => {
  return {
    ...state,
    errorMessage: '',
    events,
    initial: false
  };
};

const setSessionId = async (state, sessionId) => {
  const events = await listChatViewEvents(sessionId, state.databaseName, state.dataBaseVersion, state.eventStoreName, state.sessionIdIndexName);
  return {
    ...state,
    errorMessage: '',
    events,
    initial: false,
    sessionId
  };
};

const commandMap = {
  'ChatDebug.create': create,
  'ChatDebug.diff2': diff2,
  'ChatDebug.getCommandIds': getCommandIds,
  'ChatDebug.handleInput': wrapCommand(handleInput),
  'ChatDebug.loadContent': wrapCommand(loadContent),
  'ChatDebug.loadContent2': wrapCommand(loadContent),
  'ChatDebug.refresh': wrapCommand(refresh),
  'ChatDebug.render2': render2,
  'ChatDebug.renderEventListeners': renderEventListeners,
  'ChatDebug.rerender': wrapCommand(rerender),
  'ChatDebug.resize': wrapCommand(resize),
  'ChatDebug.saveState': wrapGetter(saveState),
  'ChatDebug.setEvents': wrapCommand(setEvents),
  'ChatDebug.setSessionId': wrapCommand(setSessionId),
  'ChatDebug.terminate': terminate
};

const listen = async () => {
  registerCommands(commandMap);
  await create$2({
    commandMap: commandMap
  });
};

const main = async () => {
  await listen();
};

main();
