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

class AssertionError extends Error {
  constructor(message) {
    super(message);
    this.name = 'AssertionError';
  }
}
const Object$1 = 1;
const Number$1 = 2;
const Array$1 = 3;
const String = 4;
const Boolean$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;
    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 string = value => {
  const type = getType(value);
  if (type !== String) {
    throw new AssertionError('expected value to be of type string');
  }
};

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

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

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

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

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

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

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

// @ts-ignore
const invokeHelper = async (callbacks, ipc, method, params, useSendAndTransfer) => {
  const {
    id,
    promise
  } = registerPromise(callbacks);
  const message = create$r(id, method, params);
  if (useSendAndTransfer && ipc.sendAndTransfer) {
    ipc.sendAndTransfer(message);
  } else {
    ipc.send(message);
  }
  const responseMessage = await promise;
  return unwrapJsonRpcResult(responseMessage);
};
const createRpc = ipc => {
  const callbacks = Object.create(null);
  ipc._resolve = (id, response) => {
    const fn = callbacks[id];
    if (!fn) {
      console.warn(`callback ${id} may already be disposed`);
      return;
    }
    fn(response);
    delete callbacks[id];
  };
  const rpc = {
    async dispose() {
      await ipc?.dispose();
    },
    invoke(method, ...params) {
      return invokeHelper(callbacks, ipc, method, params, false);
    },
    invokeAndTransfer(method, ...params) {
      return invokeHelper(callbacks, ipc, method, params, true);
    },
    // @ts-ignore
    ipc,
    /**
     * @deprecated
     */
    send(method, ...params) {
      const message = create$s(method, params);
      ipc.send(message);
    }
  };
  return rpc;
};
const requiresSocket = () => {
  return false;
};
const preparePrettyError = error => {
  return error;
};
const logError = () => {
  // handled by renderer worker
};
const handleMessage = event => {
  const actualRequiresSocket = event?.target?.requiresSocket || requiresSocket;
  const actualExecute = event?.target?.execute || execute;
  return handleJsonRpcMessage(event.target, event.data, actualExecute, event.target._resolve, preparePrettyError, logError, actualRequiresSocket);
};
const handleIpc = ipc => {
  if ('addEventListener' in ipc) {
    ipc.addEventListener('message', handleMessage);
  } else if ('on' in ipc) {
    // deprecated
    ipc.on('message', handleMessage);
  }
};
const listen$1 = async (module, options) => {
  const rawIpc = await module.listen(options);
  if (module.signal) {
    module.signal(rawIpc);
  }
  const ipc = module.wrap(rawIpc);
  return ipc;
};
const create$4 = async ({
  commandMap,
  isMessagePortOpen = true,
  messagePort
}) => {
  // TODO create a commandMap per rpc instance
  register(commandMap);
  const rawIpc = await IpcParentWithMessagePort$1.create({
    isMessagePortOpen,
    messagePort
  });
  const ipc = IpcParentWithMessagePort$1.wrap(rawIpc);
  handleIpc(ipc);
  const rpc = createRpc(ipc);
  messagePort.start();
  return rpc;
};
const PlainMessagePortRpc = {
  __proto__: null,
  create: create$4
};
const create$2 = async ({
  commandMap,
  isMessagePortOpen,
  send
}) => {
  const {
    port1,
    port2
  } = new MessageChannel();
  await send(port1);
  return create$4({
    commandMap,
    isMessagePortOpen,
    messagePort: port2
  });
};
const TransferMessagePortRpcParent = {
  __proto__: null,
  create: create$2
};
const create$1$1 = async ({
  commandMap
}) => {
  // TODO create a commandMap per rpc instance
  register(commandMap);
  const ipc = await listen$1(IpcChildWithModuleWorkerAndMessagePort$1);
  handleIpc(ipc);
  const rpc = createRpc(ipc);
  return rpc;
};
const WebWorkerRpcClient = {
  __proto__: null,
  create: create$1$1
};
const createMockRpc = ({
  commandMap
}) => {
  const invocations = [];
  const invoke = (method, ...params) => {
    invocations.push([method, ...params]);
    const command = commandMap[method];
    if (!command) {
      throw new Error(`command ${method} not found`);
    }
    return command(...params);
  };
  const mockRpc = {
    invocations,
    invoke,
    invokeAndTransfer: invoke
  };
  return mockRpc;
};

const None$1 = 'none';
const ToolBar = 'toolbar';
const Tree$1 = 'tree';
const TreeItem$1 = 'treeitem';

const Badge = 'Badge';
const SourceControlBadge = 'SourceControlBadge';

const Directory = 3;
const DirectoryExpanded = 4;
const File = 7;

const Button$2 = 1;
const Div = 4;
const Span = 8;
const Text = 12;
const Img = 17;
const TextArea = 62;

const Button$1 = 'event.button';
const ClientX = 'event.clientX';
const ClientY = 'event.clientY';
const DeltaMode = 'event.deltaMode';
const DeltaY = 'event.deltaY';
const TargetName = 'event.target.name';
const TargetValue = 'event.target.value';

const Enter = 3;

const User = 1;
const Script = 2;

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

const SourceControl$1 = 22;

const None = 0;

const ExtensionHostWorker = 44;
const ExtensionManagementWorker = 9006;
const IconThemeWorker = 7009;
const RendererWorker = 1;
const SourceControlWorker = 66;

const SetCss = 'Viewlet.setCss';
const SetDom2 = 'Viewlet.setDom2';
const SetFocusContext = 'Viewlet.setFocusContext';
const SetValueByName = 'Viewlet.setValueByName';

const List = 1;
const Tree = 2;

const FocusSourceControlInput = 24;

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

