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 {
    message,
    code: ERR_MODULE_NOT_FOUND
  };
};
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 {
    message: `Incompatible native node module: ${message}`,
    code: E_INCOMPATIBLE_NATIVE_MODULE
  };
};
const getModuleSyntaxError = () => {
  return {
    message: `ES Modules are not supported in electron`,
    code: E_MODULES_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 {
    message: actualMessage,
    code: '',
    stack: rest
  };
};
class IpcError extends VError {
  // @ts-ignore
  constructor(betterMessage, stdout = '', stderr = '') {
    if (stdout || stderr) {
      // @ts-ignore
      const {
        message,
        code,
        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 {
    resolve,
    promise
  } = 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({
      jsonrpc: '2.0',
      id: firstMessage.id,
      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 {
    resolve,
    promise
  } = 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({
        type,
        event
      });
    };
    addListener(eventEmitter, event, listener);
    listenerMap[event] = listener;
  }
  return promise;
};
const Message$1 = 3;
const create$5$1 = async ({
  messagePort,
  isMessagePortOpen
}) => {
  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 {
    type,
    event
  } = 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$1,
  signal: signal$1,
  wrap: wrap$5
};

const Two = '2.0';
const create$4 = (method, params) => {
  return {
    jsonrpc: Two,
    method,
    params
  };
};
const callbacks = Object.create(null);
const set$5 = (id, fn) => {
  callbacks[id] = fn;
};
const get$1 = id => {
  return callbacks[id];
};
const remove = id => {
  delete callbacks[id];
};
let id = 0;
const create$3 = () => {
  return ++id;
};
const registerPromise = () => {
  const id = create$3();
  const {
    resolve,
    promise
  } = Promise.withResolvers();
  set$5(id, resolve);
  return {
    id,
    promise
  };
};
const create$2 = (method, params) => {
  const {
    id,
    promise
  } = registerPromise();
  const message = {
    jsonrpc: Two,
    method,
    params,
    id
  };
  return {
    message,
    promise
  };
};
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$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,
      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$1 = (id, error) => {
  return {
    jsonrpc: Two,
    id,
    error
  };
};
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$5 = (message, result) => {
  return {
    jsonrpc: Two,
    id: message.id,
    result: result ?? null
  };
};
const getSuccessResponse = (message, result) => {
  const resultProperty = result ?? null;
  return create$5(message, resultProperty);
};
const getErrorResponseSimple = (id, error) => {
  return {
    jsonrpc: Two,
    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');
};
const invokeHelper = async (ipc, method, params, useSendAndTransfer) => {
  const {
    message,
    promise
  } = create$2(method, params);
  if (useSendAndTransfer && ipc.sendAndTransfer) {
    ipc.sendAndTransfer(message);
  } else {
    ipc.send(message);
  }
  const responseMessage = await promise;
  return unwrapJsonRpcResult(responseMessage);
};
const send = (transport, method, ...params) => {
  const message = create$4(method, params);
  transport.send(message);
};
const invoke$4 = (ipc, method, ...params) => {
  return invokeHelper(ipc, method, params, false);
};
const invokeAndTransfer$3 = (ipc, method, ...params) => {
  return invokeHelper(ipc, method, params, true);
};

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 createRpc = ipc => {
  const rpc = {
    // @ts-ignore
    ipc,
    /**
     * @deprecated
     */
    send(method, ...params) {
      send(ipc, method, ...params);
    },
    invoke(method, ...params) {
      return invoke$4(ipc, method, ...params);
    },
    invokeAndTransfer(method, ...params) {
      return invokeAndTransfer$3(ipc, method, ...params);
    },
    async dispose() {
      await ipc?.dispose();
    }
  };
  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, 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$e = async ({
  commandMap,
  messagePort,
  isMessagePortOpen
}) => {
  // TODO create a commandMap per rpc instance
  register(commandMap);
  const rawIpc = await IpcParentWithMessagePort$1.create({
    messagePort,
    isMessagePortOpen
  });
  const ipc = IpcParentWithMessagePort$1.wrap(rawIpc);
  handleIpc(ipc);
  const rpc = createRpc(ipc);
  return rpc;
};
const MessagePortRpcParent = {
  __proto__: null,
  create: create$e
};
const create$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
};
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 = {
    invoke,
    invokeAndTransfer: invoke,
    invocations
  };
  return mockRpc;
};

const DebugWorker = 55;
const EmbedsProcess$1 = 207;
const RendererWorker$1 = 1;

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

const create = rpcId => {
  return {
    // @ts-ignore
    invoke(method, ...params) {
      const rpc = get(rpcId);
      // @ts-ignore
      return rpc.invoke(method, ...params);
    },
    // @ts-ignore
    invokeAndTransfer(method, ...params) {
      const rpc = get(rpcId);
      // @ts-ignore
      return rpc.invokeAndTransfer(method, ...params);
    },
    set(rpc) {
      set$4(rpcId, rpc);
    },
    async dispose() {
      const rpc = get(rpcId);
      await rpc.dispose();
    }
  };
};

const {
  invoke: invoke$3,
  invokeAndTransfer: invokeAndTransfer$2,
  set: set$3,
  dispose: dispose$1
} = create(EmbedsProcess$1);

const EmbedsProcess = {
  __proto__: null,
  dispose: dispose$1,
  invoke: invoke$3,
  invokeAndTransfer: invokeAndTransfer$2,
  set: set$3
};

const {
  invoke: invoke$2,
  invokeAndTransfer: invokeAndTransfer$1,
  set: set$2,
  dispose
} = create(RendererWorker$1);
const searchFileHtml = async uri => {
  return invoke$2('ExtensionHost.searchFileWithHtml', uri);
};
const getFilePathElectron = async file => {
  return invoke$2('FileSystemHandle.getFilePathElectron', file);
};
const showContextMenu = async (x, y, id, ...args) => {
  return invoke$2('ContextMenu.show', x, y, id, ...args);
};
const getElectronVersion = async () => {
  return invoke$2('Process.getElectronVersion');
};
const applyBulkReplacement = async bulkEdits => {
  await invoke$2('BulkReplacement.applyBulkReplacement', bulkEdits);
};
const setColorTheme = async id => {
  // @ts-ignore
  return invoke$2(/* ColorTheme.setColorTheme */'ColorTheme.setColorTheme', /* colorThemeId */id);
};
const getNodeVersion = async () => {
  return invoke$2('Process.getNodeVersion');
};
const getChromeVersion = async () => {
  return invoke$2('Process.getChromeVersion');
};
const getV8Version = async () => {
  return invoke$2('Process.getV8Version');
};
const getFileHandles = async fileIds => {
  const files = await invoke$2('FileSystemHandle.getFileHandles', fileIds);
  return files;
};
const setWorkspacePath = async path => {
  await invoke$2('Workspace.setPath', path);
};
const registerWebViewInterceptor = async (id, port) => {
  await invokeAndTransfer$1('WebView.registerInterceptor', id, port);
};
const unregisterWebViewInterceptor = async id => {
  await invoke$2('WebView.unregisterInterceptor', id);
};
const sendMessagePortToEditorWorker = async (port, rpcId) => {
  const command = 'HandleMessagePort.handleMessagePort';
  // @ts-ignore
  await invokeAndTransfer$1('SendMessagePortToExtensionHostWorker.sendMessagePortToEditorWorker', port, command, rpcId);
};
const sendMessagePortToErrorWorker = async (port, rpcId) => {
  const command = 'Errors.handleMessagePort';
  // @ts-ignore
  await invokeAndTransfer$1('SendMessagePortToExtensionHostWorker.sendMessagePortToErrorWorker', port, command, rpcId);
};
const sendMessagePortToMarkdownWorker = async (port, rpcId) => {
  const command = 'Markdown.handleMessagePort';
  // @ts-ignore
  await invokeAndTransfer$1('SendMessagePortToExtensionHostWorker.sendMessagePortToMarkdownWorker', port, command, rpcId);
};
const sendMessagePortToIconThemeWorker = async (port, rpcId) => {
  const command = 'IconTheme.handleMessagePort';
  // @ts-ignore
  await invokeAndTransfer$1('SendMessagePortToExtensionHostWorker.sendMessagePortToIconThemeWorker', port, command, rpcId);
};
const sendMessagePortToFileSystemWorker = async (port, rpcId) => {
  const command = 'FileSystem.handleMessagePort';
  // @ts-ignore
  await invokeAndTransfer$1('SendMessagePortToExtensionHostWorker.sendMessagePortToFileSystemWorker', port, command, rpcId);
};
const readFile = async uri => {
  return invoke$2('FileSystem.readFile', uri);
};
const getWebViewSecret = async key => {
  // @ts-ignore
  return invoke$2('WebView.getSecret', key);
};
const setWebViewPort = async (uid, port, origin, portType) => {
  return invokeAndTransfer$1('WebView.setPort', uid, port, origin, portType);
};
const setFocus = key => {
  return invoke$2('Focus.setFocus', key);
};
const getFileIcon = async options => {
  return invoke$2('IconTheme.getFileIcon', options);
};
const getColorThemeNames = async () => {
  return invoke$2('ColorTheme.getColorThemeNames');
};
const disableExtension = async id => {
  // @ts-ignore
  return invoke$2('ExtensionManagement.disable', id);
};
const enableExtension = async id => {
  // @ts-ignore
  return invoke$2('ExtensionManagement.enable', id);
};
const handleDebugChange = async params => {
  // @ts-ignore
  return invoke$2('Run And Debug.handleChange', params);
};
const getFolderIcon = async options => {
  return invoke$2('IconTheme.getFolderIcon', options);
};
const closeWidget = async widgetId => {
  return invoke$2('Viewlet.closeWidget', widgetId);
};
const sendMessagePortToExtensionHostWorker = async (port, rpcId = 0) => {
  const command = 'HandleMessagePort.handleMessagePort2';
  await invokeAndTransfer$1('SendMessagePortToExtensionHostWorker.sendMessagePortToExtensionHostWorker', port, command, rpcId);
};
const sendMessagePortToSearchProcess = async port => {
  await invokeAndTransfer$1('SendMessagePortToElectron.sendMessagePortToElectron', port, 'HandleMessagePortForSearchProcess.handleMessagePortForSearchProcess');
};
const confirm = async (message, options) => {
  // @ts-ignore
  const result = await invoke$2('ConfirmPrompt.prompt', message, options);
  return result;
};
const getRecentlyOpened = async () => {
  return invoke$2(/* RecentlyOpened.getRecentlyOpened */'RecentlyOpened.getRecentlyOpened');
};
const getKeyBindings = async () => {
  return invoke$2('KeyBindingsInitial.getKeyBindings');
};
const writeClipBoardText = async text => {
  await invoke$2('ClipBoard.writeText', /* text */text);
};
const writeClipBoardImage = async blob => {
  // @ts-ignore
  await invoke$2('ClipBoard.writeImage', /* text */blob);
};
const searchFileMemory = async uri => {
  // @ts-ignore
  return invoke$2('ExtensionHost.searchFileWithMemory', uri);
};
const searchFileFetch = async uri => {
  return invoke$2('ExtensionHost.searchFileWithFetch', uri);
};
const showMessageBox = async options => {
  return invoke$2('ElectronDialog.showMessageBox', options);
};
const handleDebugResumed = async params => {
  await invoke$2('Run And Debug.handleResumed', params);
};
const openWidget = async name => {
  await invoke$2('Viewlet.openWidget', name);
};
const getIcons = async requests => {
  const icons = await invoke$2('IconTheme.getIcons', requests);
  return icons;
};
const activateByEvent = event => {
  return invoke$2('ExtensionHostManagement.activateByEvent', event);
};
const setAdditionalFocus = focusKey => {
  // @ts-ignore
  return invoke$2('Focus.setAdditionalFocus', focusKey);
};
const getActiveEditorId = () => {
  // @ts-ignore
  return invoke$2('GetActiveEditor.getActiveEditorId');
};
const getWorkspacePath = () => {
  return invoke$2('Workspace.getPath');
};
const sendMessagePortToRendererProcess = async port => {
  const command = 'HandleMessagePort.handleMessagePort';
  // @ts-ignore
  await invokeAndTransfer$1('SendMessagePortToExtensionHostWorker.sendMessagePortToRendererProcess', port, command, DebugWorker);
};
const getPreference = async key => {
  return await invoke$2('Preferences.get', key);
};
const getAllExtensions = async () => {
  return invoke$2('ExtensionManagement.getAllExtensions');
};
const rerenderEditor = async key => {
  // @ts-ignore
  return invoke$2('Editor.rerender', key);
};
const handleDebugPaused = async params => {
  await invoke$2('Run And Debug.handlePaused', params);
};
const openUri = async (uri, focus, options) => {
  await invoke$2('Main.openUri', uri, focus, options);
};
const sendMessagePortToSyntaxHighlightingWorker = async port => {
  await invokeAndTransfer$1(
  // @ts-ignore
  'SendMessagePortToSyntaxHighlightingWorker.sendMessagePortToSyntaxHighlightingWorker', port, 'HandleMessagePort.handleMessagePort2');
};
const handleDebugScriptParsed = async script => {
  await invoke$2('Run And Debug.handleScriptParsed', script);
};
const getWindowId = async () => {
  return invoke$2('GetWindowId.getWindowId');
};
const getBlob = async uri => {
  // @ts-ignore
  return invoke$2('FileSystem.getBlob', uri);
};
const getExtensionCommands = async () => {
  return invoke$2('ExtensionHost.getCommands');
};
const showErrorDialog = async errorInfo => {
  // @ts-ignore
  await invoke$2('ErrorHandling.showErrorDialog', errorInfo);
};
const getFolderSize = async uri => {
  // @ts-ignore
  return await invoke$2('FileSystem.getFolderSize', uri);
};
const getExtension = async id => {
  // @ts-ignore
  return invoke$2('ExtensionManagement.getExtension', id);
};
const getMarkdownDom = async html => {
  // @ts-ignore
  return invoke$2('Markdown.getVirtualDom', html);
};
const renderMarkdown = async (markdown, options) => {
  // @ts-ignore
  return invoke$2('Markdown.renderMarkdown', markdown, options);
};
const openNativeFolder = async uri => {
  // @ts-ignore
  await invoke$2('OpenNativeFolder.openNativeFolder', uri);
};
const uninstallExtension = async id => {
  return invoke$2('ExtensionManagement.uninstall', id);
};
const installExtension = async id => {
  // @ts-ignore
  return invoke$2('ExtensionManagement.install', id);
};
const openExtensionSearch = async () => {
  // @ts-ignore
  return invoke$2('SideBar.openViewlet', 'Extensions');
};
const setExtensionsSearchValue = async searchValue => {
  // @ts-ignore
  return invoke$2('Extensions.handleInput', searchValue);
};
const openExternal = async uri => {
  // @ts-ignore
  await invoke$2('Open.openExternal', uri);
};
const openUrl = async uri => {
  // @ts-ignore
  await invoke$2('Open.openUrl', uri);
};
const getAllPreferences = async () => {
  // @ts-ignore
  return invoke$2('Preferences.getAll');
};
const showSaveFilePicker = async () => {
  // @ts-ignore
  return invoke$2('FilePicker.showSaveFilePicker');
};
const getLogsDir = async () => {
  // @ts-ignore
  return invoke$2('PlatformPaths.getLogsDir');
};
const registerMockRpc = commandMap => {
  const mockRpc = createMockRpc({
    commandMap
  });
  set$2(mockRpc);
  return mockRpc;
};

const RendererWorker = {
  __proto__: null,
  activateByEvent,
  applyBulkReplacement,
  closeWidget,
  confirm,
  disableExtension,
  dispose,
  enableExtension,
  getActiveEditorId,
  getAllExtensions,
  getAllPreferences,
  getBlob,
  getChromeVersion,
  getColorThemeNames,
  getElectronVersion,
  getExtension,
  getExtensionCommands,
  getFileHandles,
  getFileIcon,
  getFilePathElectron,
  getFolderIcon,
  getFolderSize,
  getIcons,
  getKeyBindings,
  getLogsDir,
  getMarkdownDom,
  getNodeVersion,
  getPreference,
  getRecentlyOpened,
  getV8Version,
  getWebViewSecret,
  getWindowId,
  getWorkspacePath,
  handleDebugChange,
  handleDebugPaused,
  handleDebugResumed,
  handleDebugScriptParsed,
  installExtension,
  invoke: invoke$2,
  invokeAndTransfer: invokeAndTransfer$1,
  openExtensionSearch,
  openExternal,
  openNativeFolder,
  openUri,
  openUrl,
  openWidget,
  readFile,
  registerMockRpc,
  registerWebViewInterceptor,
  renderMarkdown,
  rerenderEditor,
  searchFileFetch,
  searchFileHtml,
  searchFileMemory,
  sendMessagePortToEditorWorker,
  sendMessagePortToErrorWorker,
  sendMessagePortToExtensionHostWorker,
  sendMessagePortToFileSystemWorker,
  sendMessagePortToIconThemeWorker,
  sendMessagePortToMarkdownWorker,
  sendMessagePortToRendererProcess,
  sendMessagePortToSearchProcess,
  sendMessagePortToSyntaxHighlightingWorker,
  set: set$2,
  setAdditionalFocus,
  setColorTheme,
  setExtensionsSearchValue,
  setFocus,
  setWebViewPort,
  setWorkspacePath,
  showContextMenu,
  showErrorDialog,
  showMessageBox,
  showSaveFilePicker,
  uninstallExtension,
  unregisterWebViewInterceptor,
  writeClipBoardImage,
  writeClipBoardText
};

const {
  invoke: invoke$1,
  set: set$1
} = EmbedsProcess;

const ERR_ABORTED = 'ERR_ABORTED';
const ERR_FAILED = 'ERR_FAILED';

const {
  invoke,
  invokeAndTransfer,
  set
} = RendererWorker;

const createWebContentsView = async (restoreId, fallThroughKeyBindings) => {
  // @ts-ignore
  const id = await invoke$1('ElectronWebContentsView.createWebContentsView', restoreId, fallThroughKeyBindings);
  return id;
};
const disposeWebContentsView = id => {
  return invoke$1('ElectronWebContentsView.disposeWebContentsView', id);
};
const resizeWebContentsView = (id, x, y, width, height) => {
  return invoke$1('ElectronWebContentsView.resizeBrowserView', id, x, y, width, height);
};
const setIframeSrcFallback = async (id, error) => {
  const {
    code,
    message
  } = error;
  await invoke$1('ElectronWebContentsView.setIframeSrcFallback', id, code, message);
};
const setIframeSrc = async (id, iframeSrc) => {
  try {
    await invoke$1('ElectronWebContentsView.setIframeSrc', id, iframeSrc);
  } catch (error) {
    console.log({
      error
    });
    // TODO send error back to embeds worker,
    // embeds worker decides how to handle error

    // @ts-ignore
    if (error && error.code === ERR_ABORTED) {
      console.info(`[embeds worker] navigation to ${iframeSrc} aborted`);
      return;
    }

    // @ts-ignore
    if (error && error.code === ERR_FAILED) {
      console.info(`[embeds worker] navigation to ${iframeSrc} canceled`);
      // ElectronWebContentsViewState.removeCanceled(webContents.id)
      return;
    }
    try {
      await setIframeSrcFallback(id, error);
    } catch (error) {
      console.warn(`Failed to set iframe src`, error);
    }
  }
};
const focus = id => {
  return invoke$1('ElectronWebContentsView.focus', id);
};
const openDevtools = id => {
  return invoke$1('ElectronWebContentsView.openDevtools', id);
};
const reload = id => {
  return invoke$1('ElectronWebContentsView.reload', id);
};
const show = id => {
  return invoke$1('ElectronWebContentsView.show', id);
};
const hide = id => {
  return invoke$1('ElectronWebContentsView.hide', id);
};
const forward = id => {
  return invoke$1('ElectronWebContentsView.forward', id);
};
const backward = id => {
  return invoke$1('ElectronWebContentsView.backward', id);
};
const getDomTree = id => {
  return invoke$1('ElectronWebContentsView.getDomTree', id);
};
const insertCss = (id, css) => {
  return invoke$1('ElectronWebContentsView.insertCss', id, css);
};
const insertJavaScript = (id, code) => {
  return invoke$1('ElectronWebContentsView.insertJavaScript', id, code);
};
const cancelNavigation = id => {
  return invoke$1('ElectronWebContentsView.cancelNavigation', id);
};
const inspectElement = (id, x, y) => {
  return invoke$1('ElectronWebContentsView.inspectElement', id, x, y);
};
const copyImageAt = (id, x, y) => {
  return invoke$1('ElectronWebContentsView.copyImageAt', id, x, y);
};
const setFallthroughKeyBindings = async (id, fallthroughKeybindings) => {
  // TODO
  // return EmbedsProcess.invoke('ElectronWebContentsView.setFallthroughKeyBindings', id, fallthroughKeybindings)
};
const getStats = (id, fallthroughKeybindings) => {
  return invoke$1('ElectronWebContentsView.getStats', id, fallthroughKeybindings);
};
const forwardEvent = key => (id, ...args) => {
  return invoke(key, ...args);
};
const handleDidNavigate = forwardEvent('ElectronBrowserView.handleDidNavigate');
const handleTitleUpdated = forwardEvent('ElectronBrowserView.handleTitleUpdated');
const handleWillNavigate = forwardEvent('ElectronBrowserView.handleWillNavigate');
const handleContextMenu = forwardEvent('ElectronBrowserView.handleContextMenu');

const exit = () => {
  globalThis.close();
};

const getPortTuple = () => {
  const {
    port1,
    port2
  } = new MessageChannel();
  return {
    port1,
    port2
  };
};

const EmbedsWorker = 208;

const sendMessagePortToEmbedsProcess = async port => {
  const outerCommand = 'HandleMessagePortForEmbedsProcess.handleMessagePortForEmbedsProcess';
  // TODO
  // @ts-ignore
  await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToSharedProcess', port, outerCommand, EmbedsWorker);
};

const createEmbedsProcessRpc = async () => {
  try {
    const {
      port1,
      port2
    } = getPortTuple();
    await sendMessagePortToEmbedsProcess(port2);
    port1.start();
    const rpc = await MessagePortRpcParent.create({
      commandMap: {},
      isMessagePortOpen: true,
      messagePort: port1
    });
    // TODO createMessageportRpcParent should call port start
    return rpc;
  } catch (error) {
    throw new VError(error, `Failed to create embeds process rpc`);
  }
};

const initialize = async () => {
  const rpc = await createEmbedsProcessRpc();
  set$1(rpc);
};

const commandMap = {
  'ElectronWebContentsView.backward': backward,
  'ElectronWebContentsView.cancelNavigation': cancelNavigation,
  'ElectronWebContentsView.copyImageAt': copyImageAt,
  'ElectronWebContentsView.createWebContentsView': createWebContentsView,
  'ElectronWebContentsView.disposeWebContentsView': disposeWebContentsView,
  'ElectronWebContentsView.focus': focus,
  'ElectronWebContentsView.forward': forward,
  'ElectronWebContentsView.getDomTree': getDomTree,
  'ElectronWebContentsView.getStats': getStats,
  'ElectronWebContentsView.handleContextMenu': handleContextMenu,
  'ElectronWebContentsView.handleDidNavigate': handleDidNavigate,
  'ElectronWebContentsView.handleTitleUpdated': handleTitleUpdated,
  'ElectronWebContentsView.handleWillNavigate': handleWillNavigate,
  'ElectronWebContentsView.hide': hide,
  'ElectronWebContentsView.insertCss': insertCss,
  'ElectronWebContentsView.insertJavaScript': insertJavaScript,
  'ElectronWebContentsView.inspectElement': inspectElement,
  'ElectronWebContentsView.openDevtools': openDevtools,
  'ElectronWebContentsView.reload': reload,
  'ElectronWebContentsView.resizeWebContentsView': resizeWebContentsView,
  'ElectronWebContentsView.setFallthroughKeyBindings': setFallthroughKeyBindings,
  'ElectronWebContentsView.setIframeSrc': setIframeSrc,
  'ElectronWebContentsView.show': show,
  'Exit.exit': exit,
  'Initialize.initialize': initialize
};

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

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

main();
