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

const None$2 = 0;
const Collapsed = 1;
const Expanded = 2;

const getRootProcess = (processes, rootPid) => {
  if (rootPid) {
    return processes.find(process => process.pid === rootPid);
  }
  return processes[0];
};
const hasChildren = (processes, pid) => {
  return processes.some(process => process.ppid === pid);
};
const getChildren = (processes, collapsedPids, process, depth) => {
  const children = processes.filter(otherProcess => otherProcess.ppid === process.pid);
  if (children.length === 0) {
    return [];
  }
  if (collapsedPids.includes(process.pid)) {
    return [];
  }
  return children.flatMap(child => withChildren(processes, collapsedPids, child, depth + 1));
};
const withChildren = (processes, collapsedPids, process, depth) => {
  const processHasChildren = hasChildren(processes, process.pid);
  let flags = None$2;
  if (processHasChildren && collapsedPids.includes(process.pid)) {
    flags = Collapsed;
  } else if (processHasChildren) {
    flags = Expanded;
  }
  const visibleProcess = {
    ...process,
    depth,
    flags
  };
  return [visibleProcess, ...getChildren(processes, collapsedPids, process, depth)];
};
const getVisibleProcesses = (processes, collapsedPids, rootPid) => {
  const rootProcess = getRootProcess(processes, rootPid);
  if (!rootProcess) {
    return [];
  }
  return withChildren(processes, collapsedPids, rootProcess, 1);
};

const collapseAll = state => {
  const parentPids = new Set();
  for (const process of state.processes) {
    parentPids.add(process.ppid);
  }
  const collapsedPids = state.processes.filter(process => parentPids.has(process.pid)).map(process => process.pid);
  const visibleProcesses = getVisibleProcesses(state.processes, collapsedPids, state.rootPid);
  return {
    ...state,
    collapsedPids,
    focusedIndex: visibleProcesses.length === 0 ? -1 : 0,
    visibleProcesses
  };
};

const {
  dispose: dispose$4,
  get: get$2,
  getCommandIds,
  getKeys: getKeys$1,
  registerCommands,
  set: set$6,
  wrapCommand,
  wrapGetter,
  wrapLoadContent
} = create$e();

const processExplorerUpdateInterval = 1000;

const getIncludeFrontendMemoryUsage = args => {
  if (!args || typeof args !== 'object') {
    return false;
  }
  const createArgs = args;
  return createArgs.includeFrontendMemoryUsage === true;
};
const getUpdateInterval = args => {
  if (!args || typeof args !== 'object') {
    return processExplorerUpdateInterval;
  }
  const createArgs = args;
  if (typeof createArgs.updateInterval !== 'number') {
    return processExplorerUpdateInterval;
  }
  return createArgs.updateInterval;
};
const create$d = (id, _uri, x, y, width, height, args, parentUid, platform = 0, assetDir = '') => {
  const state = {
    assetDir,
    collapsedPids: [],
    errorCodeFrame: '',
    errorMessage: '',
    errorStack: '',
    focus: 0,
    focused: false,
    focusedIndex: -1,
    height,
    includeFrontendMemoryUsage: getIncludeFrontendMemoryUsage(args),
    initial: true,
    parentUid,
    platform,
    processes: [],
    rootPid: -1,
    uid: id,
    updateInterval: getUpdateInterval(args),
    visibleProcesses: [],
    width,
    x,
    y
  };
  set$6(state.uid, state, state);
  return state;
};

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$1 = 4;
const Boolean$1 = 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$1;
    case 'object':
      if (value === null) {
        return Null;
      }
      if (Array.isArray(value)) {
        return Array$1;
      }
      return Object$1;
    case 'boolean':
      return Boolean$1;
    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 Error$3 = 1;
const Open = 2;
const Close = 3;
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$1 = 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$1,
  signal: signal$1,
  wrap: wrap$5
};
const stringifyCompact = value => {
  return JSON.stringify(value);
};
const parse = content => {
  if (content === 'undefined') {
    return null;
  }
  try {
    return JSON.parse(content);
  } catch (error) {
    throw new VError(error, 'failed to parse json');
  }
};
const waitForWebSocketToBeOpen = webSocket => {
  return getFirstEvent(webSocket, {
    close: Close,
    error: Error$3,
    open: Open
  });
};
const create$c = async ({
  webSocket
}) => {
  const firstWebSocketEvent = await waitForWebSocketToBeOpen(webSocket);
  if (firstWebSocketEvent.type === Error$3) {
    throw new IpcError(`WebSocket connection error`);
  }
  if (firstWebSocketEvent.type === Close) {
    throw new IpcError('Websocket connection was immediately closed');
  }
  return webSocket;
};
class IpcParentWithWebSocket extends Ipc {
  getData(event) {
    return parse(event.data);
  }
  send(message) {
    this._rawIpc.send(stringifyCompact(message));
  }
  sendAndTransfer(message) {
    throw new Error('sendAndTransfer not supported');
  }
  dispose() {
    this._rawIpc.close();
  }
  onClose(callback) {
    this._rawIpc.addEventListener('close', callback);
  }
  onMessage(callback) {
    this._rawIpc.addEventListener('message', callback);
  }
}
const wrap = webSocket => {
  return new IpcParentWithWebSocket(webSocket);
};
const IpcParentWithWebSocket$1 = {
  __proto__: null,
  create: create$c,
  wrap
};

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