/* eslint-disable  @typescript-eslint/explicit-function-return-type */
const create$1 = rpcId => {
  return {
    async dispose() {
      const rpc = get$2(rpcId);
      await rpc.dispose();
    },
    // @ts-ignore
    invoke(method, ...params) {
      const rpc = get$2(rpcId);
      // @ts-ignore
      return rpc.invoke(method, ...params);
    },
    // @ts-ignore
    invokeAndTransfer(method, ...params) {
      const rpc = get$2(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 {
  invoke: invoke$1,
  set: set$4
} = create$1(ExtensionHostWorker);

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

const {
  invoke,
  invokeAndTransfer,
  set: set$2
} = create$1(RendererWorker);
const showContextMenu2 = async (uid, menuId, x, y, args) => {
  number(uid);
  number(menuId);
  number(x);
  number(y);
  // @ts-ignore
  await invoke('ContextMenu.show2', uid, menuId, x, y, args);
};
const readFile$1 = async uri => {
  return invoke('FileSystem.readFile', uri);
};
const sendMessagePortToExtensionHostWorker$1 = async (port, rpcId = 0) => {
  const command = 'HandleMessagePort.handleMessagePort2';
  await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToExtensionHostWorker', port, command, rpcId);
};
const activateByEvent$1 = (event, assetDir, platform) => {
  return invoke('ExtensionHostManagement.activateByEvent', event, assetDir, platform);
};
const sendMessagePortToTextMeasurementWorker$1 = async port => {
  const command = 'TextMeasurement.handleMessagePort';
  // @ts-ignore
  await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToTextMeasurementWorker', port, command, 0);
};
const sendMessagePortToExtensionManagementWorker = async (port, rpcId) => {
  const command = 'Extensions.handleMessagePort';
  await invokeAndTransfer('SendMessagePortToExtensionHostWorker.sendMessagePortToExtensionManagementWorker', port, command, rpcId);
};
const getPreference = async key => {
  return await invoke('Preferences.get', key);
};
const openUri$1 = async (uri, focus, options) => {
  await invoke('Main.openUri', uri, focus, options);
};

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

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

const getActualDecorationIcon = (iconDefinitions, icon) => {
  if (typeof icon === 'number') {
    const value = iconDefinitions[icon];
    if (!value) {
      return 'not-available';
    }
    return value;
  }
  return icon;
};

const getFileIcon = ({
  name
}) => {
  return '';
};

// TODO this should be in FileSystem module
const pathBaseName = path => {
  return path.slice(path.lastIndexOf('/') + 1);
};

const getDisplayItemsGroup = (group, expandedGroups, iconDefinitions) => {
  const displayItems = [];
  const {
    id,
    items,
    label
  } = group;
  if (!items) {
    throw new Error('Source control group is missing an items property');
  }
  const {
    length
  } = items;
  const isExpanded = expandedGroups[id] || false;
  const type = isExpanded ? DirectoryExpanded : Directory;
  const icon = isExpanded ? 'ChevronDown' : 'ChevronRight';
  if (length > 0) {
    displayItems.push({
      badgeCount: length,
      decorationIcon: '',
      decorationIconTitle: '',
      decorationStrikeThrough: false,
      detail: '',
      file: '',
      groupId: id,
      icon,
      label,
      posInSet: 1,
      setSize: 1,
      type
    });
  }
  if (isExpanded) {
    for (let i = 0; i < length; i++) {
      const item = items[i];
      const {
        file,
        icon,
        iconTitle,
        strikeThrough
      } = item;
      const baseName = pathBaseName(file);
      const folderName = file.slice(0, -baseName.length - 1);
      const actualDecorationIcon = getActualDecorationIcon(iconDefinitions, icon);
      displayItems.push({
        badgeCount: 0,
        decorationIcon: actualDecorationIcon,
        decorationIconTitle: iconTitle,
        decorationStrikeThrough: strikeThrough,
        detail: folderName,
        file,
        groupId: id,
        icon: getFileIcon({
          name: file
        }),
        label: baseName,
        posInSet: i + 1,
        setSize: length,
        type: File
      });
    }
  }
  return displayItems;
};

const getDisplayItems = (allGroups, expandedGroups, iconDefinitions) => {
  const displayItems = [];
  for (const group of allGroups) {
    const groupDisplayItems = getDisplayItemsGroup(group, expandedGroups, iconDefinitions);
    displayItems.push(...groupDisplayItems);
  }
  return displayItems;
};

const getIconType = direntType => {
  switch (direntType) {
    case Directory:
    case DirectoryExpanded:
      return 2;
    default:
      return 1;
  }
};

const getMissingIconRequests = (dirents, fileIconCache) => {
  const missingRequests = [];
  for (const dirent of dirents) {
    if (!(dirent.file in fileIconCache)) {
      missingRequests.push({
        name: dirent.label,
        type: getIconType(dirent.type)
      });
    }
  }
  return missingRequests;
};

const requestFileIcons = async requests => {
  const results = await invoke('IconTheme.getIcons', requests);
  return results;
};

const updateIconCache = (iconCache, missingRequests, newIcons) => {
  if (missingRequests.length === 0) {
    return iconCache;
  }
  const newFileIconCache = {
    ...iconCache
  };
  for (let i = 0; i < missingRequests.length; i++) {
    const request = missingRequests[i];
    const icon = newIcons[i];
    newFileIconCache[request.name] = icon;
  }
  return newFileIconCache;
};

const getFileIcons = async (dirents, fileIconCache) => {
  const missingRequests = getMissingIconRequests(dirents, fileIconCache);
  const newIcons = await requestFileIcons(missingRequests);
  const newFileIconCache = updateIconCache(fileIconCache, missingRequests, newIcons);
  return newFileIconCache;
};

const getFinalDeltaY = (height, itemHeight, itemsLength) => {
  const contentHeight = itemsLength * itemHeight;
  const finalDeltaY = Math.max(contentHeight - height, 0);
  return finalDeltaY;
};

const activateByEvent = (event, assetDir, platform) => {
  string(event);
  string(assetDir);
  number(platform);
  return activateByEvent$1(event, assetDir, platform);
};

const executeProvider = async ({
  assetDir,
  event,
  method,
  params,
  platform
}) => {
  await activateByEvent(event, assetDir, platform);
  // @ts-ignore
  const result = await invoke$1(method, ...params);
  return result;
};

const CommandExecute = 'ExtensionHostCommand.executeCommand';
const SourceControlAcceptInput = 'ExtensionHostSourceControl.acceptInput';
const SourceControlGetFileDecorations = 'ExtensionHostSourceControl.getFileDecorations';
const SourceControlGetEnabledProviderIds = 'ExtensionHostSourceControl.getEnabledProviderIds';
const SourceControlGetFileBefore = 'ExtensionHostSourceControl.getFileBefore';
const SourceControlGetGroups = 'ExtensionHostSourceControl.getGroups';

const acceptInput$2 = async (providerId, text, assetDir, platform) => {
  return executeProvider({
    assetDir,
    event: 'none',
    method: SourceControlAcceptInput,
    params: [providerId, text],
    platform
    // noProviderFoundMessage: 'No source control provider found',
  });
};
const getFileDecorations$1 = (providerId, uris, assetDir, platform) => {
  string(assetDir);
  number(platform);
  return executeProvider({
    assetDir,
    event: 'none',
    method: SourceControlGetFileDecorations,
    params: [providerId, uris],
    platform
  });
};
const getFileBefore$1 = (providerId, path, assetDir, platform) => {
  return executeProvider({
    assetDir,
    event: 'none',
    method: SourceControlGetFileBefore,
    params: [providerId, path],
    platform
    // noProviderFoundMessage: 'No source control provider found',
  });
};
const getGroups$2 = (providerId, path, assetDir, platform) => {
  return executeProvider({
    assetDir,
    event: 'none',
    method: SourceControlGetGroups,
    params: [providerId, path],
    platform
    // noProviderFoundMessage: 'No source control provider found',
  });
};
const getEnabledProviderIds$1 = (scheme, root, assetDir, platform) => {
  return executeProvider({
    assetDir,
    event: `onSourceControl:${scheme}`,
    method: SourceControlGetEnabledProviderIds,
    params: [scheme, root],
    platform
    // noProviderFoundMessage: 'No source control provider found',
  });
};
const getIconDefinitions$1 = async providerId => {
  // @ts-ignore
  const result = await invoke$1('ExtensionHostSourceControl.getIconDefinitions', providerId);
  return result;
};

const acceptInput$1 = (providerId, text, assetDir, platform) => {
  string(providerId);
  string(text);
  return acceptInput$2(providerId, text, assetDir, platform);
};
const getFileDecorations = (providerId, uris, assetDir, platform) => {
  return getFileDecorations$1(providerId, uris, assetDir, platform);
};
const getFileBefore = (providerId, file, assetDir, platform) => {
  return getFileBefore$1(providerId, file, assetDir, platform);
};
const getEnabledProviderIds = (scheme, root, assetDir, platform) => {
  string(scheme);
  string(root);
  return getEnabledProviderIds$1(scheme, root, assetDir, platform);
};
const getGroups$1 = (providerId, root, assetDir, platform) => {
  return getGroups$2(providerId, root, assetDir, platform);
};
const getIconDefinitions = async providerIds => {
  try {
    if (providerIds.length === 0) {
      return [];
    }
    return await getIconDefinitions$1(providerIds[0]);
  } catch {
    return [];
  }
};

const getGroups = async (enabledProviderIds, root, assetDir, platform) => {
  const allGroups = [];
  for (const providerId of enabledProviderIds) {
    const groups = await getGroups$1(providerId, root, assetDir, platform);
    allGroups.push(...groups);
  }
  return {
    allGroups,
    gitRoot: ''
  };
};

const getTextHeight = async (input, width, fontFamily, fontSize, fontWeight, letterSpacing, lineHeight, inputPadding) => {
  try {
    if (!input) {
      return lineHeight + inputPadding * 2;
    }
    const actualInput = input;
    // TODO line height could also be like 1.5
    const lineHeightPx = `${lineHeight}px`;
    // @ts-ignore
    const height = await invoke(`MeasureTextHeight.measureTextBlockHeight`, actualInput, fontFamily, fontSize, lineHeightPx, width);
    return height + inputPadding * 2;
  } catch {
    // fallback
    const lines = input.split('\n');
    const lineCount = lines.length;
    const inputHeight = lineCount * lineHeight + inputPadding * 2;
    return inputHeight;
  }
};

const getInputHeight = async (input, width, fontFamily, fontWeight, fontSize, letterSpacing, lineHeight, inputPadding) => {
  const height = await getTextHeight(input, width, fontFamily, fontSize, fontWeight, letterSpacing, lineHeight, inputPadding);
  return height;
};

const getListHeight = (itemsLength, itemHeight, maxHeight) => {
  number(itemsLength);
  number(itemHeight);
  number(maxHeight);
  if (itemsLength === 0) {
    return itemHeight;
  }
  const totalHeight = itemsLength * itemHeight;
  return Math.min(totalHeight, maxHeight);
};

// TODO optimize this function to return the minimum number
// of visible items needed, e.g. when not scrolled 5 items with
// 20px fill 100px but when scrolled 6 items are needed
const getNumberOfVisibleItems = (listHeight, itemHeight) => {
  return Math.ceil(listHeight / itemHeight) + 1;
};

const Disk = 'file';

const RE_PROTOCOL = /^([a-z-]+):\/\//;
const getProtocol = uri => {
  if (!uri) {
    return Disk;
  }
  const protocolMatch = uri.match(RE_PROTOCOL);
  if (protocolMatch) {
    return protocolMatch[1];
  }
  return Disk;
};

const emptySourceControlButtons = [];

const getContextId = (groupId, type) => {
  if (type === File) {
    return `${groupId}-item`;
  }
  return groupId;
};

const defaultIndent = 16; // 1rem = 16px

const getTreeItemIndent = type => {
  if (type === Directory || type === DirectoryExpanded) {
    return 0;
  }
  return defaultIndent;
};

const getVisibleSourceControlItems = (items, minLineY, maxLineY, actionsCache, fileIconCache) => {
  const visible = [];
  for (let i = minLineY; i < maxLineY; i++) {
    const item = items[i];
    const contextId = getContextId(item.groupId, item.type);
    const buttons = actionsCache[contextId] || emptySourceControlButtons;
    const fileIcon = fileIconCache[item.label] || '';
    const indent = getTreeItemIndent(item.type);
    visible.push({
      ...item,
      buttons,
      fileIcon,
      indent
    });
  }
  return visible;
};

const get$1 = key => {
  return getPreference(key);
};

const getExtensions = async () => {
  return invoke$1('Extensions.getExtensions');
};

const requestSourceActions = async () => {
  const extensions = await getExtensions();
  const newCache = Object.create(null);
  for (const extension of extensions) {
    if (extension && extension['source-control-actions']) {
      for (const [key, value] of Object.entries(extension['source-control-actions'])) {
        newCache[key] = value;
      }
    }
  }
  return newCache;
};

/* eslint-disable unicorn/no-array-reduce */
const restoreExpandedGroups = groups => {
  return groups.map(group => group.id).reduce((total, current) => {
    return {
      ...total,
      [current]: true
    };
  }, Object.create(null));
};

const getRestoredInputValue = savedState => {
  if (savedState && typeof savedState === 'object' && 'inputValue' in savedState && typeof savedState['inputValue'] === 'string') {
    return savedState.inputValue;
  }
  return '';
};
const restoreState = savedState => {
  const inputValue = getRestoredInputValue(savedState);
  return {
    inputValue
  };
};

const getScrollBarSize = (size, contentSize, minimumSliderSize) => {
  if (size >= contentSize) {
    return 0;
  }
  return Math.max(Math.round(size ** 2 / contentSize), minimumSliderSize);
};

const emptyObject = {};
const RE_PLACEHOLDER = /\{(PH\d+)\}/g;
const i18nString = (key, placeholders = emptyObject) => {
  if (placeholders === emptyObject) {
    return key;
  }
  const replacer = (match, rest) => {
    return placeholders[rest];
  };
  return key.replaceAll(RE_PLACEHOLDER, replacer);
};

const OpenChanges = 'Open Changes';
const OpenFile = 'Open File';
const OpenFileHead = 'Open File (HEAD)';
const DiscardChanges = 'Discard Changes';
const StageChanges = 'Stage Changes';
const AddToGitignore = 'Add to gitignore';
const RevealInExplorerView = 'Reveal in Explorer View';
const OpenContainingFolder = 'Open Containing Folder';
const ViewAsTree$1 = 'View As Tree';
const CommitAndPush$1 = 'Commit and Push';
const Refresh$2 = 'Refresh';
const MessageEnterToCommitOnMaster = `Message (Enter) to commit on 'master'`;
const SourceControlInput$1 = 'Source Control Input';

const openChanges = () => {
  return i18nString(OpenChanges);
};
const openFile = () => {
  return i18nString(OpenFile);
};
const openFileHead = () => {
  return i18nString(OpenFileHead);
};
const discardChanges = () => {
  return i18nString(DiscardChanges);
};
const stageChanges = () => {
  return i18nString(StageChanges);
};
const addToGitignore = () => {
  return i18nString(AddToGitignore);
};
const revealInExplorerView = () => {
  return i18nString(RevealInExplorerView);
};
const openContainingFolder = () => {
  return i18nString(OpenContainingFolder);
};
const viewAsTree$1 = () => {
  return i18nString(ViewAsTree$1);
};
const commitAndPush = () => {
  return i18nString(CommitAndPush$1);
};
const refresh$1 = () => {
  return i18nString(Refresh$2);
};
const messageEnterToCommitOnMaster = () => {
  return i18nString(MessageEnterToCommitOnMaster);
};
const sourceControlInput = () => {
  return i18nString(SourceControlInput$1);
};

const loadContent = async (state, savedState) => {
  const {
    fileIconCache,
    height,
    inputFontFamily,
    inputFontSize,
    inputFontWeight,
    inputLetterSpacing,
    inputLineHeight,
    inputPadding,
    itemHeight,
    minimumSliderSize,
    width,
    workspacePath
  } = state;
  const root = workspacePath;
  const scheme = getProtocol(root);
  const {
    inputValue
  } = restoreState(savedState);
  const {
    assetDir,
    platform
  } = state;
  const enabledProviderIds = await getEnabledProviderIds(scheme, root, assetDir, platform);
  const iconDefinitions = await getIconDefinitions(enabledProviderIds);
  const {
    allGroups,
    gitRoot
  } = await getGroups(enabledProviderIds, root, assetDir, platform);
  const expandedGroups = restoreExpandedGroups(allGroups);
  const displayItems = getDisplayItems(allGroups, expandedGroups, iconDefinitions);
  const actionsCache = await requestSourceActions();

  // TODO make preferences async and more functional
  const splitButtonEnabled = await get$1('sourceControl.splitButtonEnabled');
  const badgeCount = allGroups.reduce((sum, group) => sum + group.items.length, 0);
  const total = displayItems.length;
  const contentHeight = total * itemHeight;
  const listHeight = getListHeight(total, itemHeight, height);
  const scrollBarHeight = getScrollBarSize(height, contentHeight, minimumSliderSize);
  const numberOfVisible = getNumberOfVisibleItems(listHeight, itemHeight);
  const minLineY = 0;
  const maxLineY = Math.min(numberOfVisible, total);
  const newFileIconCache = await getFileIcons(displayItems, fileIconCache);
  const visibleItems = getVisibleSourceControlItems(displayItems, minLineY, maxLineY, actionsCache, newFileIconCache);
  const finalDeltaY = getFinalDeltaY(listHeight, itemHeight, total);
  const inputPlaceholder = messageEnterToCommitOnMaster();
  const inputBoxHeight = await getInputHeight(inputValue, width, inputFontFamily, inputFontSize, inputFontWeight, inputLetterSpacing, inputLineHeight, inputPadding);
  return {
    ...state,
    actionsCache,
    allGroups,
    badgeCount,
    decorationIcons: iconDefinitions,
    enabledProviderIds,
    fileIconCache: newFileIconCache,
    finalDeltaY,
    gitRoot,
    iconDefinitions,
    initial: false,
    inputBoxHeight,
    inputPlaceholder,
    inputValue,
    items: displayItems,
    maxLineY,
    root,
    scrollBarHeight,
    splitButtonEnabled,
    visibleItems
  };
};

const info = (...args) => {
  // @ts-ignore
  // eslint-disable-next-line no-console
  console.info(...args);
};
const warn = (...args) => {
  // @ts-ignore
  console.warn(...args);
};

const acceptInput = async state => {
  const {
    assetDir,
    enabledProviderIds,
    inputValue,
    platform
  } = state;
  if (enabledProviderIds.length === 0) {
    info('[ViewletSourceControl] no source control provider found');
    return state;
  }
  const providerId = enabledProviderIds[0];
  await acceptInput$1(providerId, inputValue, assetDir, platform);
  const newState = await loadContent(state, {});
  return {
    ...newState,
    inputValue: ''
  };
};

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

const create2 = (id, uri, x, y, width, height, workspacePath, platform, assetDir) => {
  const state = {
    actionsCache: Object.create(null),
    allGroups: [],
    assetDir,
    badgeCount: 0,
    decorationIcons: [],
    deltaY: 0,
    enabledProviderIds: [],
    expandedGroups: Object.create(null),
    fileIconCache: Object.create(null),
    finalDeltaY: 0,
    focus: 0,
    gitRoot: '',
    handleOffset: 0,
    headerHeight: 40,
    // TODO
    height,
    history: [],
    iconDefinitions: [],
    id,
    index: [],
    initial: true,
    inputBoxHeight: 30,
    inputBoxMaxHeight: 214,
    inputFontFamily: 'system-ui, Ubuntu, "Droid Sans", sans-serif',
    inputFontSize: 13,
    inputFontWeight: 400,
    inputLetterSpacing: 0,
    inputLineHeight: 20,
    inputPadding: 2,
    inputPlaceholder: '',
    inputSource: 0,
    inputValue: '',
    isVisible: true,
    itemHeight: 20,
    items: [],
    maxInputLines: 5,
    maxLineY: 0,
    merge: [],
    minimumSliderSize: 20,
    minLineY: 0,
    platform,
    providerId: '',
    root: '',
    scrollBarActive: false,
    scrollBarHeight: 0,
    splitButtonEnabled: false,
    untracked: [],
    viewMode: 1,
    visibleItems: [],
    width,
    workingTree: [],
    workspacePath,
    x,
    y
  };
  set(id, state, state);
};

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

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

const isEqual$1 = (oldState, newState) => {
  return oldState.allGroups === newState.allGroups && oldState.deltaY === newState.deltaY && oldState.items === newState.items && oldState.maxLineY === newState.maxLineY && oldState.minLineY === newState.minLineY && oldState.visibleItems === newState.visibleItems;
};

const RenderItems = 4;
const RenderFocusContext = 7;
const RenderValue = 8;
const RenderCss = 10;
const RenderIncremental = 11;

const isEqual = (oldState, newState) => {
  return newState.inputSource === User || oldState.inputValue === newState.inputValue;
};

const modules = [isEqual$1, isEqual, isEqual$3, isEqual$2];
const numbers = [RenderIncremental, RenderValue, RenderCss, RenderFocusContext];

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

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

const getBadgeCount = ({
  badgeCount
}) => {
  return badgeCount;
};

const getInfo = uid => {
  const {
    newState
  } = get(uid);
  return newState.allGroups;
};

const mergeClassNames = (...classNames) => {
  return classNames.filter(Boolean).join(' ');
};

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 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) => {
  const patches = [];
  // 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;
  }
  // 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 (!(key in newNode)) {
      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 diffChildren = (oldChildren, newChildren, patches) => {
  const maxLength = Math.max(oldChildren.length, newChildren.length);
  // Track where we are: -1 means at parent, >= 0 means at child index
  let currentChildIndex = -1;
  // Collect indices of children to remove (we'll add these patches at the end in reverse order)
  const indicesToRemove = [];
  for (let i = 0; i < maxLength; i++) {
    const oldNode = oldChildren[i];
    const newNode = newChildren[i];
    if (!oldNode && !newNode) {
      continue;
    }
    if (!oldNode) {
      // Add new node - we should be at the parent
      if (currentChildIndex >= 0) {
        // Navigate back to parent
        patches.push({
          type: NavigateParent
        });
        currentChildIndex = -1;
      }
      // Flatten the entire subtree so renderInternal can handle it
      const flatNodes = treeToArray(newNode);
      patches.push({
        type: Add,
        nodes: flatNodes
      });
    } else if (newNode) {
      // Compare nodes to see if we need any patches
      const nodePatches = compareNodes(oldNode.node, newNode.node);
      // If nodePatches is null, the node types are incompatible - need to replace
      if (nodePatches === null) {
        // Navigate to this child
        if (currentChildIndex === -1) {
          patches.push({
            type: NavigateChild,
            index: i
          });
          currentChildIndex = i;
        } else if (currentChildIndex !== i) {
          patches.push({
            type: NavigateSibling,
            index: i
          });
          currentChildIndex = i;
        }
        // Replace the entire subtree
        const flatNodes = treeToArray(newNode);
        patches.push({
          type: Replace,
          nodes: flatNodes
        });
        // After replace, we're at the new element (same position)
        continue;
      }
      // Check if we need to recurse into children
      const hasChildrenToCompare = oldNode.children.length > 0 || newNode.children.length > 0;
      // Only navigate to this element if we need to do something
      if (nodePatches.length > 0 || hasChildrenToCompare) {
        // Navigate to this child if not already there
        if (currentChildIndex === -1) {
          patches.push({
            type: NavigateChild,
            index: i
          });
          currentChildIndex = i;
        } else if (currentChildIndex !== i) {
          patches.push({
            type: NavigateSibling,
            index: i
          });
          currentChildIndex = i;
        }
        // Apply node patches (these apply to the current element, not children)
        if (nodePatches.length > 0) {
          patches.push(...nodePatches);
        }
        // Compare children recursively
        if (hasChildrenToCompare) {
          diffChildren(oldNode.children, newNode.children, patches);
        }
      }
    } else {
      // Remove old node - collect the index for later removal
      indicesToRemove.push(i);
    }
  }
  // Navigate back to parent if we ended at a child
  if (currentChildIndex >= 0) {
    patches.push({
      type: NavigateParent
    });
    currentChildIndex = -1;
  }
  // Add remove patches in reverse order (highest index first)
  // This ensures indices remain valid as we remove
  for (let j = indicesToRemove.length - 1; j >= 0; j--) {
    patches.push({
      type: RemoveChild,
      index: indicesToRemove[j]
    });
  }
};
const diffTrees = (oldTree, newTree, patches, path) => {
  // At the root level (path.length === 0), we're already AT the element
  // So we compare the root node directly, then compare its children
  if (path.length === 0 && oldTree.length === 1 && newTree.length === 1) {
    const oldNode = oldTree[0];
    const newNode = newTree[0];
    // Compare root nodes
    const nodePatches = compareNodes(oldNode.node, newNode.node);
    // If nodePatches is null, the root node types are incompatible - need to replace
    if (nodePatches === null) {
      const flatNodes = treeToArray(newNode);
      patches.push({
        type: Replace,
        nodes: flatNodes
      });
      return;
    }
    if (nodePatches.length > 0) {
      patches.push(...nodePatches);
    }
    // Compare children
    if (oldNode.children.length > 0 || newNode.children.length > 0) {
      diffChildren(oldNode.children, newNode.children, patches);
    }
  } else {
    // Non-root level or multiple root elements - use the regular comparison
    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 getKeyBindings = () => {
  return [{
    command: 'Source Control.acceptInput',
    key: CtrlCmd | Enter,
    when: FocusSourceControlInput
  }];
};

const getMenuEntries = () => {
  return [{
    command: /* TODO */'-1',
    flags: None,
    id: '',
    label: openChanges()
  }, {
    command: /* TODO */'-1',
    flags: None,
    id: '',
    label: openFile()
  }, {
    command: /* TODO */'-1',
    flags: None,
    id: '',
    label: openFileHead()
  }, {
    command: /* TODO */'-1',
    flags: None,
    id: '',
    label: discardChanges()
  }, {
    command: /* TODO */'-1',
    flags: None,
    id: '',
    label: stageChanges()
  }, {
    command: /* TODO */'-1',
    flags: None,
    id: '',
    label: addToGitignore()
  }, {
    command: /* TODO */'-1',
    flags: None,
    id: '',
    label: revealInExplorerView()
  }, {
    command: /* TODO */'-1',
    flags: None,
    id: '',
    label: openContainingFolder()
  }];
};

const getMenuEntries2 = state => {
  return getMenuEntries();
};

const getMenuIds = () => {
  return [SourceControl$1];
};

const SourceControlInput = 'SourceControlInput';
const ViewAsTree = 'ViewAsTree';
const CommitAndPush = 'CommitAndPush';
const Refresh$1 = 'Refresh';

const refresh = async state => {
  const {
    actionsCache,
    assetDir,
    enabledProviderIds,
    fileIconCache,
    height,
    iconDefinitions,
    itemHeight,
    minimumSliderSize,
    platform,
    root,
    splitButtonEnabled
  } = state;
  const {
    allGroups,
    gitRoot
  } = await getGroups(enabledProviderIds, root, assetDir, platform);
  const expandedGroups = restoreExpandedGroups(allGroups);
  const displayItems = getDisplayItems(allGroups, expandedGroups, iconDefinitions);
  const badgeCount = allGroups.reduce((sum, group) => sum + group.items.length, 0);
  const total = displayItems.length;
  const contentHeight = total * itemHeight;
  const listHeight = getListHeight(total, itemHeight, height);
  const scrollBarHeight = getScrollBarSize(height, contentHeight, minimumSliderSize);
  const numberOfVisible = getNumberOfVisibleItems(listHeight, itemHeight);
  const minLineY = 0;
  const maxLineY = Math.min(numberOfVisible, total);
  const newFileIconCache = await getFileIcons(displayItems, fileIconCache);
  const visibleItems = getVisibleSourceControlItems(displayItems, minLineY, maxLineY, actionsCache, newFileIconCache);
  const finalDeltaY = getFinalDeltaY(listHeight, itemHeight, total);
  return {
    ...state,
    actionsCache,
    allGroups,
    badgeCount,
    enabledProviderIds,
    fileIconCache: newFileIconCache,
    finalDeltaY,
    gitRoot,
    items: displayItems,
    maxLineY,
    scrollBarHeight,
    splitButtonEnabled,
    visibleItems
  };
};

const viewAsTree = state => {
  return {
    ...state,
    viewMode: Tree
  };
};

const handleActionClick = async (state, actionName) => {
  switch (actionName) {
    case CommitAndPush:
      warn(`[source-control-worker] CommitAndPush action not yet implemented`);
      return state;
    case Refresh$1:
      return refresh(state);
    case ViewAsTree:
      return viewAsTree(state);
    default:
      warn(`[source-control-worker] Unknown action name: ${actionName}`);
      return state;
  }
};

const executeCommand = (id, assetDir, platform, ...args) => {
  return executeProvider({
    assetDir,
    event: `onCommand:${id}`,
    method: CommandExecute,
    params: [id, ...args],
    platform
  });
};

const handleButtonClick = async (state, clickedIndex) => {
  const {
    visibleItems
  } = state;
  const item = visibleItems[clickedIndex];
  const button = item.buttons[clickedIndex];
  if (!button) {
    return state;
  }
  await executeCommand(button.command, state.assetDir, state.platform, item.file);
  const newState = await loadContent(state, {});
  return newState;
};

const getIndex = (state, eventX, eventY) => {
  const {
    headerHeight,
    itemHeight,
    y
  } = state;
  const relativeY = eventY - y - headerHeight;
  const index = Math.floor(relativeY / itemHeight);
  return index;
};

const handleClickSourceControlButtons = async (state, index, name) => {
  const {
    visibleItems
  } = state;
  const item = visibleItems[index];
  if (!item) {
    return state;
  }
  const {
    buttons
  } = item;
  const button = buttons.find(button => button.label === name);
  if (!button) {
    warn(`[source-control-worker] Button not found ${name}`);
    return state;
  }
  const {
    file
  } = item;
  await executeCommand(button.command, state.assetDir, state.platform, file);
  const newState = await refresh(state);
  return newState;
};

const updateVisibleItems = async (state, expandedGroups) => {
  const {
    actionsCache,
    allGroups,
    fileIconCache,
    height,
    iconDefinitions,
    itemHeight
  } = state;
  const displayItems = getDisplayItems(allGroups, expandedGroups, iconDefinitions);
  const badgeCount = allGroups.reduce((sum, group) => sum + group.items.length, 0);
  const total = displayItems.length;
  const listHeight = getListHeight(total, itemHeight, height);
  const numberOfVisible = getNumberOfVisibleItems(listHeight, itemHeight);
  const minLineY = 0;
  const maxLineY = Math.min(numberOfVisible, total);
  const visibleItems = getVisibleSourceControlItems(displayItems, minLineY, maxLineY, actionsCache, fileIconCache);
  return {
    ...state,
    badgeCount,
    expandedGroups,
    items: displayItems,
    maxLineY,
    minLineY,
    visibleItems
  };
};

const handleClickDirectory = async (state, item) => {
  const {
    expandedGroups
  } = state;
  const newExpandedGroups = {
    ...expandedGroups,
    [item.groupId]: true
  };
  return updateVisibleItems(state, newExpandedGroups);
};

const handleClickDirectoryExpanded = async (state, item) => {
  const {
    expandedGroups
  } = state;
  const newExpandedGroups = {
    ...expandedGroups,
    [item.groupId]: false
  };
  return updateVisibleItems(state, newExpandedGroups);
};

const readFile = async (uri, encoding = 'utf8') => {
  const content = await readFile$1(uri);
  return content;
};

const openUri = uri => {
  return openUri$1(uri);
};

const openDiffEditor = async (before, afterPath, width) => {
  // TODO handle error
  // TODO should only pass uris to diff editor, diff editor should then resolve file contents
  {
    await openUri(`inline-diff://data://${before}<->${afterPath}`);
  }
};

const handleClickFile = async (state, item) => {
  const {
    assetDir,
    enabledProviderIds,
    platform,
    root
  } = state;
  const providerId = enabledProviderIds[0];
  const absolutePath = `${root}/${item.file}`;
  // TODO handle error
  const [fileBefore] = await Promise.all([getFileBefore(providerId, item.file, assetDir, platform), readFile(absolutePath)]);

  // TODO diff editor should determine width by itself
  await openDiffEditor(fileBefore, absolutePath);
  return state;
};

const selectIndex = async (state, index) => {
  const {
    items
  } = state;
  if (index < 0 || index >= items.length) {
    return state;
  }
  const item = items[index];
  switch (item.type) {
    case Directory:
      return handleClickDirectory(state, item);
    case DirectoryExpanded:
      return handleClickDirectoryExpanded(state, item);
    case File:
      return handleClickFile(state, item);
    default:
      warn(`unknown item type: ${item.type}`);
      return state;
  }
};

const handleClickAt = async (state, eventX, eventY, name) => {
  const index = getIndex(state, eventX, eventY);
  if (name) {
    return handleClickSourceControlButtons(state, index, name);
  }
  return selectIndex(state, index);
};

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

const handleContextMenu = async (state, button, x, y) => {
  const {
    id
  } = state;
  await show2(id, SourceControl$1, x, y, {
    menuId: SourceControl$1
  });
  return state;
};

const handleInputFocus = async state => {
  return {
    ...state,
    focus: FocusSourceControlInput,
    inputSource: Script
  };
};

const handleInput = async (state, value, inputSource = User) => {
  const {
    inputFontFamily,
    inputFontSize,
    inputFontWeight,
    inputLetterSpacing,
    inputLineHeight,
    inputPadding,
    width
  } = state;
  const inputBoxHeight = await getInputHeight(value, width, inputFontFamily, inputFontWeight, inputFontSize, inputLetterSpacing, inputLineHeight, inputPadding);
  return {
    ...state,
    inputBoxHeight,
    inputSource,
    inputValue: value
  };
};

const handleInputBlur = async state => {
  // TODO reset focus
  return state;
};

const handleMessagePort = async port => {
  await PlainMessagePortRpc.create({
    commandMap: {},
    messagePort: port
  });
};

const handleMouseOut = (state, index) => {
  const {
    items
  } = state;
  if (index === -1 || index > items.length) {
    return {
      ...state
    };
  }
  return state;
};

const handleMouseOutAt = (state, eventX, eventY) => {
  const index = getIndex(state, eventX, eventY);
  return handleMouseOut(state, index);
};

const handleMouseOver = async (state, index) => {
  const {
    items
  } = state;
  const item = items[index];
  if (!item) {
    return state;
  }
  return {
    ...state
  };
};

const handleMouseOverAt = async (state, eventX, eventY) => {
  const index = getIndex(state, eventX, eventY);
  return handleMouseOver(state, index);
};

const setDeltaY = async (state, newDeltaY) => {
  const {
    actionsCache,
    fileIconCache,
    headerHeight,
    height,
    itemHeight,
    items
  } = state;
  const normalizedDeltaY = Math.max(newDeltaY, 0);
  const newMinLineY = Math.floor(normalizedDeltaY / itemHeight);
  const total = items.length;
  const listHeight = height - headerHeight;
  const visibleCount = getNumberOfVisibleItems(listHeight, itemHeight);
  const maxLineY = Math.min(newMinLineY + visibleCount, total);
  const visible = getVisibleSourceControlItems(items, newMinLineY, maxLineY, actionsCache, fileIconCache);
  return {
    ...state,
    deltaY: newDeltaY,
    maxLineY,
    minLineY: newMinLineY,
    visibleItems: visible
  };
};

const handleWheel = async (state, deltaMode, deltaY) => {
  return setDeltaY(state, state.deltaY + deltaY);
};

const handleWorkspaceRefresh = async state => {
  return refresh(state);
};

const sendMessagePortToExtensionHostWorker = async port => {
  await sendMessagePortToExtensionHostWorker$1(port, SourceControlWorker);
};

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

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

const createTextMeasurementWorkerRpc = async () => {
  try {
    const rpc = await TransferMessagePortRpcParent.create({
      commandMap: {},
      send: sendMessagePortToTextMeasurementWorker
    });
    return rpc;
  } catch (error) {
    throw new VError(error, `Failed to create text measurement worker rpc`);
  }
};

const createExtensionManagementWorkerRpc = async () => {
  try {
    const rpc = await TransferMessagePortRpcParent.create({
      commandMap: {},
      send: port => sendMessagePortToExtensionManagementWorker(port, 0)
    });
    return rpc;
  } catch (error) {
    throw new VError(error, `Failed to create extension management rpc`);
  }
};

const initializeExtensionManagementWorker = async () => {
  try {
    const rpc = await createExtensionManagementWorkerRpc();
    set$3(rpc);
  } catch {
    // ignore
  }
};

const initialize = async () => {
  const [extensionHostRpc, textRpc] = await Promise.all([createExtensionHostRpc(), createTextMeasurementWorkerRpc(), initializeExtensionManagementWorker()]);
  set$4(extensionHostRpc);
  set$1(textRpc);
};

const getUnique = items => {
  const seens = [];
  for (const item of items) {
    if (!seens.includes(item)) {
      seens.push(item);
    }
  }
  return seens;
};

const getIndentRule = indent => {
  return `.Indent-${indent} {
  padding-left: ${indent}px;
}`;
};
const renderCss = (oldState, newState) => {
  const {
    id,
    inputBoxHeight,
    visibleItems
  } = newState;
  const indents = visibleItems.map(item => item.indent);
  const uniqueIndents = getUnique(indents);
  const indentRules = uniqueIndents.map(getIndentRule).join('\n');
  const css = indentRules ? `:root {
  --SourceControlInputHeight: ${inputBoxHeight}px;
}
${indentRules}
` : `:root {
  --SourceControlInputHeight: ${inputBoxHeight}px;
}
`;
  return [SetCss, id, css];
};

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

const Actions = 'Actions';
const SourceControlButtons = 'SourceControlButtons';
const Grow = 'Grow';
const Chevron = 'Chevron';
const ChevronRight = 'ChevronRight';
const DecorationIcon = 'DecorationIcon';
const FileIcon = 'FileIcon';
const IconButton = 'IconButton';
const InputBox = 'InputBox';
const Label = 'Label';
const LabelDetail = 'LabelDetail';
const MaskIcon = 'MaskIcon';
const MaskIconChevronDown = 'MaskIconChevronDown';
const SourceControl = 'SourceControl';
const SourceControlButton = 'SourceControlButton';
const SourceControlHeader = 'SourceControlHeader';
const SourceControlItems = 'SourceControlItems';
const SplitButton = 'SplitButton';
const SplitButtonContent = 'SplitButtonContent';
const SplitButtonContentDisabled = 'SplitButtonContentDisabled';
const SplitButtonDisabled = 'SplitButtonDisabled';
const SplitButtonDropDown = 'SplitButtonDropDown';
const SplitButtonDropDownDisabled = 'SplitButtonDropDownDisabled';
const SplitButtonSeparator = 'SplitButtonSeparator';
const StrikeThrough = 'StrikeThrough';
const TreeItem = 'TreeItem';
const Viewlet = 'Viewlet';

const HandleClickAt = 1;
const HandleContextMenu = 2;
const HandleFocus = 3;
const HandleInput = 4;
const HandleMouseOutAt = 6;
const HandleMouseOver = 7;
const HandleMouseOverAt = 8;
const HandleWheel = 9;
const HandleClickAction = 10;

const getSourceControlInputDom = inputPlaceholder => {
  return [{
    ariaLabel: sourceControlInput(),
    autocapitalize: 'off',
    autocorrect: 'off',
    childCount: 0,
    className: mergeClassNames(InputBox, 'MultilineInputBox'),
    name: SourceControlInput,
    onFocus: HandleFocus,
    onInput: HandleInput,
    placeholder: inputPlaceholder,
    spellcheck: false,
    type: TextArea
  }];
};

const getSourceControlHeaderVirtualDom = inputPlaceholder => {
  return [{
    childCount: 1,
    className: SourceControlHeader,
    type: Div
  }, ...getSourceControlInputDom(inputPlaceholder)];
};

const className$1 = mergeClassNames(Badge, SourceControlBadge);
const parentNode = {
  childCount: 1,
  className: className$1,
  type: Div
};
const getBadgeVirtualDom = count => {
  return [parentNode, text(`${count}`)];
};

const getIconVirtualDom = (icon, type = Div) => {
  return {
    childCount: 0,
    className: `MaskIcon MaskIcon${icon}`,
    role: None$1,
    type
  };
};

const getButtonVirtualDom = button => {
  const {
    icon,
    label
  } = button;
  return [{
    ariaLabel: label,
    childCount: 1,
    className: SourceControlButton,
    name: label,
    title: label,
    type: Button$2
  }, getIconVirtualDom(icon, Span)];
};

const getButtonsVirtualDom = buttons => {
  if (buttons === emptySourceControlButtons) {
    return [];
  }
  return [{
    childCount: buttons.length,
    className: SourceControlButtons,
    type: Div
  }, ...buttons.flatMap(getButtonVirtualDom)];
};

const classNameDefault = mergeClassNames(Label, Grow);
const classNameStrikeThrough = mergeClassNames(classNameDefault, StrikeThrough);
const getLabelClassName = decorationStrikeThrough => {
  if (decorationStrikeThrough) {
    return classNameStrikeThrough;
  }
  return classNameDefault;
};

const getTreeItemClassName = indent => {
  let className = TreeItem;
  className = mergeClassNames(className, `Indent-${indent}`);
  return className;
};

const PaddingRight = '12px';

const createItemDirectory = item => {
  const {
    badgeCount,
    buttons,
    decorationStrikeThrough,
    icon,
    indent,
    label,
    posInSet,
    setSize,
    type
  } = item;
  const labelClassName = getLabelClassName(decorationStrikeThrough);
  const buttonsDom = getButtonsVirtualDom(buttons);
  const hasButtons = buttons.length;
  const treeItemClassName = getTreeItemClassName(indent);
  return [{
    ariaExpanded: type === DirectoryExpanded,
    ariaPosInSet: posInSet,
    ariaSetSize: setSize,
    childCount: 3 + (hasButtons ? 1 : 0),
    className: treeItemClassName,
    paddingRight: PaddingRight,
    role: TreeItem$1,
    type: Div
  }, {
    childCount: 0,
    className: mergeClassNames(Chevron, `MaskIcon${icon}`),
    type: Div
  }, {
    childCount: 1,
    className: labelClassName,
    type: Div
  }, text(label), ...buttonsDom, ...getBadgeVirtualDom(badgeCount)];
};

const getFileIconVirtualDom = icon => {
  return {
    childCount: 0,
    className: FileIcon,
    role: None$1,
    src: icon,
    type: Img
  };
};

const chevron = {
  childCount: 1,
  className: Chevron,
  type: Div
};
const getIconsDom = (icon, fileIcon) => {
  if (icon === ChevronRight) {
    return [chevron, getIconVirtualDom(icon)];
  }
  return [getFileIconVirtualDom(fileIcon)];
};
const createItemOther = item => {
  const {
    buttons,
    decorationIcon,
    decorationIconTitle,
    decorationStrikeThrough,
    detail,
    file,
    fileIcon,
    icon,
    indent,
    label,
    posInSet,
    setSize
  } = item;
  const labelClassName = getLabelClassName(decorationStrikeThrough);
  const dom = [];
  const hasButtons = buttons.length;
  const buttonsDom = getButtonsVirtualDom(buttons);
  const treeItemClassName = getTreeItemClassName(indent);
  dom.push({
    ariaPosInSet: posInSet,
    ariaSetSize: setSize,
    childCount: 3 + (hasButtons ? 1 : 0),
    className: treeItemClassName,
    paddingRight: '12px',
    role: TreeItem$1,
    title: file,
    type: Div
  }, ...getIconsDom(icon, fileIcon));
  const labelDom = {
    childCount: 1,
    className: labelClassName,
    type: Div
  };
  dom.push(labelDom, text(label));
  if (detail) {
    labelDom.childCount++;
    dom.push({
      childCount: 1,
      className: LabelDetail,
      type: Span
    }, text(detail));
  }
  dom.push(...buttonsDom);
  dom.push({
    childCount: 0,
    className: DecorationIcon,
    src: decorationIcon,
    title: decorationIconTitle,
    type: Img
  });
  return dom;
};

const getSourceControlItemVirtualDom = item => {
  switch (item.type) {
    case Directory:
    case DirectoryExpanded:
      return createItemDirectory(item);
    default:
      return createItemOther(item);
  }
};

const getSourceControlListVirtualDom = items => {
  return [{
    childCount: items.length,
    className: SourceControlItems,
    onClick: HandleClickAt,
    onPointerOut: HandleMouseOutAt,
    onPointerOver: HandleMouseOverAt,
    role: Tree$1,
    type: Div
  }, ...items.flatMap(getSourceControlItemVirtualDom)];
};

const getSplitButtonVirtualDom = (hasItems, splitButtonEnabled, buttonText) => {
  if (!splitButtonEnabled || !hasItems) {
    return [];
  }
  return [{
    childCount: 3,
    className: mergeClassNames(SplitButton, hasItems ? '' : SplitButtonDisabled),
    type: Div
  }, {
    childCount: 1,
    className: mergeClassNames(SplitButtonContent, hasItems ? '' : SplitButtonContentDisabled),
    tabIndex: 0,
    type: Div
  }, text(buttonText), {
    childCount: 0,
    className: SplitButtonSeparator,
    type: Div
  }, {
    childCount: 1,
    className: mergeClassNames(SplitButtonDropDown, hasItems ? '' : SplitButtonDropDownDisabled),
    tabIndex: 0,
    type: Div
  }, {
    childCount: 0,
    className: mergeClassNames(MaskIcon, MaskIconChevronDown),
    type: Div
  }];
};

const className = mergeClassNames(Viewlet, SourceControl);
const getSourceControlVirtualDom = (items, splitButtonEnabled, inputPlaceholder) => {
  const hasItems = items.length > 0;
  const dom = [{
    childCount: splitButtonEnabled ? 3 : 2,
    className: className,
    onContextMenu: HandleContextMenu,
    onMouseOver: HandleMouseOver,
    // onMouseOut: DomEventListenerFunctions.HandleMouseOut,
    onWheel: HandleWheel,
    tabIndex: 0,
    type: Div
  }, ...getSourceControlHeaderVirtualDom(inputPlaceholder), ...getSplitButtonVirtualDom(hasItems, splitButtonEnabled, 'Commit'), ...getSourceControlListVirtualDom(items)];
  return dom;
};

const renderItems = (oldState, newState) => {
  const {
    id,
    initial,
    inputPlaceholder,
    splitButtonEnabled,
    visibleItems
  } = newState;
  if (initial) {
    return [SetDom2, id, []];
  }
  const dom = getSourceControlVirtualDom(visibleItems, splitButtonEnabled, inputPlaceholder);
  return [SetDom2, id, dom];
};

const renderIncremental = (oldState, newState) => {
  const oldDom = renderItems(oldState, oldState)[2];
  const newDom = renderItems(newState, newState)[2];
  const patches = diffTree(oldDom, newDom);
  const {
    id
  } = newState;
  return ['Viewlet.setPatches', id, patches];
};

const renderValue = (oldState, newState) => {
  const {
    id,
    inputValue
  } = newState;
  return [SetValueByName, id, SourceControlInput, inputValue];
};

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

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

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

const Button = 1;

const Check = 'Check';
const ListFlat = 'ListFlat';
const Refresh = 'Refresh';

const getActions = () => {
  return [{
    command: '',
    icon: ListFlat,
    id: viewAsTree$1(),
    name: ViewAsTree,
    type: Button
  }, {
    command: '',
    icon: Check,
    id: commitAndPush(),
    name: CommitAndPush,
    type: Button
  }, {
    command: '',
    icon: Refresh,
    id: refresh$1(),
    name: Refresh$1,
    type: Button
  }];
};

const getActionButtonVirtualDom = action => {
  const {
    icon,
    id,
    label
  } = action;
  return [{
    childCount: 1,
    className: IconButton,
    name: label,
    title: id,
    type: Button$2
  }, getIconVirtualDom(icon)];
};

const getActionVirtualDom = action => {
  switch (action.type) {
    case Button:
      {
        const actionButton = {
          icon: action.icon,
          id: action.id,
          label: action.name
        };
        return getActionButtonVirtualDom(actionButton);
      }
    default:
      return [];
  }
};

const getActionsVirtualDom = actions => {
  return [{
    childCount: actions.length,
    className: Actions,
    onClick: HandleClickAction,
    role: ToolBar,
    type: Div
  }, ...actions.flatMap(getActionVirtualDom)];
};

const renderActions = state => {
  const actions = getActions();
  const dom = getActionsVirtualDom(actions);
  return dom;
};

const renderEventListeners = () => {
  return [{
    name: HandleWheel,
    params: ['handleWheel', DeltaMode, DeltaY],
    passive: true
  }, {
    name: HandleFocus,
    params: ['handleFocus']
  }, {
    name: HandleClickAt,
    params: ['handleClickAt', ClientX, ClientY, TargetName]
  }, {
    name: HandleMouseOverAt,
    params: ['handleMouseOverAt', ClientX, ClientY]
  }, {
    name: HandleMouseOver,
    params: ['handleMouseOver', ClientX, ClientY]
  }, {
    name: HandleMouseOutAt,
    params: ['handleMouseOutAt', ClientX, ClientY]
  }, {
    name: HandleInput,
    params: ['handleInput', TargetValue]
  }, {
    name: HandleContextMenu,
    params: ['handleContextMenu', Button$1, ClientX, ClientY],
    preventDefault: true
  }, {
    name: HandleWheel,
    params: ['handleWheel', DeltaMode, DeltaY],
    passive: true
  }, {
    name: HandleClickAction,
    params: ['handleActionClick', TargetName]
  }];
};

const saveState = uid => {
  number(uid);
  const value = get(uid);
  const {
    newState
  } = value;
  const {
    expandedGroups,
    inputValue,
    maxLineY,
    root
  } = newState;
  return {
    deltaY: 0,
    expandedGroups,
    inputValue,
    maxLineY,
    minLineY: 0,
    root
  };
};

const updateIcons = async state => {
  const {
    items,
    maxLineY,
    minLineY
  } = state;
  const visible = items.slice(minLineY, maxLineY);
  const newFileIconCache = await getFileIcons(visible, Object.create(null));
  // TODO update visible items
  return {
    ...state,
    fileIconCache: newFileIconCache
  };
};

const viewAsList = state => {
  return {
    ...state,
    viewMode: List
  };
};

const commandMap = {
  'Initialize.initialize': initialize,
  'SourceControl.acceptInput': wrapCommand(acceptInput),
  'SourceControl.create2': create2,
  'SourceControl.diff2': diff2,
  'SourceControl.getBadgeCount': wrapGetter(getBadgeCount),
  'SourceControl.getCommandIds': getCommandIds,
  'SourceControl.getEnabledProviderIds': getEnabledProviderIds,
  'SourceControl.getFileDecorations': getFileDecorations,
  'SourceControl.getInfo': getInfo,
  'SourceControl.getKeyBindings': getKeyBindings,
  'SourceControl.getMenuEntries2': wrapGetter(getMenuEntries2),
  'SourceControl.getMenuIds': getMenuIds,
  'SourceControl.handleActionClick': wrapCommand(handleActionClick),
  'SourceControl.handleButtonClick': wrapCommand(handleButtonClick),
  'SourceControl.handleClickAt': wrapCommand(handleClickAt),
  'SourceControl.handleClickSourceControlButtons': wrapCommand(handleClickSourceControlButtons),
  'SourceControl.handleContextMenu': wrapCommand(handleContextMenu),
  'SourceControl.handleFocus': wrapCommand(handleInputFocus),
  'SourceControl.handleInput': wrapCommand(handleInput),
  'SourceControl.handleInputBlur': wrapCommand(handleInputBlur),
  'SourceControl.handleMessagePort': handleMessagePort,
  'SourceControl.handleMouseOut': wrapCommand(handleMouseOut),
  'SourceControl.handleMouseOutAt': wrapCommand(handleMouseOutAt),
  'SourceControl.handleMouseOver': wrapCommand(handleMouseOver),
  'SourceControl.handleMouseOverAt': wrapCommand(handleMouseOverAt),
  'SourceControl.handleWheel': wrapCommand(handleWheel),
  'SourceControl.handleWorkspaceRefresh': wrapCommand(handleWorkspaceRefresh),
  'SourceControl.loadContent': wrapCommand(loadContent),
  'SourceControl.refresh': wrapCommand(refresh),
  'SourceControl.render2': render2,
  'SourceControl.renderActions': wrapGetter(renderActions),
  'SourceControl.renderActions2': renderActions,
  'SourceControl.renderEventListeners': renderEventListeners,
  'SourceControl.saveState': saveState,
  'SourceControl.selectIndex': wrapCommand(selectIndex),
  'SourceControl.setDeltaY': wrapCommand(setDeltaY),
  'SourceControl.terminate': terminate,
  'SourceControl.updateIcons': wrapCommand(updateIcons),
  'SourceControl.viewAsList': wrapCommand(viewAsList),
  'SourceControl.viewAsTree': wrapCommand(viewAsTree)
};

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

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

main();
