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;
    }
  }
}

class AssertionError extends Error {
  constructor(message) {
    super(message);
    this.name = 'AssertionError';
  }
}
const Object$1 = 1;
const Number$1 = 2;
const Array$1 = 3;
const String = 4;
const Boolean = 5;
const Function = 6;
const Null = 7;
const Unknown = 8;
const getType = value => {
  switch (typeof value) {
    case 'number':
      return Number$1;
    case 'function':
      return Function;
    case 'string':
      return String;
    case 'object':
      if (value === null) {
        return Null;
      }
      if (Array.isArray(value)) {
        return Array$1;
      }
      return Object$1;
    case 'boolean':
      return Boolean;
    default:
      return Unknown;
  }
};
const number = value => {
  const type = getType(value);
  if (type !== Number$1) {
    throw new AssertionError('expected value to be of type number');
  }
};

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
};
const addListener = (emitter, type, callback) => {
  if ('addEventListener' in emitter) {
    emitter.addEventListener(type, callback);
  } else {
    emitter.on(type, callback);
  }
};
const removeListener = (emitter, type, callback) => {
  if ('removeEventListener' in emitter) {
    emitter.removeEventListener(type, callback);
  } else {
    emitter.off(type, callback);
  }
};
const getFirstEvent = (eventEmitter, eventMap) => {
  const {
    promise,
    resolve
  } = Promise.withResolvers();
  const listenerMap = Object.create(null);
  const cleanup = value => {
    for (const event of Object.keys(eventMap)) {
      removeListener(eventEmitter, event, listenerMap[event]);
    }
    resolve(value);
  };
  for (const [event, type] of Object.entries(eventMap)) {
    const listener = event => {
      cleanup({
        event,
        type
      });
    };
    addListener(eventEmitter, event, listener);
    listenerMap[event] = listener;
  }
  return promise;
};
const Message$1 = 3;
const create$5 = async ({
  isMessagePortOpen,
  messagePort
}) => {
  if (!isMessagePort(messagePort)) {
    throw new IpcError('port must be of type MessagePort');
  }
  if (isMessagePortOpen) {
    return messagePort;
  }
  const eventPromise = getFirstEvent(messagePort, {
    message: Message$1
  });
  messagePort.start();
  const {
    event,
    type
  } = await eventPromise;
  if (type !== Message$1) {
    throw new IpcError('Failed to wait for ipc message');
  }
  if (event.data !== readyMessage) {
    throw new IpcError('unexpected first message');
  }
  return messagePort;
};
const signal$1 = messagePort => {
  messagePort.start();
};
class IpcParentWithMessagePort extends Ipc {
  getData = getData$2;
  send(message) {
    this._rawIpc.postMessage(message);
  }
  sendAndTransfer(message) {
    const transfer = getTransferrables(message);
    this._rawIpc.postMessage(message, transfer);
  }
  dispose() {
    this._rawIpc.close();
  }
  onMessage(callback) {
    this._rawIpc.addEventListener('message', callback);
  }
  onClose(callback) {}
}
const wrap$5 = messagePort => {
  return new IpcParentWithMessagePort(messagePort);
};
const IpcParentWithMessagePort$1 = {
  __proto__: null,
  create: create$5,
  signal: signal$1,
  wrap: wrap$5
};