const Two$1 = '2.0';
const callbacks = Object.create(null);
const get$1 = id => {
  return callbacks[id];
};
const remove$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 ReferenceError$1:
        return ReferenceError;
      case SyntaxError$1:
        return SyntaxError;
      case TypeError$1:
        return TypeError;
      default:
        return Error;
    }
  }
  if (message.startsWith('TypeError: ')) {
    return TypeError;
  }
  if (message.startsWith('SyntaxError: ')) {
    return SyntaxError;
  }
  if (message.startsWith('ReferenceError: ')) {
    return ReferenceError;
  }
  return Error;
};
const constructError = (message, type, name) => {
  const ErrorConstructor = getErrorConstructor(message, type);
  if (ErrorConstructor === DOMException && name) {
    return new ErrorConstructor(message, name);
  }
  if (ErrorConstructor === Error) {
    const error = new Error(message);
    if (name && name !== 'VError') {
      error.name = name;
    }
    return error;
  }
  return new ErrorConstructor(message);
};
const joinLines = lines => {
  return lines.join(NewLine);
};
const splitLines = lines => {
  return lines.split(NewLine);
};
const getCurrentStack = () => {
  const stackLinesToSkip = 3;
  const currentStack = joinLines(splitLines(new Error().stack || '').slice(stackLinesToSkip));
  return currentStack;
};
const getNewLineIndex = (string, startIndex) => {
  {
    return string.indexOf(NewLine);
  }
};
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 restoreExistingError = (error, currentStack) => {
  if (typeof error.stack === 'string') {
    error.stack = error.stack + NewLine + currentStack;
  }
  return error;
};
const restoreMethodNotFoundError = (error, currentStack) => {
  const restoredError = new JsonRpcError(error.message);
  const parentStack = getParentStack(error);
  restoredError.stack = parentStack + NewLine + currentStack;
  return restoredError;
};
const restoreStackFromData = (restoredError, error, currentStack) => {
  if (error.data.stack && error.data.type && error.message) {
    restoredError.stack = error.data.type + ': ' + error.message + NewLine + error.data.stack + NewLine + currentStack;
    return;
  }
  if (error.data.stack) {
    restoredError.stack = error.data.stack;
  }
};
const applyDataProperties = (restoredError, error) => {
  if (!error.data) {
    return;
  }
  restoreStackFromData(restoredError, error, getCurrentStack());
  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;
  }
};
const applyDirectProperties = (restoredError, error) => {
  if (error.stack) {
    const lowerStack = restoredError.stack || '';
    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;
  }
};
const restoreMessageError = (error, _currentStack) => {
  const restoredError = constructError(error.message, error.type, error.name);
  if (error.data) {
    applyDataProperties(restoredError, error);
  } else {
    applyDirectProperties(restoredError, error);
  }
  return restoredError;
};
const restoreJsonRpcError = error => {
  const currentStack = getCurrentStack();
  if (error && error instanceof Error) {
    return restoreExistingError(error, currentStack);
  }
  if (error && error.code && error.code === MethodNotFound) {
    return restoreMethodNotFoundError(error, currentStack);
  }
  if (error && error.message) {
    return restoreMessageError(error);
  }
  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$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,
      data: error.stack,
      message: error.message
    };
  }
  return {
    code: Custom,
    data: {
      code: prettyError.code,
      codeFrame: prettyError.codeFrame,
      name: prettyError.name,
      stack: getStack(prettyError),
      type: getErrorType(prettyError)
    },
    message: prettyError.message
  };
};
const create$1$1 = (id, error) => {
  return {
    error,
    id,
    jsonrpc: Two$1
  };
};
const getErrorResponse = (id, error, preparePrettyError, logError) => {
  const prettyError = preparePrettyError(error);
  logError(error, prettyError);
  const errorProperty = getErrorProperty(error, prettyError);
  return create$1$1(id, errorProperty);
};
const create$b = (message, result) => {
  return {
    id: message.id,
    jsonrpc: Two$1,
    result: result ?? null
  };
};
const getSuccessResponse = (message, result) => {
  const resultProperty = result ?? null;
  return create$b(message, resultProperty);
};
const getErrorResponseSimple = (id, error) => {
  return {
    error: {
      code: Custom,
      data: error,
      // @ts-ignore
      message: error.message
    },
    id,
    jsonrpc: Two$1
  };
};
const getResponse = async (message, ipc, execute, preparePrettyError, logError, requiresSocket) => {
  try {
    const result = requiresSocket(message.method) ? await execute(message.method, ipc, ...message.params) : await execute(message.method, ...message.params);
    return getSuccessResponse(message, result);
  } catch (error) {
    if (ipc.canUseSimpleErrorResponse) {
      return getErrorResponseSimple(message.id, error);
    }
    return getErrorResponse(message.id, error, preparePrettyError, logError);
  }
};
const defaultPreparePrettyError = error => {
  return error;
};
const defaultLogError = () => {
  // ignore
};
const defaultRequiresSocket = () => {
  return false;
};
const defaultResolve = resolve;

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

const Two = '2.0';

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

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

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

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

const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
  const {
    id,
    promise
  } = registerPromise(callbacks);
  const message = create$9(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$a(method, params);
      ipc.send(message);
    }
  };
  return rpc;
};

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

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

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

const create$7 = 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$6 = async ({
  commandMap,
  isMessagePortOpen,
  send
}) => {
  const {
    port1,
    port2
  } = new MessageChannel();
  await send(port1);
  return create$7({
    commandMap,
    isMessagePortOpen,
    messagePort: port2
  });
};

const createSharedLazyRpc = factory => {
  let rpcPromise;
  const getOrCreate = () => {
    if (!rpcPromise) {
      rpcPromise = factory();
    }
    return rpcPromise;
  };
  return {
    async dispose() {
      const rpc = await getOrCreate();
      await rpc.dispose();
    },
    async invoke(method, ...params) {
      const rpc = await getOrCreate();
      return rpc.invoke(method, ...params);
    },
    async invokeAndTransfer(method, ...params) {
      const rpc = await getOrCreate();
      return rpc.invokeAndTransfer(method, ...params);
    },
    async send(method, ...params) {
      const rpc = await getOrCreate();
      rpc.send(method, ...params);
    }
  };
};

const create$5 = async ({
  commandMap,
  isMessagePortOpen,
  send
}) => {
  return createSharedLazyRpc(() => {
    return create$6({
      commandMap,
      isMessagePortOpen,
      send
    });
  });
};

const Https = 'https:';
const Ws = 'ws:';
const Wss = 'wss:';

const getWebSocketProtocol = locationProtocol => {
  return locationProtocol === Https ? Wss : Ws;
};

const getWebSocketUrl = (type, host, locationProtocol) => {
  const wsProtocol = getWebSocketProtocol(locationProtocol);
  return `${wsProtocol}//${host}/websocket/${type}`;
};

const getHost = () => {
  return location.host;
};
const getProtocol = () => {
  return location.protocol;
};

const create$4 = async ({
  commandMap,
  webSocket
}) => {
  // TODO create a commandMap per rpc instance
  register(commandMap);
  const rawIpc = await IpcParentWithWebSocket$1.create({
    webSocket
  });
  const ipc = IpcParentWithWebSocket$1.wrap(rawIpc);
  handleIpc(ipc);
  const rpc = createRpc(ipc);
  return rpc;
};