const Two$1 = '2.0';
const callbacks = Object.create(null);
const get$2 = id => {
  return callbacks[id];
};
const remove$1 = 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 TypeError$1:
        return TypeError;
      case SyntaxError$1:
        return SyntaxError;
      case ReferenceError$1:
        return ReferenceError;
      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$2(id);
  if (!fn) {
    console.log(response);
    warn(`callback ${id} may already be disposed`);
    return;
  }
  fn(response);
  remove$1(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,
      message: error.message,
      data: error.stack
    };
  }
  return {
    code: Custom,
    message: prettyError.message,
    data: {
      stack: getStack(prettyError),
      codeFrame: prettyError.codeFrame,
      type: getErrorType(prettyError),
      code: prettyError.code,
      name: prettyError.name
    }
  };
};
const create$1$2 = (id, error) => {
  return {
    jsonrpc: Two$1,
    id,
    error
  };
};
const getErrorResponse = (id, error, preparePrettyError, logError) => {
  const prettyError = preparePrettyError(error);
  logError(error, prettyError);
  const errorProperty = getErrorProperty(error, prettyError);
  return create$1$2(id, errorProperty);
};
const create$3 = (message, result) => {
  return {
    jsonrpc: Two$1,
    id: message.id,
    result: result ?? null
  };
};
const getSuccessResponse = (message, result) => {
  const resultProperty = result ?? null;
  return create$3(message, resultProperty);
};
const getErrorResponseSimple = (id, error) => {
  return {
    jsonrpc: Two$1,
    id,
    error: {
      code: Custom,
      // @ts-ignore
      message: error.message,
      data: error
    }
  };
};
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 {
      ipc: options.ipc,
      message: options.message,
      execute: options.execute,
      resolve: options.resolve || defaultResolve,
      preparePrettyError: options.preparePrettyError || defaultPreparePrettyError,
      logError: options.logError || defaultLogError,
      requiresSocket: options.requiresSocket || defaultRequiresSocket
    };
  }
  return {
    ipc: args[0],
    message: args[1],
    execute: args[2],
    resolve: args[3],
    preparePrettyError: args[4],
    logError: args[5],
    requiresSocket: args[6]
  };
};
const handleJsonRpcMessage = async (...args) => {
  const options = normalizeParams(args);
  const {
    message,
    ipc,
    execute,
    resolve,
    preparePrettyError,
    logError,
    requiresSocket
  } = 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');
};

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$1 = key => {
  return commands[key];
};
const execute$1 = (command, ...args) => {
  const fn = getCommand$1(command);
  if (!fn) {
    throw new CommandNotFoundError(command);
  }
  return fn(...args);
};

const Two = '2.0';
const create$s = (method, params) => {
  return {
    jsonrpc: Two,
    method,
    params
  };
};
const create$r = (id, method, params) => {
  const message = {
    id,
    jsonrpc: Two,
    method,
    params
  };
  return message;
};
let id = 0;
const create$q = () => {
  return ++id;
};

/* eslint-disable n/no-unsupported-features/es-syntax */

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