const create$3 = async ({
  commandMap,
  type
}) => {
  const host = getHost();
  const protocol = getProtocol();
  const wsUrl = getWebSocketUrl(type, host, protocol);
  const webSocket = new WebSocket(wsUrl);
  const rpc = await create$4({
    commandMap,
    webSocket
  });
  return rpc;
};

const create$2 = async ({
  commandMap,
  type
}) => {
  return createSharedLazyRpc(() => {
    return create$3({
      commandMap,
      type
    });
  });
};

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 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 rpcs = Object.create(null);
const set$5 = (id, rpc) => {
  rpcs[id] = rpc;
};
const get = id => {
  return rpcs[id];
};
const remove = id => {
  delete rpcs[id];
};

/* eslint-disable  @typescript-eslint/explicit-function-return-type */
const create = rpcId => {
  return {
    async dispose() {
      const rpc = get(rpcId);
      await rpc.dispose();
    },
    // @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);
    },
    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 Div = 4;
const Table$1 = 9;
const TBody = 10;
const Td = 11;
const Text = 12;
const Th = 13;
const THead = 14;
const Tr = 15;
const Pre = 51;
const Reference = 100;

const ClientX = 'event.clientX';
const ClientY = 'event.clientY';

const Enter = 3;
const Space = 9;
const End = 255;
const Home = 12;
const LeftArrow = 13;
const UpArrow = 14;
const RightArrow = 15;
const DownArrow = 16;
const ContextMenu = 56;
const Star = 131;

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

const None$1 = 0;

const Electron = 2;
const Remote = 3;

const ErrorWorker = 3308;
const FileSystemWorker$1 = 209;
const RendererWorker = 1;

const FocusSelector = 'Viewlet.focusSelector';
const SetDom2 = 'Viewlet.setDom2';
const SetFocusContext = 'Viewlet.setFocusContext';
const SetPatches = 'Viewlet.setPatches';

const Empty = 0;
const FocusExplorer = 13;

const {
  invoke: invoke$2,
  set: set$4
} = create(ErrorWorker);
const prepare = async error => {
  return invoke$2('Errors.prepare', error);
};

const {
  set: set$3
} = create(FileSystemWorker$1);

const FileSystemWorker = {
  __proto__: null,
  set: set$3
};

const {
  invoke: invoke$1,
  invokeAndTransfer,
  set: set$2
} = create(RendererWorker);
const showContextMenu2 = async (uid, menuId, x, y, args) => {
  number(uid);
  number(menuId);
  number(x);
  number(y);
  await invoke$1('ContextMenu.show2', uid, menuId, x, y, args);
};
const sendMessagePortToErrorWorker$1 = async (port, rpcId) => {
  const command = 'Errors.handleMessagePort';
  await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToErrorWorker', port, command, rpcId);
};
const sendMessagePortToFileSystemWorker$1 = async (port, rpcId) => {
  const command = 'FileSystem.handleMessagePort';
  await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToFileSystemWorker', port, command, rpcId);
};
const sendMessagePortToProcessExplorer$1 = async port => {
  const command = 'ProcessExplorer.handleMessagePort';
  await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToProcessExplorer', port, command, 0);
};

const debugProcess = async (state, index = state.focusedIndex) => {
  const process = state.visibleProcesses[index];
  if (!process) {
    return state;
  }
  await invoke$1('AttachDebugger.attachDebugger', process.pid);
  return state;
};

const isEqual$1 = (oldState, newState) => {
  return oldState.focused === newState.focused && oldState.focusedIndex === newState.focusedIndex;
};

const isEqual = (oldState, newState) => {
  return oldState.initial === newState.initial && oldState.errorCodeFrame === newState.errorCodeFrame && oldState.errorMessage === newState.errorMessage && oldState.errorStack === newState.errorStack && oldState.focusedIndex === newState.focusedIndex && oldState.visibleProcesses === newState.visibleProcesses;
};

const RenderItems = 1;
const RenderFocus = 2;
const RenderFocusContext = 3;
const RenderIncremental = 4;

const modules = [isEqual, isEqual$1, isEqual$1];
const numbers = [RenderIncremental, RenderFocus, 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 {
    oldState,
    scheduledState
  } = get$2(uid);
  return diff(oldState, scheduledState);
};

const intervals = new Map();
const pending = new Set();
const dispose$3 = uid => {
  const interval = intervals.get(uid);
  if (interval) {
    clearInterval(interval);
    intervals.delete(uid);
  }
  pending.delete(uid);
};
const update = async uid => {
  if (!getKeys$1().includes(uid)) {
    dispose$3(uid);
    return;
  }
  if (pending.has(uid)) {
    return;
  }
  pending.add(uid);
  try {
    await invoke$1('ProcessExplorer.update');
  } catch (error) {
    console.error(error);
  } finally {
    pending.delete(uid);
  }
};
const start = (uid, interval = processExplorerUpdateInterval) => {
  if (interval <= 0 || intervals.has(uid)) {
    return;
  }
  const intervalId = setInterval(() => {
    void update(uid);
  }, interval);
  intervals.set(uid, intervalId);
};
const restart = (uid, interval) => {
  dispose$3(uid);
  start(uid, interval);
};

const sendMessagePortToProcessExplorer = async port => {
  await sendMessagePortToProcessExplorer$1(port);
};

const launchProcessExplorerElectron = async () => {
  try {
    const rpc = await create$5({
      commandMap: {},
      send: sendMessagePortToProcessExplorer
    });
    return rpc;
  } catch (error) {
    throw new VError(error, 'Failed to create process explorer electron rpc');
  }
};

const launchProcessExplorerNode = async () => {
  try {
    const rpc = await create$2({
      commandMap: {},
      type: 'process-explorer'
    });
    return rpc;
  } catch (error) {
    throw new VError(error, 'Failed to create process explorer websocket rpc');
  }
};

const state$1 = {
  rpc: undefined
};
const invoke = async (method, ...params) => {
  if (!state$1.rpc) {
    throw new Error('ProcessExplorerModule is not initialized');
  }
  return state$1.rpc.invoke(method, ...params);
};
const set$1 = newRpc => {
  state$1.rpc = newRpc;
};
const dispose$2 = async () => {
  const {
    rpc
  } = state$1;
  state$1.rpc = undefined;
  await rpc?.dispose();
};

const state = {
  initializedPlatform: 0
};
const initializeProcessExplorer = async platform => {
  if (state.initializedPlatform === platform) {
    return;
  }
  if (platform === Electron) {
    const rpc = await launchProcessExplorerElectron();
    set$1(rpc);
    state.initializedPlatform = platform;
    return;
  }
  if (platform === Remote) {
    const rpc = await launchProcessExplorerNode();
    set$1(rpc);
    state.initializedPlatform = platform;
  }
};
const dispose$1 = async () => {
  state.initializedPlatform = 0;
  await dispose$2();
};

const dispose = async uid => {
  dispose$3(uid);
  dispose$4(uid);
  if (getKeys$1().length === 0) {
    await dispose$1();
  }
};

const createE2eFixtureProcess = async (state, marker) => {
  const pid = await invoke('Process.createE2eFixtureProcess', marker);
  return {
    ...state,
    rootPid: pid
  };
};
const disposeE2eFixtureProcess = async (_uid, pidOrMarker) => {
  await invoke('Process.disposeE2eFixtureProcess', pidOrMarker);
};

const expandAll = state => {
  const collapsedPids = [];
  const visibleProcesses = getVisibleProcesses(state.processes, collapsedPids, state.rootPid);
  return {
    ...state,
    collapsedPids,
    visibleProcesses
  };
};

const focusIndex = (state, index) => {
  if (index < -1 || index >= state.visibleProcesses.length) {
    return state;
  }
  return {
    ...state,
    focusedIndex: index
  };
};

const focusFirst = state => {
  if (state.visibleProcesses.length === 0) {
    return state;
  }
  return focusIndex(state, 0);
};

const focusLast = state => {
  if (state.visibleProcesses.length === 0) {
    return state;
  }
  return focusIndex(state, state.visibleProcesses.length - 1);
};

const focusNext = state => {
  if (state.focusedIndex >= state.visibleProcesses.length - 1) {
    return state;
  }
  return focusIndex(state, state.focusedIndex + 1);
};

const focusPrevious = state => {
  if (state.focusedIndex === -1 && state.visibleProcesses.length > 0) {
    return focusIndex(state, state.visibleProcesses.length - 1);
  }
  if (state.focusedIndex <= 0) {
    return state;
  }
  return focusIndex(state, state.focusedIndex - 1);
};

const getKeyBindings = () => {
  return [{
    command: 'ProcessExplorer.handleArrowRight',
    key: RightArrow,
    when: FocusExplorer
  }, {
    command: 'ProcessExplorer.handleArrowLeft',
    key: LeftArrow,
    when: FocusExplorer
  }, {
    command: 'ProcessExplorer.focusFirst',
    key: Home,
    when: FocusExplorer
  }, {
    command: 'ProcessExplorer.focusLast',
    key: End,
    when: FocusExplorer
  }, {
    command: 'ProcessExplorer.focusPrevious',
    key: UpArrow,
    when: FocusExplorer
  }, {
    command: 'ProcessExplorer.focusNext',
    key: DownArrow,
    when: FocusExplorer
  }, {
    command: 'ProcessExplorer.collapseAll',
    key: CtrlCmd | LeftArrow,
    when: FocusExplorer
  }, {
    command: 'ProcessExplorer.expandAll',
    key: CtrlCmd | RightArrow,
    when: FocusExplorer
  }, {
    command: 'ProcessExplorer.expandAll',
    key: CtrlCmd | Star,
    when: FocusExplorer
  }, {
    command: 'ProcessExplorer.handleDoubleClick',
    key: Enter,
    when: FocusExplorer
  }, {
    command: 'ProcessExplorer.handleDoubleClick',
    key: Space,
    when: FocusExplorer
  }, {
    command: 'ProcessExplorer.handleContextMenu',
    key: ContextMenu,
    when: FocusExplorer
  }];
};

const isDebuggable = command => {
  return command.includes('node ') || command.includes('node.exe') || command.includes('node.mojom.NodeService');
};

const KillProcess = 'Kill Process';
const DebugProcess = 'Debug Process';

const getMenuEntries = state => {
  const process = state.visibleProcesses[state.focusedIndex];
  if (!process) {
    return [];
  }
  const menuEntries = [{
    args: [state.focusedIndex],
    command: 'ProcessExplorer.killProcess',
    flags: None$1,
    id: 'killProcess',
    label: KillProcess
  }];
  if (isDebuggable(process.cmd)) {
    menuEntries.push({
      args: [state.focusedIndex],
      command: 'ProcessExplorer.debugProcess',
      flags: None$1,
      id: 'debugProcess',
      label: DebugProcess
    });
  }
  return menuEntries;
};

const ProcessExplorer$1 = 29;

const getMenuEntryIds = () => {
  return [ProcessExplorer$1];
};

const toggleIndex = (state, index) => {
  const process = state.visibleProcesses[index];
  if (!process || process.flags === None$2) {
    return state;
  }
  const collapsedPids = state.collapsedPids.includes(process.pid) ? state.collapsedPids.filter(pid => pid !== process.pid) : [...state.collapsedPids, process.pid];
  const visibleProcesses = getVisibleProcesses(state.processes, collapsedPids, state.rootPid);
  return {
    ...state,
    collapsedPids,
    focusedIndex: Math.min(index, visibleProcesses.length - 1),
    visibleProcesses
  };
};

const getParentIndex = state => {
  const process = state.visibleProcesses[state.focusedIndex];
  if (!process) {
    return -1;
  }
  for (let i = state.focusedIndex - 1; i >= 0; i--) {
    const otherProcess = state.visibleProcesses[i];
    if (otherProcess.depth === process.depth - 1) {
      return i;
    }
  }
  return -1;
};
const handleArrowLeft = state => {
  const process = state.visibleProcesses[state.focusedIndex];
  if (!process) {
    return state;
  }
  if (process.flags === Expanded) {
    return toggleIndex(state, state.focusedIndex);
  }
  const parentIndex = getParentIndex(state);
  if (parentIndex === -1) {
    return state;
  }
  return focusIndex(state, parentIndex);
};

const handleArrowRight = state => {
  const {
    focusedIndex,
    visibleProcesses
  } = state;
  const process = visibleProcesses[focusedIndex];
  if (!process) {
    return state;
  }
  if (process.flags === Collapsed) {
    return toggleIndex(state, focusedIndex);
  }
  const nextProcess = visibleProcesses[focusedIndex + 1];
  if (process.flags === Expanded && nextProcess && nextProcess.depth > process.depth) {
    return focusIndex(state, focusedIndex + 1);
  }
  return state;
};

const handleBlur = state => {
  return {
    ...state,
    focused: false
  };
};

const handleClickAt = (state, index) => {
  return focusIndex(state, Number(index));
};

const show2 = async (uid, menuId, x, y, args) => {
  await showContextMenu2(uid, menuId, x, y, args);
};

const handleContextMenu = async (state, index = state.focusedIndex, x = 0, y = 0) => {
  const numericIndex = Number(index);
  const process = state.visibleProcesses[numericIndex];
  if (!process) {
    return state;
  }
  const newState = {
    ...state,
    focused: false,
    focusedIndex: numericIndex
  };
  set$6(state.uid, state, newState);
  await show2(state.uid, ProcessExplorer$1, x, y, {
    index: numericIndex,
    menuId: ProcessExplorer$1
  });
  return newState;
};

const handleDoubleClick = (state, index = state.focusedIndex) => {
  return toggleIndex(state, Number(index));
};

const handleFocus = state => {
  return {
    ...state,
    focused: true
  };
};

const killProcess = async (state, index = state.focusedIndex) => {
  const process = state.visibleProcesses[index];
  if (!process) {
    return state;
  }
  await invoke('Process.kill', process.pid);
  return state;
};

const getMeasureMemory = () => {
  const {
    measureUserAgentSpecificMemory
  } = performance;
  if (typeof measureUserAgentSpecificMemory !== 'function') {
    return undefined;
  }
  return measureUserAgentSpecificMemory.bind(performance);
};

const isValidMemoryValue = value => {
  return typeof value === 'number' && Number.isFinite(value) && value >= 0;
};

const QueryOrHashRegex = /[?#]/;
const getUrlName = url => {
  if (!url || url === 'cross-origin-url') {
    return url;
  }
  try {
    const parsed = new URL(url);
    const parts = parsed.pathname.split('/').filter(Boolean);
    return parts.at(-1) || parsed.hostname || url;
  } catch {
    const withoutQuery = url.split(QueryOrHashRegex, 1)[0];
    const parts = withoutQuery.split('/').filter(Boolean);
    return parts.at(-1) || url;
  }
};

const getAttributionName = attribution => {
  const scope = attribution.scope || 'memory';
  const url = attribution.url ? getUrlName(attribution.url) : '';
  if (url) {
    return `${scope}: ${url}`;
  }
  return scope;
};

const getBreakdownName = (entry, index) => {
  if (entry.attribution && entry.attribution.length > 0) {
    return entry.attribution.map(getAttributionName).join(', ');
  }
  if (entry.types && entry.types.length > 0) {
    return entry.types.join(', ');
  }
  return `breakdown ${index + 1}`;
};

const WindowPid = -1;

const toBreakdownProcess = (entry, index) => {
  const name = getBreakdownName(entry, index);
  return {
    cmd: name,
    memory: entry.bytes,
    name,
    pid: -2 - index,
    ppid: WindowPid,
    synthetic: true
  };
};

const getFrontendMemoryUsage = async rootPid => {
  const measureMemory = getMeasureMemory();
  if (!measureMemory) {
    return [];
  }
  try {
    const measurement = await measureMemory();
    if (!isValidMemoryValue(measurement.bytes)) {
      return [];
    }
    const breakdown = measurement.breakdown || [];
    const breakdownProcesses = breakdown.filter(entry => isValidMemoryValue(entry.bytes) && entry.bytes > 0).map(toBreakdownProcess);
    return [{
      cmd: 'window',
      memory: measurement.bytes,
      name: 'window',
      pid: WindowPid,
      ppid: rootPid,
      synthetic: true
    }, ...breakdownProcesses];
  } catch {
    return [];
  }
};

const getErrorMessage = error => {
  if (error instanceof Error) {
    return error.message;
  }
  return String(error);
};
const prepareError = async error => {
  try {
    return await prepare(error);
  } catch {
    return {
      codeFrame: undefined,
      message: getErrorMessage(error),
      stack: undefined
    };
  }
};

const getFocusedIndex = (oldFocusedIndex, visibleProcesses) => {
  if (visibleProcesses.length === 0) {
    return -1;
  }
  if (oldFocusedIndex < 0) {
    return 0;
  }
  return Math.min(oldFocusedIndex, visibleProcesses.length - 1);
};
const refresh = async state => {
  try {
    await initializeProcessExplorer(state.platform);
    const includeElectronData = state.platform === Electron;
    const rootPid = state.rootPid === -1 ? await invoke('ProcessId.getMainProcessId', {
      includeElectronData
    }) : state.rootPid;
    const processes = await invoke('ListProcessesWithMemoryUsage.listProcessesWithMemoryUsage', rootPid, includeElectronData);
    const frontendMemoryProcesses = state.includeFrontendMemoryUsage ? await getFrontendMemoryUsage(rootPid) : [];
    const allProcesses = [...processes, ...frontendMemoryProcesses];
    const visibleProcesses = getVisibleProcesses(allProcesses, state.collapsedPids, rootPid);
    return {
      ...state,
      errorCodeFrame: '',
      errorMessage: '',
      errorStack: '',
      focusedIndex: getFocusedIndex(state.focusedIndex, visibleProcesses),
      initial: false,
      processes: allProcesses,
      rootPid,
      visibleProcesses
    };
  } catch (error) {
    const prettyError = await prepareError(error);
    return {
      ...state,
      errorCodeFrame: prettyError.codeFrame || '',
      errorMessage: prettyError.message || getErrorMessage(error),
      errorStack: prettyError.stack || '',
      initial: false
    };
  }
};

const hasError$1 = state => {
  return Boolean(state.errorMessage || state.errorCodeFrame || state.errorStack);
};
const loadContent = async state => {
  const newState = await refresh(state);
  if (!hasError$1(newState)) {
    start(newState.uid, newState.updateInterval);
  }
  return {
    error: undefined,
    state: newState
  };
};

const renderFocus = (oldState, newState) => {
  if (!newState.focused || oldState.focusedIndex === newState.focusedIndex) {
    return [];
  }
  if (newState.focusedIndex < 0) {
    return [FocusSelector, '.ProcessExplorerTable'];
  }
  return [FocusSelector, `[data-index="${newState.focusedIndex}"]`];
};

const renderFocusContext = (oldState, newState) => {
  if (oldState.focused === newState.focused) {
    return [];
  }
  return [SetFocusContext, newState.uid, newState.focused ? FocusExplorer : Empty];
};

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

const SetText = 1;
const Replace = 2;
const SetAttribute = 3;
const RemoveAttribute = 4;
const Add = 6;
const NavigateChild = 7;
const NavigateParent = 8;
const RemoveChild = 9;
const NavigateSibling = 10;
const SetReferenceNodeUid = 11;

const isKey = key => {
  return key !== 'type' && key !== 'childCount';
};

const getKeys = node => {
  const keys = Object.keys(node).filter(isKey);
  return keys;
};

const arrayToTree = nodes => {
  const result = [];
  let i = 0;
  while (i < nodes.length) {
    const node = nodes[i];
    const {
      children,
      nodesConsumed
    } = getChildrenWithCount(nodes, i + 1, node.childCount || 0);
    result.push({
      node,
      children
    });
    i += 1 + nodesConsumed;
  }
  return result;
};
const getChildrenWithCount = (nodes, startIndex, childCount) => {
  if (childCount === 0) {
    return {
      children: [],
      nodesConsumed: 0
    };
  }
  const children = [];
  let i = startIndex;
  let remaining = childCount;
  let totalConsumed = 0;
  while (remaining > 0 && i < nodes.length) {
    const node = nodes[i];
    const nodeChildCount = node.childCount || 0;
    const {
      children: nodeChildren,
      nodesConsumed
    } = getChildrenWithCount(nodes, i + 1, nodeChildCount);
    children.push({
      node,
      children: nodeChildren
    });
    const nodeSize = 1 + nodesConsumed;
    i += nodeSize;
    totalConsumed += nodeSize;
    remaining--;
  }
  return {
    children,
    nodesConsumed: totalConsumed
  };
};

const compareNodes = (oldNode, newNode) => {
  // Check if node type changed - return null to signal incompatible nodes
  // (caller should handle this with a Replace operation)
  if (oldNode.type !== newNode.type) {
    return null;
  }
  const patches = [];
  // Handle reference nodes - special handling for uid changes
  if (oldNode.type === Reference) {
    if (oldNode.uid !== newNode.uid) {
      patches.push({
        type: SetReferenceNodeUid,
        uid: newNode.uid
      });
    }
    return patches;
  }
  // Handle text nodes
  if (oldNode.type === Text && newNode.type === Text) {
    if (oldNode.text !== newNode.text) {
      patches.push({
        type: SetText,
        value: newNode.text
      });
    }
    return patches;
  }
  // Compare attributes
  const oldKeys = getKeys(oldNode);
  const newKeys = getKeys(newNode);
  // Check for attribute changes
  for (const key of newKeys) {
    if (oldNode[key] !== newNode[key]) {
      patches.push({
        type: SetAttribute,
        key,
        value: newNode[key]
      });
    }
  }
  // Check for removed attributes
  for (const key of oldKeys) {
    if (!Object.hasOwn(newNode, key)) {
      patches.push({
        type: RemoveAttribute,
        key
      });
    }
  }
  return patches;
};

const treeToArray = node => {
  const result = [node.node];
  for (const child of node.children) {
    result.push(...treeToArray(child));
  }
  return result;
};

const navigateToChild = (patches, currentChildIndex, index) => {
  if (currentChildIndex === -1) {
    patches.push({
      type: NavigateChild,
      index
    });
    return index;
  }
  if (currentChildIndex !== index) {
    patches.push({
      type: NavigateSibling,
      index
    });
  }
  return index;
};
const navigateToParent = (patches, currentChildIndex) => {
  if (currentChildIndex >= 0) {
    patches.push({
      type: NavigateParent
    });
  }
  return -1;
};
const addTree = (newNode, patches) => {
  patches.push({
    type: Add,
    nodes: treeToArray(newNode)
  });
};
const replaceTree = (newNode, patches) => {
  patches.push({
    type: Replace,
    nodes: treeToArray(newNode)
  });
};
const diffExistingChild = (oldNode, newNode, patches, currentChildIndex, index) => {
  const nodePatches = compareNodes(oldNode.node, newNode.node);
  if (nodePatches === null) {
    const nextChildIndex = navigateToChild(patches, currentChildIndex, index);
    replaceTree(newNode, patches);
    return nextChildIndex;
  }
  const hasChildrenToCompare = oldNode.children.length > 0 || newNode.children.length > 0;
  if (nodePatches.length === 0 && !hasChildrenToCompare) {
    return currentChildIndex;
  }
  const nextChildIndex = navigateToChild(patches, currentChildIndex, index);
  if (nodePatches.length > 0) {
    patches.push(...nodePatches);
  }
  if (hasChildrenToCompare) {
    diffChildren(oldNode.children, newNode.children, patches);
  }
  return nextChildIndex;
};
const diffRootNode = (oldNode, newNode, patches) => {
  const nodePatches = compareNodes(oldNode.node, newNode.node);
  if (nodePatches === null) {
    replaceTree(newNode, patches);
    return;
  }
  if (nodePatches.length > 0) {
    patches.push(...nodePatches);
  }
  if (oldNode.children.length > 0 || newNode.children.length > 0) {
    diffChildren(oldNode.children, newNode.children, patches);
  }
};
const diffChildren = (oldChildren, newChildren, patches) => {
  const maxLength = Math.max(oldChildren.length, newChildren.length);
  let currentChildIndex = -1;
  const indicesToRemove = [];
  for (let i = 0; i < maxLength; i++) {
    const oldNode = oldChildren[i];
    const newNode = newChildren[i];
    if (!oldNode && !newNode) {
      continue;
    }
    if (!oldNode) {
      currentChildIndex = navigateToParent(patches, currentChildIndex);
      addTree(newNode, patches);
      continue;
    }
    if (!newNode) {
      indicesToRemove.push(i);
      continue;
    }
    currentChildIndex = diffExistingChild(oldNode, newNode, patches, currentChildIndex, i);
  }
  navigateToParent(patches, currentChildIndex);
  for (let j = indicesToRemove.length - 1; j >= 0; j--) {
    patches.push({
      type: RemoveChild,
      index: indicesToRemove[j]
    });
  }
};
const diffTrees = (oldTree, newTree, patches, path) => {
  if (path.length === 0 && oldTree.length === 1 && newTree.length === 1) {
    diffRootNode(oldTree[0], newTree[0], patches);
    return;
  }
  diffChildren(oldTree, newTree, patches);
};

const removeTrailingNavigationPatches = patches => {
  // Find the last non-navigation patch
  let lastNonNavigationIndex = -1;
  for (let i = patches.length - 1; i >= 0; i--) {
    const patch = patches[i];
    if (patch.type !== NavigateChild && patch.type !== NavigateParent && patch.type !== NavigateSibling) {
      lastNonNavigationIndex = i;
      break;
    }
  }
  // Return patches up to and including the last non-navigation patch
  return lastNonNavigationIndex === -1 ? [] : patches.slice(0, lastNonNavigationIndex + 1);
};

const diffTree = (oldNodes, newNodes) => {
  // Step 1: Convert flat arrays to tree structures
  const oldTree = arrayToTree(oldNodes);
  const newTree = arrayToTree(newNodes);
  // Step 3: Compare the trees
  const patches = [];
  diffTrees(oldTree, newTree, patches, []);
  // Remove trailing navigation patches since they serve no purpose
  return removeTrailingNavigationPatches(patches);
};

const Grid = 'grid';
const GridCell = 'gridcell';
const None = 'none';
const Row$1 = 'row';
const RowGroup = 'rowgroup';

const Cell = 'ProcessExplorerCell';
const Error$1 = 'ProcessExplorerError';
const HeaderCell = 'ProcessExplorerHeaderCell';
const NameCell = 'ProcessExplorerNameCell';
const Row = 'ProcessExplorerRow';
const RowFocused = 'ProcessExplorerRowFocused';
const Table = 'ProcessExplorerTable';
const TableBody = 'ProcessExplorerTableBody';
const TableHead = 'ProcessExplorerTableHead';
const Viewlet = 'Viewlet';
const ProcessExplorer = 'ProcessExplorer';

const HandleBlur = 1;
const HandleClick = 2;
const HandleContextMenu = 3;
const HandleDoubleClick = 4;
const HandleFocus = 5;
const HandlePointerDown = 6;

const formatMemory = memory => {
  if (memory < 1000) {
    return `${memory} B`;
  }
  if (memory < 1000 ** 2) {
    return `${(memory / 1000).toFixed(1)} kB`;
  }
  if (memory < 1000 ** 3) {
    return `${(memory / 1000 ** 2).toFixed(1)} MB`;
  }
  if (memory < 1000 ** 4) {
    return `${(memory / 1000 ** 3).toFixed(1)} GB`;
  }
  return `${(memory / 1000 ** 4).toFixed(1)} TB`;
};

const getRowClassName = focused => {
  if (focused) {
    return `${Row} ${RowFocused}`;
  }
  return Row;
};
const getPaddingLeft = process => {
  if (process.depth <= 1) {
    return '0';
  }
  const depthCh = (process.depth - 1) * 1.5;
  return `${depthCh}ch`;
};
const getAriaExpanded = process => {
  switch (process.flags) {
    case Collapsed:
      return false;
    case Expanded:
      return true;
    default:
      return undefined;
  }
};
const getCellDom = (className, value, index, paddingLeft) => {
  return [{
    childCount: 1,
    className,
    'data-index': index,
    name: String(index),
    paddingLeft,
    role: GridCell,
    tabIndex: -1,
    type: Td
  }, text(value)];
};
const getHeaderDom = () => {
  return [{
    childCount: 1,
    className: TableHead,
    role: RowGroup,
    type: THead
  }, {
    childCount: 3,
    className: Row,
    role: Row$1,
    type: Tr
  }, ...['Name', 'PID', 'Memory'].flatMap(label => [{
    childCount: 1,
    className: HeaderCell,
    type: Th
  }, text(label)])];
};
const getRowDom = (process, index, focused) => {
  return [{
    ariaDescription: '',
    ariaExpanded: getAriaExpanded(process),
    ariaLevel: process.depth,
    childCount: 3,
    className: getRowClassName(focused),
    'data-index': index,
    name: String(index),
    role: Row$1,
    tabIndex: focused ? 0 : -1,
    title: process.cmd,
    type: Tr
  }, ...getCellDom(`${Cell} ${NameCell}`, process.name, index, getPaddingLeft(process)), ...getCellDom(Cell, String(process.pid), index), ...getCellDom(Cell, formatMemory(process.memory), index)];
};
const getBodyDom = state => {
  const {
    focusedIndex,
    visibleProcesses
  } = state;
  return [{
    childCount: visibleProcesses.length,
    className: TableBody,
    role: RowGroup,
    type: TBody
  }, ...visibleProcesses.flatMap((process, index) => getRowDom(process, index, index === focusedIndex))];
};
const getErrorSectionDom = (value, type) => {
  if (!value) {
    return [];
  }
  return [{
    childCount: 1,
    type
  }, text(value)];
};
const hasError = state => {
  return Boolean(state.errorMessage || state.errorCodeFrame || state.errorStack);
};
const getErrorDom = state => {
  const messageDom = getErrorSectionDom(state.errorMessage, Div);
  const codeFrameDom = getErrorSectionDom(state.errorCodeFrame, Pre);
  const stackDom = getErrorSectionDom(state.errorStack, Pre);
  const childCount = messageDom.length / 2 + codeFrameDom.length / 2 + stackDom.length / 2;
  return [{
    childCount: 1,
    className: `${Viewlet} ${ProcessExplorer}`,
    role: None,
    type: Div
  }, {
    childCount,
    className: Error$1,
    type: Div
  }, ...messageDom, ...codeFrameDom, ...stackDom];
};
const getTableDom = state => {
  return [{
    childCount: 1,
    className: `${Viewlet} ${ProcessExplorer}`,
    role: None,
    type: Div
  }, {
    ariaLabel: 'Process Explorer',
    ariaRowCount: state.visibleProcesses.length + 1,
    childCount: 2,
    className: Table,
    onBlur: HandleBlur,
    onClick: HandleClick,
    onContextMenu: HandleContextMenu,
    onDblClick: HandleDoubleClick,
    onFocus: HandleFocus,
    onPointerDown: HandlePointerDown,
    role: Grid,
    tabIndex: 0,
    type: Table$1
  }, ...getHeaderDom(), ...getBodyDom(state)];
};
const getDom = state => {
  if (state.initial) {
    return [];
  }
  if (hasError(state)) {
    return getErrorDom(state);
  }
  return getTableDom(state);
};
const renderItems = (oldState, newState) => {
  return [SetDom2, newState.uid, getDom(newState)];
};

const renderIncremental = (oldState, newState) => {
  const oldDom = renderItems(oldState, oldState)[2];
  const newDom = renderItems(newState, newState)[2];
  const patches = diffTree(oldDom, newDom);
  return [SetPatches, newState.uid, patches];
};

const getRenderer = diffType => {
  switch (diffType) {
    case RenderFocus:
      return renderFocus;
    case RenderFocusContext:
      return renderFocusContext;
    case RenderIncremental:
      return renderIncremental;
    case RenderItems:
      return renderItems;
    default:
      throw new Error(`unknown renderer ${diffType}`);
  }
};

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

const render2 = (uid, diffResult) => {
  const {
    oldState,
    scheduledState
  } = get$2(uid);
  set$6(uid, scheduledState, scheduledState);
  return applyRender(oldState, scheduledState, diffResult);
};

const renderEventListeners = () => {
  return [{
    name: HandleFocus,
    params: ['handleFocus']
  }, {
    name: HandleBlur,
    params: ['handleBlur']
  }, {
    name: HandleClick,
    params: ['handleClickAt', 'event.target.dataset.index'],
    preventDefault: true
  }, {
    name: HandleDoubleClick,
    params: ['handleDoubleClick', 'event.target.dataset.index'],
    preventDefault: true
  }, {
    name: HandleContextMenu,
    params: ['handleContextMenu', 'event.target.dataset.index', ClientX, ClientY],
    preventDefault: true
  }, {
    name: HandlePointerDown,
    params: ['handleClickAt', 'event.target.dataset.index']
  }];
};

const isRawError = value => {
  return Boolean(value && typeof value === 'object');
};
const getRawMessage = rawError => {
  if (typeof rawError.message === 'string') {
    return rawError.message;
  }
  return String(rawError.message);
};
const toError = rawError => {
  if (rawError instanceof Error) {
    return rawError;
  }
  if (!isRawError(rawError)) {
    return new Error(String(rawError));
  }
  if (typeof rawError.stack === 'string') {
    return {
      code: rawError.code,
      message: getRawMessage(rawError),
      stack: rawError.stack
    };
  }
  const error = new Error(getRawMessage(rawError));
  if (typeof rawError.code === 'string') {
    Object.assign(error, {
      code: rawError.code
    });
  }
  return error;
};
const setError = async (state, rawError) => {
  const error = toError(rawError);
  const prettyError = await prepareError(error);
  return {
    ...state,
    errorCodeFrame: prettyError.codeFrame || '',
    errorMessage: prettyError.message || getErrorMessage(error),
    errorStack: prettyError.stack || '',
    initial: false
  };
};

const setRootProcessId = (state, rootPid) => {
  return {
    ...state,
    rootPid
  };
};

const setUpdateInterval = (state, updateInterval) => {
  restart(state.uid, updateInterval);
  return {
    ...state,
    updateInterval
  };
};

const commandMap = {
  'ProcessExplorer.collapseAll': wrapCommand(collapseAll),
  'ProcessExplorer.create': create$d,
  'ProcessExplorer.createE2eFixtureProcess': wrapCommand(createE2eFixtureProcess),
  'ProcessExplorer.debugProcess': wrapCommand(debugProcess),
  'ProcessExplorer.diff2': diff2,
  'ProcessExplorer.dispose': dispose,
  'ProcessExplorer.disposeE2eFixtureProcess': disposeE2eFixtureProcess,
  'ProcessExplorer.expandAll': wrapCommand(expandAll),
  'ProcessExplorer.focusFirst': wrapCommand(focusFirst),
  'ProcessExplorer.focusLast': wrapCommand(focusLast),
  'ProcessExplorer.focusNext': wrapCommand(focusNext),
  'ProcessExplorer.focusPrevious': wrapCommand(focusPrevious),
  'ProcessExplorer.getCommandIds': getCommandIds,
  'ProcessExplorer.getKeyBindings': getKeyBindings,
  'ProcessExplorer.getMenuEntries': wrapGetter(getMenuEntries),
  'ProcessExplorer.getMenuEntryIds': getMenuEntryIds,
  'ProcessExplorer.handleArrowLeft': wrapCommand(handleArrowLeft),
  'ProcessExplorer.handleArrowRight': wrapCommand(handleArrowRight),
  'ProcessExplorer.handleBlur': wrapCommand(handleBlur),
  'ProcessExplorer.handleClickAt': wrapCommand(handleClickAt),
  'ProcessExplorer.handleContextMenu': wrapCommand(handleContextMenu),
  'ProcessExplorer.handleDoubleClick': wrapCommand(handleDoubleClick),
  'ProcessExplorer.handleFocus': wrapCommand(handleFocus),
  'ProcessExplorer.killProcess': wrapCommand(killProcess),
  'ProcessExplorer.loadContent': wrapLoadContent(loadContent),
  'ProcessExplorer.refresh': wrapCommand(refresh),
  'ProcessExplorer.render2': render2,
  'ProcessExplorer.renderEventListeners': renderEventListeners,
  'ProcessExplorer.setError': wrapCommand(setError),
  'ProcessExplorer.setRootProcessId': wrapCommand(setRootProcessId),
  'ProcessExplorer.setUpdateInterval': wrapCommand(setUpdateInterval),
  'ProcessExplorer.terminate': terminate,
  'ProcessExplorer.update': wrapCommand(refresh)
};

const sendMessagePortToErrorWorker = async port => {
  await sendMessagePortToErrorWorker$1(port, 0);
};

const createErrorWorkerRpc = async () => {
  try {
    const rpc = await create$5({
      commandMap: {},
      send: sendMessagePortToErrorWorker
    });
    return rpc;
  } catch (error) {
    throw new VError(error, `Failed to create error worker rpc`);
  }
};

const initializeErrorWorker = async () => {
  const rpc = await createErrorWorkerRpc();
  set$4(rpc);
};

const sendMessagePortToFileSystemWorker = async port => {
  await sendMessagePortToFileSystemWorker$1(port, 0);
};

const createFileSystemWorkerRpc = async () => {
  try {
    const rpc = await create$5({
      commandMap: {},
      send: sendMessagePortToFileSystemWorker
    });
    return rpc;
  } catch (error) {
    throw new VError(error, `Failed to create file system worker rpc`);
  }
};

const {
  set
} = FileSystemWorker;

const initializeFileSystemWorker = async () => {
  const rpc = await createFileSystemWorkerRpc();
  set(rpc);
};

const initializeRendererWorker = async () => {
  const rpc = await create$1({
    commandMap: commandMap
  });
  set$2(rpc);
};

const listen = async () => {
  registerCommands(commandMap);
  await Promise.all([initializeRendererWorker(), initializeFileSystemWorker(), initializeErrorWorker()]);
};

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

main();