// @ts-ignore
const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
  const {
    id,
    promise
  } = registerPromise(callbacks);
  const message = create$r(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$s(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$1;
  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$4 = async ({
  commandMap,
  isMessagePortOpen = true,
  messagePort
}) => {
  // TODO create a commandMap per rpc instance
  register(commandMap);
  const rawIpc = await IpcParentWithMessagePort$1.create({
    isMessagePortOpen,
    messagePort
  });
  const ipc = IpcParentWithMessagePort$1.wrap(rawIpc);
  handleIpc(ipc);
  const rpc = createRpc(ipc);
  messagePort.start();
  return rpc;
};
const create$2$1 = async ({
  commandMap,
  isMessagePortOpen,
  send
}) => {
  const {
    port1,
    port2
  } = new MessageChannel();
  await send(port1);
  return create$4({
    commandMap,
    isMessagePortOpen,
    messagePort: port2
  });
};
const TransferMessagePortRpcParent = {
  __proto__: null,
  create: create$2$1
};
const create$1$1 = 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 WebWorkerRpcClient = {
  __proto__: null,
  create: create$1$1
};
const createMockRpc = ({
  commandMap
}) => {
  const invocations = [];
  const invoke = (method, ...params) => {
    invocations.push([method, ...params]);
    const command = commandMap[method];
    if (!command) {
      throw new Error(`command ${method} not found`);
    }
    return command(...params);
  };
  const mockRpc = {
    invocations,
    invoke,
    invokeAndTransfer: invoke
  };
  return mockRpc;
};

const toCommandId = key => {
  const dotIndex = key.indexOf('.');
  return key.slice(dotIndex + 1);
};
const create$2 = () => {
  const states = Object.create(null);
  const commandMapRef = {};
  return {
    get(uid) {
      return states[uid];
    },
    set(uid, oldState, newState) {
      states[uid] = {
        oldState,
        newState
      };
    },
    dispose(uid) {
      delete states[uid];
    },
    getKeys() {
      return Object.keys(states).map(key => {
        return Number.parseInt(key);
      });
    },
    clear() {
      for (const key of Object.keys(states)) {
        delete states[key];
      }
    },
    wrapCommand(fn) {
      const wrapped = async (uid, ...args) => {
        const {
          oldState,
          newState
        } = states[uid];
        const newerState = await fn(newState, ...args);
        if (oldState === newerState || newState === newerState) {
          return;
        }
        const latest = states[uid];
        states[uid] = {
          oldState: latest.oldState,
          newState: newerState
        };
      };
      return wrapped;
    },
    wrapGetter(fn) {
      const wrapped = (uid, ...args) => {
        const {
          newState
        } = states[uid];
        return fn(newState, ...args);
      };
      return wrapped;
    },
    diff(uid, modules, numbers) {
      const {
        oldState,
        newState
      } = 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;
    },
    getCommandIds() {
      const keys = Object.keys(commandMapRef);
      const ids = keys.map(toCommandId);
      return ids;
    },
    registerCommands(commandMap) {
      Object.assign(commandMapRef, commandMap);
    }
  };
};
const terminate = () => {
  globalThis.close();
};

const Text = 12;

const EditorWorker$1 = 99;
const ExtensionHostWorker = 44;

const SetFocusContext = 'Viewlet.setFocusContext';

const rpcs = Object.create(null);
const set$5 = (id, rpc) => {
  rpcs[id] = rpc;
};
const get$1 = id => {
  return rpcs[id];
};
const remove = id => {
  delete rpcs[id];
};

/* eslint-disable  @typescript-eslint/explicit-function-return-type */
const create$1 = rpcId => {
  return {
    async dispose() {
      const rpc = get$1(rpcId);
      await rpc.dispose();
    },
    // @ts-ignore
    invoke(method, ...params) {
      const rpc = get$1(rpcId);
      // @ts-ignore
      return rpc.invoke(method, ...params);
    },
    // @ts-ignore
    invokeAndTransfer(method, ...params) {
      const rpc = get$1(rpcId);
      // @ts-ignore
      return rpc.invokeAndTransfer(method, ...params);
    },
    registerMockRpc(commandMap) {
      const mockRpc = createMockRpc({
        commandMap
      });
      set$5(rpcId, mockRpc);
      // @ts-ignore
      mockRpc[Symbol.dispose] = () => {
        remove(rpcId);
      };
      // @ts-ignore
      return mockRpc;
    },
    set(rpc) {
      set$5(rpcId, rpc);
    }
  };
};

const {
  dispose: dispose$3,
  invoke: invoke$3,
  invokeAndTransfer: invokeAndTransfer$1,
  registerMockRpc: registerMockRpc$1,
  set: set$4
} = create$1(EditorWorker$1);
const sendMessagePortToExtensionHostWorker$2 = async port => {
  const command = 'HandleMessagePort.handleMessagePort2';
  await invokeAndTransfer$1(
  // @ts-ignore
  'SendMessagePortToExtensionHostWorker.sendMessagePortToExtensionHostWorker', port, command, 0);
};
// TODO add tests for this
const activateByEvent$1 = async event => {
  // @ts-ignore
  await invoke$3('ActivateByEvent.activateByEvent', event);
};
const applyEdit = async (editorUid, changes) => {
  // @ts-ignore
  await invoke$3('Editor.applyEdit2', editorUid, changes);
};
const applyDocumentEdits = async (editorUid, changes) => {
  // @ts-ignore
  await invoke$3('Editor.applyDocumentEdits', editorUid, changes);
};
const applyWorkspaceEdit = async (editorUid, changes) => {
  // @ts-ignore
  await invoke$3('Editor.applyWorkspaceEdit', editorUid, changes);
};
const closeWidget = async (editorUid, widgetId, widgetName, focusId) => {
  // @ts-ignore
  await invoke$3('Editor.closeWidget2', editorUid, widgetId, widgetName, focusId);
};
const getWordAt = async (uid, rowIndex, columnIndex) => {
  // @ts-ignore
  const word = await invoke$3('Editor.getWordAt2', uid, rowIndex, columnIndex);
  return word;
};
const getLines = async editorUid => {
  const lines = await invoke$3('Editor.getLines2', editorUid);
  return lines;
};
const getPositionAtCursor$1 = async parentUid => {
  const position = await invoke$3('Editor.getPositionAtCursor', parentUid);
  return position;
};
const getOffsetAtCursor$1 = async editorId => {
  // @ts-ignore
  return await invoke$3('Editor.getOffsetAtCursor', editorId);
};
const getSelections = async editorUid => {
  const selections = await invoke$3('Editor.getSelections2', editorUid);
  return selections;
};
const getWordAtOffset2$1 = async editorUid => {
  return invoke$3('Editor.getWordAtOffset2', editorUid);
};
const closeFind2 = async editorUid => {
  return invoke$3('Editor.closeFind2', editorUid);
};
const getWordBefore$1 = async (editorUid, rowIndex, columnIndex) => {
  return invoke$3('Editor.getWordBefore2', editorUid, rowIndex, columnIndex);
};
const updateDebugInfo = async info => {
  await invoke$3('Editor.updateDebugInfo', info);
};
const getUri = async editorUid => {
  // @ts-ignore
  return invoke$3('Editor.getUri', editorUid);
};
const getLanguageId = async editorUid => {
  // @ts-ignore
  return invoke$3('Editor.getLanguageId', editorUid);
};
const getProblems = async () => {
  // @ts-ignore
  return invoke$3('Editor.getProblems');
};

const EditorWorker = {
  __proto__: null,
  activateByEvent: activateByEvent$1,
  applyDocumentEdits,
  applyEdit,
  applyWorkspaceEdit,
  closeFind2,
  closeWidget,
  dispose: dispose$3,
  getLanguageId,
  getLines,
  getOffsetAtCursor: getOffsetAtCursor$1,
  getPositionAtCursor: getPositionAtCursor$1,
  getProblems,
  getSelections,
  getUri,
  getWordAt,
  getWordAtOffset2: getWordAtOffset2$1,
  getWordBefore: getWordBefore$1,
  invoke: invoke$3,
  invokeAndTransfer: invokeAndTransfer$1,
  registerMockRpc: registerMockRpc$1,
  sendMessagePortToExtensionHostWorker: sendMessagePortToExtensionHostWorker$2,
  set: set$4,
  updateDebugInfo
};

const {
  dispose: dispose$2,
  invoke: invoke$2,
  invokeAndTransfer,
  registerMockRpc,
  set: set$3
} = create$1(ExtensionHostWorker);
const executeReferenceProvider = async (id, offset) => {
  // @ts-ignore
  return invoke$2('ExtensionHostReference.executeReferenceProvider', id, offset);
};
const executeFileReferenceProvider = async id => {
  // @ts-ignore
  return invoke$2('ExtensionHostReference.executeFileReferenceProvider', id);
};
const getRuntimeStatus = async extensionId => {
  // @ts-ignore
  return invoke$2('ExtensionHost.getRuntimeStatus', extensionId);
};
const getEnabledOutputProviderIds = async () => {
  const channels = await invoke$2('Output.getEnabledProviders');
  return channels;
};

const ExtensionHost = {
  __proto__: null,
  dispose: dispose$2,
  executeFileReferenceProvider,
  executeReferenceProvider,
  getEnabledOutputProviderIds,
  getRuntimeStatus,
  invoke: invoke$2,
  invokeAndTransfer,
  registerMockRpc,
  set: set$3
};

const {
  getWordAtOffset2,
  getWordBefore,
  invoke: invoke$1,
  sendMessagePortToExtensionHostWorker: sendMessagePortToExtensionHostWorker$1,
  set: set$2
} = EditorWorker;

const FocusEditorHovers = 9;
const FocusEditorRename = 11;

const Hover = 6;

const close = async state => {
  const {
    editorUid
  } = state;
  // @ts-ignore
  await invoke$1('Editor.closeWidget2', editorUid, Hover, 'Hovers', FocusEditorHovers);
  return state;
};

const {
  dispose: dispose$1,
  get,
  set: set$1,
  wrapCommand
} = create$2();

const create = (uid, x, y, width, height, editorUid, editorLanguageId) => {
  const state = {
    documentation: '',
    editorLanguageId,
    editorUid,
    fallbackDisplayStringLanguageId: 'typescript',
    focused: false,
    focusedIndex: -1,
    height: 0,
    hoverBorderLeft: 1,
    hoverBorderRight: 1,
    hoverDocumentationFontFamily: 'Fira Code',
    // TODO make it configurable
    hoverDocumentationFontSize: 15,
    hoverDocumentationLineHeight: '1.33333',
    hoverFullWidth: 400,
    hoverPaddingLeft: 8,
    hoverPaddingRight: 8,
    leadingWord: '',
    lineInfos: [],
    matchingDiagnostics: [],
    uid,
    version: 0,
    width: 0,
    x: 0,
    y: 0
  };
  set$1(uid, state, state);
};

const isEqual$4 = (oldState, newState) => {
  return oldState.x === newState.x && oldState.y === newState.y && oldState.width === newState.width && oldState.height === newState.height;
};

const isEqual$3 = (oldState, newState) => {
  return oldState.version === newState.version;
};

const isEqual$2 = (oldState, newState) => {
  return oldState.version === newState.version;
};

const isEqual$1 = (oldState, newState) => {
  return oldState.leadingWord === newState.leadingWord && oldState.x === newState.x && oldState.y === newState.y;
};

const isEqual = (oldState, newState) => {
  return oldState.version === newState.version;
};

const RenderItems = 1;
const RenderBounds = 8;
const RenderEventListeners = 11;
const RenderUid = 12;
const RenderContent = 13;
const RenderFocusContext = 14;

const modules = [isEqual$3, isEqual$1, isEqual$4, isEqual, isEqual$2];
const numbers = [RenderEventListeners, RenderItems, RenderBounds, RenderUid, RenderFocusContext];

const diff = (oldState, newState) => {
  const diffResult = [];
  for (let i = 0; i < modules.length; i++) {
    const fn = modules[i];
    if (!fn(oldState, newState)) {
      diffResult.push(numbers[i]);
    }
  }
  return diffResult;
};

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

const dispose = uid => {
  dispose$1(uid);
};

const commandIds = ['handleSliderPointerDown', 'handleSliderPointerMove', 'initialize'];

const getCommandIds = () => {
  return commandIds;
};

const Enter = 3;
const Escape = 8;
const Space = 9;
const End = 255;
const Home = 12;
const UpArrow = 14;
const DownArrow = 16;

const CtrlCmd = 1 << 11 >>> 0;

const getCommand = shortId => {
  return {
    args: ['Hovers', `Hovers.${shortId}`, 0, Hover],
    command: 'Editor.executeWidgetCommand'
  };
};
const getKeyBindings = () => {
  return [{
    key: DownArrow,
    ...getCommand('focusNext'),
    when: FocusEditorHovers
  }, {
    key: UpArrow,
    ...getCommand('focusPrevious'),
    when: FocusEditorHovers
  }, {
    key: Enter,
    ...getCommand('selectCurrent'),
    when: FocusEditorHovers
  }, {
    key: End,
    ...getCommand('focusLast'),
    when: FocusEditorHovers
  }, {
    key: Home,
    ...getCommand('focusFirst'),
    when: FocusEditorHovers
  }, {
    key: CtrlCmd | Space,
    ...getCommand('toggleDetails'),
    when: FocusEditorHovers
  }, {
    key: Escape,
    ...getCommand('close'),
    when: FocusEditorHovers
  }];
};

const handleSashPointerDown = (state, eventX, eventY) => {
  return state;
};

const handleSashPointerMove = (state, eventX, eventY) => {
  return state;
};

const handleSashPointerUp = (state, eventX, eventY) => {
  return state;
};

const sendMessagePortToExtensionHostWorker = async port => {
  // @ts-ignore
  await sendMessagePortToExtensionHostWorker$1(port);
};

const createExtensionHostRpc = async () => {
  try {
    const rpc = await TransferMessagePortRpcParent.create({
      commandMap: {},
      send: sendMessagePortToExtensionHostWorker
    });
    return rpc;
  } catch (error) {
    throw new VError(error, `Failed to create extension host rpc`);
  }
};

const {
  invoke,
  set
} = ExtensionHost;

const initialize = async () => {
  const rpc = await createExtensionHostRpc();
  set(rpc);
};

const measureTextBlockHeight = async (text, fontFamily, fontSize, lineHeight, width) => {
  // TODO ask editor worker or renderer process
  return 100;
};

const tokenizeCodeBlock = async (codeBlock, languageId, tokenizerPath) => {
  // TODO maybe use syntax highlighting worker for this or another worker
  return [];
};

const getHoverDetails = async (hover, error, hoverFullWidth, hoverPaddingLeft, hoverPaddingRight, hoverBorderLeft, hoverBorderRight, hoverDocumentationFontFamily, hoverDocumentationFontSize, hoverDocumentationLineHeight, fallbackDisplayStringLanguageId) => {
  if (error) {
    return {
      documentation: '',
      documentationHeight: 0,
      lineInfos: []
    };
  }
  const {
    documentation
  } = hover;
  const lineInfos = await tokenizeCodeBlock();
  const documentationHeight = await measureTextBlockHeight();
  return {
    documentation,
    documentationHeight,
    lineInfos
  };
};

//  @deprecated this doesn't work for variable width characters (unicode/emoji).
// Use position computation in renderer process instead

/*
 * @param {object} editor
 * @param {number} rowIndex
 * @param {number} columnIndex
 * @returns
 */
const x = (editor, rowIndex, columnIndex) => {
  const {
    columnWidth,
    x
  } = editor;
  const offsetX = columnIndex * columnWidth + x;
  return offsetX;
};
const y = (editor, rowIndex) => {
  const {
    rowHeight,
    y
  } = editor;
  const offsetY = (rowIndex + 1) * rowHeight + y;
  return offsetY;
};

const getHoverPositionXy = (editor, rowIndex, wordStart) => {
  const x$1 = x(editor, rowIndex, wordStart);
  const y$1 = editor.height - y(editor, rowIndex) + editor.y + 40;
  return {
    x: x$1,
    y: y$1
  };
};

const getOffsetAtCursor = editorUid => {
  // TODO ask editor worker
  return 0;
};

const getPositionAtCursor = async editorUid => {
  const position = await invoke$1('Editor.getPositionAtCursor', editorUid);
  return position;
};

const OnHover = 'onHover';

const HoverExecute = 'ExtensionHostHover.execute';

// TODO add tests for this
const activateByEvent = async event => {
  // @ts-ignore
  await invoke$1('ActivateByEvent.activateByEvent', event);
};

const execute = async ({
  args,
  editorLanguageId,
  editorUid,
  event,
  method,
  noProviderFoundMessage,
  noProviderFoundResult = undefined
}) => {
  const fullEvent = `${event}:${editorLanguageId}`;
  await activateByEvent(fullEvent);
  const result = await invoke(method, editorUid, ...args);
  return result;
};

const executeHoverProvider = async (editorUid, editorLanguageId, offset) => {
  number(editorUid);
  number(offset);
  return execute({
    args: [offset],
    editorUid,
    event: OnHover,
    method: HoverExecute,
    noProviderFoundMessage: 'No hover provider found'
  });
};

const getHover = async (editorUid, editorLanguageId, offset) => {
  try {
    number(editorUid);
    number(offset);
    // TODO invoke extension host worker directly
    const hover = await executeHoverProvider(editorUid, editorLanguageId, offset);
    return {
      error: undefined,
      hover
    };
  } catch (error) {
    return {
      error,
      hover: undefined
    };
  }
};

const getMatchingDiagnostics = (diagnostics, rowIndex, columnIndex) => {
  const matching = [];
  for (const diagnostic of diagnostics) {
    if (diagnostic.rowIndex === rowIndex) {
      matching.push(diagnostic);
    }
  }
  return matching;
};
const getEditorHoverInfo = async (editorUid, editorLanguageId, hoverFullWidth, hoverPaddingLeft, hoverPaddingRight, hoverBorderLeft, hoverBorderRight, hoverDocumentationFontFamily, hoverDocumentationFontSize, hoverDocumentationLineHeight, fallbackDisplayStringLanguageId) => {
  number(editorUid);
  const {
    columnIndex,
    rowIndex
  } = await getPositionAtCursor(editorUid);
  const offset = getOffsetAtCursor();

  // @ts-ignore
  const diagnostics = await invoke$1('Editor.getDiagnostics', editorUid);
  const wordPart = await getWordBefore(editorUid, rowIndex, columnIndex);
  const wordStart = columnIndex - wordPart.length;

  // TODO
  const editor = {};
  const {
    x,
    y
  } = getHoverPositionXy(editor, rowIndex, wordStart);
  // @ts-ignore
  const matchingDiagnostics = getMatchingDiagnostics(diagnostics, rowIndex);
  const {
    error,
    hover
  } = await getHover(editorUid, editorLanguageId, offset);
  if (!hover) {
    return {
      documentation: '',
      lineInfos: [],
      matchingDiagnostics,
      x,
      y
    };
  }
  const {
    documentation,
    lineInfos
  } = await getHoverDetails(hover, error);
  return {
    documentation,
    lineInfos,
    matchingDiagnostics,
    x,
    y
  };
};

const getWordAtOffset = getWordAtOffset2;

const loadContent = async state => {
  const {
    editorLanguageId,
    editorUid} = state;
  const wordAtOffset = await getWordAtOffset(editorUid);
  const {
    x,
    y
  } = await getPositionAtCursor(editorUid);
  const info = await getEditorHoverInfo(editorUid, editorLanguageId);
  if (!info) {
    return {
      ...state
    };
  }
  const {
    documentation,
    lineInfos,
    matchingDiagnostics
  } = info;
  return {
    ...state,
    documentation,
    leadingWord: wordAtOffset,
    lineInfos,
    matchingDiagnostics,
    width: 300,
    x,
    y
  };
};

const SetBounds = 'Viewlet.setBounds';
const SetDom2 = 'Viewlet.setDom2';
const SetUid = 'Viewlet.setUid';
const SetEventListeners = 'Viewlet.registerEventListeners';

const renderBounds = (oldState, newState) => {
  const {
    height,
    uid,
    width,
    x,
    y
  } = newState;
  return [SetBounds, uid, x, y, width, height];
};

const renderContent = (oldState, newState) => {
  const {
    uid
  } = newState;
  const dom = [];
  return [SetDom2, uid, dom];
};

const HandleSashPointerDown = 'handleSashPointerDown';
const HandleWheel = 'handleWheel';

const getEventListeners = () => {
  return [{
    name: HandleWheel,
    params: ['EditorHover.handleWheel', 'event.deltaMode', 'event.deltaY'],
    passive: true
  }];
};

const renderEventListeners = state => {
  const {
    uid
  } = state;
  const eventListeners = getEventListeners();
  return [SetEventListeners, uid, eventListeners];
};

const renderFocusContext = (oldState, newState) => {
  return [SetFocusContext, FocusEditorRename];
};

const HoverDisplayString = 'HoverDisplayString';
const HoverDocumentation = 'HoverDocumentation';
const HoverEditorRow = 'HoverEditorRow';
const HoverProblem = 'HoverProblem';
const HoverProblemDetail = 'HoverProblemDetail';
const HoverProblemMessage = 'HoverProblemMessage';

const Div = 4;
const Span = 8;

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

const getLineInfoVirtualDom = lineInfo => {
  const dom = [{
    childCount: lineInfo.length / 2,
    className: HoverEditorRow,
    type: Div
  }];
  for (let i = 0; i < lineInfo.length; i += 2) {
    const tokenText = lineInfo[i];
    const tokenClass = lineInfo[i + 1];
    dom.push({
      childCount: 1,
      className: tokenClass,
      type: Span
    }, text(tokenText));
  }
  return dom;
};
const getLineInfosVirtualDom = lineInfos => {
  const dom = lineInfos.flatMap(getLineInfoVirtualDom);
  return dom;
};

/* eslint-disable unicorn/no-immediate-mutation */

const hoverProblemMessage = {
  childCount: 1,
  className: HoverProblemMessage,
  type: Span
};
const hoverProblemDetail = {
  childCount: 1,
  className: HoverProblemDetail,
  type: Span
};
const getChildCount = (lineInfos, documentation, diagnostics) => {
  const diagnosticsCount = diagnostics && diagnostics.length > 0 ? 1 : 0;
  return lineInfos.length + documentation ? 1 : 0 + diagnosticsCount;
};
const getHoverVirtualDom = (lineInfos, documentation, diagnostics) => {
  const dom = [];
  dom.push({
    childCount: getChildCount(lineInfos, documentation, diagnostics) + 1,
    className: 'Viewlet EditorHover',
    type: Div
  });
  if (diagnostics && diagnostics.length > 0) {
    dom.push({
      childCount: diagnostics.length * 2,
      className: `${HoverDisplayString} ${HoverProblem}`,
      type: Div
    });
    for (const diagnostic of diagnostics) {
      dom.push(hoverProblemMessage, text(diagnostic.message), hoverProblemDetail, text(`${diagnostic.source} (${diagnostic.code})`));
    }
  }
  if (lineInfos.length > 0) {
    const lineInfosDom = getLineInfosVirtualDom(lineInfos);
    dom.push({
      childCount: lineInfos.length,
      className: HoverDisplayString,
      type: Div
    }, ...lineInfosDom);
  }
  if (documentation) {
    dom.push({
      childCount: 1,
      className: HoverDocumentation,
      type: Div
    }, text(documentation));
  }
  dom.push({
    childCount: 0,
    className: 'Sash SashVertical SashResize',
    onPointerDown: HandleSashPointerDown,
    type: Div
  });
  return dom;
};

const renderItems = (oldState, newState) => {
  const {
    documentation,
    lineInfos,
    matchingDiagnostics,
    uid
  } = newState;
  const dom = getHoverVirtualDom(lineInfos, documentation, matchingDiagnostics);
  return [/* method */'Viewlet.setDom2', uid, dom];
};

const renderUid = (oldState, newState) => {
  const {
    editorUid,
    uid
  } = newState;
  return [SetUid, uid, editorUid];
};

const getRenderer = diffType => {
  switch (diffType) {
    case RenderBounds:
      return renderBounds;
    case RenderContent:
      return renderContent;
    case RenderEventListeners:
      return renderEventListeners;
    case RenderFocusContext:
      return renderFocusContext;
    case RenderItems:
      return renderItems;
    case RenderUid:
      return renderUid;
    default:
      throw new Error('unknown renderer');
  }
};

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

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

const commandMap = {
  'Hover.close': wrapCommand(close),
  'Hover.create': create,
  'Hover.diff2': diff2,
  'Hover.dispose': dispose,
  'Hover.getCommandIds': getCommandIds,
  'Hover.getKeyBindings': getKeyBindings,
  'Hover.handleSashPointerDown': wrapCommand(handleSashPointerDown),
  'Hover.handleSashPointerMove': wrapCommand(handleSashPointerMove),
  'Hover.handleSashPointerUp': wrapCommand(handleSashPointerUp),
  'Hover.initialize': initialize,
  'Hover.loadContent': wrapCommand(loadContent),
  'Hover.render2': render2,
  'Hover.terminate': terminate
};

const listen = async () => {
  const rpc = await WebWorkerRpcClient.create({
    commandMap: commandMap
  });
  set$2(rpc);
};

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

main();
