var __getOwnPropNames = Object.getOwnPropertyNames;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
import require$$0$2 from "node:util";
import require$$0 from "util";
import require$$1 from "path";
import require$$2 from "os";
import require$$3 from "crypto";
import require$$4 from "net";
import require$$0$1 from "url";
import require$$2$1 from "fs";
import require$$3$1 from "child_process";
import * as fs from "node:fs";
var require_main = __commonJS({
  "main.js"(exports, module) {
    var main$3 = {};
    var is$3 = {};
    var hasRequiredIs$3;
    function requireIs$3() {
      if (hasRequiredIs$3) return is$3;
      hasRequiredIs$3 = 1;
      Object.defineProperty(is$3, "__esModule", { value: true });
      is$3.thenable = is$3.typedArray = is$3.stringArray = is$3.array = is$3.func = is$3.error = is$3.number = is$3.string = is$3.boolean = void 0;
      function boolean(value) {
        return value === true || value === false;
      }
      is$3.boolean = boolean;
      function string(value) {
        return typeof value === "string" || value instanceof String;
      }
      is$3.string = string;
      function number(value) {
        return typeof value === "number" || value instanceof Number;
      }
      is$3.number = number;
      function error(value) {
        return value instanceof Error;
      }
      is$3.error = error;
      function func(value) {
        return typeof value === "function";
      }
      is$3.func = func;
      function array(value) {
        return Array.isArray(value);
      }
      is$3.array = array;
      function stringArray(value) {
        return array(value) && value.every((elem) => string(elem));
      }
      is$3.stringArray = stringArray;
      function typedArray(value, check) {
        return Array.isArray(value) && value.every(check);
      }
      is$3.typedArray = typedArray;
      function thenable(value) {
        return value && func(value.then);
      }
      is$3.thenable = thenable;
      return is$3;
    }
    var server = {};
    var main$2 = {};
    var main$1 = {};
    var ril = {};
    var api$2 = {};
    var messages$1 = {};
    var is$2 = {};
    var hasRequiredIs$2;
    function requireIs$2() {
      if (hasRequiredIs$2) return is$2;
      hasRequiredIs$2 = 1;
      Object.defineProperty(is$2, "__esModule", { value: true });
      is$2.stringArray = is$2.array = is$2.func = is$2.error = is$2.number = is$2.string = is$2.boolean = void 0;
      function boolean(value) {
        return value === true || value === false;
      }
      is$2.boolean = boolean;
      function string(value) {
        return typeof value === "string" || value instanceof String;
      }
      is$2.string = string;
      function number(value) {
        return typeof value === "number" || value instanceof Number;
      }
      is$2.number = number;
      function error(value) {
        return value instanceof Error;
      }
      is$2.error = error;
      function func(value) {
        return typeof value === "function";
      }
      is$2.func = func;
      function array(value) {
        return Array.isArray(value);
      }
      is$2.array = array;
      function stringArray(value) {
        return array(value) && value.every((elem) => string(elem));
      }
      is$2.stringArray = stringArray;
      return is$2;
    }
    var hasRequiredMessages$1;
    function requireMessages$1() {
      if (hasRequiredMessages$1) return messages$1;
      hasRequiredMessages$1 = 1;
      Object.defineProperty(messages$1, "__esModule", { value: true });
      messages$1.Message = messages$1.NotificationType9 = messages$1.NotificationType8 = messages$1.NotificationType7 = messages$1.NotificationType6 = messages$1.NotificationType5 = messages$1.NotificationType4 = messages$1.NotificationType3 = messages$1.NotificationType2 = messages$1.NotificationType1 = messages$1.NotificationType0 = messages$1.NotificationType = messages$1.RequestType9 = messages$1.RequestType8 = messages$1.RequestType7 = messages$1.RequestType6 = messages$1.RequestType5 = messages$1.RequestType4 = messages$1.RequestType3 = messages$1.RequestType2 = messages$1.RequestType1 = messages$1.RequestType = messages$1.RequestType0 = messages$1.AbstractMessageSignature = messages$1.ParameterStructures = messages$1.ResponseError = messages$1.ErrorCodes = void 0;
      const is2 = requireIs$2();
      var ErrorCodes;
      (function(ErrorCodes2) {
        ErrorCodes2.ParseError = -32700;
        ErrorCodes2.InvalidRequest = -32600;
        ErrorCodes2.MethodNotFound = -32601;
        ErrorCodes2.InvalidParams = -32602;
        ErrorCodes2.InternalError = -32603;
        ErrorCodes2.jsonrpcReservedErrorRangeStart = -32099;
        ErrorCodes2.serverErrorStart = -32099;
        ErrorCodes2.MessageWriteError = -32099;
        ErrorCodes2.MessageReadError = -32098;
        ErrorCodes2.PendingResponseRejected = -32097;
        ErrorCodes2.ConnectionInactive = -32096;
        ErrorCodes2.ServerNotInitialized = -32002;
        ErrorCodes2.UnknownErrorCode = -32001;
        ErrorCodes2.jsonrpcReservedErrorRangeEnd = -32e3;
        ErrorCodes2.serverErrorEnd = -32e3;
      })(ErrorCodes || (messages$1.ErrorCodes = ErrorCodes = {}));
      class ResponseError extends Error {
        constructor(code, message, data) {
          super(message);
          this.code = is2.number(code) ? code : ErrorCodes.UnknownErrorCode;
          this.data = data;
          Object.setPrototypeOf(this, ResponseError.prototype);
        }
        toJson() {
          const result = {
            code: this.code,
            message: this.message
          };
          if (this.data !== void 0) {
            result.data = this.data;
          }
          return result;
        }
      }
      messages$1.ResponseError = ResponseError;
      class ParameterStructures {
        constructor(kind) {
          this.kind = kind;
        }
        static is(value) {
          return value === ParameterStructures.auto || value === ParameterStructures.byName || value === ParameterStructures.byPosition;
        }
        toString() {
          return this.kind;
        }
      }
      messages$1.ParameterStructures = ParameterStructures;
      ParameterStructures.auto = new ParameterStructures("auto");
      ParameterStructures.byPosition = new ParameterStructures("byPosition");
      ParameterStructures.byName = new ParameterStructures("byName");
      class AbstractMessageSignature {
        constructor(method, numberOfParams) {
          this.method = method;
          this.numberOfParams = numberOfParams;
        }
        get parameterStructures() {
          return ParameterStructures.auto;
        }
      }
      messages$1.AbstractMessageSignature = AbstractMessageSignature;
      class RequestType0 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 0);
        }
      }
      messages$1.RequestType0 = RequestType0;
      class RequestType extends AbstractMessageSignature {
        constructor(method, _parameterStructures = ParameterStructures.auto) {
          super(method, 1);
          this._parameterStructures = _parameterStructures;
        }
        get parameterStructures() {
          return this._parameterStructures;
        }
      }
      messages$1.RequestType = RequestType;
      class RequestType1 extends AbstractMessageSignature {
        constructor(method, _parameterStructures = ParameterStructures.auto) {
          super(method, 1);
          this._parameterStructures = _parameterStructures;
        }
        get parameterStructures() {
          return this._parameterStructures;
        }
      }
      messages$1.RequestType1 = RequestType1;
      class RequestType2 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 2);
        }
      }
      messages$1.RequestType2 = RequestType2;
      class RequestType3 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 3);
        }
      }
      messages$1.RequestType3 = RequestType3;
      class RequestType4 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 4);
        }
      }
      messages$1.RequestType4 = RequestType4;
      class RequestType5 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 5);
        }
      }
      messages$1.RequestType5 = RequestType5;
      class RequestType6 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 6);
        }
      }
      messages$1.RequestType6 = RequestType6;
      class RequestType7 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 7);
        }
      }
      messages$1.RequestType7 = RequestType7;
      class RequestType8 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 8);
        }
      }
      messages$1.RequestType8 = RequestType8;
      class RequestType9 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 9);
        }
      }
      messages$1.RequestType9 = RequestType9;
      class NotificationType extends AbstractMessageSignature {
        constructor(method, _parameterStructures = ParameterStructures.auto) {
          super(method, 1);
          this._parameterStructures = _parameterStructures;
        }
        get parameterStructures() {
          return this._parameterStructures;
        }
      }
      messages$1.NotificationType = NotificationType;
      class NotificationType0 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 0);
        }
      }
      messages$1.NotificationType0 = NotificationType0;
      class NotificationType1 extends AbstractMessageSignature {
        constructor(method, _parameterStructures = ParameterStructures.auto) {
          super(method, 1);
          this._parameterStructures = _parameterStructures;
        }
        get parameterStructures() {
          return this._parameterStructures;
        }
      }
      messages$1.NotificationType1 = NotificationType1;
      class NotificationType2 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 2);
        }
      }
      messages$1.NotificationType2 = NotificationType2;
      class NotificationType3 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 3);
        }
      }
      messages$1.NotificationType3 = NotificationType3;
      class NotificationType4 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 4);
        }
      }
      messages$1.NotificationType4 = NotificationType4;
      class NotificationType5 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 5);
        }
      }
      messages$1.NotificationType5 = NotificationType5;
      class NotificationType6 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 6);
        }
      }
      messages$1.NotificationType6 = NotificationType6;
      class NotificationType7 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 7);
        }
      }
      messages$1.NotificationType7 = NotificationType7;
      class NotificationType8 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 8);
        }
      }
      messages$1.NotificationType8 = NotificationType8;
      class NotificationType9 extends AbstractMessageSignature {
        constructor(method) {
          super(method, 9);
        }
      }
      messages$1.NotificationType9 = NotificationType9;
      var Message2;
      (function(Message3) {
        function isRequest(message) {
          const candidate = message;
          return candidate && is2.string(candidate.method) && (is2.string(candidate.id) || is2.number(candidate.id));
        }
        Message3.isRequest = isRequest;
        function isNotification(message) {
          const candidate = message;
          return candidate && is2.string(candidate.method) && message.id === void 0;
        }
        Message3.isNotification = isNotification;
        function isResponse(message) {
          const candidate = message;
          return candidate && (candidate.result !== void 0 || !!candidate.error) && (is2.string(candidate.id) || is2.number(candidate.id) || candidate.id === null);
        }
        Message3.isResponse = isResponse;
      })(Message2 || (messages$1.Message = Message2 = {}));
      return messages$1;
    }
    var linkedMap = {};
    var hasRequiredLinkedMap;
    function requireLinkedMap() {
      if (hasRequiredLinkedMap) return linkedMap;
      hasRequiredLinkedMap = 1;
      var _a;
      Object.defineProperty(linkedMap, "__esModule", { value: true });
      linkedMap.LRUCache = linkedMap.LinkedMap = linkedMap.Touch = void 0;
      var Touch;
      (function(Touch2) {
        Touch2.None = 0;
        Touch2.First = 1;
        Touch2.AsOld = Touch2.First;
        Touch2.Last = 2;
        Touch2.AsNew = Touch2.Last;
      })(Touch || (linkedMap.Touch = Touch = {}));
      class LinkedMap {
        constructor() {
          this[_a] = "LinkedMap";
          this._map = /* @__PURE__ */ new Map();
          this._head = void 0;
          this._tail = void 0;
          this._size = 0;
          this._state = 0;
        }
        clear() {
          this._map.clear();
          this._head = void 0;
          this._tail = void 0;
          this._size = 0;
          this._state++;
        }
        isEmpty() {
          return !this._head && !this._tail;
        }
        get size() {
          return this._size;
        }
        get first() {
          return this._head?.value;
        }
        get last() {
          return this._tail?.value;
        }
        has(key) {
          return this._map.has(key);
        }
        get(key, touch = Touch.None) {
          const item = this._map.get(key);
          if (!item) {
            return void 0;
          }
          if (touch !== Touch.None) {
            this.touch(item, touch);
          }
          return item.value;
        }
        set(key, value, touch = Touch.None) {
          let item = this._map.get(key);
          if (item) {
            item.value = value;
            if (touch !== Touch.None) {
              this.touch(item, touch);
            }
          } else {
            item = { key, value, next: void 0, previous: void 0 };
            switch (touch) {
              case Touch.None:
                this.addItemLast(item);
                break;
              case Touch.First:
                this.addItemFirst(item);
                break;
              case Touch.Last:
                this.addItemLast(item);
                break;
              default:
                this.addItemLast(item);
                break;
            }
            this._map.set(key, item);
            this._size++;
          }
          return this;
        }
        delete(key) {
          return !!this.remove(key);
        }
        remove(key) {
          const item = this._map.get(key);
          if (!item) {
            return void 0;
          }
          this._map.delete(key);
          this.removeItem(item);
          this._size--;
          return item.value;
        }
        shift() {
          if (!this._head && !this._tail) {
            return void 0;
          }
          if (!this._head || !this._tail) {
            throw new Error("Invalid list");
          }
          const item = this._head;
          this._map.delete(item.key);
          this.removeItem(item);
          this._size--;
          return item.value;
        }
        forEach(callbackfn, thisArg) {
          const state = this._state;
          let current = this._head;
          while (current) {
            if (thisArg) {
              callbackfn.bind(thisArg)(current.value, current.key, this);
            } else {
              callbackfn(current.value, current.key, this);
            }
            if (this._state !== state) {
              throw new Error(`LinkedMap got modified during iteration.`);
            }
            current = current.next;
          }
        }
        keys() {
          const state = this._state;
          let current = this._head;
          const iterator = {
            [Symbol.iterator]: () => {
              return iterator;
            },
            next: () => {
              if (this._state !== state) {
                throw new Error(`LinkedMap got modified during iteration.`);
              }
              if (current) {
                const result = { value: current.key, done: false };
                current = current.next;
                return result;
              } else {
                return { value: void 0, done: true };
              }
            }
          };
          return iterator;
        }
        values() {
          const state = this._state;
          let current = this._head;
          const iterator = {
            [Symbol.iterator]: () => {
              return iterator;
            },
            next: () => {
              if (this._state !== state) {
                throw new Error(`LinkedMap got modified during iteration.`);
              }
              if (current) {
                const result = { value: current.value, done: false };
                current = current.next;
                return result;
              } else {
                return { value: void 0, done: true };
              }
            }
          };
          return iterator;
        }
        entries() {
          const state = this._state;
          let current = this._head;
          const iterator = {
            [Symbol.iterator]: () => {
              return iterator;
            },
            next: () => {
              if (this._state !== state) {
                throw new Error(`LinkedMap got modified during iteration.`);
              }
              if (current) {
                const result = { value: [current.key, current.value], done: false };
                current = current.next;
                return result;
              } else {
                return { value: void 0, done: true };
              }
            }
          };
          return iterator;
        }
        [(_a = Symbol.toStringTag, Symbol.iterator)]() {
          return this.entries();
        }
        trimOld(newSize) {
          if (newSize >= this.size) {
            return;
          }
          if (newSize === 0) {
            this.clear();
            return;
          }
          let current = this._head;
          let currentSize = this.size;
          while (current && currentSize > newSize) {
            this._map.delete(current.key);
            current = current.next;
            currentSize--;
          }
          this._head = current;
          this._size = currentSize;
          if (current) {
            current.previous = void 0;
          }
          this._state++;
        }
        addItemFirst(item) {
          if (!this._head && !this._tail) {
            this._tail = item;
          } else if (!this._head) {
            throw new Error("Invalid list");
          } else {
            item.next = this._head;
            this._head.previous = item;
          }
          this._head = item;
          this._state++;
        }
        addItemLast(item) {
          if (!this._head && !this._tail) {
            this._head = item;
          } else if (!this._tail) {
            throw new Error("Invalid list");
          } else {
            item.previous = this._tail;
            this._tail.next = item;
          }
          this._tail = item;
          this._state++;
        }
        removeItem(item) {
          if (item === this._head && item === this._tail) {
            this._head = void 0;
            this._tail = void 0;
          } else if (item === this._head) {
            if (!item.next) {
              throw new Error("Invalid list");
            }
            item.next.previous = void 0;
            this._head = item.next;
          } else if (item === this._tail) {
            if (!item.previous) {
              throw new Error("Invalid list");
            }
            item.previous.next = void 0;
            this._tail = item.previous;
          } else {
            const next = item.next;
            const previous = item.previous;
            if (!next || !previous) {
              throw new Error("Invalid list");
            }
            next.previous = previous;
            previous.next = next;
          }
          item.next = void 0;
          item.previous = void 0;
          this._state++;
        }
        touch(item, touch) {
          if (!this._head || !this._tail) {
            throw new Error("Invalid list");
          }
          if (touch !== Touch.First && touch !== Touch.Last) {
            return;
          }
          if (touch === Touch.First) {
            if (item === this._head) {
              return;
            }
            const next = item.next;
            const previous = item.previous;
            if (item === this._tail) {
              previous.next = void 0;
              this._tail = previous;
            } else {
              next.previous = previous;
              previous.next = next;
            }
            item.previous = void 0;
            item.next = this._head;
            this._head.previous = item;
            this._head = item;
            this._state++;
          } else if (touch === Touch.Last) {
            if (item === this._tail) {
              return;
            }
            const next = item.next;
            const previous = item.previous;
            if (item === this._head) {
              next.previous = void 0;
              this._head = next;
            } else {
              next.previous = previous;
              previous.next = next;
            }
            item.next = void 0;
            item.previous = this._tail;
            this._tail.next = item;
            this._tail = item;
            this._state++;
          }
        }
        toJSON() {
          const data = [];
          this.forEach((value, key) => {
            data.push([key, value]);
          });
          return data;
        }
        fromJSON(data) {
          this.clear();
          for (const [key, value] of data) {
            this.set(key, value);
          }
        }
      }
      linkedMap.LinkedMap = LinkedMap;
      class LRUCache extends LinkedMap {
        constructor(limit, ratio = 1) {
          super();
          this._limit = limit;
          this._ratio = Math.min(Math.max(0, ratio), 1);
        }
        get limit() {
          return this._limit;
        }
        set limit(limit) {
          this._limit = limit;
          this.checkTrim();
        }
        get ratio() {
          return this._ratio;
        }
        set ratio(ratio) {
          this._ratio = Math.min(Math.max(0, ratio), 1);
          this.checkTrim();
        }
        get(key, touch = Touch.AsNew) {
          return super.get(key, touch);
        }
        peek(key) {
          return super.get(key, Touch.None);
        }
        set(key, value) {
          super.set(key, value, Touch.Last);
          this.checkTrim();
          return this;
        }
        checkTrim() {
          if (this.size > this._limit) {
            this.trimOld(Math.round(this._limit * this._ratio));
          }
        }
      }
      linkedMap.LRUCache = LRUCache;
      return linkedMap;
    }
    var disposable = {};
    var hasRequiredDisposable;
    function requireDisposable() {
      if (hasRequiredDisposable) return disposable;
      hasRequiredDisposable = 1;
      Object.defineProperty(disposable, "__esModule", { value: true });
      disposable.Disposable = void 0;
      var Disposable2;
      (function(Disposable3) {
        function create(func) {
          return {
            dispose: func
          };
        }
        Disposable3.create = create;
      })(Disposable2 || (disposable.Disposable = Disposable2 = {}));
      return disposable;
    }
    var events$1 = {};
    var ral$1 = {};
    var hasRequiredRal$1;
    function requireRal$1() {
      if (hasRequiredRal$1) return ral$1;
      hasRequiredRal$1 = 1;
      Object.defineProperty(ral$1, "__esModule", { value: true });
      let _ral;
      function RAL() {
        if (_ral === void 0) {
          throw new Error(`No runtime abstraction layer installed`);
        }
        return _ral;
      }
      (function(RAL2) {
        function install(ral2) {
          if (ral2 === void 0) {
            throw new Error(`No runtime abstraction layer provided`);
          }
          _ral = ral2;
        }
        RAL2.install = install;
      })(RAL || (RAL = {}));
      ral$1.default = RAL;
      return ral$1;
    }
    var hasRequiredEvents$1;
    function requireEvents$1() {
      if (hasRequiredEvents$1) return events$1;
      hasRequiredEvents$1 = 1;
      Object.defineProperty(events$1, "__esModule", { value: true });
      events$1.Emitter = events$1.Event = void 0;
      const ral_1 = requireRal$1();
      var Event;
      (function(Event2) {
        const _disposable = { dispose() {
        } };
        Event2.None = function() {
          return _disposable;
        };
      })(Event || (events$1.Event = Event = {}));
      class CallbackList {
        add(callback, context = null, bucket) {
          if (!this._callbacks) {
            this._callbacks = [];
            this._contexts = [];
          }
          this._callbacks.push(callback);
          this._contexts.push(context);
          if (Array.isArray(bucket)) {
            bucket.push({ dispose: () => this.remove(callback, context) });
          }
        }
        remove(callback, context = null) {
          if (!this._callbacks) {
            return;
          }
          let foundCallbackWithDifferentContext = false;
          for (let i = 0, len = this._callbacks.length; i < len; i++) {
            if (this._callbacks[i] === callback) {
              if (this._contexts[i] === context) {
                this._callbacks.splice(i, 1);
                this._contexts.splice(i, 1);
                return;
              } else {
                foundCallbackWithDifferentContext = true;
              }
            }
          }
          if (foundCallbackWithDifferentContext) {
            throw new Error("When adding a listener with a context, you should remove it with the same context");
          }
        }
        invoke(...args) {
          if (!this._callbacks) {
            return [];
          }
          const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
          for (let i = 0, len = callbacks.length; i < len; i++) {
            try {
              ret.push(callbacks[i].apply(contexts[i], args));
            } catch (e) {
              (0, ral_1.default)().console.error(e);
            }
          }
          return ret;
        }
        isEmpty() {
          return !this._callbacks || this._callbacks.length === 0;
        }
        dispose() {
          this._callbacks = void 0;
          this._contexts = void 0;
        }
      }
      class Emitter {
        constructor(_options) {
          this._options = _options;
        }
        /**
         * For the public to allow to subscribe
         * to events from this Emitter
         */
        get event() {
          if (!this._event) {
            this._event = (listener, thisArgs, disposables) => {
              if (!this._callbacks) {
                this._callbacks = new CallbackList();
              }
              if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
                this._options.onFirstListenerAdd(this);
              }
              this._callbacks.add(listener, thisArgs);
              const result = {
                dispose: () => {
                  if (!this._callbacks) {
                    return;
                  }
                  this._callbacks.remove(listener, thisArgs);
                  result.dispose = Emitter._noop;
                  if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
                    this._options.onLastListenerRemove(this);
                  }
                }
              };
              if (Array.isArray(disposables)) {
                disposables.push(result);
              }
              return result;
            };
          }
          return this._event;
        }
        /**
         * To be kept private to fire an event to
         * subscribers
         */
        fire(event) {
          if (this._callbacks) {
            this._callbacks.invoke.call(this._callbacks, event);
          }
        }
        dispose() {
          if (this._callbacks) {
            this._callbacks.dispose();
            this._callbacks = void 0;
          }
        }
      }
      events$1.Emitter = Emitter;
      Emitter._noop = function() {
      };
      return events$1;
    }
    var cancellation$1 = {};
    var hasRequiredCancellation$1;
    function requireCancellation$1() {
      if (hasRequiredCancellation$1) return cancellation$1;
      hasRequiredCancellation$1 = 1;
      Object.defineProperty(cancellation$1, "__esModule", { value: true });
      cancellation$1.CancellationTokenSource = cancellation$1.CancellationToken = void 0;
      const ral_1 = requireRal$1();
      const Is2 = requireIs$2();
      const events_1 = requireEvents$1();
      var CancellationToken;
      (function(CancellationToken2) {
        CancellationToken2.None = Object.freeze({
          isCancellationRequested: false,
          onCancellationRequested: events_1.Event.None
        });
        CancellationToken2.Cancelled = Object.freeze({
          isCancellationRequested: true,
          onCancellationRequested: events_1.Event.None
        });
        function is2(value) {
          const candidate = value;
          return candidate && (candidate === CancellationToken2.None || candidate === CancellationToken2.Cancelled || Is2.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested);
        }
        CancellationToken2.is = is2;
      })(CancellationToken || (cancellation$1.CancellationToken = CancellationToken = {}));
      const shortcutEvent = Object.freeze(function(callback, context) {
        const handle = (0, ral_1.default)().timer.setTimeout(callback.bind(context), 0);
        return { dispose() {
          handle.dispose();
        } };
      });
      class MutableToken {
        constructor() {
          this._isCancelled = false;
        }
        cancel() {
          if (!this._isCancelled) {
            this._isCancelled = true;
            if (this._emitter) {
              this._emitter.fire(void 0);
              this.dispose();
            }
          }
        }
        get isCancellationRequested() {
          return this._isCancelled;
        }
        get onCancellationRequested() {
          if (this._isCancelled) {
            return shortcutEvent;
          }
          if (!this._emitter) {
            this._emitter = new events_1.Emitter();
          }
          return this._emitter.event;
        }
        dispose() {
          if (this._emitter) {
            this._emitter.dispose();
            this._emitter = void 0;
          }
        }
      }
      class CancellationTokenSource {
        get token() {
          if (!this._token) {
            this._token = new MutableToken();
          }
          return this._token;
        }
        cancel() {
          if (!this._token) {
            this._token = CancellationToken.Cancelled;
          } else {
            this._token.cancel();
          }
        }
        dispose() {
          if (!this._token) {
            this._token = CancellationToken.None;
          } else if (this._token instanceof MutableToken) {
            this._token.dispose();
          }
        }
      }
      cancellation$1.CancellationTokenSource = CancellationTokenSource;
      return cancellation$1;
    }
    var sharedArrayCancellation = {};
    var hasRequiredSharedArrayCancellation;
    function requireSharedArrayCancellation() {
      if (hasRequiredSharedArrayCancellation) return sharedArrayCancellation;
      hasRequiredSharedArrayCancellation = 1;
      Object.defineProperty(sharedArrayCancellation, "__esModule", { value: true });
      sharedArrayCancellation.SharedArrayReceiverStrategy = sharedArrayCancellation.SharedArraySenderStrategy = void 0;
      const cancellation_1 = requireCancellation$1();
      var CancellationState;
      (function(CancellationState2) {
        CancellationState2.Continue = 0;
        CancellationState2.Cancelled = 1;
      })(CancellationState || (CancellationState = {}));
      class SharedArraySenderStrategy {
        constructor() {
          this.buffers = /* @__PURE__ */ new Map();
        }
        enableCancellation(request) {
          if (request.id === null) {
            return;
          }
          const buffer = new SharedArrayBuffer(4);
          const data = new Int32Array(buffer, 0, 1);
          data[0] = CancellationState.Continue;
          this.buffers.set(request.id, buffer);
          request.$cancellationData = buffer;
        }
        async sendCancellation(_conn, id) {
          const buffer = this.buffers.get(id);
          if (buffer === void 0) {
            return;
          }
          const data = new Int32Array(buffer, 0, 1);
          Atomics.store(data, 0, CancellationState.Cancelled);
        }
        cleanup(id) {
          this.buffers.delete(id);
        }
        dispose() {
          this.buffers.clear();
        }
      }
      sharedArrayCancellation.SharedArraySenderStrategy = SharedArraySenderStrategy;
      class SharedArrayBufferCancellationToken {
        constructor(buffer) {
          this.data = new Int32Array(buffer, 0, 1);
        }
        get isCancellationRequested() {
          return Atomics.load(this.data, 0) === CancellationState.Cancelled;
        }
        get onCancellationRequested() {
          throw new Error(`Cancellation over SharedArrayBuffer doesn't support cancellation events`);
        }
      }
      class SharedArrayBufferCancellationTokenSource {
        constructor(buffer) {
          this.token = new SharedArrayBufferCancellationToken(buffer);
        }
        cancel() {
        }
        dispose() {
        }
      }
      class SharedArrayReceiverStrategy {
        constructor() {
          this.kind = "request";
        }
        createCancellationTokenSource(request) {
          const buffer = request.$cancellationData;
          if (buffer === void 0) {
            return new cancellation_1.CancellationTokenSource();
          }
          return new SharedArrayBufferCancellationTokenSource(buffer);
        }
      }
      sharedArrayCancellation.SharedArrayReceiverStrategy = SharedArrayReceiverStrategy;
      return sharedArrayCancellation;
    }
    var messageReader = {};
    var semaphore = {};
    var hasRequiredSemaphore;
    function requireSemaphore() {
      if (hasRequiredSemaphore) return semaphore;
      hasRequiredSemaphore = 1;
      Object.defineProperty(semaphore, "__esModule", { value: true });
      semaphore.Semaphore = void 0;
      const ral_1 = requireRal$1();
      class Semaphore {
        constructor(capacity = 1) {
          if (capacity <= 0) {
            throw new Error("Capacity must be greater than 0");
          }
          this._capacity = capacity;
          this._active = 0;
          this._waiting = [];
        }
        lock(thunk) {
          return new Promise((resolve, reject) => {
            this._waiting.push({ thunk, resolve, reject });
            this.runNext();
          });
        }
        get active() {
          return this._active;
        }
        runNext() {
          if (this._waiting.length === 0 || this._active === this._capacity) {
            return;
          }
          (0, ral_1.default)().timer.setImmediate(() => this.doRunNext());
        }
        doRunNext() {
          if (this._waiting.length === 0 || this._active === this._capacity) {
            return;
          }
          const next = this._waiting.shift();
          this._active++;
          if (this._active > this._capacity) {
            throw new Error(`To many thunks active`);
          }
          try {
            const result = next.thunk();
            if (result instanceof Promise) {
              result.then((value) => {
                this._active--;
                next.resolve(value);
                this.runNext();
              }, (err) => {
                this._active--;
                next.reject(err);
                this.runNext();
              });
            } else {
              this._active--;
              next.resolve(result);
              this.runNext();
            }
          } catch (err) {
            this._active--;
            next.reject(err);
            this.runNext();
          }
        }
      }
      semaphore.Semaphore = Semaphore;
      return semaphore;
    }
    var hasRequiredMessageReader;
    function requireMessageReader() {
      if (hasRequiredMessageReader) return messageReader;
      hasRequiredMessageReader = 1;
      Object.defineProperty(messageReader, "__esModule", { value: true });
      messageReader.ReadableStreamMessageReader = messageReader.AbstractMessageReader = messageReader.MessageReader = void 0;
      const ral_1 = requireRal$1();
      const Is2 = requireIs$2();
      const events_1 = requireEvents$1();
      const semaphore_1 = requireSemaphore();
      var MessageReader;
      (function(MessageReader2) {
        function is2(value) {
          let candidate = value;
          return candidate && Is2.func(candidate.listen) && Is2.func(candidate.dispose) && Is2.func(candidate.onError) && Is2.func(candidate.onClose) && Is2.func(candidate.onPartialMessage);
        }
        MessageReader2.is = is2;
      })(MessageReader || (messageReader.MessageReader = MessageReader = {}));
      class AbstractMessageReader {
        constructor() {
          this.errorEmitter = new events_1.Emitter();
          this.closeEmitter = new events_1.Emitter();
          this.partialMessageEmitter = new events_1.Emitter();
        }
        dispose() {
          this.errorEmitter.dispose();
          this.closeEmitter.dispose();
        }
        get onError() {
          return this.errorEmitter.event;
        }
        fireError(error) {
          this.errorEmitter.fire(this.asError(error));
        }
        get onClose() {
          return this.closeEmitter.event;
        }
        fireClose() {
          this.closeEmitter.fire(void 0);
        }
        get onPartialMessage() {
          return this.partialMessageEmitter.event;
        }
        firePartialMessage(info) {
          this.partialMessageEmitter.fire(info);
        }
        asError(error) {
          if (error instanceof Error) {
            return error;
          } else {
            return new Error(`Reader received error. Reason: ${Is2.string(error.message) ? error.message : "unknown"}`);
          }
        }
      }
      messageReader.AbstractMessageReader = AbstractMessageReader;
      var ResolvedMessageReaderOptions;
      (function(ResolvedMessageReaderOptions2) {
        function fromOptions(options) {
          let charset;
          let contentDecoder;
          const contentDecoders = /* @__PURE__ */ new Map();
          let contentTypeDecoder;
          const contentTypeDecoders = /* @__PURE__ */ new Map();
          if (options === void 0 || typeof options === "string") {
            charset = options ?? "utf-8";
          } else {
            charset = options.charset ?? "utf-8";
            if (options.contentDecoder !== void 0) {
              contentDecoder = options.contentDecoder;
              contentDecoders.set(contentDecoder.name, contentDecoder);
            }
            if (options.contentDecoders !== void 0) {
              for (const decoder of options.contentDecoders) {
                contentDecoders.set(decoder.name, decoder);
              }
            }
            if (options.contentTypeDecoder !== void 0) {
              contentTypeDecoder = options.contentTypeDecoder;
              contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
            }
            if (options.contentTypeDecoders !== void 0) {
              for (const decoder of options.contentTypeDecoders) {
                contentTypeDecoders.set(decoder.name, decoder);
              }
            }
          }
          if (contentTypeDecoder === void 0) {
            contentTypeDecoder = (0, ral_1.default)().applicationJson.decoder;
            contentTypeDecoders.set(contentTypeDecoder.name, contentTypeDecoder);
          }
          return { charset, contentDecoder, contentDecoders, contentTypeDecoder, contentTypeDecoders };
        }
        ResolvedMessageReaderOptions2.fromOptions = fromOptions;
      })(ResolvedMessageReaderOptions || (ResolvedMessageReaderOptions = {}));
      class ReadableStreamMessageReader extends AbstractMessageReader {
        constructor(readable, options) {
          super();
          this.readable = readable;
          this.options = ResolvedMessageReaderOptions.fromOptions(options);
          this.buffer = (0, ral_1.default)().messageBuffer.create(this.options.charset);
          this._partialMessageTimeout = 1e4;
          this.nextMessageLength = -1;
          this.messageToken = 0;
          this.readSemaphore = new semaphore_1.Semaphore(1);
        }
        set partialMessageTimeout(timeout) {
          this._partialMessageTimeout = timeout;
        }
        get partialMessageTimeout() {
          return this._partialMessageTimeout;
        }
        listen(callback) {
          this.nextMessageLength = -1;
          this.messageToken = 0;
          this.partialMessageTimer = void 0;
          this.callback = callback;
          const result = this.readable.onData((data) => {
            this.onData(data);
          });
          this.readable.onError((error) => this.fireError(error));
          this.readable.onClose(() => this.fireClose());
          return result;
        }
        onData(data) {
          try {
            this.buffer.append(data);
            while (true) {
              if (this.nextMessageLength === -1) {
                const headers = this.buffer.tryReadHeaders(true);
                if (!headers) {
                  return;
                }
                const contentLength = headers.get("content-length");
                if (!contentLength) {
                  this.fireError(new Error(`Header must provide a Content-Length property.
${JSON.stringify(Object.fromEntries(headers))}`));
                  return;
                }
                const length = parseInt(contentLength);
                if (isNaN(length)) {
                  this.fireError(new Error(`Content-Length value must be a number. Got ${contentLength}`));
                  return;
                }
                this.nextMessageLength = length;
              }
              const body = this.buffer.tryReadBody(this.nextMessageLength);
              if (body === void 0) {
                this.setPartialMessageTimer();
                return;
              }
              this.clearPartialMessageTimer();
              this.nextMessageLength = -1;
              this.readSemaphore.lock(async () => {
                const bytes = this.options.contentDecoder !== void 0 ? await this.options.contentDecoder.decode(body) : body;
                const message = await this.options.contentTypeDecoder.decode(bytes, this.options);
                this.callback(message);
              }).catch((error) => {
                this.fireError(error);
              });
            }
          } catch (error) {
            this.fireError(error);
          }
        }
        clearPartialMessageTimer() {
          if (this.partialMessageTimer) {
            this.partialMessageTimer.dispose();
            this.partialMessageTimer = void 0;
          }
        }
        setPartialMessageTimer() {
          this.clearPartialMessageTimer();
          if (this._partialMessageTimeout <= 0) {
            return;
          }
          this.partialMessageTimer = (0, ral_1.default)().timer.setTimeout((token, timeout) => {
            this.partialMessageTimer = void 0;
            if (token === this.messageToken) {
              this.firePartialMessage({ messageToken: token, waitingTime: timeout });
              this.setPartialMessageTimer();
            }
          }, this._partialMessageTimeout, this.messageToken, this._partialMessageTimeout);
        }
      }
      messageReader.ReadableStreamMessageReader = ReadableStreamMessageReader;
      return messageReader;
    }
    var messageWriter = {};
    var hasRequiredMessageWriter;
    function requireMessageWriter() {
      if (hasRequiredMessageWriter) return messageWriter;
      hasRequiredMessageWriter = 1;
      Object.defineProperty(messageWriter, "__esModule", { value: true });
      messageWriter.WriteableStreamMessageWriter = messageWriter.AbstractMessageWriter = messageWriter.MessageWriter = void 0;
      const ral_1 = requireRal$1();
      const Is2 = requireIs$2();
      const semaphore_1 = requireSemaphore();
      const events_1 = requireEvents$1();
      const ContentLength = "Content-Length: ";
      const CRLF = "\r\n";
      var MessageWriter;
      (function(MessageWriter2) {
        function is2(value) {
          let candidate = value;
          return candidate && Is2.func(candidate.dispose) && Is2.func(candidate.onClose) && Is2.func(candidate.onError) && Is2.func(candidate.write);
        }
        MessageWriter2.is = is2;
      })(MessageWriter || (messageWriter.MessageWriter = MessageWriter = {}));
      class AbstractMessageWriter {
        constructor() {
          this.errorEmitter = new events_1.Emitter();
          this.closeEmitter = new events_1.Emitter();
        }
        dispose() {
          this.errorEmitter.dispose();
          this.closeEmitter.dispose();
        }
        get onError() {
          return this.errorEmitter.event;
        }
        fireError(error, message, count) {
          this.errorEmitter.fire([this.asError(error), message, count]);
        }
        get onClose() {
          return this.closeEmitter.event;
        }
        fireClose() {
          this.closeEmitter.fire(void 0);
        }
        asError(error) {
          if (error instanceof Error) {
            return error;
          } else {
            return new Error(`Writer received error. Reason: ${Is2.string(error.message) ? error.message : "unknown"}`);
          }
        }
      }
      messageWriter.AbstractMessageWriter = AbstractMessageWriter;
      var ResolvedMessageWriterOptions;
      (function(ResolvedMessageWriterOptions2) {
        function fromOptions(options) {
          if (options === void 0 || typeof options === "string") {
            return { charset: options ?? "utf-8", contentTypeEncoder: (0, ral_1.default)().applicationJson.encoder };
          } else {
            return { charset: options.charset ?? "utf-8", contentEncoder: options.contentEncoder, contentTypeEncoder: options.contentTypeEncoder ?? (0, ral_1.default)().applicationJson.encoder };
          }
        }
        ResolvedMessageWriterOptions2.fromOptions = fromOptions;
      })(ResolvedMessageWriterOptions || (ResolvedMessageWriterOptions = {}));
      class WriteableStreamMessageWriter extends AbstractMessageWriter {
        constructor(writable, options) {
          super();
          this.writable = writable;
          this.options = ResolvedMessageWriterOptions.fromOptions(options);
          this.errorCount = 0;
          this.writeSemaphore = new semaphore_1.Semaphore(1);
          this.writable.onError((error) => this.fireError(error));
          this.writable.onClose(() => this.fireClose());
        }
        async write(msg) {
          return this.writeSemaphore.lock(async () => {
            const payload = this.options.contentTypeEncoder.encode(msg, this.options).then((buffer) => {
              if (this.options.contentEncoder !== void 0) {
                return this.options.contentEncoder.encode(buffer);
              } else {
                return buffer;
              }
            });
            return payload.then((buffer) => {
              const headers = [];
              headers.push(ContentLength, buffer.byteLength.toString(), CRLF);
              headers.push(CRLF);
              return this.doWrite(msg, headers, buffer);
            }, (error) => {
              this.fireError(error);
              throw error;
            });
          });
        }
        async doWrite(msg, headers, data) {
          try {
            await this.writable.write(headers.join(""), "ascii");
            return this.writable.write(data);
          } catch (error) {
            this.handleError(error, msg);
            return Promise.reject(error);
          }
        }
        handleError(error, msg) {
          this.errorCount++;
          this.fireError(error, msg, this.errorCount);
        }
        end() {
          this.writable.end();
        }
      }
      messageWriter.WriteableStreamMessageWriter = WriteableStreamMessageWriter;
      return messageWriter;
    }
    var messageBuffer = {};
    var hasRequiredMessageBuffer;
    function requireMessageBuffer() {
      if (hasRequiredMessageBuffer) return messageBuffer;
      hasRequiredMessageBuffer = 1;
      Object.defineProperty(messageBuffer, "__esModule", { value: true });
      messageBuffer.AbstractMessageBuffer = void 0;
      const CR2 = 13;
      const LF = 10;
      const CRLF = "\r\n";
      class AbstractMessageBuffer {
        constructor(encoding = "utf-8") {
          this._encoding = encoding;
          this._chunks = [];
          this._totalLength = 0;
        }
        get encoding() {
          return this._encoding;
        }
        append(chunk) {
          const toAppend = typeof chunk === "string" ? this.fromString(chunk, this._encoding) : chunk;
          this._chunks.push(toAppend);
          this._totalLength += toAppend.byteLength;
        }
        tryReadHeaders(lowerCaseKeys = false) {
          if (this._chunks.length === 0) {
            return void 0;
          }
          let state = 0;
          let chunkIndex = 0;
          let offset = 0;
          let chunkBytesRead = 0;
          row: while (chunkIndex < this._chunks.length) {
            const chunk = this._chunks[chunkIndex];
            offset = 0;
            while (offset < chunk.length) {
              const value = chunk[offset];
              switch (value) {
                case CR2:
                  switch (state) {
                    case 0:
                      state = 1;
                      break;
                    case 2:
                      state = 3;
                      break;
                    default:
                      state = 0;
                  }
                  break;
                case LF:
                  switch (state) {
                    case 1:
                      state = 2;
                      break;
                    case 3:
                      state = 4;
                      offset++;
                      break row;
                    default:
                      state = 0;
                  }
                  break;
                default:
                  state = 0;
              }
              offset++;
            }
            chunkBytesRead += chunk.byteLength;
            chunkIndex++;
          }
          if (state !== 4) {
            return void 0;
          }
          const buffer = this._read(chunkBytesRead + offset);
          const result = /* @__PURE__ */ new Map();
          const headers = this.toString(buffer, "ascii").split(CRLF);
          if (headers.length < 2) {
            return result;
          }
          for (let i = 0; i < headers.length - 2; i++) {
            const header = headers[i];
            const index = header.indexOf(":");
            if (index === -1) {
              throw new Error(`Message header must separate key and value using ':'
${header}`);
            }
            const key = header.substr(0, index);
            const value = header.substr(index + 1).trim();
            result.set(lowerCaseKeys ? key.toLowerCase() : key, value);
          }
          return result;
        }
        tryReadBody(length) {
          if (this._totalLength < length) {
            return void 0;
          }
          return this._read(length);
        }
        get numberOfBytes() {
          return this._totalLength;
        }
        _read(byteCount) {
          if (byteCount === 0) {
            return this.emptyBuffer();
          }
          if (byteCount > this._totalLength) {
            throw new Error(`Cannot read so many bytes!`);
          }
          if (this._chunks[0].byteLength === byteCount) {
            const chunk = this._chunks[0];
            this._chunks.shift();
            this._totalLength -= byteCount;
            return this.asNative(chunk);
          }
          if (this._chunks[0].byteLength > byteCount) {
            const chunk = this._chunks[0];
            const result2 = this.asNative(chunk, byteCount);
            this._chunks[0] = chunk.slice(byteCount);
            this._totalLength -= byteCount;
            return result2;
          }
          const result = this.allocNative(byteCount);
          let resultOffset = 0;
          let chunkIndex = 0;
          while (byteCount > 0) {
            const chunk = this._chunks[chunkIndex];
            if (chunk.byteLength > byteCount) {
              const chunkPart = chunk.slice(0, byteCount);
              result.set(chunkPart, resultOffset);
              resultOffset += byteCount;
              this._chunks[chunkIndex] = chunk.slice(byteCount);
              this._totalLength -= byteCount;
              byteCount -= byteCount;
            } else {
              result.set(chunk, resultOffset);
              resultOffset += chunk.byteLength;
              this._chunks.shift();
              this._totalLength -= chunk.byteLength;
              byteCount -= chunk.byteLength;
            }
          }
          return result;
        }
      }
      messageBuffer.AbstractMessageBuffer = AbstractMessageBuffer;
      return messageBuffer;
    }
    var connection$2 = {};
    var hasRequiredConnection$1;
    function requireConnection$1() {
      if (hasRequiredConnection$1) return connection$2;
      hasRequiredConnection$1 = 1;
      (function(exports2) {
        Object.defineProperty(exports2, "__esModule", { value: true });
        exports2.createMessageConnection = exports2.ConnectionOptions = exports2.MessageStrategy = exports2.CancellationStrategy = exports2.CancellationSenderStrategy = exports2.CancellationReceiverStrategy = exports2.RequestCancellationReceiverStrategy = exports2.IdCancellationReceiverStrategy = exports2.ConnectionStrategy = exports2.ConnectionError = exports2.ConnectionErrors = exports2.LogTraceNotification = exports2.SetTraceNotification = exports2.TraceFormat = exports2.TraceValues = exports2.Trace = exports2.NullLogger = exports2.ProgressType = exports2.ProgressToken = void 0;
        const ral_1 = requireRal$1();
        const Is2 = requireIs$2();
        const messages_1 = requireMessages$1();
        const linkedMap_1 = requireLinkedMap();
        const events_1 = requireEvents$1();
        const cancellation_1 = requireCancellation$1();
        var CancelNotification;
        (function(CancelNotification2) {
          CancelNotification2.type = new messages_1.NotificationType("$/cancelRequest");
        })(CancelNotification || (CancelNotification = {}));
        var ProgressToken;
        (function(ProgressToken2) {
          function is2(value) {
            return typeof value === "string" || typeof value === "number";
          }
          ProgressToken2.is = is2;
        })(ProgressToken || (exports2.ProgressToken = ProgressToken = {}));
        var ProgressNotification;
        (function(ProgressNotification2) {
          ProgressNotification2.type = new messages_1.NotificationType("$/progress");
        })(ProgressNotification || (ProgressNotification = {}));
        class ProgressType {
          constructor() {
          }
        }
        exports2.ProgressType = ProgressType;
        var StarRequestHandler;
        (function(StarRequestHandler2) {
          function is2(value) {
            return Is2.func(value);
          }
          StarRequestHandler2.is = is2;
        })(StarRequestHandler || (StarRequestHandler = {}));
        exports2.NullLogger = Object.freeze({
          error: () => {
          },
          warn: () => {
          },
          info: () => {
          },
          log: () => {
          }
        });
        var Trace;
        (function(Trace2) {
          Trace2[Trace2["Off"] = 0] = "Off";
          Trace2[Trace2["Messages"] = 1] = "Messages";
          Trace2[Trace2["Compact"] = 2] = "Compact";
          Trace2[Trace2["Verbose"] = 3] = "Verbose";
        })(Trace || (exports2.Trace = Trace = {}));
        var TraceValues;
        (function(TraceValues2) {
          TraceValues2.Off = "off";
          TraceValues2.Messages = "messages";
          TraceValues2.Compact = "compact";
          TraceValues2.Verbose = "verbose";
        })(TraceValues || (exports2.TraceValues = TraceValues = {}));
        (function(Trace2) {
          function fromString(value) {
            if (!Is2.string(value)) {
              return Trace2.Off;
            }
            value = value.toLowerCase();
            switch (value) {
              case "off":
                return Trace2.Off;
              case "messages":
                return Trace2.Messages;
              case "compact":
                return Trace2.Compact;
              case "verbose":
                return Trace2.Verbose;
              default:
                return Trace2.Off;
            }
          }
          Trace2.fromString = fromString;
          function toString2(value) {
            switch (value) {
              case Trace2.Off:
                return "off";
              case Trace2.Messages:
                return "messages";
              case Trace2.Compact:
                return "compact";
              case Trace2.Verbose:
                return "verbose";
              default:
                return "off";
            }
          }
          Trace2.toString = toString2;
        })(Trace || (exports2.Trace = Trace = {}));
        var TraceFormat;
        (function(TraceFormat2) {
          TraceFormat2["Text"] = "text";
          TraceFormat2["JSON"] = "json";
        })(TraceFormat || (exports2.TraceFormat = TraceFormat = {}));
        (function(TraceFormat2) {
          function fromString(value) {
            if (!Is2.string(value)) {
              return TraceFormat2.Text;
            }
            value = value.toLowerCase();
            if (value === "json") {
              return TraceFormat2.JSON;
            } else {
              return TraceFormat2.Text;
            }
          }
          TraceFormat2.fromString = fromString;
        })(TraceFormat || (exports2.TraceFormat = TraceFormat = {}));
        var SetTraceNotification;
        (function(SetTraceNotification2) {
          SetTraceNotification2.type = new messages_1.NotificationType("$/setTrace");
        })(SetTraceNotification || (exports2.SetTraceNotification = SetTraceNotification = {}));
        var LogTraceNotification;
        (function(LogTraceNotification2) {
          LogTraceNotification2.type = new messages_1.NotificationType("$/logTrace");
        })(LogTraceNotification || (exports2.LogTraceNotification = LogTraceNotification = {}));
        var ConnectionErrors;
        (function(ConnectionErrors2) {
          ConnectionErrors2[ConnectionErrors2["Closed"] = 1] = "Closed";
          ConnectionErrors2[ConnectionErrors2["Disposed"] = 2] = "Disposed";
          ConnectionErrors2[ConnectionErrors2["AlreadyListening"] = 3] = "AlreadyListening";
        })(ConnectionErrors || (exports2.ConnectionErrors = ConnectionErrors = {}));
        class ConnectionError extends Error {
          constructor(code, message) {
            super(message);
            this.code = code;
            Object.setPrototypeOf(this, ConnectionError.prototype);
          }
        }
        exports2.ConnectionError = ConnectionError;
        var ConnectionStrategy;
        (function(ConnectionStrategy2) {
          function is2(value) {
            const candidate = value;
            return candidate && Is2.func(candidate.cancelUndispatched);
          }
          ConnectionStrategy2.is = is2;
        })(ConnectionStrategy || (exports2.ConnectionStrategy = ConnectionStrategy = {}));
        var IdCancellationReceiverStrategy;
        (function(IdCancellationReceiverStrategy2) {
          function is2(value) {
            const candidate = value;
            return candidate && (candidate.kind === void 0 || candidate.kind === "id") && Is2.func(candidate.createCancellationTokenSource) && (candidate.dispose === void 0 || Is2.func(candidate.dispose));
          }
          IdCancellationReceiverStrategy2.is = is2;
        })(IdCancellationReceiverStrategy || (exports2.IdCancellationReceiverStrategy = IdCancellationReceiverStrategy = {}));
        var RequestCancellationReceiverStrategy;
        (function(RequestCancellationReceiverStrategy2) {
          function is2(value) {
            const candidate = value;
            return candidate && candidate.kind === "request" && Is2.func(candidate.createCancellationTokenSource) && (candidate.dispose === void 0 || Is2.func(candidate.dispose));
          }
          RequestCancellationReceiverStrategy2.is = is2;
        })(RequestCancellationReceiverStrategy || (exports2.RequestCancellationReceiverStrategy = RequestCancellationReceiverStrategy = {}));
        var CancellationReceiverStrategy;
        (function(CancellationReceiverStrategy2) {
          CancellationReceiverStrategy2.Message = Object.freeze({
            createCancellationTokenSource(_2) {
              return new cancellation_1.CancellationTokenSource();
            }
          });
          function is2(value) {
            return IdCancellationReceiverStrategy.is(value) || RequestCancellationReceiverStrategy.is(value);
          }
          CancellationReceiverStrategy2.is = is2;
        })(CancellationReceiverStrategy || (exports2.CancellationReceiverStrategy = CancellationReceiverStrategy = {}));
        var CancellationSenderStrategy;
        (function(CancellationSenderStrategy2) {
          CancellationSenderStrategy2.Message = Object.freeze({
            sendCancellation(conn, id) {
              return conn.sendNotification(CancelNotification.type, { id });
            },
            cleanup(_2) {
            }
          });
          function is2(value) {
            const candidate = value;
            return candidate && Is2.func(candidate.sendCancellation) && Is2.func(candidate.cleanup);
          }
          CancellationSenderStrategy2.is = is2;
        })(CancellationSenderStrategy || (exports2.CancellationSenderStrategy = CancellationSenderStrategy = {}));
        var CancellationStrategy;
        (function(CancellationStrategy2) {
          CancellationStrategy2.Message = Object.freeze({
            receiver: CancellationReceiverStrategy.Message,
            sender: CancellationSenderStrategy.Message
          });
          function is2(value) {
            const candidate = value;
            return candidate && CancellationReceiverStrategy.is(candidate.receiver) && CancellationSenderStrategy.is(candidate.sender);
          }
          CancellationStrategy2.is = is2;
        })(CancellationStrategy || (exports2.CancellationStrategy = CancellationStrategy = {}));
        var MessageStrategy;
        (function(MessageStrategy2) {
          function is2(value) {
            const candidate = value;
            return candidate && Is2.func(candidate.handleMessage);
          }
          MessageStrategy2.is = is2;
        })(MessageStrategy || (exports2.MessageStrategy = MessageStrategy = {}));
        var ConnectionOptions;
        (function(ConnectionOptions2) {
          function is2(value) {
            const candidate = value;
            return candidate && (CancellationStrategy.is(candidate.cancellationStrategy) || ConnectionStrategy.is(candidate.connectionStrategy) || MessageStrategy.is(candidate.messageStrategy));
          }
          ConnectionOptions2.is = is2;
        })(ConnectionOptions || (exports2.ConnectionOptions = ConnectionOptions = {}));
        var ConnectionState;
        (function(ConnectionState2) {
          ConnectionState2[ConnectionState2["New"] = 1] = "New";
          ConnectionState2[ConnectionState2["Listening"] = 2] = "Listening";
          ConnectionState2[ConnectionState2["Closed"] = 3] = "Closed";
          ConnectionState2[ConnectionState2["Disposed"] = 4] = "Disposed";
        })(ConnectionState || (ConnectionState = {}));
        function createMessageConnection(messageReader2, messageWriter2, _logger, options) {
          const logger = _logger !== void 0 ? _logger : exports2.NullLogger;
          let sequenceNumber = 0;
          let notificationSequenceNumber = 0;
          let unknownResponseSequenceNumber = 0;
          const version = "2.0";
          let starRequestHandler = void 0;
          const requestHandlers = /* @__PURE__ */ new Map();
          let starNotificationHandler = void 0;
          const notificationHandlers = /* @__PURE__ */ new Map();
          const progressHandlers = /* @__PURE__ */ new Map();
          let timer2;
          let messageQueue = new linkedMap_1.LinkedMap();
          let responsePromises = /* @__PURE__ */ new Map();
          let knownCanceledRequests = /* @__PURE__ */ new Set();
          let requestTokens = /* @__PURE__ */ new Map();
          let trace = Trace.Off;
          let traceFormat = TraceFormat.Text;
          let tracer;
          let state = ConnectionState.New;
          const errorEmitter = new events_1.Emitter();
          const closeEmitter = new events_1.Emitter();
          const unhandledNotificationEmitter = new events_1.Emitter();
          const unhandledProgressEmitter = new events_1.Emitter();
          const disposeEmitter = new events_1.Emitter();
          const cancellationStrategy = options && options.cancellationStrategy ? options.cancellationStrategy : CancellationStrategy.Message;
          function createRequestQueueKey(id) {
            if (id === null) {
              throw new Error(`Can't send requests with id null since the response can't be correlated.`);
            }
            return "req-" + id.toString();
          }
          function createResponseQueueKey(id) {
            if (id === null) {
              return "res-unknown-" + (++unknownResponseSequenceNumber).toString();
            } else {
              return "res-" + id.toString();
            }
          }
          function createNotificationQueueKey() {
            return "not-" + (++notificationSequenceNumber).toString();
          }
          function addMessageToQueue(queue, message) {
            if (messages_1.Message.isRequest(message)) {
              queue.set(createRequestQueueKey(message.id), message);
            } else if (messages_1.Message.isResponse(message)) {
              queue.set(createResponseQueueKey(message.id), message);
            } else {
              queue.set(createNotificationQueueKey(), message);
            }
          }
          function cancelUndispatched(_message) {
            return void 0;
          }
          function isListening() {
            return state === ConnectionState.Listening;
          }
          function isClosed() {
            return state === ConnectionState.Closed;
          }
          function isDisposed() {
            return state === ConnectionState.Disposed;
          }
          function closeHandler() {
            if (state === ConnectionState.New || state === ConnectionState.Listening) {
              state = ConnectionState.Closed;
              closeEmitter.fire(void 0);
            }
          }
          function readErrorHandler(error) {
            errorEmitter.fire([error, void 0, void 0]);
          }
          function writeErrorHandler(data) {
            errorEmitter.fire(data);
          }
          messageReader2.onClose(closeHandler);
          messageReader2.onError(readErrorHandler);
          messageWriter2.onClose(closeHandler);
          messageWriter2.onError(writeErrorHandler);
          function triggerMessageQueue() {
            if (timer2 || messageQueue.size === 0) {
              return;
            }
            timer2 = (0, ral_1.default)().timer.setImmediate(() => {
              timer2 = void 0;
              processMessageQueue();
            });
          }
          function handleMessage(message) {
            if (messages_1.Message.isRequest(message)) {
              handleRequest(message);
            } else if (messages_1.Message.isNotification(message)) {
              handleNotification(message);
            } else if (messages_1.Message.isResponse(message)) {
              handleResponse(message);
            } else {
              handleInvalidMessage(message);
            }
          }
          function processMessageQueue() {
            if (messageQueue.size === 0) {
              return;
            }
            const message = messageQueue.shift();
            try {
              const messageStrategy = options?.messageStrategy;
              if (MessageStrategy.is(messageStrategy)) {
                messageStrategy.handleMessage(message, handleMessage);
              } else {
                handleMessage(message);
              }
            } finally {
              triggerMessageQueue();
            }
          }
          const callback = (message) => {
            try {
              if (messages_1.Message.isNotification(message) && message.method === CancelNotification.type.method) {
                const cancelId = message.params.id;
                const key = createRequestQueueKey(cancelId);
                const toCancel = messageQueue.get(key);
                if (messages_1.Message.isRequest(toCancel)) {
                  const strategy = options?.connectionStrategy;
                  const response = strategy && strategy.cancelUndispatched ? strategy.cancelUndispatched(toCancel, cancelUndispatched) : cancelUndispatched(toCancel);
                  if (response && (response.error !== void 0 || response.result !== void 0)) {
                    messageQueue.delete(key);
                    requestTokens.delete(cancelId);
                    response.id = toCancel.id;
                    traceSendingResponse(response, message.method, Date.now());
                    messageWriter2.write(response).catch(() => logger.error(`Sending response for canceled message failed.`));
                    return;
                  }
                }
                const cancellationToken = requestTokens.get(cancelId);
                if (cancellationToken !== void 0) {
                  cancellationToken.cancel();
                  traceReceivedNotification(message);
                  return;
                } else {
                  knownCanceledRequests.add(cancelId);
                }
              }
              addMessageToQueue(messageQueue, message);
            } finally {
              triggerMessageQueue();
            }
          };
          function handleRequest(requestMessage) {
            if (isDisposed()) {
              return;
            }
            function reply(resultOrError, method, startTime2) {
              const message = {
                jsonrpc: version,
                id: requestMessage.id
              };
              if (resultOrError instanceof messages_1.ResponseError) {
                message.error = resultOrError.toJson();
              } else {
                message.result = resultOrError === void 0 ? null : resultOrError;
              }
              traceSendingResponse(message, method, startTime2);
              messageWriter2.write(message).catch(() => logger.error(`Sending response failed.`));
            }
            function replyError(error, method, startTime2) {
              const message = {
                jsonrpc: version,
                id: requestMessage.id,
                error: error.toJson()
              };
              traceSendingResponse(message, method, startTime2);
              messageWriter2.write(message).catch(() => logger.error(`Sending response failed.`));
            }
            function replySuccess(result, method, startTime2) {
              if (result === void 0) {
                result = null;
              }
              const message = {
                jsonrpc: version,
                id: requestMessage.id,
                result
              };
              traceSendingResponse(message, method, startTime2);
              messageWriter2.write(message).catch(() => logger.error(`Sending response failed.`));
            }
            traceReceivedRequest(requestMessage);
            const element = requestHandlers.get(requestMessage.method);
            let type;
            let requestHandler;
            if (element) {
              type = element.type;
              requestHandler = element.handler;
            }
            const startTime = Date.now();
            if (requestHandler || starRequestHandler) {
              const tokenKey = requestMessage.id ?? String(Date.now());
              const cancellationSource = IdCancellationReceiverStrategy.is(cancellationStrategy.receiver) ? cancellationStrategy.receiver.createCancellationTokenSource(tokenKey) : cancellationStrategy.receiver.createCancellationTokenSource(requestMessage);
              if (requestMessage.id !== null && knownCanceledRequests.has(requestMessage.id)) {
                cancellationSource.cancel();
              }
              if (requestMessage.id !== null) {
                requestTokens.set(tokenKey, cancellationSource);
              }
              try {
                let handlerResult;
                if (requestHandler) {
                  if (requestMessage.params === void 0) {
                    if (type !== void 0 && type.numberOfParams !== 0) {
                      replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines ${type.numberOfParams} params but received none.`), requestMessage.method, startTime);
                      return;
                    }
                    handlerResult = requestHandler(cancellationSource.token);
                  } else if (Array.isArray(requestMessage.params)) {
                    if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byName) {
                      replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by name but received parameters by position`), requestMessage.method, startTime);
                      return;
                    }
                    handlerResult = requestHandler(...requestMessage.params, cancellationSource.token);
                  } else {
                    if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
                      replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InvalidParams, `Request ${requestMessage.method} defines parameters by position but received parameters by name`), requestMessage.method, startTime);
                      return;
                    }
                    handlerResult = requestHandler(requestMessage.params, cancellationSource.token);
                  }
                } else if (starRequestHandler) {
                  handlerResult = starRequestHandler(requestMessage.method, requestMessage.params, cancellationSource.token);
                }
                const promise = handlerResult;
                if (!handlerResult) {
                  requestTokens.delete(tokenKey);
                  replySuccess(handlerResult, requestMessage.method, startTime);
                } else if (promise.then) {
                  promise.then((resultOrError) => {
                    requestTokens.delete(tokenKey);
                    reply(resultOrError, requestMessage.method, startTime);
                  }, (error) => {
                    requestTokens.delete(tokenKey);
                    if (error instanceof messages_1.ResponseError) {
                      replyError(error, requestMessage.method, startTime);
                    } else if (error && Is2.string(error.message)) {
                      replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
                    } else {
                      replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
                    }
                  });
                } else {
                  requestTokens.delete(tokenKey);
                  reply(handlerResult, requestMessage.method, startTime);
                }
              } catch (error) {
                requestTokens.delete(tokenKey);
                if (error instanceof messages_1.ResponseError) {
                  reply(error, requestMessage.method, startTime);
                } else if (error && Is2.string(error.message)) {
                  replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed with message: ${error.message}`), requestMessage.method, startTime);
                } else {
                  replyError(new messages_1.ResponseError(messages_1.ErrorCodes.InternalError, `Request ${requestMessage.method} failed unexpectedly without providing any details.`), requestMessage.method, startTime);
                }
              }
            } else {
              replyError(new messages_1.ResponseError(messages_1.ErrorCodes.MethodNotFound, `Unhandled method ${requestMessage.method}`), requestMessage.method, startTime);
            }
          }
          function handleResponse(responseMessage) {
            if (isDisposed()) {
              return;
            }
            if (responseMessage.id === null) {
              if (responseMessage.error) {
                logger.error(`Received response message without id: Error is: 
${JSON.stringify(responseMessage.error, void 0, 4)}`);
              } else {
                logger.error(`Received response message without id. No further error information provided.`);
              }
            } else {
              const key = responseMessage.id;
              const responsePromise = responsePromises.get(key);
              traceReceivedResponse(responseMessage, responsePromise);
              if (responsePromise !== void 0) {
                responsePromises.delete(key);
                try {
                  if (responseMessage.error) {
                    const error = responseMessage.error;
                    responsePromise.reject(new messages_1.ResponseError(error.code, error.message, error.data));
                  } else if (responseMessage.result !== void 0) {
                    responsePromise.resolve(responseMessage.result);
                  } else {
                    throw new Error("Should never happen.");
                  }
                } catch (error) {
                  if (error.message) {
                    logger.error(`Response handler '${responsePromise.method}' failed with message: ${error.message}`);
                  } else {
                    logger.error(`Response handler '${responsePromise.method}' failed unexpectedly.`);
                  }
                }
              }
            }
          }
          function handleNotification(message) {
            if (isDisposed()) {
              return;
            }
            let type = void 0;
            let notificationHandler;
            if (message.method === CancelNotification.type.method) {
              const cancelId = message.params.id;
              knownCanceledRequests.delete(cancelId);
              traceReceivedNotification(message);
              return;
            } else {
              const element = notificationHandlers.get(message.method);
              if (element) {
                notificationHandler = element.handler;
                type = element.type;
              }
            }
            if (notificationHandler || starNotificationHandler) {
              try {
                traceReceivedNotification(message);
                if (notificationHandler) {
                  if (message.params === void 0) {
                    if (type !== void 0) {
                      if (type.numberOfParams !== 0 && type.parameterStructures !== messages_1.ParameterStructures.byName) {
                        logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received none.`);
                      }
                    }
                    notificationHandler();
                  } else if (Array.isArray(message.params)) {
                    const params = message.params;
                    if (message.method === ProgressNotification.type.method && params.length === 2 && ProgressToken.is(params[0])) {
                      notificationHandler({ token: params[0], value: params[1] });
                    } else {
                      if (type !== void 0) {
                        if (type.parameterStructures === messages_1.ParameterStructures.byName) {
                          logger.error(`Notification ${message.method} defines parameters by name but received parameters by position`);
                        }
                        if (type.numberOfParams !== message.params.length) {
                          logger.error(`Notification ${message.method} defines ${type.numberOfParams} params but received ${params.length} arguments`);
                        }
                      }
                      notificationHandler(...params);
                    }
                  } else {
                    if (type !== void 0 && type.parameterStructures === messages_1.ParameterStructures.byPosition) {
                      logger.error(`Notification ${message.method} defines parameters by position but received parameters by name`);
                    }
                    notificationHandler(message.params);
                  }
                } else if (starNotificationHandler) {
                  starNotificationHandler(message.method, message.params);
                }
              } catch (error) {
                if (error.message) {
                  logger.error(`Notification handler '${message.method}' failed with message: ${error.message}`);
                } else {
                  logger.error(`Notification handler '${message.method}' failed unexpectedly.`);
                }
              }
            } else {
              unhandledNotificationEmitter.fire(message);
            }
          }
          function handleInvalidMessage(message) {
            if (!message) {
              logger.error("Received empty message.");
              return;
            }
            logger.error(`Received message which is neither a response nor a notification message:
${JSON.stringify(message, null, 4)}`);
            const responseMessage = message;
            if (Is2.string(responseMessage.id) || Is2.number(responseMessage.id)) {
              const key = responseMessage.id;
              const responseHandler = responsePromises.get(key);
              if (responseHandler) {
                responseHandler.reject(new Error("The received response has neither a result nor an error property."));
              }
            }
          }
          function stringifyTrace(params) {
            if (params === void 0 || params === null) {
              return void 0;
            }
            switch (trace) {
              case Trace.Verbose:
                return JSON.stringify(params, null, 4);
              case Trace.Compact:
                return JSON.stringify(params);
              default:
                return void 0;
            }
          }
          function traceSendingRequest(message) {
            if (trace === Trace.Off || !tracer) {
              return;
            }
            if (traceFormat === TraceFormat.Text) {
              let data = void 0;
              if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {
                data = `Params: ${stringifyTrace(message.params)}

`;
              }
              tracer.log(`Sending request '${message.method} - (${message.id})'.`, data);
            } else {
              logLSPMessage("send-request", message);
            }
          }
          function traceSendingNotification(message) {
            if (trace === Trace.Off || !tracer) {
              return;
            }
            if (traceFormat === TraceFormat.Text) {
              let data = void 0;
              if (trace === Trace.Verbose || trace === Trace.Compact) {
                if (message.params) {
                  data = `Params: ${stringifyTrace(message.params)}

`;
                } else {
                  data = "No parameters provided.\n\n";
                }
              }
              tracer.log(`Sending notification '${message.method}'.`, data);
            } else {
              logLSPMessage("send-notification", message);
            }
          }
          function traceSendingResponse(message, method, startTime) {
            if (trace === Trace.Off || !tracer) {
              return;
            }
            if (traceFormat === TraceFormat.Text) {
              let data = void 0;
              if (trace === Trace.Verbose || trace === Trace.Compact) {
                if (message.error && message.error.data) {
                  data = `Error data: ${stringifyTrace(message.error.data)}

`;
                } else {
                  if (message.result) {
                    data = `Result: ${stringifyTrace(message.result)}

`;
                  } else if (message.error === void 0) {
                    data = "No result returned.\n\n";
                  }
                }
              }
              tracer.log(`Sending response '${method} - (${message.id})'. Processing request took ${Date.now() - startTime}ms`, data);
            } else {
              logLSPMessage("send-response", message);
            }
          }
          function traceReceivedRequest(message) {
            if (trace === Trace.Off || !tracer) {
              return;
            }
            if (traceFormat === TraceFormat.Text) {
              let data = void 0;
              if ((trace === Trace.Verbose || trace === Trace.Compact) && message.params) {
                data = `Params: ${stringifyTrace(message.params)}

`;
              }
              tracer.log(`Received request '${message.method} - (${message.id})'.`, data);
            } else {
              logLSPMessage("receive-request", message);
            }
          }
          function traceReceivedNotification(message) {
            if (trace === Trace.Off || !tracer || message.method === LogTraceNotification.type.method) {
              return;
            }
            if (traceFormat === TraceFormat.Text) {
              let data = void 0;
              if (trace === Trace.Verbose || trace === Trace.Compact) {
                if (message.params) {
                  data = `Params: ${stringifyTrace(message.params)}

`;
                } else {
                  data = "No parameters provided.\n\n";
                }
              }
              tracer.log(`Received notification '${message.method}'.`, data);
            } else {
              logLSPMessage("receive-notification", message);
            }
          }
          function traceReceivedResponse(message, responsePromise) {
            if (trace === Trace.Off || !tracer) {
              return;
            }
            if (traceFormat === TraceFormat.Text) {
              let data = void 0;
              if (trace === Trace.Verbose || trace === Trace.Compact) {
                if (message.error && message.error.data) {
                  data = `Error data: ${stringifyTrace(message.error.data)}

`;
                } else {
                  if (message.result) {
                    data = `Result: ${stringifyTrace(message.result)}

`;
                  } else if (message.error === void 0) {
                    data = "No result returned.\n\n";
                  }
                }
              }
              if (responsePromise) {
                const error = message.error ? ` Request failed: ${message.error.message} (${message.error.code}).` : "";
                tracer.log(`Received response '${responsePromise.method} - (${message.id})' in ${Date.now() - responsePromise.timerStart}ms.${error}`, data);
              } else {
                tracer.log(`Received response ${message.id} without active response promise.`, data);
              }
            } else {
              logLSPMessage("receive-response", message);
            }
          }
          function logLSPMessage(type, message) {
            if (!tracer || trace === Trace.Off) {
              return;
            }
            const lspMessage = {
              isLSPMessage: true,
              type,
              message,
              timestamp: Date.now()
            };
            tracer.log(lspMessage);
          }
          function throwIfClosedOrDisposed() {
            if (isClosed()) {
              throw new ConnectionError(ConnectionErrors.Closed, "Connection is closed.");
            }
            if (isDisposed()) {
              throw new ConnectionError(ConnectionErrors.Disposed, "Connection is disposed.");
            }
          }
          function throwIfListening() {
            if (isListening()) {
              throw new ConnectionError(ConnectionErrors.AlreadyListening, "Connection is already listening");
            }
          }
          function throwIfNotListening() {
            if (!isListening()) {
              throw new Error("Call listen() first.");
            }
          }
          function undefinedToNull(param) {
            if (param === void 0) {
              return null;
            } else {
              return param;
            }
          }
          function nullToUndefined(param) {
            if (param === null) {
              return void 0;
            } else {
              return param;
            }
          }
          function isNamedParam(param) {
            return param !== void 0 && param !== null && !Array.isArray(param) && typeof param === "object";
          }
          function computeSingleParam(parameterStructures, param) {
            switch (parameterStructures) {
              case messages_1.ParameterStructures.auto:
                if (isNamedParam(param)) {
                  return nullToUndefined(param);
                } else {
                  return [undefinedToNull(param)];
                }
              case messages_1.ParameterStructures.byName:
                if (!isNamedParam(param)) {
                  throw new Error(`Received parameters by name but param is not an object literal.`);
                }
                return nullToUndefined(param);
              case messages_1.ParameterStructures.byPosition:
                return [undefinedToNull(param)];
              default:
                throw new Error(`Unknown parameter structure ${parameterStructures.toString()}`);
            }
          }
          function computeMessageParams(type, params) {
            let result;
            const numberOfParams = type.numberOfParams;
            switch (numberOfParams) {
              case 0:
                result = void 0;
                break;
              case 1:
                result = computeSingleParam(type.parameterStructures, params[0]);
                break;
              default:
                result = [];
                for (let i = 0; i < params.length && i < numberOfParams; i++) {
                  result.push(undefinedToNull(params[i]));
                }
                if (params.length < numberOfParams) {
                  for (let i = params.length; i < numberOfParams; i++) {
                    result.push(null);
                  }
                }
                break;
            }
            return result;
          }
          const connection2 = {
            sendNotification: (type, ...args) => {
              throwIfClosedOrDisposed();
              let method;
              let messageParams;
              if (Is2.string(type)) {
                method = type;
                const first2 = args[0];
                let paramStart = 0;
                let parameterStructures = messages_1.ParameterStructures.auto;
                if (messages_1.ParameterStructures.is(first2)) {
                  paramStart = 1;
                  parameterStructures = first2;
                }
                let paramEnd = args.length;
                const numberOfParams = paramEnd - paramStart;
                switch (numberOfParams) {
                  case 0:
                    messageParams = void 0;
                    break;
                  case 1:
                    messageParams = computeSingleParam(parameterStructures, args[paramStart]);
                    break;
                  default:
                    if (parameterStructures === messages_1.ParameterStructures.byName) {
                      throw new Error(`Received ${numberOfParams} parameters for 'by Name' notification parameter structure.`);
                    }
                    messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value));
                    break;
                }
              } else {
                const params = args;
                method = type.method;
                messageParams = computeMessageParams(type, params);
              }
              const notificationMessage = {
                jsonrpc: version,
                method,
                params: messageParams
              };
              traceSendingNotification(notificationMessage);
              return messageWriter2.write(notificationMessage).catch((error) => {
                logger.error(`Sending notification failed.`);
                throw error;
              });
            },
            onNotification: (type, handler) => {
              throwIfClosedOrDisposed();
              let method;
              if (Is2.func(type)) {
                starNotificationHandler = type;
              } else if (handler) {
                if (Is2.string(type)) {
                  method = type;
                  notificationHandlers.set(type, { type: void 0, handler });
                } else {
                  method = type.method;
                  notificationHandlers.set(type.method, { type, handler });
                }
              }
              return {
                dispose: () => {
                  if (method !== void 0) {
                    notificationHandlers.delete(method);
                  } else {
                    starNotificationHandler = void 0;
                  }
                }
              };
            },
            onProgress: (_type, token, handler) => {
              if (progressHandlers.has(token)) {
                throw new Error(`Progress handler for token ${token} already registered`);
              }
              progressHandlers.set(token, handler);
              return {
                dispose: () => {
                  progressHandlers.delete(token);
                }
              };
            },
            sendProgress: (_type, token, value) => {
              return connection2.sendNotification(ProgressNotification.type, { token, value });
            },
            onUnhandledProgress: unhandledProgressEmitter.event,
            sendRequest: (type, ...args) => {
              throwIfClosedOrDisposed();
              throwIfNotListening();
              let method;
              let messageParams;
              let token = void 0;
              if (Is2.string(type)) {
                method = type;
                const first2 = args[0];
                const last = args[args.length - 1];
                let paramStart = 0;
                let parameterStructures = messages_1.ParameterStructures.auto;
                if (messages_1.ParameterStructures.is(first2)) {
                  paramStart = 1;
                  parameterStructures = first2;
                }
                let paramEnd = args.length;
                if (cancellation_1.CancellationToken.is(last)) {
                  paramEnd = paramEnd - 1;
                  token = last;
                }
                const numberOfParams = paramEnd - paramStart;
                switch (numberOfParams) {
                  case 0:
                    messageParams = void 0;
                    break;
                  case 1:
                    messageParams = computeSingleParam(parameterStructures, args[paramStart]);
                    break;
                  default:
                    if (parameterStructures === messages_1.ParameterStructures.byName) {
                      throw new Error(`Received ${numberOfParams} parameters for 'by Name' request parameter structure.`);
                    }
                    messageParams = args.slice(paramStart, paramEnd).map((value) => undefinedToNull(value));
                    break;
                }
              } else {
                const params = args;
                method = type.method;
                messageParams = computeMessageParams(type, params);
                const numberOfParams = type.numberOfParams;
                token = cancellation_1.CancellationToken.is(params[numberOfParams]) ? params[numberOfParams] : void 0;
              }
              const id = sequenceNumber++;
              let disposable2;
              if (token) {
                disposable2 = token.onCancellationRequested(() => {
                  const p = cancellationStrategy.sender.sendCancellation(connection2, id);
                  if (p === void 0) {
                    logger.log(`Received no promise from cancellation strategy when cancelling id ${id}`);
                    return Promise.resolve();
                  } else {
                    return p.catch(() => {
                      logger.log(`Sending cancellation messages for id ${id} failed`);
                    });
                  }
                });
              }
              const requestMessage = {
                jsonrpc: version,
                id,
                method,
                params: messageParams
              };
              traceSendingRequest(requestMessage);
              if (typeof cancellationStrategy.sender.enableCancellation === "function") {
                cancellationStrategy.sender.enableCancellation(requestMessage);
              }
              return new Promise(async (resolve, reject) => {
                const resolveWithCleanup = (r) => {
                  resolve(r);
                  cancellationStrategy.sender.cleanup(id);
                  disposable2?.dispose();
                };
                const rejectWithCleanup = (r) => {
                  reject(r);
                  cancellationStrategy.sender.cleanup(id);
                  disposable2?.dispose();
                };
                const responsePromise = { method, timerStart: Date.now(), resolve: resolveWithCleanup, reject: rejectWithCleanup };
                try {
                  await messageWriter2.write(requestMessage);
                  responsePromises.set(id, responsePromise);
                } catch (error) {
                  logger.error(`Sending request failed.`);
                  responsePromise.reject(new messages_1.ResponseError(messages_1.ErrorCodes.MessageWriteError, error.message ? error.message : "Unknown reason"));
                  throw error;
                }
              });
            },
            onRequest: (type, handler) => {
              throwIfClosedOrDisposed();
              let method = null;
              if (StarRequestHandler.is(type)) {
                method = void 0;
                starRequestHandler = type;
              } else if (Is2.string(type)) {
                method = null;
                if (handler !== void 0) {
                  method = type;
                  requestHandlers.set(type, { handler, type: void 0 });
                }
              } else {
                if (handler !== void 0) {
                  method = type.method;
                  requestHandlers.set(type.method, { type, handler });
                }
              }
              return {
                dispose: () => {
                  if (method === null) {
                    return;
                  }
                  if (method !== void 0) {
                    requestHandlers.delete(method);
                  } else {
                    starRequestHandler = void 0;
                  }
                }
              };
            },
            hasPendingResponse: () => {
              return responsePromises.size > 0;
            },
            trace: async (_value, _tracer, sendNotificationOrTraceOptions) => {
              let _sendNotification = false;
              let _traceFormat = TraceFormat.Text;
              if (sendNotificationOrTraceOptions !== void 0) {
                if (Is2.boolean(sendNotificationOrTraceOptions)) {
                  _sendNotification = sendNotificationOrTraceOptions;
                } else {
                  _sendNotification = sendNotificationOrTraceOptions.sendNotification || false;
                  _traceFormat = sendNotificationOrTraceOptions.traceFormat || TraceFormat.Text;
                }
              }
              trace = _value;
              traceFormat = _traceFormat;
              if (trace === Trace.Off) {
                tracer = void 0;
              } else {
                tracer = _tracer;
              }
              if (_sendNotification && !isClosed() && !isDisposed()) {
                await connection2.sendNotification(SetTraceNotification.type, { value: Trace.toString(_value) });
              }
            },
            onError: errorEmitter.event,
            onClose: closeEmitter.event,
            onUnhandledNotification: unhandledNotificationEmitter.event,
            onDispose: disposeEmitter.event,
            end: () => {
              messageWriter2.end();
            },
            dispose: () => {
              if (isDisposed()) {
                return;
              }
              state = ConnectionState.Disposed;
              disposeEmitter.fire(void 0);
              const error = new messages_1.ResponseError(messages_1.ErrorCodes.PendingResponseRejected, "Pending response rejected since connection got disposed");
              for (const promise of responsePromises.values()) {
                promise.reject(error);
              }
              responsePromises = /* @__PURE__ */ new Map();
              requestTokens = /* @__PURE__ */ new Map();
              knownCanceledRequests = /* @__PURE__ */ new Set();
              messageQueue = new linkedMap_1.LinkedMap();
              if (Is2.func(messageWriter2.dispose)) {
                messageWriter2.dispose();
              }
              if (Is2.func(messageReader2.dispose)) {
                messageReader2.dispose();
              }
            },
            listen: () => {
              throwIfClosedOrDisposed();
              throwIfListening();
              state = ConnectionState.Listening;
              messageReader2.listen(callback);
            },
            inspect: () => {
              (0, ral_1.default)().console.log("inspect");
            }
          };
          connection2.onNotification(LogTraceNotification.type, (params) => {
            if (trace === Trace.Off || !tracer) {
              return;
            }
            const verbose = trace === Trace.Verbose || trace === Trace.Compact;
            tracer.log(params.message, verbose ? params.verbose : void 0);
          });
          connection2.onNotification(ProgressNotification.type, (params) => {
            const handler = progressHandlers.get(params.token);
            if (handler) {
              handler(params.value);
            } else {
              unhandledProgressEmitter.fire(params);
            }
          });
          return connection2;
        }
        exports2.createMessageConnection = createMessageConnection;
      })(connection$2);
      return connection$2;
    }
    var hasRequiredApi$2;
    function requireApi$2() {
      if (hasRequiredApi$2) return api$2;
      hasRequiredApi$2 = 1;
      (function(exports2) {
        Object.defineProperty(exports2, "__esModule", { value: true });
        exports2.ProgressType = exports2.ProgressToken = exports2.createMessageConnection = exports2.NullLogger = exports2.ConnectionOptions = exports2.ConnectionStrategy = exports2.AbstractMessageBuffer = exports2.WriteableStreamMessageWriter = exports2.AbstractMessageWriter = exports2.MessageWriter = exports2.ReadableStreamMessageReader = exports2.AbstractMessageReader = exports2.MessageReader = exports2.SharedArrayReceiverStrategy = exports2.SharedArraySenderStrategy = exports2.CancellationToken = exports2.CancellationTokenSource = exports2.Emitter = exports2.Event = exports2.Disposable = exports2.LRUCache = exports2.Touch = exports2.LinkedMap = exports2.ParameterStructures = exports2.NotificationType9 = exports2.NotificationType8 = exports2.NotificationType7 = exports2.NotificationType6 = exports2.NotificationType5 = exports2.NotificationType4 = exports2.NotificationType3 = exports2.NotificationType2 = exports2.NotificationType1 = exports2.NotificationType0 = exports2.NotificationType = exports2.ErrorCodes = exports2.ResponseError = exports2.RequestType9 = exports2.RequestType8 = exports2.RequestType7 = exports2.RequestType6 = exports2.RequestType5 = exports2.RequestType4 = exports2.RequestType3 = exports2.RequestType2 = exports2.RequestType1 = exports2.RequestType0 = exports2.RequestType = exports2.Message = exports2.RAL = void 0;
        exports2.MessageStrategy = exports2.CancellationStrategy = exports2.CancellationSenderStrategy = exports2.CancellationReceiverStrategy = exports2.ConnectionError = exports2.ConnectionErrors = exports2.LogTraceNotification = exports2.SetTraceNotification = exports2.TraceFormat = exports2.TraceValues = exports2.Trace = void 0;
        const messages_1 = requireMessages$1();
        Object.defineProperty(exports2, "Message", { enumerable: true, get: function() {
          return messages_1.Message;
        } });
        Object.defineProperty(exports2, "RequestType", { enumerable: true, get: function() {
          return messages_1.RequestType;
        } });
        Object.defineProperty(exports2, "RequestType0", { enumerable: true, get: function() {
          return messages_1.RequestType0;
        } });
        Object.defineProperty(exports2, "RequestType1", { enumerable: true, get: function() {
          return messages_1.RequestType1;
        } });
        Object.defineProperty(exports2, "RequestType2", { enumerable: true, get: function() {
          return messages_1.RequestType2;
        } });
        Object.defineProperty(exports2, "RequestType3", { enumerable: true, get: function() {
          return messages_1.RequestType3;
        } });
        Object.defineProperty(exports2, "RequestType4", { enumerable: true, get: function() {
          return messages_1.RequestType4;
        } });
        Object.defineProperty(exports2, "RequestType5", { enumerable: true, get: function() {
          return messages_1.RequestType5;
        } });
        Object.defineProperty(exports2, "RequestType6", { enumerable: true, get: function() {
          return messages_1.RequestType6;
        } });
        Object.defineProperty(exports2, "RequestType7", { enumerable: true, get: function() {
          return messages_1.RequestType7;
        } });
        Object.defineProperty(exports2, "RequestType8", { enumerable: true, get: function() {
          return messages_1.RequestType8;
        } });
        Object.defineProperty(exports2, "RequestType9", { enumerable: true, get: function() {
          return messages_1.RequestType9;
        } });
        Object.defineProperty(exports2, "ResponseError", { enumerable: true, get: function() {
          return messages_1.ResponseError;
        } });
        Object.defineProperty(exports2, "ErrorCodes", { enumerable: true, get: function() {
          return messages_1.ErrorCodes;
        } });
        Object.defineProperty(exports2, "NotificationType", { enumerable: true, get: function() {
          return messages_1.NotificationType;
        } });
        Object.defineProperty(exports2, "NotificationType0", { enumerable: true, get: function() {
          return messages_1.NotificationType0;
        } });
        Object.defineProperty(exports2, "NotificationType1", { enumerable: true, get: function() {
          return messages_1.NotificationType1;
        } });
        Object.defineProperty(exports2, "NotificationType2", { enumerable: true, get: function() {
          return messages_1.NotificationType2;
        } });
        Object.defineProperty(exports2, "NotificationType3", { enumerable: true, get: function() {
          return messages_1.NotificationType3;
        } });
        Object.defineProperty(exports2, "NotificationType4", { enumerable: true, get: function() {
          return messages_1.NotificationType4;
        } });
        Object.defineProperty(exports2, "NotificationType5", { enumerable: true, get: function() {
          return messages_1.NotificationType5;
        } });
        Object.defineProperty(exports2, "NotificationType6", { enumerable: true, get: function() {
          return messages_1.NotificationType6;
        } });
        Object.defineProperty(exports2, "NotificationType7", { enumerable: true, get: function() {
          return messages_1.NotificationType7;
        } });
        Object.defineProperty(exports2, "NotificationType8", { enumerable: true, get: function() {
          return messages_1.NotificationType8;
        } });
        Object.defineProperty(exports2, "NotificationType9", { enumerable: true, get: function() {
          return messages_1.NotificationType9;
        } });
        Object.defineProperty(exports2, "ParameterStructures", { enumerable: true, get: function() {
          return messages_1.ParameterStructures;
        } });
        const linkedMap_1 = requireLinkedMap();
        Object.defineProperty(exports2, "LinkedMap", { enumerable: true, get: function() {
          return linkedMap_1.LinkedMap;
        } });
        Object.defineProperty(exports2, "LRUCache", { enumerable: true, get: function() {
          return linkedMap_1.LRUCache;
        } });
        Object.defineProperty(exports2, "Touch", { enumerable: true, get: function() {
          return linkedMap_1.Touch;
        } });
        const disposable_1 = requireDisposable();
        Object.defineProperty(exports2, "Disposable", { enumerable: true, get: function() {
          return disposable_1.Disposable;
        } });
        const events_1 = requireEvents$1();
        Object.defineProperty(exports2, "Event", { enumerable: true, get: function() {
          return events_1.Event;
        } });
        Object.defineProperty(exports2, "Emitter", { enumerable: true, get: function() {
          return events_1.Emitter;
        } });
        const cancellation_1 = requireCancellation$1();
        Object.defineProperty(exports2, "CancellationTokenSource", { enumerable: true, get: function() {
          return cancellation_1.CancellationTokenSource;
        } });
        Object.defineProperty(exports2, "CancellationToken", { enumerable: true, get: function() {
          return cancellation_1.CancellationToken;
        } });
        const sharedArrayCancellation_1 = requireSharedArrayCancellation();
        Object.defineProperty(exports2, "SharedArraySenderStrategy", { enumerable: true, get: function() {
          return sharedArrayCancellation_1.SharedArraySenderStrategy;
        } });
        Object.defineProperty(exports2, "SharedArrayReceiverStrategy", { enumerable: true, get: function() {
          return sharedArrayCancellation_1.SharedArrayReceiverStrategy;
        } });
        const messageReader_1 = requireMessageReader();
        Object.defineProperty(exports2, "MessageReader", { enumerable: true, get: function() {
          return messageReader_1.MessageReader;
        } });
        Object.defineProperty(exports2, "AbstractMessageReader", { enumerable: true, get: function() {
          return messageReader_1.AbstractMessageReader;
        } });
        Object.defineProperty(exports2, "ReadableStreamMessageReader", { enumerable: true, get: function() {
          return messageReader_1.ReadableStreamMessageReader;
        } });
        const messageWriter_1 = requireMessageWriter();
        Object.defineProperty(exports2, "MessageWriter", { enumerable: true, get: function() {
          return messageWriter_1.MessageWriter;
        } });
        Object.defineProperty(exports2, "AbstractMessageWriter", { enumerable: true, get: function() {
          return messageWriter_1.AbstractMessageWriter;
        } });
        Object.defineProperty(exports2, "WriteableStreamMessageWriter", { enumerable: true, get: function() {
          return messageWriter_1.WriteableStreamMessageWriter;
        } });
        const messageBuffer_1 = requireMessageBuffer();
        Object.defineProperty(exports2, "AbstractMessageBuffer", { enumerable: true, get: function() {
          return messageBuffer_1.AbstractMessageBuffer;
        } });
        const connection_1 = requireConnection$1();
        Object.defineProperty(exports2, "ConnectionStrategy", { enumerable: true, get: function() {
          return connection_1.ConnectionStrategy;
        } });
        Object.defineProperty(exports2, "ConnectionOptions", { enumerable: true, get: function() {
          return connection_1.ConnectionOptions;
        } });
        Object.defineProperty(exports2, "NullLogger", { enumerable: true, get: function() {
          return connection_1.NullLogger;
        } });
        Object.defineProperty(exports2, "createMessageConnection", { enumerable: true, get: function() {
          return connection_1.createMessageConnection;
        } });
        Object.defineProperty(exports2, "ProgressToken", { enumerable: true, get: function() {
          return connection_1.ProgressToken;
        } });
        Object.defineProperty(exports2, "ProgressType", { enumerable: true, get: function() {
          return connection_1.ProgressType;
        } });
        Object.defineProperty(exports2, "Trace", { enumerable: true, get: function() {
          return connection_1.Trace;
        } });
        Object.defineProperty(exports2, "TraceValues", { enumerable: true, get: function() {
          return connection_1.TraceValues;
        } });
        Object.defineProperty(exports2, "TraceFormat", { enumerable: true, get: function() {
          return connection_1.TraceFormat;
        } });
        Object.defineProperty(exports2, "SetTraceNotification", { enumerable: true, get: function() {
          return connection_1.SetTraceNotification;
        } });
        Object.defineProperty(exports2, "LogTraceNotification", { enumerable: true, get: function() {
          return connection_1.LogTraceNotification;
        } });
        Object.defineProperty(exports2, "ConnectionErrors", { enumerable: true, get: function() {
          return connection_1.ConnectionErrors;
        } });
        Object.defineProperty(exports2, "ConnectionError", { enumerable: true, get: function() {
          return connection_1.ConnectionError;
        } });
        Object.defineProperty(exports2, "CancellationReceiverStrategy", { enumerable: true, get: function() {
          return connection_1.CancellationReceiverStrategy;
        } });
        Object.defineProperty(exports2, "CancellationSenderStrategy", { enumerable: true, get: function() {
          return connection_1.CancellationSenderStrategy;
        } });
        Object.defineProperty(exports2, "CancellationStrategy", { enumerable: true, get: function() {
          return connection_1.CancellationStrategy;
        } });
        Object.defineProperty(exports2, "MessageStrategy", { enumerable: true, get: function() {
          return connection_1.MessageStrategy;
        } });
        const ral_1 = requireRal$1();
        exports2.RAL = ral_1.default;
      })(api$2);
      return api$2;
    }
    var hasRequiredRil;
    function requireRil() {
      if (hasRequiredRil) return ril;
      hasRequiredRil = 1;
      Object.defineProperty(ril, "__esModule", { value: true });
      const util_1 = require$$0;
      const api_1 = requireApi$2();
      class MessageBuffer extends api_1.AbstractMessageBuffer {
        constructor(encoding = "utf-8") {
          super(encoding);
        }
        emptyBuffer() {
          return MessageBuffer.emptyBuffer;
        }
        fromString(value, encoding) {
          return Buffer.from(value, encoding);
        }
        toString(value, encoding) {
          if (value instanceof Buffer) {
            return value.toString(encoding);
          } else {
            return new util_1.TextDecoder(encoding).decode(value);
          }
        }
        asNative(buffer, length) {
          if (length === void 0) {
            return buffer instanceof Buffer ? buffer : Buffer.from(buffer);
          } else {
            return buffer instanceof Buffer ? buffer.slice(0, length) : Buffer.from(buffer, 0, length);
          }
        }
        allocNative(length) {
          return Buffer.allocUnsafe(length);
        }
      }
      MessageBuffer.emptyBuffer = Buffer.allocUnsafe(0);
      class ReadableStreamWrapper {
        constructor(stream2) {
          this.stream = stream2;
        }
        onClose(listener) {
          this.stream.on("close", listener);
          return api_1.Disposable.create(() => this.stream.off("close", listener));
        }
        onError(listener) {
          this.stream.on("error", listener);
          return api_1.Disposable.create(() => this.stream.off("error", listener));
        }
        onEnd(listener) {
          this.stream.on("end", listener);
          return api_1.Disposable.create(() => this.stream.off("end", listener));
        }
        onData(listener) {
          this.stream.on("data", listener);
          return api_1.Disposable.create(() => this.stream.off("data", listener));
        }
      }
      class WritableStreamWrapper {
        constructor(stream2) {
          this.stream = stream2;
        }
        onClose(listener) {
          this.stream.on("close", listener);
          return api_1.Disposable.create(() => this.stream.off("close", listener));
        }
        onError(listener) {
          this.stream.on("error", listener);
          return api_1.Disposable.create(() => this.stream.off("error", listener));
        }
        onEnd(listener) {
          this.stream.on("end", listener);
          return api_1.Disposable.create(() => this.stream.off("end", listener));
        }
        write(data, encoding) {
          return new Promise((resolve, reject) => {
            const callback = (error) => {
              if (error === void 0 || error === null) {
                resolve();
              } else {
                reject(error);
              }
            };
            if (typeof data === "string") {
              this.stream.write(data, encoding, callback);
            } else {
              this.stream.write(data, callback);
            }
          });
        }
        end() {
          this.stream.end();
        }
      }
      const _ril = Object.freeze({
        messageBuffer: Object.freeze({
          create: (encoding) => new MessageBuffer(encoding)
        }),
        applicationJson: Object.freeze({
          encoder: Object.freeze({
            name: "application/json",
            encode: (msg, options) => {
              try {
                return Promise.resolve(Buffer.from(JSON.stringify(msg, void 0, 0), options.charset));
              } catch (err) {
                return Promise.reject(err);
              }
            }
          }),
          decoder: Object.freeze({
            name: "application/json",
            decode: (buffer, options) => {
              try {
                if (buffer instanceof Buffer) {
                  return Promise.resolve(JSON.parse(buffer.toString(options.charset)));
                } else {
                  return Promise.resolve(JSON.parse(new util_1.TextDecoder(options.charset).decode(buffer)));
                }
              } catch (err) {
                return Promise.reject(err);
              }
            }
          })
        }),
        stream: Object.freeze({
          asReadableStream: (stream2) => new ReadableStreamWrapper(stream2),
          asWritableStream: (stream2) => new WritableStreamWrapper(stream2)
        }),
        console,
        timer: Object.freeze({
          setTimeout(callback, ms, ...args) {
            const handle = setTimeout(callback, ms, ...args);
            return { dispose: () => clearTimeout(handle) };
          },
          setImmediate(callback, ...args) {
            const handle = setImmediate(callback, ...args);
            return { dispose: () => clearImmediate(handle) };
          },
          setInterval(callback, ms, ...args) {
            const handle = setInterval(callback, ms, ...args);
            return { dispose: () => clearInterval(handle) };
          }
        })
      });
      function RIL() {
        return _ril;
      }
      (function(RIL2) {
        function install() {
          api_1.RAL.install(_ril);
        }
        RIL2.install = install;
      })(RIL || (RIL = {}));
      ril.default = RIL;
      return ril;
    }
    var hasRequiredMain$3;
    function requireMain$3() {
      if (hasRequiredMain$3) return main$1;
      hasRequiredMain$3 = 1;
      (function(exports2) {
        var __createBinding = main$1 && main$1.__createBinding || (Object.create ? (function(o, m, k, k2) {
          if (k2 === void 0) k2 = k;
          var desc = Object.getOwnPropertyDescriptor(m, k);
          if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function() {
              return m[k];
            } };
          }
          Object.defineProperty(o, k2, desc);
        }) : (function(o, m, k, k2) {
          if (k2 === void 0) k2 = k;
          o[k2] = m[k];
        }));
        var __exportStar = main$1 && main$1.__exportStar || function(m, exports3) {
          for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
        };
        Object.defineProperty(exports2, "__esModule", { value: true });
        exports2.createMessageConnection = exports2.createServerSocketTransport = exports2.createClientSocketTransport = exports2.createServerPipeTransport = exports2.createClientPipeTransport = exports2.generateRandomPipeName = exports2.StreamMessageWriter = exports2.StreamMessageReader = exports2.SocketMessageWriter = exports2.SocketMessageReader = exports2.PortMessageWriter = exports2.PortMessageReader = exports2.IPCMessageWriter = exports2.IPCMessageReader = void 0;
        const ril_1 = requireRil();
        ril_1.default.install();
        const path = require$$1;
        const os = require$$2;
        const crypto_1 = require$$3;
        const net_1 = require$$4;
        const api_1 = requireApi$2();
        __exportStar(requireApi$2(), exports2);
        class IPCMessageReader extends api_1.AbstractMessageReader {
          constructor(process2) {
            super();
            this.process = process2;
            let eventEmitter = this.process;
            eventEmitter.on("error", (error) => this.fireError(error));
            eventEmitter.on("close", () => this.fireClose());
          }
          listen(callback) {
            this.process.on("message", callback);
            return api_1.Disposable.create(() => this.process.off("message", callback));
          }
        }
        exports2.IPCMessageReader = IPCMessageReader;
        class IPCMessageWriter extends api_1.AbstractMessageWriter {
          constructor(process2) {
            super();
            this.process = process2;
            this.errorCount = 0;
            const eventEmitter = this.process;
            eventEmitter.on("error", (error) => this.fireError(error));
            eventEmitter.on("close", () => this.fireClose);
          }
          write(msg) {
            try {
              if (typeof this.process.send === "function") {
                this.process.send(msg, void 0, void 0, (error) => {
                  if (error) {
                    this.errorCount++;
                    this.handleError(error, msg);
                  } else {
                    this.errorCount = 0;
                  }
                });
              }
              return Promise.resolve();
            } catch (error) {
              this.handleError(error, msg);
              return Promise.reject(error);
            }
          }
          handleError(error, msg) {
            this.errorCount++;
            this.fireError(error, msg, this.errorCount);
          }
          end() {
          }
        }
        exports2.IPCMessageWriter = IPCMessageWriter;
        class PortMessageReader extends api_1.AbstractMessageReader {
          constructor(port) {
            super();
            this.onData = new api_1.Emitter();
            port.on("close", () => this.fireClose);
            port.on("error", (error) => this.fireError(error));
            port.on("message", (message) => {
              this.onData.fire(message);
            });
          }
          listen(callback) {
            return this.onData.event(callback);
          }
        }
        exports2.PortMessageReader = PortMessageReader;
        class PortMessageWriter extends api_1.AbstractMessageWriter {
          constructor(port) {
            super();
            this.port = port;
            this.errorCount = 0;
            port.on("close", () => this.fireClose());
            port.on("error", (error) => this.fireError(error));
          }
          write(msg) {
            try {
              this.port.postMessage(msg);
              return Promise.resolve();
            } catch (error) {
              this.handleError(error, msg);
              return Promise.reject(error);
            }
          }
          handleError(error, msg) {
            this.errorCount++;
            this.fireError(error, msg, this.errorCount);
          }
          end() {
          }
        }
        exports2.PortMessageWriter = PortMessageWriter;
        class SocketMessageReader extends api_1.ReadableStreamMessageReader {
          constructor(socket, encoding = "utf-8") {
            super((0, ril_1.default)().stream.asReadableStream(socket), encoding);
          }
        }
        exports2.SocketMessageReader = SocketMessageReader;
        class SocketMessageWriter extends api_1.WriteableStreamMessageWriter {
          constructor(socket, options) {
            super((0, ril_1.default)().stream.asWritableStream(socket), options);
            this.socket = socket;
          }
          dispose() {
            super.dispose();
            this.socket.destroy();
          }
        }
        exports2.SocketMessageWriter = SocketMessageWriter;
        class StreamMessageReader extends api_1.ReadableStreamMessageReader {
          constructor(readable, encoding) {
            super((0, ril_1.default)().stream.asReadableStream(readable), encoding);
          }
        }
        exports2.StreamMessageReader = StreamMessageReader;
        class StreamMessageWriter extends api_1.WriteableStreamMessageWriter {
          constructor(writable, options) {
            super((0, ril_1.default)().stream.asWritableStream(writable), options);
          }
        }
        exports2.StreamMessageWriter = StreamMessageWriter;
        const XDG_RUNTIME_DIR = process.env["XDG_RUNTIME_DIR"];
        const safeIpcPathLengths = /* @__PURE__ */ new Map([
          ["linux", 107],
          ["darwin", 103]
        ]);
        function generateRandomPipeName() {
          const randomSuffix = (0, crypto_1.randomBytes)(21).toString("hex");
          if (process.platform === "win32") {
            return `\\\\.\\pipe\\vscode-jsonrpc-${randomSuffix}-sock`;
          }
          let result;
          if (XDG_RUNTIME_DIR) {
            result = path.join(XDG_RUNTIME_DIR, `vscode-ipc-${randomSuffix}.sock`);
          } else {
            result = path.join(os.tmpdir(), `vscode-${randomSuffix}.sock`);
          }
          const limit = safeIpcPathLengths.get(process.platform);
          if (limit !== void 0 && result.length > limit) {
            (0, ril_1.default)().console.warn(`WARNING: IPC handle "${result}" is longer than ${limit} characters.`);
          }
          return result;
        }
        exports2.generateRandomPipeName = generateRandomPipeName;
        function createClientPipeTransport(pipeName, encoding = "utf-8") {
          let connectResolve;
          const connected = new Promise((resolve, _reject) => {
            connectResolve = resolve;
          });
          return new Promise((resolve, reject) => {
            let server2 = (0, net_1.createServer)((socket) => {
              server2.close();
              connectResolve([
                new SocketMessageReader(socket, encoding),
                new SocketMessageWriter(socket, encoding)
              ]);
            });
            server2.on("error", reject);
            server2.listen(pipeName, () => {
              server2.removeListener("error", reject);
              resolve({
                onConnected: () => {
                  return connected;
                }
              });
            });
          });
        }
        exports2.createClientPipeTransport = createClientPipeTransport;
        function createServerPipeTransport(pipeName, encoding = "utf-8") {
          const socket = (0, net_1.createConnection)(pipeName);
          return [
            new SocketMessageReader(socket, encoding),
            new SocketMessageWriter(socket, encoding)
          ];
        }
        exports2.createServerPipeTransport = createServerPipeTransport;
        function createClientSocketTransport(port, encoding = "utf-8") {
          let connectResolve;
          const connected = new Promise((resolve, _reject) => {
            connectResolve = resolve;
          });
          return new Promise((resolve, reject) => {
            const server2 = (0, net_1.createServer)((socket) => {
              server2.close();
              connectResolve([
                new SocketMessageReader(socket, encoding),
                new SocketMessageWriter(socket, encoding)
              ]);
            });
            server2.on("error", reject);
            server2.listen(port, "127.0.0.1", () => {
              server2.removeListener("error", reject);
              resolve({
                onConnected: () => {
                  return connected;
                }
              });
            });
          });
        }
        exports2.createClientSocketTransport = createClientSocketTransport;
        function createServerSocketTransport(port, encoding = "utf-8") {
          const socket = (0, net_1.createConnection)(port, "127.0.0.1");
          return [
            new SocketMessageReader(socket, encoding),
            new SocketMessageWriter(socket, encoding)
          ];
        }
        exports2.createServerSocketTransport = createServerSocketTransport;
        function isReadableStream(value) {
          const candidate = value;
          return candidate.read !== void 0 && candidate.addListener !== void 0;
        }
        function isWritableStream(value) {
          const candidate = value;
          return candidate.write !== void 0 && candidate.addListener !== void 0;
        }
        function createMessageConnection(input, output, logger, options) {
          if (!logger) {
            logger = api_1.NullLogger;
          }
          const reader = isReadableStream(input) ? new StreamMessageReader(input) : input;
          const writer = isWritableStream(output) ? new StreamMessageWriter(output) : output;
          if (api_1.ConnectionStrategy.is(options)) {
            options = { connectionStrategy: options };
          }
          return (0, api_1.createMessageConnection)(reader, writer, logger, options);
        }
        exports2.createMessageConnection = createMessageConnection;
      })(main$1);
      return main$1;
    }
    var node$2;
    var hasRequiredNode$2;
    function requireNode$2() {
      if (hasRequiredNode$2) return node$2;
      hasRequiredNode$2 = 1;
      node$2 = requireMain$3();
      return node$2;
    }
    var api$1 = {};
    function commonjsRequire(path) {
      throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
    }
    var main = { exports: {} };
    var hasRequiredMain$2;
    function requireMain$2() {
      if (hasRequiredMain$2) return main.exports;
      hasRequiredMain$2 = 1;
      (function(module2, exports2) {
        (function(factory) {
          {
            var v = factory(commonjsRequire, exports2);
            if (v !== void 0) module2.exports = v;
          }
        })(function(require2, exports3) {
          Object.defineProperty(exports3, "__esModule", { value: true });
          exports3.TextDocument = exports3.EOL = exports3.WorkspaceFolder = exports3.InlineCompletionContext = exports3.SelectedCompletionInfo = exports3.InlineCompletionTriggerKind = exports3.InlineCompletionList = exports3.InlineCompletionItem = exports3.StringValue = exports3.InlayHint = exports3.InlayHintLabelPart = exports3.InlayHintKind = exports3.InlineValueContext = exports3.InlineValueEvaluatableExpression = exports3.InlineValueVariableLookup = exports3.InlineValueText = exports3.SemanticTokens = exports3.SemanticTokenModifiers = exports3.SemanticTokenTypes = exports3.SelectionRange = exports3.DocumentLink = exports3.FormattingOptions = exports3.CodeLens = exports3.CodeAction = exports3.CodeActionContext = exports3.CodeActionTriggerKind = exports3.CodeActionKind = exports3.DocumentSymbol = exports3.WorkspaceSymbol = exports3.SymbolInformation = exports3.SymbolTag = exports3.SymbolKind = exports3.DocumentHighlight = exports3.DocumentHighlightKind = exports3.SignatureInformation = exports3.ParameterInformation = exports3.Hover = exports3.MarkedString = exports3.CompletionList = exports3.CompletionItem = exports3.CompletionItemLabelDetails = exports3.InsertTextMode = exports3.InsertReplaceEdit = exports3.CompletionItemTag = exports3.InsertTextFormat = exports3.CompletionItemKind = exports3.MarkupContent = exports3.MarkupKind = exports3.TextDocumentItem = exports3.OptionalVersionedTextDocumentIdentifier = exports3.VersionedTextDocumentIdentifier = exports3.TextDocumentIdentifier = exports3.WorkspaceChange = exports3.WorkspaceEdit = exports3.DeleteFile = exports3.RenameFile = exports3.CreateFile = exports3.TextDocumentEdit = exports3.AnnotatedTextEdit = exports3.ChangeAnnotationIdentifier = exports3.ChangeAnnotation = exports3.TextEdit = exports3.Command = exports3.Diagnostic = exports3.CodeDescription = exports3.DiagnosticTag = exports3.DiagnosticSeverity = exports3.DiagnosticRelatedInformation = exports3.FoldingRange = exports3.FoldingRangeKind = exports3.ColorPresentation = exports3.ColorInformation = exports3.Color = exports3.LocationLink = exports3.Location = exports3.Range = exports3.Position = exports3.uinteger = exports3.integer = exports3.URI = exports3.DocumentUri = void 0;
          var DocumentUri2;
          (function(DocumentUri3) {
            function is2(value) {
              return typeof value === "string";
            }
            DocumentUri3.is = is2;
          })(DocumentUri2 || (exports3.DocumentUri = DocumentUri2 = {}));
          var URI2;
          (function(URI3) {
            function is2(value) {
              return typeof value === "string";
            }
            URI3.is = is2;
          })(URI2 || (exports3.URI = URI2 = {}));
          var integer2;
          (function(integer3) {
            integer3.MIN_VALUE = -2147483648;
            integer3.MAX_VALUE = 2147483647;
            function is2(value) {
              return typeof value === "number" && integer3.MIN_VALUE <= value && value <= integer3.MAX_VALUE;
            }
            integer3.is = is2;
          })(integer2 || (exports3.integer = integer2 = {}));
          var uinteger2;
          (function(uinteger3) {
            uinteger3.MIN_VALUE = 0;
            uinteger3.MAX_VALUE = 2147483647;
            function is2(value) {
              return typeof value === "number" && uinteger3.MIN_VALUE <= value && value <= uinteger3.MAX_VALUE;
            }
            uinteger3.is = is2;
          })(uinteger2 || (exports3.uinteger = uinteger2 = {}));
          var Position2;
          (function(Position3) {
            function create(line, character) {
              if (line === Number.MAX_VALUE) {
                line = uinteger2.MAX_VALUE;
              }
              if (character === Number.MAX_VALUE) {
                character = uinteger2.MAX_VALUE;
              }
              return { line, character };
            }
            Position3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(candidate) && Is2.uinteger(candidate.line) && Is2.uinteger(candidate.character);
            }
            Position3.is = is2;
          })(Position2 || (exports3.Position = Position2 = {}));
          var Range2;
          (function(Range3) {
            function create(one, two, three, four) {
              if (Is2.uinteger(one) && Is2.uinteger(two) && Is2.uinteger(three) && Is2.uinteger(four)) {
                return { start: Position2.create(one, two), end: Position2.create(three, four) };
              } else if (Position2.is(one) && Position2.is(two)) {
                return { start: one, end: two };
              } else {
                throw new Error("Range#create called with invalid arguments[".concat(one, ", ").concat(two, ", ").concat(three, ", ").concat(four, "]"));
              }
            }
            Range3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(candidate) && Position2.is(candidate.start) && Position2.is(candidate.end);
            }
            Range3.is = is2;
          })(Range2 || (exports3.Range = Range2 = {}));
          var Location2;
          (function(Location3) {
            function create(uri, range) {
              return { uri, range };
            }
            Location3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(candidate) && Range2.is(candidate.range) && (Is2.string(candidate.uri) || Is2.undefined(candidate.uri));
            }
            Location3.is = is2;
          })(Location2 || (exports3.Location = Location2 = {}));
          var LocationLink2;
          (function(LocationLink3) {
            function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
              return { targetUri, targetRange, targetSelectionRange, originSelectionRange };
            }
            LocationLink3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(candidate) && Range2.is(candidate.targetRange) && Is2.string(candidate.targetUri) && Range2.is(candidate.targetSelectionRange) && (Range2.is(candidate.originSelectionRange) || Is2.undefined(candidate.originSelectionRange));
            }
            LocationLink3.is = is2;
          })(LocationLink2 || (exports3.LocationLink = LocationLink2 = {}));
          var Color2;
          (function(Color3) {
            function create(red, green, blue, alpha) {
              return {
                red,
                green,
                blue,
                alpha
              };
            }
            Color3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(candidate) && Is2.numberRange(candidate.red, 0, 1) && Is2.numberRange(candidate.green, 0, 1) && Is2.numberRange(candidate.blue, 0, 1) && Is2.numberRange(candidate.alpha, 0, 1);
            }
            Color3.is = is2;
          })(Color2 || (exports3.Color = Color2 = {}));
          var ColorInformation2;
          (function(ColorInformation3) {
            function create(range, color) {
              return {
                range,
                color
              };
            }
            ColorInformation3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(candidate) && Range2.is(candidate.range) && Color2.is(candidate.color);
            }
            ColorInformation3.is = is2;
          })(ColorInformation2 || (exports3.ColorInformation = ColorInformation2 = {}));
          var ColorPresentation2;
          (function(ColorPresentation3) {
            function create(label, textEdit, additionalTextEdits) {
              return {
                label,
                textEdit,
                additionalTextEdits
              };
            }
            ColorPresentation3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(candidate) && Is2.string(candidate.label) && (Is2.undefined(candidate.textEdit) || TextEdit2.is(candidate)) && (Is2.undefined(candidate.additionalTextEdits) || Is2.typedArray(candidate.additionalTextEdits, TextEdit2.is));
            }
            ColorPresentation3.is = is2;
          })(ColorPresentation2 || (exports3.ColorPresentation = ColorPresentation2 = {}));
          var FoldingRangeKind2;
          (function(FoldingRangeKind3) {
            FoldingRangeKind3.Comment = "comment";
            FoldingRangeKind3.Imports = "imports";
            FoldingRangeKind3.Region = "region";
          })(FoldingRangeKind2 || (exports3.FoldingRangeKind = FoldingRangeKind2 = {}));
          var FoldingRange2;
          (function(FoldingRange3) {
            function create(startLine, endLine, startCharacter, endCharacter, kind, collapsedText) {
              var result = {
                startLine,
                endLine
              };
              if (Is2.defined(startCharacter)) {
                result.startCharacter = startCharacter;
              }
              if (Is2.defined(endCharacter)) {
                result.endCharacter = endCharacter;
              }
              if (Is2.defined(kind)) {
                result.kind = kind;
              }
              if (Is2.defined(collapsedText)) {
                result.collapsedText = collapsedText;
              }
              return result;
            }
            FoldingRange3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(candidate) && Is2.uinteger(candidate.startLine) && Is2.uinteger(candidate.startLine) && (Is2.undefined(candidate.startCharacter) || Is2.uinteger(candidate.startCharacter)) && (Is2.undefined(candidate.endCharacter) || Is2.uinteger(candidate.endCharacter)) && (Is2.undefined(candidate.kind) || Is2.string(candidate.kind));
            }
            FoldingRange3.is = is2;
          })(FoldingRange2 || (exports3.FoldingRange = FoldingRange2 = {}));
          var DiagnosticRelatedInformation2;
          (function(DiagnosticRelatedInformation3) {
            function create(location, message) {
              return {
                location,
                message
              };
            }
            DiagnosticRelatedInformation3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.defined(candidate) && Location2.is(candidate.location) && Is2.string(candidate.message);
            }
            DiagnosticRelatedInformation3.is = is2;
          })(DiagnosticRelatedInformation2 || (exports3.DiagnosticRelatedInformation = DiagnosticRelatedInformation2 = {}));
          var DiagnosticSeverity2;
          (function(DiagnosticSeverity3) {
            DiagnosticSeverity3.Error = 1;
            DiagnosticSeverity3.Warning = 2;
            DiagnosticSeverity3.Information = 3;
            DiagnosticSeverity3.Hint = 4;
          })(DiagnosticSeverity2 || (exports3.DiagnosticSeverity = DiagnosticSeverity2 = {}));
          var DiagnosticTag2;
          (function(DiagnosticTag3) {
            DiagnosticTag3.Unnecessary = 1;
            DiagnosticTag3.Deprecated = 2;
          })(DiagnosticTag2 || (exports3.DiagnosticTag = DiagnosticTag2 = {}));
          var CodeDescription2;
          (function(CodeDescription3) {
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(candidate) && Is2.string(candidate.href);
            }
            CodeDescription3.is = is2;
          })(CodeDescription2 || (exports3.CodeDescription = CodeDescription2 = {}));
          var Diagnostic2;
          (function(Diagnostic3) {
            function create(range, message, severity, code, source, relatedInformation) {
              var result = { range, message };
              if (Is2.defined(severity)) {
                result.severity = severity;
              }
              if (Is2.defined(code)) {
                result.code = code;
              }
              if (Is2.defined(source)) {
                result.source = source;
              }
              if (Is2.defined(relatedInformation)) {
                result.relatedInformation = relatedInformation;
              }
              return result;
            }
            Diagnostic3.create = create;
            function is2(value) {
              var _a;
              var candidate = value;
              return Is2.defined(candidate) && Range2.is(candidate.range) && Is2.string(candidate.message) && (Is2.number(candidate.severity) || Is2.undefined(candidate.severity)) && (Is2.integer(candidate.code) || Is2.string(candidate.code) || Is2.undefined(candidate.code)) && (Is2.undefined(candidate.codeDescription) || Is2.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href)) && (Is2.string(candidate.source) || Is2.undefined(candidate.source)) && (Is2.undefined(candidate.relatedInformation) || Is2.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation2.is));
            }
            Diagnostic3.is = is2;
          })(Diagnostic2 || (exports3.Diagnostic = Diagnostic2 = {}));
          var Command2;
          (function(Command3) {
            function create(title, command) {
              var args = [];
              for (var _i = 2; _i < arguments.length; _i++) {
                args[_i - 2] = arguments[_i];
              }
              var result = { title, command };
              if (Is2.defined(args) && args.length > 0) {
                result.arguments = args;
              }
              return result;
            }
            Command3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.defined(candidate) && Is2.string(candidate.title) && Is2.string(candidate.command);
            }
            Command3.is = is2;
          })(Command2 || (exports3.Command = Command2 = {}));
          var TextEdit2;
          (function(TextEdit3) {
            function replace(range, newText) {
              return { range, newText };
            }
            TextEdit3.replace = replace;
            function insert(position, newText) {
              return { range: { start: position, end: position }, newText };
            }
            TextEdit3.insert = insert;
            function del(range) {
              return { range, newText: "" };
            }
            TextEdit3.del = del;
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(candidate) && Is2.string(candidate.newText) && Range2.is(candidate.range);
            }
            TextEdit3.is = is2;
          })(TextEdit2 || (exports3.TextEdit = TextEdit2 = {}));
          var ChangeAnnotation2;
          (function(ChangeAnnotation3) {
            function create(label, needsConfirmation, description) {
              var result = { label };
              if (needsConfirmation !== void 0) {
                result.needsConfirmation = needsConfirmation;
              }
              if (description !== void 0) {
                result.description = description;
              }
              return result;
            }
            ChangeAnnotation3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(candidate) && Is2.string(candidate.label) && (Is2.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === void 0) && (Is2.string(candidate.description) || candidate.description === void 0);
            }
            ChangeAnnotation3.is = is2;
          })(ChangeAnnotation2 || (exports3.ChangeAnnotation = ChangeAnnotation2 = {}));
          var ChangeAnnotationIdentifier2;
          (function(ChangeAnnotationIdentifier3) {
            function is2(value) {
              var candidate = value;
              return Is2.string(candidate);
            }
            ChangeAnnotationIdentifier3.is = is2;
          })(ChangeAnnotationIdentifier2 || (exports3.ChangeAnnotationIdentifier = ChangeAnnotationIdentifier2 = {}));
          var AnnotatedTextEdit2;
          (function(AnnotatedTextEdit3) {
            function replace(range, newText, annotation) {
              return { range, newText, annotationId: annotation };
            }
            AnnotatedTextEdit3.replace = replace;
            function insert(position, newText, annotation) {
              return { range: { start: position, end: position }, newText, annotationId: annotation };
            }
            AnnotatedTextEdit3.insert = insert;
            function del(range, annotation) {
              return { range, newText: "", annotationId: annotation };
            }
            AnnotatedTextEdit3.del = del;
            function is2(value) {
              var candidate = value;
              return TextEdit2.is(candidate) && (ChangeAnnotation2.is(candidate.annotationId) || ChangeAnnotationIdentifier2.is(candidate.annotationId));
            }
            AnnotatedTextEdit3.is = is2;
          })(AnnotatedTextEdit2 || (exports3.AnnotatedTextEdit = AnnotatedTextEdit2 = {}));
          var TextDocumentEdit2;
          (function(TextDocumentEdit3) {
            function create(textDocument, edits) {
              return { textDocument, edits };
            }
            TextDocumentEdit3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.defined(candidate) && OptionalVersionedTextDocumentIdentifier2.is(candidate.textDocument) && Array.isArray(candidate.edits);
            }
            TextDocumentEdit3.is = is2;
          })(TextDocumentEdit2 || (exports3.TextDocumentEdit = TextDocumentEdit2 = {}));
          var CreateFile2;
          (function(CreateFile3) {
            function create(uri, options, annotation) {
              var result = {
                kind: "create",
                uri
              };
              if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
                result.options = options;
              }
              if (annotation !== void 0) {
                result.annotationId = annotation;
              }
              return result;
            }
            CreateFile3.create = create;
            function is2(value) {
              var candidate = value;
              return candidate && candidate.kind === "create" && Is2.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is2.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is2.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier2.is(candidate.annotationId));
            }
            CreateFile3.is = is2;
          })(CreateFile2 || (exports3.CreateFile = CreateFile2 = {}));
          var RenameFile2;
          (function(RenameFile3) {
            function create(oldUri, newUri, options, annotation) {
              var result = {
                kind: "rename",
                oldUri,
                newUri
              };
              if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
                result.options = options;
              }
              if (annotation !== void 0) {
                result.annotationId = annotation;
              }
              return result;
            }
            RenameFile3.create = create;
            function is2(value) {
              var candidate = value;
              return candidate && candidate.kind === "rename" && Is2.string(candidate.oldUri) && Is2.string(candidate.newUri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is2.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is2.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier2.is(candidate.annotationId));
            }
            RenameFile3.is = is2;
          })(RenameFile2 || (exports3.RenameFile = RenameFile2 = {}));
          var DeleteFile2;
          (function(DeleteFile3) {
            function create(uri, options, annotation) {
              var result = {
                kind: "delete",
                uri
              };
              if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
                result.options = options;
              }
              if (annotation !== void 0) {
                result.annotationId = annotation;
              }
              return result;
            }
            DeleteFile3.create = create;
            function is2(value) {
              var candidate = value;
              return candidate && candidate.kind === "delete" && Is2.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.recursive === void 0 || Is2.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is2.boolean(candidate.options.ignoreIfNotExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier2.is(candidate.annotationId));
            }
            DeleteFile3.is = is2;
          })(DeleteFile2 || (exports3.DeleteFile = DeleteFile2 = {}));
          var WorkspaceEdit2;
          (function(WorkspaceEdit3) {
            function is2(value) {
              var candidate = value;
              return candidate && (candidate.changes !== void 0 || candidate.documentChanges !== void 0) && (candidate.documentChanges === void 0 || candidate.documentChanges.every(function(change) {
                if (Is2.string(change.kind)) {
                  return CreateFile2.is(change) || RenameFile2.is(change) || DeleteFile2.is(change);
                } else {
                  return TextDocumentEdit2.is(change);
                }
              }));
            }
            WorkspaceEdit3.is = is2;
          })(WorkspaceEdit2 || (exports3.WorkspaceEdit = WorkspaceEdit2 = {}));
          var TextEditChangeImpl = (
            /** @class */
            (function() {
              function TextEditChangeImpl2(edits, changeAnnotations) {
                this.edits = edits;
                this.changeAnnotations = changeAnnotations;
              }
              TextEditChangeImpl2.prototype.insert = function(position, newText, annotation) {
                var edit;
                var id;
                if (annotation === void 0) {
                  edit = TextEdit2.insert(position, newText);
                } else if (ChangeAnnotationIdentifier2.is(annotation)) {
                  id = annotation;
                  edit = AnnotatedTextEdit2.insert(position, newText, annotation);
                } else {
                  this.assertChangeAnnotations(this.changeAnnotations);
                  id = this.changeAnnotations.manage(annotation);
                  edit = AnnotatedTextEdit2.insert(position, newText, id);
                }
                this.edits.push(edit);
                if (id !== void 0) {
                  return id;
                }
              };
              TextEditChangeImpl2.prototype.replace = function(range, newText, annotation) {
                var edit;
                var id;
                if (annotation === void 0) {
                  edit = TextEdit2.replace(range, newText);
                } else if (ChangeAnnotationIdentifier2.is(annotation)) {
                  id = annotation;
                  edit = AnnotatedTextEdit2.replace(range, newText, annotation);
                } else {
                  this.assertChangeAnnotations(this.changeAnnotations);
                  id = this.changeAnnotations.manage(annotation);
                  edit = AnnotatedTextEdit2.replace(range, newText, id);
                }
                this.edits.push(edit);
                if (id !== void 0) {
                  return id;
                }
              };
              TextEditChangeImpl2.prototype.delete = function(range, annotation) {
                var edit;
                var id;
                if (annotation === void 0) {
                  edit = TextEdit2.del(range);
                } else if (ChangeAnnotationIdentifier2.is(annotation)) {
                  id = annotation;
                  edit = AnnotatedTextEdit2.del(range, annotation);
                } else {
                  this.assertChangeAnnotations(this.changeAnnotations);
                  id = this.changeAnnotations.manage(annotation);
                  edit = AnnotatedTextEdit2.del(range, id);
                }
                this.edits.push(edit);
                if (id !== void 0) {
                  return id;
                }
              };
              TextEditChangeImpl2.prototype.add = function(edit) {
                this.edits.push(edit);
              };
              TextEditChangeImpl2.prototype.all = function() {
                return this.edits;
              };
              TextEditChangeImpl2.prototype.clear = function() {
                this.edits.splice(0, this.edits.length);
              };
              TextEditChangeImpl2.prototype.assertChangeAnnotations = function(value) {
                if (value === void 0) {
                  throw new Error("Text edit change is not configured to manage change annotations.");
                }
              };
              return TextEditChangeImpl2;
            })()
          );
          var ChangeAnnotations = (
            /** @class */
            (function() {
              function ChangeAnnotations2(annotations) {
                this._annotations = annotations === void 0 ? /* @__PURE__ */ Object.create(null) : annotations;
                this._counter = 0;
                this._size = 0;
              }
              ChangeAnnotations2.prototype.all = function() {
                return this._annotations;
              };
              Object.defineProperty(ChangeAnnotations2.prototype, "size", {
                get: function() {
                  return this._size;
                },
                enumerable: false,
                configurable: true
              });
              ChangeAnnotations2.prototype.manage = function(idOrAnnotation, annotation) {
                var id;
                if (ChangeAnnotationIdentifier2.is(idOrAnnotation)) {
                  id = idOrAnnotation;
                } else {
                  id = this.nextId();
                  annotation = idOrAnnotation;
                }
                if (this._annotations[id] !== void 0) {
                  throw new Error("Id ".concat(id, " is already in use."));
                }
                if (annotation === void 0) {
                  throw new Error("No annotation provided for id ".concat(id));
                }
                this._annotations[id] = annotation;
                this._size++;
                return id;
              };
              ChangeAnnotations2.prototype.nextId = function() {
                this._counter++;
                return this._counter.toString();
              };
              return ChangeAnnotations2;
            })()
          );
          var WorkspaceChange = (
            /** @class */
            (function() {
              function WorkspaceChange2(workspaceEdit) {
                var _this = this;
                this._textEditChanges = /* @__PURE__ */ Object.create(null);
                if (workspaceEdit !== void 0) {
                  this._workspaceEdit = workspaceEdit;
                  if (workspaceEdit.documentChanges) {
                    this._changeAnnotations = new ChangeAnnotations(workspaceEdit.changeAnnotations);
                    workspaceEdit.changeAnnotations = this._changeAnnotations.all();
                    workspaceEdit.documentChanges.forEach(function(change) {
                      if (TextDocumentEdit2.is(change)) {
                        var textEditChange = new TextEditChangeImpl(change.edits, _this._changeAnnotations);
                        _this._textEditChanges[change.textDocument.uri] = textEditChange;
                      }
                    });
                  } else if (workspaceEdit.changes) {
                    Object.keys(workspaceEdit.changes).forEach(function(key) {
                      var textEditChange = new TextEditChangeImpl(workspaceEdit.changes[key]);
                      _this._textEditChanges[key] = textEditChange;
                    });
                  }
                } else {
                  this._workspaceEdit = {};
                }
              }
              Object.defineProperty(WorkspaceChange2.prototype, "edit", {
                /**
                 * Returns the underlying {@link WorkspaceEdit} literal
                 * use to be returned from a workspace edit operation like rename.
                 */
                get: function() {
                  this.initDocumentChanges();
                  if (this._changeAnnotations !== void 0) {
                    if (this._changeAnnotations.size === 0) {
                      this._workspaceEdit.changeAnnotations = void 0;
                    } else {
                      this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
                    }
                  }
                  return this._workspaceEdit;
                },
                enumerable: false,
                configurable: true
              });
              WorkspaceChange2.prototype.getTextEditChange = function(key) {
                if (OptionalVersionedTextDocumentIdentifier2.is(key)) {
                  this.initDocumentChanges();
                  if (this._workspaceEdit.documentChanges === void 0) {
                    throw new Error("Workspace edit is not configured for document changes.");
                  }
                  var textDocument = { uri: key.uri, version: key.version };
                  var result = this._textEditChanges[textDocument.uri];
                  if (!result) {
                    var edits = [];
                    var textDocumentEdit = {
                      textDocument,
                      edits
                    };
                    this._workspaceEdit.documentChanges.push(textDocumentEdit);
                    result = new TextEditChangeImpl(edits, this._changeAnnotations);
                    this._textEditChanges[textDocument.uri] = result;
                  }
                  return result;
                } else {
                  this.initChanges();
                  if (this._workspaceEdit.changes === void 0) {
                    throw new Error("Workspace edit is not configured for normal text edit changes.");
                  }
                  var result = this._textEditChanges[key];
                  if (!result) {
                    var edits = [];
                    this._workspaceEdit.changes[key] = edits;
                    result = new TextEditChangeImpl(edits);
                    this._textEditChanges[key] = result;
                  }
                  return result;
                }
              };
              WorkspaceChange2.prototype.initDocumentChanges = function() {
                if (this._workspaceEdit.documentChanges === void 0 && this._workspaceEdit.changes === void 0) {
                  this._changeAnnotations = new ChangeAnnotations();
                  this._workspaceEdit.documentChanges = [];
                  this._workspaceEdit.changeAnnotations = this._changeAnnotations.all();
                }
              };
              WorkspaceChange2.prototype.initChanges = function() {
                if (this._workspaceEdit.documentChanges === void 0 && this._workspaceEdit.changes === void 0) {
                  this._workspaceEdit.changes = /* @__PURE__ */ Object.create(null);
                }
              };
              WorkspaceChange2.prototype.createFile = function(uri, optionsOrAnnotation, options) {
                this.initDocumentChanges();
                if (this._workspaceEdit.documentChanges === void 0) {
                  throw new Error("Workspace edit is not configured for document changes.");
                }
                var annotation;
                if (ChangeAnnotation2.is(optionsOrAnnotation) || ChangeAnnotationIdentifier2.is(optionsOrAnnotation)) {
                  annotation = optionsOrAnnotation;
                } else {
                  options = optionsOrAnnotation;
                }
                var operation;
                var id;
                if (annotation === void 0) {
                  operation = CreateFile2.create(uri, options);
                } else {
                  id = ChangeAnnotationIdentifier2.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
                  operation = CreateFile2.create(uri, options, id);
                }
                this._workspaceEdit.documentChanges.push(operation);
                if (id !== void 0) {
                  return id;
                }
              };
              WorkspaceChange2.prototype.renameFile = function(oldUri, newUri, optionsOrAnnotation, options) {
                this.initDocumentChanges();
                if (this._workspaceEdit.documentChanges === void 0) {
                  throw new Error("Workspace edit is not configured for document changes.");
                }
                var annotation;
                if (ChangeAnnotation2.is(optionsOrAnnotation) || ChangeAnnotationIdentifier2.is(optionsOrAnnotation)) {
                  annotation = optionsOrAnnotation;
                } else {
                  options = optionsOrAnnotation;
                }
                var operation;
                var id;
                if (annotation === void 0) {
                  operation = RenameFile2.create(oldUri, newUri, options);
                } else {
                  id = ChangeAnnotationIdentifier2.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
                  operation = RenameFile2.create(oldUri, newUri, options, id);
                }
                this._workspaceEdit.documentChanges.push(operation);
                if (id !== void 0) {
                  return id;
                }
              };
              WorkspaceChange2.prototype.deleteFile = function(uri, optionsOrAnnotation, options) {
                this.initDocumentChanges();
                if (this._workspaceEdit.documentChanges === void 0) {
                  throw new Error("Workspace edit is not configured for document changes.");
                }
                var annotation;
                if (ChangeAnnotation2.is(optionsOrAnnotation) || ChangeAnnotationIdentifier2.is(optionsOrAnnotation)) {
                  annotation = optionsOrAnnotation;
                } else {
                  options = optionsOrAnnotation;
                }
                var operation;
                var id;
                if (annotation === void 0) {
                  operation = DeleteFile2.create(uri, options);
                } else {
                  id = ChangeAnnotationIdentifier2.is(annotation) ? annotation : this._changeAnnotations.manage(annotation);
                  operation = DeleteFile2.create(uri, options, id);
                }
                this._workspaceEdit.documentChanges.push(operation);
                if (id !== void 0) {
                  return id;
                }
              };
              return WorkspaceChange2;
            })()
          );
          exports3.WorkspaceChange = WorkspaceChange;
          var TextDocumentIdentifier2;
          (function(TextDocumentIdentifier3) {
            function create(uri) {
              return { uri };
            }
            TextDocumentIdentifier3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.defined(candidate) && Is2.string(candidate.uri);
            }
            TextDocumentIdentifier3.is = is2;
          })(TextDocumentIdentifier2 || (exports3.TextDocumentIdentifier = TextDocumentIdentifier2 = {}));
          var VersionedTextDocumentIdentifier2;
          (function(VersionedTextDocumentIdentifier3) {
            function create(uri, version) {
              return { uri, version };
            }
            VersionedTextDocumentIdentifier3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.defined(candidate) && Is2.string(candidate.uri) && Is2.integer(candidate.version);
            }
            VersionedTextDocumentIdentifier3.is = is2;
          })(VersionedTextDocumentIdentifier2 || (exports3.VersionedTextDocumentIdentifier = VersionedTextDocumentIdentifier2 = {}));
          var OptionalVersionedTextDocumentIdentifier2;
          (function(OptionalVersionedTextDocumentIdentifier3) {
            function create(uri, version) {
              return { uri, version };
            }
            OptionalVersionedTextDocumentIdentifier3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.defined(candidate) && Is2.string(candidate.uri) && (candidate.version === null || Is2.integer(candidate.version));
            }
            OptionalVersionedTextDocumentIdentifier3.is = is2;
          })(OptionalVersionedTextDocumentIdentifier2 || (exports3.OptionalVersionedTextDocumentIdentifier = OptionalVersionedTextDocumentIdentifier2 = {}));
          var TextDocumentItem2;
          (function(TextDocumentItem3) {
            function create(uri, languageId, version, text) {
              return { uri, languageId, version, text };
            }
            TextDocumentItem3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.defined(candidate) && Is2.string(candidate.uri) && Is2.string(candidate.languageId) && Is2.integer(candidate.version) && Is2.string(candidate.text);
            }
            TextDocumentItem3.is = is2;
          })(TextDocumentItem2 || (exports3.TextDocumentItem = TextDocumentItem2 = {}));
          var MarkupKind2;
          (function(MarkupKind3) {
            MarkupKind3.PlainText = "plaintext";
            MarkupKind3.Markdown = "markdown";
            function is2(value) {
              var candidate = value;
              return candidate === MarkupKind3.PlainText || candidate === MarkupKind3.Markdown;
            }
            MarkupKind3.is = is2;
          })(MarkupKind2 || (exports3.MarkupKind = MarkupKind2 = {}));
          var MarkupContent2;
          (function(MarkupContent3) {
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(value) && MarkupKind2.is(candidate.kind) && Is2.string(candidate.value);
            }
            MarkupContent3.is = is2;
          })(MarkupContent2 || (exports3.MarkupContent = MarkupContent2 = {}));
          var CompletionItemKind2;
          (function(CompletionItemKind3) {
            CompletionItemKind3.Text = 1;
            CompletionItemKind3.Method = 2;
            CompletionItemKind3.Function = 3;
            CompletionItemKind3.Constructor = 4;
            CompletionItemKind3.Field = 5;
            CompletionItemKind3.Variable = 6;
            CompletionItemKind3.Class = 7;
            CompletionItemKind3.Interface = 8;
            CompletionItemKind3.Module = 9;
            CompletionItemKind3.Property = 10;
            CompletionItemKind3.Unit = 11;
            CompletionItemKind3.Value = 12;
            CompletionItemKind3.Enum = 13;
            CompletionItemKind3.Keyword = 14;
            CompletionItemKind3.Snippet = 15;
            CompletionItemKind3.Color = 16;
            CompletionItemKind3.File = 17;
            CompletionItemKind3.Reference = 18;
            CompletionItemKind3.Folder = 19;
            CompletionItemKind3.EnumMember = 20;
            CompletionItemKind3.Constant = 21;
            CompletionItemKind3.Struct = 22;
            CompletionItemKind3.Event = 23;
            CompletionItemKind3.Operator = 24;
            CompletionItemKind3.TypeParameter = 25;
          })(CompletionItemKind2 || (exports3.CompletionItemKind = CompletionItemKind2 = {}));
          var InsertTextFormat2;
          (function(InsertTextFormat3) {
            InsertTextFormat3.PlainText = 1;
            InsertTextFormat3.Snippet = 2;
          })(InsertTextFormat2 || (exports3.InsertTextFormat = InsertTextFormat2 = {}));
          var CompletionItemTag2;
          (function(CompletionItemTag3) {
            CompletionItemTag3.Deprecated = 1;
          })(CompletionItemTag2 || (exports3.CompletionItemTag = CompletionItemTag2 = {}));
          var InsertReplaceEdit2;
          (function(InsertReplaceEdit3) {
            function create(newText, insert, replace) {
              return { newText, insert, replace };
            }
            InsertReplaceEdit3.create = create;
            function is2(value) {
              var candidate = value;
              return candidate && Is2.string(candidate.newText) && Range2.is(candidate.insert) && Range2.is(candidate.replace);
            }
            InsertReplaceEdit3.is = is2;
          })(InsertReplaceEdit2 || (exports3.InsertReplaceEdit = InsertReplaceEdit2 = {}));
          var InsertTextMode2;
          (function(InsertTextMode3) {
            InsertTextMode3.asIs = 1;
            InsertTextMode3.adjustIndentation = 2;
          })(InsertTextMode2 || (exports3.InsertTextMode = InsertTextMode2 = {}));
          var CompletionItemLabelDetails2;
          (function(CompletionItemLabelDetails3) {
            function is2(value) {
              var candidate = value;
              return candidate && (Is2.string(candidate.detail) || candidate.detail === void 0) && (Is2.string(candidate.description) || candidate.description === void 0);
            }
            CompletionItemLabelDetails3.is = is2;
          })(CompletionItemLabelDetails2 || (exports3.CompletionItemLabelDetails = CompletionItemLabelDetails2 = {}));
          var CompletionItem2;
          (function(CompletionItem3) {
            function create(label) {
              return { label };
            }
            CompletionItem3.create = create;
          })(CompletionItem2 || (exports3.CompletionItem = CompletionItem2 = {}));
          var CompletionList2;
          (function(CompletionList3) {
            function create(items, isIncomplete) {
              return { items: items ? items : [], isIncomplete: !!isIncomplete };
            }
            CompletionList3.create = create;
          })(CompletionList2 || (exports3.CompletionList = CompletionList2 = {}));
          var MarkedString2;
          (function(MarkedString3) {
            function fromPlainText(plainText) {
              return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&");
            }
            MarkedString3.fromPlainText = fromPlainText;
            function is2(value) {
              var candidate = value;
              return Is2.string(candidate) || Is2.objectLiteral(candidate) && Is2.string(candidate.language) && Is2.string(candidate.value);
            }
            MarkedString3.is = is2;
          })(MarkedString2 || (exports3.MarkedString = MarkedString2 = {}));
          var Hover2;
          (function(Hover3) {
            function is2(value) {
              var candidate = value;
              return !!candidate && Is2.objectLiteral(candidate) && (MarkupContent2.is(candidate.contents) || MarkedString2.is(candidate.contents) || Is2.typedArray(candidate.contents, MarkedString2.is)) && (value.range === void 0 || Range2.is(value.range));
            }
            Hover3.is = is2;
          })(Hover2 || (exports3.Hover = Hover2 = {}));
          var ParameterInformation2;
          (function(ParameterInformation3) {
            function create(label, documentation) {
              return documentation ? { label, documentation } : { label };
            }
            ParameterInformation3.create = create;
          })(ParameterInformation2 || (exports3.ParameterInformation = ParameterInformation2 = {}));
          var SignatureInformation2;
          (function(SignatureInformation3) {
            function create(label, documentation) {
              var parameters = [];
              for (var _i = 2; _i < arguments.length; _i++) {
                parameters[_i - 2] = arguments[_i];
              }
              var result = { label };
              if (Is2.defined(documentation)) {
                result.documentation = documentation;
              }
              if (Is2.defined(parameters)) {
                result.parameters = parameters;
              } else {
                result.parameters = [];
              }
              return result;
            }
            SignatureInformation3.create = create;
          })(SignatureInformation2 || (exports3.SignatureInformation = SignatureInformation2 = {}));
          var DocumentHighlightKind2;
          (function(DocumentHighlightKind3) {
            DocumentHighlightKind3.Text = 1;
            DocumentHighlightKind3.Read = 2;
            DocumentHighlightKind3.Write = 3;
          })(DocumentHighlightKind2 || (exports3.DocumentHighlightKind = DocumentHighlightKind2 = {}));
          var DocumentHighlight2;
          (function(DocumentHighlight3) {
            function create(range, kind) {
              var result = { range };
              if (Is2.number(kind)) {
                result.kind = kind;
              }
              return result;
            }
            DocumentHighlight3.create = create;
          })(DocumentHighlight2 || (exports3.DocumentHighlight = DocumentHighlight2 = {}));
          var SymbolKind2;
          (function(SymbolKind3) {
            SymbolKind3.File = 1;
            SymbolKind3.Module = 2;
            SymbolKind3.Namespace = 3;
            SymbolKind3.Package = 4;
            SymbolKind3.Class = 5;
            SymbolKind3.Method = 6;
            SymbolKind3.Property = 7;
            SymbolKind3.Field = 8;
            SymbolKind3.Constructor = 9;
            SymbolKind3.Enum = 10;
            SymbolKind3.Interface = 11;
            SymbolKind3.Function = 12;
            SymbolKind3.Variable = 13;
            SymbolKind3.Constant = 14;
            SymbolKind3.String = 15;
            SymbolKind3.Number = 16;
            SymbolKind3.Boolean = 17;
            SymbolKind3.Array = 18;
            SymbolKind3.Object = 19;
            SymbolKind3.Key = 20;
            SymbolKind3.Null = 21;
            SymbolKind3.EnumMember = 22;
            SymbolKind3.Struct = 23;
            SymbolKind3.Event = 24;
            SymbolKind3.Operator = 25;
            SymbolKind3.TypeParameter = 26;
          })(SymbolKind2 || (exports3.SymbolKind = SymbolKind2 = {}));
          var SymbolTag2;
          (function(SymbolTag3) {
            SymbolTag3.Deprecated = 1;
          })(SymbolTag2 || (exports3.SymbolTag = SymbolTag2 = {}));
          var SymbolInformation2;
          (function(SymbolInformation3) {
            function create(name, kind, range, uri, containerName) {
              var result = {
                name,
                kind,
                location: { uri, range }
              };
              if (containerName) {
                result.containerName = containerName;
              }
              return result;
            }
            SymbolInformation3.create = create;
          })(SymbolInformation2 || (exports3.SymbolInformation = SymbolInformation2 = {}));
          var WorkspaceSymbol2;
          (function(WorkspaceSymbol3) {
            function create(name, kind, uri, range) {
              return range !== void 0 ? { name, kind, location: { uri, range } } : { name, kind, location: { uri } };
            }
            WorkspaceSymbol3.create = create;
          })(WorkspaceSymbol2 || (exports3.WorkspaceSymbol = WorkspaceSymbol2 = {}));
          var DocumentSymbol2;
          (function(DocumentSymbol3) {
            function create(name, detail, kind, range, selectionRange, children) {
              var result = {
                name,
                detail,
                kind,
                range,
                selectionRange
              };
              if (children !== void 0) {
                result.children = children;
              }
              return result;
            }
            DocumentSymbol3.create = create;
            function is2(value) {
              var candidate = value;
              return candidate && Is2.string(candidate.name) && Is2.number(candidate.kind) && Range2.is(candidate.range) && Range2.is(candidate.selectionRange) && (candidate.detail === void 0 || Is2.string(candidate.detail)) && (candidate.deprecated === void 0 || Is2.boolean(candidate.deprecated)) && (candidate.children === void 0 || Array.isArray(candidate.children)) && (candidate.tags === void 0 || Array.isArray(candidate.tags));
            }
            DocumentSymbol3.is = is2;
          })(DocumentSymbol2 || (exports3.DocumentSymbol = DocumentSymbol2 = {}));
          var CodeActionKind2;
          (function(CodeActionKind3) {
            CodeActionKind3.Empty = "";
            CodeActionKind3.QuickFix = "quickfix";
            CodeActionKind3.Refactor = "refactor";
            CodeActionKind3.RefactorExtract = "refactor.extract";
            CodeActionKind3.RefactorInline = "refactor.inline";
            CodeActionKind3.RefactorRewrite = "refactor.rewrite";
            CodeActionKind3.Source = "source";
            CodeActionKind3.SourceOrganizeImports = "source.organizeImports";
            CodeActionKind3.SourceFixAll = "source.fixAll";
          })(CodeActionKind2 || (exports3.CodeActionKind = CodeActionKind2 = {}));
          var CodeActionTriggerKind2;
          (function(CodeActionTriggerKind3) {
            CodeActionTriggerKind3.Invoked = 1;
            CodeActionTriggerKind3.Automatic = 2;
          })(CodeActionTriggerKind2 || (exports3.CodeActionTriggerKind = CodeActionTriggerKind2 = {}));
          var CodeActionContext2;
          (function(CodeActionContext3) {
            function create(diagnostics, only, triggerKind) {
              var result = { diagnostics };
              if (only !== void 0 && only !== null) {
                result.only = only;
              }
              if (triggerKind !== void 0 && triggerKind !== null) {
                result.triggerKind = triggerKind;
              }
              return result;
            }
            CodeActionContext3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.defined(candidate) && Is2.typedArray(candidate.diagnostics, Diagnostic2.is) && (candidate.only === void 0 || Is2.typedArray(candidate.only, Is2.string)) && (candidate.triggerKind === void 0 || candidate.triggerKind === CodeActionTriggerKind2.Invoked || candidate.triggerKind === CodeActionTriggerKind2.Automatic);
            }
            CodeActionContext3.is = is2;
          })(CodeActionContext2 || (exports3.CodeActionContext = CodeActionContext2 = {}));
          var CodeAction2;
          (function(CodeAction3) {
            function create(title, kindOrCommandOrEdit, kind) {
              var result = { title };
              var checkKind = true;
              if (typeof kindOrCommandOrEdit === "string") {
                checkKind = false;
                result.kind = kindOrCommandOrEdit;
              } else if (Command2.is(kindOrCommandOrEdit)) {
                result.command = kindOrCommandOrEdit;
              } else {
                result.edit = kindOrCommandOrEdit;
              }
              if (checkKind && kind !== void 0) {
                result.kind = kind;
              }
              return result;
            }
            CodeAction3.create = create;
            function is2(value) {
              var candidate = value;
              return candidate && Is2.string(candidate.title) && (candidate.diagnostics === void 0 || Is2.typedArray(candidate.diagnostics, Diagnostic2.is)) && (candidate.kind === void 0 || Is2.string(candidate.kind)) && (candidate.edit !== void 0 || candidate.command !== void 0) && (candidate.command === void 0 || Command2.is(candidate.command)) && (candidate.isPreferred === void 0 || Is2.boolean(candidate.isPreferred)) && (candidate.edit === void 0 || WorkspaceEdit2.is(candidate.edit));
            }
            CodeAction3.is = is2;
          })(CodeAction2 || (exports3.CodeAction = CodeAction2 = {}));
          var CodeLens2;
          (function(CodeLens3) {
            function create(range, data) {
              var result = { range };
              if (Is2.defined(data)) {
                result.data = data;
              }
              return result;
            }
            CodeLens3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.defined(candidate) && Range2.is(candidate.range) && (Is2.undefined(candidate.command) || Command2.is(candidate.command));
            }
            CodeLens3.is = is2;
          })(CodeLens2 || (exports3.CodeLens = CodeLens2 = {}));
          var FormattingOptions2;
          (function(FormattingOptions3) {
            function create(tabSize, insertSpaces) {
              return { tabSize, insertSpaces };
            }
            FormattingOptions3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.defined(candidate) && Is2.uinteger(candidate.tabSize) && Is2.boolean(candidate.insertSpaces);
            }
            FormattingOptions3.is = is2;
          })(FormattingOptions2 || (exports3.FormattingOptions = FormattingOptions2 = {}));
          var DocumentLink2;
          (function(DocumentLink3) {
            function create(range, target, data) {
              return { range, target, data };
            }
            DocumentLink3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.defined(candidate) && Range2.is(candidate.range) && (Is2.undefined(candidate.target) || Is2.string(candidate.target));
            }
            DocumentLink3.is = is2;
          })(DocumentLink2 || (exports3.DocumentLink = DocumentLink2 = {}));
          var SelectionRange2;
          (function(SelectionRange3) {
            function create(range, parent) {
              return { range, parent };
            }
            SelectionRange3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(candidate) && Range2.is(candidate.range) && (candidate.parent === void 0 || SelectionRange3.is(candidate.parent));
            }
            SelectionRange3.is = is2;
          })(SelectionRange2 || (exports3.SelectionRange = SelectionRange2 = {}));
          var SemanticTokenTypes2;
          (function(SemanticTokenTypes3) {
            SemanticTokenTypes3["namespace"] = "namespace";
            SemanticTokenTypes3["type"] = "type";
            SemanticTokenTypes3["class"] = "class";
            SemanticTokenTypes3["enum"] = "enum";
            SemanticTokenTypes3["interface"] = "interface";
            SemanticTokenTypes3["struct"] = "struct";
            SemanticTokenTypes3["typeParameter"] = "typeParameter";
            SemanticTokenTypes3["parameter"] = "parameter";
            SemanticTokenTypes3["variable"] = "variable";
            SemanticTokenTypes3["property"] = "property";
            SemanticTokenTypes3["enumMember"] = "enumMember";
            SemanticTokenTypes3["event"] = "event";
            SemanticTokenTypes3["function"] = "function";
            SemanticTokenTypes3["method"] = "method";
            SemanticTokenTypes3["macro"] = "macro";
            SemanticTokenTypes3["keyword"] = "keyword";
            SemanticTokenTypes3["modifier"] = "modifier";
            SemanticTokenTypes3["comment"] = "comment";
            SemanticTokenTypes3["string"] = "string";
            SemanticTokenTypes3["number"] = "number";
            SemanticTokenTypes3["regexp"] = "regexp";
            SemanticTokenTypes3["operator"] = "operator";
            SemanticTokenTypes3["decorator"] = "decorator";
          })(SemanticTokenTypes2 || (exports3.SemanticTokenTypes = SemanticTokenTypes2 = {}));
          var SemanticTokenModifiers2;
          (function(SemanticTokenModifiers3) {
            SemanticTokenModifiers3["declaration"] = "declaration";
            SemanticTokenModifiers3["definition"] = "definition";
            SemanticTokenModifiers3["readonly"] = "readonly";
            SemanticTokenModifiers3["static"] = "static";
            SemanticTokenModifiers3["deprecated"] = "deprecated";
            SemanticTokenModifiers3["abstract"] = "abstract";
            SemanticTokenModifiers3["async"] = "async";
            SemanticTokenModifiers3["modification"] = "modification";
            SemanticTokenModifiers3["documentation"] = "documentation";
            SemanticTokenModifiers3["defaultLibrary"] = "defaultLibrary";
          })(SemanticTokenModifiers2 || (exports3.SemanticTokenModifiers = SemanticTokenModifiers2 = {}));
          var SemanticTokens2;
          (function(SemanticTokens3) {
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(candidate) && (candidate.resultId === void 0 || typeof candidate.resultId === "string") && Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === "number");
            }
            SemanticTokens3.is = is2;
          })(SemanticTokens2 || (exports3.SemanticTokens = SemanticTokens2 = {}));
          var InlineValueText2;
          (function(InlineValueText3) {
            function create(range, text) {
              return { range, text };
            }
            InlineValueText3.create = create;
            function is2(value) {
              var candidate = value;
              return candidate !== void 0 && candidate !== null && Range2.is(candidate.range) && Is2.string(candidate.text);
            }
            InlineValueText3.is = is2;
          })(InlineValueText2 || (exports3.InlineValueText = InlineValueText2 = {}));
          var InlineValueVariableLookup2;
          (function(InlineValueVariableLookup3) {
            function create(range, variableName, caseSensitiveLookup) {
              return { range, variableName, caseSensitiveLookup };
            }
            InlineValueVariableLookup3.create = create;
            function is2(value) {
              var candidate = value;
              return candidate !== void 0 && candidate !== null && Range2.is(candidate.range) && Is2.boolean(candidate.caseSensitiveLookup) && (Is2.string(candidate.variableName) || candidate.variableName === void 0);
            }
            InlineValueVariableLookup3.is = is2;
          })(InlineValueVariableLookup2 || (exports3.InlineValueVariableLookup = InlineValueVariableLookup2 = {}));
          var InlineValueEvaluatableExpression2;
          (function(InlineValueEvaluatableExpression3) {
            function create(range, expression) {
              return { range, expression };
            }
            InlineValueEvaluatableExpression3.create = create;
            function is2(value) {
              var candidate = value;
              return candidate !== void 0 && candidate !== null && Range2.is(candidate.range) && (Is2.string(candidate.expression) || candidate.expression === void 0);
            }
            InlineValueEvaluatableExpression3.is = is2;
          })(InlineValueEvaluatableExpression2 || (exports3.InlineValueEvaluatableExpression = InlineValueEvaluatableExpression2 = {}));
          var InlineValueContext2;
          (function(InlineValueContext3) {
            function create(frameId, stoppedLocation) {
              return { frameId, stoppedLocation };
            }
            InlineValueContext3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.defined(candidate) && Range2.is(value.stoppedLocation);
            }
            InlineValueContext3.is = is2;
          })(InlineValueContext2 || (exports3.InlineValueContext = InlineValueContext2 = {}));
          var InlayHintKind2;
          (function(InlayHintKind3) {
            InlayHintKind3.Type = 1;
            InlayHintKind3.Parameter = 2;
            function is2(value) {
              return value === 1 || value === 2;
            }
            InlayHintKind3.is = is2;
          })(InlayHintKind2 || (exports3.InlayHintKind = InlayHintKind2 = {}));
          var InlayHintLabelPart2;
          (function(InlayHintLabelPart3) {
            function create(value) {
              return { value };
            }
            InlayHintLabelPart3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(candidate) && (candidate.tooltip === void 0 || Is2.string(candidate.tooltip) || MarkupContent2.is(candidate.tooltip)) && (candidate.location === void 0 || Location2.is(candidate.location)) && (candidate.command === void 0 || Command2.is(candidate.command));
            }
            InlayHintLabelPart3.is = is2;
          })(InlayHintLabelPart2 || (exports3.InlayHintLabelPart = InlayHintLabelPart2 = {}));
          var InlayHint2;
          (function(InlayHint3) {
            function create(position, label, kind) {
              var result = { position, label };
              if (kind !== void 0) {
                result.kind = kind;
              }
              return result;
            }
            InlayHint3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(candidate) && Position2.is(candidate.position) && (Is2.string(candidate.label) || Is2.typedArray(candidate.label, InlayHintLabelPart2.is)) && (candidate.kind === void 0 || InlayHintKind2.is(candidate.kind)) && candidate.textEdits === void 0 || Is2.typedArray(candidate.textEdits, TextEdit2.is) && (candidate.tooltip === void 0 || Is2.string(candidate.tooltip) || MarkupContent2.is(candidate.tooltip)) && (candidate.paddingLeft === void 0 || Is2.boolean(candidate.paddingLeft)) && (candidate.paddingRight === void 0 || Is2.boolean(candidate.paddingRight));
            }
            InlayHint3.is = is2;
          })(InlayHint2 || (exports3.InlayHint = InlayHint2 = {}));
          var StringValue2;
          (function(StringValue3) {
            function createSnippet(value) {
              return { kind: "snippet", value };
            }
            StringValue3.createSnippet = createSnippet;
          })(StringValue2 || (exports3.StringValue = StringValue2 = {}));
          var InlineCompletionItem2;
          (function(InlineCompletionItem3) {
            function create(insertText, filterText, range, command) {
              return { insertText, filterText, range, command };
            }
            InlineCompletionItem3.create = create;
          })(InlineCompletionItem2 || (exports3.InlineCompletionItem = InlineCompletionItem2 = {}));
          var InlineCompletionList2;
          (function(InlineCompletionList3) {
            function create(items) {
              return { items };
            }
            InlineCompletionList3.create = create;
          })(InlineCompletionList2 || (exports3.InlineCompletionList = InlineCompletionList2 = {}));
          var InlineCompletionTriggerKind2;
          (function(InlineCompletionTriggerKind3) {
            InlineCompletionTriggerKind3.Invoked = 0;
            InlineCompletionTriggerKind3.Automatic = 1;
          })(InlineCompletionTriggerKind2 || (exports3.InlineCompletionTriggerKind = InlineCompletionTriggerKind2 = {}));
          var SelectedCompletionInfo2;
          (function(SelectedCompletionInfo3) {
            function create(range, text) {
              return { range, text };
            }
            SelectedCompletionInfo3.create = create;
          })(SelectedCompletionInfo2 || (exports3.SelectedCompletionInfo = SelectedCompletionInfo2 = {}));
          var InlineCompletionContext2;
          (function(InlineCompletionContext3) {
            function create(triggerKind, selectedCompletionInfo) {
              return { triggerKind, selectedCompletionInfo };
            }
            InlineCompletionContext3.create = create;
          })(InlineCompletionContext2 || (exports3.InlineCompletionContext = InlineCompletionContext2 = {}));
          var WorkspaceFolder2;
          (function(WorkspaceFolder3) {
            function is2(value) {
              var candidate = value;
              return Is2.objectLiteral(candidate) && URI2.is(candidate.uri) && Is2.string(candidate.name);
            }
            WorkspaceFolder3.is = is2;
          })(WorkspaceFolder2 || (exports3.WorkspaceFolder = WorkspaceFolder2 = {}));
          exports3.EOL = ["\n", "\r\n", "\r"];
          var TextDocument2;
          (function(TextDocument3) {
            function create(uri, languageId, version, content) {
              return new FullTextDocument2(uri, languageId, version, content);
            }
            TextDocument3.create = create;
            function is2(value) {
              var candidate = value;
              return Is2.defined(candidate) && Is2.string(candidate.uri) && (Is2.undefined(candidate.languageId) || Is2.string(candidate.languageId)) && Is2.uinteger(candidate.lineCount) && Is2.func(candidate.getText) && Is2.func(candidate.positionAt) && Is2.func(candidate.offsetAt) ? true : false;
            }
            TextDocument3.is = is2;
            function applyEdits(document, edits) {
              var text = document.getText();
              var sortedEdits = mergeSort2(edits, function(a2, b) {
                var diff = a2.range.start.line - b.range.start.line;
                if (diff === 0) {
                  return a2.range.start.character - b.range.start.character;
                }
                return diff;
              });
              var lastModifiedOffset = text.length;
              for (var i = sortedEdits.length - 1; i >= 0; i--) {
                var e = sortedEdits[i];
                var startOffset = document.offsetAt(e.range.start);
                var endOffset = document.offsetAt(e.range.end);
                if (endOffset <= lastModifiedOffset) {
                  text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
                } else {
                  throw new Error("Overlapping edit");
                }
                lastModifiedOffset = startOffset;
              }
              return text;
            }
            TextDocument3.applyEdits = applyEdits;
            function mergeSort2(data, compare) {
              if (data.length <= 1) {
                return data;
              }
              var p = data.length / 2 | 0;
              var left = data.slice(0, p);
              var right = data.slice(p);
              mergeSort2(left, compare);
              mergeSort2(right, compare);
              var leftIdx = 0;
              var rightIdx = 0;
              var i = 0;
              while (leftIdx < left.length && rightIdx < right.length) {
                var ret = compare(left[leftIdx], right[rightIdx]);
                if (ret <= 0) {
                  data[i++] = left[leftIdx++];
                } else {
                  data[i++] = right[rightIdx++];
                }
              }
              while (leftIdx < left.length) {
                data[i++] = left[leftIdx++];
              }
              while (rightIdx < right.length) {
                data[i++] = right[rightIdx++];
              }
              return data;
            }
          })(TextDocument2 || (exports3.TextDocument = TextDocument2 = {}));
          var FullTextDocument2 = (
            /** @class */
            (function() {
              function FullTextDocument3(uri, languageId, version, content) {
                this._uri = uri;
                this._languageId = languageId;
                this._version = version;
                this._content = content;
                this._lineOffsets = void 0;
              }
              Object.defineProperty(FullTextDocument3.prototype, "uri", {
                get: function() {
                  return this._uri;
                },
                enumerable: false,
                configurable: true
              });
              Object.defineProperty(FullTextDocument3.prototype, "languageId", {
                get: function() {
                  return this._languageId;
                },
                enumerable: false,
                configurable: true
              });
              Object.defineProperty(FullTextDocument3.prototype, "version", {
                get: function() {
                  return this._version;
                },
                enumerable: false,
                configurable: true
              });
              FullTextDocument3.prototype.getText = function(range) {
                if (range) {
                  var start = this.offsetAt(range.start);
                  var end = this.offsetAt(range.end);
                  return this._content.substring(start, end);
                }
                return this._content;
              };
              FullTextDocument3.prototype.update = function(event, version) {
                this._content = event.text;
                this._version = version;
                this._lineOffsets = void 0;
              };
              FullTextDocument3.prototype.getLineOffsets = function() {
                if (this._lineOffsets === void 0) {
                  var lineOffsets = [];
                  var text = this._content;
                  var isLineStart = true;
                  for (var i = 0; i < text.length; i++) {
                    if (isLineStart) {
                      lineOffsets.push(i);
                      isLineStart = false;
                    }
                    var ch = text.charAt(i);
                    isLineStart = ch === "\r" || ch === "\n";
                    if (ch === "\r" && i + 1 < text.length && text.charAt(i + 1) === "\n") {
                      i++;
                    }
                  }
                  if (isLineStart && text.length > 0) {
                    lineOffsets.push(text.length);
                  }
                  this._lineOffsets = lineOffsets;
                }
                return this._lineOffsets;
              };
              FullTextDocument3.prototype.positionAt = function(offset) {
                offset = Math.max(Math.min(offset, this._content.length), 0);
                var lineOffsets = this.getLineOffsets();
                var low = 0, high = lineOffsets.length;
                if (high === 0) {
                  return Position2.create(0, offset);
                }
                while (low < high) {
                  var mid = Math.floor((low + high) / 2);
                  if (lineOffsets[mid] > offset) {
                    high = mid;
                  } else {
                    low = mid + 1;
                  }
                }
                var line = low - 1;
                return Position2.create(line, offset - lineOffsets[line]);
              };
              FullTextDocument3.prototype.offsetAt = function(position) {
                var lineOffsets = this.getLineOffsets();
                if (position.line >= lineOffsets.length) {
                  return this._content.length;
                } else if (position.line < 0) {
                  return 0;
                }
                var lineOffset = lineOffsets[position.line];
                var nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length;
                return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
              };
              Object.defineProperty(FullTextDocument3.prototype, "lineCount", {
                get: function() {
                  return this.getLineOffsets().length;
                },
                enumerable: false,
                configurable: true
              });
              return FullTextDocument3;
            })()
          );
          var Is2;
          (function(Is3) {
            var toString2 = Object.prototype.toString;
            function defined(value) {
              return typeof value !== "undefined";
            }
            Is3.defined = defined;
            function undefined$1(value) {
              return typeof value === "undefined";
            }
            Is3.undefined = undefined$1;
            function boolean(value) {
              return value === true || value === false;
            }
            Is3.boolean = boolean;
            function string(value) {
              return toString2.call(value) === "[object String]";
            }
            Is3.string = string;
            function number(value) {
              return toString2.call(value) === "[object Number]";
            }
            Is3.number = number;
            function numberRange(value, min2, max) {
              return toString2.call(value) === "[object Number]" && min2 <= value && value <= max;
            }
            Is3.numberRange = numberRange;
            function integer3(value) {
              return toString2.call(value) === "[object Number]" && -2147483648 <= value && value <= 2147483647;
            }
            Is3.integer = integer3;
            function uinteger3(value) {
              return toString2.call(value) === "[object Number]" && 0 <= value && value <= 2147483647;
            }
            Is3.uinteger = uinteger3;
            function func(value) {
              return toString2.call(value) === "[object Function]";
            }
            Is3.func = func;
            function objectLiteral(value) {
              return value !== null && typeof value === "object";
            }
            Is3.objectLiteral = objectLiteral;
            function typedArray(value, check) {
              return Array.isArray(value) && value.every(check);
            }
            Is3.typedArray = typedArray;
          })(Is2 || (Is2 = {}));
        });
      })(main, main.exports);
      return main.exports;
    }
    var messages = {};
    var hasRequiredMessages;
    function requireMessages() {
      if (hasRequiredMessages) return messages;
      hasRequiredMessages = 1;
      Object.defineProperty(messages, "__esModule", { value: true });
      messages.ProtocolNotificationType = messages.ProtocolNotificationType0 = messages.ProtocolRequestType = messages.ProtocolRequestType0 = messages.RegistrationType = messages.MessageDirection = void 0;
      const vscode_jsonrpc_1 = requireMain$3();
      var MessageDirection;
      (function(MessageDirection2) {
        MessageDirection2["clientToServer"] = "clientToServer";
        MessageDirection2["serverToClient"] = "serverToClient";
        MessageDirection2["both"] = "both";
      })(MessageDirection || (messages.MessageDirection = MessageDirection = {}));
      class RegistrationType {
        constructor(method) {
          this.method = method;
        }
      }
      messages.RegistrationType = RegistrationType;
      class ProtocolRequestType0 extends vscode_jsonrpc_1.RequestType0 {
        constructor(method) {
          super(method);
        }
      }
      messages.ProtocolRequestType0 = ProtocolRequestType0;
      class ProtocolRequestType extends vscode_jsonrpc_1.RequestType {
        constructor(method) {
          super(method, vscode_jsonrpc_1.ParameterStructures.byName);
        }
      }
      messages.ProtocolRequestType = ProtocolRequestType;
      class ProtocolNotificationType0 extends vscode_jsonrpc_1.NotificationType0 {
        constructor(method) {
          super(method);
        }
      }
      messages.ProtocolNotificationType0 = ProtocolNotificationType0;
      class ProtocolNotificationType extends vscode_jsonrpc_1.NotificationType {
        constructor(method) {
          super(method, vscode_jsonrpc_1.ParameterStructures.byName);
        }
      }
      messages.ProtocolNotificationType = ProtocolNotificationType;
      return messages;
    }
    var protocol = {};
    var is$1 = {};
    var hasRequiredIs$1;
    function requireIs$1() {
      if (hasRequiredIs$1) return is$1;
      hasRequiredIs$1 = 1;
      Object.defineProperty(is$1, "__esModule", { value: true });
      is$1.objectLiteral = is$1.typedArray = is$1.stringArray = is$1.array = is$1.func = is$1.error = is$1.number = is$1.string = is$1.boolean = void 0;
      function boolean(value) {
        return value === true || value === false;
      }
      is$1.boolean = boolean;
      function string(value) {
        return typeof value === "string" || value instanceof String;
      }
      is$1.string = string;
      function number(value) {
        return typeof value === "number" || value instanceof Number;
      }
      is$1.number = number;
      function error(value) {
        return value instanceof Error;
      }
      is$1.error = error;
      function func(value) {
        return typeof value === "function";
      }
      is$1.func = func;
      function array(value) {
        return Array.isArray(value);
      }
      is$1.array = array;
      function stringArray(value) {
        return array(value) && value.every((elem) => string(elem));
      }
      is$1.stringArray = stringArray;
      function typedArray(value, check) {
        return Array.isArray(value) && value.every(check);
      }
      is$1.typedArray = typedArray;
      function objectLiteral(value) {
        return value !== null && typeof value === "object";
      }
      is$1.objectLiteral = objectLiteral;
      return is$1;
    }
    var protocol_implementation = {};
    var hasRequiredProtocol_implementation;
    function requireProtocol_implementation() {
      if (hasRequiredProtocol_implementation) return protocol_implementation;
      hasRequiredProtocol_implementation = 1;
      Object.defineProperty(protocol_implementation, "__esModule", { value: true });
      protocol_implementation.ImplementationRequest = void 0;
      const messages_1 = requireMessages();
      var ImplementationRequest;
      (function(ImplementationRequest2) {
        ImplementationRequest2.method = "textDocument/implementation";
        ImplementationRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        ImplementationRequest2.type = new messages_1.ProtocolRequestType(ImplementationRequest2.method);
      })(ImplementationRequest || (protocol_implementation.ImplementationRequest = ImplementationRequest = {}));
      return protocol_implementation;
    }
    var protocol_typeDefinition = {};
    var hasRequiredProtocol_typeDefinition;
    function requireProtocol_typeDefinition() {
      if (hasRequiredProtocol_typeDefinition) return protocol_typeDefinition;
      hasRequiredProtocol_typeDefinition = 1;
      Object.defineProperty(protocol_typeDefinition, "__esModule", { value: true });
      protocol_typeDefinition.TypeDefinitionRequest = void 0;
      const messages_1 = requireMessages();
      var TypeDefinitionRequest;
      (function(TypeDefinitionRequest2) {
        TypeDefinitionRequest2.method = "textDocument/typeDefinition";
        TypeDefinitionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        TypeDefinitionRequest2.type = new messages_1.ProtocolRequestType(TypeDefinitionRequest2.method);
      })(TypeDefinitionRequest || (protocol_typeDefinition.TypeDefinitionRequest = TypeDefinitionRequest = {}));
      return protocol_typeDefinition;
    }
    var protocol_workspaceFolder = {};
    var hasRequiredProtocol_workspaceFolder;
    function requireProtocol_workspaceFolder() {
      if (hasRequiredProtocol_workspaceFolder) return protocol_workspaceFolder;
      hasRequiredProtocol_workspaceFolder = 1;
      Object.defineProperty(protocol_workspaceFolder, "__esModule", { value: true });
      protocol_workspaceFolder.DidChangeWorkspaceFoldersNotification = protocol_workspaceFolder.WorkspaceFoldersRequest = void 0;
      const messages_1 = requireMessages();
      var WorkspaceFoldersRequest;
      (function(WorkspaceFoldersRequest2) {
        WorkspaceFoldersRequest2.method = "workspace/workspaceFolders";
        WorkspaceFoldersRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
        WorkspaceFoldersRequest2.type = new messages_1.ProtocolRequestType0(WorkspaceFoldersRequest2.method);
      })(WorkspaceFoldersRequest || (protocol_workspaceFolder.WorkspaceFoldersRequest = WorkspaceFoldersRequest = {}));
      var DidChangeWorkspaceFoldersNotification;
      (function(DidChangeWorkspaceFoldersNotification2) {
        DidChangeWorkspaceFoldersNotification2.method = "workspace/didChangeWorkspaceFolders";
        DidChangeWorkspaceFoldersNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
        DidChangeWorkspaceFoldersNotification2.type = new messages_1.ProtocolNotificationType(DidChangeWorkspaceFoldersNotification2.method);
      })(DidChangeWorkspaceFoldersNotification || (protocol_workspaceFolder.DidChangeWorkspaceFoldersNotification = DidChangeWorkspaceFoldersNotification = {}));
      return protocol_workspaceFolder;
    }
    var protocol_configuration = {};
    var hasRequiredProtocol_configuration;
    function requireProtocol_configuration() {
      if (hasRequiredProtocol_configuration) return protocol_configuration;
      hasRequiredProtocol_configuration = 1;
      Object.defineProperty(protocol_configuration, "__esModule", { value: true });
      protocol_configuration.ConfigurationRequest = void 0;
      const messages_1 = requireMessages();
      var ConfigurationRequest;
      (function(ConfigurationRequest2) {
        ConfigurationRequest2.method = "workspace/configuration";
        ConfigurationRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
        ConfigurationRequest2.type = new messages_1.ProtocolRequestType(ConfigurationRequest2.method);
      })(ConfigurationRequest || (protocol_configuration.ConfigurationRequest = ConfigurationRequest = {}));
      return protocol_configuration;
    }
    var protocol_colorProvider = {};
    var hasRequiredProtocol_colorProvider;
    function requireProtocol_colorProvider() {
      if (hasRequiredProtocol_colorProvider) return protocol_colorProvider;
      hasRequiredProtocol_colorProvider = 1;
      Object.defineProperty(protocol_colorProvider, "__esModule", { value: true });
      protocol_colorProvider.ColorPresentationRequest = protocol_colorProvider.DocumentColorRequest = void 0;
      const messages_1 = requireMessages();
      var DocumentColorRequest;
      (function(DocumentColorRequest2) {
        DocumentColorRequest2.method = "textDocument/documentColor";
        DocumentColorRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        DocumentColorRequest2.type = new messages_1.ProtocolRequestType(DocumentColorRequest2.method);
      })(DocumentColorRequest || (protocol_colorProvider.DocumentColorRequest = DocumentColorRequest = {}));
      var ColorPresentationRequest;
      (function(ColorPresentationRequest2) {
        ColorPresentationRequest2.method = "textDocument/colorPresentation";
        ColorPresentationRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        ColorPresentationRequest2.type = new messages_1.ProtocolRequestType(ColorPresentationRequest2.method);
      })(ColorPresentationRequest || (protocol_colorProvider.ColorPresentationRequest = ColorPresentationRequest = {}));
      return protocol_colorProvider;
    }
    var protocol_foldingRange = {};
    var hasRequiredProtocol_foldingRange;
    function requireProtocol_foldingRange() {
      if (hasRequiredProtocol_foldingRange) return protocol_foldingRange;
      hasRequiredProtocol_foldingRange = 1;
      Object.defineProperty(protocol_foldingRange, "__esModule", { value: true });
      protocol_foldingRange.FoldingRangeRefreshRequest = protocol_foldingRange.FoldingRangeRequest = void 0;
      const messages_1 = requireMessages();
      var FoldingRangeRequest;
      (function(FoldingRangeRequest2) {
        FoldingRangeRequest2.method = "textDocument/foldingRange";
        FoldingRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        FoldingRangeRequest2.type = new messages_1.ProtocolRequestType(FoldingRangeRequest2.method);
      })(FoldingRangeRequest || (protocol_foldingRange.FoldingRangeRequest = FoldingRangeRequest = {}));
      var FoldingRangeRefreshRequest;
      (function(FoldingRangeRefreshRequest2) {
        FoldingRangeRefreshRequest2.method = `workspace/foldingRange/refresh`;
        FoldingRangeRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
        FoldingRangeRefreshRequest2.type = new messages_1.ProtocolRequestType0(FoldingRangeRefreshRequest2.method);
      })(FoldingRangeRefreshRequest || (protocol_foldingRange.FoldingRangeRefreshRequest = FoldingRangeRefreshRequest = {}));
      return protocol_foldingRange;
    }
    var protocol_declaration = {};
    var hasRequiredProtocol_declaration;
    function requireProtocol_declaration() {
      if (hasRequiredProtocol_declaration) return protocol_declaration;
      hasRequiredProtocol_declaration = 1;
      Object.defineProperty(protocol_declaration, "__esModule", { value: true });
      protocol_declaration.DeclarationRequest = void 0;
      const messages_1 = requireMessages();
      var DeclarationRequest;
      (function(DeclarationRequest2) {
        DeclarationRequest2.method = "textDocument/declaration";
        DeclarationRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        DeclarationRequest2.type = new messages_1.ProtocolRequestType(DeclarationRequest2.method);
      })(DeclarationRequest || (protocol_declaration.DeclarationRequest = DeclarationRequest = {}));
      return protocol_declaration;
    }
    var protocol_selectionRange = {};
    var hasRequiredProtocol_selectionRange;
    function requireProtocol_selectionRange() {
      if (hasRequiredProtocol_selectionRange) return protocol_selectionRange;
      hasRequiredProtocol_selectionRange = 1;
      Object.defineProperty(protocol_selectionRange, "__esModule", { value: true });
      protocol_selectionRange.SelectionRangeRequest = void 0;
      const messages_1 = requireMessages();
      var SelectionRangeRequest;
      (function(SelectionRangeRequest2) {
        SelectionRangeRequest2.method = "textDocument/selectionRange";
        SelectionRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        SelectionRangeRequest2.type = new messages_1.ProtocolRequestType(SelectionRangeRequest2.method);
      })(SelectionRangeRequest || (protocol_selectionRange.SelectionRangeRequest = SelectionRangeRequest = {}));
      return protocol_selectionRange;
    }
    var protocol_progress = {};
    var hasRequiredProtocol_progress;
    function requireProtocol_progress() {
      if (hasRequiredProtocol_progress) return protocol_progress;
      hasRequiredProtocol_progress = 1;
      Object.defineProperty(protocol_progress, "__esModule", { value: true });
      protocol_progress.WorkDoneProgressCancelNotification = protocol_progress.WorkDoneProgressCreateRequest = protocol_progress.WorkDoneProgress = void 0;
      const vscode_jsonrpc_1 = requireMain$3();
      const messages_1 = requireMessages();
      var WorkDoneProgress;
      (function(WorkDoneProgress2) {
        WorkDoneProgress2.type = new vscode_jsonrpc_1.ProgressType();
        function is2(value) {
          return value === WorkDoneProgress2.type;
        }
        WorkDoneProgress2.is = is2;
      })(WorkDoneProgress || (protocol_progress.WorkDoneProgress = WorkDoneProgress = {}));
      var WorkDoneProgressCreateRequest;
      (function(WorkDoneProgressCreateRequest2) {
        WorkDoneProgressCreateRequest2.method = "window/workDoneProgress/create";
        WorkDoneProgressCreateRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
        WorkDoneProgressCreateRequest2.type = new messages_1.ProtocolRequestType(WorkDoneProgressCreateRequest2.method);
      })(WorkDoneProgressCreateRequest || (protocol_progress.WorkDoneProgressCreateRequest = WorkDoneProgressCreateRequest = {}));
      var WorkDoneProgressCancelNotification;
      (function(WorkDoneProgressCancelNotification2) {
        WorkDoneProgressCancelNotification2.method = "window/workDoneProgress/cancel";
        WorkDoneProgressCancelNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
        WorkDoneProgressCancelNotification2.type = new messages_1.ProtocolNotificationType(WorkDoneProgressCancelNotification2.method);
      })(WorkDoneProgressCancelNotification || (protocol_progress.WorkDoneProgressCancelNotification = WorkDoneProgressCancelNotification = {}));
      return protocol_progress;
    }
    var protocol_callHierarchy = {};
    var hasRequiredProtocol_callHierarchy;
    function requireProtocol_callHierarchy() {
      if (hasRequiredProtocol_callHierarchy) return protocol_callHierarchy;
      hasRequiredProtocol_callHierarchy = 1;
      Object.defineProperty(protocol_callHierarchy, "__esModule", { value: true });
      protocol_callHierarchy.CallHierarchyOutgoingCallsRequest = protocol_callHierarchy.CallHierarchyIncomingCallsRequest = protocol_callHierarchy.CallHierarchyPrepareRequest = void 0;
      const messages_1 = requireMessages();
      var CallHierarchyPrepareRequest;
      (function(CallHierarchyPrepareRequest2) {
        CallHierarchyPrepareRequest2.method = "textDocument/prepareCallHierarchy";
        CallHierarchyPrepareRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        CallHierarchyPrepareRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyPrepareRequest2.method);
      })(CallHierarchyPrepareRequest || (protocol_callHierarchy.CallHierarchyPrepareRequest = CallHierarchyPrepareRequest = {}));
      var CallHierarchyIncomingCallsRequest;
      (function(CallHierarchyIncomingCallsRequest2) {
        CallHierarchyIncomingCallsRequest2.method = "callHierarchy/incomingCalls";
        CallHierarchyIncomingCallsRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        CallHierarchyIncomingCallsRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyIncomingCallsRequest2.method);
      })(CallHierarchyIncomingCallsRequest || (protocol_callHierarchy.CallHierarchyIncomingCallsRequest = CallHierarchyIncomingCallsRequest = {}));
      var CallHierarchyOutgoingCallsRequest;
      (function(CallHierarchyOutgoingCallsRequest2) {
        CallHierarchyOutgoingCallsRequest2.method = "callHierarchy/outgoingCalls";
        CallHierarchyOutgoingCallsRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        CallHierarchyOutgoingCallsRequest2.type = new messages_1.ProtocolRequestType(CallHierarchyOutgoingCallsRequest2.method);
      })(CallHierarchyOutgoingCallsRequest || (protocol_callHierarchy.CallHierarchyOutgoingCallsRequest = CallHierarchyOutgoingCallsRequest = {}));
      return protocol_callHierarchy;
    }
    var protocol_semanticTokens = {};
    var hasRequiredProtocol_semanticTokens;
    function requireProtocol_semanticTokens() {
      if (hasRequiredProtocol_semanticTokens) return protocol_semanticTokens;
      hasRequiredProtocol_semanticTokens = 1;
      Object.defineProperty(protocol_semanticTokens, "__esModule", { value: true });
      protocol_semanticTokens.SemanticTokensRefreshRequest = protocol_semanticTokens.SemanticTokensRangeRequest = protocol_semanticTokens.SemanticTokensDeltaRequest = protocol_semanticTokens.SemanticTokensRequest = protocol_semanticTokens.SemanticTokensRegistrationType = protocol_semanticTokens.TokenFormat = void 0;
      const messages_1 = requireMessages();
      var TokenFormat;
      (function(TokenFormat2) {
        TokenFormat2.Relative = "relative";
      })(TokenFormat || (protocol_semanticTokens.TokenFormat = TokenFormat = {}));
      var SemanticTokensRegistrationType;
      (function(SemanticTokensRegistrationType2) {
        SemanticTokensRegistrationType2.method = "textDocument/semanticTokens";
        SemanticTokensRegistrationType2.type = new messages_1.RegistrationType(SemanticTokensRegistrationType2.method);
      })(SemanticTokensRegistrationType || (protocol_semanticTokens.SemanticTokensRegistrationType = SemanticTokensRegistrationType = {}));
      var SemanticTokensRequest;
      (function(SemanticTokensRequest2) {
        SemanticTokensRequest2.method = "textDocument/semanticTokens/full";
        SemanticTokensRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        SemanticTokensRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensRequest2.method);
        SemanticTokensRequest2.registrationMethod = SemanticTokensRegistrationType.method;
      })(SemanticTokensRequest || (protocol_semanticTokens.SemanticTokensRequest = SemanticTokensRequest = {}));
      var SemanticTokensDeltaRequest;
      (function(SemanticTokensDeltaRequest2) {
        SemanticTokensDeltaRequest2.method = "textDocument/semanticTokens/full/delta";
        SemanticTokensDeltaRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        SemanticTokensDeltaRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensDeltaRequest2.method);
        SemanticTokensDeltaRequest2.registrationMethod = SemanticTokensRegistrationType.method;
      })(SemanticTokensDeltaRequest || (protocol_semanticTokens.SemanticTokensDeltaRequest = SemanticTokensDeltaRequest = {}));
      var SemanticTokensRangeRequest;
      (function(SemanticTokensRangeRequest2) {
        SemanticTokensRangeRequest2.method = "textDocument/semanticTokens/range";
        SemanticTokensRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        SemanticTokensRangeRequest2.type = new messages_1.ProtocolRequestType(SemanticTokensRangeRequest2.method);
        SemanticTokensRangeRequest2.registrationMethod = SemanticTokensRegistrationType.method;
      })(SemanticTokensRangeRequest || (protocol_semanticTokens.SemanticTokensRangeRequest = SemanticTokensRangeRequest = {}));
      var SemanticTokensRefreshRequest;
      (function(SemanticTokensRefreshRequest2) {
        SemanticTokensRefreshRequest2.method = `workspace/semanticTokens/refresh`;
        SemanticTokensRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
        SemanticTokensRefreshRequest2.type = new messages_1.ProtocolRequestType0(SemanticTokensRefreshRequest2.method);
      })(SemanticTokensRefreshRequest || (protocol_semanticTokens.SemanticTokensRefreshRequest = SemanticTokensRefreshRequest = {}));
      return protocol_semanticTokens;
    }
    var protocol_showDocument = {};
    var hasRequiredProtocol_showDocument;
    function requireProtocol_showDocument() {
      if (hasRequiredProtocol_showDocument) return protocol_showDocument;
      hasRequiredProtocol_showDocument = 1;
      Object.defineProperty(protocol_showDocument, "__esModule", { value: true });
      protocol_showDocument.ShowDocumentRequest = void 0;
      const messages_1 = requireMessages();
      var ShowDocumentRequest;
      (function(ShowDocumentRequest2) {
        ShowDocumentRequest2.method = "window/showDocument";
        ShowDocumentRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
        ShowDocumentRequest2.type = new messages_1.ProtocolRequestType(ShowDocumentRequest2.method);
      })(ShowDocumentRequest || (protocol_showDocument.ShowDocumentRequest = ShowDocumentRequest = {}));
      return protocol_showDocument;
    }
    var protocol_linkedEditingRange = {};
    var hasRequiredProtocol_linkedEditingRange;
    function requireProtocol_linkedEditingRange() {
      if (hasRequiredProtocol_linkedEditingRange) return protocol_linkedEditingRange;
      hasRequiredProtocol_linkedEditingRange = 1;
      Object.defineProperty(protocol_linkedEditingRange, "__esModule", { value: true });
      protocol_linkedEditingRange.LinkedEditingRangeRequest = void 0;
      const messages_1 = requireMessages();
      var LinkedEditingRangeRequest;
      (function(LinkedEditingRangeRequest2) {
        LinkedEditingRangeRequest2.method = "textDocument/linkedEditingRange";
        LinkedEditingRangeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        LinkedEditingRangeRequest2.type = new messages_1.ProtocolRequestType(LinkedEditingRangeRequest2.method);
      })(LinkedEditingRangeRequest || (protocol_linkedEditingRange.LinkedEditingRangeRequest = LinkedEditingRangeRequest = {}));
      return protocol_linkedEditingRange;
    }
    var protocol_fileOperations = {};
    var hasRequiredProtocol_fileOperations;
    function requireProtocol_fileOperations() {
      if (hasRequiredProtocol_fileOperations) return protocol_fileOperations;
      hasRequiredProtocol_fileOperations = 1;
      Object.defineProperty(protocol_fileOperations, "__esModule", { value: true });
      protocol_fileOperations.WillDeleteFilesRequest = protocol_fileOperations.DidDeleteFilesNotification = protocol_fileOperations.DidRenameFilesNotification = protocol_fileOperations.WillRenameFilesRequest = protocol_fileOperations.DidCreateFilesNotification = protocol_fileOperations.WillCreateFilesRequest = protocol_fileOperations.FileOperationPatternKind = void 0;
      const messages_1 = requireMessages();
      var FileOperationPatternKind;
      (function(FileOperationPatternKind2) {
        FileOperationPatternKind2.file = "file";
        FileOperationPatternKind2.folder = "folder";
      })(FileOperationPatternKind || (protocol_fileOperations.FileOperationPatternKind = FileOperationPatternKind = {}));
      var WillCreateFilesRequest;
      (function(WillCreateFilesRequest2) {
        WillCreateFilesRequest2.method = "workspace/willCreateFiles";
        WillCreateFilesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        WillCreateFilesRequest2.type = new messages_1.ProtocolRequestType(WillCreateFilesRequest2.method);
      })(WillCreateFilesRequest || (protocol_fileOperations.WillCreateFilesRequest = WillCreateFilesRequest = {}));
      var DidCreateFilesNotification;
      (function(DidCreateFilesNotification2) {
        DidCreateFilesNotification2.method = "workspace/didCreateFiles";
        DidCreateFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
        DidCreateFilesNotification2.type = new messages_1.ProtocolNotificationType(DidCreateFilesNotification2.method);
      })(DidCreateFilesNotification || (protocol_fileOperations.DidCreateFilesNotification = DidCreateFilesNotification = {}));
      var WillRenameFilesRequest;
      (function(WillRenameFilesRequest2) {
        WillRenameFilesRequest2.method = "workspace/willRenameFiles";
        WillRenameFilesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        WillRenameFilesRequest2.type = new messages_1.ProtocolRequestType(WillRenameFilesRequest2.method);
      })(WillRenameFilesRequest || (protocol_fileOperations.WillRenameFilesRequest = WillRenameFilesRequest = {}));
      var DidRenameFilesNotification;
      (function(DidRenameFilesNotification2) {
        DidRenameFilesNotification2.method = "workspace/didRenameFiles";
        DidRenameFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
        DidRenameFilesNotification2.type = new messages_1.ProtocolNotificationType(DidRenameFilesNotification2.method);
      })(DidRenameFilesNotification || (protocol_fileOperations.DidRenameFilesNotification = DidRenameFilesNotification = {}));
      var DidDeleteFilesNotification;
      (function(DidDeleteFilesNotification2) {
        DidDeleteFilesNotification2.method = "workspace/didDeleteFiles";
        DidDeleteFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
        DidDeleteFilesNotification2.type = new messages_1.ProtocolNotificationType(DidDeleteFilesNotification2.method);
      })(DidDeleteFilesNotification || (protocol_fileOperations.DidDeleteFilesNotification = DidDeleteFilesNotification = {}));
      var WillDeleteFilesRequest;
      (function(WillDeleteFilesRequest2) {
        WillDeleteFilesRequest2.method = "workspace/willDeleteFiles";
        WillDeleteFilesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        WillDeleteFilesRequest2.type = new messages_1.ProtocolRequestType(WillDeleteFilesRequest2.method);
      })(WillDeleteFilesRequest || (protocol_fileOperations.WillDeleteFilesRequest = WillDeleteFilesRequest = {}));
      return protocol_fileOperations;
    }
    var protocol_moniker = {};
    var hasRequiredProtocol_moniker;
    function requireProtocol_moniker() {
      if (hasRequiredProtocol_moniker) return protocol_moniker;
      hasRequiredProtocol_moniker = 1;
      Object.defineProperty(protocol_moniker, "__esModule", { value: true });
      protocol_moniker.MonikerRequest = protocol_moniker.MonikerKind = protocol_moniker.UniquenessLevel = void 0;
      const messages_1 = requireMessages();
      var UniquenessLevel;
      (function(UniquenessLevel2) {
        UniquenessLevel2.document = "document";
        UniquenessLevel2.project = "project";
        UniquenessLevel2.group = "group";
        UniquenessLevel2.scheme = "scheme";
        UniquenessLevel2.global = "global";
      })(UniquenessLevel || (protocol_moniker.UniquenessLevel = UniquenessLevel = {}));
      var MonikerKind;
      (function(MonikerKind2) {
        MonikerKind2.$import = "import";
        MonikerKind2.$export = "export";
        MonikerKind2.local = "local";
      })(MonikerKind || (protocol_moniker.MonikerKind = MonikerKind = {}));
      var MonikerRequest;
      (function(MonikerRequest2) {
        MonikerRequest2.method = "textDocument/moniker";
        MonikerRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        MonikerRequest2.type = new messages_1.ProtocolRequestType(MonikerRequest2.method);
      })(MonikerRequest || (protocol_moniker.MonikerRequest = MonikerRequest = {}));
      return protocol_moniker;
    }
    var protocol_typeHierarchy = {};
    var hasRequiredProtocol_typeHierarchy;
    function requireProtocol_typeHierarchy() {
      if (hasRequiredProtocol_typeHierarchy) return protocol_typeHierarchy;
      hasRequiredProtocol_typeHierarchy = 1;
      Object.defineProperty(protocol_typeHierarchy, "__esModule", { value: true });
      protocol_typeHierarchy.TypeHierarchySubtypesRequest = protocol_typeHierarchy.TypeHierarchySupertypesRequest = protocol_typeHierarchy.TypeHierarchyPrepareRequest = void 0;
      const messages_1 = requireMessages();
      var TypeHierarchyPrepareRequest;
      (function(TypeHierarchyPrepareRequest2) {
        TypeHierarchyPrepareRequest2.method = "textDocument/prepareTypeHierarchy";
        TypeHierarchyPrepareRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        TypeHierarchyPrepareRequest2.type = new messages_1.ProtocolRequestType(TypeHierarchyPrepareRequest2.method);
      })(TypeHierarchyPrepareRequest || (protocol_typeHierarchy.TypeHierarchyPrepareRequest = TypeHierarchyPrepareRequest = {}));
      var TypeHierarchySupertypesRequest;
      (function(TypeHierarchySupertypesRequest2) {
        TypeHierarchySupertypesRequest2.method = "typeHierarchy/supertypes";
        TypeHierarchySupertypesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        TypeHierarchySupertypesRequest2.type = new messages_1.ProtocolRequestType(TypeHierarchySupertypesRequest2.method);
      })(TypeHierarchySupertypesRequest || (protocol_typeHierarchy.TypeHierarchySupertypesRequest = TypeHierarchySupertypesRequest = {}));
      var TypeHierarchySubtypesRequest;
      (function(TypeHierarchySubtypesRequest2) {
        TypeHierarchySubtypesRequest2.method = "typeHierarchy/subtypes";
        TypeHierarchySubtypesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        TypeHierarchySubtypesRequest2.type = new messages_1.ProtocolRequestType(TypeHierarchySubtypesRequest2.method);
      })(TypeHierarchySubtypesRequest || (protocol_typeHierarchy.TypeHierarchySubtypesRequest = TypeHierarchySubtypesRequest = {}));
      return protocol_typeHierarchy;
    }
    var protocol_inlineValue = {};
    var hasRequiredProtocol_inlineValue;
    function requireProtocol_inlineValue() {
      if (hasRequiredProtocol_inlineValue) return protocol_inlineValue;
      hasRequiredProtocol_inlineValue = 1;
      Object.defineProperty(protocol_inlineValue, "__esModule", { value: true });
      protocol_inlineValue.InlineValueRefreshRequest = protocol_inlineValue.InlineValueRequest = void 0;
      const messages_1 = requireMessages();
      var InlineValueRequest;
      (function(InlineValueRequest2) {
        InlineValueRequest2.method = "textDocument/inlineValue";
        InlineValueRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        InlineValueRequest2.type = new messages_1.ProtocolRequestType(InlineValueRequest2.method);
      })(InlineValueRequest || (protocol_inlineValue.InlineValueRequest = InlineValueRequest = {}));
      var InlineValueRefreshRequest;
      (function(InlineValueRefreshRequest2) {
        InlineValueRefreshRequest2.method = `workspace/inlineValue/refresh`;
        InlineValueRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
        InlineValueRefreshRequest2.type = new messages_1.ProtocolRequestType0(InlineValueRefreshRequest2.method);
      })(InlineValueRefreshRequest || (protocol_inlineValue.InlineValueRefreshRequest = InlineValueRefreshRequest = {}));
      return protocol_inlineValue;
    }
    var protocol_inlayHint = {};
    var hasRequiredProtocol_inlayHint;
    function requireProtocol_inlayHint() {
      if (hasRequiredProtocol_inlayHint) return protocol_inlayHint;
      hasRequiredProtocol_inlayHint = 1;
      Object.defineProperty(protocol_inlayHint, "__esModule", { value: true });
      protocol_inlayHint.InlayHintRefreshRequest = protocol_inlayHint.InlayHintResolveRequest = protocol_inlayHint.InlayHintRequest = void 0;
      const messages_1 = requireMessages();
      var InlayHintRequest;
      (function(InlayHintRequest2) {
        InlayHintRequest2.method = "textDocument/inlayHint";
        InlayHintRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        InlayHintRequest2.type = new messages_1.ProtocolRequestType(InlayHintRequest2.method);
      })(InlayHintRequest || (protocol_inlayHint.InlayHintRequest = InlayHintRequest = {}));
      var InlayHintResolveRequest;
      (function(InlayHintResolveRequest2) {
        InlayHintResolveRequest2.method = "inlayHint/resolve";
        InlayHintResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        InlayHintResolveRequest2.type = new messages_1.ProtocolRequestType(InlayHintResolveRequest2.method);
      })(InlayHintResolveRequest || (protocol_inlayHint.InlayHintResolveRequest = InlayHintResolveRequest = {}));
      var InlayHintRefreshRequest;
      (function(InlayHintRefreshRequest2) {
        InlayHintRefreshRequest2.method = `workspace/inlayHint/refresh`;
        InlayHintRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
        InlayHintRefreshRequest2.type = new messages_1.ProtocolRequestType0(InlayHintRefreshRequest2.method);
      })(InlayHintRefreshRequest || (protocol_inlayHint.InlayHintRefreshRequest = InlayHintRefreshRequest = {}));
      return protocol_inlayHint;
    }
    var protocol_diagnostic = {};
    var hasRequiredProtocol_diagnostic;
    function requireProtocol_diagnostic() {
      if (hasRequiredProtocol_diagnostic) return protocol_diagnostic;
      hasRequiredProtocol_diagnostic = 1;
      Object.defineProperty(protocol_diagnostic, "__esModule", { value: true });
      protocol_diagnostic.DiagnosticRefreshRequest = protocol_diagnostic.WorkspaceDiagnosticRequest = protocol_diagnostic.DocumentDiagnosticRequest = protocol_diagnostic.DocumentDiagnosticReportKind = protocol_diagnostic.DiagnosticServerCancellationData = void 0;
      const vscode_jsonrpc_1 = requireMain$3();
      const Is2 = requireIs$1();
      const messages_1 = requireMessages();
      var DiagnosticServerCancellationData;
      (function(DiagnosticServerCancellationData2) {
        function is2(value) {
          const candidate = value;
          return candidate && Is2.boolean(candidate.retriggerRequest);
        }
        DiagnosticServerCancellationData2.is = is2;
      })(DiagnosticServerCancellationData || (protocol_diagnostic.DiagnosticServerCancellationData = DiagnosticServerCancellationData = {}));
      var DocumentDiagnosticReportKind;
      (function(DocumentDiagnosticReportKind2) {
        DocumentDiagnosticReportKind2.Full = "full";
        DocumentDiagnosticReportKind2.Unchanged = "unchanged";
      })(DocumentDiagnosticReportKind || (protocol_diagnostic.DocumentDiagnosticReportKind = DocumentDiagnosticReportKind = {}));
      var DocumentDiagnosticRequest;
      (function(DocumentDiagnosticRequest2) {
        DocumentDiagnosticRequest2.method = "textDocument/diagnostic";
        DocumentDiagnosticRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        DocumentDiagnosticRequest2.type = new messages_1.ProtocolRequestType(DocumentDiagnosticRequest2.method);
        DocumentDiagnosticRequest2.partialResult = new vscode_jsonrpc_1.ProgressType();
      })(DocumentDiagnosticRequest || (protocol_diagnostic.DocumentDiagnosticRequest = DocumentDiagnosticRequest = {}));
      var WorkspaceDiagnosticRequest;
      (function(WorkspaceDiagnosticRequest2) {
        WorkspaceDiagnosticRequest2.method = "workspace/diagnostic";
        WorkspaceDiagnosticRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        WorkspaceDiagnosticRequest2.type = new messages_1.ProtocolRequestType(WorkspaceDiagnosticRequest2.method);
        WorkspaceDiagnosticRequest2.partialResult = new vscode_jsonrpc_1.ProgressType();
      })(WorkspaceDiagnosticRequest || (protocol_diagnostic.WorkspaceDiagnosticRequest = WorkspaceDiagnosticRequest = {}));
      var DiagnosticRefreshRequest;
      (function(DiagnosticRefreshRequest2) {
        DiagnosticRefreshRequest2.method = `workspace/diagnostic/refresh`;
        DiagnosticRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
        DiagnosticRefreshRequest2.type = new messages_1.ProtocolRequestType0(DiagnosticRefreshRequest2.method);
      })(DiagnosticRefreshRequest || (protocol_diagnostic.DiagnosticRefreshRequest = DiagnosticRefreshRequest = {}));
      return protocol_diagnostic;
    }
    var protocol_notebook = {};
    var hasRequiredProtocol_notebook;
    function requireProtocol_notebook() {
      if (hasRequiredProtocol_notebook) return protocol_notebook;
      hasRequiredProtocol_notebook = 1;
      Object.defineProperty(protocol_notebook, "__esModule", { value: true });
      protocol_notebook.DidCloseNotebookDocumentNotification = protocol_notebook.DidSaveNotebookDocumentNotification = protocol_notebook.DidChangeNotebookDocumentNotification = protocol_notebook.NotebookCellArrayChange = protocol_notebook.DidOpenNotebookDocumentNotification = protocol_notebook.NotebookDocumentSyncRegistrationType = protocol_notebook.NotebookDocument = protocol_notebook.NotebookCell = protocol_notebook.ExecutionSummary = protocol_notebook.NotebookCellKind = void 0;
      const vscode_languageserver_types_1 = requireMain$2();
      const Is2 = requireIs$1();
      const messages_1 = requireMessages();
      var NotebookCellKind;
      (function(NotebookCellKind2) {
        NotebookCellKind2.Markup = 1;
        NotebookCellKind2.Code = 2;
        function is2(value) {
          return value === 1 || value === 2;
        }
        NotebookCellKind2.is = is2;
      })(NotebookCellKind || (protocol_notebook.NotebookCellKind = NotebookCellKind = {}));
      var ExecutionSummary;
      (function(ExecutionSummary2) {
        function create(executionOrder, success) {
          const result = { executionOrder };
          if (success === true || success === false) {
            result.success = success;
          }
          return result;
        }
        ExecutionSummary2.create = create;
        function is2(value) {
          const candidate = value;
          return Is2.objectLiteral(candidate) && vscode_languageserver_types_1.uinteger.is(candidate.executionOrder) && (candidate.success === void 0 || Is2.boolean(candidate.success));
        }
        ExecutionSummary2.is = is2;
        function equals(one, other) {
          if (one === other) {
            return true;
          }
          if (one === null || one === void 0 || other === null || other === void 0) {
            return false;
          }
          return one.executionOrder === other.executionOrder && one.success === other.success;
        }
        ExecutionSummary2.equals = equals;
      })(ExecutionSummary || (protocol_notebook.ExecutionSummary = ExecutionSummary = {}));
      var NotebookCell;
      (function(NotebookCell2) {
        function create(kind, document) {
          return { kind, document };
        }
        NotebookCell2.create = create;
        function is2(value) {
          const candidate = value;
          return Is2.objectLiteral(candidate) && NotebookCellKind.is(candidate.kind) && vscode_languageserver_types_1.DocumentUri.is(candidate.document) && (candidate.metadata === void 0 || Is2.objectLiteral(candidate.metadata));
        }
        NotebookCell2.is = is2;
        function diff(one, two) {
          const result = /* @__PURE__ */ new Set();
          if (one.document !== two.document) {
            result.add("document");
          }
          if (one.kind !== two.kind) {
            result.add("kind");
          }
          if (one.executionSummary !== two.executionSummary) {
            result.add("executionSummary");
          }
          if ((one.metadata !== void 0 || two.metadata !== void 0) && !equalsMetadata(one.metadata, two.metadata)) {
            result.add("metadata");
          }
          if ((one.executionSummary !== void 0 || two.executionSummary !== void 0) && !ExecutionSummary.equals(one.executionSummary, two.executionSummary)) {
            result.add("executionSummary");
          }
          return result;
        }
        NotebookCell2.diff = diff;
        function equalsMetadata(one, other) {
          if (one === other) {
            return true;
          }
          if (one === null || one === void 0 || other === null || other === void 0) {
            return false;
          }
          if (typeof one !== typeof other) {
            return false;
          }
          if (typeof one !== "object") {
            return false;
          }
          const oneArray = Array.isArray(one);
          const otherArray = Array.isArray(other);
          if (oneArray !== otherArray) {
            return false;
          }
          if (oneArray && otherArray) {
            if (one.length !== other.length) {
              return false;
            }
            for (let i = 0; i < one.length; i++) {
              if (!equalsMetadata(one[i], other[i])) {
                return false;
              }
            }
          }
          if (Is2.objectLiteral(one) && Is2.objectLiteral(other)) {
            const oneKeys = Object.keys(one);
            const otherKeys = Object.keys(other);
            if (oneKeys.length !== otherKeys.length) {
              return false;
            }
            oneKeys.sort();
            otherKeys.sort();
            if (!equalsMetadata(oneKeys, otherKeys)) {
              return false;
            }
            for (let i = 0; i < oneKeys.length; i++) {
              const prop = oneKeys[i];
              if (!equalsMetadata(one[prop], other[prop])) {
                return false;
              }
            }
          }
          return true;
        }
      })(NotebookCell || (protocol_notebook.NotebookCell = NotebookCell = {}));
      var NotebookDocument;
      (function(NotebookDocument2) {
        function create(uri, notebookType, version, cells) {
          return { uri, notebookType, version, cells };
        }
        NotebookDocument2.create = create;
        function is2(value) {
          const candidate = value;
          return Is2.objectLiteral(candidate) && Is2.string(candidate.uri) && vscode_languageserver_types_1.integer.is(candidate.version) && Is2.typedArray(candidate.cells, NotebookCell.is);
        }
        NotebookDocument2.is = is2;
      })(NotebookDocument || (protocol_notebook.NotebookDocument = NotebookDocument = {}));
      var NotebookDocumentSyncRegistrationType;
      (function(NotebookDocumentSyncRegistrationType2) {
        NotebookDocumentSyncRegistrationType2.method = "notebookDocument/sync";
        NotebookDocumentSyncRegistrationType2.messageDirection = messages_1.MessageDirection.clientToServer;
        NotebookDocumentSyncRegistrationType2.type = new messages_1.RegistrationType(NotebookDocumentSyncRegistrationType2.method);
      })(NotebookDocumentSyncRegistrationType || (protocol_notebook.NotebookDocumentSyncRegistrationType = NotebookDocumentSyncRegistrationType = {}));
      var DidOpenNotebookDocumentNotification;
      (function(DidOpenNotebookDocumentNotification2) {
        DidOpenNotebookDocumentNotification2.method = "notebookDocument/didOpen";
        DidOpenNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
        DidOpenNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidOpenNotebookDocumentNotification2.method);
        DidOpenNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method;
      })(DidOpenNotebookDocumentNotification || (protocol_notebook.DidOpenNotebookDocumentNotification = DidOpenNotebookDocumentNotification = {}));
      var NotebookCellArrayChange;
      (function(NotebookCellArrayChange2) {
        function is2(value) {
          const candidate = value;
          return Is2.objectLiteral(candidate) && vscode_languageserver_types_1.uinteger.is(candidate.start) && vscode_languageserver_types_1.uinteger.is(candidate.deleteCount) && (candidate.cells === void 0 || Is2.typedArray(candidate.cells, NotebookCell.is));
        }
        NotebookCellArrayChange2.is = is2;
        function create(start, deleteCount, cells) {
          const result = { start, deleteCount };
          if (cells !== void 0) {
            result.cells = cells;
          }
          return result;
        }
        NotebookCellArrayChange2.create = create;
      })(NotebookCellArrayChange || (protocol_notebook.NotebookCellArrayChange = NotebookCellArrayChange = {}));
      var DidChangeNotebookDocumentNotification;
      (function(DidChangeNotebookDocumentNotification2) {
        DidChangeNotebookDocumentNotification2.method = "notebookDocument/didChange";
        DidChangeNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
        DidChangeNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidChangeNotebookDocumentNotification2.method);
        DidChangeNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method;
      })(DidChangeNotebookDocumentNotification || (protocol_notebook.DidChangeNotebookDocumentNotification = DidChangeNotebookDocumentNotification = {}));
      var DidSaveNotebookDocumentNotification;
      (function(DidSaveNotebookDocumentNotification2) {
        DidSaveNotebookDocumentNotification2.method = "notebookDocument/didSave";
        DidSaveNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
        DidSaveNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidSaveNotebookDocumentNotification2.method);
        DidSaveNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method;
      })(DidSaveNotebookDocumentNotification || (protocol_notebook.DidSaveNotebookDocumentNotification = DidSaveNotebookDocumentNotification = {}));
      var DidCloseNotebookDocumentNotification;
      (function(DidCloseNotebookDocumentNotification2) {
        DidCloseNotebookDocumentNotification2.method = "notebookDocument/didClose";
        DidCloseNotebookDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
        DidCloseNotebookDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidCloseNotebookDocumentNotification2.method);
        DidCloseNotebookDocumentNotification2.registrationMethod = NotebookDocumentSyncRegistrationType.method;
      })(DidCloseNotebookDocumentNotification || (protocol_notebook.DidCloseNotebookDocumentNotification = DidCloseNotebookDocumentNotification = {}));
      return protocol_notebook;
    }
    var protocol_inlineCompletion = {};
    var hasRequiredProtocol_inlineCompletion;
    function requireProtocol_inlineCompletion() {
      if (hasRequiredProtocol_inlineCompletion) return protocol_inlineCompletion;
      hasRequiredProtocol_inlineCompletion = 1;
      Object.defineProperty(protocol_inlineCompletion, "__esModule", { value: true });
      protocol_inlineCompletion.InlineCompletionRequest = void 0;
      const messages_1 = requireMessages();
      var InlineCompletionRequest;
      (function(InlineCompletionRequest2) {
        InlineCompletionRequest2.method = "textDocument/inlineCompletion";
        InlineCompletionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
        InlineCompletionRequest2.type = new messages_1.ProtocolRequestType(InlineCompletionRequest2.method);
      })(InlineCompletionRequest || (protocol_inlineCompletion.InlineCompletionRequest = InlineCompletionRequest = {}));
      return protocol_inlineCompletion;
    }
    var hasRequiredProtocol;
    function requireProtocol() {
      if (hasRequiredProtocol) return protocol;
      hasRequiredProtocol = 1;
      (function(exports2) {
        Object.defineProperty(exports2, "__esModule", { value: true });
        exports2.WorkspaceSymbolRequest = exports2.CodeActionResolveRequest = exports2.CodeActionRequest = exports2.DocumentSymbolRequest = exports2.DocumentHighlightRequest = exports2.ReferencesRequest = exports2.DefinitionRequest = exports2.SignatureHelpRequest = exports2.SignatureHelpTriggerKind = exports2.HoverRequest = exports2.CompletionResolveRequest = exports2.CompletionRequest = exports2.CompletionTriggerKind = exports2.PublishDiagnosticsNotification = exports2.WatchKind = exports2.RelativePattern = exports2.FileChangeType = exports2.DidChangeWatchedFilesNotification = exports2.WillSaveTextDocumentWaitUntilRequest = exports2.WillSaveTextDocumentNotification = exports2.TextDocumentSaveReason = exports2.DidSaveTextDocumentNotification = exports2.DidCloseTextDocumentNotification = exports2.DidChangeTextDocumentNotification = exports2.TextDocumentContentChangeEvent = exports2.DidOpenTextDocumentNotification = exports2.TextDocumentSyncKind = exports2.TelemetryEventNotification = exports2.LogMessageNotification = exports2.ShowMessageRequest = exports2.ShowMessageNotification = exports2.MessageType = exports2.DidChangeConfigurationNotification = exports2.ExitNotification = exports2.ShutdownRequest = exports2.InitializedNotification = exports2.InitializeErrorCodes = exports2.InitializeRequest = exports2.WorkDoneProgressOptions = exports2.TextDocumentRegistrationOptions = exports2.StaticRegistrationOptions = exports2.PositionEncodingKind = exports2.FailureHandlingKind = exports2.ResourceOperationKind = exports2.UnregistrationRequest = exports2.RegistrationRequest = exports2.DocumentSelector = exports2.NotebookCellTextDocumentFilter = exports2.NotebookDocumentFilter = exports2.TextDocumentFilter = void 0;
        exports2.MonikerRequest = exports2.MonikerKind = exports2.UniquenessLevel = exports2.WillDeleteFilesRequest = exports2.DidDeleteFilesNotification = exports2.WillRenameFilesRequest = exports2.DidRenameFilesNotification = exports2.WillCreateFilesRequest = exports2.DidCreateFilesNotification = exports2.FileOperationPatternKind = exports2.LinkedEditingRangeRequest = exports2.ShowDocumentRequest = exports2.SemanticTokensRegistrationType = exports2.SemanticTokensRefreshRequest = exports2.SemanticTokensRangeRequest = exports2.SemanticTokensDeltaRequest = exports2.SemanticTokensRequest = exports2.TokenFormat = exports2.CallHierarchyPrepareRequest = exports2.CallHierarchyOutgoingCallsRequest = exports2.CallHierarchyIncomingCallsRequest = exports2.WorkDoneProgressCancelNotification = exports2.WorkDoneProgressCreateRequest = exports2.WorkDoneProgress = exports2.SelectionRangeRequest = exports2.DeclarationRequest = exports2.FoldingRangeRefreshRequest = exports2.FoldingRangeRequest = exports2.ColorPresentationRequest = exports2.DocumentColorRequest = exports2.ConfigurationRequest = exports2.DidChangeWorkspaceFoldersNotification = exports2.WorkspaceFoldersRequest = exports2.TypeDefinitionRequest = exports2.ImplementationRequest = exports2.ApplyWorkspaceEditRequest = exports2.ExecuteCommandRequest = exports2.PrepareRenameRequest = exports2.RenameRequest = exports2.PrepareSupportDefaultBehavior = exports2.DocumentOnTypeFormattingRequest = exports2.DocumentRangesFormattingRequest = exports2.DocumentRangeFormattingRequest = exports2.DocumentFormattingRequest = exports2.DocumentLinkResolveRequest = exports2.DocumentLinkRequest = exports2.CodeLensRefreshRequest = exports2.CodeLensResolveRequest = exports2.CodeLensRequest = exports2.WorkspaceSymbolResolveRequest = void 0;
        exports2.InlineCompletionRequest = exports2.DidCloseNotebookDocumentNotification = exports2.DidSaveNotebookDocumentNotification = exports2.DidChangeNotebookDocumentNotification = exports2.NotebookCellArrayChange = exports2.DidOpenNotebookDocumentNotification = exports2.NotebookDocumentSyncRegistrationType = exports2.NotebookDocument = exports2.NotebookCell = exports2.ExecutionSummary = exports2.NotebookCellKind = exports2.DiagnosticRefreshRequest = exports2.WorkspaceDiagnosticRequest = exports2.DocumentDiagnosticRequest = exports2.DocumentDiagnosticReportKind = exports2.DiagnosticServerCancellationData = exports2.InlayHintRefreshRequest = exports2.InlayHintResolveRequest = exports2.InlayHintRequest = exports2.InlineValueRefreshRequest = exports2.InlineValueRequest = exports2.TypeHierarchySupertypesRequest = exports2.TypeHierarchySubtypesRequest = exports2.TypeHierarchyPrepareRequest = void 0;
        const messages_1 = requireMessages();
        const vscode_languageserver_types_1 = requireMain$2();
        const Is2 = requireIs$1();
        const protocol_implementation_1 = requireProtocol_implementation();
        Object.defineProperty(exports2, "ImplementationRequest", { enumerable: true, get: function() {
          return protocol_implementation_1.ImplementationRequest;
        } });
        const protocol_typeDefinition_1 = requireProtocol_typeDefinition();
        Object.defineProperty(exports2, "TypeDefinitionRequest", { enumerable: true, get: function() {
          return protocol_typeDefinition_1.TypeDefinitionRequest;
        } });
        const protocol_workspaceFolder_1 = requireProtocol_workspaceFolder();
        Object.defineProperty(exports2, "WorkspaceFoldersRequest", { enumerable: true, get: function() {
          return protocol_workspaceFolder_1.WorkspaceFoldersRequest;
        } });
        Object.defineProperty(exports2, "DidChangeWorkspaceFoldersNotification", { enumerable: true, get: function() {
          return protocol_workspaceFolder_1.DidChangeWorkspaceFoldersNotification;
        } });
        const protocol_configuration_1 = requireProtocol_configuration();
        Object.defineProperty(exports2, "ConfigurationRequest", { enumerable: true, get: function() {
          return protocol_configuration_1.ConfigurationRequest;
        } });
        const protocol_colorProvider_1 = requireProtocol_colorProvider();
        Object.defineProperty(exports2, "DocumentColorRequest", { enumerable: true, get: function() {
          return protocol_colorProvider_1.DocumentColorRequest;
        } });
        Object.defineProperty(exports2, "ColorPresentationRequest", { enumerable: true, get: function() {
          return protocol_colorProvider_1.ColorPresentationRequest;
        } });
        const protocol_foldingRange_1 = requireProtocol_foldingRange();
        Object.defineProperty(exports2, "FoldingRangeRequest", { enumerable: true, get: function() {
          return protocol_foldingRange_1.FoldingRangeRequest;
        } });
        Object.defineProperty(exports2, "FoldingRangeRefreshRequest", { enumerable: true, get: function() {
          return protocol_foldingRange_1.FoldingRangeRefreshRequest;
        } });
        const protocol_declaration_1 = requireProtocol_declaration();
        Object.defineProperty(exports2, "DeclarationRequest", { enumerable: true, get: function() {
          return protocol_declaration_1.DeclarationRequest;
        } });
        const protocol_selectionRange_1 = requireProtocol_selectionRange();
        Object.defineProperty(exports2, "SelectionRangeRequest", { enumerable: true, get: function() {
          return protocol_selectionRange_1.SelectionRangeRequest;
        } });
        const protocol_progress_1 = requireProtocol_progress();
        Object.defineProperty(exports2, "WorkDoneProgress", { enumerable: true, get: function() {
          return protocol_progress_1.WorkDoneProgress;
        } });
        Object.defineProperty(exports2, "WorkDoneProgressCreateRequest", { enumerable: true, get: function() {
          return protocol_progress_1.WorkDoneProgressCreateRequest;
        } });
        Object.defineProperty(exports2, "WorkDoneProgressCancelNotification", { enumerable: true, get: function() {
          return protocol_progress_1.WorkDoneProgressCancelNotification;
        } });
        const protocol_callHierarchy_1 = requireProtocol_callHierarchy();
        Object.defineProperty(exports2, "CallHierarchyIncomingCallsRequest", { enumerable: true, get: function() {
          return protocol_callHierarchy_1.CallHierarchyIncomingCallsRequest;
        } });
        Object.defineProperty(exports2, "CallHierarchyOutgoingCallsRequest", { enumerable: true, get: function() {
          return protocol_callHierarchy_1.CallHierarchyOutgoingCallsRequest;
        } });
        Object.defineProperty(exports2, "CallHierarchyPrepareRequest", { enumerable: true, get: function() {
          return protocol_callHierarchy_1.CallHierarchyPrepareRequest;
        } });
        const protocol_semanticTokens_1 = requireProtocol_semanticTokens();
        Object.defineProperty(exports2, "TokenFormat", { enumerable: true, get: function() {
          return protocol_semanticTokens_1.TokenFormat;
        } });
        Object.defineProperty(exports2, "SemanticTokensRequest", { enumerable: true, get: function() {
          return protocol_semanticTokens_1.SemanticTokensRequest;
        } });
        Object.defineProperty(exports2, "SemanticTokensDeltaRequest", { enumerable: true, get: function() {
          return protocol_semanticTokens_1.SemanticTokensDeltaRequest;
        } });
        Object.defineProperty(exports2, "SemanticTokensRangeRequest", { enumerable: true, get: function() {
          return protocol_semanticTokens_1.SemanticTokensRangeRequest;
        } });
        Object.defineProperty(exports2, "SemanticTokensRefreshRequest", { enumerable: true, get: function() {
          return protocol_semanticTokens_1.SemanticTokensRefreshRequest;
        } });
        Object.defineProperty(exports2, "SemanticTokensRegistrationType", { enumerable: true, get: function() {
          return protocol_semanticTokens_1.SemanticTokensRegistrationType;
        } });
        const protocol_showDocument_1 = requireProtocol_showDocument();
        Object.defineProperty(exports2, "ShowDocumentRequest", { enumerable: true, get: function() {
          return protocol_showDocument_1.ShowDocumentRequest;
        } });
        const protocol_linkedEditingRange_1 = requireProtocol_linkedEditingRange();
        Object.defineProperty(exports2, "LinkedEditingRangeRequest", { enumerable: true, get: function() {
          return protocol_linkedEditingRange_1.LinkedEditingRangeRequest;
        } });
        const protocol_fileOperations_1 = requireProtocol_fileOperations();
        Object.defineProperty(exports2, "FileOperationPatternKind", { enumerable: true, get: function() {
          return protocol_fileOperations_1.FileOperationPatternKind;
        } });
        Object.defineProperty(exports2, "DidCreateFilesNotification", { enumerable: true, get: function() {
          return protocol_fileOperations_1.DidCreateFilesNotification;
        } });
        Object.defineProperty(exports2, "WillCreateFilesRequest", { enumerable: true, get: function() {
          return protocol_fileOperations_1.WillCreateFilesRequest;
        } });
        Object.defineProperty(exports2, "DidRenameFilesNotification", { enumerable: true, get: function() {
          return protocol_fileOperations_1.DidRenameFilesNotification;
        } });
        Object.defineProperty(exports2, "WillRenameFilesRequest", { enumerable: true, get: function() {
          return protocol_fileOperations_1.WillRenameFilesRequest;
        } });
        Object.defineProperty(exports2, "DidDeleteFilesNotification", { enumerable: true, get: function() {
          return protocol_fileOperations_1.DidDeleteFilesNotification;
        } });
        Object.defineProperty(exports2, "WillDeleteFilesRequest", { enumerable: true, get: function() {
          return protocol_fileOperations_1.WillDeleteFilesRequest;
        } });
        const protocol_moniker_1 = requireProtocol_moniker();
        Object.defineProperty(exports2, "UniquenessLevel", { enumerable: true, get: function() {
          return protocol_moniker_1.UniquenessLevel;
        } });
        Object.defineProperty(exports2, "MonikerKind", { enumerable: true, get: function() {
          return protocol_moniker_1.MonikerKind;
        } });
        Object.defineProperty(exports2, "MonikerRequest", { enumerable: true, get: function() {
          return protocol_moniker_1.MonikerRequest;
        } });
        const protocol_typeHierarchy_1 = requireProtocol_typeHierarchy();
        Object.defineProperty(exports2, "TypeHierarchyPrepareRequest", { enumerable: true, get: function() {
          return protocol_typeHierarchy_1.TypeHierarchyPrepareRequest;
        } });
        Object.defineProperty(exports2, "TypeHierarchySubtypesRequest", { enumerable: true, get: function() {
          return protocol_typeHierarchy_1.TypeHierarchySubtypesRequest;
        } });
        Object.defineProperty(exports2, "TypeHierarchySupertypesRequest", { enumerable: true, get: function() {
          return protocol_typeHierarchy_1.TypeHierarchySupertypesRequest;
        } });
        const protocol_inlineValue_1 = requireProtocol_inlineValue();
        Object.defineProperty(exports2, "InlineValueRequest", { enumerable: true, get: function() {
          return protocol_inlineValue_1.InlineValueRequest;
        } });
        Object.defineProperty(exports2, "InlineValueRefreshRequest", { enumerable: true, get: function() {
          return protocol_inlineValue_1.InlineValueRefreshRequest;
        } });
        const protocol_inlayHint_1 = requireProtocol_inlayHint();
        Object.defineProperty(exports2, "InlayHintRequest", { enumerable: true, get: function() {
          return protocol_inlayHint_1.InlayHintRequest;
        } });
        Object.defineProperty(exports2, "InlayHintResolveRequest", { enumerable: true, get: function() {
          return protocol_inlayHint_1.InlayHintResolveRequest;
        } });
        Object.defineProperty(exports2, "InlayHintRefreshRequest", { enumerable: true, get: function() {
          return protocol_inlayHint_1.InlayHintRefreshRequest;
        } });
        const protocol_diagnostic_1 = requireProtocol_diagnostic();
        Object.defineProperty(exports2, "DiagnosticServerCancellationData", { enumerable: true, get: function() {
          return protocol_diagnostic_1.DiagnosticServerCancellationData;
        } });
        Object.defineProperty(exports2, "DocumentDiagnosticReportKind", { enumerable: true, get: function() {
          return protocol_diagnostic_1.DocumentDiagnosticReportKind;
        } });
        Object.defineProperty(exports2, "DocumentDiagnosticRequest", { enumerable: true, get: function() {
          return protocol_diagnostic_1.DocumentDiagnosticRequest;
        } });
        Object.defineProperty(exports2, "WorkspaceDiagnosticRequest", { enumerable: true, get: function() {
          return protocol_diagnostic_1.WorkspaceDiagnosticRequest;
        } });
        Object.defineProperty(exports2, "DiagnosticRefreshRequest", { enumerable: true, get: function() {
          return protocol_diagnostic_1.DiagnosticRefreshRequest;
        } });
        const protocol_notebook_1 = requireProtocol_notebook();
        Object.defineProperty(exports2, "NotebookCellKind", { enumerable: true, get: function() {
          return protocol_notebook_1.NotebookCellKind;
        } });
        Object.defineProperty(exports2, "ExecutionSummary", { enumerable: true, get: function() {
          return protocol_notebook_1.ExecutionSummary;
        } });
        Object.defineProperty(exports2, "NotebookCell", { enumerable: true, get: function() {
          return protocol_notebook_1.NotebookCell;
        } });
        Object.defineProperty(exports2, "NotebookDocument", { enumerable: true, get: function() {
          return protocol_notebook_1.NotebookDocument;
        } });
        Object.defineProperty(exports2, "NotebookDocumentSyncRegistrationType", { enumerable: true, get: function() {
          return protocol_notebook_1.NotebookDocumentSyncRegistrationType;
        } });
        Object.defineProperty(exports2, "DidOpenNotebookDocumentNotification", { enumerable: true, get: function() {
          return protocol_notebook_1.DidOpenNotebookDocumentNotification;
        } });
        Object.defineProperty(exports2, "NotebookCellArrayChange", { enumerable: true, get: function() {
          return protocol_notebook_1.NotebookCellArrayChange;
        } });
        Object.defineProperty(exports2, "DidChangeNotebookDocumentNotification", { enumerable: true, get: function() {
          return protocol_notebook_1.DidChangeNotebookDocumentNotification;
        } });
        Object.defineProperty(exports2, "DidSaveNotebookDocumentNotification", { enumerable: true, get: function() {
          return protocol_notebook_1.DidSaveNotebookDocumentNotification;
        } });
        Object.defineProperty(exports2, "DidCloseNotebookDocumentNotification", { enumerable: true, get: function() {
          return protocol_notebook_1.DidCloseNotebookDocumentNotification;
        } });
        const protocol_inlineCompletion_1 = requireProtocol_inlineCompletion();
        Object.defineProperty(exports2, "InlineCompletionRequest", { enumerable: true, get: function() {
          return protocol_inlineCompletion_1.InlineCompletionRequest;
        } });
        var TextDocumentFilter;
        (function(TextDocumentFilter2) {
          function is2(value) {
            const candidate = value;
            return Is2.string(candidate) || (Is2.string(candidate.language) || Is2.string(candidate.scheme) || Is2.string(candidate.pattern));
          }
          TextDocumentFilter2.is = is2;
        })(TextDocumentFilter || (exports2.TextDocumentFilter = TextDocumentFilter = {}));
        var NotebookDocumentFilter;
        (function(NotebookDocumentFilter2) {
          function is2(value) {
            const candidate = value;
            return Is2.objectLiteral(candidate) && (Is2.string(candidate.notebookType) || Is2.string(candidate.scheme) || Is2.string(candidate.pattern));
          }
          NotebookDocumentFilter2.is = is2;
        })(NotebookDocumentFilter || (exports2.NotebookDocumentFilter = NotebookDocumentFilter = {}));
        var NotebookCellTextDocumentFilter;
        (function(NotebookCellTextDocumentFilter2) {
          function is2(value) {
            const candidate = value;
            return Is2.objectLiteral(candidate) && (Is2.string(candidate.notebook) || NotebookDocumentFilter.is(candidate.notebook)) && (candidate.language === void 0 || Is2.string(candidate.language));
          }
          NotebookCellTextDocumentFilter2.is = is2;
        })(NotebookCellTextDocumentFilter || (exports2.NotebookCellTextDocumentFilter = NotebookCellTextDocumentFilter = {}));
        var DocumentSelector;
        (function(DocumentSelector2) {
          function is2(value) {
            if (!Array.isArray(value)) {
              return false;
            }
            for (let elem of value) {
              if (!Is2.string(elem) && !TextDocumentFilter.is(elem) && !NotebookCellTextDocumentFilter.is(elem)) {
                return false;
              }
            }
            return true;
          }
          DocumentSelector2.is = is2;
        })(DocumentSelector || (exports2.DocumentSelector = DocumentSelector = {}));
        var RegistrationRequest;
        (function(RegistrationRequest2) {
          RegistrationRequest2.method = "client/registerCapability";
          RegistrationRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
          RegistrationRequest2.type = new messages_1.ProtocolRequestType(RegistrationRequest2.method);
        })(RegistrationRequest || (exports2.RegistrationRequest = RegistrationRequest = {}));
        var UnregistrationRequest;
        (function(UnregistrationRequest2) {
          UnregistrationRequest2.method = "client/unregisterCapability";
          UnregistrationRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
          UnregistrationRequest2.type = new messages_1.ProtocolRequestType(UnregistrationRequest2.method);
        })(UnregistrationRequest || (exports2.UnregistrationRequest = UnregistrationRequest = {}));
        var ResourceOperationKind;
        (function(ResourceOperationKind2) {
          ResourceOperationKind2.Create = "create";
          ResourceOperationKind2.Rename = "rename";
          ResourceOperationKind2.Delete = "delete";
        })(ResourceOperationKind || (exports2.ResourceOperationKind = ResourceOperationKind = {}));
        var FailureHandlingKind;
        (function(FailureHandlingKind2) {
          FailureHandlingKind2.Abort = "abort";
          FailureHandlingKind2.Transactional = "transactional";
          FailureHandlingKind2.TextOnlyTransactional = "textOnlyTransactional";
          FailureHandlingKind2.Undo = "undo";
        })(FailureHandlingKind || (exports2.FailureHandlingKind = FailureHandlingKind = {}));
        var PositionEncodingKind;
        (function(PositionEncodingKind2) {
          PositionEncodingKind2.UTF8 = "utf-8";
          PositionEncodingKind2.UTF16 = "utf-16";
          PositionEncodingKind2.UTF32 = "utf-32";
        })(PositionEncodingKind || (exports2.PositionEncodingKind = PositionEncodingKind = {}));
        var StaticRegistrationOptions;
        (function(StaticRegistrationOptions2) {
          function hasId(value) {
            const candidate = value;
            return candidate && Is2.string(candidate.id) && candidate.id.length > 0;
          }
          StaticRegistrationOptions2.hasId = hasId;
        })(StaticRegistrationOptions || (exports2.StaticRegistrationOptions = StaticRegistrationOptions = {}));
        var TextDocumentRegistrationOptions;
        (function(TextDocumentRegistrationOptions2) {
          function is2(value) {
            const candidate = value;
            return candidate && (candidate.documentSelector === null || DocumentSelector.is(candidate.documentSelector));
          }
          TextDocumentRegistrationOptions2.is = is2;
        })(TextDocumentRegistrationOptions || (exports2.TextDocumentRegistrationOptions = TextDocumentRegistrationOptions = {}));
        var WorkDoneProgressOptions;
        (function(WorkDoneProgressOptions2) {
          function is2(value) {
            const candidate = value;
            return Is2.objectLiteral(candidate) && (candidate.workDoneProgress === void 0 || Is2.boolean(candidate.workDoneProgress));
          }
          WorkDoneProgressOptions2.is = is2;
          function hasWorkDoneProgress(value) {
            const candidate = value;
            return candidate && Is2.boolean(candidate.workDoneProgress);
          }
          WorkDoneProgressOptions2.hasWorkDoneProgress = hasWorkDoneProgress;
        })(WorkDoneProgressOptions || (exports2.WorkDoneProgressOptions = WorkDoneProgressOptions = {}));
        var InitializeRequest;
        (function(InitializeRequest2) {
          InitializeRequest2.method = "initialize";
          InitializeRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          InitializeRequest2.type = new messages_1.ProtocolRequestType(InitializeRequest2.method);
        })(InitializeRequest || (exports2.InitializeRequest = InitializeRequest = {}));
        var InitializeErrorCodes;
        (function(InitializeErrorCodes2) {
          InitializeErrorCodes2.unknownProtocolVersion = 1;
        })(InitializeErrorCodes || (exports2.InitializeErrorCodes = InitializeErrorCodes = {}));
        var InitializedNotification;
        (function(InitializedNotification2) {
          InitializedNotification2.method = "initialized";
          InitializedNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
          InitializedNotification2.type = new messages_1.ProtocolNotificationType(InitializedNotification2.method);
        })(InitializedNotification || (exports2.InitializedNotification = InitializedNotification = {}));
        var ShutdownRequest;
        (function(ShutdownRequest2) {
          ShutdownRequest2.method = "shutdown";
          ShutdownRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          ShutdownRequest2.type = new messages_1.ProtocolRequestType0(ShutdownRequest2.method);
        })(ShutdownRequest || (exports2.ShutdownRequest = ShutdownRequest = {}));
        var ExitNotification;
        (function(ExitNotification2) {
          ExitNotification2.method = "exit";
          ExitNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
          ExitNotification2.type = new messages_1.ProtocolNotificationType0(ExitNotification2.method);
        })(ExitNotification || (exports2.ExitNotification = ExitNotification = {}));
        var DidChangeConfigurationNotification;
        (function(DidChangeConfigurationNotification2) {
          DidChangeConfigurationNotification2.method = "workspace/didChangeConfiguration";
          DidChangeConfigurationNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
          DidChangeConfigurationNotification2.type = new messages_1.ProtocolNotificationType(DidChangeConfigurationNotification2.method);
        })(DidChangeConfigurationNotification || (exports2.DidChangeConfigurationNotification = DidChangeConfigurationNotification = {}));
        var MessageType;
        (function(MessageType2) {
          MessageType2.Error = 1;
          MessageType2.Warning = 2;
          MessageType2.Info = 3;
          MessageType2.Log = 4;
          MessageType2.Debug = 5;
        })(MessageType || (exports2.MessageType = MessageType = {}));
        var ShowMessageNotification;
        (function(ShowMessageNotification2) {
          ShowMessageNotification2.method = "window/showMessage";
          ShowMessageNotification2.messageDirection = messages_1.MessageDirection.serverToClient;
          ShowMessageNotification2.type = new messages_1.ProtocolNotificationType(ShowMessageNotification2.method);
        })(ShowMessageNotification || (exports2.ShowMessageNotification = ShowMessageNotification = {}));
        var ShowMessageRequest;
        (function(ShowMessageRequest2) {
          ShowMessageRequest2.method = "window/showMessageRequest";
          ShowMessageRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
          ShowMessageRequest2.type = new messages_1.ProtocolRequestType(ShowMessageRequest2.method);
        })(ShowMessageRequest || (exports2.ShowMessageRequest = ShowMessageRequest = {}));
        var LogMessageNotification;
        (function(LogMessageNotification2) {
          LogMessageNotification2.method = "window/logMessage";
          LogMessageNotification2.messageDirection = messages_1.MessageDirection.serverToClient;
          LogMessageNotification2.type = new messages_1.ProtocolNotificationType(LogMessageNotification2.method);
        })(LogMessageNotification || (exports2.LogMessageNotification = LogMessageNotification = {}));
        var TelemetryEventNotification;
        (function(TelemetryEventNotification2) {
          TelemetryEventNotification2.method = "telemetry/event";
          TelemetryEventNotification2.messageDirection = messages_1.MessageDirection.serverToClient;
          TelemetryEventNotification2.type = new messages_1.ProtocolNotificationType(TelemetryEventNotification2.method);
        })(TelemetryEventNotification || (exports2.TelemetryEventNotification = TelemetryEventNotification = {}));
        var TextDocumentSyncKind;
        (function(TextDocumentSyncKind2) {
          TextDocumentSyncKind2.None = 0;
          TextDocumentSyncKind2.Full = 1;
          TextDocumentSyncKind2.Incremental = 2;
        })(TextDocumentSyncKind || (exports2.TextDocumentSyncKind = TextDocumentSyncKind = {}));
        var DidOpenTextDocumentNotification;
        (function(DidOpenTextDocumentNotification2) {
          DidOpenTextDocumentNotification2.method = "textDocument/didOpen";
          DidOpenTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
          DidOpenTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidOpenTextDocumentNotification2.method);
        })(DidOpenTextDocumentNotification || (exports2.DidOpenTextDocumentNotification = DidOpenTextDocumentNotification = {}));
        var TextDocumentContentChangeEvent;
        (function(TextDocumentContentChangeEvent2) {
          function isIncremental(event) {
            let candidate = event;
            return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range !== void 0 && (candidate.rangeLength === void 0 || typeof candidate.rangeLength === "number");
          }
          TextDocumentContentChangeEvent2.isIncremental = isIncremental;
          function isFull(event) {
            let candidate = event;
            return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range === void 0 && candidate.rangeLength === void 0;
          }
          TextDocumentContentChangeEvent2.isFull = isFull;
        })(TextDocumentContentChangeEvent || (exports2.TextDocumentContentChangeEvent = TextDocumentContentChangeEvent = {}));
        var DidChangeTextDocumentNotification;
        (function(DidChangeTextDocumentNotification2) {
          DidChangeTextDocumentNotification2.method = "textDocument/didChange";
          DidChangeTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
          DidChangeTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidChangeTextDocumentNotification2.method);
        })(DidChangeTextDocumentNotification || (exports2.DidChangeTextDocumentNotification = DidChangeTextDocumentNotification = {}));
        var DidCloseTextDocumentNotification;
        (function(DidCloseTextDocumentNotification2) {
          DidCloseTextDocumentNotification2.method = "textDocument/didClose";
          DidCloseTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
          DidCloseTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidCloseTextDocumentNotification2.method);
        })(DidCloseTextDocumentNotification || (exports2.DidCloseTextDocumentNotification = DidCloseTextDocumentNotification = {}));
        var DidSaveTextDocumentNotification;
        (function(DidSaveTextDocumentNotification2) {
          DidSaveTextDocumentNotification2.method = "textDocument/didSave";
          DidSaveTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
          DidSaveTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(DidSaveTextDocumentNotification2.method);
        })(DidSaveTextDocumentNotification || (exports2.DidSaveTextDocumentNotification = DidSaveTextDocumentNotification = {}));
        var TextDocumentSaveReason;
        (function(TextDocumentSaveReason2) {
          TextDocumentSaveReason2.Manual = 1;
          TextDocumentSaveReason2.AfterDelay = 2;
          TextDocumentSaveReason2.FocusOut = 3;
        })(TextDocumentSaveReason || (exports2.TextDocumentSaveReason = TextDocumentSaveReason = {}));
        var WillSaveTextDocumentNotification;
        (function(WillSaveTextDocumentNotification2) {
          WillSaveTextDocumentNotification2.method = "textDocument/willSave";
          WillSaveTextDocumentNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
          WillSaveTextDocumentNotification2.type = new messages_1.ProtocolNotificationType(WillSaveTextDocumentNotification2.method);
        })(WillSaveTextDocumentNotification || (exports2.WillSaveTextDocumentNotification = WillSaveTextDocumentNotification = {}));
        var WillSaveTextDocumentWaitUntilRequest;
        (function(WillSaveTextDocumentWaitUntilRequest2) {
          WillSaveTextDocumentWaitUntilRequest2.method = "textDocument/willSaveWaitUntil";
          WillSaveTextDocumentWaitUntilRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          WillSaveTextDocumentWaitUntilRequest2.type = new messages_1.ProtocolRequestType(WillSaveTextDocumentWaitUntilRequest2.method);
        })(WillSaveTextDocumentWaitUntilRequest || (exports2.WillSaveTextDocumentWaitUntilRequest = WillSaveTextDocumentWaitUntilRequest = {}));
        var DidChangeWatchedFilesNotification;
        (function(DidChangeWatchedFilesNotification2) {
          DidChangeWatchedFilesNotification2.method = "workspace/didChangeWatchedFiles";
          DidChangeWatchedFilesNotification2.messageDirection = messages_1.MessageDirection.clientToServer;
          DidChangeWatchedFilesNotification2.type = new messages_1.ProtocolNotificationType(DidChangeWatchedFilesNotification2.method);
        })(DidChangeWatchedFilesNotification || (exports2.DidChangeWatchedFilesNotification = DidChangeWatchedFilesNotification = {}));
        var FileChangeType;
        (function(FileChangeType2) {
          FileChangeType2.Created = 1;
          FileChangeType2.Changed = 2;
          FileChangeType2.Deleted = 3;
        })(FileChangeType || (exports2.FileChangeType = FileChangeType = {}));
        var RelativePattern;
        (function(RelativePattern2) {
          function is2(value) {
            const candidate = value;
            return Is2.objectLiteral(candidate) && (vscode_languageserver_types_1.URI.is(candidate.baseUri) || vscode_languageserver_types_1.WorkspaceFolder.is(candidate.baseUri)) && Is2.string(candidate.pattern);
          }
          RelativePattern2.is = is2;
        })(RelativePattern || (exports2.RelativePattern = RelativePattern = {}));
        var WatchKind;
        (function(WatchKind2) {
          WatchKind2.Create = 1;
          WatchKind2.Change = 2;
          WatchKind2.Delete = 4;
        })(WatchKind || (exports2.WatchKind = WatchKind = {}));
        var PublishDiagnosticsNotification;
        (function(PublishDiagnosticsNotification2) {
          PublishDiagnosticsNotification2.method = "textDocument/publishDiagnostics";
          PublishDiagnosticsNotification2.messageDirection = messages_1.MessageDirection.serverToClient;
          PublishDiagnosticsNotification2.type = new messages_1.ProtocolNotificationType(PublishDiagnosticsNotification2.method);
        })(PublishDiagnosticsNotification || (exports2.PublishDiagnosticsNotification = PublishDiagnosticsNotification = {}));
        var CompletionTriggerKind;
        (function(CompletionTriggerKind2) {
          CompletionTriggerKind2.Invoked = 1;
          CompletionTriggerKind2.TriggerCharacter = 2;
          CompletionTriggerKind2.TriggerForIncompleteCompletions = 3;
        })(CompletionTriggerKind || (exports2.CompletionTriggerKind = CompletionTriggerKind = {}));
        var CompletionRequest;
        (function(CompletionRequest2) {
          CompletionRequest2.method = "textDocument/completion";
          CompletionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          CompletionRequest2.type = new messages_1.ProtocolRequestType(CompletionRequest2.method);
        })(CompletionRequest || (exports2.CompletionRequest = CompletionRequest = {}));
        var CompletionResolveRequest;
        (function(CompletionResolveRequest2) {
          CompletionResolveRequest2.method = "completionItem/resolve";
          CompletionResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          CompletionResolveRequest2.type = new messages_1.ProtocolRequestType(CompletionResolveRequest2.method);
        })(CompletionResolveRequest || (exports2.CompletionResolveRequest = CompletionResolveRequest = {}));
        var HoverRequest;
        (function(HoverRequest2) {
          HoverRequest2.method = "textDocument/hover";
          HoverRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          HoverRequest2.type = new messages_1.ProtocolRequestType(HoverRequest2.method);
        })(HoverRequest || (exports2.HoverRequest = HoverRequest = {}));
        var SignatureHelpTriggerKind;
        (function(SignatureHelpTriggerKind2) {
          SignatureHelpTriggerKind2.Invoked = 1;
          SignatureHelpTriggerKind2.TriggerCharacter = 2;
          SignatureHelpTriggerKind2.ContentChange = 3;
        })(SignatureHelpTriggerKind || (exports2.SignatureHelpTriggerKind = SignatureHelpTriggerKind = {}));
        var SignatureHelpRequest;
        (function(SignatureHelpRequest2) {
          SignatureHelpRequest2.method = "textDocument/signatureHelp";
          SignatureHelpRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          SignatureHelpRequest2.type = new messages_1.ProtocolRequestType(SignatureHelpRequest2.method);
        })(SignatureHelpRequest || (exports2.SignatureHelpRequest = SignatureHelpRequest = {}));
        var DefinitionRequest;
        (function(DefinitionRequest2) {
          DefinitionRequest2.method = "textDocument/definition";
          DefinitionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          DefinitionRequest2.type = new messages_1.ProtocolRequestType(DefinitionRequest2.method);
        })(DefinitionRequest || (exports2.DefinitionRequest = DefinitionRequest = {}));
        var ReferencesRequest;
        (function(ReferencesRequest2) {
          ReferencesRequest2.method = "textDocument/references";
          ReferencesRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          ReferencesRequest2.type = new messages_1.ProtocolRequestType(ReferencesRequest2.method);
        })(ReferencesRequest || (exports2.ReferencesRequest = ReferencesRequest = {}));
        var DocumentHighlightRequest;
        (function(DocumentHighlightRequest2) {
          DocumentHighlightRequest2.method = "textDocument/documentHighlight";
          DocumentHighlightRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          DocumentHighlightRequest2.type = new messages_1.ProtocolRequestType(DocumentHighlightRequest2.method);
        })(DocumentHighlightRequest || (exports2.DocumentHighlightRequest = DocumentHighlightRequest = {}));
        var DocumentSymbolRequest;
        (function(DocumentSymbolRequest2) {
          DocumentSymbolRequest2.method = "textDocument/documentSymbol";
          DocumentSymbolRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          DocumentSymbolRequest2.type = new messages_1.ProtocolRequestType(DocumentSymbolRequest2.method);
        })(DocumentSymbolRequest || (exports2.DocumentSymbolRequest = DocumentSymbolRequest = {}));
        var CodeActionRequest;
        (function(CodeActionRequest2) {
          CodeActionRequest2.method = "textDocument/codeAction";
          CodeActionRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          CodeActionRequest2.type = new messages_1.ProtocolRequestType(CodeActionRequest2.method);
        })(CodeActionRequest || (exports2.CodeActionRequest = CodeActionRequest = {}));
        var CodeActionResolveRequest;
        (function(CodeActionResolveRequest2) {
          CodeActionResolveRequest2.method = "codeAction/resolve";
          CodeActionResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          CodeActionResolveRequest2.type = new messages_1.ProtocolRequestType(CodeActionResolveRequest2.method);
        })(CodeActionResolveRequest || (exports2.CodeActionResolveRequest = CodeActionResolveRequest = {}));
        var WorkspaceSymbolRequest;
        (function(WorkspaceSymbolRequest2) {
          WorkspaceSymbolRequest2.method = "workspace/symbol";
          WorkspaceSymbolRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          WorkspaceSymbolRequest2.type = new messages_1.ProtocolRequestType(WorkspaceSymbolRequest2.method);
        })(WorkspaceSymbolRequest || (exports2.WorkspaceSymbolRequest = WorkspaceSymbolRequest = {}));
        var WorkspaceSymbolResolveRequest;
        (function(WorkspaceSymbolResolveRequest2) {
          WorkspaceSymbolResolveRequest2.method = "workspaceSymbol/resolve";
          WorkspaceSymbolResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          WorkspaceSymbolResolveRequest2.type = new messages_1.ProtocolRequestType(WorkspaceSymbolResolveRequest2.method);
        })(WorkspaceSymbolResolveRequest || (exports2.WorkspaceSymbolResolveRequest = WorkspaceSymbolResolveRequest = {}));
        var CodeLensRequest;
        (function(CodeLensRequest2) {
          CodeLensRequest2.method = "textDocument/codeLens";
          CodeLensRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          CodeLensRequest2.type = new messages_1.ProtocolRequestType(CodeLensRequest2.method);
        })(CodeLensRequest || (exports2.CodeLensRequest = CodeLensRequest = {}));
        var CodeLensResolveRequest;
        (function(CodeLensResolveRequest2) {
          CodeLensResolveRequest2.method = "codeLens/resolve";
          CodeLensResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          CodeLensResolveRequest2.type = new messages_1.ProtocolRequestType(CodeLensResolveRequest2.method);
        })(CodeLensResolveRequest || (exports2.CodeLensResolveRequest = CodeLensResolveRequest = {}));
        var CodeLensRefreshRequest;
        (function(CodeLensRefreshRequest2) {
          CodeLensRefreshRequest2.method = `workspace/codeLens/refresh`;
          CodeLensRefreshRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
          CodeLensRefreshRequest2.type = new messages_1.ProtocolRequestType0(CodeLensRefreshRequest2.method);
        })(CodeLensRefreshRequest || (exports2.CodeLensRefreshRequest = CodeLensRefreshRequest = {}));
        var DocumentLinkRequest;
        (function(DocumentLinkRequest2) {
          DocumentLinkRequest2.method = "textDocument/documentLink";
          DocumentLinkRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          DocumentLinkRequest2.type = new messages_1.ProtocolRequestType(DocumentLinkRequest2.method);
        })(DocumentLinkRequest || (exports2.DocumentLinkRequest = DocumentLinkRequest = {}));
        var DocumentLinkResolveRequest;
        (function(DocumentLinkResolveRequest2) {
          DocumentLinkResolveRequest2.method = "documentLink/resolve";
          DocumentLinkResolveRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          DocumentLinkResolveRequest2.type = new messages_1.ProtocolRequestType(DocumentLinkResolveRequest2.method);
        })(DocumentLinkResolveRequest || (exports2.DocumentLinkResolveRequest = DocumentLinkResolveRequest = {}));
        var DocumentFormattingRequest;
        (function(DocumentFormattingRequest2) {
          DocumentFormattingRequest2.method = "textDocument/formatting";
          DocumentFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          DocumentFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentFormattingRequest2.method);
        })(DocumentFormattingRequest || (exports2.DocumentFormattingRequest = DocumentFormattingRequest = {}));
        var DocumentRangeFormattingRequest;
        (function(DocumentRangeFormattingRequest2) {
          DocumentRangeFormattingRequest2.method = "textDocument/rangeFormatting";
          DocumentRangeFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          DocumentRangeFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentRangeFormattingRequest2.method);
        })(DocumentRangeFormattingRequest || (exports2.DocumentRangeFormattingRequest = DocumentRangeFormattingRequest = {}));
        var DocumentRangesFormattingRequest;
        (function(DocumentRangesFormattingRequest2) {
          DocumentRangesFormattingRequest2.method = "textDocument/rangesFormatting";
          DocumentRangesFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          DocumentRangesFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentRangesFormattingRequest2.method);
        })(DocumentRangesFormattingRequest || (exports2.DocumentRangesFormattingRequest = DocumentRangesFormattingRequest = {}));
        var DocumentOnTypeFormattingRequest;
        (function(DocumentOnTypeFormattingRequest2) {
          DocumentOnTypeFormattingRequest2.method = "textDocument/onTypeFormatting";
          DocumentOnTypeFormattingRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          DocumentOnTypeFormattingRequest2.type = new messages_1.ProtocolRequestType(DocumentOnTypeFormattingRequest2.method);
        })(DocumentOnTypeFormattingRequest || (exports2.DocumentOnTypeFormattingRequest = DocumentOnTypeFormattingRequest = {}));
        var PrepareSupportDefaultBehavior;
        (function(PrepareSupportDefaultBehavior2) {
          PrepareSupportDefaultBehavior2.Identifier = 1;
        })(PrepareSupportDefaultBehavior || (exports2.PrepareSupportDefaultBehavior = PrepareSupportDefaultBehavior = {}));
        var RenameRequest;
        (function(RenameRequest2) {
          RenameRequest2.method = "textDocument/rename";
          RenameRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          RenameRequest2.type = new messages_1.ProtocolRequestType(RenameRequest2.method);
        })(RenameRequest || (exports2.RenameRequest = RenameRequest = {}));
        var PrepareRenameRequest;
        (function(PrepareRenameRequest2) {
          PrepareRenameRequest2.method = "textDocument/prepareRename";
          PrepareRenameRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          PrepareRenameRequest2.type = new messages_1.ProtocolRequestType(PrepareRenameRequest2.method);
        })(PrepareRenameRequest || (exports2.PrepareRenameRequest = PrepareRenameRequest = {}));
        var ExecuteCommandRequest;
        (function(ExecuteCommandRequest2) {
          ExecuteCommandRequest2.method = "workspace/executeCommand";
          ExecuteCommandRequest2.messageDirection = messages_1.MessageDirection.clientToServer;
          ExecuteCommandRequest2.type = new messages_1.ProtocolRequestType(ExecuteCommandRequest2.method);
        })(ExecuteCommandRequest || (exports2.ExecuteCommandRequest = ExecuteCommandRequest = {}));
        var ApplyWorkspaceEditRequest;
        (function(ApplyWorkspaceEditRequest2) {
          ApplyWorkspaceEditRequest2.method = "workspace/applyEdit";
          ApplyWorkspaceEditRequest2.messageDirection = messages_1.MessageDirection.serverToClient;
          ApplyWorkspaceEditRequest2.type = new messages_1.ProtocolRequestType("workspace/applyEdit");
        })(ApplyWorkspaceEditRequest || (exports2.ApplyWorkspaceEditRequest = ApplyWorkspaceEditRequest = {}));
      })(protocol);
      return protocol;
    }
    var connection$1 = {};
    var hasRequiredConnection;
    function requireConnection() {
      if (hasRequiredConnection) return connection$1;
      hasRequiredConnection = 1;
      Object.defineProperty(connection$1, "__esModule", { value: true });
      connection$1.createProtocolConnection = void 0;
      const vscode_jsonrpc_1 = requireMain$3();
      function createProtocolConnection(input, output, logger, options) {
        if (vscode_jsonrpc_1.ConnectionStrategy.is(options)) {
          options = { connectionStrategy: options };
        }
        return (0, vscode_jsonrpc_1.createMessageConnection)(input, output, logger, options);
      }
      connection$1.createProtocolConnection = createProtocolConnection;
      return connection$1;
    }
    var hasRequiredApi$1;
    function requireApi$1() {
      if (hasRequiredApi$1) return api$1;
      hasRequiredApi$1 = 1;
      (function(exports2) {
        var __createBinding = api$1 && api$1.__createBinding || (Object.create ? (function(o, m, k, k2) {
          if (k2 === void 0) k2 = k;
          var desc = Object.getOwnPropertyDescriptor(m, k);
          if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function() {
              return m[k];
            } };
          }
          Object.defineProperty(o, k2, desc);
        }) : (function(o, m, k, k2) {
          if (k2 === void 0) k2 = k;
          o[k2] = m[k];
        }));
        var __exportStar = api$1 && api$1.__exportStar || function(m, exports3) {
          for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
        };
        Object.defineProperty(exports2, "__esModule", { value: true });
        exports2.LSPErrorCodes = exports2.createProtocolConnection = void 0;
        __exportStar(requireMain$3(), exports2);
        __exportStar(requireMain$2(), exports2);
        __exportStar(requireMessages(), exports2);
        __exportStar(requireProtocol(), exports2);
        var connection_1 = requireConnection();
        Object.defineProperty(exports2, "createProtocolConnection", { enumerable: true, get: function() {
          return connection_1.createProtocolConnection;
        } });
        var LSPErrorCodes;
        (function(LSPErrorCodes2) {
          LSPErrorCodes2.lspReservedErrorRangeStart = -32899;
          LSPErrorCodes2.RequestFailed = -32803;
          LSPErrorCodes2.ServerCancelled = -32802;
          LSPErrorCodes2.ContentModified = -32801;
          LSPErrorCodes2.RequestCancelled = -32800;
          LSPErrorCodes2.lspReservedErrorRangeEnd = -32800;
        })(LSPErrorCodes || (exports2.LSPErrorCodes = LSPErrorCodes = {}));
      })(api$1);
      return api$1;
    }
    var hasRequiredMain$1;
    function requireMain$1() {
      if (hasRequiredMain$1) return main$2;
      hasRequiredMain$1 = 1;
      (function(exports2) {
        var __createBinding = main$2 && main$2.__createBinding || (Object.create ? (function(o, m, k, k2) {
          if (k2 === void 0) k2 = k;
          var desc = Object.getOwnPropertyDescriptor(m, k);
          if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function() {
              return m[k];
            } };
          }
          Object.defineProperty(o, k2, desc);
        }) : (function(o, m, k, k2) {
          if (k2 === void 0) k2 = k;
          o[k2] = m[k];
        }));
        var __exportStar = main$2 && main$2.__exportStar || function(m, exports3) {
          for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
        };
        Object.defineProperty(exports2, "__esModule", { value: true });
        exports2.createProtocolConnection = void 0;
        const node_1 = requireNode$2();
        __exportStar(requireNode$2(), exports2);
        __exportStar(requireApi$1(), exports2);
        function createProtocolConnection(input, output, logger, options) {
          return (0, node_1.createMessageConnection)(input, output, logger, options);
        }
        exports2.createProtocolConnection = createProtocolConnection;
      })(main$2);
      return main$2;
    }
    var uuid = {};
    var hasRequiredUuid;
    function requireUuid() {
      if (hasRequiredUuid) return uuid;
      hasRequiredUuid = 1;
      Object.defineProperty(uuid, "__esModule", { value: true });
      uuid.generateUuid = uuid.parse = uuid.isUUID = uuid.v4 = uuid.empty = void 0;
      class ValueUUID {
        constructor(_value) {
          this._value = _value;
        }
        asHex() {
          return this._value;
        }
        equals(other) {
          return this.asHex() === other.asHex();
        }
      }
      class V4UUID extends ValueUUID {
        static _oneOf(array) {
          return array[Math.floor(array.length * Math.random())];
        }
        static _randomHex() {
          return V4UUID._oneOf(V4UUID._chars);
        }
        constructor() {
          super([
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            "-",
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            "-",
            "4",
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            "-",
            V4UUID._oneOf(V4UUID._timeHighBits),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            "-",
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex(),
            V4UUID._randomHex()
          ].join(""));
        }
      }
      V4UUID._chars = ["0", "1", "2", "3", "4", "5", "6", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"];
      V4UUID._timeHighBits = ["8", "9", "a", "b"];
      uuid.empty = new ValueUUID("00000000-0000-0000-0000-000000000000");
      function v4() {
        return new V4UUID();
      }
      uuid.v4 = v4;
      const _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
      function isUUID(value) {
        return _UUIDPattern.test(value);
      }
      uuid.isUUID = isUUID;
      function parse(value) {
        if (!isUUID(value)) {
          throw new Error("invalid uuid");
        }
        return new ValueUUID(value);
      }
      uuid.parse = parse;
      function generateUuid() {
        return v4().asHex();
      }
      uuid.generateUuid = generateUuid;
      return uuid;
    }
    var progress = {};
    var hasRequiredProgress;
    function requireProgress() {
      if (hasRequiredProgress) return progress;
      hasRequiredProgress = 1;
      Object.defineProperty(progress, "__esModule", { value: true });
      progress.attachPartialResult = progress.ProgressFeature = progress.attachWorkDone = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const uuid_1 = requireUuid();
      class WorkDoneProgressReporterImpl {
        constructor(_connection, _token) {
          this._connection = _connection;
          this._token = _token;
          WorkDoneProgressReporterImpl.Instances.set(this._token, this);
        }
        begin(title, percentage, message, cancellable) {
          let param = {
            kind: "begin",
            title,
            percentage,
            message,
            cancellable
          };
          this._connection.sendProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, param);
        }
        report(arg0, arg1) {
          let param = {
            kind: "report"
          };
          if (typeof arg0 === "number") {
            param.percentage = arg0;
            if (arg1 !== void 0) {
              param.message = arg1;
            }
          } else {
            param.message = arg0;
          }
          this._connection.sendProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, param);
        }
        done() {
          WorkDoneProgressReporterImpl.Instances.delete(this._token);
          this._connection.sendProgress(vscode_languageserver_protocol_1.WorkDoneProgress.type, this._token, { kind: "end" });
        }
      }
      WorkDoneProgressReporterImpl.Instances = /* @__PURE__ */ new Map();
      class WorkDoneProgressServerReporterImpl extends WorkDoneProgressReporterImpl {
        constructor(connection2, token) {
          super(connection2, token);
          this._source = new vscode_languageserver_protocol_1.CancellationTokenSource();
        }
        get token() {
          return this._source.token;
        }
        done() {
          this._source.dispose();
          super.done();
        }
        cancel() {
          this._source.cancel();
        }
      }
      class NullProgressReporter {
        constructor() {
        }
        begin() {
        }
        report() {
        }
        done() {
        }
      }
      class NullProgressServerReporter extends NullProgressReporter {
        constructor() {
          super();
          this._source = new vscode_languageserver_protocol_1.CancellationTokenSource();
        }
        get token() {
          return this._source.token;
        }
        done() {
          this._source.dispose();
        }
        cancel() {
          this._source.cancel();
        }
      }
      function attachWorkDone(connection2, params) {
        if (params === void 0 || params.workDoneToken === void 0) {
          return new NullProgressReporter();
        }
        const token = params.workDoneToken;
        delete params.workDoneToken;
        return new WorkDoneProgressReporterImpl(connection2, token);
      }
      progress.attachWorkDone = attachWorkDone;
      const ProgressFeature = (Base) => {
        return class extends Base {
          constructor() {
            super();
            this._progressSupported = false;
          }
          initialize(capabilities) {
            super.initialize(capabilities);
            if (capabilities?.window?.workDoneProgress === true) {
              this._progressSupported = true;
              this.connection.onNotification(vscode_languageserver_protocol_1.WorkDoneProgressCancelNotification.type, (params) => {
                let progress2 = WorkDoneProgressReporterImpl.Instances.get(params.token);
                if (progress2 instanceof WorkDoneProgressServerReporterImpl || progress2 instanceof NullProgressServerReporter) {
                  progress2.cancel();
                }
              });
            }
          }
          attachWorkDoneProgress(token) {
            if (token === void 0) {
              return new NullProgressReporter();
            } else {
              return new WorkDoneProgressReporterImpl(this.connection, token);
            }
          }
          createWorkDoneProgress() {
            if (this._progressSupported) {
              const token = (0, uuid_1.generateUuid)();
              return this.connection.sendRequest(vscode_languageserver_protocol_1.WorkDoneProgressCreateRequest.type, { token }).then(() => {
                const result = new WorkDoneProgressServerReporterImpl(this.connection, token);
                return result;
              });
            } else {
              return Promise.resolve(new NullProgressServerReporter());
            }
          }
        };
      };
      progress.ProgressFeature = ProgressFeature;
      var ResultProgress;
      (function(ResultProgress2) {
        ResultProgress2.type = new vscode_languageserver_protocol_1.ProgressType();
      })(ResultProgress || (ResultProgress = {}));
      class ResultProgressReporterImpl {
        constructor(_connection, _token) {
          this._connection = _connection;
          this._token = _token;
        }
        report(data) {
          this._connection.sendProgress(ResultProgress.type, this._token, data);
        }
      }
      function attachPartialResult(connection2, params) {
        if (params === void 0 || params.partialResultToken === void 0) {
          return void 0;
        }
        const token = params.partialResultToken;
        delete params.partialResultToken;
        return new ResultProgressReporterImpl(connection2, token);
      }
      progress.attachPartialResult = attachPartialResult;
      return progress;
    }
    var configuration = {};
    var hasRequiredConfiguration;
    function requireConfiguration() {
      if (hasRequiredConfiguration) return configuration;
      hasRequiredConfiguration = 1;
      Object.defineProperty(configuration, "__esModule", { value: true });
      configuration.ConfigurationFeature = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const Is2 = requireIs$3();
      const ConfigurationFeature = (Base) => {
        return class extends Base {
          getConfiguration(arg) {
            if (!arg) {
              return this._getConfiguration({});
            } else if (Is2.string(arg)) {
              return this._getConfiguration({ section: arg });
            } else {
              return this._getConfiguration(arg);
            }
          }
          _getConfiguration(arg) {
            let params = {
              items: Array.isArray(arg) ? arg : [arg]
            };
            return this.connection.sendRequest(vscode_languageserver_protocol_1.ConfigurationRequest.type, params).then((result) => {
              if (Array.isArray(result)) {
                return Array.isArray(arg) ? result : result[0];
              } else {
                return Array.isArray(arg) ? [] : null;
              }
            });
          }
        };
      };
      configuration.ConfigurationFeature = ConfigurationFeature;
      return configuration;
    }
    var workspaceFolder = {};
    var hasRequiredWorkspaceFolder;
    function requireWorkspaceFolder() {
      if (hasRequiredWorkspaceFolder) return workspaceFolder;
      hasRequiredWorkspaceFolder = 1;
      Object.defineProperty(workspaceFolder, "__esModule", { value: true });
      workspaceFolder.WorkspaceFoldersFeature = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const WorkspaceFoldersFeature = (Base) => {
        return class extends Base {
          constructor() {
            super();
            this._notificationIsAutoRegistered = false;
          }
          initialize(capabilities) {
            super.initialize(capabilities);
            let workspaceCapabilities = capabilities.workspace;
            if (workspaceCapabilities && workspaceCapabilities.workspaceFolders) {
              this._onDidChangeWorkspaceFolders = new vscode_languageserver_protocol_1.Emitter();
              this.connection.onNotification(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type, (params) => {
                this._onDidChangeWorkspaceFolders.fire(params.event);
              });
            }
          }
          fillServerCapabilities(capabilities) {
            super.fillServerCapabilities(capabilities);
            const changeNotifications = capabilities.workspace?.workspaceFolders?.changeNotifications;
            this._notificationIsAutoRegistered = changeNotifications === true || typeof changeNotifications === "string";
          }
          getWorkspaceFolders() {
            return this.connection.sendRequest(vscode_languageserver_protocol_1.WorkspaceFoldersRequest.type);
          }
          get onDidChangeWorkspaceFolders() {
            if (!this._onDidChangeWorkspaceFolders) {
              throw new Error("Client doesn't support sending workspace folder change events.");
            }
            if (!this._notificationIsAutoRegistered && !this._unregistration) {
              this._unregistration = this.connection.client.register(vscode_languageserver_protocol_1.DidChangeWorkspaceFoldersNotification.type);
            }
            return this._onDidChangeWorkspaceFolders.event;
          }
        };
      };
      workspaceFolder.WorkspaceFoldersFeature = WorkspaceFoldersFeature;
      return workspaceFolder;
    }
    var callHierarchy = {};
    var hasRequiredCallHierarchy;
    function requireCallHierarchy() {
      if (hasRequiredCallHierarchy) return callHierarchy;
      hasRequiredCallHierarchy = 1;
      Object.defineProperty(callHierarchy, "__esModule", { value: true });
      callHierarchy.CallHierarchyFeature = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const CallHierarchyFeature = (Base) => {
        return class extends Base {
          get callHierarchy() {
            return {
              onPrepare: (handler) => {
                return this.connection.onRequest(vscode_languageserver_protocol_1.CallHierarchyPrepareRequest.type, (params, cancel) => {
                  return handler(params, cancel, this.attachWorkDoneProgress(params), void 0);
                });
              },
              onIncomingCalls: (handler) => {
                const type = vscode_languageserver_protocol_1.CallHierarchyIncomingCallsRequest.type;
                return this.connection.onRequest(type, (params, cancel) => {
                  return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                });
              },
              onOutgoingCalls: (handler) => {
                const type = vscode_languageserver_protocol_1.CallHierarchyOutgoingCallsRequest.type;
                return this.connection.onRequest(type, (params, cancel) => {
                  return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                });
              }
            };
          }
        };
      };
      callHierarchy.CallHierarchyFeature = CallHierarchyFeature;
      return callHierarchy;
    }
    var semanticTokens = {};
    var hasRequiredSemanticTokens;
    function requireSemanticTokens() {
      if (hasRequiredSemanticTokens) return semanticTokens;
      hasRequiredSemanticTokens = 1;
      Object.defineProperty(semanticTokens, "__esModule", { value: true });
      semanticTokens.SemanticTokensBuilder = semanticTokens.SemanticTokensDiff = semanticTokens.SemanticTokensFeature = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const SemanticTokensFeature = (Base) => {
        return class extends Base {
          get semanticTokens() {
            return {
              refresh: () => {
                return this.connection.sendRequest(vscode_languageserver_protocol_1.SemanticTokensRefreshRequest.type);
              },
              on: (handler) => {
                const type = vscode_languageserver_protocol_1.SemanticTokensRequest.type;
                return this.connection.onRequest(type, (params, cancel) => {
                  return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                });
              },
              onDelta: (handler) => {
                const type = vscode_languageserver_protocol_1.SemanticTokensDeltaRequest.type;
                return this.connection.onRequest(type, (params, cancel) => {
                  return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                });
              },
              onRange: (handler) => {
                const type = vscode_languageserver_protocol_1.SemanticTokensRangeRequest.type;
                return this.connection.onRequest(type, (params, cancel) => {
                  return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                });
              }
            };
          }
        };
      };
      semanticTokens.SemanticTokensFeature = SemanticTokensFeature;
      class SemanticTokensDiff {
        constructor(originalSequence, modifiedSequence) {
          this.originalSequence = originalSequence;
          this.modifiedSequence = modifiedSequence;
        }
        computeDiff() {
          const originalLength = this.originalSequence.length;
          const modifiedLength = this.modifiedSequence.length;
          let startIndex = 0;
          while (startIndex < modifiedLength && startIndex < originalLength && this.originalSequence[startIndex] === this.modifiedSequence[startIndex]) {
            startIndex++;
          }
          if (startIndex < modifiedLength && startIndex < originalLength) {
            let originalEndIndex = originalLength - 1;
            let modifiedEndIndex = modifiedLength - 1;
            while (originalEndIndex >= startIndex && modifiedEndIndex >= startIndex && this.originalSequence[originalEndIndex] === this.modifiedSequence[modifiedEndIndex]) {
              originalEndIndex--;
              modifiedEndIndex--;
            }
            if (originalEndIndex < startIndex || modifiedEndIndex < startIndex) {
              originalEndIndex++;
              modifiedEndIndex++;
            }
            const deleteCount = originalEndIndex - startIndex + 1;
            const newData = this.modifiedSequence.slice(startIndex, modifiedEndIndex + 1);
            if (newData.length === 1 && newData[0] === this.originalSequence[originalEndIndex]) {
              return [
                { start: startIndex, deleteCount: deleteCount - 1 }
              ];
            } else {
              return [
                { start: startIndex, deleteCount, data: newData }
              ];
            }
          } else if (startIndex < modifiedLength) {
            return [
              { start: startIndex, deleteCount: 0, data: this.modifiedSequence.slice(startIndex) }
            ];
          } else if (startIndex < originalLength) {
            return [
              { start: startIndex, deleteCount: originalLength - startIndex }
            ];
          } else {
            return [];
          }
        }
      }
      semanticTokens.SemanticTokensDiff = SemanticTokensDiff;
      class SemanticTokensBuilder {
        constructor() {
          this._prevData = void 0;
          this.initialize();
        }
        initialize() {
          this._id = Date.now();
          this._prevLine = 0;
          this._prevChar = 0;
          this._data = [];
          this._dataLen = 0;
        }
        push(line, char, length, tokenType, tokenModifiers) {
          let pushLine = line;
          let pushChar = char;
          if (this._dataLen > 0) {
            pushLine -= this._prevLine;
            if (pushLine === 0) {
              pushChar -= this._prevChar;
            }
          }
          this._data[this._dataLen++] = pushLine;
          this._data[this._dataLen++] = pushChar;
          this._data[this._dataLen++] = length;
          this._data[this._dataLen++] = tokenType;
          this._data[this._dataLen++] = tokenModifiers;
          this._prevLine = line;
          this._prevChar = char;
        }
        get id() {
          return this._id.toString();
        }
        previousResult(id) {
          if (this.id === id) {
            this._prevData = this._data;
          }
          this.initialize();
        }
        build() {
          this._prevData = void 0;
          return {
            resultId: this.id,
            data: this._data
          };
        }
        canBuildEdits() {
          return this._prevData !== void 0;
        }
        buildEdits() {
          if (this._prevData !== void 0) {
            return {
              resultId: this.id,
              edits: new SemanticTokensDiff(this._prevData, this._data).computeDiff()
            };
          } else {
            return this.build();
          }
        }
      }
      semanticTokens.SemanticTokensBuilder = SemanticTokensBuilder;
      return semanticTokens;
    }
    var showDocument = {};
    var hasRequiredShowDocument;
    function requireShowDocument() {
      if (hasRequiredShowDocument) return showDocument;
      hasRequiredShowDocument = 1;
      Object.defineProperty(showDocument, "__esModule", { value: true });
      showDocument.ShowDocumentFeature = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const ShowDocumentFeature = (Base) => {
        return class extends Base {
          showDocument(params) {
            return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowDocumentRequest.type, params);
          }
        };
      };
      showDocument.ShowDocumentFeature = ShowDocumentFeature;
      return showDocument;
    }
    var fileOperations = {};
    var hasRequiredFileOperations;
    function requireFileOperations() {
      if (hasRequiredFileOperations) return fileOperations;
      hasRequiredFileOperations = 1;
      Object.defineProperty(fileOperations, "__esModule", { value: true });
      fileOperations.FileOperationsFeature = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const FileOperationsFeature = (Base) => {
        return class extends Base {
          onDidCreateFiles(handler) {
            return this.connection.onNotification(vscode_languageserver_protocol_1.DidCreateFilesNotification.type, (params) => {
              handler(params);
            });
          }
          onDidRenameFiles(handler) {
            return this.connection.onNotification(vscode_languageserver_protocol_1.DidRenameFilesNotification.type, (params) => {
              handler(params);
            });
          }
          onDidDeleteFiles(handler) {
            return this.connection.onNotification(vscode_languageserver_protocol_1.DidDeleteFilesNotification.type, (params) => {
              handler(params);
            });
          }
          onWillCreateFiles(handler) {
            return this.connection.onRequest(vscode_languageserver_protocol_1.WillCreateFilesRequest.type, (params, cancel) => {
              return handler(params, cancel);
            });
          }
          onWillRenameFiles(handler) {
            return this.connection.onRequest(vscode_languageserver_protocol_1.WillRenameFilesRequest.type, (params, cancel) => {
              return handler(params, cancel);
            });
          }
          onWillDeleteFiles(handler) {
            return this.connection.onRequest(vscode_languageserver_protocol_1.WillDeleteFilesRequest.type, (params, cancel) => {
              return handler(params, cancel);
            });
          }
        };
      };
      fileOperations.FileOperationsFeature = FileOperationsFeature;
      return fileOperations;
    }
    var linkedEditingRange = {};
    var hasRequiredLinkedEditingRange;
    function requireLinkedEditingRange() {
      if (hasRequiredLinkedEditingRange) return linkedEditingRange;
      hasRequiredLinkedEditingRange = 1;
      Object.defineProperty(linkedEditingRange, "__esModule", { value: true });
      linkedEditingRange.LinkedEditingRangeFeature = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const LinkedEditingRangeFeature = (Base) => {
        return class extends Base {
          onLinkedEditingRange(handler) {
            return this.connection.onRequest(vscode_languageserver_protocol_1.LinkedEditingRangeRequest.type, (params, cancel) => {
              return handler(params, cancel, this.attachWorkDoneProgress(params), void 0);
            });
          }
        };
      };
      linkedEditingRange.LinkedEditingRangeFeature = LinkedEditingRangeFeature;
      return linkedEditingRange;
    }
    var typeHierarchy = {};
    var hasRequiredTypeHierarchy;
    function requireTypeHierarchy() {
      if (hasRequiredTypeHierarchy) return typeHierarchy;
      hasRequiredTypeHierarchy = 1;
      Object.defineProperty(typeHierarchy, "__esModule", { value: true });
      typeHierarchy.TypeHierarchyFeature = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const TypeHierarchyFeature = (Base) => {
        return class extends Base {
          get typeHierarchy() {
            return {
              onPrepare: (handler) => {
                return this.connection.onRequest(vscode_languageserver_protocol_1.TypeHierarchyPrepareRequest.type, (params, cancel) => {
                  return handler(params, cancel, this.attachWorkDoneProgress(params), void 0);
                });
              },
              onSupertypes: (handler) => {
                const type = vscode_languageserver_protocol_1.TypeHierarchySupertypesRequest.type;
                return this.connection.onRequest(type, (params, cancel) => {
                  return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                });
              },
              onSubtypes: (handler) => {
                const type = vscode_languageserver_protocol_1.TypeHierarchySubtypesRequest.type;
                return this.connection.onRequest(type, (params, cancel) => {
                  return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                });
              }
            };
          }
        };
      };
      typeHierarchy.TypeHierarchyFeature = TypeHierarchyFeature;
      return typeHierarchy;
    }
    var inlineValue = {};
    var hasRequiredInlineValue;
    function requireInlineValue() {
      if (hasRequiredInlineValue) return inlineValue;
      hasRequiredInlineValue = 1;
      Object.defineProperty(inlineValue, "__esModule", { value: true });
      inlineValue.InlineValueFeature = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const InlineValueFeature = (Base) => {
        return class extends Base {
          get inlineValue() {
            return {
              refresh: () => {
                return this.connection.sendRequest(vscode_languageserver_protocol_1.InlineValueRefreshRequest.type);
              },
              on: (handler) => {
                return this.connection.onRequest(vscode_languageserver_protocol_1.InlineValueRequest.type, (params, cancel) => {
                  return handler(params, cancel, this.attachWorkDoneProgress(params));
                });
              }
            };
          }
        };
      };
      inlineValue.InlineValueFeature = InlineValueFeature;
      return inlineValue;
    }
    var foldingRange = {};
    var hasRequiredFoldingRange;
    function requireFoldingRange() {
      if (hasRequiredFoldingRange) return foldingRange;
      hasRequiredFoldingRange = 1;
      Object.defineProperty(foldingRange, "__esModule", { value: true });
      foldingRange.FoldingRangeFeature = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const FoldingRangeFeature = (Base) => {
        return class extends Base {
          get foldingRange() {
            return {
              refresh: () => {
                return this.connection.sendRequest(vscode_languageserver_protocol_1.FoldingRangeRefreshRequest.type);
              },
              on: (handler) => {
                const type = vscode_languageserver_protocol_1.FoldingRangeRequest.type;
                return this.connection.onRequest(type, (params, cancel) => {
                  return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                });
              }
            };
          }
        };
      };
      foldingRange.FoldingRangeFeature = FoldingRangeFeature;
      return foldingRange;
    }
    var inlayHint = {};
    var hasRequiredInlayHint;
    function requireInlayHint() {
      if (hasRequiredInlayHint) return inlayHint;
      hasRequiredInlayHint = 1;
      Object.defineProperty(inlayHint, "__esModule", { value: true });
      inlayHint.InlayHintFeature = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const InlayHintFeature = (Base) => {
        return class extends Base {
          get inlayHint() {
            return {
              refresh: () => {
                return this.connection.sendRequest(vscode_languageserver_protocol_1.InlayHintRefreshRequest.type);
              },
              on: (handler) => {
                return this.connection.onRequest(vscode_languageserver_protocol_1.InlayHintRequest.type, (params, cancel) => {
                  return handler(params, cancel, this.attachWorkDoneProgress(params));
                });
              },
              resolve: (handler) => {
                return this.connection.onRequest(vscode_languageserver_protocol_1.InlayHintResolveRequest.type, (params, cancel) => {
                  return handler(params, cancel);
                });
              }
            };
          }
        };
      };
      inlayHint.InlayHintFeature = InlayHintFeature;
      return inlayHint;
    }
    var diagnostic = {};
    var hasRequiredDiagnostic;
    function requireDiagnostic() {
      if (hasRequiredDiagnostic) return diagnostic;
      hasRequiredDiagnostic = 1;
      Object.defineProperty(diagnostic, "__esModule", { value: true });
      diagnostic.DiagnosticFeature = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const DiagnosticFeature = (Base) => {
        return class extends Base {
          get diagnostics() {
            return {
              refresh: () => {
                return this.connection.sendRequest(vscode_languageserver_protocol_1.DiagnosticRefreshRequest.type);
              },
              on: (handler) => {
                return this.connection.onRequest(vscode_languageserver_protocol_1.DocumentDiagnosticRequest.type, (params, cancel) => {
                  return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(vscode_languageserver_protocol_1.DocumentDiagnosticRequest.partialResult, params));
                });
              },
              onWorkspace: (handler) => {
                return this.connection.onRequest(vscode_languageserver_protocol_1.WorkspaceDiagnosticRequest.type, (params, cancel) => {
                  return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(vscode_languageserver_protocol_1.WorkspaceDiagnosticRequest.partialResult, params));
                });
              }
            };
          }
        };
      };
      diagnostic.DiagnosticFeature = DiagnosticFeature;
      return diagnostic;
    }
    var notebook = {};
    var textDocuments = {};
    var hasRequiredTextDocuments;
    function requireTextDocuments() {
      if (hasRequiredTextDocuments) return textDocuments;
      hasRequiredTextDocuments = 1;
      Object.defineProperty(textDocuments, "__esModule", { value: true });
      textDocuments.TextDocuments = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      class TextDocuments {
        /**
         * Create a new text document manager.
         */
        constructor(configuration2) {
          this._configuration = configuration2;
          this._syncedDocuments = /* @__PURE__ */ new Map();
          this._onDidChangeContent = new vscode_languageserver_protocol_1.Emitter();
          this._onDidOpen = new vscode_languageserver_protocol_1.Emitter();
          this._onDidClose = new vscode_languageserver_protocol_1.Emitter();
          this._onDidSave = new vscode_languageserver_protocol_1.Emitter();
          this._onWillSave = new vscode_languageserver_protocol_1.Emitter();
        }
        /**
         * An event that fires when a text document managed by this manager
         * has been opened.
         */
        get onDidOpen() {
          return this._onDidOpen.event;
        }
        /**
         * An event that fires when a text document managed by this manager
         * has been opened or the content changes.
         */
        get onDidChangeContent() {
          return this._onDidChangeContent.event;
        }
        /**
         * An event that fires when a text document managed by this manager
         * will be saved.
         */
        get onWillSave() {
          return this._onWillSave.event;
        }
        /**
         * Sets a handler that will be called if a participant wants to provide
         * edits during a text document save.
         */
        onWillSaveWaitUntil(handler) {
          this._willSaveWaitUntil = handler;
        }
        /**
         * An event that fires when a text document managed by this manager
         * has been saved.
         */
        get onDidSave() {
          return this._onDidSave.event;
        }
        /**
         * An event that fires when a text document managed by this manager
         * has been closed.
         */
        get onDidClose() {
          return this._onDidClose.event;
        }
        /**
         * Returns the document for the given URI. Returns undefined if
         * the document is not managed by this instance.
         *
         * @param uri The text document's URI to retrieve.
         * @return the text document or `undefined`.
         */
        get(uri) {
          return this._syncedDocuments.get(uri);
        }
        /**
         * Returns all text documents managed by this instance.
         *
         * @return all text documents.
         */
        all() {
          return Array.from(this._syncedDocuments.values());
        }
        /**
         * Returns the URIs of all text documents managed by this instance.
         *
         * @return the URI's of all text documents.
         */
        keys() {
          return Array.from(this._syncedDocuments.keys());
        }
        /**
         * Listens for `low level` notification on the given connection to
         * update the text documents managed by this instance.
         *
         * Please note that the connection only provides handlers not an event model. Therefore
         * listening on a connection will overwrite the following handlers on a connection:
         * `onDidOpenTextDocument`, `onDidChangeTextDocument`, `onDidCloseTextDocument`,
         * `onWillSaveTextDocument`, `onWillSaveTextDocumentWaitUntil` and `onDidSaveTextDocument`.
         *
         * Use the corresponding events on the TextDocuments instance instead.
         *
         * @param connection The connection to listen on.
         */
        listen(connection2) {
          connection2.__textDocumentSync = vscode_languageserver_protocol_1.TextDocumentSyncKind.Incremental;
          const disposables = [];
          disposables.push(connection2.onDidOpenTextDocument((event) => {
            const td = event.textDocument;
            const document = this._configuration.create(td.uri, td.languageId, td.version, td.text);
            this._syncedDocuments.set(td.uri, document);
            const toFire = Object.freeze({ document });
            this._onDidOpen.fire(toFire);
            this._onDidChangeContent.fire(toFire);
          }));
          disposables.push(connection2.onDidChangeTextDocument((event) => {
            const td = event.textDocument;
            const changes = event.contentChanges;
            if (changes.length === 0) {
              return;
            }
            const { version } = td;
            if (version === null || version === void 0) {
              throw new Error(`Received document change event for ${td.uri} without valid version identifier`);
            }
            let syncedDocument = this._syncedDocuments.get(td.uri);
            if (syncedDocument !== void 0) {
              syncedDocument = this._configuration.update(syncedDocument, changes, version);
              this._syncedDocuments.set(td.uri, syncedDocument);
              this._onDidChangeContent.fire(Object.freeze({ document: syncedDocument }));
            }
          }));
          disposables.push(connection2.onDidCloseTextDocument((event) => {
            let syncedDocument = this._syncedDocuments.get(event.textDocument.uri);
            if (syncedDocument !== void 0) {
              this._syncedDocuments.delete(event.textDocument.uri);
              this._onDidClose.fire(Object.freeze({ document: syncedDocument }));
            }
          }));
          disposables.push(connection2.onWillSaveTextDocument((event) => {
            let syncedDocument = this._syncedDocuments.get(event.textDocument.uri);
            if (syncedDocument !== void 0) {
              this._onWillSave.fire(Object.freeze({ document: syncedDocument, reason: event.reason }));
            }
          }));
          disposables.push(connection2.onWillSaveTextDocumentWaitUntil((event, token) => {
            let syncedDocument = this._syncedDocuments.get(event.textDocument.uri);
            if (syncedDocument !== void 0 && this._willSaveWaitUntil) {
              return this._willSaveWaitUntil(Object.freeze({ document: syncedDocument, reason: event.reason }), token);
            } else {
              return [];
            }
          }));
          disposables.push(connection2.onDidSaveTextDocument((event) => {
            let syncedDocument = this._syncedDocuments.get(event.textDocument.uri);
            if (syncedDocument !== void 0) {
              this._onDidSave.fire(Object.freeze({ document: syncedDocument }));
            }
          }));
          return vscode_languageserver_protocol_1.Disposable.create(() => {
            disposables.forEach((disposable2) => disposable2.dispose());
          });
        }
      }
      textDocuments.TextDocuments = TextDocuments;
      return textDocuments;
    }
    var hasRequiredNotebook;
    function requireNotebook() {
      if (hasRequiredNotebook) return notebook;
      hasRequiredNotebook = 1;
      Object.defineProperty(notebook, "__esModule", { value: true });
      notebook.NotebookDocuments = notebook.NotebookSyncFeature = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const textDocuments_1 = requireTextDocuments();
      const NotebookSyncFeature = (Base) => {
        return class extends Base {
          get synchronization() {
            return {
              onDidOpenNotebookDocument: (handler) => {
                return this.connection.onNotification(vscode_languageserver_protocol_1.DidOpenNotebookDocumentNotification.type, (params) => {
                  handler(params);
                });
              },
              onDidChangeNotebookDocument: (handler) => {
                return this.connection.onNotification(vscode_languageserver_protocol_1.DidChangeNotebookDocumentNotification.type, (params) => {
                  handler(params);
                });
              },
              onDidSaveNotebookDocument: (handler) => {
                return this.connection.onNotification(vscode_languageserver_protocol_1.DidSaveNotebookDocumentNotification.type, (params) => {
                  handler(params);
                });
              },
              onDidCloseNotebookDocument: (handler) => {
                return this.connection.onNotification(vscode_languageserver_protocol_1.DidCloseNotebookDocumentNotification.type, (params) => {
                  handler(params);
                });
              }
            };
          }
        };
      };
      notebook.NotebookSyncFeature = NotebookSyncFeature;
      class CellTextDocumentConnection2 {
        onDidOpenTextDocument(handler) {
          this.openHandler = handler;
          return vscode_languageserver_protocol_1.Disposable.create(() => {
            this.openHandler = void 0;
          });
        }
        openTextDocument(params) {
          this.openHandler && this.openHandler(params);
        }
        onDidChangeTextDocument(handler) {
          this.changeHandler = handler;
          return vscode_languageserver_protocol_1.Disposable.create(() => {
            this.changeHandler = handler;
          });
        }
        changeTextDocument(params) {
          this.changeHandler && this.changeHandler(params);
        }
        onDidCloseTextDocument(handler) {
          this.closeHandler = handler;
          return vscode_languageserver_protocol_1.Disposable.create(() => {
            this.closeHandler = void 0;
          });
        }
        closeTextDocument(params) {
          this.closeHandler && this.closeHandler(params);
        }
        onWillSaveTextDocument() {
          return CellTextDocumentConnection2.NULL_DISPOSE;
        }
        onWillSaveTextDocumentWaitUntil() {
          return CellTextDocumentConnection2.NULL_DISPOSE;
        }
        onDidSaveTextDocument() {
          return CellTextDocumentConnection2.NULL_DISPOSE;
        }
      }
      CellTextDocumentConnection2.NULL_DISPOSE = Object.freeze({ dispose: () => {
      } });
      class NotebookDocuments {
        constructor(configurationOrTextDocuments) {
          if (configurationOrTextDocuments instanceof textDocuments_1.TextDocuments) {
            this._cellTextDocuments = configurationOrTextDocuments;
          } else {
            this._cellTextDocuments = new textDocuments_1.TextDocuments(configurationOrTextDocuments);
          }
          this.notebookDocuments = /* @__PURE__ */ new Map();
          this.notebookCellMap = /* @__PURE__ */ new Map();
          this._onDidOpen = new vscode_languageserver_protocol_1.Emitter();
          this._onDidChange = new vscode_languageserver_protocol_1.Emitter();
          this._onDidSave = new vscode_languageserver_protocol_1.Emitter();
          this._onDidClose = new vscode_languageserver_protocol_1.Emitter();
        }
        get cellTextDocuments() {
          return this._cellTextDocuments;
        }
        getCellTextDocument(cell) {
          return this._cellTextDocuments.get(cell.document);
        }
        getNotebookDocument(uri) {
          return this.notebookDocuments.get(uri);
        }
        getNotebookCell(uri) {
          const value = this.notebookCellMap.get(uri);
          return value && value[0];
        }
        findNotebookDocumentForCell(cell) {
          const key = typeof cell === "string" ? cell : cell.document;
          const value = this.notebookCellMap.get(key);
          return value && value[1];
        }
        get onDidOpen() {
          return this._onDidOpen.event;
        }
        get onDidSave() {
          return this._onDidSave.event;
        }
        get onDidChange() {
          return this._onDidChange.event;
        }
        get onDidClose() {
          return this._onDidClose.event;
        }
        /**
         * Listens for `low level` notification on the given connection to
         * update the notebook documents managed by this instance.
         *
         * Please note that the connection only provides handlers not an event model. Therefore
         * listening on a connection will overwrite the following handlers on a connection:
         * `onDidOpenNotebookDocument`, `onDidChangeNotebookDocument`, `onDidSaveNotebookDocument`,
         *  and `onDidCloseNotebookDocument`.
         *
         * @param connection The connection to listen on.
         */
        listen(connection2) {
          const cellTextDocumentConnection = new CellTextDocumentConnection2();
          const disposables = [];
          disposables.push(this.cellTextDocuments.listen(cellTextDocumentConnection));
          disposables.push(connection2.notebooks.synchronization.onDidOpenNotebookDocument((params) => {
            this.notebookDocuments.set(params.notebookDocument.uri, params.notebookDocument);
            for (const cellTextDocument of params.cellTextDocuments) {
              cellTextDocumentConnection.openTextDocument({ textDocument: cellTextDocument });
            }
            this.updateCellMap(params.notebookDocument);
            this._onDidOpen.fire(params.notebookDocument);
          }));
          disposables.push(connection2.notebooks.synchronization.onDidChangeNotebookDocument((params) => {
            const notebookDocument = this.notebookDocuments.get(params.notebookDocument.uri);
            if (notebookDocument === void 0) {
              return;
            }
            notebookDocument.version = params.notebookDocument.version;
            const oldMetadata = notebookDocument.metadata;
            let metadataChanged = false;
            const change = params.change;
            if (change.metadata !== void 0) {
              metadataChanged = true;
              notebookDocument.metadata = change.metadata;
            }
            const opened = [];
            const closed = [];
            const data = [];
            const text = [];
            if (change.cells !== void 0) {
              const changedCells = change.cells;
              if (changedCells.structure !== void 0) {
                const array = changedCells.structure.array;
                notebookDocument.cells.splice(array.start, array.deleteCount, ...array.cells !== void 0 ? array.cells : []);
                if (changedCells.structure.didOpen !== void 0) {
                  for (const open of changedCells.structure.didOpen) {
                    cellTextDocumentConnection.openTextDocument({ textDocument: open });
                    opened.push(open.uri);
                  }
                }
                if (changedCells.structure.didClose) {
                  for (const close of changedCells.structure.didClose) {
                    cellTextDocumentConnection.closeTextDocument({ textDocument: close });
                    closed.push(close.uri);
                  }
                }
              }
              if (changedCells.data !== void 0) {
                const cellUpdates = new Map(changedCells.data.map((cell) => [cell.document, cell]));
                for (let i = 0; i <= notebookDocument.cells.length; i++) {
                  const change2 = cellUpdates.get(notebookDocument.cells[i].document);
                  if (change2 !== void 0) {
                    const old = notebookDocument.cells.splice(i, 1, change2);
                    data.push({ old: old[0], new: change2 });
                    cellUpdates.delete(change2.document);
                    if (cellUpdates.size === 0) {
                      break;
                    }
                  }
                }
              }
              if (changedCells.textContent !== void 0) {
                for (const cellTextDocument of changedCells.textContent) {
                  cellTextDocumentConnection.changeTextDocument({ textDocument: cellTextDocument.document, contentChanges: cellTextDocument.changes });
                  text.push(cellTextDocument.document.uri);
                }
              }
            }
            this.updateCellMap(notebookDocument);
            const changeEvent = { notebookDocument };
            if (metadataChanged) {
              changeEvent.metadata = { old: oldMetadata, new: notebookDocument.metadata };
            }
            const added = [];
            for (const open of opened) {
              added.push(this.getNotebookCell(open));
            }
            const removed = [];
            for (const close of closed) {
              removed.push(this.getNotebookCell(close));
            }
            const textContent = [];
            for (const change2 of text) {
              textContent.push(this.getNotebookCell(change2));
            }
            if (added.length > 0 || removed.length > 0 || data.length > 0 || textContent.length > 0) {
              changeEvent.cells = { added, removed, changed: { data, textContent } };
            }
            if (changeEvent.metadata !== void 0 || changeEvent.cells !== void 0) {
              this._onDidChange.fire(changeEvent);
            }
          }));
          disposables.push(connection2.notebooks.synchronization.onDidSaveNotebookDocument((params) => {
            const notebookDocument = this.notebookDocuments.get(params.notebookDocument.uri);
            if (notebookDocument === void 0) {
              return;
            }
            this._onDidSave.fire(notebookDocument);
          }));
          disposables.push(connection2.notebooks.synchronization.onDidCloseNotebookDocument((params) => {
            const notebookDocument = this.notebookDocuments.get(params.notebookDocument.uri);
            if (notebookDocument === void 0) {
              return;
            }
            this._onDidClose.fire(notebookDocument);
            for (const cellTextDocument of params.cellTextDocuments) {
              cellTextDocumentConnection.closeTextDocument({ textDocument: cellTextDocument });
            }
            this.notebookDocuments.delete(params.notebookDocument.uri);
            for (const cell of notebookDocument.cells) {
              this.notebookCellMap.delete(cell.document);
            }
          }));
          return vscode_languageserver_protocol_1.Disposable.create(() => {
            disposables.forEach((disposable2) => disposable2.dispose());
          });
        }
        updateCellMap(notebookDocument) {
          for (const cell of notebookDocument.cells) {
            this.notebookCellMap.set(cell.document, [cell, notebookDocument]);
          }
        }
      }
      notebook.NotebookDocuments = NotebookDocuments;
      return notebook;
    }
    var moniker = {};
    var hasRequiredMoniker;
    function requireMoniker() {
      if (hasRequiredMoniker) return moniker;
      hasRequiredMoniker = 1;
      Object.defineProperty(moniker, "__esModule", { value: true });
      moniker.MonikerFeature = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const MonikerFeature = (Base) => {
        return class extends Base {
          get moniker() {
            return {
              on: (handler) => {
                const type = vscode_languageserver_protocol_1.MonikerRequest.type;
                return this.connection.onRequest(type, (params, cancel) => {
                  return handler(params, cancel, this.attachWorkDoneProgress(params), this.attachPartialResultProgress(type, params));
                });
              }
            };
          }
        };
      };
      moniker.MonikerFeature = MonikerFeature;
      return moniker;
    }
    var hasRequiredServer;
    function requireServer() {
      if (hasRequiredServer) return server;
      hasRequiredServer = 1;
      Object.defineProperty(server, "__esModule", { value: true });
      server.createConnection = server.combineFeatures = server.combineNotebooksFeatures = server.combineLanguagesFeatures = server.combineWorkspaceFeatures = server.combineWindowFeatures = server.combineClientFeatures = server.combineTracerFeatures = server.combineTelemetryFeatures = server.combineConsoleFeatures = server._NotebooksImpl = server._LanguagesImpl = server.BulkUnregistration = server.BulkRegistration = server.ErrorMessageTracker = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const Is2 = requireIs$3();
      const UUID = requireUuid();
      const progress_1 = requireProgress();
      const configuration_1 = requireConfiguration();
      const workspaceFolder_1 = requireWorkspaceFolder();
      const callHierarchy_1 = requireCallHierarchy();
      const semanticTokens_1 = requireSemanticTokens();
      const showDocument_1 = requireShowDocument();
      const fileOperations_1 = requireFileOperations();
      const linkedEditingRange_1 = requireLinkedEditingRange();
      const typeHierarchy_1 = requireTypeHierarchy();
      const inlineValue_1 = requireInlineValue();
      const foldingRange_1 = requireFoldingRange();
      const inlayHint_1 = requireInlayHint();
      const diagnostic_1 = requireDiagnostic();
      const notebook_1 = requireNotebook();
      const moniker_1 = requireMoniker();
      function null2Undefined(value) {
        if (value === null) {
          return void 0;
        }
        return value;
      }
      class ErrorMessageTracker {
        constructor() {
          this._messages = /* @__PURE__ */ Object.create(null);
        }
        /**
         * Add a message to the tracker.
         *
         * @param message The message to add.
         */
        add(message) {
          let count = this._messages[message];
          if (!count) {
            count = 0;
          }
          count++;
          this._messages[message] = count;
        }
        /**
         * Send all tracked messages to the connection's window.
         *
         * @param connection The connection established between client and server.
         */
        sendErrors(connection2) {
          Object.keys(this._messages).forEach((message) => {
            connection2.window.showErrorMessage(message);
          });
        }
      }
      server.ErrorMessageTracker = ErrorMessageTracker;
      class RemoteConsoleImpl {
        constructor() {
        }
        rawAttach(connection2) {
          this._rawConnection = connection2;
        }
        attach(connection2) {
          this._connection = connection2;
        }
        get connection() {
          if (!this._connection) {
            throw new Error("Remote is not attached to a connection yet.");
          }
          return this._connection;
        }
        fillServerCapabilities(_capabilities) {
        }
        initialize(_capabilities) {
        }
        error(message) {
          this.send(vscode_languageserver_protocol_1.MessageType.Error, message);
        }
        warn(message) {
          this.send(vscode_languageserver_protocol_1.MessageType.Warning, message);
        }
        info(message) {
          this.send(vscode_languageserver_protocol_1.MessageType.Info, message);
        }
        log(message) {
          this.send(vscode_languageserver_protocol_1.MessageType.Log, message);
        }
        debug(message) {
          this.send(vscode_languageserver_protocol_1.MessageType.Debug, message);
        }
        send(type, message) {
          if (this._rawConnection) {
            this._rawConnection.sendNotification(vscode_languageserver_protocol_1.LogMessageNotification.type, { type, message }).catch(() => {
              (0, vscode_languageserver_protocol_1.RAL)().console.error(`Sending log message failed`);
            });
          }
        }
      }
      class _RemoteWindowImpl {
        constructor() {
        }
        attach(connection2) {
          this._connection = connection2;
        }
        get connection() {
          if (!this._connection) {
            throw new Error("Remote is not attached to a connection yet.");
          }
          return this._connection;
        }
        initialize(_capabilities) {
        }
        fillServerCapabilities(_capabilities) {
        }
        showErrorMessage(message, ...actions) {
          let params = { type: vscode_languageserver_protocol_1.MessageType.Error, message, actions };
          return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
        }
        showWarningMessage(message, ...actions) {
          let params = { type: vscode_languageserver_protocol_1.MessageType.Warning, message, actions };
          return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
        }
        showInformationMessage(message, ...actions) {
          let params = { type: vscode_languageserver_protocol_1.MessageType.Info, message, actions };
          return this.connection.sendRequest(vscode_languageserver_protocol_1.ShowMessageRequest.type, params).then(null2Undefined);
        }
      }
      const RemoteWindowImpl = (0, showDocument_1.ShowDocumentFeature)((0, progress_1.ProgressFeature)(_RemoteWindowImpl));
      var BulkRegistration;
      (function(BulkRegistration2) {
        function create() {
          return new BulkRegistrationImpl();
        }
        BulkRegistration2.create = create;
      })(BulkRegistration || (server.BulkRegistration = BulkRegistration = {}));
      class BulkRegistrationImpl {
        constructor() {
          this._registrations = [];
          this._registered = /* @__PURE__ */ new Set();
        }
        add(type, registerOptions) {
          const method = Is2.string(type) ? type : type.method;
          if (this._registered.has(method)) {
            throw new Error(`${method} is already added to this registration`);
          }
          const id = UUID.generateUuid();
          this._registrations.push({
            id,
            method,
            registerOptions: registerOptions || {}
          });
          this._registered.add(method);
        }
        asRegistrationParams() {
          return {
            registrations: this._registrations
          };
        }
      }
      var BulkUnregistration;
      (function(BulkUnregistration2) {
        function create() {
          return new BulkUnregistrationImpl(void 0, []);
        }
        BulkUnregistration2.create = create;
      })(BulkUnregistration || (server.BulkUnregistration = BulkUnregistration = {}));
      class BulkUnregistrationImpl {
        constructor(_connection, unregistrations) {
          this._connection = _connection;
          this._unregistrations = /* @__PURE__ */ new Map();
          unregistrations.forEach((unregistration) => {
            this._unregistrations.set(unregistration.method, unregistration);
          });
        }
        get isAttached() {
          return !!this._connection;
        }
        attach(connection2) {
          this._connection = connection2;
        }
        add(unregistration) {
          this._unregistrations.set(unregistration.method, unregistration);
        }
        dispose() {
          let unregistrations = [];
          for (let unregistration of this._unregistrations.values()) {
            unregistrations.push(unregistration);
          }
          let params = {
            unregisterations: unregistrations
          };
          this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).catch(() => {
            this._connection.console.info(`Bulk unregistration failed.`);
          });
        }
        disposeSingle(arg) {
          const method = Is2.string(arg) ? arg : arg.method;
          const unregistration = this._unregistrations.get(method);
          if (!unregistration) {
            return false;
          }
          let params = {
            unregisterations: [unregistration]
          };
          this._connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).then(() => {
            this._unregistrations.delete(method);
          }, (_error) => {
            this._connection.console.info(`Un-registering request handler for ${unregistration.id} failed.`);
          });
          return true;
        }
      }
      class RemoteClientImpl {
        attach(connection2) {
          this._connection = connection2;
        }
        get connection() {
          if (!this._connection) {
            throw new Error("Remote is not attached to a connection yet.");
          }
          return this._connection;
        }
        initialize(_capabilities) {
        }
        fillServerCapabilities(_capabilities) {
        }
        register(typeOrRegistrations, registerOptionsOrType, registerOptions) {
          if (typeOrRegistrations instanceof BulkRegistrationImpl) {
            return this.registerMany(typeOrRegistrations);
          } else if (typeOrRegistrations instanceof BulkUnregistrationImpl) {
            return this.registerSingle1(typeOrRegistrations, registerOptionsOrType, registerOptions);
          } else {
            return this.registerSingle2(typeOrRegistrations, registerOptionsOrType);
          }
        }
        registerSingle1(unregistration, type, registerOptions) {
          const method = Is2.string(type) ? type : type.method;
          const id = UUID.generateUuid();
          let params = {
            registrations: [{ id, method, registerOptions: registerOptions || {} }]
          };
          if (!unregistration.isAttached) {
            unregistration.attach(this.connection);
          }
          return this.connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then((_result) => {
            unregistration.add({ id, method });
            return unregistration;
          }, (_error) => {
            this.connection.console.info(`Registering request handler for ${method} failed.`);
            return Promise.reject(_error);
          });
        }
        registerSingle2(type, registerOptions) {
          const method = Is2.string(type) ? type : type.method;
          const id = UUID.generateUuid();
          let params = {
            registrations: [{ id, method, registerOptions: registerOptions || {} }]
          };
          return this.connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then((_result) => {
            return vscode_languageserver_protocol_1.Disposable.create(() => {
              this.unregisterSingle(id, method).catch(() => {
                this.connection.console.info(`Un-registering capability with id ${id} failed.`);
              });
            });
          }, (_error) => {
            this.connection.console.info(`Registering request handler for ${method} failed.`);
            return Promise.reject(_error);
          });
        }
        unregisterSingle(id, method) {
          let params = {
            unregisterations: [{ id, method }]
          };
          return this.connection.sendRequest(vscode_languageserver_protocol_1.UnregistrationRequest.type, params).catch(() => {
            this.connection.console.info(`Un-registering request handler for ${id} failed.`);
          });
        }
        registerMany(registrations) {
          let params = registrations.asRegistrationParams();
          return this.connection.sendRequest(vscode_languageserver_protocol_1.RegistrationRequest.type, params).then(() => {
            return new BulkUnregistrationImpl(this._connection, params.registrations.map((registration) => {
              return { id: registration.id, method: registration.method };
            }));
          }, (_error) => {
            this.connection.console.info(`Bulk registration failed.`);
            return Promise.reject(_error);
          });
        }
      }
      class _RemoteWorkspaceImpl {
        constructor() {
        }
        attach(connection2) {
          this._connection = connection2;
        }
        get connection() {
          if (!this._connection) {
            throw new Error("Remote is not attached to a connection yet.");
          }
          return this._connection;
        }
        initialize(_capabilities) {
        }
        fillServerCapabilities(_capabilities) {
        }
        applyEdit(paramOrEdit) {
          function isApplyWorkspaceEditParams(value) {
            return value && !!value.edit;
          }
          let params = isApplyWorkspaceEditParams(paramOrEdit) ? paramOrEdit : { edit: paramOrEdit };
          return this.connection.sendRequest(vscode_languageserver_protocol_1.ApplyWorkspaceEditRequest.type, params);
        }
      }
      const RemoteWorkspaceImpl = (0, fileOperations_1.FileOperationsFeature)((0, workspaceFolder_1.WorkspaceFoldersFeature)((0, configuration_1.ConfigurationFeature)(_RemoteWorkspaceImpl)));
      class TracerImpl {
        constructor() {
          this._trace = vscode_languageserver_protocol_1.Trace.Off;
        }
        attach(connection2) {
          this._connection = connection2;
        }
        get connection() {
          if (!this._connection) {
            throw new Error("Remote is not attached to a connection yet.");
          }
          return this._connection;
        }
        initialize(_capabilities) {
        }
        fillServerCapabilities(_capabilities) {
        }
        set trace(value) {
          this._trace = value;
        }
        log(message, verbose) {
          if (this._trace === vscode_languageserver_protocol_1.Trace.Off) {
            return;
          }
          this.connection.sendNotification(vscode_languageserver_protocol_1.LogTraceNotification.type, {
            message,
            verbose: this._trace === vscode_languageserver_protocol_1.Trace.Verbose ? verbose : void 0
          }).catch(() => {
          });
        }
      }
      class TelemetryImpl {
        constructor() {
        }
        attach(connection2) {
          this._connection = connection2;
        }
        get connection() {
          if (!this._connection) {
            throw new Error("Remote is not attached to a connection yet.");
          }
          return this._connection;
        }
        initialize(_capabilities) {
        }
        fillServerCapabilities(_capabilities) {
        }
        logEvent(data) {
          this.connection.sendNotification(vscode_languageserver_protocol_1.TelemetryEventNotification.type, data).catch(() => {
            this.connection.console.log(`Sending TelemetryEventNotification failed`);
          });
        }
      }
      class _LanguagesImpl {
        constructor() {
        }
        attach(connection2) {
          this._connection = connection2;
        }
        get connection() {
          if (!this._connection) {
            throw new Error("Remote is not attached to a connection yet.");
          }
          return this._connection;
        }
        initialize(_capabilities) {
        }
        fillServerCapabilities(_capabilities) {
        }
        attachWorkDoneProgress(params) {
          return (0, progress_1.attachWorkDone)(this.connection, params);
        }
        attachPartialResultProgress(_type, params) {
          return (0, progress_1.attachPartialResult)(this.connection, params);
        }
      }
      server._LanguagesImpl = _LanguagesImpl;
      const LanguagesImpl = (0, foldingRange_1.FoldingRangeFeature)((0, moniker_1.MonikerFeature)((0, diagnostic_1.DiagnosticFeature)((0, inlayHint_1.InlayHintFeature)((0, inlineValue_1.InlineValueFeature)((0, typeHierarchy_1.TypeHierarchyFeature)((0, linkedEditingRange_1.LinkedEditingRangeFeature)((0, semanticTokens_1.SemanticTokensFeature)((0, callHierarchy_1.CallHierarchyFeature)(_LanguagesImpl)))))))));
      class _NotebooksImpl {
        constructor() {
        }
        attach(connection2) {
          this._connection = connection2;
        }
        get connection() {
          if (!this._connection) {
            throw new Error("Remote is not attached to a connection yet.");
          }
          return this._connection;
        }
        initialize(_capabilities) {
        }
        fillServerCapabilities(_capabilities) {
        }
        attachWorkDoneProgress(params) {
          return (0, progress_1.attachWorkDone)(this.connection, params);
        }
        attachPartialResultProgress(_type, params) {
          return (0, progress_1.attachPartialResult)(this.connection, params);
        }
      }
      server._NotebooksImpl = _NotebooksImpl;
      const NotebooksImpl = (0, notebook_1.NotebookSyncFeature)(_NotebooksImpl);
      function combineConsoleFeatures(one, two) {
        return function(Base) {
          return two(one(Base));
        };
      }
      server.combineConsoleFeatures = combineConsoleFeatures;
      function combineTelemetryFeatures(one, two) {
        return function(Base) {
          return two(one(Base));
        };
      }
      server.combineTelemetryFeatures = combineTelemetryFeatures;
      function combineTracerFeatures(one, two) {
        return function(Base) {
          return two(one(Base));
        };
      }
      server.combineTracerFeatures = combineTracerFeatures;
      function combineClientFeatures(one, two) {
        return function(Base) {
          return two(one(Base));
        };
      }
      server.combineClientFeatures = combineClientFeatures;
      function combineWindowFeatures(one, two) {
        return function(Base) {
          return two(one(Base));
        };
      }
      server.combineWindowFeatures = combineWindowFeatures;
      function combineWorkspaceFeatures(one, two) {
        return function(Base) {
          return two(one(Base));
        };
      }
      server.combineWorkspaceFeatures = combineWorkspaceFeatures;
      function combineLanguagesFeatures(one, two) {
        return function(Base) {
          return two(one(Base));
        };
      }
      server.combineLanguagesFeatures = combineLanguagesFeatures;
      function combineNotebooksFeatures(one, two) {
        return function(Base) {
          return two(one(Base));
        };
      }
      server.combineNotebooksFeatures = combineNotebooksFeatures;
      function combineFeatures(one, two) {
        function combine(one2, two2, func) {
          if (one2 && two2) {
            return func(one2, two2);
          } else if (one2) {
            return one2;
          } else {
            return two2;
          }
        }
        let result = {
          __brand: "features",
          console: combine(one.console, two.console, combineConsoleFeatures),
          tracer: combine(one.tracer, two.tracer, combineTracerFeatures),
          telemetry: combine(one.telemetry, two.telemetry, combineTelemetryFeatures),
          client: combine(one.client, two.client, combineClientFeatures),
          window: combine(one.window, two.window, combineWindowFeatures),
          workspace: combine(one.workspace, two.workspace, combineWorkspaceFeatures),
          languages: combine(one.languages, two.languages, combineLanguagesFeatures),
          notebooks: combine(one.notebooks, two.notebooks, combineNotebooksFeatures)
        };
        return result;
      }
      server.combineFeatures = combineFeatures;
      function createConnection(connectionFactory, watchDog, factories) {
        const logger = factories && factories.console ? new (factories.console(RemoteConsoleImpl))() : new RemoteConsoleImpl();
        const connection2 = connectionFactory(logger);
        logger.rawAttach(connection2);
        const tracer = factories && factories.tracer ? new (factories.tracer(TracerImpl))() : new TracerImpl();
        const telemetry = factories && factories.telemetry ? new (factories.telemetry(TelemetryImpl))() : new TelemetryImpl();
        const client = factories && factories.client ? new (factories.client(RemoteClientImpl))() : new RemoteClientImpl();
        const remoteWindow = factories && factories.window ? new (factories.window(RemoteWindowImpl))() : new RemoteWindowImpl();
        const workspace = factories && factories.workspace ? new (factories.workspace(RemoteWorkspaceImpl))() : new RemoteWorkspaceImpl();
        const languages = factories && factories.languages ? new (factories.languages(LanguagesImpl))() : new LanguagesImpl();
        const notebooks = factories && factories.notebooks ? new (factories.notebooks(NotebooksImpl))() : new NotebooksImpl();
        const allRemotes = [logger, tracer, telemetry, client, remoteWindow, workspace, languages, notebooks];
        function asPromise(value) {
          if (value instanceof Promise) {
            return value;
          } else if (Is2.thenable(value)) {
            return new Promise((resolve, reject) => {
              value.then((resolved) => resolve(resolved), (error) => reject(error));
            });
          } else {
            return Promise.resolve(value);
          }
        }
        let shutdownHandler = void 0;
        let initializeHandler = void 0;
        let exitHandler = void 0;
        let protocolConnection = {
          listen: () => connection2.listen(),
          sendRequest: (type, ...params) => connection2.sendRequest(Is2.string(type) ? type : type.method, ...params),
          onRequest: (type, handler) => connection2.onRequest(type, handler),
          sendNotification: (type, param) => {
            const method = Is2.string(type) ? type : type.method;
            return connection2.sendNotification(method, param);
          },
          onNotification: (type, handler) => connection2.onNotification(type, handler),
          onProgress: connection2.onProgress,
          sendProgress: connection2.sendProgress,
          onInitialize: (handler) => {
            initializeHandler = handler;
            return {
              dispose: () => {
                initializeHandler = void 0;
              }
            };
          },
          onInitialized: (handler) => connection2.onNotification(vscode_languageserver_protocol_1.InitializedNotification.type, handler),
          onShutdown: (handler) => {
            shutdownHandler = handler;
            return {
              dispose: () => {
                shutdownHandler = void 0;
              }
            };
          },
          onExit: (handler) => {
            exitHandler = handler;
            return {
              dispose: () => {
                exitHandler = void 0;
              }
            };
          },
          get console() {
            return logger;
          },
          get telemetry() {
            return telemetry;
          },
          get tracer() {
            return tracer;
          },
          get client() {
            return client;
          },
          get window() {
            return remoteWindow;
          },
          get workspace() {
            return workspace;
          },
          get languages() {
            return languages;
          },
          get notebooks() {
            return notebooks;
          },
          onDidChangeConfiguration: (handler) => connection2.onNotification(vscode_languageserver_protocol_1.DidChangeConfigurationNotification.type, handler),
          onDidChangeWatchedFiles: (handler) => connection2.onNotification(vscode_languageserver_protocol_1.DidChangeWatchedFilesNotification.type, handler),
          __textDocumentSync: void 0,
          onDidOpenTextDocument: (handler) => connection2.onNotification(vscode_languageserver_protocol_1.DidOpenTextDocumentNotification.type, handler),
          onDidChangeTextDocument: (handler) => connection2.onNotification(vscode_languageserver_protocol_1.DidChangeTextDocumentNotification.type, handler),
          onDidCloseTextDocument: (handler) => connection2.onNotification(vscode_languageserver_protocol_1.DidCloseTextDocumentNotification.type, handler),
          onWillSaveTextDocument: (handler) => connection2.onNotification(vscode_languageserver_protocol_1.WillSaveTextDocumentNotification.type, handler),
          onWillSaveTextDocumentWaitUntil: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.WillSaveTextDocumentWaitUntilRequest.type, handler),
          onDidSaveTextDocument: (handler) => connection2.onNotification(vscode_languageserver_protocol_1.DidSaveTextDocumentNotification.type, handler),
          sendDiagnostics: (params) => connection2.sendNotification(vscode_languageserver_protocol_1.PublishDiagnosticsNotification.type, params),
          onHover: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.HoverRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), void 0);
          }),
          onCompletion: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.CompletionRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), (0, progress_1.attachPartialResult)(connection2, params));
          }),
          onCompletionResolve: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.CompletionResolveRequest.type, handler),
          onSignatureHelp: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.SignatureHelpRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), void 0);
          }),
          onDeclaration: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.DeclarationRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), (0, progress_1.attachPartialResult)(connection2, params));
          }),
          onDefinition: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.DefinitionRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), (0, progress_1.attachPartialResult)(connection2, params));
          }),
          onTypeDefinition: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.TypeDefinitionRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), (0, progress_1.attachPartialResult)(connection2, params));
          }),
          onImplementation: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.ImplementationRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), (0, progress_1.attachPartialResult)(connection2, params));
          }),
          onReferences: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.ReferencesRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), (0, progress_1.attachPartialResult)(connection2, params));
          }),
          onDocumentHighlight: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.DocumentHighlightRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), (0, progress_1.attachPartialResult)(connection2, params));
          }),
          onDocumentSymbol: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.DocumentSymbolRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), (0, progress_1.attachPartialResult)(connection2, params));
          }),
          onWorkspaceSymbol: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.WorkspaceSymbolRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), (0, progress_1.attachPartialResult)(connection2, params));
          }),
          onWorkspaceSymbolResolve: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.WorkspaceSymbolResolveRequest.type, handler),
          onCodeAction: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.CodeActionRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), (0, progress_1.attachPartialResult)(connection2, params));
          }),
          onCodeActionResolve: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.CodeActionResolveRequest.type, (params, cancel) => {
            return handler(params, cancel);
          }),
          onCodeLens: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.CodeLensRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), (0, progress_1.attachPartialResult)(connection2, params));
          }),
          onCodeLensResolve: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.CodeLensResolveRequest.type, (params, cancel) => {
            return handler(params, cancel);
          }),
          onDocumentFormatting: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.DocumentFormattingRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), void 0);
          }),
          onDocumentRangeFormatting: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.DocumentRangeFormattingRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), void 0);
          }),
          onDocumentOnTypeFormatting: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.DocumentOnTypeFormattingRequest.type, (params, cancel) => {
            return handler(params, cancel);
          }),
          onRenameRequest: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.RenameRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), void 0);
          }),
          onPrepareRename: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.PrepareRenameRequest.type, (params, cancel) => {
            return handler(params, cancel);
          }),
          onDocumentLinks: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.DocumentLinkRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), (0, progress_1.attachPartialResult)(connection2, params));
          }),
          onDocumentLinkResolve: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.DocumentLinkResolveRequest.type, (params, cancel) => {
            return handler(params, cancel);
          }),
          onDocumentColor: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.DocumentColorRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), (0, progress_1.attachPartialResult)(connection2, params));
          }),
          onColorPresentation: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.ColorPresentationRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), (0, progress_1.attachPartialResult)(connection2, params));
          }),
          onFoldingRanges: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.FoldingRangeRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), (0, progress_1.attachPartialResult)(connection2, params));
          }),
          onSelectionRanges: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.SelectionRangeRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), (0, progress_1.attachPartialResult)(connection2, params));
          }),
          onExecuteCommand: (handler) => connection2.onRequest(vscode_languageserver_protocol_1.ExecuteCommandRequest.type, (params, cancel) => {
            return handler(params, cancel, (0, progress_1.attachWorkDone)(connection2, params), void 0);
          }),
          dispose: () => connection2.dispose()
        };
        for (let remote of allRemotes) {
          remote.attach(protocolConnection);
        }
        connection2.onRequest(vscode_languageserver_protocol_1.InitializeRequest.type, (params) => {
          watchDog.initialize(params);
          if (Is2.string(params.trace)) {
            tracer.trace = vscode_languageserver_protocol_1.Trace.fromString(params.trace);
          }
          for (let remote of allRemotes) {
            remote.initialize(params.capabilities);
          }
          if (initializeHandler) {
            let result = initializeHandler(params, new vscode_languageserver_protocol_1.CancellationTokenSource().token, (0, progress_1.attachWorkDone)(connection2, params), void 0);
            return asPromise(result).then((value) => {
              if (value instanceof vscode_languageserver_protocol_1.ResponseError) {
                return value;
              }
              let result2 = value;
              if (!result2) {
                result2 = { capabilities: {} };
              }
              let capabilities = result2.capabilities;
              if (!capabilities) {
                capabilities = {};
                result2.capabilities = capabilities;
              }
              if (capabilities.textDocumentSync === void 0 || capabilities.textDocumentSync === null) {
                capabilities.textDocumentSync = Is2.number(protocolConnection.__textDocumentSync) ? protocolConnection.__textDocumentSync : vscode_languageserver_protocol_1.TextDocumentSyncKind.None;
              } else if (!Is2.number(capabilities.textDocumentSync) && !Is2.number(capabilities.textDocumentSync.change)) {
                capabilities.textDocumentSync.change = Is2.number(protocolConnection.__textDocumentSync) ? protocolConnection.__textDocumentSync : vscode_languageserver_protocol_1.TextDocumentSyncKind.None;
              }
              for (let remote of allRemotes) {
                remote.fillServerCapabilities(capabilities);
              }
              return result2;
            });
          } else {
            let result = { capabilities: { textDocumentSync: vscode_languageserver_protocol_1.TextDocumentSyncKind.None } };
            for (let remote of allRemotes) {
              remote.fillServerCapabilities(result.capabilities);
            }
            return result;
          }
        });
        connection2.onRequest(vscode_languageserver_protocol_1.ShutdownRequest.type, () => {
          watchDog.shutdownReceived = true;
          if (shutdownHandler) {
            return shutdownHandler(new vscode_languageserver_protocol_1.CancellationTokenSource().token);
          } else {
            return void 0;
          }
        });
        connection2.onNotification(vscode_languageserver_protocol_1.ExitNotification.type, () => {
          try {
            if (exitHandler) {
              exitHandler();
            }
          } finally {
            if (watchDog.shutdownReceived) {
              watchDog.exit(0);
            } else {
              watchDog.exit(1);
            }
          }
        });
        connection2.onNotification(vscode_languageserver_protocol_1.SetTraceNotification.type, (params) => {
          tracer.trace = vscode_languageserver_protocol_1.Trace.fromString(params.value);
        });
        return protocolConnection;
      }
      server.createConnection = createConnection;
      return server;
    }
    var files = {};
    var hasRequiredFiles;
    function requireFiles() {
      if (hasRequiredFiles) return files;
      hasRequiredFiles = 1;
      Object.defineProperty(files, "__esModule", { value: true });
      files.resolveModulePath = files.FileSystem = files.resolveGlobalYarnPath = files.resolveGlobalNodePath = files.resolve = files.uriToFilePath = void 0;
      const url = require$$0$1;
      const path = require$$1;
      const fs2 = require$$2$1;
      const child_process_1 = require$$3$1;
      function uriToFilePath(uri) {
        let parsed = url.parse(uri);
        if (parsed.protocol !== "file:" || !parsed.path) {
          return void 0;
        }
        let segments = parsed.path.split("/");
        for (var i = 0, len = segments.length; i < len; i++) {
          segments[i] = decodeURIComponent(segments[i]);
        }
        if (process.platform === "win32" && segments.length > 1) {
          let first2 = segments[0];
          let second = segments[1];
          if (first2.length === 0 && second.length > 1 && second[1] === ":") {
            segments.shift();
          }
        }
        return path.normalize(segments.join("/"));
      }
      files.uriToFilePath = uriToFilePath;
      function isWindows() {
        return process.platform === "win32";
      }
      function resolve(moduleName, nodePath, cwd, tracer) {
        const nodePathKey = "NODE_PATH";
        const app = [
          "var p = process;",
          "p.on('message',function(m){",
          "if(m.c==='e'){",
          "p.exit(0);",
          "}",
          "else if(m.c==='rs'){",
          "try{",
          "var r=require.resolve(m.a);",
          "p.send({c:'r',s:true,r:r});",
          "}",
          "catch(err){",
          "p.send({c:'r',s:false});",
          "}",
          "}",
          "});"
        ].join("");
        return new Promise((resolve2, reject) => {
          let env = process.env;
          let newEnv = /* @__PURE__ */ Object.create(null);
          Object.keys(env).forEach((key) => newEnv[key] = env[key]);
          if (nodePath && fs2.existsSync(nodePath)) {
            if (newEnv[nodePathKey]) {
              newEnv[nodePathKey] = nodePath + path.delimiter + newEnv[nodePathKey];
            } else {
              newEnv[nodePathKey] = nodePath;
            }
            if (tracer) {
              tracer(`NODE_PATH value is: ${newEnv[nodePathKey]}`);
            }
          }
          newEnv["ELECTRON_RUN_AS_NODE"] = "1";
          try {
            let cp = (0, child_process_1.fork)("", [], {
              cwd,
              env: newEnv,
              execArgv: ["-e", app]
            });
            if (cp.pid === void 0) {
              reject(new Error(`Starting process to resolve node module  ${moduleName} failed`));
              return;
            }
            cp.on("error", (error) => {
              reject(error);
            });
            cp.on("message", (message2) => {
              if (message2.c === "r") {
                cp.send({ c: "e" });
                if (message2.s) {
                  resolve2(message2.r);
                } else {
                  reject(new Error(`Failed to resolve module: ${moduleName}`));
                }
              }
            });
            let message = {
              c: "rs",
              a: moduleName
            };
            cp.send(message);
          } catch (error) {
            reject(error);
          }
        });
      }
      files.resolve = resolve;
      function resolveGlobalNodePath(tracer) {
        let npmCommand = "npm";
        const env = /* @__PURE__ */ Object.create(null);
        Object.keys(process.env).forEach((key) => env[key] = process.env[key]);
        env["NO_UPDATE_NOTIFIER"] = "true";
        const options = {
          encoding: "utf8",
          env
        };
        if (isWindows()) {
          npmCommand = "npm.cmd";
          options.shell = true;
        }
        let handler = () => {
        };
        try {
          process.on("SIGPIPE", handler);
          let stdout = (0, child_process_1.spawnSync)(npmCommand, ["config", "get", "prefix"], options).stdout;
          if (!stdout) {
            if (tracer) {
              tracer(`'npm config get prefix' didn't return a value.`);
            }
            return void 0;
          }
          let prefix = stdout.trim();
          if (tracer) {
            tracer(`'npm config get prefix' value is: ${prefix}`);
          }
          if (prefix.length > 0) {
            if (isWindows()) {
              return path.join(prefix, "node_modules");
            } else {
              return path.join(prefix, "lib", "node_modules");
            }
          }
          return void 0;
        } catch (err) {
          return void 0;
        } finally {
          process.removeListener("SIGPIPE", handler);
        }
      }
      files.resolveGlobalNodePath = resolveGlobalNodePath;
      function resolveGlobalYarnPath(tracer) {
        let yarnCommand = "yarn";
        let options = {
          encoding: "utf8"
        };
        if (isWindows()) {
          yarnCommand = "yarn.cmd";
          options.shell = true;
        }
        let handler = () => {
        };
        try {
          process.on("SIGPIPE", handler);
          let results = (0, child_process_1.spawnSync)(yarnCommand, ["global", "dir", "--json"], options);
          let stdout = results.stdout;
          if (!stdout) {
            if (tracer) {
              tracer(`'yarn global dir' didn't return a value.`);
              if (results.stderr) {
                tracer(results.stderr);
              }
            }
            return void 0;
          }
          let lines = stdout.trim().split(/\r?\n/);
          for (let line of lines) {
            try {
              let yarn = JSON.parse(line);
              if (yarn.type === "log") {
                return path.join(yarn.data, "node_modules");
              }
            } catch (e) {
            }
          }
          return void 0;
        } catch (err) {
          return void 0;
        } finally {
          process.removeListener("SIGPIPE", handler);
        }
      }
      files.resolveGlobalYarnPath = resolveGlobalYarnPath;
      var FileSystem;
      (function(FileSystem2) {
        let _isCaseSensitive = void 0;
        function isCaseSensitive() {
          if (_isCaseSensitive !== void 0) {
            return _isCaseSensitive;
          }
          if (process.platform === "win32") {
            _isCaseSensitive = false;
          } else {
            _isCaseSensitive = !fs2.existsSync(__filename.toUpperCase()) || !fs2.existsSync(__filename.toLowerCase());
          }
          return _isCaseSensitive;
        }
        FileSystem2.isCaseSensitive = isCaseSensitive;
        function isParent(parent, child) {
          if (isCaseSensitive()) {
            return path.normalize(child).indexOf(path.normalize(parent)) === 0;
          } else {
            return path.normalize(child).toLowerCase().indexOf(path.normalize(parent).toLowerCase()) === 0;
          }
        }
        FileSystem2.isParent = isParent;
      })(FileSystem || (files.FileSystem = FileSystem = {}));
      function resolveModulePath(workspaceRoot, moduleName, nodePath, tracer) {
        if (nodePath) {
          if (!path.isAbsolute(nodePath)) {
            nodePath = path.join(workspaceRoot, nodePath);
          }
          return resolve(moduleName, nodePath, nodePath, tracer).then((value) => {
            if (FileSystem.isParent(nodePath, value)) {
              return value;
            } else {
              return Promise.reject(new Error(`Failed to load ${moduleName} from node path location.`));
            }
          }).then(void 0, (_error) => {
            return resolve(moduleName, resolveGlobalNodePath(tracer), workspaceRoot, tracer);
          });
        } else {
          return resolve(moduleName, resolveGlobalNodePath(tracer), workspaceRoot, tracer);
        }
      }
      files.resolveModulePath = resolveModulePath;
      return files;
    }
    var node$1;
    var hasRequiredNode$1;
    function requireNode$1() {
      if (hasRequiredNode$1) return node$1;
      hasRequiredNode$1 = 1;
      node$1 = requireMain$1();
      return node$1;
    }
    var api = {};
    var inlineCompletion_proposed = {};
    var hasRequiredInlineCompletion_proposed;
    function requireInlineCompletion_proposed() {
      if (hasRequiredInlineCompletion_proposed) return inlineCompletion_proposed;
      hasRequiredInlineCompletion_proposed = 1;
      Object.defineProperty(inlineCompletion_proposed, "__esModule", { value: true });
      inlineCompletion_proposed.InlineCompletionFeature = void 0;
      const vscode_languageserver_protocol_1 = requireMain$1();
      const InlineCompletionFeature = (Base) => {
        return class extends Base {
          get inlineCompletion() {
            return {
              on: (handler) => {
                return this.connection.onRequest(vscode_languageserver_protocol_1.InlineCompletionRequest.type, (params, cancel) => {
                  return handler(params, cancel, this.attachWorkDoneProgress(params));
                });
              }
            };
          }
        };
      };
      inlineCompletion_proposed.InlineCompletionFeature = InlineCompletionFeature;
      return inlineCompletion_proposed;
    }
    var hasRequiredApi;
    function requireApi() {
      if (hasRequiredApi) return api;
      hasRequiredApi = 1;
      (function(exports2) {
        var __createBinding = api && api.__createBinding || (Object.create ? (function(o, m, k, k2) {
          if (k2 === void 0) k2 = k;
          var desc = Object.getOwnPropertyDescriptor(m, k);
          if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function() {
              return m[k];
            } };
          }
          Object.defineProperty(o, k2, desc);
        }) : (function(o, m, k, k2) {
          if (k2 === void 0) k2 = k;
          o[k2] = m[k];
        }));
        var __exportStar = api && api.__exportStar || function(m, exports3) {
          for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
        };
        Object.defineProperty(exports2, "__esModule", { value: true });
        exports2.ProposedFeatures = exports2.NotebookDocuments = exports2.TextDocuments = exports2.SemanticTokensBuilder = void 0;
        const semanticTokens_1 = requireSemanticTokens();
        Object.defineProperty(exports2, "SemanticTokensBuilder", { enumerable: true, get: function() {
          return semanticTokens_1.SemanticTokensBuilder;
        } });
        const ic = requireInlineCompletion_proposed();
        __exportStar(requireMain$1(), exports2);
        const textDocuments_1 = requireTextDocuments();
        Object.defineProperty(exports2, "TextDocuments", { enumerable: true, get: function() {
          return textDocuments_1.TextDocuments;
        } });
        const notebook_1 = requireNotebook();
        Object.defineProperty(exports2, "NotebookDocuments", { enumerable: true, get: function() {
          return notebook_1.NotebookDocuments;
        } });
        __exportStar(requireServer(), exports2);
        var ProposedFeatures;
        (function(ProposedFeatures2) {
          ProposedFeatures2.all = {
            __brand: "features",
            languages: ic.InlineCompletionFeature
          };
        })(ProposedFeatures || (exports2.ProposedFeatures = ProposedFeatures = {}));
      })(api);
      return api;
    }
    var hasRequiredMain;
    function requireMain() {
      if (hasRequiredMain) return main$3;
      hasRequiredMain = 1;
      (function(exports2) {
        var __createBinding = main$3 && main$3.__createBinding || (Object.create ? (function(o, m, k, k2) {
          if (k2 === void 0) k2 = k;
          var desc = Object.getOwnPropertyDescriptor(m, k);
          if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
            desc = { enumerable: true, get: function() {
              return m[k];
            } };
          }
          Object.defineProperty(o, k2, desc);
        }) : (function(o, m, k, k2) {
          if (k2 === void 0) k2 = k;
          o[k2] = m[k];
        }));
        var __exportStar = main$3 && main$3.__exportStar || function(m, exports3) {
          for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p);
        };
        Object.defineProperty(exports2, "__esModule", { value: true });
        exports2.createConnection = exports2.Files = void 0;
        const node_util_1 = require$$0$2;
        const Is2 = requireIs$3();
        const server_1 = requireServer();
        const fm = requireFiles();
        const node_1 = requireNode$1();
        __exportStar(requireNode$1(), exports2);
        __exportStar(requireApi(), exports2);
        var Files;
        (function(Files2) {
          Files2.uriToFilePath = fm.uriToFilePath;
          Files2.resolveGlobalNodePath = fm.resolveGlobalNodePath;
          Files2.resolveGlobalYarnPath = fm.resolveGlobalYarnPath;
          Files2.resolve = fm.resolve;
          Files2.resolveModulePath = fm.resolveModulePath;
        })(Files || (exports2.Files = Files = {}));
        function endProtocolConnection() {
          {
            return;
          }
        }
        let _shutdownReceived = false;
        let exitTimer = void 0;
        function setupExitTimer() {
          const argName = "--clientProcessId";
          function runTimer(value) {
            try {
              let processId = parseInt(value);
              if (!isNaN(processId)) {
                exitTimer = setInterval(() => {
                  try {
                    process.kill(processId, 0);
                  } catch (ex) {
                    endProtocolConnection();
                    process.exit(_shutdownReceived ? 0 : 1);
                  }
                }, 3e3);
              }
            } catch (e) {
            }
          }
          for (let i = 2; i < process.argv.length; i++) {
            let arg = process.argv[i];
            if (arg === argName && i + 1 < process.argv.length) {
              runTimer(process.argv[i + 1]);
              return;
            } else {
              let args = arg.split("=");
              if (args[0] === argName) {
                runTimer(args[1]);
              }
            }
          }
        }
        setupExitTimer();
        const watchDog = {
          initialize: (params) => {
            const processId = params.processId;
            if (Is2.number(processId) && exitTimer === void 0) {
              setInterval(() => {
                try {
                  process.kill(processId, 0);
                } catch (ex) {
                  process.exit(_shutdownReceived ? 0 : 1);
                }
              }, 3e3);
            }
          },
          get shutdownReceived() {
            return _shutdownReceived;
          },
          set shutdownReceived(value) {
            _shutdownReceived = value;
          },
          exit: (code) => {
            process.exit(code);
          }
        };
        function createConnection(arg1, arg2, arg3, arg4) {
          let factories;
          let input;
          let output;
          let options;
          if (arg1 !== void 0 && arg1.__brand === "features") {
            factories = arg1;
            arg1 = arg2;
            arg2 = arg3;
            arg3 = arg4;
          }
          if (node_1.ConnectionStrategy.is(arg1) || node_1.ConnectionOptions.is(arg1)) {
            options = arg1;
          } else {
            input = arg1;
            output = arg2;
            options = arg3;
          }
          return _createConnection(input, output, options, factories);
        }
        exports2.createConnection = createConnection;
        function _createConnection(input, output, options, factories) {
          let stdio = false;
          if (!input && !output && process.argv.length > 2) {
            let port = void 0;
            let pipeName = void 0;
            let argv = process.argv.slice(2);
            for (let i = 0; i < argv.length; i++) {
              let arg = argv[i];
              if (arg === "--node-ipc") {
                input = new node_1.IPCMessageReader(process);
                output = new node_1.IPCMessageWriter(process);
                break;
              } else if (arg === "--stdio") {
                stdio = true;
                input = process.stdin;
                output = process.stdout;
                break;
              } else if (arg === "--socket") {
                port = parseInt(argv[i + 1]);
                break;
              } else if (arg === "--pipe") {
                pipeName = argv[i + 1];
                break;
              } else {
                var args = arg.split("=");
                if (args[0] === "--socket") {
                  port = parseInt(args[1]);
                  break;
                } else if (args[0] === "--pipe") {
                  pipeName = args[1];
                  break;
                }
              }
            }
            if (port) {
              let transport = (0, node_1.createServerSocketTransport)(port);
              input = transport[0];
              output = transport[1];
            } else if (pipeName) {
              let transport = (0, node_1.createServerPipeTransport)(pipeName);
              input = transport[0];
              output = transport[1];
            }
          }
          var commandLineMessage = "Use arguments of createConnection or set command line parameters: '--node-ipc', '--stdio' or '--socket={number}'";
          if (!input) {
            throw new Error("Connection input stream is not set. " + commandLineMessage);
          }
          if (!output) {
            throw new Error("Connection output stream is not set. " + commandLineMessage);
          }
          if (Is2.func(input.read) && Is2.func(input.on)) {
            let inputStream = input;
            inputStream.on("end", () => {
              process.exit(_shutdownReceived ? 0 : 1);
            });
            inputStream.on("close", () => {
              process.exit(_shutdownReceived ? 0 : 1);
            });
          }
          const connectionFactory = (logger) => {
            const result = (0, node_1.createProtocolConnection)(input, output, logger, options);
            if (stdio) {
              patchConsole(logger);
            }
            return result;
          };
          return (0, server_1.createConnection)(connectionFactory, watchDog, factories);
        }
        function patchConsole(logger) {
          function serialize(args) {
            return args.map((arg) => typeof arg === "string" ? arg : (0, node_util_1.inspect)(arg)).join(" ");
          }
          const counters = /* @__PURE__ */ new Map();
          console.assert = function assert(assertion, ...args) {
            if (assertion) {
              return;
            }
            if (args.length === 0) {
              logger.error("Assertion failed");
            } else {
              const [message, ...rest] = args;
              logger.error(`Assertion failed: ${message} ${serialize(rest)}`);
            }
          };
          console.count = function count(label = "default") {
            const message = String(label);
            let counter = counters.get(message) ?? 0;
            counter += 1;
            counters.set(message, counter);
            logger.log(`${message}: ${message}`);
          };
          console.countReset = function countReset(label) {
            if (label === void 0) {
              counters.clear();
            } else {
              counters.delete(String(label));
            }
          };
          console.debug = function debug(...args) {
            logger.log(serialize(args));
          };
          console.dir = function dir(arg, options) {
            logger.log((0, node_util_1.inspect)(arg, options));
          };
          console.log = function log(...args) {
            logger.log(serialize(args));
          };
          console.error = function error(...args) {
            logger.error(serialize(args));
          };
          console.trace = function trace(...args) {
            const stack = new Error().stack.replace(/(.+\n){2}/, "");
            let message = "Trace";
            if (args.length !== 0) {
              message += `: ${serialize(args)}`;
            }
            logger.log(`${message}
${stack}`);
          };
          console.warn = function warn(...args) {
            logger.warn(serialize(args));
          };
        }
      })(main$3);
      return main$3;
    }
    var mainExports$1 = requireMain();
    function isAstNode(obj) {
      return typeof obj === "object" && obj !== null && typeof obj.$type === "string";
    }
    function isReference(obj) {
      return typeof obj === "object" && obj !== null && typeof obj.$refText === "string" && "ref" in obj;
    }
    function isMultiReference(obj) {
      return typeof obj === "object" && obj !== null && typeof obj.$refText === "string" && "items" in obj;
    }
    function isAstNodeDescription(obj) {
      return typeof obj === "object" && obj !== null && typeof obj.name === "string" && typeof obj.type === "string" && typeof obj.path === "string";
    }
    function isLinkingError(obj) {
      return typeof obj === "object" && obj !== null && typeof obj.info === "object" && typeof obj.message === "string";
    }
    class AbstractAstReflection {
      constructor() {
        this.subtypes = {};
        this.allSubtypes = {};
      }
      getAllTypes() {
        return Object.keys(this.types);
      }
      getReferenceType(refInfo) {
        const metaData = this.types[refInfo.container.$type];
        if (!metaData) {
          throw new Error(`Type ${refInfo.container.$type || "undefined"} not found.`);
        }
        const referenceType = metaData.properties[refInfo.property]?.referenceType;
        if (!referenceType) {
          throw new Error(`Property ${refInfo.property || "undefined"} of type ${refInfo.container.$type} is not a reference.`);
        }
        return referenceType;
      }
      getTypeMetaData(type) {
        const result = this.types[type];
        if (!result) {
          return {
            name: type,
            properties: {},
            superTypes: []
          };
        }
        return result;
      }
      isInstance(node2, type) {
        return isAstNode(node2) && this.isSubtype(node2.$type, type);
      }
      isSubtype(subtype, supertype) {
        if (subtype === supertype) {
          return true;
        }
        let nested = this.subtypes[subtype];
        if (!nested) {
          nested = this.subtypes[subtype] = {};
        }
        const existing = nested[supertype];
        if (existing !== void 0) {
          return existing;
        } else {
          const metaData = this.types[subtype];
          const result = metaData ? metaData.superTypes.some((s) => this.isSubtype(s, supertype)) : false;
          nested[supertype] = result;
          return result;
        }
      }
      getAllSubTypes(type) {
        const existing = this.allSubtypes[type];
        if (existing) {
          return existing;
        } else {
          const allTypes = this.getAllTypes();
          const types = [];
          for (const possibleSubType of allTypes) {
            if (this.isSubtype(possibleSubType, type)) {
              types.push(possibleSubType);
            }
          }
          this.allSubtypes[type] = types;
          return types;
        }
      }
    }
    function isCompositeCstNode(node2) {
      return typeof node2 === "object" && node2 !== null && Array.isArray(node2.content);
    }
    function isLeafCstNode(node2) {
      return typeof node2 === "object" && node2 !== null && typeof node2.tokenType === "object";
    }
    function isRootCstNode(node2) {
      return isCompositeCstNode(node2) && typeof node2.fullText === "string";
    }
    const AbstractElement = {
      $type: "AbstractElement",
      cardinality: "cardinality"
    };
    function isAbstractElement(item) {
      return reflection$1.isInstance(item, AbstractElement.$type);
    }
    const AbstractParserRule = {
      $type: "AbstractParserRule"
    };
    function isAbstractParserRule(item) {
      return reflection$1.isInstance(item, AbstractParserRule.$type);
    }
    const AbstractRule = {
      $type: "AbstractRule"
    };
    const AbstractType = {
      $type: "AbstractType"
    };
    const Action = {
      $type: "Action",
      cardinality: "cardinality",
      feature: "feature",
      inferredType: "inferredType",
      operator: "operator",
      type: "type"
    };
    function isAction(item) {
      return reflection$1.isInstance(item, Action.$type);
    }
    const Alternatives = {
      $type: "Alternatives",
      cardinality: "cardinality",
      elements: "elements"
    };
    function isAlternatives(item) {
      return reflection$1.isInstance(item, Alternatives.$type);
    }
    const ArrayLiteral = {
      $type: "ArrayLiteral",
      elements: "elements"
    };
    const ArrayType = {
      $type: "ArrayType",
      elementType: "elementType"
    };
    const Assignment$1 = {
      $type: "Assignment",
      cardinality: "cardinality",
      feature: "feature",
      operator: "operator",
      predicate: "predicate",
      terminal: "terminal"
    };
    function isAssignment(item) {
      return reflection$1.isInstance(item, Assignment$1.$type);
    }
    const BooleanLiteral = {
      $type: "BooleanLiteral",
      true: "true"
    };
    function isBooleanLiteral(item) {
      return reflection$1.isInstance(item, BooleanLiteral.$type);
    }
    const CharacterRange = {
      $type: "CharacterRange",
      cardinality: "cardinality",
      left: "left",
      lookahead: "lookahead",
      parenthesized: "parenthesized",
      right: "right"
    };
    function isCharacterRange(item) {
      return reflection$1.isInstance(item, CharacterRange.$type);
    }
    const Condition$1 = {
      $type: "Condition"
    };
    const Conjunction = {
      $type: "Conjunction",
      left: "left",
      right: "right"
    };
    function isConjunction(item) {
      return reflection$1.isInstance(item, Conjunction.$type);
    }
    const CrossReference = {
      $type: "CrossReference",
      cardinality: "cardinality",
      deprecatedSyntax: "deprecatedSyntax",
      isMulti: "isMulti",
      terminal: "terminal",
      type: "type"
    };
    function isCrossReference(item) {
      return reflection$1.isInstance(item, CrossReference.$type);
    }
    const Disjunction = {
      $type: "Disjunction",
      left: "left",
      right: "right"
    };
    function isDisjunction(item) {
      return reflection$1.isInstance(item, Disjunction.$type);
    }
    const EndOfFile = {
      $type: "EndOfFile",
      cardinality: "cardinality"
    };
    function isEndOfFile(item) {
      return reflection$1.isInstance(item, EndOfFile.$type);
    }
    const Grammar = {
      $type: "Grammar",
      imports: "imports",
      interfaces: "interfaces",
      isDeclared: "isDeclared",
      name: "name",
      rules: "rules",
      types: "types"
    };
    const GrammarImport = {
      $type: "GrammarImport",
      path: "path"
    };
    const Group$1 = {
      $type: "Group",
      cardinality: "cardinality",
      elements: "elements",
      guardCondition: "guardCondition",
      predicate: "predicate"
    };
    function isGroup$1(item) {
      return reflection$1.isInstance(item, Group$1.$type);
    }
    const InferredType = {
      $type: "InferredType",
      name: "name"
    };
    function isInferredType(item) {
      return reflection$1.isInstance(item, InferredType.$type);
    }
    const InfixRule = {
      $type: "InfixRule",
      call: "call",
      dataType: "dataType",
      inferredType: "inferredType",
      name: "name",
      operators: "operators",
      parameters: "parameters",
      returnType: "returnType"
    };
    function isInfixRule(item) {
      return reflection$1.isInstance(item, InfixRule.$type);
    }
    const InfixRuleOperatorList = {
      $type: "InfixRuleOperatorList",
      associativity: "associativity",
      operators: "operators"
    };
    const InfixRuleOperators = {
      $type: "InfixRuleOperators",
      precedences: "precedences"
    };
    const Interface = {
      $type: "Interface",
      attributes: "attributes",
      name: "name",
      superTypes: "superTypes"
    };
    function isInterface(item) {
      return reflection$1.isInstance(item, Interface.$type);
    }
    const Keyword = {
      $type: "Keyword",
      cardinality: "cardinality",
      predicate: "predicate",
      value: "value"
    };
    function isKeyword(item) {
      return reflection$1.isInstance(item, Keyword.$type);
    }
    const NamedArgument = {
      $type: "NamedArgument",
      calledByName: "calledByName",
      parameter: "parameter",
      value: "value"
    };
    const NegatedToken = {
      $type: "NegatedToken",
      cardinality: "cardinality",
      lookahead: "lookahead",
      parenthesized: "parenthesized",
      terminal: "terminal"
    };
    function isNegatedToken(item) {
      return reflection$1.isInstance(item, NegatedToken.$type);
    }
    const Negation = {
      $type: "Negation",
      value: "value"
    };
    function isNegation(item) {
      return reflection$1.isInstance(item, Negation.$type);
    }
    const NumberLiteral = {
      $type: "NumberLiteral",
      value: "value"
    };
    const Parameter$1 = {
      $type: "Parameter",
      name: "name"
    };
    const ParameterReference = {
      $type: "ParameterReference",
      parameter: "parameter"
    };
    function isParameterReference(item) {
      return reflection$1.isInstance(item, ParameterReference.$type);
    }
    const ParserRule = {
      $type: "ParserRule",
      dataType: "dataType",
      definition: "definition",
      entry: "entry",
      fragment: "fragment",
      inferredType: "inferredType",
      name: "name",
      parameters: "parameters",
      returnType: "returnType"
    };
    function isParserRule(item) {
      return reflection$1.isInstance(item, ParserRule.$type);
    }
    const ReferenceType = {
      $type: "ReferenceType",
      isMulti: "isMulti",
      referenceType: "referenceType"
    };
    const RegexToken = {
      $type: "RegexToken",
      cardinality: "cardinality",
      lookahead: "lookahead",
      parenthesized: "parenthesized",
      regex: "regex"
    };
    function isRegexToken(item) {
      return reflection$1.isInstance(item, RegexToken.$type);
    }
    const ReturnType = {
      $type: "ReturnType",
      name: "name"
    };
    function isReturnType(item) {
      return reflection$1.isInstance(item, ReturnType.$type);
    }
    const RuleCall = {
      $type: "RuleCall",
      arguments: "arguments",
      cardinality: "cardinality",
      predicate: "predicate",
      rule: "rule"
    };
    function isRuleCall(item) {
      return reflection$1.isInstance(item, RuleCall.$type);
    }
    const SimpleType = {
      $type: "SimpleType",
      primitiveType: "primitiveType",
      stringType: "stringType",
      typeRef: "typeRef"
    };
    function isSimpleType(item) {
      return reflection$1.isInstance(item, SimpleType.$type);
    }
    const StringLiteral = {
      $type: "StringLiteral",
      value: "value"
    };
    const TerminalAlternatives = {
      $type: "TerminalAlternatives",
      cardinality: "cardinality",
      elements: "elements",
      lookahead: "lookahead",
      parenthesized: "parenthesized"
    };
    function isTerminalAlternatives(item) {
      return reflection$1.isInstance(item, TerminalAlternatives.$type);
    }
    const TerminalElement = {
      $type: "TerminalElement",
      cardinality: "cardinality",
      lookahead: "lookahead",
      parenthesized: "parenthesized"
    };
    const TerminalGroup = {
      $type: "TerminalGroup",
      cardinality: "cardinality",
      elements: "elements",
      lookahead: "lookahead",
      parenthesized: "parenthesized"
    };
    function isTerminalGroup(item) {
      return reflection$1.isInstance(item, TerminalGroup.$type);
    }
    const TerminalRule = {
      $type: "TerminalRule",
      definition: "definition",
      fragment: "fragment",
      hidden: "hidden",
      name: "name",
      type: "type"
    };
    function isTerminalRule(item) {
      return reflection$1.isInstance(item, TerminalRule.$type);
    }
    const TerminalRuleCall = {
      $type: "TerminalRuleCall",
      cardinality: "cardinality",
      lookahead: "lookahead",
      parenthesized: "parenthesized",
      rule: "rule"
    };
    function isTerminalRuleCall(item) {
      return reflection$1.isInstance(item, TerminalRuleCall.$type);
    }
    const Type = {
      $type: "Type",
      name: "name",
      type: "type"
    };
    function isType(item) {
      return reflection$1.isInstance(item, Type.$type);
    }
    const TypeAttribute = {
      $type: "TypeAttribute",
      defaultValue: "defaultValue",
      isOptional: "isOptional",
      name: "name",
      type: "type"
    };
    const TypeDefinition = {
      $type: "TypeDefinition"
    };
    const UnionType = {
      $type: "UnionType",
      types: "types"
    };
    const UnorderedGroup = {
      $type: "UnorderedGroup",
      cardinality: "cardinality",
      elements: "elements"
    };
    function isUnorderedGroup(item) {
      return reflection$1.isInstance(item, UnorderedGroup.$type);
    }
    const UntilToken = {
      $type: "UntilToken",
      cardinality: "cardinality",
      lookahead: "lookahead",
      parenthesized: "parenthesized",
      terminal: "terminal"
    };
    function isUntilToken(item) {
      return reflection$1.isInstance(item, UntilToken.$type);
    }
    const ValueLiteral = {
      $type: "ValueLiteral"
    };
    const Wildcard = {
      $type: "Wildcard",
      cardinality: "cardinality",
      lookahead: "lookahead",
      parenthesized: "parenthesized"
    };
    function isWildcard(item) {
      return reflection$1.isInstance(item, Wildcard.$type);
    }
    class LangiumGrammarAstReflection extends AbstractAstReflection {
      constructor() {
        super(...arguments);
        this.types = {
          AbstractElement: {
            name: AbstractElement.$type,
            properties: {
              cardinality: {
                name: AbstractElement.cardinality
              }
            },
            superTypes: []
          },
          AbstractParserRule: {
            name: AbstractParserRule.$type,
            properties: {},
            superTypes: [AbstractRule.$type, AbstractType.$type]
          },
          AbstractRule: {
            name: AbstractRule.$type,
            properties: {},
            superTypes: []
          },
          AbstractType: {
            name: AbstractType.$type,
            properties: {},
            superTypes: []
          },
          Action: {
            name: Action.$type,
            properties: {
              cardinality: {
                name: Action.cardinality
              },
              feature: {
                name: Action.feature
              },
              inferredType: {
                name: Action.inferredType
              },
              operator: {
                name: Action.operator
              },
              type: {
                name: Action.type,
                referenceType: AbstractType.$type
              }
            },
            superTypes: [AbstractElement.$type]
          },
          Alternatives: {
            name: Alternatives.$type,
            properties: {
              cardinality: {
                name: Alternatives.cardinality
              },
              elements: {
                name: Alternatives.elements,
                defaultValue: []
              }
            },
            superTypes: [AbstractElement.$type]
          },
          ArrayLiteral: {
            name: ArrayLiteral.$type,
            properties: {
              elements: {
                name: ArrayLiteral.elements,
                defaultValue: []
              }
            },
            superTypes: [ValueLiteral.$type]
          },
          ArrayType: {
            name: ArrayType.$type,
            properties: {
              elementType: {
                name: ArrayType.elementType
              }
            },
            superTypes: [TypeDefinition.$type]
          },
          Assignment: {
            name: Assignment$1.$type,
            properties: {
              cardinality: {
                name: Assignment$1.cardinality
              },
              feature: {
                name: Assignment$1.feature
              },
              operator: {
                name: Assignment$1.operator
              },
              predicate: {
                name: Assignment$1.predicate
              },
              terminal: {
                name: Assignment$1.terminal
              }
            },
            superTypes: [AbstractElement.$type]
          },
          BooleanLiteral: {
            name: BooleanLiteral.$type,
            properties: {
              true: {
                name: BooleanLiteral.true,
                defaultValue: false
              }
            },
            superTypes: [Condition$1.$type, ValueLiteral.$type]
          },
          CharacterRange: {
            name: CharacterRange.$type,
            properties: {
              cardinality: {
                name: CharacterRange.cardinality
              },
              left: {
                name: CharacterRange.left
              },
              lookahead: {
                name: CharacterRange.lookahead
              },
              parenthesized: {
                name: CharacterRange.parenthesized,
                defaultValue: false
              },
              right: {
                name: CharacterRange.right
              }
            },
            superTypes: [TerminalElement.$type]
          },
          Condition: {
            name: Condition$1.$type,
            properties: {},
            superTypes: []
          },
          Conjunction: {
            name: Conjunction.$type,
            properties: {
              left: {
                name: Conjunction.left
              },
              right: {
                name: Conjunction.right
              }
            },
            superTypes: [Condition$1.$type]
          },
          CrossReference: {
            name: CrossReference.$type,
            properties: {
              cardinality: {
                name: CrossReference.cardinality
              },
              deprecatedSyntax: {
                name: CrossReference.deprecatedSyntax,
                defaultValue: false
              },
              isMulti: {
                name: CrossReference.isMulti,
                defaultValue: false
              },
              terminal: {
                name: CrossReference.terminal
              },
              type: {
                name: CrossReference.type,
                referenceType: AbstractType.$type
              }
            },
            superTypes: [AbstractElement.$type]
          },
          Disjunction: {
            name: Disjunction.$type,
            properties: {
              left: {
                name: Disjunction.left
              },
              right: {
                name: Disjunction.right
              }
            },
            superTypes: [Condition$1.$type]
          },
          EndOfFile: {
            name: EndOfFile.$type,
            properties: {
              cardinality: {
                name: EndOfFile.cardinality
              }
            },
            superTypes: [AbstractElement.$type]
          },
          Grammar: {
            name: Grammar.$type,
            properties: {
              imports: {
                name: Grammar.imports,
                defaultValue: []
              },
              interfaces: {
                name: Grammar.interfaces,
                defaultValue: []
              },
              isDeclared: {
                name: Grammar.isDeclared,
                defaultValue: false
              },
              name: {
                name: Grammar.name
              },
              rules: {
                name: Grammar.rules,
                defaultValue: []
              },
              types: {
                name: Grammar.types,
                defaultValue: []
              }
            },
            superTypes: []
          },
          GrammarImport: {
            name: GrammarImport.$type,
            properties: {
              path: {
                name: GrammarImport.path
              }
            },
            superTypes: []
          },
          Group: {
            name: Group$1.$type,
            properties: {
              cardinality: {
                name: Group$1.cardinality
              },
              elements: {
                name: Group$1.elements,
                defaultValue: []
              },
              guardCondition: {
                name: Group$1.guardCondition
              },
              predicate: {
                name: Group$1.predicate
              }
            },
            superTypes: [AbstractElement.$type]
          },
          InferredType: {
            name: InferredType.$type,
            properties: {
              name: {
                name: InferredType.name
              }
            },
            superTypes: [AbstractType.$type]
          },
          InfixRule: {
            name: InfixRule.$type,
            properties: {
              call: {
                name: InfixRule.call
              },
              dataType: {
                name: InfixRule.dataType
              },
              inferredType: {
                name: InfixRule.inferredType
              },
              name: {
                name: InfixRule.name
              },
              operators: {
                name: InfixRule.operators
              },
              parameters: {
                name: InfixRule.parameters,
                defaultValue: []
              },
              returnType: {
                name: InfixRule.returnType,
                referenceType: AbstractType.$type
              }
            },
            superTypes: [AbstractParserRule.$type]
          },
          InfixRuleOperatorList: {
            name: InfixRuleOperatorList.$type,
            properties: {
              associativity: {
                name: InfixRuleOperatorList.associativity
              },
              operators: {
                name: InfixRuleOperatorList.operators,
                defaultValue: []
              }
            },
            superTypes: []
          },
          InfixRuleOperators: {
            name: InfixRuleOperators.$type,
            properties: {
              precedences: {
                name: InfixRuleOperators.precedences,
                defaultValue: []
              }
            },
            superTypes: []
          },
          Interface: {
            name: Interface.$type,
            properties: {
              attributes: {
                name: Interface.attributes,
                defaultValue: []
              },
              name: {
                name: Interface.name
              },
              superTypes: {
                name: Interface.superTypes,
                defaultValue: [],
                referenceType: AbstractType.$type
              }
            },
            superTypes: [AbstractType.$type]
          },
          Keyword: {
            name: Keyword.$type,
            properties: {
              cardinality: {
                name: Keyword.cardinality
              },
              predicate: {
                name: Keyword.predicate
              },
              value: {
                name: Keyword.value
              }
            },
            superTypes: [AbstractElement.$type]
          },
          NamedArgument: {
            name: NamedArgument.$type,
            properties: {
              calledByName: {
                name: NamedArgument.calledByName,
                defaultValue: false
              },
              parameter: {
                name: NamedArgument.parameter,
                referenceType: Parameter$1.$type
              },
              value: {
                name: NamedArgument.value
              }
            },
            superTypes: []
          },
          NegatedToken: {
            name: NegatedToken.$type,
            properties: {
              cardinality: {
                name: NegatedToken.cardinality
              },
              lookahead: {
                name: NegatedToken.lookahead
              },
              parenthesized: {
                name: NegatedToken.parenthesized,
                defaultValue: false
              },
              terminal: {
                name: NegatedToken.terminal
              }
            },
            superTypes: [TerminalElement.$type]
          },
          Negation: {
            name: Negation.$type,
            properties: {
              value: {
                name: Negation.value
              }
            },
            superTypes: [Condition$1.$type]
          },
          NumberLiteral: {
            name: NumberLiteral.$type,
            properties: {
              value: {
                name: NumberLiteral.value
              }
            },
            superTypes: [ValueLiteral.$type]
          },
          Parameter: {
            name: Parameter$1.$type,
            properties: {
              name: {
                name: Parameter$1.name
              }
            },
            superTypes: []
          },
          ParameterReference: {
            name: ParameterReference.$type,
            properties: {
              parameter: {
                name: ParameterReference.parameter,
                referenceType: Parameter$1.$type
              }
            },
            superTypes: [Condition$1.$type]
          },
          ParserRule: {
            name: ParserRule.$type,
            properties: {
              dataType: {
                name: ParserRule.dataType
              },
              definition: {
                name: ParserRule.definition
              },
              entry: {
                name: ParserRule.entry,
                defaultValue: false
              },
              fragment: {
                name: ParserRule.fragment,
                defaultValue: false
              },
              inferredType: {
                name: ParserRule.inferredType
              },
              name: {
                name: ParserRule.name
              },
              parameters: {
                name: ParserRule.parameters,
                defaultValue: []
              },
              returnType: {
                name: ParserRule.returnType,
                referenceType: AbstractType.$type
              }
            },
            superTypes: [AbstractParserRule.$type]
          },
          ReferenceType: {
            name: ReferenceType.$type,
            properties: {
              isMulti: {
                name: ReferenceType.isMulti,
                defaultValue: false
              },
              referenceType: {
                name: ReferenceType.referenceType
              }
            },
            superTypes: [TypeDefinition.$type]
          },
          RegexToken: {
            name: RegexToken.$type,
            properties: {
              cardinality: {
                name: RegexToken.cardinality
              },
              lookahead: {
                name: RegexToken.lookahead
              },
              parenthesized: {
                name: RegexToken.parenthesized,
                defaultValue: false
              },
              regex: {
                name: RegexToken.regex
              }
            },
            superTypes: [TerminalElement.$type]
          },
          ReturnType: {
            name: ReturnType.$type,
            properties: {
              name: {
                name: ReturnType.name
              }
            },
            superTypes: []
          },
          RuleCall: {
            name: RuleCall.$type,
            properties: {
              arguments: {
                name: RuleCall.arguments,
                defaultValue: []
              },
              cardinality: {
                name: RuleCall.cardinality
              },
              predicate: {
                name: RuleCall.predicate
              },
              rule: {
                name: RuleCall.rule,
                referenceType: AbstractRule.$type
              }
            },
            superTypes: [AbstractElement.$type]
          },
          SimpleType: {
            name: SimpleType.$type,
            properties: {
              primitiveType: {
                name: SimpleType.primitiveType
              },
              stringType: {
                name: SimpleType.stringType
              },
              typeRef: {
                name: SimpleType.typeRef,
                referenceType: AbstractType.$type
              }
            },
            superTypes: [TypeDefinition.$type]
          },
          StringLiteral: {
            name: StringLiteral.$type,
            properties: {
              value: {
                name: StringLiteral.value
              }
            },
            superTypes: [ValueLiteral.$type]
          },
          TerminalAlternatives: {
            name: TerminalAlternatives.$type,
            properties: {
              cardinality: {
                name: TerminalAlternatives.cardinality
              },
              elements: {
                name: TerminalAlternatives.elements,
                defaultValue: []
              },
              lookahead: {
                name: TerminalAlternatives.lookahead
              },
              parenthesized: {
                name: TerminalAlternatives.parenthesized,
                defaultValue: false
              }
            },
            superTypes: [TerminalElement.$type]
          },
          TerminalElement: {
            name: TerminalElement.$type,
            properties: {
              cardinality: {
                name: TerminalElement.cardinality
              },
              lookahead: {
                name: TerminalElement.lookahead
              },
              parenthesized: {
                name: TerminalElement.parenthesized,
                defaultValue: false
              }
            },
            superTypes: [AbstractElement.$type]
          },
          TerminalGroup: {
            name: TerminalGroup.$type,
            properties: {
              cardinality: {
                name: TerminalGroup.cardinality
              },
              elements: {
                name: TerminalGroup.elements,
                defaultValue: []
              },
              lookahead: {
                name: TerminalGroup.lookahead
              },
              parenthesized: {
                name: TerminalGroup.parenthesized,
                defaultValue: false
              }
            },
            superTypes: [TerminalElement.$type]
          },
          TerminalRule: {
            name: TerminalRule.$type,
            properties: {
              definition: {
                name: TerminalRule.definition
              },
              fragment: {
                name: TerminalRule.fragment,
                defaultValue: false
              },
              hidden: {
                name: TerminalRule.hidden,
                defaultValue: false
              },
              name: {
                name: TerminalRule.name
              },
              type: {
                name: TerminalRule.type
              }
            },
            superTypes: [AbstractRule.$type]
          },
          TerminalRuleCall: {
            name: TerminalRuleCall.$type,
            properties: {
              cardinality: {
                name: TerminalRuleCall.cardinality
              },
              lookahead: {
                name: TerminalRuleCall.lookahead
              },
              parenthesized: {
                name: TerminalRuleCall.parenthesized,
                defaultValue: false
              },
              rule: {
                name: TerminalRuleCall.rule,
                referenceType: TerminalRule.$type
              }
            },
            superTypes: [TerminalElement.$type]
          },
          Type: {
            name: Type.$type,
            properties: {
              name: {
                name: Type.name
              },
              type: {
                name: Type.type
              }
            },
            superTypes: [AbstractType.$type]
          },
          TypeAttribute: {
            name: TypeAttribute.$type,
            properties: {
              defaultValue: {
                name: TypeAttribute.defaultValue
              },
              isOptional: {
                name: TypeAttribute.isOptional,
                defaultValue: false
              },
              name: {
                name: TypeAttribute.name
              },
              type: {
                name: TypeAttribute.type
              }
            },
            superTypes: []
          },
          TypeDefinition: {
            name: TypeDefinition.$type,
            properties: {},
            superTypes: []
          },
          UnionType: {
            name: UnionType.$type,
            properties: {
              types: {
                name: UnionType.types,
                defaultValue: []
              }
            },
            superTypes: [TypeDefinition.$type]
          },
          UnorderedGroup: {
            name: UnorderedGroup.$type,
            properties: {
              cardinality: {
                name: UnorderedGroup.cardinality
              },
              elements: {
                name: UnorderedGroup.elements,
                defaultValue: []
              }
            },
            superTypes: [AbstractElement.$type]
          },
          UntilToken: {
            name: UntilToken.$type,
            properties: {
              cardinality: {
                name: UntilToken.cardinality
              },
              lookahead: {
                name: UntilToken.lookahead
              },
              parenthesized: {
                name: UntilToken.parenthesized,
                defaultValue: false
              },
              terminal: {
                name: UntilToken.terminal
              }
            },
            superTypes: [TerminalElement.$type]
          },
          ValueLiteral: {
            name: ValueLiteral.$type,
            properties: {},
            superTypes: []
          },
          Wildcard: {
            name: Wildcard.$type,
            properties: {
              cardinality: {
                name: Wildcard.cardinality
              },
              lookahead: {
                name: Wildcard.lookahead
              },
              parenthesized: {
                name: Wildcard.parenthesized,
                defaultValue: false
              }
            },
            superTypes: [TerminalElement.$type]
          }
        };
      }
    }
    const reflection$1 = new LangiumGrammarAstReflection();
    class StreamImpl {
      constructor(startFn, nextFn) {
        this.startFn = startFn;
        this.nextFn = nextFn;
      }
      iterator() {
        const iterator = {
          state: this.startFn(),
          next: () => this.nextFn(iterator.state),
          [Symbol.iterator]: () => iterator
        };
        return iterator;
      }
      [Symbol.iterator]() {
        return this.iterator();
      }
      isEmpty() {
        const iterator = this.iterator();
        return Boolean(iterator.next().done);
      }
      count() {
        const iterator = this.iterator();
        let count = 0;
        let next = iterator.next();
        while (!next.done) {
          count++;
          next = iterator.next();
        }
        return count;
      }
      toArray() {
        const result = [];
        const iterator = this.iterator();
        let next;
        do {
          next = iterator.next();
          if (next.value !== void 0) {
            result.push(next.value);
          }
        } while (!next.done);
        return result;
      }
      toSet() {
        return new Set(this);
      }
      toMap(keyFn, valueFn) {
        const entryStream = this.map((element) => [
          keyFn ? keyFn(element) : element,
          valueFn ? valueFn(element) : element
        ]);
        return new Map(entryStream);
      }
      toString() {
        return this.join();
      }
      concat(other) {
        return new StreamImpl(() => ({ first: this.startFn(), firstDone: false, iterator: other[Symbol.iterator]() }), (state) => {
          let result;
          if (!state.firstDone) {
            do {
              result = this.nextFn(state.first);
              if (!result.done) {
                return result;
              }
            } while (!result.done);
            state.firstDone = true;
          }
          do {
            result = state.iterator.next();
            if (!result.done) {
              return result;
            }
          } while (!result.done);
          return DONE_RESULT;
        });
      }
      join(separator = ",") {
        const iterator = this.iterator();
        let value = "";
        let result;
        let addSeparator = false;
        do {
          result = iterator.next();
          if (!result.done) {
            if (addSeparator) {
              value += separator;
            }
            value += toString$1(result.value);
          }
          addSeparator = true;
        } while (!result.done);
        return value;
      }
      indexOf(searchElement, fromIndex = 0) {
        const iterator = this.iterator();
        let index = 0;
        let next = iterator.next();
        while (!next.done) {
          if (index >= fromIndex && next.value === searchElement) {
            return index;
          }
          next = iterator.next();
          index++;
        }
        return -1;
      }
      every(predicate) {
        const iterator = this.iterator();
        let next = iterator.next();
        while (!next.done) {
          if (!predicate(next.value)) {
            return false;
          }
          next = iterator.next();
        }
        return true;
      }
      some(predicate) {
        const iterator = this.iterator();
        let next = iterator.next();
        while (!next.done) {
          if (predicate(next.value)) {
            return true;
          }
          next = iterator.next();
        }
        return false;
      }
      forEach(callbackfn) {
        const iterator = this.iterator();
        let index = 0;
        let next = iterator.next();
        while (!next.done) {
          callbackfn(next.value, index);
          next = iterator.next();
          index++;
        }
      }
      map(callbackfn) {
        return new StreamImpl(this.startFn, (state) => {
          const { done, value } = this.nextFn(state);
          if (done) {
            return DONE_RESULT;
          } else {
            return { done: false, value: callbackfn(value) };
          }
        });
      }
      filter(predicate) {
        return new StreamImpl(this.startFn, (state) => {
          let result;
          do {
            result = this.nextFn(state);
            if (!result.done && predicate(result.value)) {
              return result;
            }
          } while (!result.done);
          return DONE_RESULT;
        });
      }
      nonNullable() {
        return this.filter((e) => e !== void 0 && e !== null);
      }
      reduce(callbackfn, initialValue) {
        const iterator = this.iterator();
        let previousValue = initialValue;
        let next = iterator.next();
        while (!next.done) {
          if (previousValue === void 0) {
            previousValue = next.value;
          } else {
            previousValue = callbackfn(previousValue, next.value);
          }
          next = iterator.next();
        }
        return previousValue;
      }
      reduceRight(callbackfn, initialValue) {
        return this.recursiveReduce(this.iterator(), callbackfn, initialValue);
      }
      recursiveReduce(iterator, callbackfn, initialValue) {
        const next = iterator.next();
        if (next.done) {
          return initialValue;
        }
        const previousValue = this.recursiveReduce(iterator, callbackfn, initialValue);
        if (previousValue === void 0) {
          return next.value;
        }
        return callbackfn(previousValue, next.value);
      }
      find(predicate) {
        const iterator = this.iterator();
        let next = iterator.next();
        while (!next.done) {
          if (predicate(next.value)) {
            return next.value;
          }
          next = iterator.next();
        }
        return void 0;
      }
      findIndex(predicate) {
        const iterator = this.iterator();
        let index = 0;
        let next = iterator.next();
        while (!next.done) {
          if (predicate(next.value)) {
            return index;
          }
          next = iterator.next();
          index++;
        }
        return -1;
      }
      includes(searchElement) {
        const iterator = this.iterator();
        let next = iterator.next();
        while (!next.done) {
          if (next.value === searchElement) {
            return true;
          }
          next = iterator.next();
        }
        return false;
      }
      flatMap(callbackfn) {
        return new StreamImpl(() => ({ this: this.startFn() }), (state) => {
          do {
            if (state.iterator) {
              const next = state.iterator.next();
              if (next.done) {
                state.iterator = void 0;
              } else {
                return next;
              }
            }
            const { done, value } = this.nextFn(state.this);
            if (!done) {
              const mapped = callbackfn(value);
              if (isIterable(mapped)) {
                state.iterator = mapped[Symbol.iterator]();
              } else {
                return { done: false, value: mapped };
              }
            }
          } while (state.iterator);
          return DONE_RESULT;
        });
      }
      flat(depth) {
        if (depth === void 0) {
          depth = 1;
        }
        if (depth <= 0) {
          return this;
        }
        const stream2 = depth > 1 ? this.flat(depth - 1) : this;
        return new StreamImpl(() => ({ this: stream2.startFn() }), (state) => {
          do {
            if (state.iterator) {
              const next = state.iterator.next();
              if (next.done) {
                state.iterator = void 0;
              } else {
                return next;
              }
            }
            const { done, value } = stream2.nextFn(state.this);
            if (!done) {
              if (isIterable(value)) {
                state.iterator = value[Symbol.iterator]();
              } else {
                return { done: false, value };
              }
            }
          } while (state.iterator);
          return DONE_RESULT;
        });
      }
      head() {
        const iterator = this.iterator();
        const result = iterator.next();
        if (result.done) {
          return void 0;
        }
        return result.value;
      }
      tail(skipCount = 1) {
        return new StreamImpl(() => {
          const state = this.startFn();
          for (let i = 0; i < skipCount; i++) {
            const next = this.nextFn(state);
            if (next.done) {
              return state;
            }
          }
          return state;
        }, this.nextFn);
      }
      limit(maxSize) {
        return new StreamImpl(() => ({ size: 0, state: this.startFn() }), (state) => {
          state.size++;
          if (state.size > maxSize) {
            return DONE_RESULT;
          }
          return this.nextFn(state.state);
        });
      }
      distinct(by) {
        return new StreamImpl(() => ({ set: /* @__PURE__ */ new Set(), internalState: this.startFn() }), (state) => {
          let result;
          do {
            result = this.nextFn(state.internalState);
            if (!result.done) {
              const value = by ? by(result.value) : result.value;
              if (!state.set.has(value)) {
                state.set.add(value);
                return result;
              }
            }
          } while (!result.done);
          return DONE_RESULT;
        });
      }
      exclude(other, key) {
        const otherKeySet = /* @__PURE__ */ new Set();
        for (const item of other) {
          const value = key ? key(item) : item;
          otherKeySet.add(value);
        }
        return this.filter((e) => {
          const ownKey = key ? key(e) : e;
          return !otherKeySet.has(ownKey);
        });
      }
    }
    function toString$1(item) {
      if (typeof item === "string") {
        return item;
      }
      if (typeof item === "undefined") {
        return "undefined";
      }
      if (typeof item.toString === "function") {
        return item.toString();
      }
      return Object.prototype.toString.call(item);
    }
    function isIterable(obj) {
      return !!obj && typeof obj[Symbol.iterator] === "function";
    }
    const EMPTY_STREAM = new StreamImpl(() => void 0, () => DONE_RESULT);
    const DONE_RESULT = Object.freeze({ done: true, value: void 0 });
    function stream(...collections) {
      if (collections.length === 1) {
        const collection = collections[0];
        if (collection instanceof StreamImpl) {
          return collection;
        }
        if (isIterable(collection)) {
          return new StreamImpl(() => collection[Symbol.iterator](), (iterator) => iterator.next());
        }
        if (typeof collection.length === "number") {
          return new StreamImpl(() => ({ index: 0 }), (state) => {
            if (state.index < collection.length) {
              return { done: false, value: collection[state.index++] };
            } else {
              return DONE_RESULT;
            }
          });
        }
      }
      if (collections.length > 1) {
        return new StreamImpl(() => ({ collIndex: 0, arrIndex: 0 }), (state) => {
          do {
            if (state.iterator) {
              const next = state.iterator.next();
              if (!next.done) {
                return next;
              }
              state.iterator = void 0;
            }
            if (state.array) {
              if (state.arrIndex < state.array.length) {
                return { done: false, value: state.array[state.arrIndex++] };
              }
              state.array = void 0;
              state.arrIndex = 0;
            }
            if (state.collIndex < collections.length) {
              const collection = collections[state.collIndex++];
              if (isIterable(collection)) {
                state.iterator = collection[Symbol.iterator]();
              } else if (collection && typeof collection.length === "number") {
                state.array = collection;
              }
            }
          } while (state.iterator || state.array || state.collIndex < collections.length);
          return DONE_RESULT;
        });
      }
      return EMPTY_STREAM;
    }
    class TreeStreamImpl extends StreamImpl {
      constructor(root2, children, options) {
        super(() => ({
          iterators: options?.includeRoot ? [[root2][Symbol.iterator]()] : [children(root2)[Symbol.iterator]()],
          pruned: false
        }), (state) => {
          if (state.pruned) {
            state.iterators.pop();
            state.pruned = false;
          }
          while (state.iterators.length > 0) {
            const iterator = state.iterators[state.iterators.length - 1];
            const next = iterator.next();
            if (next.done) {
              state.iterators.pop();
            } else {
              state.iterators.push(children(next.value)[Symbol.iterator]());
              return next;
            }
          }
          return DONE_RESULT;
        });
      }
      iterator() {
        const iterator = {
          state: this.startFn(),
          next: () => this.nextFn(iterator.state),
          prune: () => {
            iterator.state.pruned = true;
          },
          [Symbol.iterator]: () => iterator
        };
        return iterator;
      }
    }
    var Reduction;
    (function(Reduction2) {
      function sum(stream2) {
        return stream2.reduce((a2, b) => a2 + b, 0);
      }
      Reduction2.sum = sum;
      function product(stream2) {
        return stream2.reduce((a2, b) => a2 * b, 0);
      }
      Reduction2.product = product;
      function min2(stream2) {
        return stream2.reduce((a2, b) => Math.min(a2, b));
      }
      Reduction2.min = min2;
      function max(stream2) {
        return stream2.reduce((a2, b) => Math.max(a2, b));
      }
      Reduction2.max = max;
    })(Reduction || (Reduction = {}));
    function getDatatypeNode(cstNode) {
      let current = cstNode;
      let found = false;
      while (current) {
        const definingRule = getContainerOfType(current.grammarSource, isParserRule);
        if (definingRule && definingRule.dataType) {
          current = current.container;
          found = true;
        } else if (found) {
          return current;
        } else {
          return void 0;
        }
      }
      return void 0;
    }
    function streamCst(node2) {
      return new TreeStreamImpl(node2, (element) => {
        if (isCompositeCstNode(element)) {
          return element.content;
        } else {
          return [];
        }
      }, { includeRoot: true });
    }
    function flattenCst(node2) {
      return streamCst(node2).filter(isLeafCstNode);
    }
    function isChildNode(child, parent) {
      while (child.container) {
        child = child.container;
        if (child === parent) {
          return true;
        }
      }
      return false;
    }
    function tokenToRange(token) {
      return {
        start: {
          character: token.startColumn - 1,
          line: token.startLine - 1
        },
        end: {
          character: token.endColumn,
          // endColumn uses the correct index
          line: token.endLine - 1
        }
      };
    }
    function toDocumentSegment(node2) {
      if (!node2) {
        return void 0;
      }
      const { offset, end, range } = node2;
      return {
        range,
        offset,
        end,
        length: end - offset
      };
    }
    var RangeComparison;
    (function(RangeComparison2) {
      RangeComparison2[RangeComparison2["Before"] = 0] = "Before";
      RangeComparison2[RangeComparison2["After"] = 1] = "After";
      RangeComparison2[RangeComparison2["OverlapFront"] = 2] = "OverlapFront";
      RangeComparison2[RangeComparison2["OverlapBack"] = 3] = "OverlapBack";
      RangeComparison2[RangeComparison2["Inside"] = 4] = "Inside";
      RangeComparison2[RangeComparison2["Outside"] = 5] = "Outside";
    })(RangeComparison || (RangeComparison = {}));
    function compareRange(range, to) {
      if (range.end.line < to.start.line || range.end.line === to.start.line && range.end.character <= to.start.character) {
        return RangeComparison.Before;
      } else if (range.start.line > to.end.line || range.start.line === to.end.line && range.start.character >= to.end.character) {
        return RangeComparison.After;
      }
      const startInside = range.start.line > to.start.line || range.start.line === to.start.line && range.start.character >= to.start.character;
      const endInside = range.end.line < to.end.line || range.end.line === to.end.line && range.end.character <= to.end.character;
      if (startInside && endInside) {
        return RangeComparison.Inside;
      } else if (startInside) {
        return RangeComparison.OverlapBack;
      } else if (endInside) {
        return RangeComparison.OverlapFront;
      } else {
        return RangeComparison.Outside;
      }
    }
    function inRange(range, to) {
      const comparison = compareRange(range, to);
      return comparison > RangeComparison.After;
    }
    const DefaultNameRegexp = /^[\w\p{L}]$/u;
    function findDeclarationNodeAtOffset(cstNode, offset, nameRegexp = DefaultNameRegexp) {
      if (cstNode) {
        if (offset > 0) {
          const localOffset = offset - cstNode.offset;
          const textAtOffset = cstNode.text.charAt(localOffset);
          if (!nameRegexp.test(textAtOffset)) {
            offset--;
          }
        }
        return findLeafNodeAtOffset(cstNode, offset);
      }
      return void 0;
    }
    function findCommentNode(cstNode, commentNames) {
      if (cstNode) {
        const previous = getPreviousNode(cstNode, true);
        if (previous && isCommentNode(previous, commentNames)) {
          return previous;
        }
        if (isRootCstNode(cstNode)) {
          const endIndex = cstNode.content.findIndex((e) => !e.hidden);
          for (let i = endIndex - 1; i >= 0; i--) {
            const child = cstNode.content[i];
            if (isCommentNode(child, commentNames)) {
              return child;
            }
          }
        }
      }
      return void 0;
    }
    function isCommentNode(cstNode, commentNames) {
      return isLeafCstNode(cstNode) && commentNames.includes(cstNode.tokenType.name);
    }
    function findLeafNodeAtOffset(node2, offset) {
      if (isLeafCstNode(node2)) {
        return node2;
      } else if (isCompositeCstNode(node2)) {
        const searchResult = binarySearch(node2, offset, false);
        if (searchResult) {
          return findLeafNodeAtOffset(searchResult, offset);
        }
      }
      return void 0;
    }
    function findLeafNodeBeforeOffset(node2, offset) {
      if (isLeafCstNode(node2)) {
        return node2;
      } else if (isCompositeCstNode(node2)) {
        const searchResult = binarySearch(node2, offset, true);
        if (searchResult) {
          return findLeafNodeBeforeOffset(searchResult, offset);
        }
      }
      return void 0;
    }
    function binarySearch(node2, offset, closest) {
      let left = 0;
      let right = node2.content.length - 1;
      let closestNode = void 0;
      while (left <= right) {
        const middle = Math.floor((left + right) / 2);
        const middleNode = node2.content[middle];
        if (middleNode.offset <= offset && middleNode.end > offset) {
          return middleNode;
        }
        if (middleNode.end <= offset) {
          closestNode = closest ? middleNode : void 0;
          left = middle + 1;
        } else {
          right = middle - 1;
        }
      }
      return closestNode;
    }
    function getPreviousNode(node2, hidden = true) {
      while (node2.container) {
        const parent = node2.container;
        let index = parent.content.indexOf(node2);
        while (index > 0) {
          index--;
          const previous = parent.content[index];
          if (hidden || !previous.hidden) {
            return previous;
          }
        }
        node2 = parent;
      }
      return void 0;
    }
    function linkContentToContainer(node2, options = {}) {
      for (const [name, value] of Object.entries(node2)) {
        if (!name.startsWith("$")) {
          if (Array.isArray(value)) {
            value.forEach((item, index) => {
              if (isAstNode(item)) {
                item.$container = node2;
                item.$containerProperty = name;
                item.$containerIndex = index;
                if (options.deep) {
                  linkContentToContainer(item, options);
                }
              }
            });
          } else if (isAstNode(value)) {
            value.$container = node2;
            value.$containerProperty = name;
            if (options.deep) {
              linkContentToContainer(value, options);
            }
          }
        }
      }
    }
    function getContainerOfType(node2, typePredicate) {
      let item = node2;
      while (item) {
        if (typePredicate(item)) {
          return item;
        }
        item = item.$container;
      }
      return void 0;
    }
    function getDocument(node2) {
      const rootNode = findRootNode(node2);
      const result = rootNode.$document;
      if (!result) {
        throw new Error("AST node has no document.");
      }
      return result;
    }
    function findRootNode(node2) {
      while (node2.$container) {
        node2 = node2.$container;
      }
      return node2;
    }
    function getReferenceNodes(reference) {
      if (isReference(reference)) {
        return reference.ref ? [reference.ref] : [];
      } else if (isMultiReference(reference)) {
        return reference.items.map((item) => item.ref);
      }
      return [];
    }
    function streamContents(node2, options) {
      if (!node2) {
        throw new Error("Node must be an AstNode.");
      }
      const range = options?.range;
      return new StreamImpl(() => ({
        keys: Object.keys(node2),
        keyIndex: 0,
        arrayIndex: 0
      }), (state) => {
        while (state.keyIndex < state.keys.length) {
          const property2 = state.keys[state.keyIndex];
          if (!property2.startsWith("$")) {
            const value = node2[property2];
            if (isAstNode(value)) {
              state.keyIndex++;
              if (isAstNodeInRange(value, range)) {
                return { done: false, value };
              }
            } else if (Array.isArray(value)) {
              while (state.arrayIndex < value.length) {
                const index = state.arrayIndex++;
                const element = value[index];
                if (isAstNode(element) && isAstNodeInRange(element, range)) {
                  return { done: false, value: element };
                }
              }
              state.arrayIndex = 0;
            }
          }
          state.keyIndex++;
        }
        return DONE_RESULT;
      });
    }
    function streamAllContents(root2, options) {
      if (!root2) {
        throw new Error("Root node must be an AstNode.");
      }
      return new TreeStreamImpl(root2, (node2) => streamContents(node2, options));
    }
    function streamAst(root2, options) {
      if (!root2) {
        throw new Error("Root node must be an AstNode.");
      }
      return new TreeStreamImpl(root2, (node2) => streamContents(node2, options), { includeRoot: true });
    }
    function isAstNodeInRange(astNode, range) {
      if (!range) {
        return true;
      }
      const nodeRange = astNode.$cstNode?.range;
      if (!nodeRange) {
        return false;
      }
      return inRange(nodeRange, range);
    }
    function streamReferences(node2) {
      return new StreamImpl(() => ({
        keys: Object.keys(node2),
        keyIndex: 0,
        arrayIndex: 0
      }), (state) => {
        while (state.keyIndex < state.keys.length) {
          const property2 = state.keys[state.keyIndex];
          if (!property2.startsWith("$")) {
            const value = node2[property2];
            if (isReference(value) || isMultiReference(value)) {
              state.keyIndex++;
              return { done: false, value: { reference: value, container: node2, property: property2 } };
            } else if (Array.isArray(value)) {
              while (state.arrayIndex < value.length) {
                const index = state.arrayIndex++;
                const element = value[index];
                if (isReference(element) || isMultiReference(value)) {
                  return { done: false, value: { reference: element, container: node2, property: property2, index } };
                }
              }
              state.arrayIndex = 0;
            }
          }
          state.keyIndex++;
        }
        return DONE_RESULT;
      });
    }
    function assignMandatoryProperties(reflection2, node2) {
      const typeMetaData = reflection2.getTypeMetaData(node2.$type);
      const genericNode = node2;
      for (const property2 of Object.values(typeMetaData.properties)) {
        if (property2.defaultValue !== void 0 && genericNode[property2.name] === void 0) {
          genericNode[property2.name] = copyDefaultValue(property2.defaultValue);
        }
      }
    }
    function copyDefaultValue(propertyType) {
      if (Array.isArray(propertyType)) {
        return [...propertyType.map(copyDefaultValue)];
      } else {
        return propertyType;
      }
    }
    class ErrorWithLocation extends Error {
      constructor(node2, message) {
        super(node2 ? `${message} at ${node2.range.start.line}:${node2.range.start.character}` : message);
      }
    }
    function assertUnreachable(_2, message = "Error: Got unexpected value.") {
      throw new Error(message);
    }
    function cc(char) {
      return char.charCodeAt(0);
    }
    function insertToSet(item, set) {
      if (Array.isArray(item)) {
        item.forEach(function(subItem) {
          set.push(subItem);
        });
      } else {
        set.push(item);
      }
    }
    function addFlag(flagObj, flagKey) {
      if (flagObj[flagKey] === true) {
        throw "duplicate flag " + flagKey;
      }
      flagObj[flagKey];
      flagObj[flagKey] = true;
    }
    function ASSERT_EXISTS(obj) {
      if (obj === void 0) {
        throw Error("Internal Error - Should never get here!");
      }
      return true;
    }
    function ASSERT_NEVER_REACH_HERE() {
      throw Error("Internal Error - Should never get here!");
    }
    function isCharacter(obj) {
      return obj["type"] === "Character";
    }
    const digitsCharCodes = [];
    for (let i = cc("0"); i <= cc("9"); i++) {
      digitsCharCodes.push(i);
    }
    const wordCharCodes = [cc("_")].concat(digitsCharCodes);
    for (let i = cc("a"); i <= cc("z"); i++) {
      wordCharCodes.push(i);
    }
    for (let i = cc("A"); i <= cc("Z"); i++) {
      wordCharCodes.push(i);
    }
    const whitespaceCodes = [
      cc(" "),
      cc("\f"),
      cc("\n"),
      cc("\r"),
      cc("	"),
      cc("\v"),
      cc("	"),
      cc(" "),
      cc(" "),
      cc(" "),
      cc(" "),
      cc(" "),
      cc(" "),
      cc(" "),
      cc(" "),
      cc(" "),
      cc(" "),
      cc(" "),
      cc(" "),
      cc(" "),
      cc("\u2028"),
      cc("\u2029"),
      cc(" "),
      cc(" "),
      cc("　"),
      cc("\uFEFF")
    ];
    const hexDigitPattern = /[0-9a-fA-F]/;
    const decimalPattern = /[0-9]/;
    const decimalPatternNoZero = /[1-9]/;
    class RegExpParser {
      constructor() {
        this.idx = 0;
        this.input = "";
        this.groupIdx = 0;
      }
      saveState() {
        return {
          idx: this.idx,
          input: this.input,
          groupIdx: this.groupIdx
        };
      }
      restoreState(newState2) {
        this.idx = newState2.idx;
        this.input = newState2.input;
        this.groupIdx = newState2.groupIdx;
      }
      pattern(input) {
        this.idx = 0;
        this.input = input;
        this.groupIdx = 0;
        this.consumeChar("/");
        const value = this.disjunction();
        this.consumeChar("/");
        const flags = {
          type: "Flags",
          loc: { begin: this.idx, end: input.length },
          global: false,
          ignoreCase: false,
          multiLine: false,
          unicode: false,
          sticky: false
        };
        while (this.isRegExpFlag()) {
          switch (this.popChar()) {
            case "g":
              addFlag(flags, "global");
              break;
            case "i":
              addFlag(flags, "ignoreCase");
              break;
            case "m":
              addFlag(flags, "multiLine");
              break;
            case "u":
              addFlag(flags, "unicode");
              break;
            case "y":
              addFlag(flags, "sticky");
              break;
          }
        }
        if (this.idx !== this.input.length) {
          throw Error("Redundant input: " + this.input.substring(this.idx));
        }
        return {
          type: "Pattern",
          flags,
          value,
          loc: this.loc(0)
        };
      }
      disjunction() {
        const alts = [];
        const begin = this.idx;
        alts.push(this.alternative());
        while (this.peekChar() === "|") {
          this.consumeChar("|");
          alts.push(this.alternative());
        }
        return { type: "Disjunction", value: alts, loc: this.loc(begin) };
      }
      alternative() {
        const terms = [];
        const begin = this.idx;
        while (this.isTerm()) {
          terms.push(this.term());
        }
        return { type: "Alternative", value: terms, loc: this.loc(begin) };
      }
      term() {
        if (this.isAssertion()) {
          return this.assertion();
        } else {
          return this.atom();
        }
      }
      assertion() {
        const begin = this.idx;
        switch (this.popChar()) {
          case "^":
            return {
              type: "StartAnchor",
              loc: this.loc(begin)
            };
          case "$":
            return { type: "EndAnchor", loc: this.loc(begin) };
          // '\b' or '\B'
          case "\\":
            switch (this.popChar()) {
              case "b":
                return {
                  type: "WordBoundary",
                  loc: this.loc(begin)
                };
              case "B":
                return {
                  type: "NonWordBoundary",
                  loc: this.loc(begin)
                };
            }
            throw Error("Invalid Assertion Escape");
          // '(?=' or '(?!'
          case "(":
            this.consumeChar("?");
            let type;
            switch (this.popChar()) {
              case "=":
                type = "Lookahead";
                break;
              case "!":
                type = "NegativeLookahead";
                break;
              case "<": {
                switch (this.popChar()) {
                  case "=":
                    type = "Lookbehind";
                    break;
                  case "!":
                    type = "NegativeLookbehind";
                }
                break;
              }
            }
            ASSERT_EXISTS(type);
            const disjunction = this.disjunction();
            this.consumeChar(")");
            return {
              type,
              value: disjunction,
              loc: this.loc(begin)
            };
        }
        return ASSERT_NEVER_REACH_HERE();
      }
      quantifier(isBacktracking = false) {
        let range = void 0;
        const begin = this.idx;
        switch (this.popChar()) {
          case "*":
            range = {
              atLeast: 0,
              atMost: Infinity
            };
            break;
          case "+":
            range = {
              atLeast: 1,
              atMost: Infinity
            };
            break;
          case "?":
            range = {
              atLeast: 0,
              atMost: 1
            };
            break;
          case "{":
            const atLeast = this.integerIncludingZero();
            switch (this.popChar()) {
              case "}":
                range = {
                  atLeast,
                  atMost: atLeast
                };
                break;
              case ",":
                let atMost;
                if (this.isDigit()) {
                  atMost = this.integerIncludingZero();
                  range = {
                    atLeast,
                    atMost
                  };
                } else {
                  range = {
                    atLeast,
                    atMost: Infinity
                  };
                }
                this.consumeChar("}");
                break;
            }
            if (isBacktracking === true && range === void 0) {
              return void 0;
            }
            ASSERT_EXISTS(range);
            break;
        }
        if (isBacktracking === true && range === void 0) {
          return void 0;
        }
        if (ASSERT_EXISTS(range)) {
          if (this.peekChar(0) === "?") {
            this.consumeChar("?");
            range.greedy = false;
          } else {
            range.greedy = true;
          }
          range.type = "Quantifier";
          range.loc = this.loc(begin);
          return range;
        }
      }
      atom() {
        let atom2;
        const begin = this.idx;
        switch (this.peekChar()) {
          case ".":
            atom2 = this.dotAll();
            break;
          case "\\":
            atom2 = this.atomEscape();
            break;
          case "[":
            atom2 = this.characterClass();
            break;
          case "(":
            atom2 = this.group();
            break;
        }
        if (atom2 === void 0 && this.isPatternCharacter()) {
          atom2 = this.patternCharacter();
        }
        if (ASSERT_EXISTS(atom2)) {
          atom2.loc = this.loc(begin);
          if (this.isQuantifier()) {
            atom2.quantifier = this.quantifier();
          }
          return atom2;
        }
      }
      dotAll() {
        this.consumeChar(".");
        return {
          type: "Set",
          complement: true,
          value: [cc("\n"), cc("\r"), cc("\u2028"), cc("\u2029")]
        };
      }
      atomEscape() {
        this.consumeChar("\\");
        switch (this.peekChar()) {
          case "1":
          case "2":
          case "3":
          case "4":
          case "5":
          case "6":
          case "7":
          case "8":
          case "9":
            return this.decimalEscapeAtom();
          case "d":
          case "D":
          case "s":
          case "S":
          case "w":
          case "W":
            return this.characterClassEscape();
          case "f":
          case "n":
          case "r":
          case "t":
          case "v":
            return this.controlEscapeAtom();
          case "c":
            return this.controlLetterEscapeAtom();
          case "0":
            return this.nulCharacterAtom();
          case "x":
            return this.hexEscapeSequenceAtom();
          case "u":
            return this.regExpUnicodeEscapeSequenceAtom();
          default:
            return this.identityEscapeAtom();
        }
      }
      decimalEscapeAtom() {
        const value = this.positiveInteger();
        return { type: "GroupBackReference", value };
      }
      characterClassEscape() {
        let set;
        let complement = false;
        switch (this.popChar()) {
          case "d":
            set = digitsCharCodes;
            break;
          case "D":
            set = digitsCharCodes;
            complement = true;
            break;
          case "s":
            set = whitespaceCodes;
            break;
          case "S":
            set = whitespaceCodes;
            complement = true;
            break;
          case "w":
            set = wordCharCodes;
            break;
          case "W":
            set = wordCharCodes;
            complement = true;
            break;
        }
        if (ASSERT_EXISTS(set)) {
          return { type: "Set", value: set, complement };
        }
      }
      controlEscapeAtom() {
        let escapeCode;
        switch (this.popChar()) {
          case "f":
            escapeCode = cc("\f");
            break;
          case "n":
            escapeCode = cc("\n");
            break;
          case "r":
            escapeCode = cc("\r");
            break;
          case "t":
            escapeCode = cc("	");
            break;
          case "v":
            escapeCode = cc("\v");
            break;
        }
        if (ASSERT_EXISTS(escapeCode)) {
          return { type: "Character", value: escapeCode };
        }
      }
      controlLetterEscapeAtom() {
        this.consumeChar("c");
        const letter = this.popChar();
        if (/[a-zA-Z]/.test(letter) === false) {
          throw Error("Invalid ");
        }
        const letterCode = letter.toUpperCase().charCodeAt(0) - 64;
        return { type: "Character", value: letterCode };
      }
      nulCharacterAtom() {
        this.consumeChar("0");
        return { type: "Character", value: cc("\0") };
      }
      hexEscapeSequenceAtom() {
        this.consumeChar("x");
        return this.parseHexDigits(2);
      }
      regExpUnicodeEscapeSequenceAtom() {
        this.consumeChar("u");
        return this.parseHexDigits(4);
      }
      identityEscapeAtom() {
        const escapedChar = this.popChar();
        return { type: "Character", value: cc(escapedChar) };
      }
      classPatternCharacterAtom() {
        switch (this.peekChar()) {
          // istanbul ignore next
          case "\n":
          // istanbul ignore next
          case "\r":
          // istanbul ignore next
          case "\u2028":
          // istanbul ignore next
          case "\u2029":
          // istanbul ignore next
          case "\\":
          // istanbul ignore next
          case "]":
            throw Error("TBD");
          default:
            const nextChar = this.popChar();
            return { type: "Character", value: cc(nextChar) };
        }
      }
      characterClass() {
        const set = [];
        let complement = false;
        this.consumeChar("[");
        if (this.peekChar(0) === "^") {
          this.consumeChar("^");
          complement = true;
        }
        while (this.isClassAtom()) {
          const from = this.classAtom();
          from.type === "Character";
          if (isCharacter(from) && this.isRangeDash()) {
            this.consumeChar("-");
            const to = this.classAtom();
            to.type === "Character";
            if (isCharacter(to)) {
              if (to.value < from.value) {
                throw Error("Range out of order in character class");
              }
              set.push({ from: from.value, to: to.value });
            } else {
              insertToSet(from.value, set);
              set.push(cc("-"));
              insertToSet(to.value, set);
            }
          } else {
            insertToSet(from.value, set);
          }
        }
        this.consumeChar("]");
        return { type: "Set", complement, value: set };
      }
      classAtom() {
        switch (this.peekChar()) {
          // istanbul ignore next
          case "]":
          // istanbul ignore next
          case "\n":
          // istanbul ignore next
          case "\r":
          // istanbul ignore next
          case "\u2028":
          // istanbul ignore next
          case "\u2029":
            throw Error("TBD");
          case "\\":
            return this.classEscape();
          default:
            return this.classPatternCharacterAtom();
        }
      }
      classEscape() {
        this.consumeChar("\\");
        switch (this.peekChar()) {
          // Matches a backspace.
          // (Not to be confused with \b word boundary outside characterClass)
          case "b":
            this.consumeChar("b");
            return { type: "Character", value: cc("\b") };
          case "d":
          case "D":
          case "s":
          case "S":
          case "w":
          case "W":
            return this.characterClassEscape();
          case "f":
          case "n":
          case "r":
          case "t":
          case "v":
            return this.controlEscapeAtom();
          case "c":
            return this.controlLetterEscapeAtom();
          case "0":
            return this.nulCharacterAtom();
          case "x":
            return this.hexEscapeSequenceAtom();
          case "u":
            return this.regExpUnicodeEscapeSequenceAtom();
          default:
            return this.identityEscapeAtom();
        }
      }
      group() {
        let capturing = true;
        this.consumeChar("(");
        switch (this.peekChar(0)) {
          case "?":
            this.consumeChar("?");
            this.consumeChar(":");
            capturing = false;
            break;
          default:
            this.groupIdx++;
            break;
        }
        const value = this.disjunction();
        this.consumeChar(")");
        const groupAst = {
          type: "Group",
          capturing,
          value
        };
        if (capturing) {
          groupAst["idx"] = this.groupIdx;
        }
        return groupAst;
      }
      positiveInteger() {
        let number = this.popChar();
        if (decimalPatternNoZero.test(number) === false) {
          throw Error("Expecting a positive integer");
        }
        while (decimalPattern.test(this.peekChar(0))) {
          number += this.popChar();
        }
        return parseInt(number, 10);
      }
      integerIncludingZero() {
        let number = this.popChar();
        if (decimalPattern.test(number) === false) {
          throw Error("Expecting an integer");
        }
        while (decimalPattern.test(this.peekChar(0))) {
          number += this.popChar();
        }
        return parseInt(number, 10);
      }
      patternCharacter() {
        const nextChar = this.popChar();
        switch (nextChar) {
          // istanbul ignore next
          case "\n":
          // istanbul ignore next
          case "\r":
          // istanbul ignore next
          case "\u2028":
          // istanbul ignore next
          case "\u2029":
          // istanbul ignore next
          case "^":
          // istanbul ignore next
          case "$":
          // istanbul ignore next
          case "\\":
          // istanbul ignore next
          case ".":
          // istanbul ignore next
          case "*":
          // istanbul ignore next
          case "+":
          // istanbul ignore next
          case "?":
          // istanbul ignore next
          case "(":
          // istanbul ignore next
          case ")":
          // istanbul ignore next
          case "[":
          // istanbul ignore next
          case "|":
            throw Error("TBD");
          default:
            return { type: "Character", value: cc(nextChar) };
        }
      }
      isRegExpFlag() {
        switch (this.peekChar(0)) {
          case "g":
          case "i":
          case "m":
          case "u":
          case "y":
            return true;
          default:
            return false;
        }
      }
      isRangeDash() {
        return this.peekChar() === "-" && this.isClassAtom(1);
      }
      isDigit() {
        return decimalPattern.test(this.peekChar(0));
      }
      isClassAtom(howMuch = 0) {
        switch (this.peekChar(howMuch)) {
          case "]":
          case "\n":
          case "\r":
          case "\u2028":
          case "\u2029":
            return false;
          default:
            return true;
        }
      }
      isTerm() {
        return this.isAtom() || this.isAssertion();
      }
      isAtom() {
        if (this.isPatternCharacter()) {
          return true;
        }
        switch (this.peekChar(0)) {
          case ".":
          case "\\":
          // atomEscape
          case "[":
          // characterClass
          // TODO: isAtom must be called before isAssertion - disambiguate
          case "(":
            return true;
          default:
            return false;
        }
      }
      isAssertion() {
        switch (this.peekChar(0)) {
          case "^":
          case "$":
            return true;
          // '\b' or '\B'
          case "\\":
            switch (this.peekChar(1)) {
              case "b":
              case "B":
                return true;
              default:
                return false;
            }
          // '(?=' or '(?!' or `(?<=` or `(?<!`
          case "(":
            return this.peekChar(1) === "?" && (this.peekChar(2) === "=" || this.peekChar(2) === "!" || this.peekChar(2) === "<" && (this.peekChar(3) === "=" || this.peekChar(3) === "!"));
          default:
            return false;
        }
      }
      isQuantifier() {
        const prevState = this.saveState();
        try {
          return this.quantifier(true) !== void 0;
        } catch (e) {
          return false;
        } finally {
          this.restoreState(prevState);
        }
      }
      isPatternCharacter() {
        switch (this.peekChar()) {
          case "^":
          case "$":
          case "\\":
          case ".":
          case "*":
          case "+":
          case "?":
          case "(":
          case ")":
          case "[":
          case "|":
          case "/":
          case "\n":
          case "\r":
          case "\u2028":
          case "\u2029":
            return false;
          default:
            return true;
        }
      }
      parseHexDigits(howMany) {
        let hexString = "";
        for (let i = 0; i < howMany; i++) {
          const hexChar = this.popChar();
          if (hexDigitPattern.test(hexChar) === false) {
            throw Error("Expecting a HexDecimal digits");
          }
          hexString += hexChar;
        }
        const charCode = parseInt(hexString, 16);
        return { type: "Character", value: charCode };
      }
      peekChar(howMuch = 0) {
        return this.input[this.idx + howMuch];
      }
      popChar() {
        const nextChar = this.peekChar(0);
        this.consumeChar(void 0);
        return nextChar;
      }
      consumeChar(char) {
        if (char !== void 0 && this.input[this.idx] !== char) {
          throw Error("Expected: '" + char + "' but found: '" + this.input[this.idx] + "' at offset: " + this.idx);
        }
        if (this.idx >= this.input.length) {
          throw Error("Unexpected end of input");
        }
        this.idx++;
      }
      loc(begin) {
        return { begin, end: this.idx };
      }
    }
    class BaseRegExpVisitor {
      visitChildren(node2) {
        for (const key in node2) {
          const child = node2[key];
          if (node2.hasOwnProperty(key)) {
            if (child.type !== void 0) {
              this.visit(child);
            } else if (Array.isArray(child)) {
              child.forEach((subChild) => {
                this.visit(subChild);
              }, this);
            }
          }
        }
      }
      visit(node2) {
        switch (node2.type) {
          case "Pattern":
            this.visitPattern(node2);
            break;
          case "Flags":
            this.visitFlags(node2);
            break;
          case "Disjunction":
            this.visitDisjunction(node2);
            break;
          case "Alternative":
            this.visitAlternative(node2);
            break;
          case "StartAnchor":
            this.visitStartAnchor(node2);
            break;
          case "EndAnchor":
            this.visitEndAnchor(node2);
            break;
          case "WordBoundary":
            this.visitWordBoundary(node2);
            break;
          case "NonWordBoundary":
            this.visitNonWordBoundary(node2);
            break;
          case "Lookahead":
            this.visitLookahead(node2);
            break;
          case "NegativeLookahead":
            this.visitNegativeLookahead(node2);
            break;
          case "Lookbehind":
            this.visitLookbehind(node2);
            break;
          case "NegativeLookbehind":
            this.visitNegativeLookbehind(node2);
            break;
          case "Character":
            this.visitCharacter(node2);
            break;
          case "Set":
            this.visitSet(node2);
            break;
          case "Group":
            this.visitGroup(node2);
            break;
          case "GroupBackReference":
            this.visitGroupBackReference(node2);
            break;
          case "Quantifier":
            this.visitQuantifier(node2);
            break;
        }
        this.visitChildren(node2);
      }
      visitPattern(node2) {
      }
      visitFlags(node2) {
      }
      visitDisjunction(node2) {
      }
      visitAlternative(node2) {
      }
      // Assertion
      visitStartAnchor(node2) {
      }
      visitEndAnchor(node2) {
      }
      visitWordBoundary(node2) {
      }
      visitNonWordBoundary(node2) {
      }
      visitLookahead(node2) {
      }
      visitNegativeLookahead(node2) {
      }
      visitLookbehind(node2) {
      }
      visitNegativeLookbehind(node2) {
      }
      // atoms
      visitCharacter(node2) {
      }
      visitSet(node2) {
      }
      visitGroup(node2) {
      }
      visitGroupBackReference(node2) {
      }
      visitQuantifier(node2) {
      }
    }
    const NEWLINE_REGEXP = /\r?\n/gm;
    const regexpParser = new RegExpParser();
    class TerminalRegExpVisitor extends BaseRegExpVisitor {
      constructor() {
        super(...arguments);
        this.isStarting = true;
        this.endRegexpStack = [];
        this.multiline = false;
      }
      get endRegex() {
        return this.endRegexpStack.join("");
      }
      reset(regex) {
        this.multiline = false;
        this.regex = regex;
        this.startRegexp = "";
        this.isStarting = true;
        this.endRegexpStack = [];
      }
      visitGroup(node2) {
        if (node2.quantifier) {
          this.isStarting = false;
          this.endRegexpStack = [];
        }
      }
      visitCharacter(node2) {
        const char = String.fromCharCode(node2.value);
        if (!this.multiline && char === "\n") {
          this.multiline = true;
        }
        if (node2.quantifier) {
          this.isStarting = false;
          this.endRegexpStack = [];
        } else {
          const escapedChar = escapeRegExp(char);
          this.endRegexpStack.push(escapedChar);
          if (this.isStarting) {
            this.startRegexp += escapedChar;
          }
        }
      }
      visitSet(node2) {
        if (!this.multiline) {
          const set = this.regex.substring(node2.loc.begin, node2.loc.end);
          const regex = new RegExp(set);
          this.multiline = Boolean("\n".match(regex));
        }
        if (node2.quantifier) {
          this.isStarting = false;
          this.endRegexpStack = [];
        } else {
          const set = this.regex.substring(node2.loc.begin, node2.loc.end);
          this.endRegexpStack.push(set);
          if (this.isStarting) {
            this.startRegexp += set;
          }
        }
      }
      visitChildren(node2) {
        if (node2.type === "Group") {
          const group = node2;
          if (group.quantifier) {
            return;
          }
        }
        super.visitChildren(node2);
      }
    }
    const visitor = new TerminalRegExpVisitor();
    function isMultilineComment(regexp) {
      try {
        if (typeof regexp === "string") {
          regexp = new RegExp(regexp);
        }
        regexp = regexp.toString();
        visitor.reset(regexp);
        visitor.visit(regexpParser.pattern(regexp));
        return visitor.multiline;
      } catch {
        return false;
      }
    }
    const whitespaceCharacters = "\f\n\r	\v              \u2028\u2029  　\uFEFF".split("");
    function isWhitespace(value) {
      const regexp = typeof value === "string" ? new RegExp(value) : value;
      return whitespaceCharacters.some((ws) => regexp.test(ws));
    }
    function escapeRegExp(value) {
      return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    }
    function partialMatches(regex, input) {
      const partial = partialRegExp(regex);
      const match = input.match(partial);
      return !!match && match[0].length > 0;
    }
    function partialRegExp(regex) {
      if (typeof regex === "string") {
        regex = new RegExp(regex);
      }
      const re = regex, source = regex.source;
      let i = 0;
      function process2() {
        let result = "", tmp;
        function appendRaw(nbChars) {
          result += source.substr(i, nbChars);
          i += nbChars;
        }
        function appendOptional(nbChars) {
          result += "(?:" + source.substr(i, nbChars) + "|$)";
          i += nbChars;
        }
        while (i < source.length) {
          switch (source[i]) {
            case "\\":
              switch (source[i + 1]) {
                case "c":
                  appendOptional(3);
                  break;
                case "x":
                  appendOptional(4);
                  break;
                case "u":
                  if (re.unicode) {
                    if (source[i + 2] === "{") {
                      appendOptional(source.indexOf("}", i) - i + 1);
                    } else {
                      appendOptional(6);
                    }
                  } else {
                    appendOptional(2);
                  }
                  break;
                case "p":
                case "P":
                  if (re.unicode) {
                    appendOptional(source.indexOf("}", i) - i + 1);
                  } else {
                    appendOptional(2);
                  }
                  break;
                case "k":
                  appendOptional(source.indexOf(">", i) - i + 1);
                  break;
                default:
                  appendOptional(2);
                  break;
              }
              break;
            case "[":
              tmp = /\[(?:\\.|.)*?\]/g;
              tmp.lastIndex = i;
              tmp = tmp.exec(source) || [];
              appendOptional(tmp[0].length);
              break;
            case "|":
            case "^":
            case "$":
            case "*":
            case "+":
            case "?":
              appendRaw(1);
              break;
            case "{":
              tmp = /\{\d+,?\d*\}/g;
              tmp.lastIndex = i;
              tmp = tmp.exec(source);
              if (tmp) {
                appendRaw(tmp[0].length);
              } else {
                appendOptional(1);
              }
              break;
            case "(":
              if (source[i + 1] === "?") {
                switch (source[i + 2]) {
                  case ":":
                    result += "(?:";
                    i += 3;
                    result += process2() + "|$)";
                    break;
                  case "=":
                    result += "(?=";
                    i += 3;
                    result += process2() + ")";
                    break;
                  case "!":
                    tmp = i;
                    i += 3;
                    process2();
                    result += source.substr(tmp, i - tmp);
                    break;
                  case "<":
                    switch (source[i + 3]) {
                      case "=":
                      case "!":
                        tmp = i;
                        i += 4;
                        process2();
                        result += source.substr(tmp, i - tmp);
                        break;
                      default:
                        appendRaw(source.indexOf(">", i) - i + 1);
                        result += process2() + "|$)";
                        break;
                    }
                    break;
                }
              } else {
                appendRaw(1);
                result += process2() + "|$)";
              }
              break;
            case ")":
              ++i;
              return result;
            default:
              appendOptional(1);
              break;
          }
        }
        return result;
      }
      return new RegExp(process2(), regex.flags);
    }
    function getEntryRule(grammar) {
      return grammar.rules.find((e) => isParserRule(e) && e.entry);
    }
    function getHiddenRules(grammar) {
      return grammar.rules.filter((e) => isTerminalRule(e) && e.hidden);
    }
    function getAllReachableRules(grammar, allTerminals) {
      const ruleNames = /* @__PURE__ */ new Set();
      const entryRule = getEntryRule(grammar);
      if (!entryRule) {
        return new Set(grammar.rules);
      }
      const topMostRules = [entryRule].concat(getHiddenRules(grammar));
      for (const rule of topMostRules) {
        ruleDfs(rule, ruleNames, allTerminals);
      }
      const rules = /* @__PURE__ */ new Set();
      for (const rule of grammar.rules) {
        if (ruleNames.has(rule.name) || isTerminalRule(rule) && rule.hidden) {
          rules.add(rule);
        }
      }
      return rules;
    }
    function ruleDfs(rule, visitedSet, allTerminals) {
      visitedSet.add(rule.name);
      streamAllContents(rule).forEach((node2) => {
        if (isRuleCall(node2) || allTerminals) {
          const refRule = node2.rule.ref;
          if (refRule && !visitedSet.has(refRule.name)) {
            ruleDfs(refRule, visitedSet, allTerminals);
          }
        }
      });
    }
    function getCrossReferenceTerminal(crossRef) {
      if (crossRef.terminal) {
        return crossRef.terminal;
      } else if (crossRef.type.ref) {
        const nameAssigment = findNameAssignment(crossRef.type.ref);
        return nameAssigment?.terminal;
      }
      return void 0;
    }
    function isCommentTerminal(terminalRule) {
      return terminalRule.hidden && !isWhitespace(terminalRegex(terminalRule));
    }
    function findNodesForProperty(node2, property2) {
      if (!node2 || !property2) {
        return [];
      }
      return findNodesForPropertyInternal(node2, property2, node2.astNode, true);
    }
    function findNodeForProperty(node2, property2, index) {
      if (!node2 || !property2) {
        return void 0;
      }
      const nodes = findNodesForPropertyInternal(node2, property2, node2.astNode, true);
      if (nodes.length === 0) {
        return void 0;
      }
      if (index !== void 0) {
        index = Math.max(0, Math.min(index, nodes.length - 1));
      } else {
        index = 0;
      }
      return nodes[index];
    }
    function findNodesForPropertyInternal(node2, property2, element, first2) {
      if (!first2) {
        const nodeFeature = getContainerOfType(node2.grammarSource, isAssignment);
        if (nodeFeature && nodeFeature.feature === property2) {
          return [node2];
        }
      }
      if (isCompositeCstNode(node2) && node2.astNode === element) {
        return node2.content.flatMap((e) => findNodesForPropertyInternal(e, property2, element, false));
      }
      return [];
    }
    function findNodeForKeyword(node2, keyword, index) {
      if (!node2) {
        return void 0;
      }
      const nodes = findNodesForKeywordInternal(node2, keyword, node2?.astNode);
      if (nodes.length === 0) {
        return void 0;
      }
      if (index !== void 0) {
        index = Math.max(0, Math.min(index, nodes.length - 1));
      } else {
        index = 0;
      }
      return nodes[index];
    }
    function findNodesForKeywordInternal(node2, keyword, element) {
      if (node2.astNode !== element) {
        return [];
      }
      if (isKeyword(node2.grammarSource) && node2.grammarSource.value === keyword) {
        return [node2];
      }
      const treeIterator = streamCst(node2).iterator();
      let result;
      const keywordNodes = [];
      do {
        result = treeIterator.next();
        if (!result.done) {
          const childNode = result.value;
          if (childNode.astNode === element) {
            if (isKeyword(childNode.grammarSource) && childNode.grammarSource.value === keyword) {
              keywordNodes.push(childNode);
            }
          } else {
            treeIterator.prune();
          }
        }
      } while (!result.done);
      return keywordNodes;
    }
    function findAssignment(cstNode) {
      const astNode = cstNode.astNode;
      while (astNode === cstNode.container?.astNode) {
        const assignment = getContainerOfType(cstNode.grammarSource, isAssignment);
        if (assignment) {
          return assignment;
        }
        cstNode = cstNode.container;
      }
      return void 0;
    }
    function findNameAssignment(type) {
      let startNode = type;
      if (isInferredType(startNode)) {
        if (isAction(startNode.$container)) {
          startNode = startNode.$container.$container;
        } else if (isAbstractParserRule(startNode.$container)) {
          startNode = startNode.$container;
        } else {
          assertUnreachable(startNode.$container);
        }
      }
      return findNameAssignmentInternal(type, startNode, /* @__PURE__ */ new Map());
    }
    function findNameAssignmentInternal(type, startNode, cache) {
      function go(node2, refType) {
        let childAssignment = void 0;
        const parentAssignment = getContainerOfType(node2, isAssignment);
        if (!parentAssignment) {
          childAssignment = findNameAssignmentInternal(refType, refType, cache);
        }
        cache.set(type, childAssignment);
        return childAssignment;
      }
      if (cache.has(type)) {
        return cache.get(type);
      }
      cache.set(type, void 0);
      for (const node2 of streamAllContents(startNode)) {
        if (isAssignment(node2) && node2.feature.toLowerCase() === "name") {
          cache.set(type, node2);
          return node2;
        } else if (isRuleCall(node2) && isParserRule(node2.rule.ref)) {
          return go(node2, node2.rule.ref);
        } else if (isSimpleType(node2) && node2.typeRef?.ref) {
          return go(node2, node2.typeRef.ref);
        }
      }
      return void 0;
    }
    function isOptionalCardinality(cardinality, element) {
      return cardinality === "?" || cardinality === "*" || isGroup$1(element) && Boolean(element.guardCondition);
    }
    function isArrayCardinality(cardinality) {
      return cardinality === "*" || cardinality === "+";
    }
    function isDataTypeRule(rule) {
      return isDataTypeRuleInternal(rule, /* @__PURE__ */ new Set());
    }
    function isDataTypeRuleInternal(rule, visited) {
      if (visited.has(rule)) {
        return true;
      } else {
        visited.add(rule);
      }
      for (const node2 of streamAllContents(rule)) {
        if (isRuleCall(node2)) {
          if (!node2.rule.ref) {
            return false;
          }
          if (isParserRule(node2.rule.ref) && !isDataTypeRuleInternal(node2.rule.ref, visited)) {
            return false;
          }
          if (isInfixRule(node2.rule.ref)) {
            return false;
          }
        } else if (isAssignment(node2)) {
          return false;
        } else if (isAction(node2)) {
          return false;
        }
      }
      return Boolean(rule.definition);
    }
    function getExplicitRuleType(rule) {
      if (isTerminalRule(rule)) {
        return void 0;
      }
      if (rule.inferredType) {
        return rule.inferredType.name;
      } else if (rule.dataType) {
        return rule.dataType;
      } else if (rule.returnType) {
        const refType = rule.returnType.ref;
        if (refType) {
          return refType.name;
        }
      }
      return void 0;
    }
    function getTypeName(type) {
      if (isAbstractParserRule(type)) {
        return isParserRule(type) && isDataTypeRule(type) ? type.name : getExplicitRuleType(type) ?? type.name;
      } else if (isInterface(type) || isType(type) || isReturnType(type)) {
        return type.name;
      } else if (isAction(type)) {
        const actionType = getActionType(type);
        if (actionType) {
          return actionType;
        }
      } else if (isInferredType(type)) {
        return type.name;
      }
      throw new Error("Cannot get name of Unknown Type");
    }
    function getActionType(action) {
      if (action.inferredType) {
        return action.inferredType.name;
      } else if (action.type?.ref) {
        return getTypeName(action.type.ref);
      }
      return void 0;
    }
    function getRuleType(rule) {
      if (isTerminalRule(rule)) {
        return rule.type?.name ?? "string";
      } else {
        return getExplicitRuleType(rule) ?? rule.name;
      }
    }
    function terminalRegex(terminalRule) {
      const flags = {
        s: false,
        i: false,
        u: false
      };
      const source = abstractElementToRegex(terminalRule.definition, flags);
      const flagText = Object.entries(flags).filter(([, value]) => value).map(([name]) => name).join("");
      return new RegExp(source, flagText);
    }
    const WILDCARD = /[\s\S]/.source;
    function abstractElementToRegex(element, flags) {
      if (isTerminalAlternatives(element)) {
        return terminalAlternativesToRegex(element);
      } else if (isTerminalGroup(element)) {
        return terminalGroupToRegex(element);
      } else if (isCharacterRange(element)) {
        return characterRangeToRegex(element);
      } else if (isTerminalRuleCall(element)) {
        const rule = element.rule.ref;
        if (!rule) {
          throw new Error("Missing rule reference.");
        }
        return withCardinality(abstractElementToRegex(rule.definition), {
          cardinality: element.cardinality,
          lookahead: element.lookahead,
          parenthesized: element.parenthesized
        });
      } else if (isNegatedToken(element)) {
        return negateTokenToRegex(element);
      } else if (isUntilToken(element)) {
        return untilTokenToRegex(element);
      } else if (isRegexToken(element)) {
        const lastSlash = element.regex.lastIndexOf("/");
        const source = element.regex.substring(1, lastSlash);
        const regexFlags = element.regex.substring(lastSlash + 1);
        if (flags) {
          flags.i = regexFlags.includes("i");
          flags.s = regexFlags.includes("s");
          flags.u = regexFlags.includes("u");
        }
        return withCardinality(source, {
          cardinality: element.cardinality,
          lookahead: element.lookahead,
          parenthesized: element.parenthesized,
          wrap: false
        });
      } else if (isWildcard(element)) {
        return withCardinality(WILDCARD, {
          cardinality: element.cardinality,
          lookahead: element.lookahead,
          parenthesized: element.parenthesized
        });
      } else {
        throw new Error(`Invalid terminal element: ${element?.$type}, ${element?.$cstNode?.text}`);
      }
    }
    function terminalAlternativesToRegex(alternatives) {
      return withCardinality(alternatives.elements.map((e) => abstractElementToRegex(e)).join("|"), {
        cardinality: alternatives.cardinality,
        lookahead: alternatives.lookahead,
        parenthesized: alternatives.parenthesized,
        wrap: false
        // wrapping is not required for top level alternatives, and nested alternatives are already parenthesized according to the grammar
      });
    }
    function terminalGroupToRegex(group) {
      return withCardinality(group.elements.map((e) => abstractElementToRegex(e)).join(""), {
        cardinality: group.cardinality,
        lookahead: group.lookahead,
        parenthesized: group.parenthesized,
        wrap: false
        // wrapping is not required for top level group, and nested group are already parenthesized according to the grammar
      });
    }
    function untilTokenToRegex(until) {
      return withCardinality(`${WILDCARD}*?${abstractElementToRegex(until.terminal)}`, {
        cardinality: until.cardinality,
        lookahead: until.lookahead,
        parenthesized: until.parenthesized
      });
    }
    function negateTokenToRegex(negate) {
      return withCardinality(`(?!${abstractElementToRegex(negate.terminal)})${WILDCARD}*?`, {
        cardinality: negate.cardinality,
        lookahead: negate.lookahead,
        parenthesized: negate.parenthesized
      });
    }
    function characterRangeToRegex(range) {
      if (range.right) {
        return withCardinality(`[${keywordToRegex(range.left)}-${keywordToRegex(range.right)}]`, {
          cardinality: range.cardinality,
          lookahead: range.lookahead,
          parenthesized: range.parenthesized,
          wrap: false
        });
      }
      return withCardinality(keywordToRegex(range.left), {
        cardinality: range.cardinality,
        lookahead: range.lookahead,
        parenthesized: range.parenthesized,
        wrap: false
      });
    }
    function keywordToRegex(keyword) {
      return escapeRegExp(keyword.value);
    }
    function withCardinality(regex, options) {
      if (options.parenthesized || options.lookahead || options.wrap !== false) {
        const groupConfig = options.lookahead ?? (options.parenthesized ? "" : "?:");
        regex = `(${groupConfig}${regex})`;
      }
      if (options.cardinality) {
        return `${regex}${options.cardinality}`;
      }
      return regex;
    }
    function findNextFeatures(featureStack, unparsedTokens) {
      const context = {
        stacks: featureStack,
        tokens: unparsedTokens
      };
      interpretTokens(context);
      context.stacks.flat().forEach((feature) => {
        feature.property = void 0;
      });
      const nextStacks = findNextFeatureStacks(context.stacks);
      return nextStacks.map((e) => e[e.length - 1]);
    }
    function findNextFeaturesInternal(stack) {
      const features = [];
      if (stack.length === 0) {
        return features;
      }
      const top = stack[stack.length - 1];
      const { group, child } = findGroupAndChild(top.feature);
      if (isArrayCardinality(child.cardinality)) {
        const repeatingFeatures = findFirstFeaturesInternal({
          feature: child,
          type: top.type,
          property: top.property
        });
        features.push(...repeatingFeatures);
      }
      let groupIndex = -1;
      if (group) {
        groupIndex = group.elements.indexOf(child);
      }
      const parentStack = stack.slice(0, -1);
      if (!group) {
        const parent = getAbstractElementParent(child);
        if (parent) {
          features.push(...findNextFeaturesInternal([
            ...parentStack,
            {
              feature: parent
            }
          ]));
        } else {
          features.push(...findNextFeaturesInternal(parentStack));
        }
      } else {
        const nextIndex = groupIndex + 1;
        const { stacks, end } = findNextFeaturesInGroup({
          feature: group,
          type: top.type
        }, nextIndex);
        for (const newStack of stacks) {
          features.push([...parentStack, ...newStack]);
        }
        if (end) {
          groupIndex = group.elements.length - 1;
        }
      }
      if (group && groupIndex === group.elements.length - 1) {
        features.push(...findNextFeaturesInternal([
          ...parentStack,
          {
            feature: group
          }
        ]));
      }
      return features;
    }
    function findFirstFeatures(next) {
      return findFirstFeaturesInternal({ feature: next });
    }
    function findFirstFeaturesInternal(next) {
      const { feature, type } = next;
      if (isGroup$1(feature)) {
        return findNextFeaturesInGroup(next, 0).stacks;
      } else if (isAlternatives(feature) || isUnorderedGroup(feature)) {
        return feature.elements.flatMap((e) => findFirstFeaturesInternal({
          feature: e,
          type,
          property: next.property
        }));
      } else if (isAssignment(feature)) {
        return findFirstFeaturesInternal({
          feature: feature.terminal,
          type,
          property: next.property ?? feature.feature
        });
      } else if (isAction(feature)) {
        return findNextFeaturesInternal([{
          feature,
          type: getTypeName(feature),
          property: next.property ?? feature.feature
        }]);
      } else if (isRuleCall(feature) && isParserRule(feature.rule.ref)) {
        const rule = feature.rule.ref;
        const stacks = findFirstFeaturesInternal({
          feature: rule.definition,
          type: rule.fragment || rule.dataType ? void 0 : getExplicitRuleType(rule) ?? rule.name,
          property: next.property
        });
        for (const stack of stacks) {
          stack.unshift(next);
        }
        return stacks;
      } else if (isRuleCall(feature) && isInfixRule(feature.rule.ref)) {
        const rule = feature.rule.ref;
        const call = rule.call.rule.ref;
        if (!isParserRule(call)) {
          console.error("Failed to resolve reference to " + rule.call.rule.$refText);
          return [];
        }
        const stacks = findFirstFeaturesInternal({
          feature: call.definition,
          type: getExplicitRuleType(call) ?? call.name,
          property: "parts"
        });
        for (const stack of stacks) {
          stack.unshift(next);
        }
        return stacks;
      } else {
        return [[next]];
      }
    }
    function findNextFeaturesInGroup(next, index) {
      const features = [];
      let firstFeature;
      while (index < next.feature.elements.length) {
        const feature = next.feature.elements[index];
        firstFeature = {
          feature,
          type: next.type
        };
        const stacks = findFirstFeaturesInternal(firstFeature);
        features.push(...stacks);
        if (isElementOptional(feature, /* @__PURE__ */ new Map())) {
          index++;
        } else {
          break;
        }
      }
      return {
        stacks: features,
        end: index >= next.feature.elements.length
      };
    }
    function isElementOptional(feature, visited) {
      const visitedResult = visited.get(feature);
      if (visitedResult !== void 0) {
        return visitedResult;
      }
      visited.set(feature, false);
      if (isOptionalCardinality(feature.cardinality, feature)) {
        visited.set(feature, true);
        return true;
      }
      if (isGroup$1(feature)) {
        for (const element of feature.elements) {
          if (!isElementOptional(element, visited)) {
            visited.set(feature, false);
            return false;
          }
        }
        visited.set(feature, true);
        return true;
      } else if (isAlternatives(feature) || isUnorderedGroup(feature)) {
        for (const element of feature.elements) {
          if (isElementOptional(element, visited)) {
            visited.set(feature, true);
            return true;
          }
        }
        visited.set(feature, false);
        return false;
      } else if (isRuleCall(feature) && isParserRule(feature.rule.ref)) {
        const rule = feature.rule.ref;
        const result = isElementOptional(rule.definition, visited);
        visited.set(feature, result);
        return result;
      }
      return false;
    }
    function interpretTokens(context) {
      for (const token of context.tokens) {
        const nextFeatureStacks = findNextFeatureStacks(context.stacks, token);
        context.stacks = nextFeatureStacks;
      }
    }
    function findNextFeatureStacks(stacks, token) {
      const newStacks = [];
      for (const stack of stacks) {
        newStacks.push(...interpretStackToken(stack, token));
      }
      return newStacks;
    }
    function interpretStackToken(stack, token) {
      const allNextFeatures = findNextFeaturesInternal(stack);
      const matchingNextFeatures = allNextFeatures.filter((next) => token ? featureMatches(next[next.length - 1].feature, token) : true);
      return matchingNextFeatures;
    }
    function findGroupAndChild(feature) {
      let parent;
      let item = feature;
      while (item.$container) {
        if (isGroup$1(item.$container)) {
          parent = item.$container;
          break;
        } else if (isAbstractElement(item.$container)) {
          item = item.$container;
        } else {
          break;
        }
      }
      if (parent) {
        return { group: parent, child: item };
      }
      return {
        group: void 0,
        // Even if there is no group, return the feature parent if it is an assignment
        // We need this later to handle the cardinality of the feature correctly
        child: getContainerOfType(feature, isAssignment) ?? feature
      };
    }
    function getAbstractElementParent(element) {
      const parent = element.$container;
      const assignment = getContainerOfType(parent, isAssignment);
      if (assignment) {
        return getAbstractElementParent(assignment);
      } else {
        if (parent && isAbstractElement(parent)) {
          return parent;
        }
      }
      return void 0;
    }
    function featureMatches(feature, token) {
      if (isKeyword(feature)) {
        const content = feature.value;
        return content === token.tokenType.name;
      } else if (isRuleCall(feature)) {
        return ruleMatches(feature.rule.ref, token);
      } else if (isCrossReference(feature)) {
        const crossRefTerminal = getCrossReferenceTerminal(feature);
        if (crossRefTerminal) {
          return featureMatches(crossRefTerminal, token);
        }
      }
      return false;
    }
    function ruleMatches(rule, token) {
      if (isParserRule(rule)) {
        const ruleFeatures = findFirstFeatures(rule.definition);
        return ruleFeatures.some((e) => featureMatches(e[e.length - 1].feature, token));
      } else if (isTerminalRule(rule)) {
        return terminalRegex(rule).test(token.image);
      } else {
        return false;
      }
    }
    function mergeCompletionProviderOptions(options) {
      const triggerCharacters = Array.from(new Set(options.flatMap((option2) => option2?.triggerCharacters ?? [])));
      const allCommitCharacters = Array.from(new Set(options.flatMap((option2) => option2?.allCommitCharacters ?? [])));
      return {
        triggerCharacters: triggerCharacters.length > 0 ? triggerCharacters : void 0,
        allCommitCharacters: allCommitCharacters.length > 0 ? allCommitCharacters : void 0
      };
    }
    class DefaultCompletionProvider {
      constructor(services) {
        this.scopeProvider = services.references.ScopeProvider;
        this.grammar = services.Grammar;
        this.completionParser = services.parser.CompletionParser;
        this.nameProvider = services.references.NameProvider;
        this.lexer = services.parser.Lexer;
        this.nodeKindProvider = services.shared.lsp.NodeKindProvider;
        this.fuzzyMatcher = services.shared.lsp.FuzzyMatcher;
        this.grammarConfig = services.parser.GrammarConfig;
        this.astReflection = services.shared.AstReflection;
        this.documentationProvider = services.documentation.DocumentationProvider;
      }
      async getCompletion(document, params, _cancelToken) {
        const items = [];
        const contexts = this.buildContexts(document, params.position);
        const acceptor = (context, value) => {
          const completionItem = this.fillCompletionItem(context, value);
          if (completionItem) {
            items.push(completionItem);
          }
        };
        const distinctionFunction = (element) => {
          if (isKeyword(element.feature)) {
            return element.feature.value;
          } else {
            return element.feature;
          }
        };
        const completedFeatures = [];
        for (const context of contexts) {
          await Promise.all(stream(context.features).distinct(distinctionFunction).exclude(completedFeatures).map((e) => this.completionFor(context, e, acceptor)));
          completedFeatures.push(...context.features);
          if (!this.continueCompletion(items)) {
            break;
          }
        }
        return mainExports$1.CompletionList.create(this.deduplicateItems(items), true);
      }
      /**
       * The completion algorithm could yield the same reference/keyword multiple times.
       *
       * This methods deduplicates these items afterwards before returning to the client.
       * Unique items are identified as a combination of `kind`, `label` and `detail`.
       */
      deduplicateItems(items) {
        return stream(items).distinct((item) => `${item.kind}_${item.label}_${item.detail}`).toArray();
      }
      findFeaturesAt(document, offset) {
        const text = document.getText({
          start: mainExports$1.Position.create(0, 0),
          end: document.positionAt(offset)
        });
        const parserResult = this.completionParser.parse(text);
        const tokens2 = parserResult.tokens;
        if (parserResult.tokenIndex === 0) {
          const parserRule = getEntryRule(this.grammar);
          const syntheticEntryRuleCall = this.buildSyntheticEntryRuleCall(parserRule);
          return findNextFeatures([[syntheticEntryRuleCall]], tokens2);
        }
        const leftoverTokens = [...tokens2].splice(parserResult.tokenIndex);
        const features = findNextFeatures([parserResult.elementStack.map((feature) => ({ feature }))], leftoverTokens);
        return features;
      }
      buildSyntheticEntryRuleCall(rule) {
        const start = {
          $type: "Group",
          $container: void 0,
          elements: []
        };
        const startNext = {
          feature: start
        };
        const ruleCall = {
          $type: "RuleCall",
          $container: void 0,
          rule: {
            ref: rule,
            $refText: rule.name
          },
          arguments: []
        };
        const group = {
          $type: "Group",
          $container: void 0,
          elements: [
            start,
            ruleCall
          ]
        };
        start.$container = group;
        ruleCall.$container = group;
        return startNext;
      }
      *buildContexts(document, position) {
        const cst = document.parseResult.value.$cstNode;
        if (!cst) {
          return;
        }
        const textDocument = document.textDocument;
        const text = textDocument.getText();
        const offset = textDocument.offsetAt(position);
        const partialContext = {
          document,
          textDocument,
          offset,
          position
        };
        const dataTypeRuleOffsets = this.findDataTypeRuleStart(cst, offset);
        if (dataTypeRuleOffsets) {
          const [ruleStart, ruleEnd] = dataTypeRuleOffsets;
          const parentNode = findLeafNodeBeforeOffset(cst, ruleStart)?.astNode;
          yield {
            ...partialContext,
            node: parentNode,
            tokenOffset: ruleStart,
            tokenEndOffset: ruleEnd,
            features: this.findFeaturesAt(textDocument, ruleStart)
          };
        }
        const { nextTokenStart, nextTokenEnd, previousTokenStart, previousTokenEnd } = this.backtrackToAnyToken(text, offset);
        let astNodeOffset = nextTokenStart;
        if (offset <= nextTokenStart && previousTokenStart !== void 0) {
          astNodeOffset = previousTokenStart;
        }
        const astNode = findLeafNodeBeforeOffset(cst, astNodeOffset)?.astNode;
        let performNextCompletion = true;
        if (previousTokenStart !== void 0 && previousTokenEnd !== void 0 && previousTokenEnd === offset) {
          yield {
            ...partialContext,
            node: astNode,
            tokenOffset: previousTokenStart,
            tokenEndOffset: previousTokenEnd,
            features: this.findFeaturesAt(textDocument, previousTokenStart)
          };
          performNextCompletion = this.performNextTokenCompletion(document, text.substring(previousTokenStart, previousTokenEnd), previousTokenStart, previousTokenEnd);
          if (performNextCompletion) {
            yield {
              ...partialContext,
              node: astNode,
              tokenOffset: previousTokenEnd,
              tokenEndOffset: previousTokenEnd,
              features: this.findFeaturesAt(textDocument, previousTokenEnd)
            };
          }
        }
        if (!astNode) {
          const parserRule = getEntryRule(this.grammar);
          if (!parserRule) {
            throw new Error("Missing entry parser rule");
          }
          yield {
            ...partialContext,
            tokenOffset: nextTokenStart,
            tokenEndOffset: nextTokenEnd,
            features: findFirstFeatures(parserRule.definition).map((f) => f[f.length - 1])
          };
        } else if (performNextCompletion) {
          yield {
            ...partialContext,
            node: astNode,
            tokenOffset: nextTokenStart,
            tokenEndOffset: nextTokenEnd,
            features: this.findFeaturesAt(textDocument, nextTokenStart)
          };
        }
      }
      performNextTokenCompletion(document, text, _offset, _end) {
        return new RegExp("\\P{L}$", "u").test(text);
      }
      findDataTypeRuleStart(cst, offset) {
        const containerNode = findDeclarationNodeAtOffset(cst, offset, this.grammarConfig.nameRegexp);
        if (!containerNode) {
          return void 0;
        }
        const fullNode = getDatatypeNode(containerNode);
        if (fullNode) {
          return [fullNode.offset, fullNode.end];
        }
        return void 0;
      }
      /**
       * Indicates whether the completion should continue to process the next completion context.
       *
       * The default implementation continues the completion only if there are currently no proposed completion items.
       */
      continueCompletion(items) {
        return items.length === 0;
      }
      /**
       * This method returns two sets of token offset information.
       *
       * The `nextToken*` offsets are related to the token at the cursor position.
       * If there is none, both offsets are simply set to `offset`.
       *
       * The `previousToken*` offsets are related to the last token before the current token at the cursor position.
       * They are `undefined`, if there is no token before the cursor position.
       */
      backtrackToAnyToken(text, offset) {
        const tokens2 = this.lexer.tokenize(text).tokens;
        if (tokens2.length === 0) {
          return {
            nextTokenStart: offset,
            nextTokenEnd: offset
          };
        }
        let previousToken;
        for (const token of tokens2) {
          if (token.startOffset >= offset) {
            return {
              nextTokenStart: offset,
              nextTokenEnd: offset,
              previousTokenStart: previousToken ? previousToken.startOffset : void 0,
              previousTokenEnd: previousToken ? previousToken.endOffset + 1 : void 0
            };
          }
          if (token.endOffset >= offset) {
            return {
              nextTokenStart: token.startOffset,
              nextTokenEnd: token.endOffset + 1,
              previousTokenStart: previousToken ? previousToken.startOffset : void 0,
              previousTokenEnd: previousToken ? previousToken.endOffset + 1 : void 0
            };
          }
          previousToken = token;
        }
        return {
          nextTokenStart: offset,
          nextTokenEnd: offset,
          previousTokenStart: previousToken ? previousToken.startOffset : void 0,
          previousTokenEnd: previousToken ? previousToken.endOffset + 1 : void 0
        };
      }
      completionFor(context, next, acceptor) {
        if (isKeyword(next.feature)) {
          return this.completionForKeyword(context, next.feature, acceptor);
        } else if (isCrossReference(next.feature) && context.node) {
          return this.completionForCrossReference(context, next, acceptor);
        }
      }
      completionForCrossReference(context, next, acceptor) {
        const assignment = getContainerOfType(next.feature, isAssignment);
        let node2 = context.node;
        if (assignment && node2) {
          if (next.type) {
            node2 = {
              $type: next.type,
              $container: node2,
              $containerProperty: next.property
            };
            assignMandatoryProperties(this.astReflection, node2);
          }
          let reference;
          if (next.feature.isMulti) {
            reference = {
              $refText: "",
              items: []
            };
          } else {
            reference = {
              $refText: "",
              ref: void 0
            };
          }
          const refInfo = {
            reference,
            container: node2,
            property: assignment.feature
          };
          try {
            for (const candidate of this.getReferenceCandidates(refInfo, context)) {
              acceptor(context, this.createReferenceCompletionItem(candidate, refInfo, context));
            }
          } catch (err) {
            console.error(err);
          }
        }
      }
      /**
       * Override this method to change how the stream of candidates is determined for a reference.
       * This way completion-specific modifications and refinements can be added to the proposals computation
       *  beyond the rules being implemented in the scope provider, e.g. filtering.
       *
       * @param refInfo Information about the reference for which the candidates are requested.
       * @param _context Information about the completion request including document, cursor position, token under cursor, etc.
       * @returns A stream of all elements being valid for the given reference.
       */
      getReferenceCandidates(refInfo, _context) {
        return this.scopeProvider.getScope(refInfo).getAllElements();
      }
      /**
       * Override this method to change how reference completion items are created.
       *
       * To change the `kind` of a completion item, override the `NodeKindProvider` service instead.
       * To change the `documentation`, override the `DocumentationProvider` service instead.
       *
       * @param nodeDescription The description of a reference candidate
       * @param _refInfo Information about the reference for which the candidate is proposed
       * @param _context The completion context
       * @returns A partial completion item
       */
      createReferenceCompletionItem(nodeDescription, _refInfo, _context) {
        const kind = this.nodeKindProvider.getCompletionItemKind(nodeDescription);
        const documentation = this.getReferenceDocumentation(nodeDescription);
        return {
          nodeDescription,
          kind,
          documentation,
          detail: nodeDescription.type,
          sortText: "0"
        };
      }
      getReferenceDocumentation(nodeDescription) {
        if (!nodeDescription.node) {
          return void 0;
        }
        const documentationText = this.documentationProvider.getDocumentation(nodeDescription.node);
        if (!documentationText) {
          return void 0;
        }
        return { kind: "markdown", value: documentationText };
      }
      completionForKeyword(context, keyword, acceptor) {
        if (!this.filterKeyword(context, keyword)) {
          return;
        }
        acceptor(context, {
          label: keyword.value,
          kind: this.getKeywordCompletionItemKind(keyword),
          detail: "Keyword",
          sortText: "1"
        });
      }
      getKeywordCompletionItemKind(_keyword) {
        return mainExports$1.CompletionItemKind.Keyword;
      }
      filterKeyword(context, keyword) {
        return new RegExp("\\p{L}", "u").test(keyword.value);
      }
      fillCompletionItem(context, item) {
        let label;
        if (typeof item.label === "string") {
          label = item.label;
        } else if ("node" in item) {
          const name = this.nameProvider.getName(item.node);
          if (!name) {
            return void 0;
          }
          label = name;
        } else if ("nodeDescription" in item) {
          label = item.nodeDescription.name;
        } else {
          return void 0;
        }
        let insertText;
        if (typeof item.textEdit?.newText === "string") {
          insertText = item.textEdit.newText;
        } else if (typeof item.insertText === "string") {
          insertText = item.insertText;
        } else {
          insertText = label;
        }
        const textEdit = item.textEdit ?? this.buildCompletionTextEdit(context, label, insertText);
        if (!textEdit) {
          return void 0;
        }
        const completionItem = {
          additionalTextEdits: item.additionalTextEdits,
          command: item.command,
          commitCharacters: item.commitCharacters,
          data: item.data,
          detail: item.detail,
          documentation: item.documentation,
          filterText: item.filterText,
          insertText: item.insertText,
          insertTextFormat: item.insertTextFormat,
          insertTextMode: item.insertTextMode,
          kind: item.kind,
          labelDetails: item.labelDetails,
          preselect: item.preselect,
          sortText: item.sortText,
          tags: item.tags,
          textEditText: item.textEditText,
          textEdit,
          label
        };
        return completionItem;
      }
      buildCompletionTextEdit(context, label, newText) {
        const content = context.textDocument.getText();
        const identifier = content.substring(context.tokenOffset, context.offset);
        if (this.fuzzyMatcher.match(identifier, label)) {
          const start = context.textDocument.positionAt(context.tokenOffset);
          const end = context.position;
          return {
            newText,
            range: {
              start,
              end
            }
          };
        } else {
          return void 0;
        }
      }
    }
    var LIB;
    (() => {
      var t = { 975: (t2) => {
        function e2(t3) {
          if ("string" != typeof t3) throw new TypeError("Path must be a string. Received " + JSON.stringify(t3));
        }
        function r2(t3, e3) {
          for (var r3, n3 = "", i2 = 0, o2 = -1, s2 = 0, h2 = 0; h2 <= t3.length; ++h2) {
            if (h2 < t3.length) r3 = t3.charCodeAt(h2);
            else {
              if (47 === r3) break;
              r3 = 47;
            }
            if (47 === r3) {
              if (o2 === h2 - 1 || 1 === s2) ;
              else if (o2 !== h2 - 1 && 2 === s2) {
                if (n3.length < 2 || 2 !== i2 || 46 !== n3.charCodeAt(n3.length - 1) || 46 !== n3.charCodeAt(n3.length - 2)) {
                  if (n3.length > 2) {
                    var a3 = n3.lastIndexOf("/");
                    if (a3 !== n3.length - 1) {
                      -1 === a3 ? (n3 = "", i2 = 0) : i2 = (n3 = n3.slice(0, a3)).length - 1 - n3.lastIndexOf("/"), o2 = h2, s2 = 0;
                      continue;
                    }
                  } else if (2 === n3.length || 1 === n3.length) {
                    n3 = "", i2 = 0, o2 = h2, s2 = 0;
                    continue;
                  }
                }
                e3 && (n3.length > 0 ? n3 += "/.." : n3 = "..", i2 = 2);
              } else n3.length > 0 ? n3 += "/" + t3.slice(o2 + 1, h2) : n3 = t3.slice(o2 + 1, h2), i2 = h2 - o2 - 1;
              o2 = h2, s2 = 0;
            } else 46 === r3 && -1 !== s2 ? ++s2 : s2 = -1;
          }
          return n3;
        }
        var n2 = { resolve: function() {
          for (var t3, n3 = "", i2 = false, o2 = arguments.length - 1; o2 >= -1 && !i2; o2--) {
            var s2;
            o2 >= 0 ? s2 = arguments[o2] : (void 0 === t3 && (t3 = process.cwd()), s2 = t3), e2(s2), 0 !== s2.length && (n3 = s2 + "/" + n3, i2 = 47 === s2.charCodeAt(0));
          }
          return n3 = r2(n3, !i2), i2 ? n3.length > 0 ? "/" + n3 : "/" : n3.length > 0 ? n3 : ".";
        }, normalize: function(t3) {
          if (e2(t3), 0 === t3.length) return ".";
          var n3 = 47 === t3.charCodeAt(0), i2 = 47 === t3.charCodeAt(t3.length - 1);
          return 0 !== (t3 = r2(t3, !n3)).length || n3 || (t3 = "."), t3.length > 0 && i2 && (t3 += "/"), n3 ? "/" + t3 : t3;
        }, isAbsolute: function(t3) {
          return e2(t3), t3.length > 0 && 47 === t3.charCodeAt(0);
        }, join: function() {
          if (0 === arguments.length) return ".";
          for (var t3, r3 = 0; r3 < arguments.length; ++r3) {
            var i2 = arguments[r3];
            e2(i2), i2.length > 0 && (void 0 === t3 ? t3 = i2 : t3 += "/" + i2);
          }
          return void 0 === t3 ? "." : n2.normalize(t3);
        }, relative: function(t3, r3) {
          if (e2(t3), e2(r3), t3 === r3) return "";
          if ((t3 = n2.resolve(t3)) === (r3 = n2.resolve(r3))) return "";
          for (var i2 = 1; i2 < t3.length && 47 === t3.charCodeAt(i2); ++i2) ;
          for (var o2 = t3.length, s2 = o2 - i2, h2 = 1; h2 < r3.length && 47 === r3.charCodeAt(h2); ++h2) ;
          for (var a3 = r3.length - h2, c2 = s2 < a3 ? s2 : a3, f2 = -1, u2 = 0; u2 <= c2; ++u2) {
            if (u2 === c2) {
              if (a3 > c2) {
                if (47 === r3.charCodeAt(h2 + u2)) return r3.slice(h2 + u2 + 1);
                if (0 === u2) return r3.slice(h2 + u2);
              } else s2 > c2 && (47 === t3.charCodeAt(i2 + u2) ? f2 = u2 : 0 === u2 && (f2 = 0));
              break;
            }
            var l2 = t3.charCodeAt(i2 + u2);
            if (l2 !== r3.charCodeAt(h2 + u2)) break;
            47 === l2 && (f2 = u2);
          }
          var g2 = "";
          for (u2 = i2 + f2 + 1; u2 <= o2; ++u2) u2 !== o2 && 47 !== t3.charCodeAt(u2) || (0 === g2.length ? g2 += ".." : g2 += "/..");
          return g2.length > 0 ? g2 + r3.slice(h2 + f2) : (h2 += f2, 47 === r3.charCodeAt(h2) && ++h2, r3.slice(h2));
        }, _makeLong: function(t3) {
          return t3;
        }, dirname: function(t3) {
          if (e2(t3), 0 === t3.length) return ".";
          for (var r3 = t3.charCodeAt(0), n3 = 47 === r3, i2 = -1, o2 = true, s2 = t3.length - 1; s2 >= 1; --s2) if (47 === (r3 = t3.charCodeAt(s2))) {
            if (!o2) {
              i2 = s2;
              break;
            }
          } else o2 = false;
          return -1 === i2 ? n3 ? "/" : "." : n3 && 1 === i2 ? "//" : t3.slice(0, i2);
        }, basename: function(t3, r3) {
          if (void 0 !== r3 && "string" != typeof r3) throw new TypeError('"ext" argument must be a string');
          e2(t3);
          var n3, i2 = 0, o2 = -1, s2 = true;
          if (void 0 !== r3 && r3.length > 0 && r3.length <= t3.length) {
            if (r3.length === t3.length && r3 === t3) return "";
            var h2 = r3.length - 1, a3 = -1;
            for (n3 = t3.length - 1; n3 >= 0; --n3) {
              var c2 = t3.charCodeAt(n3);
              if (47 === c2) {
                if (!s2) {
                  i2 = n3 + 1;
                  break;
                }
              } else -1 === a3 && (s2 = false, a3 = n3 + 1), h2 >= 0 && (c2 === r3.charCodeAt(h2) ? -1 == --h2 && (o2 = n3) : (h2 = -1, o2 = a3));
            }
            return i2 === o2 ? o2 = a3 : -1 === o2 && (o2 = t3.length), t3.slice(i2, o2);
          }
          for (n3 = t3.length - 1; n3 >= 0; --n3) if (47 === t3.charCodeAt(n3)) {
            if (!s2) {
              i2 = n3 + 1;
              break;
            }
          } else -1 === o2 && (s2 = false, o2 = n3 + 1);
          return -1 === o2 ? "" : t3.slice(i2, o2);
        }, extname: function(t3) {
          e2(t3);
          for (var r3 = -1, n3 = 0, i2 = -1, o2 = true, s2 = 0, h2 = t3.length - 1; h2 >= 0; --h2) {
            var a3 = t3.charCodeAt(h2);
            if (47 !== a3) -1 === i2 && (o2 = false, i2 = h2 + 1), 46 === a3 ? -1 === r3 ? r3 = h2 : 1 !== s2 && (s2 = 1) : -1 !== r3 && (s2 = -1);
            else if (!o2) {
              n3 = h2 + 1;
              break;
            }
          }
          return -1 === r3 || -1 === i2 || 0 === s2 || 1 === s2 && r3 === i2 - 1 && r3 === n3 + 1 ? "" : t3.slice(r3, i2);
        }, format: function(t3) {
          if (null === t3 || "object" != typeof t3) throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof t3);
          return (function(t4, e3) {
            var r3 = e3.dir || e3.root, n3 = e3.base || (e3.name || "") + (e3.ext || "");
            return r3 ? r3 === e3.root ? r3 + n3 : r3 + "/" + n3 : n3;
          })(0, t3);
        }, parse: function(t3) {
          e2(t3);
          var r3 = { root: "", dir: "", base: "", ext: "", name: "" };
          if (0 === t3.length) return r3;
          var n3, i2 = t3.charCodeAt(0), o2 = 47 === i2;
          o2 ? (r3.root = "/", n3 = 1) : n3 = 0;
          for (var s2 = -1, h2 = 0, a3 = -1, c2 = true, f2 = t3.length - 1, u2 = 0; f2 >= n3; --f2) if (47 !== (i2 = t3.charCodeAt(f2))) -1 === a3 && (c2 = false, a3 = f2 + 1), 46 === i2 ? -1 === s2 ? s2 = f2 : 1 !== u2 && (u2 = 1) : -1 !== s2 && (u2 = -1);
          else if (!c2) {
            h2 = f2 + 1;
            break;
          }
          return -1 === s2 || -1 === a3 || 0 === u2 || 1 === u2 && s2 === a3 - 1 && s2 === h2 + 1 ? -1 !== a3 && (r3.base = r3.name = 0 === h2 && o2 ? t3.slice(1, a3) : t3.slice(h2, a3)) : (0 === h2 && o2 ? (r3.name = t3.slice(1, s2), r3.base = t3.slice(1, a3)) : (r3.name = t3.slice(h2, s2), r3.base = t3.slice(h2, a3)), r3.ext = t3.slice(s2, a3)), h2 > 0 ? r3.dir = t3.slice(0, h2 - 1) : o2 && (r3.dir = "/"), r3;
        }, sep: "/", delimiter: ":", win32: null, posix: null };
        n2.posix = n2, t2.exports = n2;
      } }, e = {};
      function r(n2) {
        var i2 = e[n2];
        if (void 0 !== i2) return i2.exports;
        var o2 = e[n2] = { exports: {} };
        return t[n2](o2, o2.exports, r), o2.exports;
      }
      r.d = (t2, e2) => {
        for (var n2 in e2) r.o(e2, n2) && !r.o(t2, n2) && Object.defineProperty(t2, n2, { enumerable: true, get: e2[n2] });
      }, r.o = (t2, e2) => Object.prototype.hasOwnProperty.call(t2, e2), r.r = (t2) => {
        "undefined" != typeof Symbol && Symbol.toStringTag && Object.defineProperty(t2, Symbol.toStringTag, { value: "Module" }), Object.defineProperty(t2, "__esModule", { value: true });
      };
      var n = {};
      let i;
      if (r.r(n), r.d(n, { URI: () => l, Utils: () => I }), "object" == typeof process) i = "win32" === process.platform;
      else if ("object" == typeof navigator) {
        let t2 = navigator.userAgent;
        i = t2.indexOf("Windows") >= 0;
      }
      const o = /^\w[\w\d+.-]*$/, s = /^\//, h = /^\/\//;
      function a2(t2, e2) {
        if (!t2.scheme && e2) throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${t2.authority}", path: "${t2.path}", query: "${t2.query}", fragment: "${t2.fragment}"}`);
        if (t2.scheme && !o.test(t2.scheme)) throw new Error("[UriError]: Scheme contains illegal characters.");
        if (t2.path) {
          if (t2.authority) {
            if (!s.test(t2.path)) throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character');
          } else if (h.test(t2.path)) throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")');
        }
      }
      const c = "", f = "/", u = /^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
      class l {
        static isUri(t2) {
          return t2 instanceof l || !!t2 && "string" == typeof t2.authority && "string" == typeof t2.fragment && "string" == typeof t2.path && "string" == typeof t2.query && "string" == typeof t2.scheme && "string" == typeof t2.fsPath && "function" == typeof t2.with && "function" == typeof t2.toString;
        }
        scheme;
        authority;
        path;
        query;
        fragment;
        constructor(t2, e2, r2, n2, i2, o2 = false) {
          "object" == typeof t2 ? (this.scheme = t2.scheme || c, this.authority = t2.authority || c, this.path = t2.path || c, this.query = t2.query || c, this.fragment = t2.fragment || c) : (this.scheme = /* @__PURE__ */ (function(t3, e3) {
            return t3 || e3 ? t3 : "file";
          })(t2, o2), this.authority = e2 || c, this.path = (function(t3, e3) {
            switch (t3) {
              case "https":
              case "http":
              case "file":
                e3 ? e3[0] !== f && (e3 = f + e3) : e3 = f;
            }
            return e3;
          })(this.scheme, r2 || c), this.query = n2 || c, this.fragment = i2 || c, a2(this, o2));
        }
        get fsPath() {
          return v(this);
        }
        with(t2) {
          if (!t2) return this;
          let { scheme: e2, authority: r2, path: n2, query: i2, fragment: o2 } = t2;
          return void 0 === e2 ? e2 = this.scheme : null === e2 && (e2 = c), void 0 === r2 ? r2 = this.authority : null === r2 && (r2 = c), void 0 === n2 ? n2 = this.path : null === n2 && (n2 = c), void 0 === i2 ? i2 = this.query : null === i2 && (i2 = c), void 0 === o2 ? o2 = this.fragment : null === o2 && (o2 = c), e2 === this.scheme && r2 === this.authority && n2 === this.path && i2 === this.query && o2 === this.fragment ? this : new d(e2, r2, n2, i2, o2);
        }
        static parse(t2, e2 = false) {
          const r2 = u.exec(t2);
          return r2 ? new d(r2[2] || c, w(r2[4] || c), w(r2[5] || c), w(r2[7] || c), w(r2[9] || c), e2) : new d(c, c, c, c, c);
        }
        static file(t2) {
          let e2 = c;
          if (i && (t2 = t2.replace(/\\/g, f)), t2[0] === f && t2[1] === f) {
            const r2 = t2.indexOf(f, 2);
            -1 === r2 ? (e2 = t2.substring(2), t2 = f) : (e2 = t2.substring(2, r2), t2 = t2.substring(r2) || f);
          }
          return new d("file", e2, t2, c, c);
        }
        static from(t2) {
          const e2 = new d(t2.scheme, t2.authority, t2.path, t2.query, t2.fragment);
          return a2(e2, true), e2;
        }
        toString(t2 = false) {
          return b(this, t2);
        }
        toJSON() {
          return this;
        }
        static revive(t2) {
          if (t2) {
            if (t2 instanceof l) return t2;
            {
              const e2 = new d(t2);
              return e2._formatted = t2.external, e2._fsPath = t2._sep === g ? t2.fsPath : null, e2;
            }
          }
          return t2;
        }
      }
      const g = i ? 1 : void 0;
      class d extends l {
        _formatted = null;
        _fsPath = null;
        get fsPath() {
          return this._fsPath || (this._fsPath = v(this)), this._fsPath;
        }
        toString(t2 = false) {
          return t2 ? b(this, true) : (this._formatted || (this._formatted = b(this, false)), this._formatted);
        }
        toJSON() {
          const t2 = { $mid: 1 };
          return this._fsPath && (t2.fsPath = this._fsPath, t2._sep = g), this._formatted && (t2.external = this._formatted), this.path && (t2.path = this.path), this.scheme && (t2.scheme = this.scheme), this.authority && (t2.authority = this.authority), this.query && (t2.query = this.query), this.fragment && (t2.fragment = this.fragment), t2;
        }
      }
      const p = { 58: "%3A", 47: "%2F", 63: "%3F", 35: "%23", 91: "%5B", 93: "%5D", 64: "%40", 33: "%21", 36: "%24", 38: "%26", 39: "%27", 40: "%28", 41: "%29", 42: "%2A", 43: "%2B", 44: "%2C", 59: "%3B", 61: "%3D", 32: "%20" };
      function m(t2, e2, r2) {
        let n2, i2 = -1;
        for (let o2 = 0; o2 < t2.length; o2++) {
          const s2 = t2.charCodeAt(o2);
          if (s2 >= 97 && s2 <= 122 || s2 >= 65 && s2 <= 90 || s2 >= 48 && s2 <= 57 || 45 === s2 || 46 === s2 || 95 === s2 || 126 === s2 || e2 && 47 === s2 || r2 && 91 === s2 || r2 && 93 === s2 || r2 && 58 === s2) -1 !== i2 && (n2 += encodeURIComponent(t2.substring(i2, o2)), i2 = -1), void 0 !== n2 && (n2 += t2.charAt(o2));
          else {
            void 0 === n2 && (n2 = t2.substr(0, o2));
            const e3 = p[s2];
            void 0 !== e3 ? (-1 !== i2 && (n2 += encodeURIComponent(t2.substring(i2, o2)), i2 = -1), n2 += e3) : -1 === i2 && (i2 = o2);
          }
        }
        return -1 !== i2 && (n2 += encodeURIComponent(t2.substring(i2))), void 0 !== n2 ? n2 : t2;
      }
      function y(t2) {
        let e2;
        for (let r2 = 0; r2 < t2.length; r2++) {
          const n2 = t2.charCodeAt(r2);
          35 === n2 || 63 === n2 ? (void 0 === e2 && (e2 = t2.substr(0, r2)), e2 += p[n2]) : void 0 !== e2 && (e2 += t2[r2]);
        }
        return void 0 !== e2 ? e2 : t2;
      }
      function v(t2, e2) {
        let r2;
        return r2 = t2.authority && t2.path.length > 1 && "file" === t2.scheme ? `//${t2.authority}${t2.path}` : 47 === t2.path.charCodeAt(0) && (t2.path.charCodeAt(1) >= 65 && t2.path.charCodeAt(1) <= 90 || t2.path.charCodeAt(1) >= 97 && t2.path.charCodeAt(1) <= 122) && 58 === t2.path.charCodeAt(2) ? t2.path[1].toLowerCase() + t2.path.substr(2) : t2.path, i && (r2 = r2.replace(/\//g, "\\")), r2;
      }
      function b(t2, e2) {
        const r2 = e2 ? y : m;
        let n2 = "", { scheme: i2, authority: o2, path: s2, query: h2, fragment: a3 } = t2;
        if (i2 && (n2 += i2, n2 += ":"), (o2 || "file" === i2) && (n2 += f, n2 += f), o2) {
          let t3 = o2.indexOf("@");
          if (-1 !== t3) {
            const e3 = o2.substr(0, t3);
            o2 = o2.substr(t3 + 1), t3 = e3.lastIndexOf(":"), -1 === t3 ? n2 += r2(e3, false, false) : (n2 += r2(e3.substr(0, t3), false, false), n2 += ":", n2 += r2(e3.substr(t3 + 1), false, true)), n2 += "@";
          }
          o2 = o2.toLowerCase(), t3 = o2.lastIndexOf(":"), -1 === t3 ? n2 += r2(o2, false, true) : (n2 += r2(o2.substr(0, t3), false, true), n2 += o2.substr(t3));
        }
        if (s2) {
          if (s2.length >= 3 && 47 === s2.charCodeAt(0) && 58 === s2.charCodeAt(2)) {
            const t3 = s2.charCodeAt(1);
            t3 >= 65 && t3 <= 90 && (s2 = `/${String.fromCharCode(t3 + 32)}:${s2.substr(3)}`);
          } else if (s2.length >= 2 && 58 === s2.charCodeAt(1)) {
            const t3 = s2.charCodeAt(0);
            t3 >= 65 && t3 <= 90 && (s2 = `${String.fromCharCode(t3 + 32)}:${s2.substr(2)}`);
          }
          n2 += r2(s2, true, false);
        }
        return h2 && (n2 += "?", n2 += r2(h2, false, false)), a3 && (n2 += "#", n2 += e2 ? a3 : m(a3, false, false)), n2;
      }
      function C(t2) {
        try {
          return decodeURIComponent(t2);
        } catch {
          return t2.length > 3 ? t2.substr(0, 3) + C(t2.substr(3)) : t2;
        }
      }
      const A2 = /(%[0-9A-Za-z][0-9A-Za-z])+/g;
      function w(t2) {
        return t2.match(A2) ? t2.replace(A2, ((t3) => C(t3))) : t2;
      }
      var x = r(975);
      const P = x.posix || x, _2 = "/";
      var I;
      !(function(t2) {
        t2.joinPath = function(t3, ...e2) {
          return t3.with({ path: P.join(t3.path, ...e2) });
        }, t2.resolvePath = function(t3, ...e2) {
          let r2 = t3.path, n2 = false;
          r2[0] !== _2 && (r2 = _2 + r2, n2 = true);
          let i2 = P.resolve(r2, ...e2);
          return n2 && i2[0] === _2 && !t3.authority && (i2 = i2.substring(1)), t3.with({ path: i2 });
        }, t2.dirname = function(t3) {
          if (0 === t3.path.length || t3.path === _2) return t3;
          let e2 = P.dirname(t3.path);
          return 1 === e2.length && 46 === e2.charCodeAt(0) && (e2 = ""), t3.with({ path: e2 });
        }, t2.basename = function(t3) {
          return P.basename(t3.path);
        }, t2.extname = function(t3) {
          return P.extname(t3.path);
        };
      })(I || (I = {})), LIB = n;
    })();
    const { URI: URI$1, Utils } = LIB;
    var UriUtils;
    (function(UriUtils2) {
      UriUtils2.basename = Utils.basename;
      UriUtils2.dirname = Utils.dirname;
      UriUtils2.extname = Utils.extname;
      UriUtils2.joinPath = Utils.joinPath;
      UriUtils2.resolvePath = Utils.resolvePath;
      const isWindows = typeof process === "object" && process?.platform === "win32";
      function equals(a2, b) {
        return a2?.toString() === b?.toString();
      }
      UriUtils2.equals = equals;
      function relative(from, to) {
        const fromPath = typeof from === "string" ? URI$1.parse(from).path : from.path;
        const toPath = typeof to === "string" ? URI$1.parse(to).path : to.path;
        const fromParts = fromPath.split("/").filter((e) => e.length > 0);
        const toParts = toPath.split("/").filter((e) => e.length > 0);
        if (isWindows) {
          const upperCaseDriveLetter = /^[A-Z]:$/;
          if (fromParts[0] && upperCaseDriveLetter.test(fromParts[0])) {
            fromParts[0] = fromParts[0].toLowerCase();
          }
          if (toParts[0] && upperCaseDriveLetter.test(toParts[0])) {
            toParts[0] = toParts[0].toLowerCase();
          }
          if (fromParts[0] !== toParts[0]) {
            return toPath.substring(1);
          }
        }
        let i = 0;
        for (; i < fromParts.length; i++) {
          if (fromParts[i] !== toParts[i]) {
            break;
          }
        }
        const backPart = "../".repeat(fromParts.length - i);
        const toPart = toParts.slice(i).join("/");
        return backPart + toPart;
      }
      UriUtils2.relative = relative;
      function normalize(uri) {
        return URI$1.parse(uri.toString()).toString();
      }
      UriUtils2.normalize = normalize;
      function contains(parent, child) {
        let parentPath = typeof parent === "string" ? parent : parent.path;
        let childPath = typeof child === "string" ? child : child.path;
        if (childPath.charAt(childPath.length - 1) === "/") {
          childPath = childPath.slice(0, -1);
        }
        if (parentPath.charAt(parentPath.length - 1) === "/") {
          parentPath = parentPath.slice(0, -1);
        }
        if (childPath === parentPath) {
          return true;
        }
        if (childPath.length < parentPath.length) {
          return false;
        }
        if (childPath.charAt(parentPath.length) !== "/") {
          return false;
        }
        return childPath.startsWith(parentPath);
      }
      UriUtils2.contains = contains;
    })(UriUtils || (UriUtils = {}));
    class UriTrie {
      constructor() {
        this.root = { name: "", children: /* @__PURE__ */ new Map() };
      }
      normalizeUri(uri) {
        return UriUtils.normalize(uri);
      }
      clear() {
        this.root.children.clear();
      }
      insert(uri, element) {
        const node2 = this.getNode(this.normalizeUri(uri), true);
        node2.element = element;
      }
      delete(uri) {
        const nodeToDelete = this.getNode(this.normalizeUri(uri), false);
        if (nodeToDelete?.parent) {
          nodeToDelete.parent.children.delete(nodeToDelete.name);
        }
      }
      has(uri) {
        return this.getNode(this.normalizeUri(uri), false)?.element !== void 0;
      }
      hasNode(uri) {
        return this.getNode(this.normalizeUri(uri), false) !== void 0;
      }
      find(uri) {
        return this.getNode(this.normalizeUri(uri), false)?.element;
      }
      findNode(uri) {
        const uriString = this.normalizeUri(uri);
        const node2 = this.getNode(uriString, false);
        if (!node2) {
          return void 0;
        }
        return {
          name: node2.name,
          uri: UriUtils.joinPath(URI$1.parse(uriString), node2.name).toString(),
          element: node2.element
        };
      }
      findChildren(uri) {
        const uriString = this.normalizeUri(uri);
        const node2 = this.getNode(uriString, false);
        if (!node2) {
          return [];
        }
        return Array.from(node2.children.values()).map((child) => ({
          name: child.name,
          uri: UriUtils.joinPath(URI$1.parse(uriString), child.name).toString(),
          element: child.element
        }));
      }
      all() {
        return this.collectValues(this.root);
      }
      findAll(prefix) {
        const node2 = this.getNode(UriUtils.normalize(prefix), false);
        if (!node2) {
          return [];
        }
        return this.collectValues(node2);
      }
      getNode(uri, create) {
        const parts = uri.split("/");
        if (uri.charAt(uri.length - 1) === "/") {
          parts.pop();
        }
        let current = this.root;
        for (const part of parts) {
          let child = current.children.get(part);
          if (!child) {
            if (create) {
              child = {
                name: part,
                children: /* @__PURE__ */ new Map(),
                parent: current
              };
              current.children.set(part, child);
            } else {
              return void 0;
            }
          }
          current = child;
        }
        return current;
      }
      collectValues(node2) {
        const result = [];
        if (node2.element) {
          result.push(node2.element);
        }
        for (const child of node2.children.values()) {
          result.push(...this.collectValues(child));
        }
        return result;
      }
    }
    class DefaultDefinitionProvider {
      constructor(services) {
        this.nameProvider = services.references.NameProvider;
        this.references = services.references.References;
        this.grammarConfig = services.parser.GrammarConfig;
      }
      getDefinition(document, params, _cancelToken) {
        const rootNode = document.parseResult.value;
        if (rootNode.$cstNode) {
          const cst = rootNode.$cstNode;
          const sourceCstNode = findDeclarationNodeAtOffset(cst, document.textDocument.offsetAt(params.position), this.grammarConfig.nameRegexp);
          if (sourceCstNode) {
            return this.collectLocationLinks(sourceCstNode, params);
          }
        }
        return void 0;
      }
      collectLocationLinks(sourceCstNode, _params) {
        const goToLinks = this.findLinks(sourceCstNode);
        if (goToLinks.length > 0) {
          return goToLinks.map((link) => mainExports$1.LocationLink.create(link.targetDocument.textDocument.uri, (link.target.astNode.$cstNode ?? link.target).range, link.target.range, link.source.range));
        }
        return void 0;
      }
      findLinks(source) {
        const datatypeSourceNode = getDatatypeNode(source) ?? source;
        const targets = this.references.findDeclarationNodes(source);
        const links = [];
        for (const target of targets) {
          const targetDocument = getDocument(target.astNode);
          if (targets && targetDocument) {
            links.push({
              source: datatypeSourceNode,
              target,
              targetDocument
            });
          }
        }
        return links;
      }
    }
    function createGrammarConfig(services) {
      const rules = [];
      const grammar = services.Grammar;
      for (const rule of grammar.rules) {
        if (isTerminalRule(rule) && isCommentTerminal(rule) && isMultilineComment(terminalRegex(rule))) {
          rules.push(rule.name);
        }
      }
      return {
        multilineCommentRules: rules,
        nameRegexp: DefaultNameRegexp
      };
    }
    function PRINT_ERROR(msg) {
      if (console && console.error) {
        console.error(`Error: ${msg}`);
      }
    }
    function PRINT_WARNING(msg) {
      if (console && console.warn) {
        console.warn(`Warning: ${msg}`);
      }
    }
    function timer(func) {
      const start = (/* @__PURE__ */ new Date()).getTime();
      const val = func();
      const end = (/* @__PURE__ */ new Date()).getTime();
      const total = end - start;
      return { time: total, value: val };
    }
    function toFastProperties(toBecomeFast) {
      function FakeConstructor() {
      }
      FakeConstructor.prototype = toBecomeFast;
      const fakeInstance = new FakeConstructor();
      function fakeAccess() {
        return typeof fakeInstance.bar;
      }
      fakeAccess();
      fakeAccess();
      return toBecomeFast;
    }
    function tokenLabel$1(tokType) {
      if (hasTokenLabel$1(tokType)) {
        return tokType.LABEL;
      } else {
        return tokType.name;
      }
    }
    function hasTokenLabel$1(obj) {
      return typeof obj.LABEL === "string" && obj.LABEL !== "";
    }
    class AbstractProduction {
      get definition() {
        return this._definition;
      }
      set definition(value) {
        this._definition = value;
      }
      constructor(_definition) {
        this._definition = _definition;
      }
      accept(visitor2) {
        visitor2.visit(this);
        this.definition.forEach((prod) => {
          prod.accept(visitor2);
        });
      }
    }
    class NonTerminal extends AbstractProduction {
      constructor(options) {
        super([]);
        this.idx = 1;
        Object.assign(this, pickOnlyDefined(options));
      }
      set definition(definition) {
      }
      get definition() {
        if (this.referencedRule !== void 0) {
          return this.referencedRule.definition;
        }
        return [];
      }
      accept(visitor2) {
        visitor2.visit(this);
      }
    }
    class Rule extends AbstractProduction {
      constructor(options) {
        super(options.definition);
        this.orgText = "";
        Object.assign(this, pickOnlyDefined(options));
      }
    }
    class Alternative extends AbstractProduction {
      constructor(options) {
        super(options.definition);
        this.ignoreAmbiguities = false;
        Object.assign(this, pickOnlyDefined(options));
      }
    }
    class Option extends AbstractProduction {
      constructor(options) {
        super(options.definition);
        this.idx = 1;
        Object.assign(this, pickOnlyDefined(options));
      }
    }
    class RepetitionMandatory extends AbstractProduction {
      constructor(options) {
        super(options.definition);
        this.idx = 1;
        Object.assign(this, pickOnlyDefined(options));
      }
    }
    class RepetitionMandatoryWithSeparator extends AbstractProduction {
      constructor(options) {
        super(options.definition);
        this.idx = 1;
        Object.assign(this, pickOnlyDefined(options));
      }
    }
    class Repetition extends AbstractProduction {
      constructor(options) {
        super(options.definition);
        this.idx = 1;
        Object.assign(this, pickOnlyDefined(options));
      }
    }
    class RepetitionWithSeparator extends AbstractProduction {
      constructor(options) {
        super(options.definition);
        this.idx = 1;
        Object.assign(this, pickOnlyDefined(options));
      }
    }
    class Alternation extends AbstractProduction {
      get definition() {
        return this._definition;
      }
      set definition(value) {
        this._definition = value;
      }
      constructor(options) {
        super(options.definition);
        this.idx = 1;
        this.ignoreAmbiguities = false;
        this.hasPredicates = false;
        Object.assign(this, pickOnlyDefined(options));
      }
    }
    class Terminal {
      constructor(options) {
        this.idx = 1;
        Object.assign(this, pickOnlyDefined(options));
      }
      accept(visitor2) {
        visitor2.visit(this);
      }
    }
    function serializeGrammar(topRules) {
      return topRules.map(serializeProduction);
    }
    function serializeProduction(node2) {
      function convertDefinition(definition) {
        return definition.map(serializeProduction);
      }
      if (node2 instanceof NonTerminal) {
        const serializedNonTerminal = {
          type: "NonTerminal",
          name: node2.nonTerminalName,
          idx: node2.idx
        };
        if (typeof node2.label === "string") {
          serializedNonTerminal.label = node2.label;
        }
        return serializedNonTerminal;
      } else if (node2 instanceof Alternative) {
        return {
          type: "Alternative",
          definition: convertDefinition(node2.definition)
        };
      } else if (node2 instanceof Option) {
        return {
          type: "Option",
          idx: node2.idx,
          definition: convertDefinition(node2.definition)
        };
      } else if (node2 instanceof RepetitionMandatory) {
        return {
          type: "RepetitionMandatory",
          idx: node2.idx,
          definition: convertDefinition(node2.definition)
        };
      } else if (node2 instanceof RepetitionMandatoryWithSeparator) {
        return {
          type: "RepetitionMandatoryWithSeparator",
          idx: node2.idx,
          separator: serializeProduction(new Terminal({ terminalType: node2.separator })),
          definition: convertDefinition(node2.definition)
        };
      } else if (node2 instanceof RepetitionWithSeparator) {
        return {
          type: "RepetitionWithSeparator",
          idx: node2.idx,
          separator: serializeProduction(new Terminal({ terminalType: node2.separator })),
          definition: convertDefinition(node2.definition)
        };
      } else if (node2 instanceof Repetition) {
        return {
          type: "Repetition",
          idx: node2.idx,
          definition: convertDefinition(node2.definition)
        };
      } else if (node2 instanceof Alternation) {
        return {
          type: "Alternation",
          idx: node2.idx,
          definition: convertDefinition(node2.definition)
        };
      } else if (node2 instanceof Terminal) {
        const serializedTerminal = {
          type: "Terminal",
          name: node2.terminalType.name,
          label: tokenLabel$1(node2.terminalType),
          idx: node2.idx
        };
        if (typeof node2.label === "string") {
          serializedTerminal.terminalLabel = node2.label;
        }
        const pattern = node2.terminalType.PATTERN;
        if (node2.terminalType.PATTERN) {
          serializedTerminal.pattern = pattern instanceof RegExp ? pattern.source : pattern;
        }
        return serializedTerminal;
      } else if (node2 instanceof Rule) {
        return {
          type: "Rule",
          name: node2.name,
          orgText: node2.orgText,
          definition: convertDefinition(node2.definition)
        };
      } else {
        throw Error("non exhaustive match");
      }
    }
    function pickOnlyDefined(obj) {
      return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== void 0));
    }
    class GAstVisitor {
      visit(node2) {
        const nodeAny = node2;
        switch (nodeAny.constructor) {
          case NonTerminal:
            return this.visitNonTerminal(nodeAny);
          case Alternative:
            return this.visitAlternative(nodeAny);
          case Option:
            return this.visitOption(nodeAny);
          case RepetitionMandatory:
            return this.visitRepetitionMandatory(nodeAny);
          case RepetitionMandatoryWithSeparator:
            return this.visitRepetitionMandatoryWithSeparator(nodeAny);
          case RepetitionWithSeparator:
            return this.visitRepetitionWithSeparator(nodeAny);
          case Repetition:
            return this.visitRepetition(nodeAny);
          case Alternation:
            return this.visitAlternation(nodeAny);
          case Terminal:
            return this.visitTerminal(nodeAny);
          case Rule:
            return this.visitRule(nodeAny);
          /* c8 ignore next 2 */
          default:
            throw Error("non exhaustive match");
        }
      }
      /* c8 ignore next */
      visitNonTerminal(node2) {
      }
      /* c8 ignore next */
      visitAlternative(node2) {
      }
      /* c8 ignore next */
      visitOption(node2) {
      }
      /* c8 ignore next */
      visitRepetition(node2) {
      }
      /* c8 ignore next */
      visitRepetitionMandatory(node2) {
      }
      /* c8 ignore next 3 */
      visitRepetitionMandatoryWithSeparator(node2) {
      }
      /* c8 ignore next */
      visitRepetitionWithSeparator(node2) {
      }
      /* c8 ignore next */
      visitAlternation(node2) {
      }
      /* c8 ignore next */
      visitTerminal(node2) {
      }
      /* c8 ignore next */
      visitRule(node2) {
      }
    }
    function isSequenceProd(prod) {
      return prod instanceof Alternative || prod instanceof Option || prod instanceof Repetition || prod instanceof RepetitionMandatory || prod instanceof RepetitionMandatoryWithSeparator || prod instanceof RepetitionWithSeparator || prod instanceof Terminal || prod instanceof Rule;
    }
    function isOptionalProd(prod, alreadyVisited = []) {
      const isDirectlyOptional = prod instanceof Option || prod instanceof Repetition || prod instanceof RepetitionWithSeparator;
      if (isDirectlyOptional) {
        return true;
      }
      if (prod instanceof Alternation) {
        return prod.definition.some((subProd) => {
          return isOptionalProd(subProd, alreadyVisited);
        });
      } else if (prod instanceof NonTerminal && alreadyVisited.includes(prod)) {
        return false;
      } else if (prod instanceof AbstractProduction) {
        if (prod instanceof NonTerminal) {
          alreadyVisited.push(prod);
        }
        return prod.definition.every((subProd) => {
          return isOptionalProd(subProd, alreadyVisited);
        });
      } else {
        return false;
      }
    }
    function isBranchingProd(prod) {
      return prod instanceof Alternation;
    }
    function getProductionDslName$1(prod) {
      if (prod instanceof NonTerminal) {
        return "SUBRULE";
      } else if (prod instanceof Option) {
        return "OPTION";
      } else if (prod instanceof Alternation) {
        return "OR";
      } else if (prod instanceof RepetitionMandatory) {
        return "AT_LEAST_ONE";
      } else if (prod instanceof RepetitionMandatoryWithSeparator) {
        return "AT_LEAST_ONE_SEP";
      } else if (prod instanceof RepetitionWithSeparator) {
        return "MANY_SEP";
      } else if (prod instanceof Repetition) {
        return "MANY";
      } else if (prod instanceof Terminal) {
        return "CONSUME";
      } else {
        throw Error("non exhaustive match");
      }
    }
    class RestWalker {
      walk(prod, prevRest = []) {
        prod.definition.forEach((subProd, index) => {
          const currRest = prod.definition.slice(index + 1);
          if (subProd instanceof NonTerminal) {
            this.walkProdRef(subProd, currRest, prevRest);
          } else if (subProd instanceof Terminal) {
            this.walkTerminal(subProd, currRest, prevRest);
          } else if (subProd instanceof Alternative) {
            this.walkFlat(subProd, currRest, prevRest);
          } else if (subProd instanceof Option) {
            this.walkOption(subProd, currRest, prevRest);
          } else if (subProd instanceof RepetitionMandatory) {
            this.walkAtLeastOne(subProd, currRest, prevRest);
          } else if (subProd instanceof RepetitionMandatoryWithSeparator) {
            this.walkAtLeastOneSep(subProd, currRest, prevRest);
          } else if (subProd instanceof RepetitionWithSeparator) {
            this.walkManySep(subProd, currRest, prevRest);
          } else if (subProd instanceof Repetition) {
            this.walkMany(subProd, currRest, prevRest);
          } else if (subProd instanceof Alternation) {
            this.walkOr(subProd, currRest, prevRest);
          } else {
            throw Error("non exhaustive match");
          }
        });
      }
      walkTerminal(terminal, currRest, prevRest) {
      }
      walkProdRef(refProd, currRest, prevRest) {
      }
      walkFlat(flatProd, currRest, prevRest) {
        const fullOrRest = currRest.concat(prevRest);
        this.walk(flatProd, fullOrRest);
      }
      walkOption(optionProd, currRest, prevRest) {
        const fullOrRest = currRest.concat(prevRest);
        this.walk(optionProd, fullOrRest);
      }
      walkAtLeastOne(atLeastOneProd, currRest, prevRest) {
        const fullAtLeastOneRest = [
          new Option({ definition: atLeastOneProd.definition })
        ].concat(currRest, prevRest);
        this.walk(atLeastOneProd, fullAtLeastOneRest);
      }
      walkAtLeastOneSep(atLeastOneSepProd, currRest, prevRest) {
        const fullAtLeastOneSepRest = restForRepetitionWithSeparator(atLeastOneSepProd, currRest, prevRest);
        this.walk(atLeastOneSepProd, fullAtLeastOneSepRest);
      }
      walkMany(manyProd, currRest, prevRest) {
        const fullManyRest = [
          new Option({ definition: manyProd.definition })
        ].concat(currRest, prevRest);
        this.walk(manyProd, fullManyRest);
      }
      walkManySep(manySepProd, currRest, prevRest) {
        const fullManySepRest = restForRepetitionWithSeparator(manySepProd, currRest, prevRest);
        this.walk(manySepProd, fullManySepRest);
      }
      walkOr(orProd, currRest, prevRest) {
        const fullOrRest = currRest.concat(prevRest);
        orProd.definition.forEach((alt) => {
          const prodWrapper = new Alternative({ definition: [alt] });
          this.walk(prodWrapper, fullOrRest);
        });
      }
    }
    function restForRepetitionWithSeparator(repSepProd, currRest, prevRest) {
      const repSepRest = [
        new Option({
          definition: [
            new Terminal({ terminalType: repSepProd.separator })
          ].concat(repSepProd.definition)
        })
      ];
      const fullRepSepRest = repSepRest.concat(currRest, prevRest);
      return fullRepSepRest;
    }
    function first(prod) {
      if (prod instanceof NonTerminal) {
        return first(prod.referencedRule);
      } else if (prod instanceof Terminal) {
        return firstForTerminal(prod);
      } else if (isSequenceProd(prod)) {
        return firstForSequence(prod);
      } else if (isBranchingProd(prod)) {
        return firstForBranching(prod);
      } else {
        throw Error("non exhaustive match");
      }
    }
    function firstForSequence(prod) {
      let firstSet = [];
      const seq = prod.definition;
      let nextSubProdIdx = 0;
      let hasInnerProdsRemaining = seq.length > nextSubProdIdx;
      let currSubProd;
      let isLastInnerProdOptional = true;
      while (hasInnerProdsRemaining && isLastInnerProdOptional) {
        currSubProd = seq[nextSubProdIdx];
        isLastInnerProdOptional = isOptionalProd(currSubProd);
        firstSet = firstSet.concat(first(currSubProd));
        nextSubProdIdx = nextSubProdIdx + 1;
        hasInnerProdsRemaining = seq.length > nextSubProdIdx;
      }
      return [...new Set(firstSet)];
    }
    function firstForBranching(prod) {
      const allAlternativesFirsts = prod.definition.map((innerProd) => {
        return first(innerProd);
      });
      return [...new Set(allAlternativesFirsts.flat())];
    }
    function firstForTerminal(terminal) {
      return [terminal.terminalType];
    }
    const IN$1 = "_~IN~_";
    class ResyncFollowsWalker extends RestWalker {
      constructor(topProd) {
        super();
        this.topProd = topProd;
        this.follows = {};
      }
      startWalking() {
        this.walk(this.topProd);
        return this.follows;
      }
      walkTerminal(terminal, currRest, prevRest) {
      }
      walkProdRef(refProd, currRest, prevRest) {
        const followName = buildBetweenProdsFollowPrefix(refProd.referencedRule, refProd.idx) + this.topProd.name;
        const fullRest = currRest.concat(prevRest);
        const restProd = new Alternative({ definition: fullRest });
        const t_in_topProd_follows = first(restProd);
        this.follows[followName] = t_in_topProd_follows;
      }
    }
    function computeAllProdsFollows(topProductions) {
      const reSyncFollows = {};
      topProductions.forEach((topProd) => {
        const currRefsFollow = new ResyncFollowsWalker(topProd).startWalking();
        Object.assign(reSyncFollows, currRefsFollow);
      });
      return reSyncFollows;
    }
    function buildBetweenProdsFollowPrefix(inner, occurenceInParent) {
      return inner.name + occurenceInParent + IN$1;
    }
    let regExpAstCache = {};
    const regExpParser = new RegExpParser();
    function getRegExpAst(regExp) {
      const regExpStr = regExp.toString();
      if (regExpAstCache.hasOwnProperty(regExpStr)) {
        return regExpAstCache[regExpStr];
      } else {
        const regExpAst = regExpParser.pattern(regExpStr);
        regExpAstCache[regExpStr] = regExpAst;
        return regExpAst;
      }
    }
    function clearRegExpParserCache() {
      regExpAstCache = {};
    }
    const complementErrorMessage = "Complement Sets are not supported for first char optimization";
    const failedOptimizationPrefixMsg = 'Unable to use "first char" lexer optimizations:\n';
    function getOptimizedStartCodesIndices(regExp, ensureOptimizations = false) {
      try {
        const ast = getRegExpAst(regExp);
        const firstChars = firstCharOptimizedIndices(ast.value, {}, ast.flags.ignoreCase);
        return firstChars;
      } catch (e) {
        if (e.message === complementErrorMessage) {
          if (ensureOptimizations) {
            PRINT_WARNING(`${failedOptimizationPrefixMsg}	Unable to optimize: < ${regExp.toString()} >
	Complement Sets cannot be automatically optimized.
	This will disable the lexer's first char optimizations.
	See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#COMPLEMENT for details.`);
          }
        } else {
          let msgSuffix = "";
          if (ensureOptimizations) {
            msgSuffix = "\n	This will disable the lexer's first char optimizations.\n	See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#REGEXP_PARSING for details.";
          }
          PRINT_ERROR(`${failedOptimizationPrefixMsg}
	Failed parsing: < ${regExp.toString()} >
	Using the @chevrotain/regexp-to-ast library
	Please open an issue at: https://github.com/chevrotain/chevrotain/issues` + msgSuffix);
        }
      }
      return [];
    }
    function firstCharOptimizedIndices(ast, result, ignoreCase) {
      switch (ast.type) {
        case "Disjunction":
          for (let i = 0; i < ast.value.length; i++) {
            firstCharOptimizedIndices(ast.value[i], result, ignoreCase);
          }
          break;
        case "Alternative":
          const terms = ast.value;
          for (let i = 0; i < terms.length; i++) {
            const term = terms[i];
            switch (term.type) {
              case "EndAnchor":
              // A group back reference cannot affect potential starting char.
              // because if a back reference is the first production than automatically
              // the group being referenced has had to come BEFORE so its codes have already been added
              case "GroupBackReference":
              // assertions do not affect potential starting codes
              case "Lookahead":
              case "NegativeLookahead":
              case "Lookbehind":
              case "NegativeLookbehind":
              case "StartAnchor":
              case "WordBoundary":
              case "NonWordBoundary":
                continue;
            }
            const atom2 = term;
            switch (atom2.type) {
              case "Character":
                addOptimizedIdxToResult(atom2.value, result, ignoreCase);
                break;
              case "Set":
                if (atom2.complement === true) {
                  throw Error(complementErrorMessage);
                }
                atom2.value.forEach((code) => {
                  if (typeof code === "number") {
                    addOptimizedIdxToResult(code, result, ignoreCase);
                  } else {
                    const range = code;
                    if (ignoreCase === true) {
                      for (let rangeCode = range.from; rangeCode <= range.to; rangeCode++) {
                        addOptimizedIdxToResult(rangeCode, result, ignoreCase);
                      }
                    } else {
                      for (let rangeCode = range.from; rangeCode <= range.to && rangeCode < minOptimizationVal; rangeCode++) {
                        addOptimizedIdxToResult(rangeCode, result, ignoreCase);
                      }
                      if (range.to >= minOptimizationVal) {
                        const minUnOptVal = range.from >= minOptimizationVal ? range.from : minOptimizationVal;
                        const maxUnOptVal = range.to;
                        const minOptIdx = charCodeToOptimizedIndex(minUnOptVal);
                        const maxOptIdx = charCodeToOptimizedIndex(maxUnOptVal);
                        for (let currOptIdx = minOptIdx; currOptIdx <= maxOptIdx; currOptIdx++) {
                          result[currOptIdx] = currOptIdx;
                        }
                      }
                    }
                  }
                });
                break;
              case "Group":
                firstCharOptimizedIndices(atom2.value, result, ignoreCase);
                break;
              /* istanbul ignore next */
              default:
                throw Error("Non Exhaustive Match");
            }
            const isOptionalQuantifier = atom2.quantifier !== void 0 && atom2.quantifier.atLeast === 0;
            if (
              // A group may be optional due to empty contents /(?:)/
              // or if everything inside it is optional /((a)?)/
              atom2.type === "Group" && isWholeOptional(atom2) === false || // If this term is not a group it may only be optional if it has an optional quantifier
              atom2.type !== "Group" && isOptionalQuantifier === false
            ) {
              break;
            }
          }
          break;
        /* istanbul ignore next */
        default:
          throw Error("non exhaustive match!");
      }
      return Object.values(result);
    }
    function addOptimizedIdxToResult(code, result, ignoreCase) {
      const optimizedCharIdx = charCodeToOptimizedIndex(code);
      result[optimizedCharIdx] = optimizedCharIdx;
      if (ignoreCase === true) {
        handleIgnoreCase(code, result);
      }
    }
    function handleIgnoreCase(code, result) {
      const char = String.fromCharCode(code);
      const upperChar = char.toUpperCase();
      if (upperChar !== char) {
        const optimizedCharIdx = charCodeToOptimizedIndex(upperChar.charCodeAt(0));
        result[optimizedCharIdx] = optimizedCharIdx;
      } else {
        const lowerChar = char.toLowerCase();
        if (lowerChar !== char) {
          const optimizedCharIdx = charCodeToOptimizedIndex(lowerChar.charCodeAt(0));
          result[optimizedCharIdx] = optimizedCharIdx;
        }
      }
    }
    function findCode(setNode, targetCharCodes) {
      return setNode.value.find((codeOrRange) => {
        if (typeof codeOrRange === "number") {
          return targetCharCodes.includes(codeOrRange);
        } else {
          const range = codeOrRange;
          return targetCharCodes.find((targetCode) => range.from <= targetCode && targetCode <= range.to) !== void 0;
        }
      });
    }
    function isWholeOptional(ast) {
      const quantifier = ast.quantifier;
      if (quantifier && quantifier.atLeast === 0) {
        return true;
      }
      if (!ast.value) {
        return false;
      }
      return Array.isArray(ast.value) ? ast.value.every(isWholeOptional) : isWholeOptional(ast.value);
    }
    class CharCodeFinder extends BaseRegExpVisitor {
      constructor(targetCharCodes) {
        super();
        this.targetCharCodes = targetCharCodes;
        this.found = false;
      }
      visitChildren(node2) {
        if (this.found === true) {
          return;
        }
        switch (node2.type) {
          case "Lookahead":
            this.visitLookahead(node2);
            return;
          case "NegativeLookahead":
            this.visitNegativeLookahead(node2);
            return;
          case "Lookbehind":
            this.visitLookbehind(node2);
            return;
          case "NegativeLookbehind":
            this.visitNegativeLookbehind(node2);
            return;
        }
        super.visitChildren(node2);
      }
      visitCharacter(node2) {
        if (this.targetCharCodes.includes(node2.value)) {
          this.found = true;
        }
      }
      visitSet(node2) {
        if (node2.complement) {
          if (findCode(node2, this.targetCharCodes) === void 0) {
            this.found = true;
          }
        } else {
          if (findCode(node2, this.targetCharCodes) !== void 0) {
            this.found = true;
          }
        }
      }
    }
    function canMatchCharCode(charCodes, pattern) {
      if (pattern instanceof RegExp) {
        const ast = getRegExpAst(pattern);
        const charCodeFinder = new CharCodeFinder(charCodes);
        charCodeFinder.visit(ast);
        return charCodeFinder.found;
      } else {
        for (const char of pattern) {
          const charCode = char.charCodeAt(0);
          if (charCodes.includes(charCode)) {
            return true;
          }
        }
        return false;
      }
    }
    const PATTERN = "PATTERN";
    const DEFAULT_MODE = "defaultMode";
    const MODES = "modes";
    function analyzeTokenTypes(tokenTypes, options) {
      options = Object.assign({ safeMode: false, positionTracking: "full", lineTerminatorCharacters: ["\r", "\n"], tracer: (msg, action) => action() }, options);
      const tracer = options.tracer;
      tracer("initCharCodeToOptimizedIndexMap", () => {
        initCharCodeToOptimizedIndexMap();
      });
      let onlyRelevantTypes;
      tracer("Reject Lexer.NA", () => {
        onlyRelevantTypes = tokenTypes.filter((currType) => {
          return currType[PATTERN] !== Lexer.NA;
        });
      });
      let hasCustom = false;
      let allTransformedPatterns;
      tracer("Transform Patterns", () => {
        hasCustom = false;
        allTransformedPatterns = onlyRelevantTypes.map((currType) => {
          const currPattern = currType[PATTERN];
          if (currPattern instanceof RegExp) {
            const regExpSource = currPattern.source;
            if (regExpSource.length === 1 && // only these regExp meta characters which can appear in a length one regExp
            regExpSource !== "^" && regExpSource !== "$" && regExpSource !== "." && !currPattern.ignoreCase) {
              return regExpSource;
            } else if (regExpSource.length === 2 && regExpSource[0] === "\\" && // not a meta character
            ![
              "d",
              "D",
              "s",
              "S",
              "t",
              "r",
              "n",
              "t",
              "0",
              "c",
              "b",
              "B",
              "f",
              "v",
              "w",
              "W"
            ].includes(regExpSource[1])) {
              return regExpSource[1];
            } else {
              return addStickyFlag(currPattern);
            }
          } else if (typeof currPattern === "function") {
            hasCustom = true;
            return { exec: currPattern };
          } else if (typeof currPattern === "object") {
            hasCustom = true;
            return currPattern;
          } else if (typeof currPattern === "string") {
            if (currPattern.length === 1) {
              return currPattern;
            } else {
              const escapedRegExpString = currPattern.replace(/[\\^$.*+?()[\]{}|]/g, "\\$&");
              const wrappedRegExp = new RegExp(escapedRegExpString);
              return addStickyFlag(wrappedRegExp);
            }
          } else {
            throw Error("non exhaustive match");
          }
        });
      });
      let patternIdxToType;
      let patternIdxToGroup;
      let patternIdxToLongerAltIdxArr;
      let patternIdxToPushMode;
      let patternIdxToPopMode;
      tracer("misc mapping", () => {
        patternIdxToType = onlyRelevantTypes.map((currType) => currType.tokenTypeIdx);
        patternIdxToGroup = onlyRelevantTypes.map((clazz) => {
          const groupName = clazz.GROUP;
          if (groupName === Lexer.SKIPPED) {
            return void 0;
          } else if (typeof groupName === "string") {
            return groupName;
          } else if (groupName === void 0) {
            return false;
          } else {
            throw Error("non exhaustive match");
          }
        });
        patternIdxToLongerAltIdxArr = onlyRelevantTypes.map((clazz) => {
          const longerAltType = clazz.LONGER_ALT;
          if (longerAltType) {
            const longerAltIdxArr = Array.isArray(longerAltType) ? longerAltType.map((type) => onlyRelevantTypes.indexOf(type)) : [onlyRelevantTypes.indexOf(longerAltType)];
            return longerAltIdxArr;
          }
        });
        patternIdxToPushMode = onlyRelevantTypes.map((clazz) => clazz.PUSH_MODE);
        patternIdxToPopMode = onlyRelevantTypes.map((clazz) => Object.hasOwn(clazz, "POP_MODE"));
      });
      let patternIdxToCanLineTerminator;
      tracer("Line Terminator Handling", () => {
        const lineTerminatorCharCodes = getCharCodes(options.lineTerminatorCharacters);
        patternIdxToCanLineTerminator = onlyRelevantTypes.map((tokType) => false);
        if (options.positionTracking !== "onlyOffset") {
          patternIdxToCanLineTerminator = onlyRelevantTypes.map((tokType) => {
            if (Object.hasOwn(tokType, "LINE_BREAKS")) {
              return !!tokType.LINE_BREAKS;
            } else {
              return checkLineBreaksIssues(tokType, lineTerminatorCharCodes) === false && canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN);
            }
          });
        }
      });
      let patternIdxToIsCustom;
      let patternIdxToShort;
      let emptyGroups;
      let patternIdxToConfig;
      tracer("Misc Mapping #2", () => {
        patternIdxToIsCustom = onlyRelevantTypes.map(isCustomPattern);
        patternIdxToShort = allTransformedPatterns.map(isShortPattern);
        emptyGroups = onlyRelevantTypes.reduce((acc, clazz) => {
          const groupName = clazz.GROUP;
          if (typeof groupName === "string" && !(groupName === Lexer.SKIPPED)) {
            acc[groupName] = [];
          }
          return acc;
        }, {});
        patternIdxToConfig = allTransformedPatterns.map((x, idx) => {
          return {
            pattern: allTransformedPatterns[idx],
            longerAlt: patternIdxToLongerAltIdxArr[idx],
            canLineTerminator: patternIdxToCanLineTerminator[idx],
            isCustom: patternIdxToIsCustom[idx],
            short: patternIdxToShort[idx],
            group: patternIdxToGroup[idx],
            push: patternIdxToPushMode[idx],
            pop: patternIdxToPopMode[idx],
            tokenTypeIdx: patternIdxToType[idx],
            tokenType: onlyRelevantTypes[idx]
          };
        });
      });
      let canBeOptimized = true;
      let charCodeToPatternIdxToConfig = [];
      if (!options.safeMode) {
        tracer("First Char Optimization", () => {
          charCodeToPatternIdxToConfig = onlyRelevantTypes.reduce((result, currTokType, idx) => {
            if (typeof currTokType.PATTERN === "string") {
              const charCode = currTokType.PATTERN.charCodeAt(0);
              const optimizedIdx = charCodeToOptimizedIndex(charCode);
              addToMapOfArrays(result, optimizedIdx, patternIdxToConfig[idx]);
            } else if (Array.isArray(currTokType.START_CHARS_HINT)) {
              let lastOptimizedIdx;
              currTokType.START_CHARS_HINT.forEach((charOrInt) => {
                const charCode = typeof charOrInt === "string" ? charOrInt.charCodeAt(0) : charOrInt;
                const currOptimizedIdx = charCodeToOptimizedIndex(charCode);
                if (lastOptimizedIdx !== currOptimizedIdx) {
                  lastOptimizedIdx = currOptimizedIdx;
                  addToMapOfArrays(result, currOptimizedIdx, patternIdxToConfig[idx]);
                }
              });
            } else if (currTokType.PATTERN instanceof RegExp) {
              if (currTokType.PATTERN.unicode) {
                canBeOptimized = false;
                if (options.ensureOptimizations) {
                  PRINT_ERROR(`${failedOptimizationPrefixMsg}	Unable to analyze < ${currTokType.PATTERN.toString()} > pattern.
	The regexp unicode flag is not currently supported by the regexp-to-ast library.
	This will disable the lexer's first char optimizations.
	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNICODE_OPTIMIZE`);
                }
              } else {
                const optimizedCodes = getOptimizedStartCodesIndices(currTokType.PATTERN, options.ensureOptimizations);
                if (optimizedCodes.length === 0) {
                  canBeOptimized = false;
                }
                optimizedCodes.forEach((code) => {
                  addToMapOfArrays(result, code, patternIdxToConfig[idx]);
                });
              }
            } else {
              if (options.ensureOptimizations) {
                PRINT_ERROR(`${failedOptimizationPrefixMsg}	TokenType: <${currTokType.name}> is using a custom token pattern without providing <start_chars_hint> parameter.
	This will disable the lexer's first char optimizations.
	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_OPTIMIZE`);
              }
              canBeOptimized = false;
            }
            return result;
          }, []);
        });
      }
      return {
        emptyGroups,
        patternIdxToConfig,
        charCodeToPatternIdxToConfig,
        hasCustom,
        canBeOptimized
      };
    }
    function validatePatterns(tokenTypes, validModesNames) {
      let errors = [];
      const missingResult = findMissingPatterns(tokenTypes);
      errors = errors.concat(missingResult.errors);
      const invalidResult = findInvalidPatterns(missingResult.valid);
      const validTokenTypes = invalidResult.valid;
      errors = errors.concat(invalidResult.errors);
      errors = errors.concat(validateRegExpPattern(validTokenTypes));
      errors = errors.concat(findInvalidGroupType(validTokenTypes));
      errors = errors.concat(findModesThatDoNotExist(validTokenTypes, validModesNames));
      errors = errors.concat(findUnreachablePatterns(validTokenTypes));
      return errors;
    }
    function validateRegExpPattern(tokenTypes) {
      let errors = [];
      const withRegExpPatterns = tokenTypes.filter((currTokType) => currTokType[PATTERN] instanceof RegExp);
      errors = errors.concat(findEndOfInputAnchor(withRegExpPatterns));
      errors = errors.concat(findStartOfInputAnchor(withRegExpPatterns));
      errors = errors.concat(findUnsupportedFlags(withRegExpPatterns));
      errors = errors.concat(findDuplicatePatterns(withRegExpPatterns));
      errors = errors.concat(findEmptyMatchRegExps(withRegExpPatterns));
      return errors;
    }
    function findMissingPatterns(tokenTypes) {
      const tokenTypesWithMissingPattern = tokenTypes.filter((currType) => {
        return !Object.hasOwn(currType, PATTERN);
      });
      const errors = tokenTypesWithMissingPattern.map((currType) => {
        return {
          message: "Token Type: ->" + currType.name + "<- missing static 'PATTERN' property",
          type: LexerDefinitionErrorType.MISSING_PATTERN,
          tokenTypes: [currType]
        };
      });
      const valid = tokenTypes.filter((x) => !tokenTypesWithMissingPattern.includes(x));
      return { errors, valid };
    }
    function findInvalidPatterns(tokenTypes) {
      const tokenTypesWithInvalidPattern = tokenTypes.filter((currType) => {
        const pattern = currType[PATTERN];
        return !(pattern instanceof RegExp) && !(typeof pattern === "function") && !Object.hasOwn(pattern, "exec") && !(typeof pattern === "string");
      });
      const errors = tokenTypesWithInvalidPattern.map((currType) => {
        return {
          message: "Token Type: ->" + currType.name + "<- static 'PATTERN' can only be a RegExp, a Function matching the {CustomPatternMatcherFunc} type or an Object matching the {ICustomPattern} interface.",
          type: LexerDefinitionErrorType.INVALID_PATTERN,
          tokenTypes: [currType]
        };
      });
      const valid = tokenTypes.filter((x) => !tokenTypesWithInvalidPattern.includes(x));
      return { errors, valid };
    }
    const end_of_input = /[^\\][$]/;
    function findEndOfInputAnchor(tokenTypes) {
      class EndAnchorFinder extends BaseRegExpVisitor {
        constructor() {
          super(...arguments);
          this.found = false;
        }
        visitEndAnchor(node2) {
          this.found = true;
        }
      }
      const invalidRegex = tokenTypes.filter((currType) => {
        const pattern = currType.PATTERN;
        try {
          const regexpAst = getRegExpAst(pattern);
          const endAnchorVisitor = new EndAnchorFinder();
          endAnchorVisitor.visit(regexpAst);
          return endAnchorVisitor.found;
        } catch (e) {
          return end_of_input.test(pattern.source);
        }
      });
      const errors = invalidRegex.map((currType) => {
        return {
          message: "Unexpected RegExp Anchor Error:\n	Token Type: ->" + currType.name + "<- static 'PATTERN' cannot contain end of input anchor '$'\n	See chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS	for details.",
          type: LexerDefinitionErrorType.EOI_ANCHOR_FOUND,
          tokenTypes: [currType]
        };
      });
      return errors;
    }
    function findEmptyMatchRegExps(tokenTypes) {
      const matchesEmptyString = tokenTypes.filter((currType) => {
        const pattern = currType.PATTERN;
        return pattern.test("");
      });
      const errors = matchesEmptyString.map((currType) => {
        return {
          message: "Token Type: ->" + currType.name + "<- static 'PATTERN' must not match an empty string",
          type: LexerDefinitionErrorType.EMPTY_MATCH_PATTERN,
          tokenTypes: [currType]
        };
      });
      return errors;
    }
    const start_of_input = /[^\\[][\^]|^\^/;
    function findStartOfInputAnchor(tokenTypes) {
      class StartAnchorFinder extends BaseRegExpVisitor {
        constructor() {
          super(...arguments);
          this.found = false;
        }
        visitStartAnchor(node2) {
          this.found = true;
        }
      }
      const invalidRegex = tokenTypes.filter((currType) => {
        const pattern = currType.PATTERN;
        try {
          const regexpAst = getRegExpAst(pattern);
          const startAnchorVisitor = new StartAnchorFinder();
          startAnchorVisitor.visit(regexpAst);
          return startAnchorVisitor.found;
        } catch (e) {
          return start_of_input.test(pattern.source);
        }
      });
      const errors = invalidRegex.map((currType) => {
        return {
          message: "Unexpected RegExp Anchor Error:\n	Token Type: ->" + currType.name + "<- static 'PATTERN' cannot contain start of input anchor '^'\n	See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#ANCHORS	for details.",
          type: LexerDefinitionErrorType.SOI_ANCHOR_FOUND,
          tokenTypes: [currType]
        };
      });
      return errors;
    }
    function findUnsupportedFlags(tokenTypes) {
      const invalidFlags = tokenTypes.filter((currType) => {
        const pattern = currType[PATTERN];
        return pattern instanceof RegExp && (pattern.multiline || pattern.global);
      });
      const errors = invalidFlags.map((currType) => {
        return {
          message: "Token Type: ->" + currType.name + "<- static 'PATTERN' may NOT contain global('g') or multiline('m')",
          type: LexerDefinitionErrorType.UNSUPPORTED_FLAGS_FOUND,
          tokenTypes: [currType]
        };
      });
      return errors;
    }
    function findDuplicatePatterns(tokenTypes) {
      const found = [];
      let identicalPatterns = tokenTypes.map((outerType) => {
        return tokenTypes.reduce((result, innerType) => {
          if (outerType.PATTERN.source === innerType.PATTERN.source && !found.includes(innerType) && innerType.PATTERN !== Lexer.NA) {
            found.push(innerType);
            result.push(innerType);
            return result;
          }
          return result;
        }, []);
      });
      identicalPatterns = identicalPatterns.filter(Boolean);
      const duplicatePatterns = identicalPatterns.filter((currIdenticalSet) => {
        return currIdenticalSet.length > 1;
      });
      const errors = duplicatePatterns.map((setOfIdentical) => {
        const tokenTypeNames = setOfIdentical.map((currType) => {
          return currType.name;
        });
        const dupPatternSrc = setOfIdentical[0].PATTERN;
        return {
          message: `The same RegExp pattern ->${dupPatternSrc}<-has been used in all of the following Token Types: ${tokenTypeNames.join(", ")} <-`,
          type: LexerDefinitionErrorType.DUPLICATE_PATTERNS_FOUND,
          tokenTypes: setOfIdentical
        };
      });
      return errors;
    }
    function findInvalidGroupType(tokenTypes) {
      const invalidTypes = tokenTypes.filter((clazz) => {
        if (!Object.hasOwn(clazz, "GROUP")) {
          return false;
        }
        const group = clazz.GROUP;
        return group !== Lexer.SKIPPED && group !== Lexer.NA && !(typeof group === "string");
      });
      const errors = invalidTypes.map((currType) => {
        return {
          message: "Token Type: ->" + currType.name + "<- static 'GROUP' can only be Lexer.SKIPPED/Lexer.NA/A String",
          type: LexerDefinitionErrorType.INVALID_GROUP_TYPE_FOUND,
          tokenTypes: [currType]
        };
      });
      return errors;
    }
    function findModesThatDoNotExist(tokenTypes, validModes) {
      const invalidModes = tokenTypes.filter((clazz) => {
        return clazz.PUSH_MODE !== void 0 && !validModes.includes(clazz.PUSH_MODE);
      });
      const errors = invalidModes.map((tokType) => {
        const msg = `Token Type: ->${tokType.name}<- static 'PUSH_MODE' value cannot refer to a Lexer Mode ->${tokType.PUSH_MODE}<-which does not exist`;
        return {
          message: msg,
          type: LexerDefinitionErrorType.PUSH_MODE_DOES_NOT_EXIST,
          tokenTypes: [tokType]
        };
      });
      return errors;
    }
    function findUnreachablePatterns(tokenTypes) {
      const errors = [];
      const canBeTested = tokenTypes.reduce((result, tokType, idx) => {
        const pattern = tokType.PATTERN;
        if (pattern === Lexer.NA) {
          return result;
        }
        if (typeof pattern === "string") {
          result.push({ str: pattern, idx, tokenType: tokType });
        } else if (pattern instanceof RegExp && noMetaChar(pattern)) {
          result.push({ str: pattern.source, idx, tokenType: tokType });
        }
        return result;
      }, []);
      tokenTypes.forEach((aTokType, aIdx) => {
        canBeTested.forEach(({ str: bStr, idx: bIdx, tokenType: bTokType }) => {
          if (aIdx < bIdx && tryToMatchStrToPattern(bStr, aTokType.PATTERN)) {
            const msg = `Token: ->${bTokType.name}<- can never be matched.
Because it appears AFTER the Token Type ->${aTokType.name}<-in the lexer's definition.
See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#UNREACHABLE`;
            errors.push({
              message: msg,
              type: LexerDefinitionErrorType.UNREACHABLE_PATTERN,
              tokenTypes: [aTokType, bTokType]
            });
          }
        });
      });
      return errors;
    }
    function tryToMatchStrToPattern(str, pattern) {
      if (pattern instanceof RegExp) {
        if (usesLookAheadOrBehind(pattern)) {
          return false;
        }
        const regExpArray = pattern.exec(str);
        return regExpArray !== null && regExpArray.index === 0;
      } else if (typeof pattern === "function") {
        return pattern(str, 0, [], {});
      } else if (Object.hasOwn(pattern, "exec")) {
        return pattern.exec(str, 0, [], {});
      } else if (typeof pattern === "string") {
        return pattern === str;
      } else {
        throw Error("non exhaustive match");
      }
    }
    function noMetaChar(regExp) {
      const metaChars = [
        ".",
        "\\",
        "[",
        "]",
        "|",
        "^",
        "$",
        "(",
        ")",
        "?",
        "*",
        "+",
        "{"
      ];
      return metaChars.find((char) => regExp.source.indexOf(char) !== -1) === void 0;
    }
    function usesLookAheadOrBehind(regExp) {
      return /(\(\?=)|(\(\?!)|(\(\?<=)|(\(\?<!)/.test(regExp.source);
    }
    function addStickyFlag(pattern) {
      const flags = pattern.ignoreCase ? "iy" : "y";
      return new RegExp(`${pattern.source}`, flags);
    }
    function performRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) {
      const errors = [];
      if (!Object.hasOwn(lexerDefinition, DEFAULT_MODE)) {
        errors.push({
          message: "A MultiMode Lexer cannot be initialized without a <" + DEFAULT_MODE + "> property in its definition\n",
          type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE
        });
      }
      if (!Object.hasOwn(lexerDefinition, MODES)) {
        errors.push({
          message: "A MultiMode Lexer cannot be initialized without a <" + MODES + "> property in its definition\n",
          type: LexerDefinitionErrorType.MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY
        });
      }
      if (Object.hasOwn(lexerDefinition, MODES) && Object.hasOwn(lexerDefinition, DEFAULT_MODE) && !Object.hasOwn(lexerDefinition.modes, lexerDefinition.defaultMode)) {
        errors.push({
          message: `A MultiMode Lexer cannot be initialized with a ${DEFAULT_MODE}: <${lexerDefinition.defaultMode}>which does not exist
`,
          type: LexerDefinitionErrorType.MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST
        });
      }
      if (Object.hasOwn(lexerDefinition, MODES)) {
        Object.keys(lexerDefinition.modes).forEach((currModeName) => {
          const currModeValue = lexerDefinition.modes[currModeName];
          currModeValue.forEach((currTokType, currIdx) => {
            if (currTokType === void 0) {
              errors.push({
                message: `A Lexer cannot be initialized using an undefined Token Type. Mode:<${currModeName}> at index: <${currIdx}>
`,
                type: LexerDefinitionErrorType.LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED
              });
            } else if (Object.hasOwn(currTokType, "LONGER_ALT")) {
              const longerAlt = Array.isArray(currTokType.LONGER_ALT) ? currTokType.LONGER_ALT : [currTokType.LONGER_ALT];
              longerAlt.forEach((currLongerAlt) => {
                if (currLongerAlt !== void 0 && !currModeValue.includes(currLongerAlt)) {
                  errors.push({
                    message: `A MultiMode Lexer cannot be initialized with a longer_alt <${currLongerAlt.name}> on token <${currTokType.name}> outside of mode <${currModeName}>
`,
                    type: LexerDefinitionErrorType.MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE
                  });
                }
              });
            }
          });
        });
      }
      return errors;
    }
    function performWarningRuntimeChecks(lexerDefinition, trackLines, lineTerminatorCharacters) {
      const warnings = [];
      let hasAnyLineBreak = false;
      const allTokenTypes = Object.values(lexerDefinition.modes || {}).flat().filter(Boolean);
      const concreteTokenTypes = allTokenTypes.filter((currType) => currType[PATTERN] !== Lexer.NA);
      const terminatorCharCodes = getCharCodes(lineTerminatorCharacters);
      if (trackLines) {
        concreteTokenTypes.forEach((tokType) => {
          const currIssue = checkLineBreaksIssues(tokType, terminatorCharCodes);
          if (currIssue !== false) {
            const message = buildLineBreakIssueMessage(tokType, currIssue);
            const warningDescriptor = {
              message,
              type: currIssue.issue,
              tokenType: tokType
            };
            warnings.push(warningDescriptor);
          } else {
            if (Object.hasOwn(tokType, "LINE_BREAKS")) {
              if (tokType.LINE_BREAKS === true) {
                hasAnyLineBreak = true;
              }
            } else {
              if (canMatchCharCode(terminatorCharCodes, tokType.PATTERN)) {
                hasAnyLineBreak = true;
              }
            }
          }
        });
      }
      if (trackLines && !hasAnyLineBreak) {
        warnings.push({
          message: "Warning: No LINE_BREAKS Found.\n	This Lexer has been defined to track line and column information,\n	But none of the Token Types can be identified as matching a line terminator.\n	See https://chevrotain.io/docs/guide/resolving_lexer_errors.html#LINE_BREAKS \n	for details.",
          type: LexerDefinitionErrorType.NO_LINE_BREAKS_FLAGS
        });
      }
      return warnings;
    }
    function cloneEmptyGroups(emptyGroups) {
      const clonedResult = {};
      const groupKeys = Object.keys(emptyGroups);
      groupKeys.forEach((currKey) => {
        const currGroupValue = emptyGroups[currKey];
        if (Array.isArray(currGroupValue)) {
          clonedResult[currKey] = [];
        } else {
          throw Error("non exhaustive match");
        }
      });
      return clonedResult;
    }
    function isCustomPattern(tokenType) {
      const pattern = tokenType.PATTERN;
      if (pattern instanceof RegExp) {
        return false;
      } else if (typeof pattern === "function") {
        return true;
      } else if (Object.hasOwn(pattern, "exec")) {
        return true;
      } else if (typeof pattern === "string") {
        return false;
      } else {
        throw Error("non exhaustive match");
      }
    }
    function isShortPattern(pattern) {
      if (typeof pattern === "string" && pattern.length === 1) {
        return pattern.charCodeAt(0);
      } else {
        return false;
      }
    }
    const LineTerminatorOptimizedTester = {
      // implements /\n|\r\n?/g.test
      test: function(text) {
        const len = text.length;
        for (let i = this.lastIndex; i < len; i++) {
          const c = text.charCodeAt(i);
          if (c === 10) {
            this.lastIndex = i + 1;
            return true;
          } else if (c === 13) {
            if (text.charCodeAt(i + 1) === 10) {
              this.lastIndex = i + 2;
            } else {
              this.lastIndex = i + 1;
            }
            return true;
          }
        }
        return false;
      },
      lastIndex: 0
    };
    function checkLineBreaksIssues(tokType, lineTerminatorCharCodes) {
      if (Object.hasOwn(tokType, "LINE_BREAKS")) {
        return false;
      } else {
        if (tokType.PATTERN instanceof RegExp) {
          try {
            canMatchCharCode(lineTerminatorCharCodes, tokType.PATTERN);
          } catch (e) {
            return {
              issue: LexerDefinitionErrorType.IDENTIFY_TERMINATOR,
              errMsg: e.message
            };
          }
          return false;
        } else if (typeof tokType.PATTERN === "string") {
          return false;
        } else if (isCustomPattern(tokType)) {
          return { issue: LexerDefinitionErrorType.CUSTOM_LINE_BREAK };
        } else {
          throw Error("non exhaustive match");
        }
      }
    }
    function buildLineBreakIssueMessage(tokType, details) {
      if (details.issue === LexerDefinitionErrorType.IDENTIFY_TERMINATOR) {
        return `Warning: unable to identify line terminator usage in pattern.
	The problem is in the <${tokType.name}> Token Type
	 Root cause: ${details.errMsg}.
	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#IDENTIFY_TERMINATOR`;
      } else if (details.issue === LexerDefinitionErrorType.CUSTOM_LINE_BREAK) {
        return `Warning: A Custom Token Pattern should specify the <line_breaks> option.
	The problem is in the <${tokType.name}> Token Type
	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#CUSTOM_LINE_BREAK`;
      } else {
        throw Error("non exhaustive match");
      }
    }
    function getCharCodes(charsOrCodes) {
      const charCodes = charsOrCodes.map((numOrString) => {
        if (typeof numOrString === "string") {
          return numOrString.charCodeAt(0);
        } else {
          return numOrString;
        }
      });
      return charCodes;
    }
    function addToMapOfArrays(map2, key, value) {
      if (map2[key] === void 0) {
        map2[key] = [value];
      } else {
        map2[key].push(value);
      }
    }
    const minOptimizationVal = 256;
    let charCodeToOptimizedIdxMap = [];
    function charCodeToOptimizedIndex(charCode) {
      return charCode < minOptimizationVal ? charCode : charCodeToOptimizedIdxMap[charCode];
    }
    function initCharCodeToOptimizedIndexMap() {
      if (charCodeToOptimizedIdxMap.length === 0) {
        charCodeToOptimizedIdxMap = new Array(65536);
        for (let i = 0; i < 65536; i++) {
          charCodeToOptimizedIdxMap[i] = i > 255 ? 255 + ~~(i / 255) : i;
        }
      }
    }
    function tokenStructuredMatcher(tokInstance, tokConstructor) {
      const instanceType = tokInstance.tokenTypeIdx;
      if (instanceType === tokConstructor.tokenTypeIdx) {
        return true;
      } else {
        return tokConstructor.isParent === true && tokConstructor.categoryMatchesMap[instanceType] === true;
      }
    }
    function tokenStructuredMatcherNoCategories(token, tokType) {
      return token.tokenTypeIdx === tokType.tokenTypeIdx;
    }
    let tokenShortNameIdx = 1;
    const tokenIdxToClass = {};
    function augmentTokenTypes(tokenTypes) {
      const tokenTypesAndParents = expandCategories(tokenTypes);
      assignTokenDefaultProps(tokenTypesAndParents);
      assignCategoriesMapProp(tokenTypesAndParents);
      assignCategoriesTokensProp(tokenTypesAndParents);
      tokenTypesAndParents.forEach((tokType) => {
        tokType.isParent = tokType.categoryMatches.length > 0;
      });
    }
    function expandCategories(tokenTypes) {
      let result = [...tokenTypes];
      let categories = tokenTypes;
      let searching = true;
      while (searching) {
        categories = categories.map((currTokType) => currTokType.CATEGORIES).flat().filter(Boolean);
        const newCategories = categories.filter((x) => !result.includes(x));
        result = result.concat(newCategories);
        if (newCategories.length === 0) {
          searching = false;
        } else {
          categories = newCategories;
        }
      }
      return result;
    }
    function assignTokenDefaultProps(tokenTypes) {
      tokenTypes.forEach((currTokType) => {
        if (!hasShortKeyProperty(currTokType)) {
          tokenIdxToClass[tokenShortNameIdx] = currTokType;
          currTokType.tokenTypeIdx = tokenShortNameIdx++;
        }
        if (hasCategoriesProperty(currTokType) && !Array.isArray(currTokType.CATEGORIES)) {
          currTokType.CATEGORIES = [currTokType.CATEGORIES];
        }
        if (!hasCategoriesProperty(currTokType)) {
          currTokType.CATEGORIES = [];
        }
        if (!hasExtendingTokensTypesProperty(currTokType)) {
          currTokType.categoryMatches = [];
        }
        if (!hasExtendingTokensTypesMapProperty(currTokType)) {
          currTokType.categoryMatchesMap = {};
        }
      });
    }
    function assignCategoriesTokensProp(tokenTypes) {
      tokenTypes.forEach((currTokType) => {
        currTokType.categoryMatches = [];
        Object.keys(currTokType.categoryMatchesMap).forEach((key) => {
          currTokType.categoryMatches.push(tokenIdxToClass[key].tokenTypeIdx);
        });
      });
    }
    function assignCategoriesMapProp(tokenTypes) {
      tokenTypes.forEach((currTokType) => {
        singleAssignCategoriesToksMap([], currTokType);
      });
    }
    function singleAssignCategoriesToksMap(path, nextNode) {
      path.forEach((pathNode) => {
        nextNode.categoryMatchesMap[pathNode.tokenTypeIdx] = true;
      });
      nextNode.CATEGORIES.forEach((nextCategory) => {
        const newPath = path.concat(nextNode);
        if (!newPath.includes(nextCategory)) {
          singleAssignCategoriesToksMap(newPath, nextCategory);
        }
      });
    }
    function hasShortKeyProperty(tokType) {
      return Object.hasOwn(tokType !== null && tokType !== void 0 ? tokType : {}, "tokenTypeIdx");
    }
    function hasCategoriesProperty(tokType) {
      return Object.hasOwn(tokType !== null && tokType !== void 0 ? tokType : {}, "CATEGORIES");
    }
    function hasExtendingTokensTypesProperty(tokType) {
      return Object.hasOwn(tokType !== null && tokType !== void 0 ? tokType : {}, "categoryMatches");
    }
    function hasExtendingTokensTypesMapProperty(tokType) {
      return Object.hasOwn(tokType !== null && tokType !== void 0 ? tokType : {}, "categoryMatchesMap");
    }
    function isTokenType(tokType) {
      return Object.hasOwn(tokType !== null && tokType !== void 0 ? tokType : {}, "tokenTypeIdx");
    }
    const defaultLexerErrorProvider = {
      buildUnableToPopLexerModeMessage(token) {
        return `Unable to pop Lexer Mode after encountering Token ->${token.image}<- The Mode Stack is empty`;
      },
      buildUnexpectedCharactersMessage(fullText, startOffset, length, line, column, mode) {
        return `unexpected character: ->${fullText.charAt(startOffset)}<- at offset: ${startOffset}, skipped ${length} characters.`;
      }
    };
    var LexerDefinitionErrorType;
    (function(LexerDefinitionErrorType2) {
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["MISSING_PATTERN"] = 0] = "MISSING_PATTERN";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["INVALID_PATTERN"] = 1] = "INVALID_PATTERN";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["EOI_ANCHOR_FOUND"] = 2] = "EOI_ANCHOR_FOUND";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["UNSUPPORTED_FLAGS_FOUND"] = 3] = "UNSUPPORTED_FLAGS_FOUND";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["DUPLICATE_PATTERNS_FOUND"] = 4] = "DUPLICATE_PATTERNS_FOUND";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["INVALID_GROUP_TYPE_FOUND"] = 5] = "INVALID_GROUP_TYPE_FOUND";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["PUSH_MODE_DOES_NOT_EXIST"] = 6] = "PUSH_MODE_DOES_NOT_EXIST";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE"] = 7] = "MULTI_MODE_LEXER_WITHOUT_DEFAULT_MODE";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY"] = 8] = "MULTI_MODE_LEXER_WITHOUT_MODES_PROPERTY";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST"] = 9] = "MULTI_MODE_LEXER_DEFAULT_MODE_VALUE_DOES_NOT_EXIST";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED"] = 10] = "LEXER_DEFINITION_CANNOT_CONTAIN_UNDEFINED";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["SOI_ANCHOR_FOUND"] = 11] = "SOI_ANCHOR_FOUND";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["EMPTY_MATCH_PATTERN"] = 12] = "EMPTY_MATCH_PATTERN";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["NO_LINE_BREAKS_FLAGS"] = 13] = "NO_LINE_BREAKS_FLAGS";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["UNREACHABLE_PATTERN"] = 14] = "UNREACHABLE_PATTERN";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["IDENTIFY_TERMINATOR"] = 15] = "IDENTIFY_TERMINATOR";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["CUSTOM_LINE_BREAK"] = 16] = "CUSTOM_LINE_BREAK";
      LexerDefinitionErrorType2[LexerDefinitionErrorType2["MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE"] = 17] = "MULTI_MODE_LEXER_LONGER_ALT_NOT_IN_CURRENT_MODE";
    })(LexerDefinitionErrorType || (LexerDefinitionErrorType = {}));
    const DEFAULT_LEXER_CONFIG = {
      deferDefinitionErrorsHandling: false,
      positionTracking: "full",
      lineTerminatorsPattern: /\n|\r\n?/g,
      lineTerminatorCharacters: ["\n", "\r"],
      ensureOptimizations: false,
      safeMode: false,
      errorMessageProvider: defaultLexerErrorProvider,
      traceInitPerf: false,
      skipValidations: false,
      recoveryEnabled: true
    };
    Object.freeze(DEFAULT_LEXER_CONFIG);
    class Lexer {
      constructor(lexerDefinition, config = DEFAULT_LEXER_CONFIG) {
        this.lexerDefinition = lexerDefinition;
        this.lexerDefinitionErrors = [];
        this.lexerDefinitionWarning = [];
        this.patternIdxToConfig = {};
        this.charCodeToPatternIdxToConfig = {};
        this.modes = [];
        this.emptyGroups = {};
        this.trackStartLines = true;
        this.trackEndLines = true;
        this.hasCustom = false;
        this.canModeBeOptimized = {};
        this.TRACE_INIT = (phaseDesc, phaseImpl) => {
          if (this.traceInitPerf === true) {
            this.traceInitIndent++;
            const indent = new Array(this.traceInitIndent + 1).join("	");
            if (this.traceInitIndent < this.traceInitMaxIdent) {
              console.log(`${indent}--> <${phaseDesc}>`);
            }
            const { time, value } = timer(phaseImpl);
            const traceMethod = time > 10 ? console.warn : console.log;
            if (this.traceInitIndent < this.traceInitMaxIdent) {
              traceMethod(`${indent}<-- <${phaseDesc}> time: ${time}ms`);
            }
            this.traceInitIndent--;
            return value;
          } else {
            return phaseImpl();
          }
        };
        if (typeof config === "boolean") {
          throw Error("The second argument to the Lexer constructor is now an ILexerConfig Object.\na boolean 2nd argument is no longer supported");
        }
        this.config = Object.assign({}, DEFAULT_LEXER_CONFIG, config);
        const traceInitVal = this.config.traceInitPerf;
        if (traceInitVal === true) {
          this.traceInitMaxIdent = Infinity;
          this.traceInitPerf = true;
        } else if (typeof traceInitVal === "number") {
          this.traceInitMaxIdent = traceInitVal;
          this.traceInitPerf = true;
        }
        this.traceInitIndent = -1;
        this.TRACE_INIT("Lexer Constructor", () => {
          let actualDefinition;
          let hasOnlySingleMode = true;
          this.TRACE_INIT("Lexer Config handling", () => {
            if (this.config.lineTerminatorsPattern === DEFAULT_LEXER_CONFIG.lineTerminatorsPattern) {
              this.config.lineTerminatorsPattern = LineTerminatorOptimizedTester;
            } else {
              if (this.config.lineTerminatorCharacters === DEFAULT_LEXER_CONFIG.lineTerminatorCharacters) {
                throw Error("Error: Missing <lineTerminatorCharacters> property on the Lexer config.\n	For details See: https://chevrotain.io/docs/guide/resolving_lexer_errors.html#MISSING_LINE_TERM_CHARS");
              }
            }
            if (config.safeMode && config.ensureOptimizations) {
              throw Error('"safeMode" and "ensureOptimizations" flags are mutually exclusive.');
            }
            this.trackStartLines = /full|onlyStart/i.test(this.config.positionTracking);
            this.trackEndLines = /full/i.test(this.config.positionTracking);
            if (Array.isArray(lexerDefinition)) {
              actualDefinition = {
                modes: { defaultMode: [...lexerDefinition] },
                defaultMode: DEFAULT_MODE
              };
            } else {
              hasOnlySingleMode = false;
              actualDefinition = Object.assign({}, lexerDefinition);
            }
          });
          if (this.config.skipValidations === false) {
            this.TRACE_INIT("performRuntimeChecks", () => {
              this.lexerDefinitionErrors = this.lexerDefinitionErrors.concat(performRuntimeChecks(actualDefinition, this.trackStartLines, this.config.lineTerminatorCharacters));
            });
            this.TRACE_INIT("performWarningRuntimeChecks", () => {
              this.lexerDefinitionWarning = this.lexerDefinitionWarning.concat(performWarningRuntimeChecks(actualDefinition, this.trackStartLines, this.config.lineTerminatorCharacters));
            });
          }
          actualDefinition.modes = actualDefinition.modes ? actualDefinition.modes : {};
          Object.entries(actualDefinition.modes).forEach(([currModeName, currModeValue]) => {
            actualDefinition.modes[currModeName] = currModeValue.filter((currTokType) => currTokType !== void 0);
          });
          const allModeNames = Object.keys(actualDefinition.modes);
          Object.entries(actualDefinition.modes).forEach(([currModName, currModDef]) => {
            this.TRACE_INIT(`Mode: <${currModName}> processing`, () => {
              this.modes.push(currModName);
              if (this.config.skipValidations === false) {
                this.TRACE_INIT(`validatePatterns`, () => {
                  this.lexerDefinitionErrors = this.lexerDefinitionErrors.concat(validatePatterns(currModDef, allModeNames));
                });
              }
              if (this.lexerDefinitionErrors.length === 0) {
                augmentTokenTypes(currModDef);
                let currAnalyzeResult;
                this.TRACE_INIT(`analyzeTokenTypes`, () => {
                  currAnalyzeResult = analyzeTokenTypes(currModDef, {
                    lineTerminatorCharacters: this.config.lineTerminatorCharacters,
                    positionTracking: config.positionTracking,
                    ensureOptimizations: config.ensureOptimizations,
                    safeMode: config.safeMode,
                    tracer: this.TRACE_INIT
                  });
                });
                this.patternIdxToConfig[currModName] = currAnalyzeResult.patternIdxToConfig;
                this.charCodeToPatternIdxToConfig[currModName] = currAnalyzeResult.charCodeToPatternIdxToConfig;
                this.emptyGroups = Object.assign({}, this.emptyGroups, currAnalyzeResult.emptyGroups);
                this.hasCustom = currAnalyzeResult.hasCustom || this.hasCustom;
                this.canModeBeOptimized[currModName] = currAnalyzeResult.canBeOptimized;
              }
            });
          });
          this.defaultMode = actualDefinition.defaultMode;
          if (this.lexerDefinitionErrors.length > 0 && !this.config.deferDefinitionErrorsHandling) {
            const allErrMessages = this.lexerDefinitionErrors.map((error) => {
              return error.message;
            });
            const allErrMessagesString = allErrMessages.join("-----------------------\n");
            throw new Error("Errors detected in definition of Lexer:\n" + allErrMessagesString);
          }
          this.lexerDefinitionWarning.forEach((warningDescriptor) => {
            PRINT_WARNING(warningDescriptor.message);
          });
          this.TRACE_INIT("Choosing sub-methods implementations", () => {
            if (hasOnlySingleMode) {
              this.handleModes = () => {
              };
            }
            if (this.trackStartLines === false) {
              this.computeNewColumn = (x) => x;
            }
            if (this.trackEndLines === false) {
              this.updateTokenEndLineColumnLocation = () => {
              };
            }
            if (/full/i.test(this.config.positionTracking)) {
              this.createTokenInstance = this.createFullToken;
            } else if (/onlyStart/i.test(this.config.positionTracking)) {
              this.createTokenInstance = this.createStartOnlyToken;
            } else if (/onlyOffset/i.test(this.config.positionTracking)) {
              this.createTokenInstance = this.createOffsetOnlyToken;
            } else {
              throw Error(`Invalid <positionTracking> config option: "${this.config.positionTracking}"`);
            }
            if (this.hasCustom) {
              this.addToken = this.addTokenUsingPush;
              this.handlePayload = this.handlePayloadWithCustom;
            } else {
              this.addToken = this.addTokenUsingMemberAccess;
              this.handlePayload = this.handlePayloadNoCustom;
            }
          });
          this.TRACE_INIT("Failed Optimization Warnings", () => {
            const unOptimizedModes = Object.entries(this.canModeBeOptimized).reduce((cannotBeOptimized, [modeName, canBeOptimized]) => {
              if (canBeOptimized === false) {
                cannotBeOptimized.push(modeName);
              }
              return cannotBeOptimized;
            }, []);
            if (config.ensureOptimizations && unOptimizedModes.length > 0) {
              throw Error(`Lexer Modes: < ${unOptimizedModes.join(", ")} > cannot be optimized.
	 Disable the "ensureOptimizations" lexer config flag to silently ignore this and run the lexer in an un-optimized mode.
	 Or inspect the console log for details on how to resolve these issues.`);
            }
          });
          this.TRACE_INIT("clearRegExpParserCache", () => {
            clearRegExpParserCache();
          });
          this.TRACE_INIT("toFastProperties", () => {
            toFastProperties(this);
          });
        });
      }
      tokenize(text, initialMode = this.defaultMode) {
        if (this.lexerDefinitionErrors.length > 0) {
          const allErrMessages = this.lexerDefinitionErrors.map((error) => {
            return error.message;
          });
          const allErrMessagesString = allErrMessages.join("-----------------------\n");
          throw new Error("Unable to Tokenize because Errors detected in definition of Lexer:\n" + allErrMessagesString);
        }
        return this.tokenizeInternal(text, initialMode);
      }
      // There is quite a bit of duplication between this and "tokenizeInternalLazy"
      // This is intentional due to performance considerations.
      // this method also used quite a bit of `!` none null assertions because it is too optimized
      // for `tsc` to always understand it is "safe"
      tokenizeInternal(text, initialMode) {
        let i, j, k, matchAltImage, longerAlt, matchedImage, payload, altPayload, imageLength, group, tokType, newToken, errLength, msg, match;
        const orgText = text;
        const orgLength = orgText.length;
        let offset = 0;
        let matchedTokensIndex = 0;
        const guessedNumberOfTokens = this.hasCustom ? 0 : Math.floor(text.length / 10);
        const matchedTokens = new Array(guessedNumberOfTokens);
        const errors = [];
        let line = this.trackStartLines ? 1 : void 0;
        let column = this.trackStartLines ? 1 : void 0;
        const groups = cloneEmptyGroups(this.emptyGroups);
        const trackLines = this.trackStartLines;
        const lineTerminatorPattern = this.config.lineTerminatorsPattern;
        let currModePatternsLength = 0;
        let patternIdxToConfig = [];
        let currCharCodeToPatternIdxToConfig = [];
        const modeStack = [];
        const emptyArray = [];
        Object.freeze(emptyArray);
        let isOptimizedMode = false;
        const pop_mode = (popToken) => {
          if (modeStack.length === 1 && // if we have both a POP_MODE and a PUSH_MODE this is in-fact a "transition"
          // So no error should occur.
          popToken.tokenType.PUSH_MODE === void 0) {
            const msg2 = this.config.errorMessageProvider.buildUnableToPopLexerModeMessage(popToken);
            errors.push({
              offset: popToken.startOffset,
              line: popToken.startLine,
              column: popToken.startColumn,
              length: popToken.image.length,
              message: msg2
            });
          } else {
            modeStack.pop();
            const newMode = modeStack.at(-1);
            patternIdxToConfig = this.patternIdxToConfig[newMode];
            currCharCodeToPatternIdxToConfig = this.charCodeToPatternIdxToConfig[newMode];
            currModePatternsLength = patternIdxToConfig.length;
            const modeCanBeOptimized = this.canModeBeOptimized[newMode] && this.config.safeMode === false;
            if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {
              isOptimizedMode = true;
            } else {
              isOptimizedMode = false;
            }
          }
        };
        function push_mode(newMode) {
          modeStack.push(newMode);
          currCharCodeToPatternIdxToConfig = this.charCodeToPatternIdxToConfig[newMode];
          patternIdxToConfig = this.patternIdxToConfig[newMode];
          currModePatternsLength = patternIdxToConfig.length;
          currModePatternsLength = patternIdxToConfig.length;
          const modeCanBeOptimized = this.canModeBeOptimized[newMode] && this.config.safeMode === false;
          if (currCharCodeToPatternIdxToConfig && modeCanBeOptimized) {
            isOptimizedMode = true;
          } else {
            isOptimizedMode = false;
          }
        }
        push_mode.call(this, initialMode);
        let currConfig;
        const recoveryEnabled = this.config.recoveryEnabled;
        while (offset < orgLength) {
          matchedImage = null;
          imageLength = -1;
          const nextCharCode = orgText.charCodeAt(offset);
          let chosenPatternIdxToConfig;
          if (isOptimizedMode) {
            const optimizedCharIdx = charCodeToOptimizedIndex(nextCharCode);
            const possiblePatterns = currCharCodeToPatternIdxToConfig[optimizedCharIdx];
            chosenPatternIdxToConfig = possiblePatterns !== void 0 ? possiblePatterns : emptyArray;
          } else {
            chosenPatternIdxToConfig = patternIdxToConfig;
          }
          const chosenPatternsLength = chosenPatternIdxToConfig.length;
          for (i = 0; i < chosenPatternsLength; i++) {
            currConfig = chosenPatternIdxToConfig[i];
            const currPattern = currConfig.pattern;
            payload = null;
            const singleCharCode = currConfig.short;
            if (singleCharCode !== false) {
              if (nextCharCode === singleCharCode) {
                imageLength = 1;
                matchedImage = currPattern;
              }
            } else if (currConfig.isCustom === true) {
              match = currPattern.exec(orgText, offset, matchedTokens, groups);
              if (match !== null) {
                matchedImage = match[0];
                imageLength = matchedImage.length;
                if (match.payload !== void 0) {
                  payload = match.payload;
                }
              } else {
                matchedImage = null;
              }
            } else {
              currPattern.lastIndex = offset;
              imageLength = this.matchLength(currPattern, text, offset);
            }
            if (imageLength !== -1) {
              longerAlt = currConfig.longerAlt;
              if (longerAlt !== void 0) {
                matchedImage = text.substring(offset, offset + imageLength);
                const longerAltLength = longerAlt.length;
                for (k = 0; k < longerAltLength; k++) {
                  const longerAltConfig = patternIdxToConfig[longerAlt[k]];
                  const longerAltPattern = longerAltConfig.pattern;
                  altPayload = null;
                  if (longerAltConfig.isCustom === true) {
                    match = longerAltPattern.exec(orgText, offset, matchedTokens, groups);
                    if (match !== null) {
                      matchAltImage = match[0];
                      if (match.payload !== void 0) {
                        altPayload = match.payload;
                      }
                    } else {
                      matchAltImage = null;
                    }
                  } else {
                    longerAltPattern.lastIndex = offset;
                    matchAltImage = this.match(longerAltPattern, text, offset);
                  }
                  if (matchAltImage && matchAltImage.length > matchedImage.length) {
                    matchedImage = matchAltImage;
                    imageLength = matchAltImage.length;
                    payload = altPayload;
                    currConfig = longerAltConfig;
                    break;
                  }
                }
              }
              break;
            }
          }
          if (imageLength !== -1) {
            group = currConfig.group;
            if (group !== void 0) {
              matchedImage = matchedImage !== null ? matchedImage : text.substring(offset, offset + imageLength);
              tokType = currConfig.tokenTypeIdx;
              newToken = this.createTokenInstance(matchedImage, offset, tokType, currConfig.tokenType, line, column, imageLength);
              this.handlePayload(newToken, payload);
              if (group === false) {
                matchedTokensIndex = this.addToken(matchedTokens, matchedTokensIndex, newToken);
              } else {
                groups[group].push(newToken);
              }
            }
            if (trackLines === true && currConfig.canLineTerminator === true) {
              let numOfLTsInMatch = 0;
              let foundTerminator;
              let lastLTEndOffset;
              lineTerminatorPattern.lastIndex = 0;
              do {
                matchedImage = matchedImage !== null ? matchedImage : text.substring(offset, offset + imageLength);
                foundTerminator = lineTerminatorPattern.test(matchedImage);
                if (foundTerminator === true) {
                  lastLTEndOffset = lineTerminatorPattern.lastIndex - 1;
                  numOfLTsInMatch++;
                }
              } while (foundTerminator === true);
              if (numOfLTsInMatch !== 0) {
                line = line + numOfLTsInMatch;
                column = imageLength - lastLTEndOffset;
                this.updateTokenEndLineColumnLocation(newToken, group, lastLTEndOffset, numOfLTsInMatch, line, column, imageLength);
              } else {
                column = this.computeNewColumn(column, imageLength);
              }
            } else {
              column = this.computeNewColumn(column, imageLength);
            }
            offset = offset + imageLength;
            this.handleModes(currConfig, pop_mode, push_mode, newToken);
          } else {
            const errorStartOffset = offset;
            const errorLine = line;
            const errorColumn = column;
            let foundResyncPoint = recoveryEnabled === false;
            while (foundResyncPoint === false && offset < orgLength) {
              offset++;
              for (j = 0; j < currModePatternsLength; j++) {
                const currConfig2 = patternIdxToConfig[j];
                const currPattern = currConfig2.pattern;
                const singleCharCode = currConfig2.short;
                if (singleCharCode !== false) {
                  if (orgText.charCodeAt(offset) === singleCharCode) {
                    foundResyncPoint = true;
                  }
                } else if (currConfig2.isCustom === true) {
                  foundResyncPoint = currPattern.exec(orgText, offset, matchedTokens, groups) !== null;
                } else {
                  currPattern.lastIndex = offset;
                  foundResyncPoint = currPattern.exec(text) !== null;
                }
                if (foundResyncPoint === true) {
                  break;
                }
              }
            }
            errLength = offset - errorStartOffset;
            column = this.computeNewColumn(column, errLength);
            msg = this.config.errorMessageProvider.buildUnexpectedCharactersMessage(orgText, errorStartOffset, errLength, errorLine, errorColumn, modeStack.at(-1));
            errors.push({
              offset: errorStartOffset,
              line: errorLine,
              column: errorColumn,
              length: errLength,
              message: msg
            });
            if (recoveryEnabled === false) {
              break;
            }
          }
        }
        if (!this.hasCustom) {
          matchedTokens.length = matchedTokensIndex;
        }
        return {
          tokens: matchedTokens,
          groups,
          errors
        };
      }
      handleModes(config, pop_mode, push_mode, newToken) {
        if (config.pop === true) {
          const pushMode = config.push;
          pop_mode(newToken);
          if (pushMode !== void 0) {
            push_mode.call(this, pushMode);
          }
        } else if (config.push !== void 0) {
          push_mode.call(this, config.push);
        }
      }
      // TODO: decrease this under 600 characters? inspect stripping comments option in TSC compiler
      updateTokenEndLineColumnLocation(newToken, group, lastLTIdx, numOfLTsInMatch, line, column, imageLength) {
        let lastCharIsLT, fixForEndingInLT;
        if (group !== void 0) {
          lastCharIsLT = lastLTIdx === imageLength - 1;
          fixForEndingInLT = lastCharIsLT ? -1 : 0;
          if (!(numOfLTsInMatch === 1 && lastCharIsLT === true)) {
            newToken.endLine = line + fixForEndingInLT;
            newToken.endColumn = column - 1 + -fixForEndingInLT;
          }
        }
      }
      computeNewColumn(oldColumn, imageLength) {
        return oldColumn + imageLength;
      }
      createOffsetOnlyToken(image, startOffset, tokenTypeIdx, tokenType) {
        return {
          image,
          startOffset,
          tokenTypeIdx,
          tokenType
        };
      }
      createStartOnlyToken(image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn) {
        return {
          image,
          startOffset,
          startLine,
          startColumn,
          tokenTypeIdx,
          tokenType
        };
      }
      createFullToken(image, startOffset, tokenTypeIdx, tokenType, startLine, startColumn, imageLength) {
        return {
          image,
          startOffset,
          endOffset: startOffset + imageLength - 1,
          startLine,
          endLine: startLine,
          startColumn,
          endColumn: startColumn + imageLength - 1,
          tokenTypeIdx,
          tokenType
        };
      }
      addTokenUsingPush(tokenVector, index, tokenToAdd) {
        tokenVector.push(tokenToAdd);
        return index;
      }
      addTokenUsingMemberAccess(tokenVector, index, tokenToAdd) {
        tokenVector[index] = tokenToAdd;
        index++;
        return index;
      }
      handlePayloadNoCustom(token, payload) {
      }
      handlePayloadWithCustom(token, payload) {
        if (payload !== null) {
          token.payload = payload;
        }
      }
      match(pattern, text, offset) {
        const found = pattern.test(text);
        if (found === true) {
          return text.substring(offset, pattern.lastIndex);
        }
        return null;
      }
      matchLength(pattern, text, offset) {
        const found = pattern.test(text);
        if (found === true) {
          return pattern.lastIndex - offset;
        }
        return -1;
      }
    }
    Lexer.SKIPPED = "This marks a skipped Token pattern, this means each token identified by it will be consumed and then thrown into oblivion, this can be used to for example to completely ignore whitespace.";
    Lexer.NA = /NOT_APPLICABLE/;
    function tokenLabel(tokType) {
      if (hasTokenLabel(tokType)) {
        return tokType.LABEL;
      } else {
        return tokType.name;
      }
    }
    function hasTokenLabel(obj) {
      return typeof obj.LABEL === "string" && obj.LABEL !== "";
    }
    const PARENT = "parent";
    const CATEGORIES = "categories";
    const LABEL = "label";
    const GROUP$1 = "group";
    const PUSH_MODE = "push_mode";
    const POP_MODE = "pop_mode";
    const LONGER_ALT = "longer_alt";
    const LINE_BREAKS = "line_breaks";
    const START_CHARS_HINT = "start_chars_hint";
    function createToken(config) {
      return createTokenInternal(config);
    }
    function createTokenInternal(config) {
      const pattern = config.pattern;
      const tokenType = {};
      tokenType.name = config.name;
      if (pattern !== void 0) {
        tokenType.PATTERN = pattern;
      }
      if (Object.hasOwn(config, PARENT)) {
        throw "The parent property is no longer supported.\nSee: https://github.com/chevrotain/chevrotain/issues/564#issuecomment-349062346 for details.";
      }
      if (Object.hasOwn(config, CATEGORIES)) {
        tokenType.CATEGORIES = config[CATEGORIES];
      }
      augmentTokenTypes([tokenType]);
      if (Object.hasOwn(config, LABEL)) {
        tokenType.LABEL = config[LABEL];
      }
      if (Object.hasOwn(config, GROUP$1)) {
        tokenType.GROUP = config[GROUP$1];
      }
      if (Object.hasOwn(config, POP_MODE)) {
        tokenType.POP_MODE = config[POP_MODE];
      }
      if (Object.hasOwn(config, PUSH_MODE)) {
        tokenType.PUSH_MODE = config[PUSH_MODE];
      }
      if (Object.hasOwn(config, LONGER_ALT)) {
        tokenType.LONGER_ALT = config[LONGER_ALT];
      }
      if (Object.hasOwn(config, LINE_BREAKS)) {
        tokenType.LINE_BREAKS = config[LINE_BREAKS];
      }
      if (Object.hasOwn(config, START_CHARS_HINT)) {
        tokenType.START_CHARS_HINT = config[START_CHARS_HINT];
      }
      return tokenType;
    }
    const EOF = createToken({ name: "EOF", pattern: Lexer.NA });
    augmentTokenTypes([EOF]);
    function createTokenInstance(tokType, image, startOffset, endOffset, startLine, endLine, startColumn, endColumn) {
      return {
        image,
        startOffset,
        endOffset,
        startLine,
        endLine,
        startColumn,
        endColumn,
        tokenTypeIdx: tokType.tokenTypeIdx,
        tokenType: tokType
      };
    }
    function tokenMatcher(token, tokType) {
      return tokenStructuredMatcher(token, tokType);
    }
    const defaultParserErrorProvider = {
      buildMismatchTokenMessage({ expected, actual, previous, ruleName }) {
        const hasLabel = hasTokenLabel(expected);
        const expectedMsg = hasLabel ? `--> ${tokenLabel(expected)} <--` : `token of type --> ${expected.name} <--`;
        const msg = `Expecting ${expectedMsg} but found --> '${actual.image}' <--`;
        return msg;
      },
      buildNotAllInputParsedMessage({ firstRedundant, ruleName }) {
        return "Redundant input, expecting EOF but found: " + firstRedundant.image;
      },
      buildNoViableAltMessage({ expectedPathsPerAlt, actual, previous, customUserDescription, ruleName }) {
        const errPrefix = "Expecting: ";
        const actualText = actual[0].image;
        const errSuffix = "\nbut found: '" + actualText + "'";
        if (customUserDescription) {
          return errPrefix + customUserDescription + errSuffix;
        } else {
          const allLookAheadPaths = expectedPathsPerAlt.reduce((result, currAltPaths) => result.concat(currAltPaths), []);
          const nextValidTokenSequences = allLookAheadPaths.map((currPath) => `[${currPath.map((currTokenType) => tokenLabel(currTokenType)).join(", ")}]`);
          const nextValidSequenceItems = nextValidTokenSequences.map((itemMsg, idx) => `  ${idx + 1}. ${itemMsg}`);
          const calculatedDescription = `one of these possible Token sequences:
${nextValidSequenceItems.join("\n")}`;
          return errPrefix + calculatedDescription + errSuffix;
        }
      },
      buildEarlyExitMessage({ expectedIterationPaths, actual, customUserDescription, ruleName }) {
        const errPrefix = "Expecting: ";
        const actualText = actual[0].image;
        const errSuffix = "\nbut found: '" + actualText + "'";
        if (customUserDescription) {
          return errPrefix + customUserDescription + errSuffix;
        } else {
          const nextValidTokenSequences = expectedIterationPaths.map((currPath) => `[${currPath.map((currTokenType) => tokenLabel(currTokenType)).join(",")}]`);
          const calculatedDescription = `expecting at least one iteration which starts with one of these possible Token sequences::
  <${nextValidTokenSequences.join(" ,")}>`;
          return errPrefix + calculatedDescription + errSuffix;
        }
      }
    };
    Object.freeze(defaultParserErrorProvider);
    const defaultGrammarResolverErrorProvider = {
      buildRuleNotFoundError(topLevelRule, undefinedRule) {
        const msg = "Invalid grammar, reference to a rule which is not defined: ->" + undefinedRule.nonTerminalName + "<-\ninside top level rule: ->" + topLevelRule.name + "<-";
        return msg;
      }
    };
    const defaultGrammarValidatorErrorProvider = {
      buildDuplicateFoundError(topLevelRule, duplicateProds) {
        function getExtraProductionArgument2(prod) {
          if (prod instanceof Terminal) {
            return prod.terminalType.name;
          } else if (prod instanceof NonTerminal) {
            return prod.nonTerminalName;
          } else {
            return "";
          }
        }
        const topLevelName = topLevelRule.name;
        const duplicateProd = duplicateProds[0];
        const index = duplicateProd.idx;
        const dslName = getProductionDslName$1(duplicateProd);
        const extraArgument = getExtraProductionArgument2(duplicateProd);
        const hasExplicitIndex = index > 0;
        let msg = `->${dslName}${hasExplicitIndex ? index : ""}<- ${extraArgument ? `with argument: ->${extraArgument}<-` : ""}
                  appears more than once (${duplicateProds.length} times) in the top level rule: ->${topLevelName}<-.                  
                  For further details see: https://chevrotain.io/docs/FAQ.html#NUMERICAL_SUFFIXES 
                  `;
        msg = msg.replace(/[ \t]+/g, " ");
        msg = msg.replace(/\s\s+/g, "\n");
        return msg;
      },
      buildNamespaceConflictError(rule) {
        const errMsg = `Namespace conflict found in grammar.
The grammar has both a Terminal(Token) and a Non-Terminal(Rule) named: <${rule.name}>.
To resolve this make sure each Terminal and Non-Terminal names are unique
This is easy to accomplish by using the convention that Terminal names start with an uppercase letter
and Non-Terminal names start with a lower case letter.`;
        return errMsg;
      },
      buildAlternationPrefixAmbiguityError(options) {
        const pathMsg = options.prefixPath.map((currTok) => tokenLabel(currTok)).join(", ");
        const occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx;
        const errMsg = `Ambiguous alternatives: <${options.ambiguityIndices.join(" ,")}> due to common lookahead prefix
in <OR${occurrence}> inside <${options.topLevelRule.name}> Rule,
<${pathMsg}> may appears as a prefix path in all these alternatives.
See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#COMMON_PREFIX
For Further details.`;
        return errMsg;
      },
      buildAlternationAmbiguityError(options) {
        const occurrence = options.alternation.idx === 0 ? "" : options.alternation.idx;
        const isEmptyPath = options.prefixPath.length === 0;
        let currMessage = `Ambiguous Alternatives Detected: <${options.ambiguityIndices.join(" ,")}> in <OR${occurrence}> inside <${options.topLevelRule.name}> Rule,
`;
        if (isEmptyPath) {
          currMessage += `These alternatives are all empty (match no tokens), making them indistinguishable.
Only the last alternative may be empty.
`;
        } else {
          const pathMsg = options.prefixPath.map((currtok) => tokenLabel(currtok)).join(", ");
          currMessage += `<${pathMsg}> may appears as a prefix path in all these alternatives.
`;
        }
        currMessage += `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES
For Further details.`;
        return currMessage;
      },
      buildEmptyRepetitionError(options) {
        let dslName = getProductionDslName$1(options.repetition);
        if (options.repetition.idx !== 0) {
          dslName += options.repetition.idx;
        }
        const errMsg = `The repetition <${dslName}> within Rule <${options.topLevelRule.name}> can never consume any tokens.
This could lead to an infinite loop.`;
        return errMsg;
      },
      // TODO: remove - `errors_public` from nyc.config.js exclude
      //       once this method is fully removed from this file
      buildTokenNameError(options) {
        return "deprecated";
      },
      buildEmptyAlternationError(options) {
        const errMsg = `Ambiguous empty alternative: <${options.emptyChoiceIdx + 1}> in <OR${options.alternation.idx}> inside <${options.topLevelRule.name}> Rule.
Only the last alternative may be an empty alternative.`;
        return errMsg;
      },
      buildTooManyAlternativesError(options) {
        const errMsg = `An Alternation cannot have more than 256 alternatives:
<OR${options.alternation.idx}> inside <${options.topLevelRule.name}> Rule.
 has ${options.alternation.definition.length + 1} alternatives.`;
        return errMsg;
      },
      buildLeftRecursionError(options) {
        const ruleName = options.topLevelRule.name;
        const pathNames = options.leftRecursionPath.map((currRule) => currRule.name);
        const leftRecursivePath = `${ruleName} --> ${pathNames.concat([ruleName]).join(" --> ")}`;
        const errMsg = `Left Recursion found in grammar.
rule: <${ruleName}> can be invoked from itself (directly or indirectly)
without consuming any Tokens. The grammar path that causes this is: 
 ${leftRecursivePath}
 To fix this refactor your grammar to remove the left recursion.
see: https://en.wikipedia.org/wiki/LL_parser#Left_factoring.`;
        return errMsg;
      },
      // TODO: remove - `errors_public` from nyc.config.js exclude
      //       once this method is fully removed from this file
      buildInvalidRuleNameError(options) {
        return "deprecated";
      },
      buildDuplicateRuleNameError(options) {
        let ruleName;
        if (options.topLevelRule instanceof Rule) {
          ruleName = options.topLevelRule.name;
        } else {
          ruleName = options.topLevelRule;
        }
        const errMsg = `Duplicate definition, rule: ->${ruleName}<- is already defined in the grammar: ->${options.grammarName}<-`;
        return errMsg;
      }
    };
    function resolveGrammar$1(topLevels, errMsgProvider) {
      const refResolver = new GastRefResolverVisitor(topLevels, errMsgProvider);
      refResolver.resolveRefs();
      return refResolver.errors;
    }
    class GastRefResolverVisitor extends GAstVisitor {
      constructor(nameToTopRule, errMsgProvider) {
        super();
        this.nameToTopRule = nameToTopRule;
        this.errMsgProvider = errMsgProvider;
        this.errors = [];
      }
      resolveRefs() {
        Object.values(this.nameToTopRule).forEach((prod) => {
          this.currTopLevel = prod;
          prod.accept(this);
        });
      }
      visitNonTerminal(node2) {
        const ref = this.nameToTopRule[node2.nonTerminalName];
        if (!ref) {
          const msg = this.errMsgProvider.buildRuleNotFoundError(this.currTopLevel, node2);
          this.errors.push({
            message: msg,
            type: ParserDefinitionErrorType.UNRESOLVED_SUBRULE_REF,
            ruleName: this.currTopLevel.name,
            unresolvedRefName: node2.nonTerminalName
          });
        } else {
          node2.referencedRule = ref;
        }
      }
    }
    class AbstractNextPossibleTokensWalker extends RestWalker {
      constructor(topProd, path) {
        super();
        this.topProd = topProd;
        this.path = path;
        this.possibleTokTypes = [];
        this.nextProductionName = "";
        this.nextProductionOccurrence = 0;
        this.found = false;
        this.isAtEndOfPath = false;
      }
      startWalking() {
        this.found = false;
        if (this.path.ruleStack[0] !== this.topProd.name) {
          throw Error("The path does not start with the walker's top Rule!");
        }
        this.ruleStack = [...this.path.ruleStack].reverse();
        this.occurrenceStack = [...this.path.occurrenceStack].reverse();
        this.ruleStack.pop();
        this.occurrenceStack.pop();
        this.updateExpectedNext();
        this.walk(this.topProd);
        return this.possibleTokTypes;
      }
      walk(prod, prevRest = []) {
        if (!this.found) {
          super.walk(prod, prevRest);
        }
      }
      walkProdRef(refProd, currRest, prevRest) {
        if (refProd.referencedRule.name === this.nextProductionName && refProd.idx === this.nextProductionOccurrence) {
          const fullRest = currRest.concat(prevRest);
          this.updateExpectedNext();
          this.walk(refProd.referencedRule, fullRest);
        }
      }
      updateExpectedNext() {
        if (this.ruleStack.length === 0) {
          this.nextProductionName = "";
          this.nextProductionOccurrence = 0;
          this.isAtEndOfPath = true;
        } else {
          this.nextProductionName = this.ruleStack.pop();
          this.nextProductionOccurrence = this.occurrenceStack.pop();
        }
      }
    }
    class NextAfterTokenWalker extends AbstractNextPossibleTokensWalker {
      constructor(topProd, path) {
        super(topProd, path);
        this.path = path;
        this.nextTerminalName = "";
        this.nextTerminalOccurrence = 0;
        this.nextTerminalName = this.path.lastTok.name;
        this.nextTerminalOccurrence = this.path.lastTokOccurrence;
      }
      walkTerminal(terminal, currRest, prevRest) {
        if (this.isAtEndOfPath && terminal.terminalType.name === this.nextTerminalName && terminal.idx === this.nextTerminalOccurrence && !this.found) {
          const fullRest = currRest.concat(prevRest);
          const restProd = new Alternative({ definition: fullRest });
          this.possibleTokTypes = first(restProd);
          this.found = true;
        }
      }
    }
    class AbstractNextTerminalAfterProductionWalker extends RestWalker {
      constructor(topRule, occurrence) {
        super();
        this.topRule = topRule;
        this.occurrence = occurrence;
        this.result = {
          token: void 0,
          occurrence: void 0,
          isEndOfRule: void 0
        };
      }
      startWalking() {
        this.walk(this.topRule);
        return this.result;
      }
    }
    class NextTerminalAfterManyWalker extends AbstractNextTerminalAfterProductionWalker {
      walkMany(manyProd, currRest, prevRest) {
        if (manyProd.idx === this.occurrence) {
          const firstAfterMany = currRest.concat(prevRest)[0];
          this.result.isEndOfRule = firstAfterMany === void 0;
          if (firstAfterMany instanceof Terminal) {
            this.result.token = firstAfterMany.terminalType;
            this.result.occurrence = firstAfterMany.idx;
          }
        } else {
          super.walkMany(manyProd, currRest, prevRest);
        }
      }
    }
    class NextTerminalAfterManySepWalker extends AbstractNextTerminalAfterProductionWalker {
      walkManySep(manySepProd, currRest, prevRest) {
        if (manySepProd.idx === this.occurrence) {
          const firstAfterManySep = currRest.concat(prevRest)[0];
          this.result.isEndOfRule = firstAfterManySep === void 0;
          if (firstAfterManySep instanceof Terminal) {
            this.result.token = firstAfterManySep.terminalType;
            this.result.occurrence = firstAfterManySep.idx;
          }
        } else {
          super.walkManySep(manySepProd, currRest, prevRest);
        }
      }
    }
    class NextTerminalAfterAtLeastOneWalker extends AbstractNextTerminalAfterProductionWalker {
      walkAtLeastOne(atLeastOneProd, currRest, prevRest) {
        if (atLeastOneProd.idx === this.occurrence) {
          const firstAfterAtLeastOne = currRest.concat(prevRest)[0];
          this.result.isEndOfRule = firstAfterAtLeastOne === void 0;
          if (firstAfterAtLeastOne instanceof Terminal) {
            this.result.token = firstAfterAtLeastOne.terminalType;
            this.result.occurrence = firstAfterAtLeastOne.idx;
          }
        } else {
          super.walkAtLeastOne(atLeastOneProd, currRest, prevRest);
        }
      }
    }
    class NextTerminalAfterAtLeastOneSepWalker extends AbstractNextTerminalAfterProductionWalker {
      walkAtLeastOneSep(atleastOneSepProd, currRest, prevRest) {
        if (atleastOneSepProd.idx === this.occurrence) {
          const firstAfterfirstAfterAtLeastOneSep = currRest.concat(prevRest)[0];
          this.result.isEndOfRule = firstAfterfirstAfterAtLeastOneSep === void 0;
          if (firstAfterfirstAfterAtLeastOneSep instanceof Terminal) {
            this.result.token = firstAfterfirstAfterAtLeastOneSep.terminalType;
            this.result.occurrence = firstAfterfirstAfterAtLeastOneSep.idx;
          }
        } else {
          super.walkAtLeastOneSep(atleastOneSepProd, currRest, prevRest);
        }
      }
    }
    function possiblePathsFrom(targetDef, maxLength, currPath = []) {
      currPath = [...currPath];
      let result = [];
      let i = 0;
      function remainingPathWith(nextDef) {
        return nextDef.concat(targetDef.slice(i + 1));
      }
      function getAlternativesForProd(definition) {
        const alternatives = possiblePathsFrom(remainingPathWith(definition), maxLength, currPath);
        return result.concat(alternatives);
      }
      while (currPath.length < maxLength && i < targetDef.length) {
        const prod = targetDef[i];
        if (prod instanceof Alternative) {
          return getAlternativesForProd(prod.definition);
        } else if (prod instanceof NonTerminal) {
          return getAlternativesForProd(prod.definition);
        } else if (prod instanceof Option) {
          result = getAlternativesForProd(prod.definition);
        } else if (prod instanceof RepetitionMandatory) {
          const newDef = prod.definition.concat([
            new Repetition({
              definition: prod.definition
            })
          ]);
          return getAlternativesForProd(newDef);
        } else if (prod instanceof RepetitionMandatoryWithSeparator) {
          const newDef = [
            new Alternative({ definition: prod.definition }),
            new Repetition({
              definition: [new Terminal({ terminalType: prod.separator })].concat(prod.definition)
            })
          ];
          return getAlternativesForProd(newDef);
        } else if (prod instanceof RepetitionWithSeparator) {
          const newDef = prod.definition.concat([
            new Repetition({
              definition: [new Terminal({ terminalType: prod.separator })].concat(prod.definition)
            })
          ]);
          result = getAlternativesForProd(newDef);
        } else if (prod instanceof Repetition) {
          const newDef = prod.definition.concat([
            new Repetition({
              definition: prod.definition
            })
          ]);
          result = getAlternativesForProd(newDef);
        } else if (prod instanceof Alternation) {
          prod.definition.forEach((currAlt) => {
            if (currAlt.definition.length !== 0) {
              result = getAlternativesForProd(currAlt.definition);
            }
          });
          return result;
        } else if (prod instanceof Terminal) {
          currPath.push(prod.terminalType);
        } else {
          throw Error("non exhaustive match");
        }
        i++;
      }
      result.push({
        partialPath: currPath,
        suffixDef: targetDef.slice(i)
      });
      return result;
    }
    function nextPossibleTokensAfter(initialDef, tokenVector, tokMatcher, maxLookAhead) {
      const EXIT_NON_TERMINAL = "EXIT_NONE_TERMINAL";
      const EXIT_NON_TERMINAL_ARR = [EXIT_NON_TERMINAL];
      const EXIT_ALTERNATIVE = "EXIT_ALTERNATIVE";
      let foundCompletePath = false;
      const tokenVectorLength = tokenVector.length;
      const minimalAlternativesIndex = tokenVectorLength - maxLookAhead - 1;
      const result = [];
      const possiblePaths = [];
      possiblePaths.push({
        idx: -1,
        def: initialDef,
        ruleStack: [],
        occurrenceStack: []
      });
      while (possiblePaths.length !== 0) {
        const currPath = possiblePaths.pop();
        if (currPath === EXIT_ALTERNATIVE) {
          if (foundCompletePath && possiblePaths.at(-1).idx <= minimalAlternativesIndex) {
            possiblePaths.pop();
          }
          continue;
        }
        const currDef = currPath.def;
        const currIdx = currPath.idx;
        const currRuleStack = currPath.ruleStack;
        const currOccurrenceStack = currPath.occurrenceStack;
        if (currDef.length === 0) {
          continue;
        }
        const prod = currDef[0];
        if (prod === EXIT_NON_TERMINAL) {
          const nextPath = {
            idx: currIdx,
            def: currDef.slice(1),
            ruleStack: currRuleStack.slice(0, -1),
            occurrenceStack: currOccurrenceStack.slice(0, -1)
          };
          possiblePaths.push(nextPath);
        } else if (prod instanceof Terminal) {
          if (currIdx < tokenVectorLength - 1) {
            const nextIdx = currIdx + 1;
            const actualToken = tokenVector[nextIdx];
            if (tokMatcher(actualToken, prod.terminalType)) {
              const nextPath = {
                idx: nextIdx,
                def: currDef.slice(1),
                ruleStack: currRuleStack,
                occurrenceStack: currOccurrenceStack
              };
              possiblePaths.push(nextPath);
            }
          } else if (currIdx === tokenVectorLength - 1) {
            result.push({
              nextTokenType: prod.terminalType,
              nextTokenOccurrence: prod.idx,
              ruleStack: currRuleStack,
              occurrenceStack: currOccurrenceStack
            });
            foundCompletePath = true;
          } else {
            throw Error("non exhaustive match");
          }
        } else if (prod instanceof NonTerminal) {
          const newRuleStack = [...currRuleStack];
          newRuleStack.push(prod.nonTerminalName);
          const newOccurrenceStack = [...currOccurrenceStack];
          newOccurrenceStack.push(prod.idx);
          const nextPath = {
            idx: currIdx,
            def: prod.definition.concat(EXIT_NON_TERMINAL_ARR, currDef.slice(1)),
            ruleStack: newRuleStack,
            occurrenceStack: newOccurrenceStack
          };
          possiblePaths.push(nextPath);
        } else if (prod instanceof Option) {
          const nextPathWithout = {
            idx: currIdx,
            def: currDef.slice(1),
            ruleStack: currRuleStack,
            occurrenceStack: currOccurrenceStack
          };
          possiblePaths.push(nextPathWithout);
          possiblePaths.push(EXIT_ALTERNATIVE);
          const nextPathWith = {
            idx: currIdx,
            def: prod.definition.concat(currDef.slice(1)),
            ruleStack: currRuleStack,
            occurrenceStack: currOccurrenceStack
          };
          possiblePaths.push(nextPathWith);
        } else if (prod instanceof RepetitionMandatory) {
          const secondIteration = new Repetition({
            definition: prod.definition,
            idx: prod.idx
          });
          const nextDef = prod.definition.concat([secondIteration], currDef.slice(1));
          const nextPath = {
            idx: currIdx,
            def: nextDef,
            ruleStack: currRuleStack,
            occurrenceStack: currOccurrenceStack
          };
          possiblePaths.push(nextPath);
        } else if (prod instanceof RepetitionMandatoryWithSeparator) {
          const separatorGast = new Terminal({
            terminalType: prod.separator
          });
          const secondIteration = new Repetition({
            definition: [separatorGast].concat(prod.definition),
            idx: prod.idx
          });
          const nextDef = prod.definition.concat([secondIteration], currDef.slice(1));
          const nextPath = {
            idx: currIdx,
            def: nextDef,
            ruleStack: currRuleStack,
            occurrenceStack: currOccurrenceStack
          };
          possiblePaths.push(nextPath);
        } else if (prod instanceof RepetitionWithSeparator) {
          const nextPathWithout = {
            idx: currIdx,
            def: currDef.slice(1),
            ruleStack: currRuleStack,
            occurrenceStack: currOccurrenceStack
          };
          possiblePaths.push(nextPathWithout);
          possiblePaths.push(EXIT_ALTERNATIVE);
          const separatorGast = new Terminal({
            terminalType: prod.separator
          });
          const nthRepetition = new Repetition({
            definition: [separatorGast].concat(prod.definition),
            idx: prod.idx
          });
          const nextDef = prod.definition.concat([nthRepetition], currDef.slice(1));
          const nextPathWith = {
            idx: currIdx,
            def: nextDef,
            ruleStack: currRuleStack,
            occurrenceStack: currOccurrenceStack
          };
          possiblePaths.push(nextPathWith);
        } else if (prod instanceof Repetition) {
          const nextPathWithout = {
            idx: currIdx,
            def: currDef.slice(1),
            ruleStack: currRuleStack,
            occurrenceStack: currOccurrenceStack
          };
          possiblePaths.push(nextPathWithout);
          possiblePaths.push(EXIT_ALTERNATIVE);
          const nthRepetition = new Repetition({
            definition: prod.definition,
            idx: prod.idx
          });
          const nextDef = prod.definition.concat([nthRepetition], currDef.slice(1));
          const nextPathWith = {
            idx: currIdx,
            def: nextDef,
            ruleStack: currRuleStack,
            occurrenceStack: currOccurrenceStack
          };
          possiblePaths.push(nextPathWith);
        } else if (prod instanceof Alternation) {
          for (let i = prod.definition.length - 1; i >= 0; i--) {
            const currAlt = prod.definition[i];
            const currAltPath = {
              idx: currIdx,
              def: currAlt.definition.concat(currDef.slice(1)),
              ruleStack: currRuleStack,
              occurrenceStack: currOccurrenceStack
            };
            possiblePaths.push(currAltPath);
            possiblePaths.push(EXIT_ALTERNATIVE);
          }
        } else if (prod instanceof Alternative) {
          possiblePaths.push({
            idx: currIdx,
            def: prod.definition.concat(currDef.slice(1)),
            ruleStack: currRuleStack,
            occurrenceStack: currOccurrenceStack
          });
        } else if (prod instanceof Rule) {
          possiblePaths.push(expandTopLevelRule(prod, currIdx, currRuleStack, currOccurrenceStack));
        } else {
          throw Error("non exhaustive match");
        }
      }
      return result;
    }
    function expandTopLevelRule(topRule, currIdx, currRuleStack, currOccurrenceStack) {
      const newRuleStack = [...currRuleStack];
      newRuleStack.push(topRule.name);
      const newCurrOccurrenceStack = [...currOccurrenceStack];
      newCurrOccurrenceStack.push(1);
      return {
        idx: currIdx,
        def: topRule.definition,
        ruleStack: newRuleStack,
        occurrenceStack: newCurrOccurrenceStack
      };
    }
    var PROD_TYPE;
    (function(PROD_TYPE2) {
      PROD_TYPE2[PROD_TYPE2["OPTION"] = 0] = "OPTION";
      PROD_TYPE2[PROD_TYPE2["REPETITION"] = 1] = "REPETITION";
      PROD_TYPE2[PROD_TYPE2["REPETITION_MANDATORY"] = 2] = "REPETITION_MANDATORY";
      PROD_TYPE2[PROD_TYPE2["REPETITION_MANDATORY_WITH_SEPARATOR"] = 3] = "REPETITION_MANDATORY_WITH_SEPARATOR";
      PROD_TYPE2[PROD_TYPE2["REPETITION_WITH_SEPARATOR"] = 4] = "REPETITION_WITH_SEPARATOR";
      PROD_TYPE2[PROD_TYPE2["ALTERNATION"] = 5] = "ALTERNATION";
    })(PROD_TYPE || (PROD_TYPE = {}));
    function getProdType$1(prod) {
      if (prod instanceof Option || prod === "Option") {
        return PROD_TYPE.OPTION;
      } else if (prod instanceof Repetition || prod === "Repetition") {
        return PROD_TYPE.REPETITION;
      } else if (prod instanceof RepetitionMandatory || prod === "RepetitionMandatory") {
        return PROD_TYPE.REPETITION_MANDATORY;
      } else if (prod instanceof RepetitionMandatoryWithSeparator || prod === "RepetitionMandatoryWithSeparator") {
        return PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR;
      } else if (prod instanceof RepetitionWithSeparator || prod === "RepetitionWithSeparator") {
        return PROD_TYPE.REPETITION_WITH_SEPARATOR;
      } else if (prod instanceof Alternation || prod === "Alternation") {
        return PROD_TYPE.ALTERNATION;
      } else {
        throw Error("non exhaustive match");
      }
    }
    function getLookaheadPaths(options) {
      const { occurrence, rule, prodType, maxLookahead } = options;
      const type = getProdType$1(prodType);
      if (type === PROD_TYPE.ALTERNATION) {
        return getLookaheadPathsForOr(occurrence, rule, maxLookahead);
      } else {
        return getLookaheadPathsForOptionalProd(occurrence, rule, type, maxLookahead);
      }
    }
    function buildLookaheadFuncForOr(occurrence, ruleGrammar, maxLookahead, hasPredicates, dynamicTokensEnabled, laFuncBuilder) {
      const lookAheadPaths = getLookaheadPathsForOr(occurrence, ruleGrammar, maxLookahead);
      const tokenMatcher2 = areTokenCategoriesNotUsed(lookAheadPaths) ? tokenStructuredMatcherNoCategories : tokenStructuredMatcher;
      return laFuncBuilder(lookAheadPaths, hasPredicates, tokenMatcher2, dynamicTokensEnabled);
    }
    function buildLookaheadFuncForOptionalProd(occurrence, ruleGrammar, k, dynamicTokensEnabled, prodType, lookaheadBuilder) {
      const lookAheadPaths = getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, k);
      const tokenMatcher2 = areTokenCategoriesNotUsed(lookAheadPaths) ? tokenStructuredMatcherNoCategories : tokenStructuredMatcher;
      return lookaheadBuilder(lookAheadPaths[0], tokenMatcher2, dynamicTokensEnabled);
    }
    function buildAlternativesLookAheadFunc(alts, hasPredicates, tokenMatcher2, dynamicTokensEnabled) {
      const numOfAlts = alts.length;
      const areAllOneTokenLookahead = alts.every((currAlt) => {
        return currAlt.every((currPath) => {
          return currPath.length === 1;
        });
      });
      if (hasPredicates) {
        return function(orAlts) {
          const predicates = orAlts.map((currAlt) => currAlt.GATE);
          for (let t = 0; t < numOfAlts; t++) {
            const currAlt = alts[t];
            const currNumOfPaths = currAlt.length;
            const currPredicate = predicates[t];
            if (currPredicate !== void 0 && currPredicate.call(this) === false) {
              continue;
            }
            nextPath: for (let j = 0; j < currNumOfPaths; j++) {
              const currPath = currAlt[j];
              const currPathLength = currPath.length;
              for (let i = 0; i < currPathLength; i++) {
                const nextToken = this.LA_FAST(i + 1);
                if (tokenMatcher2(nextToken, currPath[i]) === false) {
                  continue nextPath;
                }
              }
              return t;
            }
          }
          return void 0;
        };
      } else if (areAllOneTokenLookahead && !dynamicTokensEnabled) {
        const singleTokenAlts = alts.map((currAlt) => {
          return currAlt.flat();
        });
        const choiceToAlt = singleTokenAlts.reduce((result, currAlt, idx) => {
          currAlt.forEach((currTokType) => {
            if (!(currTokType.tokenTypeIdx in result)) {
              result[currTokType.tokenTypeIdx] = idx;
            }
            currTokType.categoryMatches.forEach((currExtendingType) => {
              if (!Object.hasOwn(result, currExtendingType)) {
                result[currExtendingType] = idx;
              }
            });
          });
          return result;
        }, {});
        return function() {
          const nextToken = this.LA_FAST(1);
          return choiceToAlt[nextToken.tokenTypeIdx];
        };
      } else {
        return function() {
          for (let t = 0; t < numOfAlts; t++) {
            const currAlt = alts[t];
            const currNumOfPaths = currAlt.length;
            nextPath: for (let j = 0; j < currNumOfPaths; j++) {
              const currPath = currAlt[j];
              const currPathLength = currPath.length;
              for (let i = 0; i < currPathLength; i++) {
                const nextToken = this.LA_FAST(i + 1);
                if (tokenMatcher2(nextToken, currPath[i]) === false) {
                  continue nextPath;
                }
              }
              return t;
            }
          }
          return void 0;
        };
      }
    }
    function buildSingleAlternativeLookaheadFunction(alt, tokenMatcher2, dynamicTokensEnabled) {
      const areAllOneTokenLookahead = alt.every((currPath) => {
        return currPath.length === 1;
      });
      const numOfPaths = alt.length;
      if (areAllOneTokenLookahead && !dynamicTokensEnabled) {
        const singleTokensTypes = alt.flat();
        if (singleTokensTypes.length === 1 && singleTokensTypes[0].categoryMatches.length === 0) {
          const expectedTokenType = singleTokensTypes[0];
          const expectedTokenUniqueKey = expectedTokenType.tokenTypeIdx;
          return function() {
            return this.LA_FAST(1).tokenTypeIdx === expectedTokenUniqueKey;
          };
        } else {
          const choiceToAlt = singleTokensTypes.reduce((result, currTokType, idx) => {
            result[currTokType.tokenTypeIdx] = true;
            currTokType.categoryMatches.forEach((currExtendingType) => {
              result[currExtendingType] = true;
            });
            return result;
          }, []);
          return function() {
            const nextToken = this.LA_FAST(1);
            return choiceToAlt[nextToken.tokenTypeIdx] === true;
          };
        }
      } else {
        return function() {
          nextPath: for (let j = 0; j < numOfPaths; j++) {
            const currPath = alt[j];
            const currPathLength = currPath.length;
            for (let i = 0; i < currPathLength; i++) {
              const nextToken = this.LA_FAST(i + 1);
              if (tokenMatcher2(nextToken, currPath[i]) === false) {
                continue nextPath;
              }
            }
            return true;
          }
          return false;
        };
      }
    }
    class RestDefinitionFinderWalker extends RestWalker {
      constructor(topProd, targetOccurrence, targetProdType) {
        super();
        this.topProd = topProd;
        this.targetOccurrence = targetOccurrence;
        this.targetProdType = targetProdType;
      }
      startWalking() {
        this.walk(this.topProd);
        return this.restDef;
      }
      checkIsTarget(node2, expectedProdType, currRest, prevRest) {
        if (node2.idx === this.targetOccurrence && this.targetProdType === expectedProdType) {
          this.restDef = currRest.concat(prevRest);
          return true;
        }
        return false;
      }
      walkOption(optionProd, currRest, prevRest) {
        if (!this.checkIsTarget(optionProd, PROD_TYPE.OPTION, currRest, prevRest)) {
          super.walkOption(optionProd, currRest, prevRest);
        }
      }
      walkAtLeastOne(atLeastOneProd, currRest, prevRest) {
        if (!this.checkIsTarget(atLeastOneProd, PROD_TYPE.REPETITION_MANDATORY, currRest, prevRest)) {
          super.walkOption(atLeastOneProd, currRest, prevRest);
        }
      }
      walkAtLeastOneSep(atLeastOneSepProd, currRest, prevRest) {
        if (!this.checkIsTarget(atLeastOneSepProd, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, currRest, prevRest)) {
          super.walkOption(atLeastOneSepProd, currRest, prevRest);
        }
      }
      walkMany(manyProd, currRest, prevRest) {
        if (!this.checkIsTarget(manyProd, PROD_TYPE.REPETITION, currRest, prevRest)) {
          super.walkOption(manyProd, currRest, prevRest);
        }
      }
      walkManySep(manySepProd, currRest, prevRest) {
        if (!this.checkIsTarget(manySepProd, PROD_TYPE.REPETITION_WITH_SEPARATOR, currRest, prevRest)) {
          super.walkOption(manySepProd, currRest, prevRest);
        }
      }
    }
    class InsideDefinitionFinderVisitor extends GAstVisitor {
      constructor(targetOccurrence, targetProdType, targetRef) {
        super();
        this.targetOccurrence = targetOccurrence;
        this.targetProdType = targetProdType;
        this.targetRef = targetRef;
        this.result = [];
      }
      checkIsTarget(node2, expectedProdName) {
        if (node2.idx === this.targetOccurrence && this.targetProdType === expectedProdName && (this.targetRef === void 0 || node2 === this.targetRef)) {
          this.result = node2.definition;
        }
      }
      visitOption(node2) {
        this.checkIsTarget(node2, PROD_TYPE.OPTION);
      }
      visitRepetition(node2) {
        this.checkIsTarget(node2, PROD_TYPE.REPETITION);
      }
      visitRepetitionMandatory(node2) {
        this.checkIsTarget(node2, PROD_TYPE.REPETITION_MANDATORY);
      }
      visitRepetitionMandatoryWithSeparator(node2) {
        this.checkIsTarget(node2, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR);
      }
      visitRepetitionWithSeparator(node2) {
        this.checkIsTarget(node2, PROD_TYPE.REPETITION_WITH_SEPARATOR);
      }
      visitAlternation(node2) {
        this.checkIsTarget(node2, PROD_TYPE.ALTERNATION);
      }
    }
    function initializeArrayOfArrays(size) {
      const result = new Array(size);
      for (let i = 0; i < size; i++) {
        result[i] = [];
      }
      return result;
    }
    function pathToHashKeys(path) {
      let keys2 = [""];
      for (let i = 0; i < path.length; i++) {
        const tokType = path[i];
        const longerKeys = [];
        for (let j = 0; j < keys2.length; j++) {
          const currShorterKey = keys2[j];
          longerKeys.push(currShorterKey + "_" + tokType.tokenTypeIdx);
          for (let t = 0; t < tokType.categoryMatches.length; t++) {
            const categoriesKeySuffix = "_" + tokType.categoryMatches[t];
            longerKeys.push(currShorterKey + categoriesKeySuffix);
          }
        }
        keys2 = longerKeys;
      }
      return keys2;
    }
    function isUniquePrefixHash(altKnownPathsKeys, searchPathKeys, idx) {
      for (let currAltIdx = 0; currAltIdx < altKnownPathsKeys.length; currAltIdx++) {
        if (currAltIdx === idx) {
          continue;
        }
        const otherAltKnownPathsKeys = altKnownPathsKeys[currAltIdx];
        for (let searchIdx = 0; searchIdx < searchPathKeys.length; searchIdx++) {
          const searchKey = searchPathKeys[searchIdx];
          if (otherAltKnownPathsKeys[searchKey] === true) {
            return false;
          }
        }
      }
      return true;
    }
    function lookAheadSequenceFromAlternatives(altsDefs, k) {
      const partialAlts = altsDefs.map((currAlt) => possiblePathsFrom([currAlt], 1));
      const finalResult = initializeArrayOfArrays(partialAlts.length);
      const altsHashes = partialAlts.map((currAltPaths) => {
        const dict = {};
        currAltPaths.forEach((item) => {
          const keys2 = pathToHashKeys(item.partialPath);
          keys2.forEach((currKey) => {
            dict[currKey] = true;
          });
        });
        return dict;
      });
      let newData = partialAlts;
      for (let pathLength = 1; pathLength <= k; pathLength++) {
        const currDataset = newData;
        newData = initializeArrayOfArrays(currDataset.length);
        for (let altIdx = 0; altIdx < currDataset.length; altIdx++) {
          const currAltPathsAndSuffixes = currDataset[altIdx];
          for (let currPathIdx = 0; currPathIdx < currAltPathsAndSuffixes.length; currPathIdx++) {
            const currPathPrefix = currAltPathsAndSuffixes[currPathIdx].partialPath;
            const suffixDef = currAltPathsAndSuffixes[currPathIdx].suffixDef;
            const prefixKeys = pathToHashKeys(currPathPrefix);
            const isUnique = isUniquePrefixHash(altsHashes, prefixKeys, altIdx);
            if (isUnique || suffixDef.length === 0 || currPathPrefix.length === k) {
              const currAltResult = finalResult[altIdx];
              if (containsPath(currAltResult, currPathPrefix) === false) {
                currAltResult.push(currPathPrefix);
                for (let j = 0; j < prefixKeys.length; j++) {
                  const currKey = prefixKeys[j];
                  altsHashes[altIdx][currKey] = true;
                }
              }
            } else {
              const newPartialPathsAndSuffixes = possiblePathsFrom(suffixDef, pathLength + 1, currPathPrefix);
              newData[altIdx] = newData[altIdx].concat(newPartialPathsAndSuffixes);
              newPartialPathsAndSuffixes.forEach((item) => {
                const prefixKeys2 = pathToHashKeys(item.partialPath);
                prefixKeys2.forEach((key) => {
                  altsHashes[altIdx][key] = true;
                });
              });
            }
          }
        }
      }
      return finalResult;
    }
    function getLookaheadPathsForOr(occurrence, ruleGrammar, k, orProd) {
      const visitor2 = new InsideDefinitionFinderVisitor(occurrence, PROD_TYPE.ALTERNATION, orProd);
      ruleGrammar.accept(visitor2);
      return lookAheadSequenceFromAlternatives(visitor2.result, k);
    }
    function getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, k) {
      const insideDefVisitor = new InsideDefinitionFinderVisitor(occurrence, prodType);
      ruleGrammar.accept(insideDefVisitor);
      const insideDef = insideDefVisitor.result;
      const afterDefWalker = new RestDefinitionFinderWalker(ruleGrammar, occurrence, prodType);
      const afterDef = afterDefWalker.startWalking();
      const insideFlat = new Alternative({ definition: insideDef });
      const afterFlat = new Alternative({ definition: afterDef });
      return lookAheadSequenceFromAlternatives([insideFlat, afterFlat], k);
    }
    function containsPath(alternative, searchPath) {
      compareOtherPath: for (let i = 0; i < alternative.length; i++) {
        const otherPath = alternative[i];
        if (otherPath.length !== searchPath.length) {
          continue;
        }
        for (let j = 0; j < otherPath.length; j++) {
          const searchTok = searchPath[j];
          const otherTok = otherPath[j];
          const matchingTokens = searchTok === otherTok || otherTok.categoryMatchesMap[searchTok.tokenTypeIdx] !== void 0;
          if (matchingTokens === false) {
            continue compareOtherPath;
          }
        }
        return true;
      }
      return false;
    }
    function isStrictPrefixOfPath(prefix, other) {
      return prefix.length < other.length && prefix.every((tokType, idx) => {
        const otherTokType = other[idx];
        return tokType === otherTokType || otherTokType.categoryMatchesMap[tokType.tokenTypeIdx];
      });
    }
    function areTokenCategoriesNotUsed(lookAheadPaths) {
      return lookAheadPaths.every((singleAltPaths) => singleAltPaths.every((singlePath) => singlePath.every((token) => token.categoryMatches.length === 0)));
    }
    function validateLookahead(options) {
      const lookaheadValidationErrorMessages = options.lookaheadStrategy.validate({
        rules: options.rules,
        tokenTypes: options.tokenTypes,
        grammarName: options.grammarName
      });
      return lookaheadValidationErrorMessages.map((errorMessage) => Object.assign({ type: ParserDefinitionErrorType.CUSTOM_LOOKAHEAD_VALIDATION }, errorMessage));
    }
    function validateGrammar$1(topLevels, tokenTypes, errMsgProvider, grammarName) {
      const duplicateErrors = topLevels.flatMap((currTopLevel) => validateDuplicateProductions(currTopLevel, errMsgProvider));
      const termsNamespaceConflictErrors = checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider);
      const tooManyAltsErrors = topLevels.flatMap((curRule) => validateTooManyAlts(curRule, errMsgProvider));
      const duplicateRulesError = topLevels.flatMap((curRule) => validateRuleDoesNotAlreadyExist(curRule, topLevels, grammarName, errMsgProvider));
      return duplicateErrors.concat(termsNamespaceConflictErrors, tooManyAltsErrors, duplicateRulesError);
    }
    function validateDuplicateProductions(topLevelRule, errMsgProvider) {
      const collectorVisitor2 = new OccurrenceValidationCollector();
      topLevelRule.accept(collectorVisitor2);
      const allRuleProductions = collectorVisitor2.allProductions;
      const productionGroups = Object.groupBy(allRuleProductions, identifyProductionForDuplicates);
      const duplicates = Object.fromEntries(Object.entries(productionGroups).filter(([_k, currGroup]) => currGroup.length > 1));
      const errors = Object.values(duplicates).map((currDuplicates) => {
        const firstProd = currDuplicates[0];
        const msg = errMsgProvider.buildDuplicateFoundError(topLevelRule, currDuplicates);
        const dslName = getProductionDslName$1(firstProd);
        const defError = {
          message: msg,
          type: ParserDefinitionErrorType.DUPLICATE_PRODUCTIONS,
          ruleName: topLevelRule.name,
          dslName,
          occurrence: firstProd.idx
        };
        const param = getExtraProductionArgument(firstProd);
        if (param) {
          defError.parameter = param;
        }
        return defError;
      });
      return errors;
    }
    function identifyProductionForDuplicates(prod) {
      return `${getProductionDslName$1(prod)}_#_${prod.idx}_#_${getExtraProductionArgument(prod)}`;
    }
    function getExtraProductionArgument(prod) {
      if (prod instanceof Terminal) {
        return prod.terminalType.name;
      } else if (prod instanceof NonTerminal) {
        return prod.nonTerminalName;
      } else {
        return "";
      }
    }
    class OccurrenceValidationCollector extends GAstVisitor {
      constructor() {
        super(...arguments);
        this.allProductions = [];
      }
      visitNonTerminal(subrule) {
        this.allProductions.push(subrule);
      }
      visitOption(option2) {
        this.allProductions.push(option2);
      }
      visitRepetitionWithSeparator(manySep) {
        this.allProductions.push(manySep);
      }
      visitRepetitionMandatory(atLeastOne) {
        this.allProductions.push(atLeastOne);
      }
      visitRepetitionMandatoryWithSeparator(atLeastOneSep) {
        this.allProductions.push(atLeastOneSep);
      }
      visitRepetition(many) {
        this.allProductions.push(many);
      }
      visitAlternation(or) {
        this.allProductions.push(or);
      }
      visitTerminal(terminal) {
        this.allProductions.push(terminal);
      }
    }
    function validateRuleDoesNotAlreadyExist(rule, allRules, className, errMsgProvider) {
      const errors = [];
      const occurrences = allRules.reduce((result, curRule) => {
        if (curRule.name === rule.name) {
          return result + 1;
        }
        return result;
      }, 0);
      if (occurrences > 1) {
        const errMsg = errMsgProvider.buildDuplicateRuleNameError({
          topLevelRule: rule,
          grammarName: className
        });
        errors.push({
          message: errMsg,
          type: ParserDefinitionErrorType.DUPLICATE_RULE_NAME,
          ruleName: rule.name
        });
      }
      return errors;
    }
    function validateRuleIsOverridden(ruleName, definedRulesNames, className) {
      const errors = [];
      let errMsg;
      if (!definedRulesNames.includes(ruleName)) {
        errMsg = `Invalid rule override, rule: ->${ruleName}<- cannot be overridden in the grammar: ->${className}<-as it is not defined in any of the super grammars `;
        errors.push({
          message: errMsg,
          type: ParserDefinitionErrorType.INVALID_RULE_OVERRIDE,
          ruleName
        });
      }
      return errors;
    }
    function validateNoLeftRecursion(topRule, currRule, errMsgProvider, path = []) {
      const errors = [];
      const nextNonTerminals = getFirstNoneTerminal(currRule.definition);
      if (nextNonTerminals.length === 0) {
        return [];
      } else {
        const ruleName = topRule.name;
        const foundLeftRecursion = nextNonTerminals.includes(topRule);
        if (foundLeftRecursion) {
          errors.push({
            message: errMsgProvider.buildLeftRecursionError({
              topLevelRule: topRule,
              leftRecursionPath: path
            }),
            type: ParserDefinitionErrorType.LEFT_RECURSION,
            ruleName
          });
        }
        const excluded = path.concat([topRule]);
        const validNextSteps = nextNonTerminals.filter((x) => !excluded.includes(x));
        const errorsFromNextSteps = validNextSteps.flatMap((currRefRule) => {
          const newPath = [...path];
          newPath.push(currRefRule);
          return validateNoLeftRecursion(topRule, currRefRule, errMsgProvider, newPath);
        });
        return errors.concat(errorsFromNextSteps);
      }
    }
    function getFirstNoneTerminal(definition) {
      let result = [];
      if (definition.length === 0) {
        return result;
      }
      const firstProd = definition[0];
      if (firstProd instanceof NonTerminal) {
        result.push(firstProd.referencedRule);
      } else if (firstProd instanceof Alternative || firstProd instanceof Option || firstProd instanceof RepetitionMandatory || firstProd instanceof RepetitionMandatoryWithSeparator || firstProd instanceof RepetitionWithSeparator || firstProd instanceof Repetition) {
        result = result.concat(getFirstNoneTerminal(firstProd.definition));
      } else if (firstProd instanceof Alternation) {
        result = firstProd.definition.map((currSubDef) => getFirstNoneTerminal(currSubDef.definition)).flat();
      } else if (firstProd instanceof Terminal) ;
      else {
        throw Error("non exhaustive match");
      }
      const isFirstOptional = isOptionalProd(firstProd);
      const hasMore = definition.length > 1;
      if (isFirstOptional && hasMore) {
        const rest = definition.slice(1);
        return result.concat(getFirstNoneTerminal(rest));
      } else {
        return result;
      }
    }
    class OrCollector extends GAstVisitor {
      constructor() {
        super(...arguments);
        this.alternations = [];
      }
      visitAlternation(node2) {
        this.alternations.push(node2);
      }
    }
    function validateEmptyOrAlternative(topLevelRule, errMsgProvider) {
      const orCollector = new OrCollector();
      topLevelRule.accept(orCollector);
      const ors = orCollector.alternations;
      const errors = ors.flatMap((currOr) => {
        const exceptLast = currOr.definition.slice(0, -1);
        return exceptLast.flatMap((currAlternative, currAltIdx) => {
          const possibleFirstInAlt = nextPossibleTokensAfter([currAlternative], [], tokenStructuredMatcher, 1);
          if (possibleFirstInAlt.length === 0) {
            return [
              {
                message: errMsgProvider.buildEmptyAlternationError({
                  topLevelRule,
                  alternation: currOr,
                  emptyChoiceIdx: currAltIdx
                }),
                type: ParserDefinitionErrorType.NONE_LAST_EMPTY_ALT,
                ruleName: topLevelRule.name,
                occurrence: currOr.idx,
                alternative: currAltIdx + 1
              }
            ];
          } else {
            return [];
          }
        });
      });
      return errors;
    }
    function validateAmbiguousAlternationAlternatives(topLevelRule, globalMaxLookahead, errMsgProvider) {
      const orCollector = new OrCollector();
      topLevelRule.accept(orCollector);
      let ors = orCollector.alternations;
      ors = ors.filter((currOr) => currOr.ignoreAmbiguities !== true);
      const errors = ors.flatMap((currOr) => {
        const currOccurrence = currOr.idx;
        const actualMaxLookahead = currOr.maxLookahead || globalMaxLookahead;
        const alternatives = getLookaheadPathsForOr(currOccurrence, topLevelRule, actualMaxLookahead, currOr);
        const altsAmbiguityErrors = checkAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider);
        const altsPrefixAmbiguityErrors = checkPrefixAlternativesAmbiguities(alternatives, currOr, topLevelRule, errMsgProvider);
        return altsAmbiguityErrors.concat(altsPrefixAmbiguityErrors);
      });
      return errors;
    }
    class RepetitionCollector extends GAstVisitor {
      constructor() {
        super(...arguments);
        this.allProductions = [];
      }
      visitRepetitionWithSeparator(manySep) {
        this.allProductions.push(manySep);
      }
      visitRepetitionMandatory(atLeastOne) {
        this.allProductions.push(atLeastOne);
      }
      visitRepetitionMandatoryWithSeparator(atLeastOneSep) {
        this.allProductions.push(atLeastOneSep);
      }
      visitRepetition(many) {
        this.allProductions.push(many);
      }
    }
    function validateTooManyAlts(topLevelRule, errMsgProvider) {
      const orCollector = new OrCollector();
      topLevelRule.accept(orCollector);
      const ors = orCollector.alternations;
      const errors = ors.flatMap((currOr) => {
        if (currOr.definition.length > 255) {
          return [
            {
              message: errMsgProvider.buildTooManyAlternativesError({
                topLevelRule,
                alternation: currOr
              }),
              type: ParserDefinitionErrorType.TOO_MANY_ALTS,
              ruleName: topLevelRule.name,
              occurrence: currOr.idx
            }
          ];
        } else {
          return [];
        }
      });
      return errors;
    }
    function validateSomeNonEmptyLookaheadPath(topLevelRules, maxLookahead, errMsgProvider) {
      const errors = [];
      topLevelRules.forEach((currTopRule) => {
        const collectorVisitor2 = new RepetitionCollector();
        currTopRule.accept(collectorVisitor2);
        const allRuleProductions = collectorVisitor2.allProductions;
        allRuleProductions.forEach((currProd) => {
          const prodType = getProdType$1(currProd);
          const actualMaxLookahead = currProd.maxLookahead || maxLookahead;
          const currOccurrence = currProd.idx;
          const paths = getLookaheadPathsForOptionalProd(currOccurrence, currTopRule, prodType, actualMaxLookahead);
          const pathsInsideProduction = paths[0];
          if (pathsInsideProduction.flat().length === 0) {
            const errMsg = errMsgProvider.buildEmptyRepetitionError({
              topLevelRule: currTopRule,
              repetition: currProd
            });
            errors.push({
              message: errMsg,
              type: ParserDefinitionErrorType.NO_NON_EMPTY_LOOKAHEAD,
              ruleName: currTopRule.name
            });
          }
        });
      });
      return errors;
    }
    function checkAlternativesAmbiguities(alternatives, alternation2, rule, errMsgProvider) {
      const foundAmbiguousPaths = [];
      const identicalAmbiguities = alternatives.reduce((result, currAlt, currAltIdx) => {
        if (alternation2.definition[currAltIdx].ignoreAmbiguities === true) {
          return result;
        }
        currAlt.forEach((currPath) => {
          const altsCurrPathAppearsIn = [currAltIdx];
          alternatives.forEach((currOtherAlt, currOtherAltIdx) => {
            if (currAltIdx !== currOtherAltIdx && containsPath(currOtherAlt, currPath) && // ignore (skip) ambiguities with this "other" alternative
            alternation2.definition[currOtherAltIdx].ignoreAmbiguities !== true) {
              altsCurrPathAppearsIn.push(currOtherAltIdx);
            }
          });
          if (altsCurrPathAppearsIn.length > 1 && !containsPath(foundAmbiguousPaths, currPath)) {
            foundAmbiguousPaths.push(currPath);
            result.push({
              alts: altsCurrPathAppearsIn,
              path: currPath
            });
          }
        });
        return result;
      }, []);
      const currErrors = identicalAmbiguities.map((currAmbDescriptor) => {
        const ambgIndices = currAmbDescriptor.alts.map((currAltIdx) => currAltIdx + 1);
        const currMessage = errMsgProvider.buildAlternationAmbiguityError({
          topLevelRule: rule,
          alternation: alternation2,
          ambiguityIndices: ambgIndices,
          prefixPath: currAmbDescriptor.path
        });
        return {
          message: currMessage,
          type: ParserDefinitionErrorType.AMBIGUOUS_ALTS,
          ruleName: rule.name,
          occurrence: alternation2.idx,
          alternatives: currAmbDescriptor.alts
        };
      });
      return currErrors;
    }
    function checkPrefixAlternativesAmbiguities(alternatives, alternation2, rule, errMsgProvider) {
      const pathsAndIndices = alternatives.reduce((result, currAlt, idx) => {
        const currPathsAndIdx = currAlt.map((currPath) => {
          return { idx, path: currPath };
        });
        return result.concat(currPathsAndIdx);
      }, []);
      const errors = pathsAndIndices.flatMap((currPathAndIdx) => {
        const alternativeGast = alternation2.definition[currPathAndIdx.idx];
        if (alternativeGast.ignoreAmbiguities === true) {
          return [];
        }
        const targetIdx = currPathAndIdx.idx;
        const targetPath = currPathAndIdx.path;
        const prefixAmbiguitiesPathsAndIndices = pathsAndIndices.filter((searchPathAndIdx) => {
          return (
            // ignore (skip) ambiguities with this "other" alternative
            alternation2.definition[searchPathAndIdx.idx].ignoreAmbiguities !== true && searchPathAndIdx.idx < targetIdx && // checking for strict prefix because identical lookaheads
            // will be be detected using a different validation.
            isStrictPrefixOfPath(searchPathAndIdx.path, targetPath)
          );
        });
        const currPathPrefixErrors = prefixAmbiguitiesPathsAndIndices.map((currAmbPathAndIdx) => {
          const ambgIndices = [currAmbPathAndIdx.idx + 1, targetIdx + 1];
          const occurrence = alternation2.idx === 0 ? "" : alternation2.idx;
          const message = errMsgProvider.buildAlternationPrefixAmbiguityError({
            topLevelRule: rule,
            alternation: alternation2,
            ambiguityIndices: ambgIndices,
            prefixPath: currAmbPathAndIdx.path
          });
          return {
            message,
            type: ParserDefinitionErrorType.AMBIGUOUS_PREFIX_ALTS,
            ruleName: rule.name,
            occurrence,
            alternatives: ambgIndices
          };
        });
        return currPathPrefixErrors;
      });
      return errors;
    }
    function checkTerminalAndNoneTerminalsNameSpace(topLevels, tokenTypes, errMsgProvider) {
      const errors = [];
      const tokenNames = tokenTypes.map((currToken) => currToken.name);
      topLevels.forEach((currRule) => {
        const currRuleName = currRule.name;
        if (tokenNames.includes(currRuleName)) {
          const errMsg = errMsgProvider.buildNamespaceConflictError(currRule);
          errors.push({
            message: errMsg,
            type: ParserDefinitionErrorType.CONFLICT_TOKENS_RULES_NAMESPACE,
            ruleName: currRuleName
          });
        }
      });
      return errors;
    }
    function resolveGrammar(options) {
      const actualOptions = Object.assign({ errMsgProvider: defaultGrammarResolverErrorProvider }, options);
      const topRulesTable = {};
      options.rules.forEach((rule) => {
        topRulesTable[rule.name] = rule;
      });
      return resolveGrammar$1(topRulesTable, actualOptions.errMsgProvider);
    }
    function validateGrammar(options) {
      var _a;
      const errMsgProvider = (_a = options.errMsgProvider) !== null && _a !== void 0 ? _a : defaultGrammarValidatorErrorProvider;
      return validateGrammar$1(options.rules, options.tokenTypes, errMsgProvider, options.grammarName);
    }
    const MISMATCHED_TOKEN_EXCEPTION = "MismatchedTokenException";
    const NO_VIABLE_ALT_EXCEPTION = "NoViableAltException";
    const EARLY_EXIT_EXCEPTION = "EarlyExitException";
    const NOT_ALL_INPUT_PARSED_EXCEPTION = "NotAllInputParsedException";
    const RECOGNITION_EXCEPTION_NAMES = [
      MISMATCHED_TOKEN_EXCEPTION,
      NO_VIABLE_ALT_EXCEPTION,
      EARLY_EXIT_EXCEPTION,
      NOT_ALL_INPUT_PARSED_EXCEPTION
    ];
    Object.freeze(RECOGNITION_EXCEPTION_NAMES);
    function isRecognitionException(error) {
      return RECOGNITION_EXCEPTION_NAMES.includes(error.name);
    }
    class RecognitionException extends Error {
      constructor(message, token) {
        super(message);
        this.token = token;
        this.resyncedTokens = [];
        Object.setPrototypeOf(this, new.target.prototype);
        if (Error.captureStackTrace) {
          Error.captureStackTrace(this, this.constructor);
        }
      }
    }
    class MismatchedTokenException extends RecognitionException {
      constructor(message, token, previousToken) {
        super(message, token);
        this.previousToken = previousToken;
        this.name = MISMATCHED_TOKEN_EXCEPTION;
      }
    }
    class NoViableAltException extends RecognitionException {
      constructor(message, token, previousToken) {
        super(message, token);
        this.previousToken = previousToken;
        this.name = NO_VIABLE_ALT_EXCEPTION;
      }
    }
    class NotAllInputParsedException extends RecognitionException {
      constructor(message, token) {
        super(message, token);
        this.name = NOT_ALL_INPUT_PARSED_EXCEPTION;
      }
    }
    class EarlyExitException extends RecognitionException {
      constructor(message, token, previousToken) {
        super(message, token);
        this.previousToken = previousToken;
        this.name = EARLY_EXIT_EXCEPTION;
      }
    }
    const EOF_FOLLOW_KEY = {};
    const IN_RULE_RECOVERY_EXCEPTION = "InRuleRecoveryException";
    class InRuleRecoveryException extends Error {
      constructor(message) {
        super(message);
        this.name = IN_RULE_RECOVERY_EXCEPTION;
      }
    }
    class Recoverable {
      initRecoverable(config) {
        this.firstAfterRepMap = {};
        this.resyncFollows = {};
        this.recoveryEnabled = Object.hasOwn(config, "recoveryEnabled") ? config.recoveryEnabled : DEFAULT_PARSER_CONFIG.recoveryEnabled;
        if (this.recoveryEnabled) {
          this.attemptInRepetitionRecovery = attemptInRepetitionRecovery;
        }
      }
      getTokenToInsert(tokType) {
        const tokToInsert = createTokenInstance(tokType, "", NaN, NaN, NaN, NaN, NaN, NaN);
        tokToInsert.isInsertedInRecovery = true;
        return tokToInsert;
      }
      canTokenTypeBeInsertedInRecovery(tokType) {
        return true;
      }
      canTokenTypeBeDeletedInRecovery(tokType) {
        return true;
      }
      tryInRepetitionRecovery(grammarRule, grammarRuleArgs, lookAheadFunc, expectedTokType) {
        const reSyncTokType = this.findReSyncTokenType();
        const savedLexerState = this.exportLexerState();
        const resyncedTokens = [];
        let passedResyncPoint = false;
        const nextTokenWithoutResync = this.LA_FAST(1);
        let currToken = this.LA_FAST(1);
        const generateErrorMessage = () => {
          const previousToken = this.LA(0);
          const msg = this.errorMessageProvider.buildMismatchTokenMessage({
            expected: expectedTokType,
            actual: nextTokenWithoutResync,
            previous: previousToken,
            ruleName: this.getCurrRuleFullName()
          });
          const error = new MismatchedTokenException(msg, nextTokenWithoutResync, this.LA(0));
          error.resyncedTokens = resyncedTokens.slice(0, -1);
          this.SAVE_ERROR(error);
        };
        while (!passedResyncPoint) {
          if (this.tokenMatcher(currToken, expectedTokType)) {
            generateErrorMessage();
            return;
          } else if (lookAheadFunc.call(this)) {
            generateErrorMessage();
            grammarRule.apply(this, grammarRuleArgs);
            return;
          } else if (this.tokenMatcher(currToken, reSyncTokType)) {
            passedResyncPoint = true;
          } else {
            currToken = this.SKIP_TOKEN();
            this.addToResyncTokens(currToken, resyncedTokens);
          }
        }
        this.importLexerState(savedLexerState);
      }
      shouldInRepetitionRecoveryBeTried(expectTokAfterLastMatch, nextTokIdx, notStuck) {
        if (notStuck === false) {
          return false;
        }
        if (this.tokenMatcher(this.LA_FAST(1), expectTokAfterLastMatch)) {
          return false;
        }
        if (this.isBackTracking()) {
          return false;
        }
        if (this.canPerformInRuleRecovery(expectTokAfterLastMatch, this.getFollowsForInRuleRecovery(expectTokAfterLastMatch, nextTokIdx))) {
          return false;
        }
        return true;
      }
      // TODO: should this be a member method or a utility? it does not have any state or usage of 'this'...
      // TODO: should this be more explicitly part of the public API?
      getNextPossibleTokenTypes(grammarPath) {
        const topRuleName = grammarPath.ruleStack[0];
        const gastProductions = this.getGAstProductions();
        const topProduction = gastProductions[topRuleName];
        const nextPossibleTokenTypes = new NextAfterTokenWalker(topProduction, grammarPath).startWalking();
        return nextPossibleTokenTypes;
      }
      // Error Recovery functionality
      getFollowsForInRuleRecovery(tokType, tokIdxInRule) {
        const grammarPath = this.getCurrentGrammarPath(tokType, tokIdxInRule);
        const follows = this.getNextPossibleTokenTypes(grammarPath);
        return follows;
      }
      tryInRuleRecovery(expectedTokType, follows) {
        if (this.canRecoverWithSingleTokenInsertion(expectedTokType, follows)) {
          const tokToInsert = this.getTokenToInsert(expectedTokType);
          return tokToInsert;
        }
        if (this.canRecoverWithSingleTokenDeletion(expectedTokType)) {
          const nextTok = this.SKIP_TOKEN();
          this.consumeToken();
          return nextTok;
        }
        throw new InRuleRecoveryException("sad sad panda");
      }
      canPerformInRuleRecovery(expectedToken, follows) {
        return this.canRecoverWithSingleTokenInsertion(expectedToken, follows) || this.canRecoverWithSingleTokenDeletion(expectedToken);
      }
      canRecoverWithSingleTokenInsertion(expectedTokType, follows) {
        if (!this.canTokenTypeBeInsertedInRecovery(expectedTokType)) {
          return false;
        }
        if (follows.length === 0) {
          return false;
        }
        const mismatchedTok = this.LA_FAST(1);
        const isMisMatchedTokInFollows = follows.find((possibleFollowsTokType) => {
          return this.tokenMatcher(mismatchedTok, possibleFollowsTokType);
        }) !== void 0;
        return isMisMatchedTokInFollows;
      }
      canRecoverWithSingleTokenDeletion(expectedTokType) {
        if (!this.canTokenTypeBeDeletedInRecovery(expectedTokType)) {
          return false;
        }
        const isNextTokenWhatIsExpected = this.tokenMatcher(
          // not using LA_FAST because LA(2) might be un-safe with maxLookahead=1
          // in some edge cases (?)
          this.LA(2),
          expectedTokType
        );
        return isNextTokenWhatIsExpected;
      }
      isInCurrentRuleReSyncSet(tokenTypeIdx) {
        const followKey = this.getCurrFollowKey();
        const currentRuleReSyncSet = this.getFollowSetFromFollowKey(followKey);
        return currentRuleReSyncSet.includes(tokenTypeIdx);
      }
      findReSyncTokenType() {
        const allPossibleReSyncTokTypes = this.flattenFollowSet();
        let nextToken = this.LA_FAST(1);
        let k = 2;
        while (true) {
          const foundMatch = allPossibleReSyncTokTypes.find((resyncTokType) => {
            const canMatch = tokenMatcher(nextToken, resyncTokType);
            return canMatch;
          });
          if (foundMatch !== void 0) {
            return foundMatch;
          }
          nextToken = this.LA(k);
          k++;
        }
      }
      getCurrFollowKey() {
        if (this.RULE_STACK_IDX === 0) {
          return EOF_FOLLOW_KEY;
        }
        const currRuleShortName = this.currRuleShortName;
        const currRuleIdx = this.getLastExplicitRuleOccurrenceIndex();
        const prevRuleShortName = this.getPreviousExplicitRuleShortName();
        return {
          ruleName: this.shortRuleNameToFullName(currRuleShortName),
          idxInCallingRule: currRuleIdx,
          inRule: this.shortRuleNameToFullName(prevRuleShortName)
        };
      }
      buildFullFollowKeyStack() {
        const explicitRuleStack = this.RULE_STACK;
        const explicitOccurrenceStack = this.RULE_OCCURRENCE_STACK;
        const len = this.RULE_STACK_IDX + 1;
        const result = new Array(len);
        for (let idx = 0; idx < len; idx++) {
          if (idx === 0) {
            result[idx] = EOF_FOLLOW_KEY;
          } else {
            result[idx] = {
              ruleName: this.shortRuleNameToFullName(explicitRuleStack[idx]),
              idxInCallingRule: explicitOccurrenceStack[idx],
              inRule: this.shortRuleNameToFullName(explicitRuleStack[idx - 1])
            };
          }
        }
        return result;
      }
      flattenFollowSet() {
        const followStack = this.buildFullFollowKeyStack().map((currKey) => {
          return this.getFollowSetFromFollowKey(currKey);
        });
        return followStack.flat();
      }
      getFollowSetFromFollowKey(followKey) {
        if (followKey === EOF_FOLLOW_KEY) {
          return [EOF];
        }
        const followName = followKey.ruleName + followKey.idxInCallingRule + IN$1 + followKey.inRule;
        return this.resyncFollows[followName];
      }
      // It does not make any sense to include a virtual EOF token in the list of resynced tokens
      // as EOF does not really exist and thus does not contain any useful information (line/column numbers)
      addToResyncTokens(token, resyncTokens) {
        if (!this.tokenMatcher(token, EOF)) {
          resyncTokens.push(token);
        }
        return resyncTokens;
      }
      reSyncTo(tokType) {
        const resyncedTokens = [];
        let nextTok = this.LA_FAST(1);
        while (this.tokenMatcher(nextTok, tokType) === false) {
          nextTok = this.SKIP_TOKEN();
          this.addToResyncTokens(nextTok, resyncedTokens);
        }
        return resyncedTokens.slice(0, -1);
      }
      attemptInRepetitionRecovery(prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) {
      }
      getCurrentGrammarPath(tokType, tokIdxInRule) {
        const pathRuleStack = this.getHumanReadableRuleStack();
        const pathOccurrenceStack = this.RULE_OCCURRENCE_STACK.slice(0, this.RULE_OCCURRENCE_STACK_IDX + 1);
        const grammarPath = {
          ruleStack: pathRuleStack,
          occurrenceStack: pathOccurrenceStack,
          lastTok: tokType,
          lastTokOccurrence: tokIdxInRule
        };
        return grammarPath;
      }
      getHumanReadableRuleStack() {
        const len = this.RULE_STACK_IDX + 1;
        const result = new Array(len);
        for (let i = 0; i < len; i++) {
          result[i] = this.shortRuleNameToFullName(this.RULE_STACK[i]);
        }
        return result;
      }
    }
    function attemptInRepetitionRecovery(prodFunc, args, lookaheadFunc, dslMethodIdx, prodOccurrence, nextToksWalker, notStuck) {
      const key = this.getKeyForAutomaticLookahead(dslMethodIdx, prodOccurrence);
      let firstAfterRepInfo = this.firstAfterRepMap[key];
      if (firstAfterRepInfo === void 0) {
        const currRuleName = this.getCurrRuleFullName();
        const ruleGrammar = this.getGAstProductions()[currRuleName];
        const walker = new nextToksWalker(ruleGrammar, prodOccurrence);
        firstAfterRepInfo = walker.startWalking();
        this.firstAfterRepMap[key] = firstAfterRepInfo;
      }
      let expectTokAfterLastMatch = firstAfterRepInfo.token;
      let nextTokIdx = firstAfterRepInfo.occurrence;
      const isEndOfRule = firstAfterRepInfo.isEndOfRule;
      if (this.RULE_STACK_IDX === 0 && isEndOfRule && expectTokAfterLastMatch === void 0) {
        expectTokAfterLastMatch = EOF;
        nextTokIdx = 1;
      }
      if (expectTokAfterLastMatch === void 0 || nextTokIdx === void 0) {
        return;
      }
      if (this.shouldInRepetitionRecoveryBeTried(expectTokAfterLastMatch, nextTokIdx, notStuck)) {
        this.tryInRepetitionRecovery(prodFunc, args, lookaheadFunc, expectTokAfterLastMatch);
      }
    }
    const BITS_FOR_METHOD_TYPE = 4;
    const BITS_FOR_OCCURRENCE_IDX = 8;
    const OR_IDX = 1 << BITS_FOR_OCCURRENCE_IDX;
    const OPTION_IDX = 2 << BITS_FOR_OCCURRENCE_IDX;
    const MANY_IDX = 3 << BITS_FOR_OCCURRENCE_IDX;
    const AT_LEAST_ONE_IDX = 4 << BITS_FOR_OCCURRENCE_IDX;
    const MANY_SEP_IDX = 5 << BITS_FOR_OCCURRENCE_IDX;
    const AT_LEAST_ONE_SEP_IDX = 6 << BITS_FOR_OCCURRENCE_IDX;
    function getKeyForAutomaticLookahead(ruleIdx, dslMethodIdx, occurrence) {
      return occurrence | dslMethodIdx | ruleIdx;
    }
    class LLkLookaheadStrategy {
      constructor(options) {
        var _a;
        this.maxLookahead = (_a = options === null || options === void 0 ? void 0 : options.maxLookahead) !== null && _a !== void 0 ? _a : DEFAULT_PARSER_CONFIG.maxLookahead;
      }
      validate(options) {
        const leftRecursionErrors = this.validateNoLeftRecursion(options.rules);
        if (leftRecursionErrors.length === 0) {
          const emptyAltErrors = this.validateEmptyOrAlternatives(options.rules);
          const ambiguousAltsErrors = this.validateAmbiguousAlternationAlternatives(options.rules, this.maxLookahead);
          const emptyRepetitionErrors = this.validateSomeNonEmptyLookaheadPath(options.rules, this.maxLookahead);
          const allErrors = [
            ...leftRecursionErrors,
            ...emptyAltErrors,
            ...ambiguousAltsErrors,
            ...emptyRepetitionErrors
          ];
          return allErrors;
        }
        return leftRecursionErrors;
      }
      validateNoLeftRecursion(rules) {
        return rules.flatMap((currTopRule) => validateNoLeftRecursion(currTopRule, currTopRule, defaultGrammarValidatorErrorProvider));
      }
      validateEmptyOrAlternatives(rules) {
        return rules.flatMap((currTopRule) => validateEmptyOrAlternative(currTopRule, defaultGrammarValidatorErrorProvider));
      }
      validateAmbiguousAlternationAlternatives(rules, maxLookahead) {
        return rules.flatMap((currTopRule) => validateAmbiguousAlternationAlternatives(currTopRule, maxLookahead, defaultGrammarValidatorErrorProvider));
      }
      validateSomeNonEmptyLookaheadPath(rules, maxLookahead) {
        return validateSomeNonEmptyLookaheadPath(rules, maxLookahead, defaultGrammarValidatorErrorProvider);
      }
      buildLookaheadForAlternation(options) {
        return buildLookaheadFuncForOr(options.prodOccurrence, options.rule, options.maxLookahead, options.hasPredicates, options.dynamicTokensEnabled, buildAlternativesLookAheadFunc);
      }
      buildLookaheadForOptional(options) {
        return buildLookaheadFuncForOptionalProd(options.prodOccurrence, options.rule, options.maxLookahead, options.dynamicTokensEnabled, getProdType$1(options.prodType), buildSingleAlternativeLookaheadFunction);
      }
    }
    class LooksAhead {
      initLooksAhead(config) {
        this.dynamicTokensEnabled = Object.hasOwn(config, "dynamicTokensEnabled") ? config.dynamicTokensEnabled : DEFAULT_PARSER_CONFIG.dynamicTokensEnabled;
        this.maxLookahead = Object.hasOwn(config, "maxLookahead") ? config.maxLookahead : DEFAULT_PARSER_CONFIG.maxLookahead;
        this.lookaheadStrategy = Object.hasOwn(config, "lookaheadStrategy") ? config.lookaheadStrategy : new LLkLookaheadStrategy({ maxLookahead: this.maxLookahead });
        this.lookAheadFuncsCache = /* @__PURE__ */ new Map();
      }
      preComputeLookaheadFunctions(rules) {
        rules.forEach((currRule) => {
          this.TRACE_INIT(`${currRule.name} Rule Lookahead`, () => {
            const { alternation: alternation2, repetition: repetition2, option: option2, repetitionMandatory: repetitionMandatory2, repetitionMandatoryWithSeparator, repetitionWithSeparator } = collectMethods(currRule);
            alternation2.forEach((currProd) => {
              const prodIdx = currProd.idx === 0 ? "" : currProd.idx;
              this.TRACE_INIT(`${getProductionDslName$1(currProd)}${prodIdx}`, () => {
                const laFunc = this.lookaheadStrategy.buildLookaheadForAlternation({
                  prodOccurrence: currProd.idx,
                  rule: currRule,
                  maxLookahead: currProd.maxLookahead || this.maxLookahead,
                  hasPredicates: currProd.hasPredicates,
                  dynamicTokensEnabled: this.dynamicTokensEnabled
                });
                const key = getKeyForAutomaticLookahead(this.fullRuleNameToShort[currRule.name], OR_IDX, currProd.idx);
                this.setLaFuncCache(key, laFunc);
              });
            });
            repetition2.forEach((currProd) => {
              this.computeLookaheadFunc(currRule, currProd.idx, MANY_IDX, "Repetition", currProd.maxLookahead, getProductionDslName$1(currProd));
            });
            option2.forEach((currProd) => {
              this.computeLookaheadFunc(currRule, currProd.idx, OPTION_IDX, "Option", currProd.maxLookahead, getProductionDslName$1(currProd));
            });
            repetitionMandatory2.forEach((currProd) => {
              this.computeLookaheadFunc(currRule, currProd.idx, AT_LEAST_ONE_IDX, "RepetitionMandatory", currProd.maxLookahead, getProductionDslName$1(currProd));
            });
            repetitionMandatoryWithSeparator.forEach((currProd) => {
              this.computeLookaheadFunc(currRule, currProd.idx, AT_LEAST_ONE_SEP_IDX, "RepetitionMandatoryWithSeparator", currProd.maxLookahead, getProductionDslName$1(currProd));
            });
            repetitionWithSeparator.forEach((currProd) => {
              this.computeLookaheadFunc(currRule, currProd.idx, MANY_SEP_IDX, "RepetitionWithSeparator", currProd.maxLookahead, getProductionDslName$1(currProd));
            });
          });
        });
      }
      computeLookaheadFunc(rule, prodOccurrence, prodKey, prodType, prodMaxLookahead, dslMethodName) {
        this.TRACE_INIT(`${dslMethodName}${prodOccurrence === 0 ? "" : prodOccurrence}`, () => {
          const laFunc = this.lookaheadStrategy.buildLookaheadForOptional({
            prodOccurrence,
            rule,
            maxLookahead: prodMaxLookahead || this.maxLookahead,
            dynamicTokensEnabled: this.dynamicTokensEnabled,
            prodType
          });
          const key = getKeyForAutomaticLookahead(this.fullRuleNameToShort[rule.name], prodKey, prodOccurrence);
          this.setLaFuncCache(key, laFunc);
        });
      }
      // this actually returns a number, but it is always used as a string (object prop key)
      getKeyForAutomaticLookahead(dslMethodIdx, occurrence) {
        return getKeyForAutomaticLookahead(this.currRuleShortName, dslMethodIdx, occurrence);
      }
      getLaFuncFromCache(key) {
        return this.lookAheadFuncsCache.get(key);
      }
      /* istanbul ignore next */
      setLaFuncCache(key, value) {
        this.lookAheadFuncsCache.set(key, value);
      }
    }
    class DslMethodsCollectorVisitor extends GAstVisitor {
      constructor() {
        super(...arguments);
        this.dslMethods = {
          option: [],
          alternation: [],
          repetition: [],
          repetitionWithSeparator: [],
          repetitionMandatory: [],
          repetitionMandatoryWithSeparator: []
        };
      }
      reset() {
        this.dslMethods = {
          option: [],
          alternation: [],
          repetition: [],
          repetitionWithSeparator: [],
          repetitionMandatory: [],
          repetitionMandatoryWithSeparator: []
        };
      }
      visitOption(option2) {
        this.dslMethods.option.push(option2);
      }
      visitRepetitionWithSeparator(manySep) {
        this.dslMethods.repetitionWithSeparator.push(manySep);
      }
      visitRepetitionMandatory(atLeastOne) {
        this.dslMethods.repetitionMandatory.push(atLeastOne);
      }
      visitRepetitionMandatoryWithSeparator(atLeastOneSep) {
        this.dslMethods.repetitionMandatoryWithSeparator.push(atLeastOneSep);
      }
      visitRepetition(many) {
        this.dslMethods.repetition.push(many);
      }
      visitAlternation(or) {
        this.dslMethods.alternation.push(or);
      }
    }
    const collectorVisitor = new DslMethodsCollectorVisitor();
    function collectMethods(rule) {
      collectorVisitor.reset();
      rule.accept(collectorVisitor);
      const dslMethods = collectorVisitor.dslMethods;
      collectorVisitor.reset();
      return dslMethods;
    }
    function setNodeLocationOnlyOffset(currNodeLocation, newLocationInfo) {
      if (isNaN(currNodeLocation.startOffset) === true) {
        currNodeLocation.startOffset = newLocationInfo.startOffset;
        currNodeLocation.endOffset = newLocationInfo.endOffset;
      } else if (currNodeLocation.endOffset < newLocationInfo.endOffset === true) {
        currNodeLocation.endOffset = newLocationInfo.endOffset;
      }
    }
    function setNodeLocationFull(currNodeLocation, newLocationInfo) {
      if (isNaN(currNodeLocation.startOffset) === true) {
        currNodeLocation.startOffset = newLocationInfo.startOffset;
        currNodeLocation.startColumn = newLocationInfo.startColumn;
        currNodeLocation.startLine = newLocationInfo.startLine;
        currNodeLocation.endOffset = newLocationInfo.endOffset;
        currNodeLocation.endColumn = newLocationInfo.endColumn;
        currNodeLocation.endLine = newLocationInfo.endLine;
      } else if (currNodeLocation.endOffset < newLocationInfo.endOffset === true) {
        currNodeLocation.endOffset = newLocationInfo.endOffset;
        currNodeLocation.endColumn = newLocationInfo.endColumn;
        currNodeLocation.endLine = newLocationInfo.endLine;
      }
    }
    function addTerminalToCst(node2, token, tokenTypeName) {
      if (node2.children[tokenTypeName] === void 0) {
        node2.children[tokenTypeName] = [token];
      } else {
        node2.children[tokenTypeName].push(token);
      }
    }
    function addNoneTerminalToCst(node2, ruleName, ruleResult) {
      if (node2.children[ruleName] === void 0) {
        node2.children[ruleName] = [ruleResult];
      } else {
        node2.children[ruleName].push(ruleResult);
      }
    }
    const NAME = "name";
    function defineNameProp(obj, nameValue) {
      Object.defineProperty(obj, NAME, {
        enumerable: false,
        configurable: true,
        writable: false,
        value: nameValue
      });
    }
    function defaultVisit(ctx, param) {
      const childrenNames = Object.keys(ctx);
      const childrenNamesLength = childrenNames.length;
      for (let i = 0; i < childrenNamesLength; i++) {
        const currChildName = childrenNames[i];
        const currChildArray = ctx[currChildName];
        const currChildArrayLength = currChildArray.length;
        for (let j = 0; j < currChildArrayLength; j++) {
          const currChild = currChildArray[j];
          if (currChild.tokenTypeIdx === void 0) {
            this[currChild.name](currChild.children, param);
          }
        }
      }
    }
    function createBaseSemanticVisitorConstructor(grammarName, ruleNames) {
      const derivedConstructor = function() {
      };
      defineNameProp(derivedConstructor, grammarName + "BaseSemantics");
      const semanticProto = {
        visit: function(cstNode, param) {
          if (Array.isArray(cstNode)) {
            cstNode = cstNode[0];
          }
          if (cstNode === void 0) {
            return void 0;
          }
          return this[cstNode.name](cstNode.children, param);
        },
        validateVisitor: function() {
          const semanticDefinitionErrors = validateVisitor(this, ruleNames);
          if (semanticDefinitionErrors.length !== 0) {
            const errorMessages = semanticDefinitionErrors.map((currDefError) => currDefError.msg);
            throw Error(`Errors Detected in CST Visitor <${this.constructor.name}>:
	${errorMessages.join("\n\n").replace(/\n/g, "\n	")}`);
          }
        }
      };
      derivedConstructor.prototype = semanticProto;
      derivedConstructor.prototype.constructor = derivedConstructor;
      derivedConstructor._RULE_NAMES = ruleNames;
      return derivedConstructor;
    }
    function createBaseVisitorConstructorWithDefaults(grammarName, ruleNames, baseConstructor) {
      const derivedConstructor = function() {
      };
      defineNameProp(derivedConstructor, grammarName + "BaseSemanticsWithDefaults");
      const withDefaultsProto = Object.create(baseConstructor.prototype);
      ruleNames.forEach((ruleName) => {
        withDefaultsProto[ruleName] = defaultVisit;
      });
      derivedConstructor.prototype = withDefaultsProto;
      derivedConstructor.prototype.constructor = derivedConstructor;
      return derivedConstructor;
    }
    var CstVisitorDefinitionError;
    (function(CstVisitorDefinitionError2) {
      CstVisitorDefinitionError2[CstVisitorDefinitionError2["REDUNDANT_METHOD"] = 0] = "REDUNDANT_METHOD";
      CstVisitorDefinitionError2[CstVisitorDefinitionError2["MISSING_METHOD"] = 1] = "MISSING_METHOD";
    })(CstVisitorDefinitionError || (CstVisitorDefinitionError = {}));
    function validateVisitor(visitorInstance, ruleNames) {
      const missingErrors = validateMissingCstMethods(visitorInstance, ruleNames);
      return missingErrors;
    }
    function validateMissingCstMethods(visitorInstance, ruleNames) {
      const missingRuleNames = ruleNames.filter((currRuleName) => {
        return typeof visitorInstance[currRuleName] === "function" === false;
      });
      const errors = missingRuleNames.map((currRuleName) => {
        return {
          msg: `Missing visitor method: <${currRuleName}> on ${visitorInstance.constructor.name} CST Visitor.`,
          type: CstVisitorDefinitionError.MISSING_METHOD,
          methodName: currRuleName
        };
      });
      return errors.filter(Boolean);
    }
    class TreeBuilder {
      initTreeBuilder(config) {
        this.CST_STACK = [];
        this.outputCst = config.outputCst;
        this.nodeLocationTracking = Object.hasOwn(config, "nodeLocationTracking") ? config.nodeLocationTracking : DEFAULT_PARSER_CONFIG.nodeLocationTracking;
        if (!this.outputCst) {
          this.cstInvocationStateUpdate = () => {
          };
          this.cstFinallyStateUpdate = () => {
          };
          this.cstPostTerminal = () => {
          };
          this.cstPostNonTerminal = () => {
          };
          this.cstPostRule = () => {
          };
        } else {
          if (/full/i.test(this.nodeLocationTracking)) {
            if (this.recoveryEnabled) {
              this.setNodeLocationFromToken = setNodeLocationFull;
              this.setNodeLocationFromNode = setNodeLocationFull;
              this.cstPostRule = () => {
              };
              this.setInitialNodeLocation = this.setInitialNodeLocationFullRecovery;
            } else {
              this.setNodeLocationFromToken = () => {
              };
              this.setNodeLocationFromNode = () => {
              };
              this.cstPostRule = this.cstPostRuleFull;
              this.setInitialNodeLocation = this.setInitialNodeLocationFullRegular;
            }
          } else if (/onlyOffset/i.test(this.nodeLocationTracking)) {
            if (this.recoveryEnabled) {
              this.setNodeLocationFromToken = setNodeLocationOnlyOffset;
              this.setNodeLocationFromNode = setNodeLocationOnlyOffset;
              this.cstPostRule = () => {
              };
              this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRecovery;
            } else {
              this.setNodeLocationFromToken = () => {
              };
              this.setNodeLocationFromNode = () => {
              };
              this.cstPostRule = this.cstPostRuleOnlyOffset;
              this.setInitialNodeLocation = this.setInitialNodeLocationOnlyOffsetRegular;
            }
          } else if (/none/i.test(this.nodeLocationTracking)) {
            this.setNodeLocationFromToken = () => {
            };
            this.setNodeLocationFromNode = () => {
            };
            this.cstPostRule = () => {
            };
            this.setInitialNodeLocation = () => {
            };
          } else {
            throw Error(`Invalid <nodeLocationTracking> config option: "${config.nodeLocationTracking}"`);
          }
        }
      }
      setInitialNodeLocationOnlyOffsetRecovery(cstNode) {
        cstNode.location = {
          startOffset: NaN,
          endOffset: NaN
        };
      }
      setInitialNodeLocationOnlyOffsetRegular(cstNode) {
        cstNode.location = {
          // without error recovery the starting Location of a new CstNode is guaranteed
          // To be the next Token's startOffset (for valid inputs).
          // For invalid inputs there won't be any CSTOutput so this potential
          // inaccuracy does not matter
          startOffset: this.LA_FAST(1).startOffset,
          endOffset: NaN
        };
      }
      setInitialNodeLocationFullRecovery(cstNode) {
        cstNode.location = {
          startOffset: NaN,
          startLine: NaN,
          startColumn: NaN,
          endOffset: NaN,
          endLine: NaN,
          endColumn: NaN
        };
      }
      /**
           *  @see setInitialNodeLocationOnlyOffsetRegular for explanation why this work
      
           * @param cstNode
           */
      setInitialNodeLocationFullRegular(cstNode) {
        const nextToken = this.LA_FAST(1);
        cstNode.location = {
          startOffset: nextToken.startOffset,
          startLine: nextToken.startLine,
          startColumn: nextToken.startColumn,
          endOffset: NaN,
          endLine: NaN,
          endColumn: NaN
        };
      }
      cstInvocationStateUpdate(fullRuleName) {
        const cstNode = {
          name: fullRuleName,
          children: /* @__PURE__ */ Object.create(null)
        };
        this.setInitialNodeLocation(cstNode);
        this.CST_STACK.push(cstNode);
      }
      cstFinallyStateUpdate() {
        this.CST_STACK.pop();
      }
      cstPostRuleFull(ruleCstNode) {
        const prevToken = this.LA(0);
        const loc = ruleCstNode.location;
        if (loc.startOffset <= prevToken.startOffset === true) {
          loc.endOffset = prevToken.endOffset;
          loc.endLine = prevToken.endLine;
          loc.endColumn = prevToken.endColumn;
        } else {
          loc.startOffset = NaN;
          loc.startLine = NaN;
          loc.startColumn = NaN;
        }
      }
      cstPostRuleOnlyOffset(ruleCstNode) {
        const prevToken = this.LA(0);
        const loc = ruleCstNode.location;
        if (loc.startOffset <= prevToken.startOffset === true) {
          loc.endOffset = prevToken.endOffset;
        } else {
          loc.startOffset = NaN;
        }
      }
      cstPostTerminal(key, consumedToken) {
        const rootCst = this.CST_STACK[this.CST_STACK.length - 1];
        addTerminalToCst(rootCst, consumedToken, key);
        this.setNodeLocationFromToken(rootCst.location, consumedToken);
      }
      cstPostNonTerminal(ruleCstResult, ruleName) {
        const preCstNode = this.CST_STACK[this.CST_STACK.length - 1];
        addNoneTerminalToCst(preCstNode, ruleName, ruleCstResult);
        this.setNodeLocationFromNode(preCstNode.location, ruleCstResult.location);
      }
      getBaseCstVisitorConstructor() {
        if (this.baseCstVisitorConstructor === void 0) {
          const newBaseCstVisitorConstructor = createBaseSemanticVisitorConstructor(this.className, Object.keys(this.gastProductionsCache));
          this.baseCstVisitorConstructor = newBaseCstVisitorConstructor;
          return newBaseCstVisitorConstructor;
        }
        return this.baseCstVisitorConstructor;
      }
      getBaseCstVisitorConstructorWithDefaults() {
        if (this.baseCstVisitorWithDefaultsConstructor === void 0) {
          const newConstructor = createBaseVisitorConstructorWithDefaults(this.className, Object.keys(this.gastProductionsCache), this.getBaseCstVisitorConstructor());
          this.baseCstVisitorWithDefaultsConstructor = newConstructor;
          return newConstructor;
        }
        return this.baseCstVisitorWithDefaultsConstructor;
      }
      getPreviousExplicitRuleShortName() {
        return this.RULE_STACK[this.RULE_STACK_IDX - 1];
      }
      getLastExplicitRuleOccurrenceIndex() {
        return this.RULE_OCCURRENCE_STACK[this.RULE_OCCURRENCE_STACK_IDX];
      }
    }
    class LexerAdapter {
      initLexerAdapter() {
        this.tokVector = [];
        this.tokVectorLength = 0;
        this.currIdx = -1;
      }
      set input(newInput) {
        if (this.selfAnalysisDone !== true) {
          throw Error(`Missing <performSelfAnalysis> invocation at the end of the Parser's constructor.`);
        }
        this.reset();
        this.tokVector = newInput;
        this.tokVectorLength = newInput.length;
      }
      get input() {
        return this.tokVector;
      }
      // skips a token and returns the next token
      SKIP_TOKEN() {
        if (this.currIdx <= this.tokVectorLength - 2) {
          this.consumeToken();
          return this.LA_FAST(1);
        } else {
          return END_OF_FILE;
        }
      }
      // Lexer (accessing Token vector) related methods which can be overridden to implement lazy lexers
      // or lexers dependent on parser context.
      // Performance Optimized version of LA without bound checks
      // note that token beyond the end of the token vector EOF Token will still be returned
      // due to using sentinels at the end of the token vector. (for K=max lookahead)
      LA_FAST(howMuch) {
        const soughtIdx = this.currIdx + howMuch;
        return this.tokVector[soughtIdx];
      }
      LA(howMuch) {
        const soughtIdx = this.currIdx + howMuch;
        if (soughtIdx < 0 || this.tokVectorLength <= soughtIdx) {
          return END_OF_FILE;
        } else {
          return this.tokVector[soughtIdx];
        }
      }
      consumeToken() {
        this.currIdx++;
      }
      exportLexerState() {
        return this.currIdx;
      }
      importLexerState(newState2) {
        this.currIdx = newState2;
      }
      resetLexerState() {
        this.currIdx = -1;
      }
      moveToTerminatedState() {
        this.currIdx = this.tokVectorLength - 1;
      }
      getLexerPosition() {
        return this.exportLexerState();
      }
    }
    class RecognizerApi {
      ACTION(impl) {
        return impl.call(this);
      }
      consume(idx, tokType, options) {
        return this.consumeInternal(tokType, idx, options);
      }
      subrule(idx, ruleToCall, options) {
        return this.subruleInternal(ruleToCall, idx, options);
      }
      option(idx, actionORMethodDef) {
        return this.optionInternal(actionORMethodDef, idx);
      }
      or(idx, altsOrOpts) {
        return this.orInternal(altsOrOpts, idx);
      }
      many(idx, actionORMethodDef) {
        return this.manyInternal(idx, actionORMethodDef);
      }
      atLeastOne(idx, actionORMethodDef) {
        return this.atLeastOneInternal(idx, actionORMethodDef);
      }
      CONSUME(tokType, options) {
        return this.consumeInternal(tokType, 0, options);
      }
      CONSUME1(tokType, options) {
        return this.consumeInternal(tokType, 1, options);
      }
      CONSUME2(tokType, options) {
        return this.consumeInternal(tokType, 2, options);
      }
      CONSUME3(tokType, options) {
        return this.consumeInternal(tokType, 3, options);
      }
      CONSUME4(tokType, options) {
        return this.consumeInternal(tokType, 4, options);
      }
      CONSUME5(tokType, options) {
        return this.consumeInternal(tokType, 5, options);
      }
      CONSUME6(tokType, options) {
        return this.consumeInternal(tokType, 6, options);
      }
      CONSUME7(tokType, options) {
        return this.consumeInternal(tokType, 7, options);
      }
      CONSUME8(tokType, options) {
        return this.consumeInternal(tokType, 8, options);
      }
      CONSUME9(tokType, options) {
        return this.consumeInternal(tokType, 9, options);
      }
      SUBRULE(ruleToCall, options) {
        return this.subruleInternal(ruleToCall, 0, options);
      }
      SUBRULE1(ruleToCall, options) {
        return this.subruleInternal(ruleToCall, 1, options);
      }
      SUBRULE2(ruleToCall, options) {
        return this.subruleInternal(ruleToCall, 2, options);
      }
      SUBRULE3(ruleToCall, options) {
        return this.subruleInternal(ruleToCall, 3, options);
      }
      SUBRULE4(ruleToCall, options) {
        return this.subruleInternal(ruleToCall, 4, options);
      }
      SUBRULE5(ruleToCall, options) {
        return this.subruleInternal(ruleToCall, 5, options);
      }
      SUBRULE6(ruleToCall, options) {
        return this.subruleInternal(ruleToCall, 6, options);
      }
      SUBRULE7(ruleToCall, options) {
        return this.subruleInternal(ruleToCall, 7, options);
      }
      SUBRULE8(ruleToCall, options) {
        return this.subruleInternal(ruleToCall, 8, options);
      }
      SUBRULE9(ruleToCall, options) {
        return this.subruleInternal(ruleToCall, 9, options);
      }
      OPTION(actionORMethodDef) {
        return this.optionInternal(actionORMethodDef, 0);
      }
      OPTION1(actionORMethodDef) {
        return this.optionInternal(actionORMethodDef, 1);
      }
      OPTION2(actionORMethodDef) {
        return this.optionInternal(actionORMethodDef, 2);
      }
      OPTION3(actionORMethodDef) {
        return this.optionInternal(actionORMethodDef, 3);
      }
      OPTION4(actionORMethodDef) {
        return this.optionInternal(actionORMethodDef, 4);
      }
      OPTION5(actionORMethodDef) {
        return this.optionInternal(actionORMethodDef, 5);
      }
      OPTION6(actionORMethodDef) {
        return this.optionInternal(actionORMethodDef, 6);
      }
      OPTION7(actionORMethodDef) {
        return this.optionInternal(actionORMethodDef, 7);
      }
      OPTION8(actionORMethodDef) {
        return this.optionInternal(actionORMethodDef, 8);
      }
      OPTION9(actionORMethodDef) {
        return this.optionInternal(actionORMethodDef, 9);
      }
      OR(altsOrOpts) {
        return this.orInternal(altsOrOpts, 0);
      }
      OR1(altsOrOpts) {
        return this.orInternal(altsOrOpts, 1);
      }
      OR2(altsOrOpts) {
        return this.orInternal(altsOrOpts, 2);
      }
      OR3(altsOrOpts) {
        return this.orInternal(altsOrOpts, 3);
      }
      OR4(altsOrOpts) {
        return this.orInternal(altsOrOpts, 4);
      }
      OR5(altsOrOpts) {
        return this.orInternal(altsOrOpts, 5);
      }
      OR6(altsOrOpts) {
        return this.orInternal(altsOrOpts, 6);
      }
      OR7(altsOrOpts) {
        return this.orInternal(altsOrOpts, 7);
      }
      OR8(altsOrOpts) {
        return this.orInternal(altsOrOpts, 8);
      }
      OR9(altsOrOpts) {
        return this.orInternal(altsOrOpts, 9);
      }
      MANY(actionORMethodDef) {
        this.manyInternal(0, actionORMethodDef);
      }
      MANY1(actionORMethodDef) {
        this.manyInternal(1, actionORMethodDef);
      }
      MANY2(actionORMethodDef) {
        this.manyInternal(2, actionORMethodDef);
      }
      MANY3(actionORMethodDef) {
        this.manyInternal(3, actionORMethodDef);
      }
      MANY4(actionORMethodDef) {
        this.manyInternal(4, actionORMethodDef);
      }
      MANY5(actionORMethodDef) {
        this.manyInternal(5, actionORMethodDef);
      }
      MANY6(actionORMethodDef) {
        this.manyInternal(6, actionORMethodDef);
      }
      MANY7(actionORMethodDef) {
        this.manyInternal(7, actionORMethodDef);
      }
      MANY8(actionORMethodDef) {
        this.manyInternal(8, actionORMethodDef);
      }
      MANY9(actionORMethodDef) {
        this.manyInternal(9, actionORMethodDef);
      }
      MANY_SEP(options) {
        this.manySepFirstInternal(0, options);
      }
      MANY_SEP1(options) {
        this.manySepFirstInternal(1, options);
      }
      MANY_SEP2(options) {
        this.manySepFirstInternal(2, options);
      }
      MANY_SEP3(options) {
        this.manySepFirstInternal(3, options);
      }
      MANY_SEP4(options) {
        this.manySepFirstInternal(4, options);
      }
      MANY_SEP5(options) {
        this.manySepFirstInternal(5, options);
      }
      MANY_SEP6(options) {
        this.manySepFirstInternal(6, options);
      }
      MANY_SEP7(options) {
        this.manySepFirstInternal(7, options);
      }
      MANY_SEP8(options) {
        this.manySepFirstInternal(8, options);
      }
      MANY_SEP9(options) {
        this.manySepFirstInternal(9, options);
      }
      AT_LEAST_ONE(actionORMethodDef) {
        this.atLeastOneInternal(0, actionORMethodDef);
      }
      AT_LEAST_ONE1(actionORMethodDef) {
        return this.atLeastOneInternal(1, actionORMethodDef);
      }
      AT_LEAST_ONE2(actionORMethodDef) {
        this.atLeastOneInternal(2, actionORMethodDef);
      }
      AT_LEAST_ONE3(actionORMethodDef) {
        this.atLeastOneInternal(3, actionORMethodDef);
      }
      AT_LEAST_ONE4(actionORMethodDef) {
        this.atLeastOneInternal(4, actionORMethodDef);
      }
      AT_LEAST_ONE5(actionORMethodDef) {
        this.atLeastOneInternal(5, actionORMethodDef);
      }
      AT_LEAST_ONE6(actionORMethodDef) {
        this.atLeastOneInternal(6, actionORMethodDef);
      }
      AT_LEAST_ONE7(actionORMethodDef) {
        this.atLeastOneInternal(7, actionORMethodDef);
      }
      AT_LEAST_ONE8(actionORMethodDef) {
        this.atLeastOneInternal(8, actionORMethodDef);
      }
      AT_LEAST_ONE9(actionORMethodDef) {
        this.atLeastOneInternal(9, actionORMethodDef);
      }
      AT_LEAST_ONE_SEP(options) {
        this.atLeastOneSepFirstInternal(0, options);
      }
      AT_LEAST_ONE_SEP1(options) {
        this.atLeastOneSepFirstInternal(1, options);
      }
      AT_LEAST_ONE_SEP2(options) {
        this.atLeastOneSepFirstInternal(2, options);
      }
      AT_LEAST_ONE_SEP3(options) {
        this.atLeastOneSepFirstInternal(3, options);
      }
      AT_LEAST_ONE_SEP4(options) {
        this.atLeastOneSepFirstInternal(4, options);
      }
      AT_LEAST_ONE_SEP5(options) {
        this.atLeastOneSepFirstInternal(5, options);
      }
      AT_LEAST_ONE_SEP6(options) {
        this.atLeastOneSepFirstInternal(6, options);
      }
      AT_LEAST_ONE_SEP7(options) {
        this.atLeastOneSepFirstInternal(7, options);
      }
      AT_LEAST_ONE_SEP8(options) {
        this.atLeastOneSepFirstInternal(8, options);
      }
      AT_LEAST_ONE_SEP9(options) {
        this.atLeastOneSepFirstInternal(9, options);
      }
      RULE(name, implementation, config = DEFAULT_RULE_CONFIG) {
        if (this.definedRulesNames.includes(name)) {
          const errMsg = defaultGrammarValidatorErrorProvider.buildDuplicateRuleNameError({
            topLevelRule: name,
            grammarName: this.className
          });
          const error = {
            message: errMsg,
            type: ParserDefinitionErrorType.DUPLICATE_RULE_NAME,
            ruleName: name
          };
          this.definitionErrors.push(error);
        }
        this.definedRulesNames.push(name);
        const ruleImplementation = this.defineRule(name, implementation, config);
        this[name] = ruleImplementation;
        return ruleImplementation;
      }
      OVERRIDE_RULE(name, impl, config = DEFAULT_RULE_CONFIG) {
        const ruleErrors = validateRuleIsOverridden(name, this.definedRulesNames, this.className);
        this.definitionErrors = this.definitionErrors.concat(ruleErrors);
        const ruleImplementation = this.defineRule(name, impl, config);
        this[name] = ruleImplementation;
        return ruleImplementation;
      }
      BACKTRACK(grammarRule, args) {
        var _a;
        const ruleToCall = (_a = grammarRule.coreRule) !== null && _a !== void 0 ? _a : grammarRule;
        return function() {
          this.isBackTrackingStack.push(1);
          const orgState = this.saveRecogState();
          try {
            ruleToCall.apply(this, args);
            return true;
          } catch (e) {
            if (isRecognitionException(e)) {
              return false;
            } else {
              throw e;
            }
          } finally {
            this.reloadRecogState(orgState);
            this.isBackTrackingStack.pop();
          }
        };
      }
      // GAST export APIs
      getGAstProductions() {
        return this.gastProductionsCache;
      }
      getSerializedGastProductions() {
        return serializeGrammar(Object.values(this.gastProductionsCache));
      }
    }
    class RecognizerEngine {
      initRecognizerEngine(tokenVocabulary, config) {
        this.className = this.constructor.name;
        this.shortRuleNameToFull = {};
        this.fullRuleNameToShort = {};
        this.ruleShortNameIdx = 256;
        this.tokenMatcher = tokenStructuredMatcherNoCategories;
        this.subruleIdx = 0;
        this.currRuleShortName = 0;
        this.definedRulesNames = [];
        this.tokensMap = {};
        this.isBackTrackingStack = [];
        this.RULE_STACK = [];
        this.RULE_STACK_IDX = -1;
        this.RULE_OCCURRENCE_STACK = [];
        this.RULE_OCCURRENCE_STACK_IDX = -1;
        this.gastProductionsCache = {};
        if (Object.hasOwn(config, "serializedGrammar")) {
          throw Error("The Parser's configuration can no longer contain a <serializedGrammar> property.\n	See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_6-0-0\n	For Further details.");
        }
        if (Array.isArray(tokenVocabulary)) {
          if (tokenVocabulary.length === 0) {
            throw Error("A Token Vocabulary cannot be empty.\n	Note that the first argument for the parser constructor\n	is no longer a Token vector (since v4.0).");
          }
          if (typeof tokenVocabulary[0].startOffset === "number") {
            throw Error("The Parser constructor no longer accepts a token vector as the first argument.\n	See: https://chevrotain.io/docs/changes/BREAKING_CHANGES.html#_4-0-0\n	For Further details.");
          }
        }
        if (Array.isArray(tokenVocabulary)) {
          this.tokensMap = tokenVocabulary.reduce((acc, tokType) => {
            acc[tokType.name] = tokType;
            return acc;
          }, {});
        } else if (Object.hasOwn(tokenVocabulary, "modes") && Object.values(tokenVocabulary.modes).flat().every(isTokenType)) {
          const allTokenTypes2 = Object.values(tokenVocabulary.modes).flat();
          const uniqueTokens = [...new Set(allTokenTypes2)];
          this.tokensMap = uniqueTokens.reduce((acc, tokType) => {
            acc[tokType.name] = tokType;
            return acc;
          }, {});
        } else if (typeof tokenVocabulary === "object" && tokenVocabulary !== null) {
          this.tokensMap = Object.assign({}, tokenVocabulary);
        } else {
          throw new Error("<tokensDictionary> argument must be An Array of Token constructors, A dictionary of Token constructors or an IMultiModeLexerDefinition");
        }
        this.tokensMap["EOF"] = EOF;
        const allTokenTypes = Object.hasOwn(tokenVocabulary, "modes") ? Object.values(tokenVocabulary.modes).flat() : Object.values(tokenVocabulary);
        const noTokenCategoriesUsed = allTokenTypes.every(
          // intentional "==" to also cover "undefined"
          (tokenConstructor) => {
            var _a;
            return ((_a = tokenConstructor.categoryMatches) === null || _a === void 0 ? void 0 : _a.length) == 0;
          }
        );
        this.tokenMatcher = noTokenCategoriesUsed ? tokenStructuredMatcherNoCategories : tokenStructuredMatcher;
        augmentTokenTypes(Object.values(this.tokensMap));
      }
      defineRule(ruleName, impl, config) {
        if (this.selfAnalysisDone) {
          throw Error(`Grammar rule <${ruleName}> may not be defined after the 'performSelfAnalysis' method has been called'
Make sure that all grammar rule definitions are done before 'performSelfAnalysis' is called.`);
        }
        const resyncEnabled = Object.hasOwn(config, "resyncEnabled") ? config.resyncEnabled : DEFAULT_RULE_CONFIG.resyncEnabled;
        const recoveryValueFunc = Object.hasOwn(config, "recoveryValueFunc") ? config.recoveryValueFunc : DEFAULT_RULE_CONFIG.recoveryValueFunc;
        const shortName = this.ruleShortNameIdx << BITS_FOR_METHOD_TYPE + BITS_FOR_OCCURRENCE_IDX;
        this.ruleShortNameIdx++;
        this.shortRuleNameToFull[shortName] = ruleName;
        this.fullRuleNameToShort[ruleName] = shortName;
        let coreRuleFunction;
        if (this.outputCst === true) {
          coreRuleFunction = function invokeRuleWithTry(...args) {
            try {
              this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx);
              impl.apply(this, args);
              const cst = this.CST_STACK[this.CST_STACK.length - 1];
              this.cstPostRule(cst);
              return cst;
            } catch (e) {
              return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc);
            } finally {
              this.ruleFinallyStateUpdate();
            }
          };
        } else {
          coreRuleFunction = function invokeRuleWithTryCst(...args) {
            try {
              this.ruleInvocationStateUpdate(shortName, ruleName, this.subruleIdx);
              return impl.apply(this, args);
            } catch (e) {
              return this.invokeRuleCatch(e, resyncEnabled, recoveryValueFunc);
            } finally {
              this.ruleFinallyStateUpdate();
            }
          };
        }
        const rootRuleFunction = function rootRule(...args) {
          this.onBeforeParse(ruleName);
          try {
            return coreRuleFunction.apply(this, args);
          } finally {
            this.onAfterParse(ruleName);
          }
        };
        const wrappedGrammarRule = Object.assign(rootRuleFunction, { ruleName, originalGrammarAction: impl, coreRule: coreRuleFunction });
        return wrappedGrammarRule;
      }
      invokeRuleCatch(e, resyncEnabledConfig, recoveryValueFunc) {
        const isFirstInvokedRule = this.RULE_STACK_IDX === 0;
        const reSyncEnabled = resyncEnabledConfig && !this.isBackTracking() && this.recoveryEnabled;
        if (isRecognitionException(e)) {
          const recogError = e;
          if (reSyncEnabled) {
            const reSyncTokType = this.findReSyncTokenType();
            if (this.isInCurrentRuleReSyncSet(reSyncTokType)) {
              recogError.resyncedTokens = this.reSyncTo(reSyncTokType);
              if (this.outputCst) {
                const partialCstResult = this.CST_STACK[this.CST_STACK.length - 1];
                partialCstResult.recoveredNode = true;
                return partialCstResult;
              } else {
                return recoveryValueFunc(e);
              }
            } else {
              if (this.outputCst) {
                const partialCstResult = this.CST_STACK[this.CST_STACK.length - 1];
                partialCstResult.recoveredNode = true;
                recogError.partialCstResult = partialCstResult;
              }
              throw recogError;
            }
          } else if (isFirstInvokedRule) {
            this.moveToTerminatedState();
            return recoveryValueFunc(e);
          } else {
            throw recogError;
          }
        } else {
          throw e;
        }
      }
      // Implementation of parsing DSL
      optionInternal(actionORMethodDef, occurrence) {
        const key = this.getKeyForAutomaticLookahead(OPTION_IDX, occurrence);
        return this.optionInternalLogic(actionORMethodDef, occurrence, key);
      }
      optionInternalLogic(actionORMethodDef, occurrence, key) {
        let lookAheadFunc = this.getLaFuncFromCache(key);
        let action;
        if (typeof actionORMethodDef !== "function") {
          action = actionORMethodDef.DEF;
          const predicate = actionORMethodDef.GATE;
          if (predicate !== void 0) {
            const orgLookaheadFunction = lookAheadFunc;
            lookAheadFunc = () => {
              return predicate.call(this) && orgLookaheadFunction.call(this);
            };
          }
        } else {
          action = actionORMethodDef;
        }
        if (lookAheadFunc.call(this) === true) {
          return action.call(this);
        }
        return void 0;
      }
      atLeastOneInternal(prodOccurrence, actionORMethodDef) {
        const laKey = this.getKeyForAutomaticLookahead(AT_LEAST_ONE_IDX, prodOccurrence);
        return this.atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, laKey);
      }
      atLeastOneInternalLogic(prodOccurrence, actionORMethodDef, key) {
        let lookAheadFunc = this.getLaFuncFromCache(key);
        let action;
        if (typeof actionORMethodDef !== "function") {
          action = actionORMethodDef.DEF;
          const predicate = actionORMethodDef.GATE;
          if (predicate !== void 0) {
            const orgLookaheadFunction = lookAheadFunc;
            lookAheadFunc = () => {
              return predicate.call(this) && orgLookaheadFunction.call(this);
            };
          }
        } else {
          action = actionORMethodDef;
        }
        if (lookAheadFunc.call(this) === true) {
          let notStuck = this.doSingleRepetition(action);
          while (lookAheadFunc.call(this) === true && notStuck === true) {
            notStuck = this.doSingleRepetition(action);
          }
        } else {
          throw this.raiseEarlyExitException(prodOccurrence, PROD_TYPE.REPETITION_MANDATORY, actionORMethodDef.ERR_MSG);
        }
        this.attemptInRepetitionRecovery(this.atLeastOneInternal, [prodOccurrence, actionORMethodDef], lookAheadFunc, AT_LEAST_ONE_IDX, prodOccurrence, NextTerminalAfterAtLeastOneWalker);
      }
      atLeastOneSepFirstInternal(prodOccurrence, options) {
        const laKey = this.getKeyForAutomaticLookahead(AT_LEAST_ONE_SEP_IDX, prodOccurrence);
        this.atLeastOneSepFirstInternalLogic(prodOccurrence, options, laKey);
      }
      atLeastOneSepFirstInternalLogic(prodOccurrence, options, key) {
        const action = options.DEF;
        const separator = options.SEP;
        const firstIterationLookaheadFunc = this.getLaFuncFromCache(key);
        if (firstIterationLookaheadFunc.call(this) === true) {
          action.call(this);
          const separatorLookAheadFunc = () => {
            return this.tokenMatcher(this.LA_FAST(1), separator);
          };
          while (this.tokenMatcher(this.LA_FAST(1), separator) === true) {
            this.CONSUME(separator);
            action.call(this);
          }
          this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [
            prodOccurrence,
            separator,
            separatorLookAheadFunc,
            action,
            NextTerminalAfterAtLeastOneSepWalker
          ], separatorLookAheadFunc, AT_LEAST_ONE_SEP_IDX, prodOccurrence, NextTerminalAfterAtLeastOneSepWalker);
        } else {
          throw this.raiseEarlyExitException(prodOccurrence, PROD_TYPE.REPETITION_MANDATORY_WITH_SEPARATOR, options.ERR_MSG);
        }
      }
      manyInternal(prodOccurrence, actionORMethodDef) {
        const laKey = this.getKeyForAutomaticLookahead(MANY_IDX, prodOccurrence);
        return this.manyInternalLogic(prodOccurrence, actionORMethodDef, laKey);
      }
      manyInternalLogic(prodOccurrence, actionORMethodDef, key) {
        let lookaheadFunction = this.getLaFuncFromCache(key);
        let action;
        if (typeof actionORMethodDef !== "function") {
          action = actionORMethodDef.DEF;
          const predicate = actionORMethodDef.GATE;
          if (predicate !== void 0) {
            const orgLookaheadFunction = lookaheadFunction;
            lookaheadFunction = () => {
              return predicate.call(this) && orgLookaheadFunction.call(this);
            };
          }
        } else {
          action = actionORMethodDef;
        }
        let notStuck = true;
        while (lookaheadFunction.call(this) === true && notStuck === true) {
          notStuck = this.doSingleRepetition(action);
        }
        this.attemptInRepetitionRecovery(
          this.manyInternal,
          [prodOccurrence, actionORMethodDef],
          lookaheadFunction,
          MANY_IDX,
          prodOccurrence,
          NextTerminalAfterManyWalker,
          // The notStuck parameter is only relevant when "attemptInRepetitionRecovery"
          // is invoked from manyInternal, in the MANY_SEP case and AT_LEAST_ONE[_SEP]
          // An infinite loop cannot occur as:
          // - Either the lookahead is guaranteed to consume something (Single Token Separator)
          // - AT_LEAST_ONE by definition is guaranteed to consume something (or error out).
          notStuck
        );
      }
      manySepFirstInternal(prodOccurrence, options) {
        const laKey = this.getKeyForAutomaticLookahead(MANY_SEP_IDX, prodOccurrence);
        this.manySepFirstInternalLogic(prodOccurrence, options, laKey);
      }
      manySepFirstInternalLogic(prodOccurrence, options, key) {
        const action = options.DEF;
        const separator = options.SEP;
        const firstIterationLaFunc = this.getLaFuncFromCache(key);
        if (firstIterationLaFunc.call(this) === true) {
          action.call(this);
          const separatorLookAheadFunc = () => {
            return this.tokenMatcher(this.LA_FAST(1), separator);
          };
          while (this.tokenMatcher(this.LA_FAST(1), separator) === true) {
            this.CONSUME(separator);
            action.call(this);
          }
          this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [
            prodOccurrence,
            separator,
            separatorLookAheadFunc,
            action,
            NextTerminalAfterManySepWalker
          ], separatorLookAheadFunc, MANY_SEP_IDX, prodOccurrence, NextTerminalAfterManySepWalker);
        }
      }
      repetitionSepSecondInternal(prodOccurrence, separator, separatorLookAheadFunc, action, nextTerminalAfterWalker) {
        while (separatorLookAheadFunc()) {
          this.CONSUME(separator);
          action.call(this);
        }
        this.attemptInRepetitionRecovery(this.repetitionSepSecondInternal, [
          prodOccurrence,
          separator,
          separatorLookAheadFunc,
          action,
          nextTerminalAfterWalker
        ], separatorLookAheadFunc, AT_LEAST_ONE_SEP_IDX, prodOccurrence, nextTerminalAfterWalker);
      }
      doSingleRepetition(action) {
        const beforeIteration = this.getLexerPosition();
        action.call(this);
        const afterIteration = this.getLexerPosition();
        return afterIteration > beforeIteration;
      }
      orInternal(altsOrOpts, occurrence) {
        const laKey = this.getKeyForAutomaticLookahead(OR_IDX, occurrence);
        const alts = Array.isArray(altsOrOpts) ? altsOrOpts : altsOrOpts.DEF;
        const laFunc = this.getLaFuncFromCache(laKey);
        const altIdxToTake = laFunc.call(this, alts);
        if (altIdxToTake !== void 0) {
          const chosenAlternative = alts[altIdxToTake];
          return chosenAlternative.ALT.call(this);
        }
        this.raiseNoAltException(occurrence, altsOrOpts.ERR_MSG);
      }
      ruleFinallyStateUpdate() {
        this.RULE_STACK_IDX--;
        this.RULE_OCCURRENCE_STACK_IDX--;
        if (this.RULE_STACK_IDX >= 0) {
          this.currRuleShortName = this.RULE_STACK[this.RULE_STACK_IDX];
        }
        this.cstFinallyStateUpdate();
      }
      subruleInternal(ruleToCall, idx, options) {
        let ruleResult;
        try {
          const args = options !== void 0 ? options.ARGS : void 0;
          this.subruleIdx = idx;
          ruleResult = ruleToCall.coreRule.apply(this, args);
          this.cstPostNonTerminal(ruleResult, options !== void 0 && options.LABEL !== void 0 ? options.LABEL : ruleToCall.ruleName);
          return ruleResult;
        } catch (e) {
          throw this.subruleInternalError(e, options, ruleToCall.ruleName);
        }
      }
      subruleInternalError(e, options, ruleName) {
        if (isRecognitionException(e) && e.partialCstResult !== void 0) {
          this.cstPostNonTerminal(e.partialCstResult, options !== void 0 && options.LABEL !== void 0 ? options.LABEL : ruleName);
          delete e.partialCstResult;
        }
        throw e;
      }
      consumeInternal(tokType, idx, options) {
        let consumedToken;
        try {
          const nextToken = this.LA_FAST(1);
          if (this.tokenMatcher(nextToken, tokType) === true) {
            this.consumeToken();
            consumedToken = nextToken;
          } else {
            this.consumeInternalError(tokType, nextToken, options);
          }
        } catch (eFromConsumption) {
          consumedToken = this.consumeInternalRecovery(tokType, idx, eFromConsumption);
        }
        this.cstPostTerminal(options !== void 0 && options.LABEL !== void 0 ? options.LABEL : tokType.name, consumedToken);
        return consumedToken;
      }
      consumeInternalError(tokType, nextToken, options) {
        let msg;
        const previousToken = this.LA(0);
        if (options !== void 0 && options.ERR_MSG) {
          msg = options.ERR_MSG;
        } else {
          msg = this.errorMessageProvider.buildMismatchTokenMessage({
            expected: tokType,
            actual: nextToken,
            previous: previousToken,
            ruleName: this.getCurrRuleFullName()
          });
        }
        throw this.SAVE_ERROR(new MismatchedTokenException(msg, nextToken, previousToken));
      }
      consumeInternalRecovery(tokType, idx, eFromConsumption) {
        if (this.recoveryEnabled && // TODO: more robust checking of the exception type. Perhaps Typescript extending expressions?
        eFromConsumption.name === "MismatchedTokenException" && !this.isBackTracking()) {
          const follows = this.getFollowsForInRuleRecovery(tokType, idx);
          try {
            return this.tryInRuleRecovery(tokType, follows);
          } catch (eFromInRuleRecovery) {
            if (eFromInRuleRecovery.name === IN_RULE_RECOVERY_EXCEPTION) {
              throw eFromConsumption;
            } else {
              throw eFromInRuleRecovery;
            }
          }
        } else {
          throw eFromConsumption;
        }
      }
      saveRecogState() {
        const savedErrors = this.errors;
        const savedRuleStack = this.RULE_STACK.slice(0, this.RULE_STACK_IDX + 1);
        return {
          errors: savedErrors,
          lexerState: this.exportLexerState(),
          RULE_STACK: savedRuleStack,
          CST_STACK: this.CST_STACK
        };
      }
      reloadRecogState(newState2) {
        this.errors = newState2.errors;
        this.importLexerState(newState2.lexerState);
        const saved = newState2.RULE_STACK;
        for (let i = 0; i < saved.length; i++) {
          this.RULE_STACK[i] = saved[i];
        }
        this.RULE_STACK_IDX = saved.length - 1;
        if (this.RULE_STACK_IDX >= 0) {
          this.currRuleShortName = this.RULE_STACK[this.RULE_STACK_IDX];
        }
      }
      ruleInvocationStateUpdate(shortName, fullName, idxInCallingRule) {
        this.RULE_OCCURRENCE_STACK[++this.RULE_OCCURRENCE_STACK_IDX] = idxInCallingRule;
        this.RULE_STACK[++this.RULE_STACK_IDX] = shortName;
        this.currRuleShortName = shortName;
        this.cstInvocationStateUpdate(fullName);
      }
      isBackTracking() {
        return this.isBackTrackingStack.length !== 0;
      }
      getCurrRuleFullName() {
        const shortName = this.currRuleShortName;
        return this.shortRuleNameToFull[shortName];
      }
      shortRuleNameToFullName(shortName) {
        return this.shortRuleNameToFull[shortName];
      }
      isAtEndOfInput() {
        return this.tokenMatcher(this.LA(1), EOF);
      }
      reset() {
        this.resetLexerState();
        this.subruleIdx = 0;
        this.currRuleShortName = 0;
        this.isBackTrackingStack = [];
        this.errors = [];
        this.RULE_STACK_IDX = -1;
        this.RULE_OCCURRENCE_STACK_IDX = -1;
        this.CST_STACK = [];
      }
      /**
       * Hook called before the root-level parsing rule is invoked.
       * This is only called when a rule is invoked directly by the consumer
       * (e.g., `parser.json()`), not when invoked as a sub-rule via SUBRULE.
       *
       * Override this method to perform actions before parsing begins.
       * The default implementation is a no-op.
       *
       * @param ruleName - The name of the root rule being invoked.
       */
      onBeforeParse(ruleName) {
        for (let i = 0; i < this.maxLookahead + 1; i++) {
          this.tokVector.push(END_OF_FILE);
        }
      }
      /**
       * Hook called after the root-level parsing rule has completed (or thrown).
       * This is only called when a rule is invoked directly by the consumer
       * (e.g., `parser.json()`), not when invoked as a sub-rule via SUBRULE.
       *
       * This hook is called in a `finally` block, so it executes regardless of
       * whether parsing succeeded or threw an error.
       *
       * Override this method to perform actions after parsing completes.
       * The default implementation is a no-op.
       *
       * @param ruleName - The name of the root rule that was invoked.
       */
      onAfterParse(ruleName) {
        if (this.isAtEndOfInput() === false) {
          const firstRedundantTok = this.LA(1);
          const errMsg = this.errorMessageProvider.buildNotAllInputParsedMessage({
            firstRedundant: firstRedundantTok,
            ruleName: this.getCurrRuleFullName()
          });
          this.SAVE_ERROR(new NotAllInputParsedException(errMsg, firstRedundantTok));
        }
        while (this.tokVector.at(-1) === END_OF_FILE) {
          this.tokVector.pop();
        }
      }
    }
    class ErrorHandler {
      initErrorHandler(config) {
        this._errors = [];
        this.errorMessageProvider = Object.hasOwn(config, "errorMessageProvider") ? config.errorMessageProvider : DEFAULT_PARSER_CONFIG.errorMessageProvider;
      }
      SAVE_ERROR(error) {
        if (isRecognitionException(error)) {
          error.context = {
            ruleStack: this.getHumanReadableRuleStack(),
            ruleOccurrenceStack: this.RULE_OCCURRENCE_STACK.slice(0, this.RULE_OCCURRENCE_STACK_IDX + 1)
          };
          this._errors.push(error);
          return error;
        } else {
          throw Error("Trying to save an Error which is not a RecognitionException");
        }
      }
      get errors() {
        return [...this._errors];
      }
      set errors(newErrors) {
        this._errors = newErrors;
      }
      // TODO: consider caching the error message computed information
      raiseEarlyExitException(occurrence, prodType, userDefinedErrMsg) {
        const ruleName = this.getCurrRuleFullName();
        const ruleGrammar = this.getGAstProductions()[ruleName];
        const lookAheadPathsPerAlternative = getLookaheadPathsForOptionalProd(occurrence, ruleGrammar, prodType, this.maxLookahead);
        const insideProdPaths = lookAheadPathsPerAlternative[0];
        const actualTokens = [];
        for (let i = 1; i <= this.maxLookahead; i++) {
          actualTokens.push(this.LA(i));
        }
        const msg = this.errorMessageProvider.buildEarlyExitMessage({
          expectedIterationPaths: insideProdPaths,
          actual: actualTokens,
          previous: this.LA(0),
          customUserDescription: userDefinedErrMsg,
          ruleName
        });
        throw this.SAVE_ERROR(new EarlyExitException(msg, this.LA(1), this.LA(0)));
      }
      // TODO: consider caching the error message computed information
      raiseNoAltException(occurrence, errMsgTypes) {
        const ruleName = this.getCurrRuleFullName();
        const ruleGrammar = this.getGAstProductions()[ruleName];
        const lookAheadPathsPerAlternative = getLookaheadPathsForOr(occurrence, ruleGrammar, this.maxLookahead);
        const actualTokens = [];
        for (let i = 1; i <= this.maxLookahead; i++) {
          actualTokens.push(this.LA(i));
        }
        const previousToken = this.LA(0);
        const errMsg = this.errorMessageProvider.buildNoViableAltMessage({
          expectedPathsPerAlt: lookAheadPathsPerAlternative,
          actual: actualTokens,
          previous: previousToken,
          customUserDescription: errMsgTypes,
          ruleName: this.getCurrRuleFullName()
        });
        throw this.SAVE_ERROR(new NoViableAltException(errMsg, this.LA(1), previousToken));
      }
    }
    const RECORDING_NULL_OBJECT = {
      description: "This Object indicates the Parser is during Recording Phase"
    };
    Object.freeze(RECORDING_NULL_OBJECT);
    const HANDLE_SEPARATOR = true;
    const MAX_METHOD_IDX = Math.pow(2, BITS_FOR_OCCURRENCE_IDX) - 1;
    const RFT = createToken({ name: "RECORDING_PHASE_TOKEN", pattern: Lexer.NA });
    augmentTokenTypes([RFT]);
    const RECORDING_PHASE_TOKEN = createTokenInstance(
      RFT,
      "This IToken indicates the Parser is in Recording Phase\n	See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details",
      // Using "-1" instead of NaN (as in EOF) because an actual number is less likely to
      // cause errors if the output of LA or CONSUME would be (incorrectly) used during the recording phase.
      -1,
      -1,
      -1,
      -1,
      -1,
      -1
    );
    Object.freeze(RECORDING_PHASE_TOKEN);
    const RECORDING_PHASE_CSTNODE = {
      name: "This CSTNode indicates the Parser is in Recording Phase\n	See: https://chevrotain.io/docs/guide/internals.html#grammar-recording for details",
      children: {}
    };
    class GastRecorder {
      initGastRecorder(config) {
        this.recordingProdStack = [];
        this.RECORDING_PHASE = false;
      }
      enableRecording() {
        this.RECORDING_PHASE = true;
        this.TRACE_INIT("Enable Recording", () => {
          for (let i = 0; i < 10; i++) {
            const idx = i > 0 ? i : "";
            this[`CONSUME${idx}`] = function(arg1, arg2) {
              return this.consumeInternalRecord(arg1, i, arg2);
            };
            this[`SUBRULE${idx}`] = function(arg1, arg2) {
              return this.subruleInternalRecord(arg1, i, arg2);
            };
            this[`OPTION${idx}`] = function(arg1) {
              return this.optionInternalRecord(arg1, i);
            };
            this[`OR${idx}`] = function(arg1) {
              return this.orInternalRecord(arg1, i);
            };
            this[`MANY${idx}`] = function(arg1) {
              this.manyInternalRecord(i, arg1);
            };
            this[`MANY_SEP${idx}`] = function(arg1) {
              this.manySepFirstInternalRecord(i, arg1);
            };
            this[`AT_LEAST_ONE${idx}`] = function(arg1) {
              this.atLeastOneInternalRecord(i, arg1);
            };
            this[`AT_LEAST_ONE_SEP${idx}`] = function(arg1) {
              this.atLeastOneSepFirstInternalRecord(i, arg1);
            };
          }
          this[`consume`] = function(idx, arg1, arg2) {
            return this.consumeInternalRecord(arg1, idx, arg2);
          };
          this[`subrule`] = function(idx, arg1, arg2) {
            return this.subruleInternalRecord(arg1, idx, arg2);
          };
          this[`option`] = function(idx, arg1) {
            return this.optionInternalRecord(arg1, idx);
          };
          this[`or`] = function(idx, arg1) {
            return this.orInternalRecord(arg1, idx);
          };
          this[`many`] = function(idx, arg1) {
            this.manyInternalRecord(idx, arg1);
          };
          this[`atLeastOne`] = function(idx, arg1) {
            this.atLeastOneInternalRecord(idx, arg1);
          };
          this.ACTION = this.ACTION_RECORD;
          this.BACKTRACK = this.BACKTRACK_RECORD;
          this.LA = this.LA_RECORD;
        });
      }
      disableRecording() {
        this.RECORDING_PHASE = false;
        this.TRACE_INIT("Deleting Recording methods", () => {
          const that = this;
          for (let i = 0; i < 10; i++) {
            const idx = i > 0 ? i : "";
            delete that[`CONSUME${idx}`];
            delete that[`SUBRULE${idx}`];
            delete that[`OPTION${idx}`];
            delete that[`OR${idx}`];
            delete that[`MANY${idx}`];
            delete that[`MANY_SEP${idx}`];
            delete that[`AT_LEAST_ONE${idx}`];
            delete that[`AT_LEAST_ONE_SEP${idx}`];
          }
          delete that[`consume`];
          delete that[`subrule`];
          delete that[`option`];
          delete that[`or`];
          delete that[`many`];
          delete that[`atLeastOne`];
          delete that.ACTION;
          delete that.BACKTRACK;
          delete that.LA;
        });
      }
      //   Parser methods are called inside an ACTION?
      //   Maybe try/catch/finally on ACTIONS while disabling the recorders state changes?
      // @ts-expect-error -- noop place holder
      ACTION_RECORD(impl) {
      }
      // Executing backtracking logic will break our recording logic assumptions
      BACKTRACK_RECORD(grammarRule, args) {
        return () => true;
      }
      // LA is part of the official API and may be used for custom lookahead logic
      // by end users who may forget to wrap it in ACTION or inside a GATE
      LA_RECORD(howMuch) {
        return END_OF_FILE;
      }
      topLevelRuleRecord(name, def) {
        try {
          const newTopLevelRule = new Rule({ definition: [], name });
          newTopLevelRule.name = name;
          this.recordingProdStack.push(newTopLevelRule);
          def.call(this);
          this.recordingProdStack.pop();
          return newTopLevelRule;
        } catch (originalError) {
          if (originalError.KNOWN_RECORDER_ERROR !== true) {
            try {
              originalError.message = originalError.message + '\n	 This error was thrown during the "grammar recording phase" For more info see:\n	https://chevrotain.io/docs/guide/internals.html#grammar-recording';
            } catch (mutabilityError) {
              throw originalError;
            }
          }
          throw originalError;
        }
      }
      // Implementation of parsing DSL
      optionInternalRecord(actionORMethodDef, occurrence) {
        return recordProd.call(this, Option, actionORMethodDef, occurrence);
      }
      atLeastOneInternalRecord(occurrence, actionORMethodDef) {
        recordProd.call(this, RepetitionMandatory, actionORMethodDef, occurrence);
      }
      atLeastOneSepFirstInternalRecord(occurrence, options) {
        recordProd.call(this, RepetitionMandatoryWithSeparator, options, occurrence, HANDLE_SEPARATOR);
      }
      manyInternalRecord(occurrence, actionORMethodDef) {
        recordProd.call(this, Repetition, actionORMethodDef, occurrence);
      }
      manySepFirstInternalRecord(occurrence, options) {
        recordProd.call(this, RepetitionWithSeparator, options, occurrence, HANDLE_SEPARATOR);
      }
      orInternalRecord(altsOrOpts, occurrence) {
        return recordOrProd.call(this, altsOrOpts, occurrence);
      }
      subruleInternalRecord(ruleToCall, occurrence, options) {
        assertMethodIdxIsValid(occurrence);
        if (!ruleToCall || !Object.hasOwn(ruleToCall, "ruleName")) {
          const error = new Error(`<SUBRULE${getIdxSuffix(occurrence)}> argument is invalid expecting a Parser method reference but got: <${JSON.stringify(ruleToCall)}>
 inside top level rule: <${this.recordingProdStack[0].name}>`);
          error.KNOWN_RECORDER_ERROR = true;
          throw error;
        }
        const prevProd = this.recordingProdStack.at(-1);
        const ruleName = ruleToCall.ruleName;
        const newNoneTerminal = new NonTerminal({
          idx: occurrence,
          nonTerminalName: ruleName,
          label: options === null || options === void 0 ? void 0 : options.LABEL,
          // The resolving of the `referencedRule` property will be done once all the Rule's GASTs have been created
          referencedRule: void 0
        });
        prevProd.definition.push(newNoneTerminal);
        return this.outputCst ? RECORDING_PHASE_CSTNODE : RECORDING_NULL_OBJECT;
      }
      consumeInternalRecord(tokType, occurrence, options) {
        assertMethodIdxIsValid(occurrence);
        if (!hasShortKeyProperty(tokType)) {
          const error = new Error(`<CONSUME${getIdxSuffix(occurrence)}> argument is invalid expecting a TokenType reference but got: <${JSON.stringify(tokType)}>
 inside top level rule: <${this.recordingProdStack[0].name}>`);
          error.KNOWN_RECORDER_ERROR = true;
          throw error;
        }
        const prevProd = this.recordingProdStack.at(-1);
        const newNoneTerminal = new Terminal({
          idx: occurrence,
          terminalType: tokType,
          label: options === null || options === void 0 ? void 0 : options.LABEL
        });
        prevProd.definition.push(newNoneTerminal);
        return RECORDING_PHASE_TOKEN;
      }
    }
    function recordProd(prodConstructor, mainProdArg, occurrence, handleSep = false) {
      assertMethodIdxIsValid(occurrence);
      const prevProd = this.recordingProdStack.at(-1);
      const grammarAction = typeof mainProdArg === "function" ? mainProdArg : mainProdArg.DEF;
      const newProd = new prodConstructor({ definition: [], idx: occurrence });
      if (handleSep) {
        newProd.separator = mainProdArg.SEP;
      }
      if (Object.hasOwn(mainProdArg, "MAX_LOOKAHEAD")) {
        newProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD;
      }
      this.recordingProdStack.push(newProd);
      grammarAction.call(this);
      prevProd.definition.push(newProd);
      this.recordingProdStack.pop();
      return RECORDING_NULL_OBJECT;
    }
    function recordOrProd(mainProdArg, occurrence) {
      assertMethodIdxIsValid(occurrence);
      const prevProd = this.recordingProdStack.at(-1);
      const hasOptions = Array.isArray(mainProdArg) === false;
      const alts = hasOptions === false ? mainProdArg : mainProdArg.DEF;
      const newOrProd = new Alternation({
        definition: [],
        idx: occurrence,
        ignoreAmbiguities: hasOptions && mainProdArg.IGNORE_AMBIGUITIES === true
      });
      if (Object.hasOwn(mainProdArg, "MAX_LOOKAHEAD")) {
        newOrProd.maxLookahead = mainProdArg.MAX_LOOKAHEAD;
      }
      const hasPredicates = alts.some((currAlt) => typeof currAlt.GATE === "function");
      newOrProd.hasPredicates = hasPredicates;
      prevProd.definition.push(newOrProd);
      alts.forEach((currAlt) => {
        const currAltFlat = new Alternative({ definition: [] });
        newOrProd.definition.push(currAltFlat);
        if (Object.hasOwn(currAlt, "IGNORE_AMBIGUITIES")) {
          currAltFlat.ignoreAmbiguities = currAlt.IGNORE_AMBIGUITIES;
        } else if (Object.hasOwn(currAlt, "GATE")) {
          currAltFlat.ignoreAmbiguities = true;
        }
        this.recordingProdStack.push(currAltFlat);
        currAlt.ALT.call(this);
        this.recordingProdStack.pop();
      });
      return RECORDING_NULL_OBJECT;
    }
    function getIdxSuffix(idx) {
      return idx === 0 ? "" : `${idx}`;
    }
    function assertMethodIdxIsValid(idx) {
      if (idx < 0 || idx > MAX_METHOD_IDX) {
        const error = new Error(
          // The stack trace will contain all the needed details
          `Invalid DSL Method idx value: <${idx}>
	Idx value must be a none negative value smaller than ${MAX_METHOD_IDX + 1}`
        );
        error.KNOWN_RECORDER_ERROR = true;
        throw error;
      }
    }
    class PerformanceTracer {
      initPerformanceTracer(config) {
        if (Object.hasOwn(config, "traceInitPerf")) {
          const userTraceInitPerf = config.traceInitPerf;
          const traceIsNumber = typeof userTraceInitPerf === "number";
          this.traceInitMaxIdent = traceIsNumber ? userTraceInitPerf : Infinity;
          this.traceInitPerf = traceIsNumber ? userTraceInitPerf > 0 : userTraceInitPerf;
        } else {
          this.traceInitMaxIdent = 0;
          this.traceInitPerf = DEFAULT_PARSER_CONFIG.traceInitPerf;
        }
        this.traceInitIndent = -1;
      }
      TRACE_INIT(phaseDesc, phaseImpl) {
        if (this.traceInitPerf === true) {
          this.traceInitIndent++;
          const indent = new Array(this.traceInitIndent + 1).join("	");
          if (this.traceInitIndent < this.traceInitMaxIdent) {
            console.log(`${indent}--> <${phaseDesc}>`);
          }
          const { time, value } = timer(phaseImpl);
          const traceMethod = time > 10 ? console.warn : console.log;
          if (this.traceInitIndent < this.traceInitMaxIdent) {
            traceMethod(`${indent}<-- <${phaseDesc}> time: ${time}ms`);
          }
          this.traceInitIndent--;
          return value;
        } else {
          return phaseImpl();
        }
      }
    }
    function applyMixins(derivedCtor, baseCtors) {
      baseCtors.forEach((baseCtor) => {
        const baseProto = baseCtor.prototype;
        Object.getOwnPropertyNames(baseProto).forEach((propName) => {
          if (propName === "constructor") {
            return;
          }
          const basePropDescriptor = Object.getOwnPropertyDescriptor(baseProto, propName);
          if (basePropDescriptor && (basePropDescriptor.get || basePropDescriptor.set)) {
            Object.defineProperty(derivedCtor.prototype, propName, basePropDescriptor);
          } else {
            derivedCtor.prototype[propName] = baseCtor.prototype[propName];
          }
        });
      });
    }
    const END_OF_FILE = createTokenInstance(EOF, "", NaN, NaN, NaN, NaN, NaN, NaN);
    Object.freeze(END_OF_FILE);
    const DEFAULT_PARSER_CONFIG = Object.freeze({
      recoveryEnabled: false,
      maxLookahead: 3,
      dynamicTokensEnabled: false,
      outputCst: true,
      errorMessageProvider: defaultParserErrorProvider,
      nodeLocationTracking: "none",
      traceInitPerf: false,
      skipValidations: false
    });
    const DEFAULT_RULE_CONFIG = Object.freeze({
      recoveryValueFunc: () => void 0,
      resyncEnabled: true
    });
    var ParserDefinitionErrorType;
    (function(ParserDefinitionErrorType2) {
      ParserDefinitionErrorType2[ParserDefinitionErrorType2["INVALID_RULE_NAME"] = 0] = "INVALID_RULE_NAME";
      ParserDefinitionErrorType2[ParserDefinitionErrorType2["DUPLICATE_RULE_NAME"] = 1] = "DUPLICATE_RULE_NAME";
      ParserDefinitionErrorType2[ParserDefinitionErrorType2["INVALID_RULE_OVERRIDE"] = 2] = "INVALID_RULE_OVERRIDE";
      ParserDefinitionErrorType2[ParserDefinitionErrorType2["DUPLICATE_PRODUCTIONS"] = 3] = "DUPLICATE_PRODUCTIONS";
      ParserDefinitionErrorType2[ParserDefinitionErrorType2["UNRESOLVED_SUBRULE_REF"] = 4] = "UNRESOLVED_SUBRULE_REF";
      ParserDefinitionErrorType2[ParserDefinitionErrorType2["LEFT_RECURSION"] = 5] = "LEFT_RECURSION";
      ParserDefinitionErrorType2[ParserDefinitionErrorType2["NONE_LAST_EMPTY_ALT"] = 6] = "NONE_LAST_EMPTY_ALT";
      ParserDefinitionErrorType2[ParserDefinitionErrorType2["AMBIGUOUS_ALTS"] = 7] = "AMBIGUOUS_ALTS";
      ParserDefinitionErrorType2[ParserDefinitionErrorType2["CONFLICT_TOKENS_RULES_NAMESPACE"] = 8] = "CONFLICT_TOKENS_RULES_NAMESPACE";
      ParserDefinitionErrorType2[ParserDefinitionErrorType2["INVALID_TOKEN_NAME"] = 9] = "INVALID_TOKEN_NAME";
      ParserDefinitionErrorType2[ParserDefinitionErrorType2["NO_NON_EMPTY_LOOKAHEAD"] = 10] = "NO_NON_EMPTY_LOOKAHEAD";
      ParserDefinitionErrorType2[ParserDefinitionErrorType2["AMBIGUOUS_PREFIX_ALTS"] = 11] = "AMBIGUOUS_PREFIX_ALTS";
      ParserDefinitionErrorType2[ParserDefinitionErrorType2["TOO_MANY_ALTS"] = 12] = "TOO_MANY_ALTS";
      ParserDefinitionErrorType2[ParserDefinitionErrorType2["CUSTOM_LOOKAHEAD_VALIDATION"] = 13] = "CUSTOM_LOOKAHEAD_VALIDATION";
    })(ParserDefinitionErrorType || (ParserDefinitionErrorType = {}));
    function EMPTY_ALT(value = void 0) {
      return function() {
        return value;
      };
    }
    class Parser {
      /**
       *  @deprecated use the **instance** method with the same name instead
       */
      static performSelfAnalysis(parserInstance) {
        throw Error("The **static** `performSelfAnalysis` method has been deprecated.	\nUse the **instance** method with the same name instead.");
      }
      performSelfAnalysis() {
        this.TRACE_INIT("performSelfAnalysis", () => {
          let defErrorsMsgs;
          this.selfAnalysisDone = true;
          const className = this.className;
          this.TRACE_INIT("toFastProps", () => {
            toFastProperties(this);
          });
          this.TRACE_INIT("Grammar Recording", () => {
            try {
              this.enableRecording();
              this.definedRulesNames.forEach((currRuleName) => {
                const wrappedRule = this[currRuleName];
                const originalGrammarAction = wrappedRule["originalGrammarAction"];
                let recordedRuleGast;
                this.TRACE_INIT(`${currRuleName} Rule`, () => {
                  recordedRuleGast = this.topLevelRuleRecord(currRuleName, originalGrammarAction);
                });
                this.gastProductionsCache[currRuleName] = recordedRuleGast;
              });
            } finally {
              this.disableRecording();
            }
          });
          let resolverErrors = [];
          this.TRACE_INIT("Grammar Resolving", () => {
            resolverErrors = resolveGrammar({
              rules: Object.values(this.gastProductionsCache)
            });
            this.definitionErrors = this.definitionErrors.concat(resolverErrors);
          });
          this.TRACE_INIT("Grammar Validations", () => {
            if (resolverErrors.length === 0 && this.skipValidations === false) {
              const validationErrors = validateGrammar({
                rules: Object.values(this.gastProductionsCache),
                tokenTypes: Object.values(this.tokensMap),
                errMsgProvider: defaultGrammarValidatorErrorProvider,
                grammarName: className
              });
              const lookaheadValidationErrors = validateLookahead({
                lookaheadStrategy: this.lookaheadStrategy,
                rules: Object.values(this.gastProductionsCache),
                tokenTypes: Object.values(this.tokensMap),
                grammarName: className
              });
              this.definitionErrors = this.definitionErrors.concat(validationErrors, lookaheadValidationErrors);
            }
          });
          if (this.definitionErrors.length === 0) {
            if (this.recoveryEnabled) {
              this.TRACE_INIT("computeAllProdsFollows", () => {
                const allFollows = computeAllProdsFollows(Object.values(this.gastProductionsCache));
                this.resyncFollows = allFollows;
              });
            }
            this.TRACE_INIT("ComputeLookaheadFunctions", () => {
              var _a, _b;
              (_b = (_a = this.lookaheadStrategy).initialize) === null || _b === void 0 ? void 0 : _b.call(_a, {
                rules: Object.values(this.gastProductionsCache)
              });
              this.preComputeLookaheadFunctions(Object.values(this.gastProductionsCache));
            });
          }
          if (!Parser.DEFER_DEFINITION_ERRORS_HANDLING && this.definitionErrors.length !== 0) {
            defErrorsMsgs = this.definitionErrors.map((defError) => defError.message);
            throw new Error(`Parser Definition Errors detected:
 ${defErrorsMsgs.join("\n-------------------------------\n")}`);
          }
        });
      }
      constructor(tokenVocabulary, config) {
        this.definitionErrors = [];
        this.selfAnalysisDone = false;
        const that = this;
        that.initErrorHandler(config);
        that.initLexerAdapter();
        that.initLooksAhead(config);
        that.initRecognizerEngine(tokenVocabulary, config);
        that.initRecoverable(config);
        that.initTreeBuilder(config);
        that.initGastRecorder(config);
        that.initPerformanceTracer(config);
        if (Object.hasOwn(config, "ignoredIssues")) {
          throw new Error("The <ignoredIssues> IParserConfig property has been deprecated.\n	Please use the <IGNORE_AMBIGUITIES> flag on the relevant DSL method instead.\n	See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#IGNORING_AMBIGUITIES\n	For further details.");
        }
        this.skipValidations = Object.hasOwn(config, "skipValidations") ? config.skipValidations : DEFAULT_PARSER_CONFIG.skipValidations;
      }
    }
    Parser.DEFER_DEFINITION_ERRORS_HANDLING = false;
    applyMixins(Parser, [
      Recoverable,
      LooksAhead,
      TreeBuilder,
      LexerAdapter,
      RecognizerEngine,
      RecognizerApi,
      ErrorHandler,
      GastRecorder,
      PerformanceTracer
    ]);
    class EmbeddedActionsParser extends Parser {
      constructor(tokenVocabulary, config = DEFAULT_PARSER_CONFIG) {
        const configClone = Object.assign({}, config);
        configClone.outputCst = false;
        super(tokenVocabulary, configClone);
      }
    }
    function arrayMap(array, iteratee) {
      var index = -1, length = array == null ? 0 : array.length, result = Array(length);
      while (++index < length) {
        result[index] = iteratee(array[index], index, array);
      }
      return result;
    }
    function listCacheClear() {
      this.__data__ = [];
      this.size = 0;
    }
    function eq(value, other) {
      return value === other || value !== value && other !== other;
    }
    function assocIndexOf(array, key) {
      var length = array.length;
      while (length--) {
        if (eq(array[length][0], key)) {
          return length;
        }
      }
      return -1;
    }
    var arrayProto = Array.prototype;
    var splice = arrayProto.splice;
    function listCacheDelete(key) {
      var data = this.__data__, index = assocIndexOf(data, key);
      if (index < 0) {
        return false;
      }
      var lastIndex = data.length - 1;
      if (index == lastIndex) {
        data.pop();
      } else {
        splice.call(data, index, 1);
      }
      --this.size;
      return true;
    }
    function listCacheGet(key) {
      var data = this.__data__, index = assocIndexOf(data, key);
      return index < 0 ? void 0 : data[index][1];
    }
    function listCacheHas(key) {
      return assocIndexOf(this.__data__, key) > -1;
    }
    function listCacheSet(key, value) {
      var data = this.__data__, index = assocIndexOf(data, key);
      if (index < 0) {
        ++this.size;
        data.push([key, value]);
      } else {
        data[index][1] = value;
      }
      return this;
    }
    function ListCache(entries) {
      var index = -1, length = entries == null ? 0 : entries.length;
      this.clear();
      while (++index < length) {
        var entry = entries[index];
        this.set(entry[0], entry[1]);
      }
    }
    ListCache.prototype.clear = listCacheClear;
    ListCache.prototype["delete"] = listCacheDelete;
    ListCache.prototype.get = listCacheGet;
    ListCache.prototype.has = listCacheHas;
    ListCache.prototype.set = listCacheSet;
    function stackClear() {
      this.__data__ = new ListCache();
      this.size = 0;
    }
    function stackDelete(key) {
      var data = this.__data__, result = data["delete"](key);
      this.size = data.size;
      return result;
    }
    function stackGet(key) {
      return this.__data__.get(key);
    }
    function stackHas(key) {
      return this.__data__.has(key);
    }
    var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
    var freeSelf = typeof self == "object" && self && self.Object === Object && self;
    var root = freeGlobal || freeSelf || Function("return this")();
    var Symbol$1 = root.Symbol;
    var objectProto$c = Object.prototype;
    var hasOwnProperty$9 = objectProto$c.hasOwnProperty;
    var nativeObjectToString$1 = objectProto$c.toString;
    var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : void 0;
    function getRawTag(value) {
      var isOwn = hasOwnProperty$9.call(value, symToStringTag$1), tag = value[symToStringTag$1];
      try {
        value[symToStringTag$1] = void 0;
        var unmasked = true;
      } catch (e) {
      }
      var result = nativeObjectToString$1.call(value);
      if (unmasked) {
        if (isOwn) {
          value[symToStringTag$1] = tag;
        } else {
          delete value[symToStringTag$1];
        }
      }
      return result;
    }
    var objectProto$b = Object.prototype;
    var nativeObjectToString = objectProto$b.toString;
    function objectToString(value) {
      return nativeObjectToString.call(value);
    }
    var nullTag = "[object Null]", undefinedTag = "[object Undefined]";
    var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : void 0;
    function baseGetTag(value) {
      if (value == null) {
        return value === void 0 ? undefinedTag : nullTag;
      }
      return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
    }
    function isObject(value) {
      var type = typeof value;
      return value != null && (type == "object" || type == "function");
    }
    var asyncTag = "[object AsyncFunction]", funcTag$1 = "[object Function]", genTag = "[object GeneratorFunction]", proxyTag = "[object Proxy]";
    function isFunction(value) {
      if (!isObject(value)) {
        return false;
      }
      var tag = baseGetTag(value);
      return tag == funcTag$1 || tag == genTag || tag == asyncTag || tag == proxyTag;
    }
    var coreJsData = root["__core-js_shared__"];
    var maskSrcKey = (function() {
      var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "");
      return uid ? "Symbol(src)_1." + uid : "";
    })();
    function isMasked(func) {
      return !!maskSrcKey && maskSrcKey in func;
    }
    var funcProto$1 = Function.prototype;
    var funcToString$1 = funcProto$1.toString;
    function toSource(func) {
      if (func != null) {
        try {
          return funcToString$1.call(func);
        } catch (e) {
        }
        try {
          return func + "";
        } catch (e) {
        }
      }
      return "";
    }
    var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
    var reIsHostCtor = /^\[object .+?Constructor\]$/;
    var funcProto = Function.prototype, objectProto$a = Object.prototype;
    var funcToString = funcProto.toString;
    var hasOwnProperty$8 = objectProto$a.hasOwnProperty;
    var reIsNative = RegExp(
      "^" + funcToString.call(hasOwnProperty$8).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
    );
    function baseIsNative(value) {
      if (!isObject(value) || isMasked(value)) {
        return false;
      }
      var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
      return pattern.test(toSource(value));
    }
    function getValue(object, key) {
      return object == null ? void 0 : object[key];
    }
    function getNative(object, key) {
      var value = getValue(object, key);
      return baseIsNative(value) ? value : void 0;
    }
    var Map$1 = getNative(root, "Map");
    var nativeCreate = getNative(Object, "create");
    function hashClear() {
      this.__data__ = nativeCreate ? nativeCreate(null) : {};
      this.size = 0;
    }
    function hashDelete(key) {
      var result = this.has(key) && delete this.__data__[key];
      this.size -= result ? 1 : 0;
      return result;
    }
    var HASH_UNDEFINED$2 = "__lodash_hash_undefined__";
    var objectProto$9 = Object.prototype;
    var hasOwnProperty$7 = objectProto$9.hasOwnProperty;
    function hashGet(key) {
      var data = this.__data__;
      if (nativeCreate) {
        var result = data[key];
        return result === HASH_UNDEFINED$2 ? void 0 : result;
      }
      return hasOwnProperty$7.call(data, key) ? data[key] : void 0;
    }
    var objectProto$8 = Object.prototype;
    var hasOwnProperty$6 = objectProto$8.hasOwnProperty;
    function hashHas(key) {
      var data = this.__data__;
      return nativeCreate ? data[key] !== void 0 : hasOwnProperty$6.call(data, key);
    }
    var HASH_UNDEFINED$1 = "__lodash_hash_undefined__";
    function hashSet(key, value) {
      var data = this.__data__;
      this.size += this.has(key) ? 0 : 1;
      data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED$1 : value;
      return this;
    }
    function Hash(entries) {
      var index = -1, length = entries == null ? 0 : entries.length;
      this.clear();
      while (++index < length) {
        var entry = entries[index];
        this.set(entry[0], entry[1]);
      }
    }
    Hash.prototype.clear = hashClear;
    Hash.prototype["delete"] = hashDelete;
    Hash.prototype.get = hashGet;
    Hash.prototype.has = hashHas;
    Hash.prototype.set = hashSet;
    function mapCacheClear() {
      this.size = 0;
      this.__data__ = {
        "hash": new Hash(),
        "map": new (Map$1 || ListCache)(),
        "string": new Hash()
      };
    }
    function isKeyable(value) {
      var type = typeof value;
      return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
    }
    function getMapData(map2, key) {
      var data = map2.__data__;
      return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
    }
    function mapCacheDelete(key) {
      var result = getMapData(this, key)["delete"](key);
      this.size -= result ? 1 : 0;
      return result;
    }
    function mapCacheGet(key) {
      return getMapData(this, key).get(key);
    }
    function mapCacheHas(key) {
      return getMapData(this, key).has(key);
    }
    function mapCacheSet(key, value) {
      var data = getMapData(this, key), size = data.size;
      data.set(key, value);
      this.size += data.size == size ? 0 : 1;
      return this;
    }
    function MapCache(entries) {
      var index = -1, length = entries == null ? 0 : entries.length;
      this.clear();
      while (++index < length) {
        var entry = entries[index];
        this.set(entry[0], entry[1]);
      }
    }
    MapCache.prototype.clear = mapCacheClear;
    MapCache.prototype["delete"] = mapCacheDelete;
    MapCache.prototype.get = mapCacheGet;
    MapCache.prototype.has = mapCacheHas;
    MapCache.prototype.set = mapCacheSet;
    var LARGE_ARRAY_SIZE$1 = 200;
    function stackSet(key, value) {
      var data = this.__data__;
      if (data instanceof ListCache) {
        var pairs = data.__data__;
        if (!Map$1 || pairs.length < LARGE_ARRAY_SIZE$1 - 1) {
          pairs.push([key, value]);
          this.size = ++data.size;
          return this;
        }
        data = this.__data__ = new MapCache(pairs);
      }
      data.set(key, value);
      this.size = data.size;
      return this;
    }
    function Stack(entries) {
      var data = this.__data__ = new ListCache(entries);
      this.size = data.size;
    }
    Stack.prototype.clear = stackClear;
    Stack.prototype["delete"] = stackDelete;
    Stack.prototype.get = stackGet;
    Stack.prototype.has = stackHas;
    Stack.prototype.set = stackSet;
    var HASH_UNDEFINED = "__lodash_hash_undefined__";
    function setCacheAdd(value) {
      this.__data__.set(value, HASH_UNDEFINED);
      return this;
    }
    function setCacheHas(value) {
      return this.__data__.has(value);
    }
    function SetCache(values) {
      var index = -1, length = values == null ? 0 : values.length;
      this.__data__ = new MapCache();
      while (++index < length) {
        this.add(values[index]);
      }
    }
    SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
    SetCache.prototype.has = setCacheHas;
    function arraySome(array, predicate) {
      var index = -1, length = array == null ? 0 : array.length;
      while (++index < length) {
        if (predicate(array[index], index, array)) {
          return true;
        }
      }
      return false;
    }
    function cacheHas(cache, key) {
      return cache.has(key);
    }
    var COMPARE_PARTIAL_FLAG$5 = 1, COMPARE_UNORDERED_FLAG$3 = 2;
    function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
      var isPartial = bitmask & COMPARE_PARTIAL_FLAG$5, arrLength = array.length, othLength = other.length;
      if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
        return false;
      }
      var arrStacked = stack.get(array);
      var othStacked = stack.get(other);
      if (arrStacked && othStacked) {
        return arrStacked == other && othStacked == array;
      }
      var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG$3 ? new SetCache() : void 0;
      stack.set(array, other);
      stack.set(other, array);
      while (++index < arrLength) {
        var arrValue = array[index], othValue = other[index];
        if (customizer) {
          var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
        }
        if (compared !== void 0) {
          if (compared) {
            continue;
          }
          result = false;
          break;
        }
        if (seen) {
          if (!arraySome(other, function(othValue2, othIndex) {
            if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
              return seen.push(othIndex);
            }
          })) {
            result = false;
            break;
          }
        } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
          result = false;
          break;
        }
      }
      stack["delete"](array);
      stack["delete"](other);
      return result;
    }
    var Uint8Array2 = root.Uint8Array;
    function mapToArray(map2) {
      var index = -1, result = Array(map2.size);
      map2.forEach(function(value, key) {
        result[++index] = [key, value];
      });
      return result;
    }
    function setToArray(set) {
      var index = -1, result = Array(set.size);
      set.forEach(function(value) {
        result[++index] = value;
      });
      return result;
    }
    var COMPARE_PARTIAL_FLAG$4 = 1, COMPARE_UNORDERED_FLAG$2 = 2;
    var boolTag$1 = "[object Boolean]", dateTag$1 = "[object Date]", errorTag$1 = "[object Error]", mapTag$3 = "[object Map]", numberTag$1 = "[object Number]", regexpTag$1 = "[object RegExp]", setTag$3 = "[object Set]", stringTag$1 = "[object String]", symbolTag$1 = "[object Symbol]";
    var arrayBufferTag$1 = "[object ArrayBuffer]", dataViewTag$2 = "[object DataView]";
    var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : void 0, symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : void 0;
    function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
      switch (tag) {
        case dataViewTag$2:
          if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
            return false;
          }
          object = object.buffer;
          other = other.buffer;
        case arrayBufferTag$1:
          if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) {
            return false;
          }
          return true;
        case boolTag$1:
        case dateTag$1:
        case numberTag$1:
          return eq(+object, +other);
        case errorTag$1:
          return object.name == other.name && object.message == other.message;
        case regexpTag$1:
        case stringTag$1:
          return object == other + "";
        case mapTag$3:
          var convert = mapToArray;
        case setTag$3:
          var isPartial = bitmask & COMPARE_PARTIAL_FLAG$4;
          convert || (convert = setToArray);
          if (object.size != other.size && !isPartial) {
            return false;
          }
          var stacked = stack.get(object);
          if (stacked) {
            return stacked == other;
          }
          bitmask |= COMPARE_UNORDERED_FLAG$2;
          stack.set(object, other);
          var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
          stack["delete"](object);
          return result;
        case symbolTag$1:
          if (symbolValueOf) {
            return symbolValueOf.call(object) == symbolValueOf.call(other);
          }
      }
      return false;
    }
    function arrayPush(array, values) {
      var index = -1, length = values.length, offset = array.length;
      while (++index < length) {
        array[offset + index] = values[index];
      }
      return array;
    }
    var isArray = Array.isArray;
    function baseGetAllKeys(object, keysFunc, symbolsFunc) {
      var result = keysFunc(object);
      return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
    }
    function arrayFilter(array, predicate) {
      var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = [];
      while (++index < length) {
        var value = array[index];
        if (predicate(value, index, array)) {
          result[resIndex++] = value;
        }
      }
      return result;
    }
    function stubArray() {
      return [];
    }
    var objectProto$7 = Object.prototype;
    var propertyIsEnumerable$1 = objectProto$7.propertyIsEnumerable;
    var nativeGetSymbols = Object.getOwnPropertySymbols;
    var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
      if (object == null) {
        return [];
      }
      object = Object(object);
      return arrayFilter(nativeGetSymbols(object), function(symbol) {
        return propertyIsEnumerable$1.call(object, symbol);
      });
    };
    function baseTimes(n, iteratee) {
      var index = -1, result = Array(n);
      while (++index < n) {
        result[index] = iteratee(index);
      }
      return result;
    }
    function isObjectLike(value) {
      return value != null && typeof value == "object";
    }
    var argsTag$2 = "[object Arguments]";
    function baseIsArguments(value) {
      return isObjectLike(value) && baseGetTag(value) == argsTag$2;
    }
    var objectProto$6 = Object.prototype;
    var hasOwnProperty$5 = objectProto$6.hasOwnProperty;
    var propertyIsEnumerable = objectProto$6.propertyIsEnumerable;
    var isArguments = baseIsArguments(/* @__PURE__ */ (function() {
      return arguments;
    })()) ? baseIsArguments : function(value) {
      return isObjectLike(value) && hasOwnProperty$5.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
    };
    function stubFalse() {
      return false;
    }
    var freeExports$1 = typeof exports == "object" && exports && !exports.nodeType && exports;
    var freeModule$1 = freeExports$1 && typeof module == "object" && module && !module.nodeType && module;
    var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1;
    var Buffer$1 = moduleExports$1 ? root.Buffer : void 0;
    var nativeIsBuffer = Buffer$1 ? Buffer$1.isBuffer : void 0;
    var isBuffer = nativeIsBuffer || stubFalse;
    var MAX_SAFE_INTEGER$1 = 9007199254740991;
    var reIsUint = /^(?:0|[1-9]\d*)$/;
    function isIndex(value, length) {
      var type = typeof value;
      length = length == null ? MAX_SAFE_INTEGER$1 : length;
      return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
    }
    var MAX_SAFE_INTEGER = 9007199254740991;
    function isLength(value) {
      return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
    }
    var argsTag$1 = "[object Arguments]", arrayTag$1 = "[object Array]", boolTag = "[object Boolean]", dateTag = "[object Date]", errorTag = "[object Error]", funcTag = "[object Function]", mapTag$2 = "[object Map]", numberTag = "[object Number]", objectTag$2 = "[object Object]", regexpTag = "[object RegExp]", setTag$2 = "[object Set]", stringTag = "[object String]", weakMapTag$1 = "[object WeakMap]";
    var arrayBufferTag = "[object ArrayBuffer]", dataViewTag$1 = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]";
    var typedArrayTags = {};
    typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
    typedArrayTags[argsTag$1] = typedArrayTags[arrayTag$1] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag$1] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag$2] = typedArrayTags[numberTag] = typedArrayTags[objectTag$2] = typedArrayTags[regexpTag] = typedArrayTags[setTag$2] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag$1] = false;
    function baseIsTypedArray(value) {
      return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
    }
    function baseUnary(func) {
      return function(value) {
        return func(value);
      };
    }
    var freeExports = typeof exports == "object" && exports && !exports.nodeType && exports;
    var freeModule = freeExports && typeof module == "object" && module && !module.nodeType && module;
    var moduleExports = freeModule && freeModule.exports === freeExports;
    var freeProcess = moduleExports && freeGlobal.process;
    var nodeUtil = (function() {
      try {
        var types = freeModule && freeModule.require && freeModule.require("util").types;
        if (types) {
          return types;
        }
        return freeProcess && freeProcess.binding && freeProcess.binding("util");
      } catch (e) {
      }
    })();
    var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
    var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
    var objectProto$5 = Object.prototype;
    var hasOwnProperty$4 = objectProto$5.hasOwnProperty;
    function arrayLikeKeys(value, inherited) {
      var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType2 = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType2, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length;
      for (var key in value) {
        if (hasOwnProperty$4.call(value, key) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode.
        (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers.
        isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays.
        isType2 && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties.
        isIndex(key, length)))) {
          result.push(key);
        }
      }
      return result;
    }
    var objectProto$4 = Object.prototype;
    function isPrototype(value) {
      var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto$4;
      return value === proto;
    }
    function overArg(func, transform) {
      return function(arg) {
        return func(transform(arg));
      };
    }
    var nativeKeys = overArg(Object.keys, Object);
    var objectProto$3 = Object.prototype;
    var hasOwnProperty$3 = objectProto$3.hasOwnProperty;
    function baseKeys(object) {
      if (!isPrototype(object)) {
        return nativeKeys(object);
      }
      var result = [];
      for (var key in Object(object)) {
        if (hasOwnProperty$3.call(object, key) && key != "constructor") {
          result.push(key);
        }
      }
      return result;
    }
    function isArrayLike(value) {
      return value != null && isLength(value.length) && !isFunction(value);
    }
    function keys(object) {
      return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
    }
    function getAllKeys(object) {
      return baseGetAllKeys(object, keys, getSymbols);
    }
    var COMPARE_PARTIAL_FLAG$3 = 1;
    var objectProto$2 = Object.prototype;
    var hasOwnProperty$2 = objectProto$2.hasOwnProperty;
    function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
      var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length;
      if (objLength != othLength && !isPartial) {
        return false;
      }
      var index = objLength;
      while (index--) {
        var key = objProps[index];
        if (!(isPartial ? key in other : hasOwnProperty$2.call(other, key))) {
          return false;
        }
      }
      var objStacked = stack.get(object);
      var othStacked = stack.get(other);
      if (objStacked && othStacked) {
        return objStacked == other && othStacked == object;
      }
      var result = true;
      stack.set(object, other);
      stack.set(other, object);
      var skipCtor = isPartial;
      while (++index < objLength) {
        key = objProps[index];
        var objValue = object[key], othValue = other[key];
        if (customizer) {
          var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
        }
        if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
          result = false;
          break;
        }
        skipCtor || (skipCtor = key == "constructor");
      }
      if (result && !skipCtor) {
        var objCtor = object.constructor, othCtor = other.constructor;
        if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
          result = false;
        }
      }
      stack["delete"](object);
      stack["delete"](other);
      return result;
    }
    var DataView = getNative(root, "DataView");
    var Promise$1 = getNative(root, "Promise");
    var Set$1 = getNative(root, "Set");
    var WeakMap = getNative(root, "WeakMap");
    var mapTag$1 = "[object Map]", objectTag$1 = "[object Object]", promiseTag = "[object Promise]", setTag$1 = "[object Set]", weakMapTag = "[object WeakMap]";
    var dataViewTag = "[object DataView]";
    var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map$1), promiseCtorString = toSource(Promise$1), setCtorString = toSource(Set$1), weakMapCtorString = toSource(WeakMap);
    var getTag = baseGetTag;
    if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map$1 && getTag(new Map$1()) != mapTag$1 || Promise$1 && getTag(Promise$1.resolve()) != promiseTag || Set$1 && getTag(new Set$1()) != setTag$1 || WeakMap && getTag(new WeakMap()) != weakMapTag) {
      getTag = function(value) {
        var result = baseGetTag(value), Ctor = result == objectTag$1 ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : "";
        if (ctorString) {
          switch (ctorString) {
            case dataViewCtorString:
              return dataViewTag;
            case mapCtorString:
              return mapTag$1;
            case promiseCtorString:
              return promiseTag;
            case setCtorString:
              return setTag$1;
            case weakMapCtorString:
              return weakMapTag;
          }
        }
        return result;
      };
    }
    var COMPARE_PARTIAL_FLAG$2 = 1;
    var argsTag = "[object Arguments]", arrayTag = "[object Array]", objectTag = "[object Object]";
    var objectProto$1 = Object.prototype;
    var hasOwnProperty$1 = objectProto$1.hasOwnProperty;
    function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
      var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other);
      objTag = objTag == argsTag ? objectTag : objTag;
      othTag = othTag == argsTag ? objectTag : othTag;
      var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag;
      if (isSameTag && isBuffer(object)) {
        if (!isBuffer(other)) {
          return false;
        }
        objIsArr = true;
        objIsObj = false;
      }
      if (isSameTag && !objIsObj) {
        stack || (stack = new Stack());
        return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
      }
      if (!(bitmask & COMPARE_PARTIAL_FLAG$2)) {
        var objIsWrapped = objIsObj && hasOwnProperty$1.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty$1.call(other, "__wrapped__");
        if (objIsWrapped || othIsWrapped) {
          var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
          stack || (stack = new Stack());
          return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
        }
      }
      if (!isSameTag) {
        return false;
      }
      stack || (stack = new Stack());
      return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
    }
    function baseIsEqual(value, other, bitmask, customizer, stack) {
      if (value === other) {
        return true;
      }
      if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) {
        return value !== value && other !== other;
      }
      return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
    }
    var COMPARE_PARTIAL_FLAG$1 = 1, COMPARE_UNORDERED_FLAG$1 = 2;
    function baseIsMatch(object, source, matchData, customizer) {
      var index = matchData.length, length = index;
      if (object == null) {
        return !length;
      }
      object = Object(object);
      while (index--) {
        var data = matchData[index];
        if (data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
          return false;
        }
      }
      while (++index < length) {
        data = matchData[index];
        var key = data[0], objValue = object[key], srcValue = data[1];
        if (data[2]) {
          if (objValue === void 0 && !(key in object)) {
            return false;
          }
        } else {
          var stack = new Stack();
          var result;
          if (!(result === void 0 ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$1 | COMPARE_UNORDERED_FLAG$1, customizer, stack) : result)) {
            return false;
          }
        }
      }
      return true;
    }
    function isStrictComparable(value) {
      return value === value && !isObject(value);
    }
    function getMatchData(object) {
      var result = keys(object), length = result.length;
      while (length--) {
        var key = result[length], value = object[key];
        result[length] = [key, value, isStrictComparable(value)];
      }
      return result;
    }
    function matchesStrictComparable(key, srcValue) {
      return function(object) {
        if (object == null) {
          return false;
        }
        return object[key] === srcValue && (srcValue !== void 0 || key in Object(object));
      };
    }
    function baseMatches(source) {
      var matchData = getMatchData(source);
      if (matchData.length == 1 && matchData[0][2]) {
        return matchesStrictComparable(matchData[0][0], matchData[0][1]);
      }
      return function(object) {
        return object === source || baseIsMatch(object, source, matchData);
      };
    }
    var symbolTag = "[object Symbol]";
    function isSymbol(value) {
      return typeof value == "symbol" || isObjectLike(value) && baseGetTag(value) == symbolTag;
    }
    var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/;
    function isKey(value, object) {
      if (isArray(value)) {
        return false;
      }
      var type = typeof value;
      if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol(value)) {
        return true;
      }
      return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object(object);
    }
    var FUNC_ERROR_TEXT = "Expected a function";
    function memoize(func, resolver) {
      if (typeof func != "function" || resolver != null && typeof resolver != "function") {
        throw new TypeError(FUNC_ERROR_TEXT);
      }
      var memoized = function() {
        var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
        if (cache.has(key)) {
          return cache.get(key);
        }
        var result = func.apply(this, args);
        memoized.cache = cache.set(key, result) || cache;
        return result;
      };
      memoized.cache = new (memoize.Cache || MapCache)();
      return memoized;
    }
    memoize.Cache = MapCache;
    var MAX_MEMOIZE_SIZE = 500;
    function memoizeCapped(func) {
      var result = memoize(func, function(key) {
        if (cache.size === MAX_MEMOIZE_SIZE) {
          cache.clear();
        }
        return key;
      });
      var cache = result.cache;
      return result;
    }
    var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
    var reEscapeChar = /\\(\\)?/g;
    var stringToPath = memoizeCapped(function(string) {
      var result = [];
      if (string.charCodeAt(0) === 46) {
        result.push("");
      }
      string.replace(rePropName, function(match, number, quote, subString) {
        result.push(quote ? subString.replace(reEscapeChar, "$1") : number || match);
      });
      return result;
    });
    var symbolProto = Symbol$1 ? Symbol$1.prototype : void 0, symbolToString = symbolProto ? symbolProto.toString : void 0;
    function baseToString(value) {
      if (typeof value == "string") {
        return value;
      }
      if (isArray(value)) {
        return arrayMap(value, baseToString) + "";
      }
      if (isSymbol(value)) {
        return symbolToString ? symbolToString.call(value) : "";
      }
      var result = value + "";
      return result == "0" && 1 / value == -Infinity ? "-0" : result;
    }
    function toString(value) {
      return value == null ? "" : baseToString(value);
    }
    function castPath(value, object) {
      if (isArray(value)) {
        return value;
      }
      return isKey(value, object) ? [value] : stringToPath(toString(value));
    }
    function toKey(value) {
      if (typeof value == "string" || isSymbol(value)) {
        return value;
      }
      var result = value + "";
      return result == "0" && 1 / value == -Infinity ? "-0" : result;
    }
    function baseGet(object, path) {
      path = castPath(path, object);
      var index = 0, length = path.length;
      while (object != null && index < length) {
        object = object[toKey(path[index++])];
      }
      return index && index == length ? object : void 0;
    }
    function get(object, path, defaultValue) {
      var result = object == null ? void 0 : baseGet(object, path);
      return result === void 0 ? defaultValue : result;
    }
    function baseHasIn(object, key) {
      return object != null && key in Object(object);
    }
    function hasPath(object, path, hasFunc) {
      path = castPath(path, object);
      var index = -1, length = path.length, result = false;
      while (++index < length) {
        var key = toKey(path[index]);
        if (!(result = object != null && hasFunc(object, key))) {
          break;
        }
        object = object[key];
      }
      if (result || ++index != length) {
        return result;
      }
      length = object == null ? 0 : object.length;
      return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object));
    }
    function hasIn(object, path) {
      return object != null && hasPath(object, path, baseHasIn);
    }
    var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2;
    function baseMatchesProperty(path, srcValue) {
      if (isKey(path) && isStrictComparable(srcValue)) {
        return matchesStrictComparable(toKey(path), srcValue);
      }
      return function(object) {
        var objValue = get(object, path);
        return objValue === void 0 && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
      };
    }
    function identity(value) {
      return value;
    }
    function baseProperty(key) {
      return function(object) {
        return object == null ? void 0 : object[key];
      };
    }
    function basePropertyDeep(path) {
      return function(object) {
        return baseGet(object, path);
      };
    }
    function property(path) {
      return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
    }
    function baseIteratee(value) {
      if (typeof value == "function") {
        return value;
      }
      if (value == null) {
        return identity;
      }
      if (typeof value == "object") {
        return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value);
      }
      return property(value);
    }
    function createBaseFor(fromRight) {
      return function(object, iteratee, keysFunc) {
        var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length;
        while (length--) {
          var key = props[++index];
          if (iteratee(iterable[key], key, iterable) === false) {
            break;
          }
        }
        return object;
      };
    }
    var baseFor = createBaseFor();
    function baseForOwn(object, iteratee) {
      return object && baseFor(object, iteratee, keys);
    }
    function createBaseEach(eachFunc, fromRight) {
      return function(collection, iteratee) {
        if (collection == null) {
          return collection;
        }
        if (!isArrayLike(collection)) {
          return eachFunc(collection, iteratee);
        }
        var length = collection.length, index = -1, iterable = Object(collection);
        while (++index < length) {
          if (iteratee(iterable[index], index, iterable) === false) {
            break;
          }
        }
        return collection;
      };
    }
    var baseEach = createBaseEach(baseForOwn);
    function baseMap(collection, iteratee) {
      var index = -1, result = isArrayLike(collection) ? Array(collection.length) : [];
      baseEach(collection, function(value, key, collection2) {
        result[++index] = iteratee(value, key, collection2);
      });
      return result;
    }
    function map(collection, iteratee) {
      var func = isArray(collection) ? arrayMap : baseMap;
      return func(collection, baseIteratee(iteratee));
    }
    function baseFilter(collection, predicate) {
      var result = [];
      baseEach(collection, function(value, index, collection2) {
        if (predicate(value, index, collection2)) {
          result.push(value);
        }
      });
      return result;
    }
    function filter(collection, predicate) {
      var func = isArray(collection) ? arrayFilter : baseFilter;
      return func(collection, baseIteratee(predicate));
    }
    function buildATNKey(rule, type, occurrence) {
      return `${rule.name}_${type}_${occurrence}`;
    }
    const ATN_BASIC = 1;
    const ATN_RULE_START = 2;
    const ATN_PLUS_BLOCK_START = 4;
    const ATN_STAR_BLOCK_START = 5;
    const ATN_RULE_STOP = 7;
    const ATN_BLOCK_END = 8;
    const ATN_STAR_LOOP_BACK = 9;
    const ATN_STAR_LOOP_ENTRY = 10;
    const ATN_PLUS_LOOP_BACK = 11;
    const ATN_LOOP_END = 12;
    class AbstractTransition {
      constructor(target) {
        this.target = target;
      }
      isEpsilon() {
        return false;
      }
    }
    class AtomTransition extends AbstractTransition {
      constructor(target, tokenType) {
        super(target);
        this.tokenType = tokenType;
      }
    }
    class EpsilonTransition extends AbstractTransition {
      constructor(target) {
        super(target);
      }
      isEpsilon() {
        return true;
      }
    }
    class RuleTransition extends AbstractTransition {
      constructor(ruleStart, rule, followState) {
        super(ruleStart);
        this.rule = rule;
        this.followState = followState;
      }
      isEpsilon() {
        return true;
      }
    }
    function createATN(rules) {
      const atn = {
        decisionMap: {},
        decisionStates: [],
        ruleToStartState: /* @__PURE__ */ new Map(),
        ruleToStopState: /* @__PURE__ */ new Map(),
        states: []
      };
      createRuleStartAndStopATNStates(atn, rules);
      const ruleLength = rules.length;
      for (let i = 0; i < ruleLength; i++) {
        const rule = rules[i];
        const ruleBlock = block(atn, rule, rule);
        if (ruleBlock === void 0) {
          continue;
        }
        buildRuleHandle(atn, rule, ruleBlock);
      }
      return atn;
    }
    function createRuleStartAndStopATNStates(atn, rules) {
      const ruleLength = rules.length;
      for (let i = 0; i < ruleLength; i++) {
        const rule = rules[i];
        const start = newState(atn, rule, void 0, {
          type: ATN_RULE_START
        });
        const stop = newState(atn, rule, void 0, {
          type: ATN_RULE_STOP
        });
        start.stop = stop;
        atn.ruleToStartState.set(rule, start);
        atn.ruleToStopState.set(rule, stop);
      }
    }
    function atom(atn, rule, production) {
      if (production instanceof Terminal) {
        return tokenRef(atn, rule, production.terminalType, production);
      } else if (production instanceof NonTerminal) {
        return ruleRef(atn, rule, production);
      } else if (production instanceof Alternation) {
        return alternation(atn, rule, production);
      } else if (production instanceof Option) {
        return option(atn, rule, production);
      } else if (production instanceof Repetition) {
        return repetition(atn, rule, production);
      } else if (production instanceof RepetitionWithSeparator) {
        return repetitionSep(atn, rule, production);
      } else if (production instanceof RepetitionMandatory) {
        return repetitionMandatory(atn, rule, production);
      } else if (production instanceof RepetitionMandatoryWithSeparator) {
        return repetitionMandatorySep(atn, rule, production);
      } else {
        return block(atn, rule, production);
      }
    }
    function repetition(atn, rule, repetition2) {
      const starState = newState(atn, rule, repetition2, {
        type: ATN_STAR_BLOCK_START
      });
      defineDecisionState(atn, starState);
      const handle = makeAlts(atn, rule, starState, repetition2, block(atn, rule, repetition2));
      return star(atn, rule, repetition2, handle);
    }
    function repetitionSep(atn, rule, repetition2) {
      const starState = newState(atn, rule, repetition2, {
        type: ATN_STAR_BLOCK_START
      });
      defineDecisionState(atn, starState);
      const handle = makeAlts(atn, rule, starState, repetition2, block(atn, rule, repetition2));
      const sep = tokenRef(atn, rule, repetition2.separator, repetition2);
      return star(atn, rule, repetition2, handle, sep);
    }
    function repetitionMandatory(atn, rule, repetition2) {
      const plusState = newState(atn, rule, repetition2, {
        type: ATN_PLUS_BLOCK_START
      });
      defineDecisionState(atn, plusState);
      const handle = makeAlts(atn, rule, plusState, repetition2, block(atn, rule, repetition2));
      return plus(atn, rule, repetition2, handle);
    }
    function repetitionMandatorySep(atn, rule, repetition2) {
      const plusState = newState(atn, rule, repetition2, {
        type: ATN_PLUS_BLOCK_START
      });
      defineDecisionState(atn, plusState);
      const handle = makeAlts(atn, rule, plusState, repetition2, block(atn, rule, repetition2));
      const sep = tokenRef(atn, rule, repetition2.separator, repetition2);
      return plus(atn, rule, repetition2, handle, sep);
    }
    function alternation(atn, rule, alternation2) {
      const start = newState(atn, rule, alternation2, {
        type: ATN_BASIC
      });
      defineDecisionState(atn, start);
      const alts = map(alternation2.definition, (e) => atom(atn, rule, e));
      const handle = makeAlts(atn, rule, start, alternation2, ...alts);
      return handle;
    }
    function option(atn, rule, option2) {
      const start = newState(atn, rule, option2, {
        type: ATN_BASIC
      });
      defineDecisionState(atn, start);
      const handle = makeAlts(atn, rule, start, option2, block(atn, rule, option2));
      return optional(atn, rule, option2, handle);
    }
    function block(atn, rule, block2) {
      const handles = filter(map(block2.definition, (e) => atom(atn, rule, e)), (e) => e !== void 0);
      if (handles.length === 1) {
        return handles[0];
      } else if (handles.length === 0) {
        return void 0;
      } else {
        return makeBlock(atn, handles);
      }
    }
    function plus(atn, rule, plus2, handle, sep) {
      const blkStart = handle.left;
      const blkEnd = handle.right;
      const loop = newState(atn, rule, plus2, {
        type: ATN_PLUS_LOOP_BACK
      });
      defineDecisionState(atn, loop);
      const end = newState(atn, rule, plus2, {
        type: ATN_LOOP_END
      });
      blkStart.loopback = loop;
      end.loopback = loop;
      atn.decisionMap[buildATNKey(rule, sep ? "RepetitionMandatoryWithSeparator" : "RepetitionMandatory", plus2.idx)] = loop;
      epsilon(blkEnd, loop);
      if (sep === void 0) {
        epsilon(loop, blkStart);
        epsilon(loop, end);
      } else {
        epsilon(loop, end);
        epsilon(loop, sep.left);
        epsilon(sep.right, blkStart);
      }
      return {
        left: blkStart,
        right: end
      };
    }
    function star(atn, rule, star2, handle, sep) {
      const start = handle.left;
      const end = handle.right;
      const entry = newState(atn, rule, star2, {
        type: ATN_STAR_LOOP_ENTRY
      });
      defineDecisionState(atn, entry);
      const loopEnd = newState(atn, rule, star2, {
        type: ATN_LOOP_END
      });
      const loop = newState(atn, rule, star2, {
        type: ATN_STAR_LOOP_BACK
      });
      entry.loopback = loop;
      loopEnd.loopback = loop;
      epsilon(entry, start);
      epsilon(entry, loopEnd);
      epsilon(end, loop);
      if (sep !== void 0) {
        epsilon(loop, loopEnd);
        epsilon(loop, sep.left);
        epsilon(sep.right, start);
      } else {
        epsilon(loop, entry);
      }
      atn.decisionMap[buildATNKey(rule, sep ? "RepetitionWithSeparator" : "Repetition", star2.idx)] = entry;
      return {
        left: entry,
        right: loopEnd
      };
    }
    function optional(atn, rule, optional2, handle) {
      const start = handle.left;
      const end = handle.right;
      epsilon(start, end);
      atn.decisionMap[buildATNKey(rule, "Option", optional2.idx)] = start;
      return handle;
    }
    function defineDecisionState(atn, state) {
      atn.decisionStates.push(state);
      state.decision = atn.decisionStates.length - 1;
      return state.decision;
    }
    function makeAlts(atn, rule, start, production, ...alts) {
      const end = newState(atn, rule, production, {
        type: ATN_BLOCK_END,
        start
      });
      start.end = end;
      for (const alt of alts) {
        if (alt !== void 0) {
          epsilon(start, alt.left);
          epsilon(alt.right, end);
        } else {
          epsilon(start, end);
        }
      }
      const handle = {
        left: start,
        right: end
      };
      atn.decisionMap[buildATNKey(rule, getProdType(production), production.idx)] = start;
      return handle;
    }
    function getProdType(production) {
      if (production instanceof Alternation) {
        return "Alternation";
      } else if (production instanceof Option) {
        return "Option";
      } else if (production instanceof Repetition) {
        return "Repetition";
      } else if (production instanceof RepetitionWithSeparator) {
        return "RepetitionWithSeparator";
      } else if (production instanceof RepetitionMandatory) {
        return "RepetitionMandatory";
      } else if (production instanceof RepetitionMandatoryWithSeparator) {
        return "RepetitionMandatoryWithSeparator";
      } else {
        throw new Error("Invalid production type encountered");
      }
    }
    function makeBlock(atn, alts) {
      const altsLength = alts.length;
      for (let i = 0; i < altsLength - 1; i++) {
        const handle = alts[i];
        let transition;
        if (handle.left.transitions.length === 1) {
          transition = handle.left.transitions[0];
        }
        const isRuleTransition = transition instanceof RuleTransition;
        const ruleTransition = transition;
        const next = alts[i + 1].left;
        if (handle.left.type === ATN_BASIC && handle.right.type === ATN_BASIC && transition !== void 0 && (isRuleTransition && ruleTransition.followState === handle.right || transition.target === handle.right)) {
          if (isRuleTransition) {
            ruleTransition.followState = next;
          } else {
            transition.target = next;
          }
          removeState(atn, handle.right);
        } else {
          epsilon(handle.right, next);
        }
      }
      const first2 = alts[0];
      const last = alts[altsLength - 1];
      return {
        left: first2.left,
        right: last.right
      };
    }
    function tokenRef(atn, rule, tokenType, production) {
      const left = newState(atn, rule, production, {
        type: ATN_BASIC
      });
      const right = newState(atn, rule, production, {
        type: ATN_BASIC
      });
      addTransition(left, new AtomTransition(right, tokenType));
      return {
        left,
        right
      };
    }
    function ruleRef(atn, currentRule, nonTerminal) {
      const rule = nonTerminal.referencedRule;
      const start = atn.ruleToStartState.get(rule);
      const left = newState(atn, currentRule, nonTerminal, {
        type: ATN_BASIC
      });
      const right = newState(atn, currentRule, nonTerminal, {
        type: ATN_BASIC
      });
      const call = new RuleTransition(start, rule, right);
      addTransition(left, call);
      return {
        left,
        right
      };
    }
    function buildRuleHandle(atn, rule, block2) {
      const start = atn.ruleToStartState.get(rule);
      epsilon(start, block2.left);
      const stop = atn.ruleToStopState.get(rule);
      epsilon(block2.right, stop);
      const handle = {
        left: start,
        right: stop
      };
      return handle;
    }
    function epsilon(a2, b) {
      const transition = new EpsilonTransition(b);
      addTransition(a2, transition);
    }
    function newState(atn, rule, production, partial) {
      const t = Object.assign({
        atn,
        production,
        epsilonOnlyTransitions: false,
        rule,
        transitions: [],
        nextTokenWithinRule: [],
        stateNumber: atn.states.length
      }, partial);
      atn.states.push(t);
      return t;
    }
    function addTransition(state, transition) {
      if (state.transitions.length === 0) {
        state.epsilonOnlyTransitions = transition.isEpsilon();
      }
      state.transitions.push(transition);
    }
    function removeState(atn, state) {
      atn.states.splice(atn.states.indexOf(state), 1);
    }
    const DFA_ERROR = {};
    class ATNConfigSet {
      constructor() {
        this.map = {};
        this.configs = [];
      }
      get size() {
        return this.configs.length;
      }
      finalize() {
        this.map = {};
      }
      add(config) {
        const key = getATNConfigKey(config);
        if (!(key in this.map)) {
          this.map[key] = this.configs.length;
          this.configs.push(config);
        }
      }
      get elements() {
        return this.configs;
      }
      get alts() {
        return map(this.configs, (e) => e.alt);
      }
      get key() {
        let value = "";
        for (const k in this.map) {
          value += k + ":";
        }
        return value;
      }
    }
    function getATNConfigKey(config, alt = true) {
      return `${alt ? `a${config.alt}` : ""}s${config.state.stateNumber}:${config.stack.map((e) => e.stateNumber.toString()).join("_")}`;
    }
    function baseExtremum(array, iteratee, comparator) {
      var index = -1, length = array.length;
      while (++index < length) {
        var value = array[index], current = iteratee(value);
        if (current != null && (computed === void 0 ? current === current && !isSymbol(current) : comparator(current, computed))) {
          var computed = current, result = value;
        }
      }
      return result;
    }
    function baseLt(value, other) {
      return value < other;
    }
    function min(array) {
      return array && array.length ? baseExtremum(array, identity, baseLt) : void 0;
    }
    var spreadableSymbol = Symbol$1 ? Symbol$1.isConcatSpreadable : void 0;
    function isFlattenable(value) {
      return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
    }
    function baseFlatten(array, depth, predicate, isStrict, result) {
      var index = -1, length = array.length;
      predicate || (predicate = isFlattenable);
      result || (result = []);
      while (++index < length) {
        var value = array[index];
        if (predicate(value)) {
          {
            arrayPush(result, value);
          }
        } else {
          result[result.length] = value;
        }
      }
      return result;
    }
    function flatMap(collection, iteratee) {
      return baseFlatten(map(collection, iteratee));
    }
    function baseFindIndex(array, predicate, fromIndex, fromRight) {
      var length = array.length, index = fromIndex + -1;
      while (++index < length) {
        if (predicate(array[index], index, array)) {
          return index;
        }
      }
      return -1;
    }
    function baseIsNaN(value) {
      return value !== value;
    }
    function strictIndexOf(array, value, fromIndex) {
      var index = fromIndex - 1, length = array.length;
      while (++index < length) {
        if (array[index] === value) {
          return index;
        }
      }
      return -1;
    }
    function baseIndexOf(array, value, fromIndex) {
      return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex);
    }
    function arrayIncludes(array, value) {
      var length = array == null ? 0 : array.length;
      return !!length && baseIndexOf(array, value, 0) > -1;
    }
    function noop() {
    }
    var INFINITY = 1 / 0;
    var createSet = !(Set$1 && 1 / setToArray(new Set$1([, -0]))[1] == INFINITY) ? noop : function(values) {
      return new Set$1(values);
    };
    var LARGE_ARRAY_SIZE = 200;
    function baseUniq(array, iteratee, comparator) {
      var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result;
      if (length >= LARGE_ARRAY_SIZE) {
        var set = iteratee ? null : createSet(array);
        if (set) {
          return setToArray(set);
        }
        isCommon = false;
        includes = cacheHas;
        seen = new SetCache();
      } else {
        seen = iteratee ? [] : result;
      }
      outer:
        while (++index < length) {
          var value = array[index], computed = iteratee ? iteratee(value) : value;
          value = value !== 0 ? value : 0;
          if (isCommon && computed === computed) {
            var seenIndex = seen.length;
            while (seenIndex--) {
              if (seen[seenIndex] === computed) {
                continue outer;
              }
            }
            if (iteratee) {
              seen.push(computed);
            }
            result.push(value);
          } else if (!includes(seen, computed, comparator)) {
            if (seen !== result) {
              seen.push(computed);
            }
            result.push(value);
          }
        }
      return result;
    }
    function uniqBy(array, iteratee) {
      return array && array.length ? baseUniq(array, baseIteratee(iteratee)) : [];
    }
    function flatten(array) {
      var length = array == null ? 0 : array.length;
      return length ? baseFlatten(array) : [];
    }
    function arrayEach(array, iteratee) {
      var index = -1, length = array == null ? 0 : array.length;
      while (++index < length) {
        if (iteratee(array[index], index, array) === false) {
          break;
        }
      }
      return array;
    }
    function castFunction(value) {
      return typeof value == "function" ? value : identity;
    }
    function forEach(collection, iteratee) {
      var func = isArray(collection) ? arrayEach : baseEach;
      return func(collection, castFunction(iteratee));
    }
    var mapTag = "[object Map]", setTag = "[object Set]";
    var objectProto = Object.prototype;
    var hasOwnProperty = objectProto.hasOwnProperty;
    function isEmpty(value) {
      if (value == null) {
        return true;
      }
      if (isArrayLike(value) && (isArray(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer(value) || isTypedArray(value) || isArguments(value))) {
        return !value.length;
      }
      var tag = getTag(value);
      if (tag == mapTag || tag == setTag) {
        return !value.size;
      }
      if (isPrototype(value)) {
        return !baseKeys(value).length;
      }
      for (var key in value) {
        if (hasOwnProperty.call(value, key)) {
          return false;
        }
      }
      return true;
    }
    function arrayReduce(array, iteratee, accumulator, initAccum) {
      var index = -1, length = array == null ? 0 : array.length;
      if (initAccum && length) {
        accumulator = array[++index];
      }
      while (++index < length) {
        accumulator = iteratee(accumulator, array[index], index, array);
      }
      return accumulator;
    }
    function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
      eachFunc(collection, function(value, index, collection2) {
        accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index, collection2);
      });
      return accumulator;
    }
    function reduce(collection, iteratee, accumulator) {
      var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3;
      return func(collection, baseIteratee(iteratee), accumulator, initAccum, baseEach);
    }
    function createDFACache(startState, decision) {
      const map2 = {};
      return (predicateSet) => {
        const key = predicateSet.toString();
        let existing = map2[key];
        if (existing !== void 0) {
          return existing;
        } else {
          existing = {
            atnStartState: startState,
            decision,
            states: {}
          };
          map2[key] = existing;
          return existing;
        }
      };
    }
    class PredicateSet {
      constructor() {
        this.predicates = [];
      }
      is(index) {
        return index >= this.predicates.length || this.predicates[index];
      }
      set(index, value) {
        this.predicates[index] = value;
      }
      toString() {
        let value = "";
        const size = this.predicates.length;
        for (let i = 0; i < size; i++) {
          value += this.predicates[i] === true ? "1" : "0";
        }
        return value;
      }
    }
    const EMPTY_PREDICATES = new PredicateSet();
    class LLStarLookaheadStrategy extends LLkLookaheadStrategy {
      constructor(options) {
        var _a, _b;
        super();
        this.logging = (_a = options === null || options === void 0 ? void 0 : options.logging) !== null && _a !== void 0 ? _a : ((message) => console.log(message));
        this.incomplete = (_b = options === null || options === void 0 ? void 0 : options.incomplete) !== null && _b !== void 0 ? _b : false;
      }
      initialize(options) {
        this.atn = createATN(options.rules);
        this.dfas = initATNSimulator(this.atn);
      }
      validateAmbiguousAlternationAlternatives() {
        return [];
      }
      validateEmptyOrAlternatives() {
        return [];
      }
      buildLookaheadForAlternation(options) {
        const { prodOccurrence, rule, hasPredicates, dynamicTokensEnabled } = options;
        const dfas = this.dfas;
        const logging = this.logging;
        const incomplete = this.incomplete;
        const key = buildATNKey(rule, "Alternation", prodOccurrence);
        const decisionState = this.atn.decisionMap[key];
        const decisionIndex = decisionState.decision;
        const partialAlts = map(getLookaheadPaths({
          maxLookahead: 1,
          occurrence: prodOccurrence,
          prodType: "Alternation",
          rule
        }), (currAlt) => map(currAlt, (path) => path[0]));
        if (isLL1Sequence(partialAlts, false) && !dynamicTokensEnabled) {
          const choiceToAlt = reduce(partialAlts, (result, currAlt, idx) => {
            forEach(currAlt, (currTokType) => {
              if (currTokType) {
                result[currTokType.tokenTypeIdx] = idx;
                forEach(currTokType.categoryMatches, (currExtendingType) => {
                  result[currExtendingType] = idx;
                });
              }
            });
            return result;
          }, {});
          if (hasPredicates) {
            return function(orAlts) {
              var _a;
              const nextToken = this.LA_FAST(1);
              const prediction = choiceToAlt[nextToken.tokenTypeIdx];
              if (orAlts !== void 0 && prediction !== void 0) {
                const gate = (_a = orAlts[prediction]) === null || _a === void 0 ? void 0 : _a.GATE;
                if (gate !== void 0 && gate.call(this) === false) {
                  return void 0;
                }
              }
              return prediction;
            };
          } else {
            return function() {
              const nextToken = this.LA_FAST(1);
              return choiceToAlt[nextToken.tokenTypeIdx];
            };
          }
        } else if (hasPredicates) {
          return function(orAlts) {
            const predicates = new PredicateSet();
            const length = orAlts === void 0 ? 0 : orAlts.length;
            for (let i = 0; i < length; i++) {
              const gate = orAlts === null || orAlts === void 0 ? void 0 : orAlts[i].GATE;
              predicates.set(i, gate === void 0 || gate.call(this));
            }
            const result = adaptivePredict.call(this, dfas, decisionIndex, predicates, logging, incomplete);
            return typeof result === "number" ? result : void 0;
          };
        } else {
          return function() {
            const result = adaptivePredict.call(this, dfas, decisionIndex, EMPTY_PREDICATES, logging, incomplete);
            return typeof result === "number" ? result : void 0;
          };
        }
      }
      buildLookaheadForOptional(options) {
        const { prodOccurrence, rule, prodType, dynamicTokensEnabled } = options;
        const dfas = this.dfas;
        const logging = this.logging;
        const incomplete = this.incomplete;
        const key = buildATNKey(rule, prodType, prodOccurrence);
        const decisionState = this.atn.decisionMap[key];
        const decisionIndex = decisionState.decision;
        const alts = map(getLookaheadPaths({
          maxLookahead: 1,
          occurrence: prodOccurrence,
          prodType,
          rule
        }), (e) => {
          return map(e, (g) => g[0]);
        });
        if (isLL1Sequence(alts) && alts[0][0] && !dynamicTokensEnabled) {
          const alt = alts[0];
          const singleTokensTypes = flatten(alt);
          if (singleTokensTypes.length === 1 && isEmpty(singleTokensTypes[0].categoryMatches)) {
            const expectedTokenType = singleTokensTypes[0];
            const expectedTokenUniqueKey = expectedTokenType.tokenTypeIdx;
            return function() {
              return this.LA_FAST(1).tokenTypeIdx === expectedTokenUniqueKey;
            };
          } else {
            const choiceToAlt = reduce(singleTokensTypes, (result, currTokType) => {
              if (currTokType !== void 0) {
                result[currTokType.tokenTypeIdx] = true;
                forEach(currTokType.categoryMatches, (currExtendingType) => {
                  result[currExtendingType] = true;
                });
              }
              return result;
            }, {});
            return function() {
              const nextToken = this.LA_FAST(1);
              return choiceToAlt[nextToken.tokenTypeIdx] === true;
            };
          }
        }
        return function() {
          const result = adaptivePredict.call(this, dfas, decisionIndex, EMPTY_PREDICATES, logging, incomplete);
          return typeof result === "object" ? false : result === 0;
        };
      }
    }
    function isLL1Sequence(sequences, allowEmpty = true) {
      const fullSet = /* @__PURE__ */ new Set();
      for (const alt of sequences) {
        const altSet = /* @__PURE__ */ new Set();
        for (const tokType of alt) {
          if (tokType === void 0) {
            if (allowEmpty) {
              break;
            } else {
              return false;
            }
          }
          const indices = [tokType.tokenTypeIdx].concat(tokType.categoryMatches);
          for (const index of indices) {
            if (fullSet.has(index)) {
              if (!altSet.has(index)) {
                return false;
              }
            } else {
              fullSet.add(index);
              altSet.add(index);
            }
          }
        }
      }
      return true;
    }
    function initATNSimulator(atn) {
      const decisionLength = atn.decisionStates.length;
      const decisionToDFA = Array(decisionLength);
      for (let i = 0; i < decisionLength; i++) {
        decisionToDFA[i] = createDFACache(atn.decisionStates[i], i);
      }
      return decisionToDFA;
    }
    function adaptivePredict(dfaCaches, decision, predicateSet, logging, incomplete) {
      const dfa = dfaCaches[decision](predicateSet);
      let start = dfa.start;
      if (start === void 0) {
        const closure2 = computeStartState(dfa.atnStartState);
        start = addDFAState(dfa, newDFAState(closure2));
        dfa.start = start;
      }
      const alt = performLookahead.apply(this, [dfa, start, predicateSet, logging, incomplete]);
      return alt;
    }
    function performLookahead(dfa, s0, predicateSet, logging, incomplete) {
      let previousD = s0;
      let i = 1;
      const path = [];
      let t = this.LA_FAST(i++);
      while (true) {
        let d = getExistingTargetState(previousD, t);
        if (d === void 0) {
          d = computeLookaheadTarget.apply(this, [dfa, previousD, t, i, predicateSet, logging]);
        }
        if (d === DFA_ERROR) {
          return buildAdaptivePredictError(path, previousD, t);
        }
        if (d.isAcceptState === true) {
          if (incomplete === true && tokenMatcher(t, EOF)) {
            const bestGuess = getBestGuess(previousD, predicateSet);
            if (bestGuess !== void 0) {
              return bestGuess;
            }
          }
          return d.prediction;
        }
        previousD = d;
        path.push(t);
        t = this.LA(i++);
      }
    }
    function computeLookaheadTarget(dfa, previousD, token, lookahead, predicateSet, logging) {
      const reach = computeReachSet(previousD.configs, token, predicateSet);
      if (reach.size === 0) {
        addDFAEdge(dfa, previousD, token, DFA_ERROR);
        return DFA_ERROR;
      }
      let newState2 = newDFAState(reach);
      const predictedAlt = getUniqueAlt(reach, predicateSet);
      if (predictedAlt !== void 0) {
        newState2.isAcceptState = true;
        newState2.prediction = predictedAlt;
        newState2.configs.uniqueAlt = predictedAlt;
      } else if (hasConflictTerminatingPrediction(reach)) {
        const prediction = min(reach.alts);
        newState2.isAcceptState = true;
        newState2.prediction = prediction;
        newState2.configs.uniqueAlt = prediction;
        reportLookaheadAmbiguity.apply(this, [dfa, lookahead, reach.alts, logging]);
      }
      newState2 = addDFAEdge(dfa, previousD, token, newState2);
      return newState2;
    }
    function reportLookaheadAmbiguity(dfa, lookahead, ambiguityIndices, logging) {
      const prefixPath = [];
      for (let i = 1; i <= lookahead; i++) {
        prefixPath.push(this.LA(i).tokenType);
      }
      const atnState = dfa.atnStartState;
      const topLevelRule = atnState.rule;
      const production = atnState.production;
      const message = buildAmbiguityError({
        topLevelRule,
        ambiguityIndices,
        production,
        prefixPath
      });
      logging(message);
    }
    function buildAmbiguityError(options) {
      const pathMsg = map(options.prefixPath, (currtok) => tokenLabel(currtok)).join(", ");
      const occurrence = options.production.idx === 0 ? "" : options.production.idx;
      let currMessage = `Ambiguous Alternatives Detected: <${options.ambiguityIndices.join(", ")}> in <${getProductionDslName(options.production)}${occurrence}> inside <${options.topLevelRule.name}> Rule,
<${pathMsg}> may appears as a prefix path in all these alternatives.
`;
      currMessage = currMessage + `See: https://chevrotain.io/docs/guide/resolving_grammar_errors.html#AMBIGUOUS_ALTERNATIVES
For Further details.`;
      return currMessage;
    }
    function getProductionDslName(prod) {
      if (prod instanceof NonTerminal) {
        return "SUBRULE";
      } else if (prod instanceof Option) {
        return "OPTION";
      } else if (prod instanceof Alternation) {
        return "OR";
      } else if (prod instanceof RepetitionMandatory) {
        return "AT_LEAST_ONE";
      } else if (prod instanceof RepetitionMandatoryWithSeparator) {
        return "AT_LEAST_ONE_SEP";
      } else if (prod instanceof RepetitionWithSeparator) {
        return "MANY_SEP";
      } else if (prod instanceof Repetition) {
        return "MANY";
      } else if (prod instanceof Terminal) {
        return "CONSUME";
      } else {
        throw Error("non exhaustive match");
      }
    }
    function buildAdaptivePredictError(path, previous, current) {
      const nextTransitions = flatMap(previous.configs.elements, (e) => e.state.transitions);
      const nextTokenTypes = uniqBy(nextTransitions.filter((e) => e instanceof AtomTransition).map((e) => e.tokenType), (e) => e.tokenTypeIdx);
      return {
        actualToken: current,
        possibleTokenTypes: nextTokenTypes,
        tokenPath: path
      };
    }
    function getExistingTargetState(state, token) {
      return state.edges[token.tokenTypeIdx];
    }
    function computeReachSet(configs, token, predicateSet) {
      const intermediate = new ATNConfigSet();
      const skippedStopStates = [];
      for (const c of configs.elements) {
        if (predicateSet.is(c.alt) === false) {
          continue;
        }
        if (c.state.type === ATN_RULE_STOP) {
          skippedStopStates.push(c);
          continue;
        }
        const transitionLength = c.state.transitions.length;
        for (let i = 0; i < transitionLength; i++) {
          const transition = c.state.transitions[i];
          const target = getReachableTarget(transition, token);
          if (target !== void 0) {
            intermediate.add({
              state: target,
              alt: c.alt,
              stack: c.stack
            });
          }
        }
      }
      let reach;
      if (skippedStopStates.length === 0 && intermediate.size === 1) {
        reach = intermediate;
      }
      if (reach === void 0) {
        reach = new ATNConfigSet();
        for (const c of intermediate.elements) {
          closure(c, reach);
        }
      }
      if (skippedStopStates.length > 0 && !hasConfigInRuleStopState(reach)) {
        for (const c of skippedStopStates) {
          reach.add(c);
        }
      }
      return reach;
    }
    function getReachableTarget(transition, token) {
      if (transition instanceof AtomTransition && tokenMatcher(token, transition.tokenType)) {
        return transition.target;
      }
      return void 0;
    }
    function getUniqueAlt(configs, predicateSet) {
      let alt;
      for (const c of configs.elements) {
        if (predicateSet.is(c.alt) === true) {
          if (alt === void 0) {
            alt = c.alt;
          } else if (alt !== c.alt) {
            return void 0;
          }
        }
      }
      return alt;
    }
    function newDFAState(closure2) {
      return {
        configs: closure2,
        edges: {},
        isAcceptState: false,
        prediction: -1
      };
    }
    function addDFAEdge(dfa, from, token, to) {
      to = addDFAState(dfa, to);
      from.edges[token.tokenTypeIdx] = to;
      return to;
    }
    function addDFAState(dfa, state) {
      if (state === DFA_ERROR) {
        return state;
      }
      const mapKey = state.configs.key;
      const existing = dfa.states[mapKey];
      if (existing !== void 0) {
        return existing;
      }
      state.configs.finalize();
      dfa.states[mapKey] = state;
      return state;
    }
    function computeStartState(atnState) {
      const configs = new ATNConfigSet();
      const numberOfTransitions = atnState.transitions.length;
      for (let i = 0; i < numberOfTransitions; i++) {
        const target = atnState.transitions[i].target;
        const config = {
          state: target,
          alt: i,
          stack: []
        };
        closure(config, configs);
      }
      return configs;
    }
    function closure(config, configs) {
      const p = config.state;
      if (p.type === ATN_RULE_STOP) {
        if (config.stack.length > 0) {
          const atnStack = [...config.stack];
          const followState = atnStack.pop();
          const followConfig = {
            state: followState,
            alt: config.alt,
            stack: atnStack
          };
          closure(followConfig, configs);
        } else {
          configs.add(config);
        }
        return;
      }
      if (!p.epsilonOnlyTransitions) {
        configs.add(config);
      }
      const transitionLength = p.transitions.length;
      for (let i = 0; i < transitionLength; i++) {
        const transition = p.transitions[i];
        const c = getEpsilonTarget(config, transition);
        if (c !== void 0) {
          closure(c, configs);
        }
      }
    }
    function getEpsilonTarget(config, transition) {
      if (transition instanceof EpsilonTransition) {
        return {
          state: transition.target,
          alt: config.alt,
          stack: config.stack
        };
      } else if (transition instanceof RuleTransition) {
        const stack = [...config.stack, transition.followState];
        return {
          state: transition.target,
          alt: config.alt,
          stack
        };
      }
      return void 0;
    }
    function hasConfigInRuleStopState(configs) {
      for (const c of configs.elements) {
        if (c.state.type === ATN_RULE_STOP) {
          return true;
        }
      }
      return false;
    }
    function allConfigsInRuleStopStates(configs) {
      for (const c of configs.elements) {
        if (c.state.type !== ATN_RULE_STOP) {
          return false;
        }
      }
      return true;
    }
    function hasConflictTerminatingPrediction(configs) {
      if (allConfigsInRuleStopStates(configs)) {
        return true;
      }
      const altSets = getConflictingAltSets(configs.elements);
      const heuristic = hasConflictingAltSet(altSets) && !hasStateAssociatedWithOneAlt(altSets);
      return heuristic;
    }
    function getConflictingAltSets(configs) {
      const configToAlts = /* @__PURE__ */ new Map();
      for (const c of configs) {
        const key = getATNConfigKey(c, false);
        let alts = configToAlts.get(key);
        if (alts === void 0) {
          alts = {};
          configToAlts.set(key, alts);
        }
        alts[c.alt] = true;
      }
      return configToAlts;
    }
    function hasConflictingAltSet(altSets) {
      for (const value of Array.from(altSets.values())) {
        if (Object.keys(value).length > 1) {
          return true;
        }
      }
      return false;
    }
    function hasStateAssociatedWithOneAlt(altSets) {
      for (const value of Array.from(altSets.values())) {
        if (Object.keys(value).length === 1) {
          return true;
        }
      }
      return false;
    }
    function getBestGuess(state, predicateSet) {
      let bestAlt = void 0;
      for (const c of state.configs.elements) {
        if (predicateSet.is(c.alt) === false || c.state.type === ATN_RULE_STOP) {
          continue;
        }
        if (bestAlt === void 0) {
          bestAlt = c.alt;
        } else if (bestAlt !== c.alt) {
          return void 0;
        }
      }
      return bestAlt;
    }
    var DocumentUri;
    (function(DocumentUri2) {
      function is2(value) {
        return typeof value === "string";
      }
      DocumentUri2.is = is2;
    })(DocumentUri || (DocumentUri = {}));
    var URI;
    (function(URI2) {
      function is2(value) {
        return typeof value === "string";
      }
      URI2.is = is2;
    })(URI || (URI = {}));
    var integer;
    (function(integer2) {
      integer2.MIN_VALUE = -2147483648;
      integer2.MAX_VALUE = 2147483647;
      function is2(value) {
        return typeof value === "number" && integer2.MIN_VALUE <= value && value <= integer2.MAX_VALUE;
      }
      integer2.is = is2;
    })(integer || (integer = {}));
    var uinteger;
    (function(uinteger2) {
      uinteger2.MIN_VALUE = 0;
      uinteger2.MAX_VALUE = 2147483647;
      function is2(value) {
        return typeof value === "number" && uinteger2.MIN_VALUE <= value && value <= uinteger2.MAX_VALUE;
      }
      uinteger2.is = is2;
    })(uinteger || (uinteger = {}));
    var Position;
    (function(Position2) {
      function create(line, character) {
        if (line === Number.MAX_VALUE) {
          line = uinteger.MAX_VALUE;
        }
        if (character === Number.MAX_VALUE) {
          character = uinteger.MAX_VALUE;
        }
        return { line, character };
      }
      Position2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.objectLiteral(candidate) && Is.uinteger(candidate.line) && Is.uinteger(candidate.character);
      }
      Position2.is = is2;
    })(Position || (Position = {}));
    var Range;
    (function(Range2) {
      function create(one, two, three, four) {
        if (Is.uinteger(one) && Is.uinteger(two) && Is.uinteger(three) && Is.uinteger(four)) {
          return { start: Position.create(one, two), end: Position.create(three, four) };
        } else if (Position.is(one) && Position.is(two)) {
          return { start: one, end: two };
        } else {
          throw new Error(`Range#create called with invalid arguments[${one}, ${two}, ${three}, ${four}]`);
        }
      }
      Range2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.objectLiteral(candidate) && Position.is(candidate.start) && Position.is(candidate.end);
      }
      Range2.is = is2;
    })(Range || (Range = {}));
    var Location;
    (function(Location2) {
      function create(uri, range) {
        return { uri, range };
      }
      Location2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.objectLiteral(candidate) && Range.is(candidate.range) && (Is.string(candidate.uri) || Is.undefined(candidate.uri));
      }
      Location2.is = is2;
    })(Location || (Location = {}));
    var LocationLink;
    (function(LocationLink2) {
      function create(targetUri, targetRange, targetSelectionRange, originSelectionRange) {
        return { targetUri, targetRange, targetSelectionRange, originSelectionRange };
      }
      LocationLink2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.objectLiteral(candidate) && Range.is(candidate.targetRange) && Is.string(candidate.targetUri) && Range.is(candidate.targetSelectionRange) && (Range.is(candidate.originSelectionRange) || Is.undefined(candidate.originSelectionRange));
      }
      LocationLink2.is = is2;
    })(LocationLink || (LocationLink = {}));
    var Color;
    (function(Color2) {
      function create(red, green, blue, alpha) {
        return {
          red,
          green,
          blue,
          alpha
        };
      }
      Color2.create = create;
      function is2(value) {
        const candidate = value;
        return Is.objectLiteral(candidate) && Is.numberRange(candidate.red, 0, 1) && Is.numberRange(candidate.green, 0, 1) && Is.numberRange(candidate.blue, 0, 1) && Is.numberRange(candidate.alpha, 0, 1);
      }
      Color2.is = is2;
    })(Color || (Color = {}));
    var ColorInformation;
    (function(ColorInformation2) {
      function create(range, color) {
        return {
          range,
          color
        };
      }
      ColorInformation2.create = create;
      function is2(value) {
        const candidate = value;
        return Is.objectLiteral(candidate) && Range.is(candidate.range) && Color.is(candidate.color);
      }
      ColorInformation2.is = is2;
    })(ColorInformation || (ColorInformation = {}));
    var ColorPresentation;
    (function(ColorPresentation2) {
      function create(label, textEdit, additionalTextEdits) {
        return {
          label,
          textEdit,
          additionalTextEdits
        };
      }
      ColorPresentation2.create = create;
      function is2(value) {
        const candidate = value;
        return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.undefined(candidate.textEdit) || TextEdit.is(candidate)) && (Is.undefined(candidate.additionalTextEdits) || Is.typedArray(candidate.additionalTextEdits, TextEdit.is));
      }
      ColorPresentation2.is = is2;
    })(ColorPresentation || (ColorPresentation = {}));
    var FoldingRangeKind;
    (function(FoldingRangeKind2) {
      FoldingRangeKind2.Comment = "comment";
      FoldingRangeKind2.Imports = "imports";
      FoldingRangeKind2.Region = "region";
    })(FoldingRangeKind || (FoldingRangeKind = {}));
    var FoldingRange;
    (function(FoldingRange2) {
      function create(startLine, endLine, startCharacter, endCharacter, kind, collapsedText) {
        const result = {
          startLine,
          endLine
        };
        if (Is.defined(startCharacter)) {
          result.startCharacter = startCharacter;
        }
        if (Is.defined(endCharacter)) {
          result.endCharacter = endCharacter;
        }
        if (Is.defined(kind)) {
          result.kind = kind;
        }
        if (Is.defined(collapsedText)) {
          result.collapsedText = collapsedText;
        }
        return result;
      }
      FoldingRange2.create = create;
      function is2(value) {
        const candidate = value;
        return Is.objectLiteral(candidate) && Is.uinteger(candidate.startLine) && Is.uinteger(candidate.startLine) && (Is.undefined(candidate.startCharacter) || Is.uinteger(candidate.startCharacter)) && (Is.undefined(candidate.endCharacter) || Is.uinteger(candidate.endCharacter)) && (Is.undefined(candidate.kind) || Is.string(candidate.kind));
      }
      FoldingRange2.is = is2;
    })(FoldingRange || (FoldingRange = {}));
    var DiagnosticRelatedInformation;
    (function(DiagnosticRelatedInformation2) {
      function create(location, message) {
        return {
          location,
          message
        };
      }
      DiagnosticRelatedInformation2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.defined(candidate) && Location.is(candidate.location) && Is.string(candidate.message);
      }
      DiagnosticRelatedInformation2.is = is2;
    })(DiagnosticRelatedInformation || (DiagnosticRelatedInformation = {}));
    var DiagnosticSeverity;
    (function(DiagnosticSeverity2) {
      DiagnosticSeverity2.Error = 1;
      DiagnosticSeverity2.Warning = 2;
      DiagnosticSeverity2.Information = 3;
      DiagnosticSeverity2.Hint = 4;
    })(DiagnosticSeverity || (DiagnosticSeverity = {}));
    var DiagnosticTag;
    (function(DiagnosticTag2) {
      DiagnosticTag2.Unnecessary = 1;
      DiagnosticTag2.Deprecated = 2;
    })(DiagnosticTag || (DiagnosticTag = {}));
    var CodeDescription;
    (function(CodeDescription2) {
      function is2(value) {
        const candidate = value;
        return Is.objectLiteral(candidate) && Is.string(candidate.href);
      }
      CodeDescription2.is = is2;
    })(CodeDescription || (CodeDescription = {}));
    var Diagnostic;
    (function(Diagnostic2) {
      function create(range, message, severity, code, source, relatedInformation) {
        let result = { range, message };
        if (Is.defined(severity)) {
          result.severity = severity;
        }
        if (Is.defined(code)) {
          result.code = code;
        }
        if (Is.defined(source)) {
          result.source = source;
        }
        if (Is.defined(relatedInformation)) {
          result.relatedInformation = relatedInformation;
        }
        return result;
      }
      Diagnostic2.create = create;
      function is2(value) {
        var _a;
        let candidate = value;
        return Is.defined(candidate) && Range.is(candidate.range) && Is.string(candidate.message) && (Is.number(candidate.severity) || Is.undefined(candidate.severity)) && (Is.integer(candidate.code) || Is.string(candidate.code) || Is.undefined(candidate.code)) && (Is.undefined(candidate.codeDescription) || Is.string((_a = candidate.codeDescription) === null || _a === void 0 ? void 0 : _a.href)) && (Is.string(candidate.source) || Is.undefined(candidate.source)) && (Is.undefined(candidate.relatedInformation) || Is.typedArray(candidate.relatedInformation, DiagnosticRelatedInformation.is));
      }
      Diagnostic2.is = is2;
    })(Diagnostic || (Diagnostic = {}));
    var Command;
    (function(Command2) {
      function create(title, command, ...args) {
        let result = { title, command };
        if (Is.defined(args) && args.length > 0) {
          result.arguments = args;
        }
        return result;
      }
      Command2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.defined(candidate) && Is.string(candidate.title) && Is.string(candidate.command);
      }
      Command2.is = is2;
    })(Command || (Command = {}));
    var TextEdit;
    (function(TextEdit2) {
      function replace(range, newText) {
        return { range, newText };
      }
      TextEdit2.replace = replace;
      function insert(position, newText) {
        return { range: { start: position, end: position }, newText };
      }
      TextEdit2.insert = insert;
      function del(range) {
        return { range, newText: "" };
      }
      TextEdit2.del = del;
      function is2(value) {
        const candidate = value;
        return Is.objectLiteral(candidate) && Is.string(candidate.newText) && Range.is(candidate.range);
      }
      TextEdit2.is = is2;
    })(TextEdit || (TextEdit = {}));
    var ChangeAnnotation;
    (function(ChangeAnnotation2) {
      function create(label, needsConfirmation, description) {
        const result = { label };
        if (needsConfirmation !== void 0) {
          result.needsConfirmation = needsConfirmation;
        }
        if (description !== void 0) {
          result.description = description;
        }
        return result;
      }
      ChangeAnnotation2.create = create;
      function is2(value) {
        const candidate = value;
        return Is.objectLiteral(candidate) && Is.string(candidate.label) && (Is.boolean(candidate.needsConfirmation) || candidate.needsConfirmation === void 0) && (Is.string(candidate.description) || candidate.description === void 0);
      }
      ChangeAnnotation2.is = is2;
    })(ChangeAnnotation || (ChangeAnnotation = {}));
    var ChangeAnnotationIdentifier;
    (function(ChangeAnnotationIdentifier2) {
      function is2(value) {
        const candidate = value;
        return Is.string(candidate);
      }
      ChangeAnnotationIdentifier2.is = is2;
    })(ChangeAnnotationIdentifier || (ChangeAnnotationIdentifier = {}));
    var AnnotatedTextEdit;
    (function(AnnotatedTextEdit2) {
      function replace(range, newText, annotation) {
        return { range, newText, annotationId: annotation };
      }
      AnnotatedTextEdit2.replace = replace;
      function insert(position, newText, annotation) {
        return { range: { start: position, end: position }, newText, annotationId: annotation };
      }
      AnnotatedTextEdit2.insert = insert;
      function del(range, annotation) {
        return { range, newText: "", annotationId: annotation };
      }
      AnnotatedTextEdit2.del = del;
      function is2(value) {
        const candidate = value;
        return TextEdit.is(candidate) && (ChangeAnnotation.is(candidate.annotationId) || ChangeAnnotationIdentifier.is(candidate.annotationId));
      }
      AnnotatedTextEdit2.is = is2;
    })(AnnotatedTextEdit || (AnnotatedTextEdit = {}));
    var TextDocumentEdit;
    (function(TextDocumentEdit2) {
      function create(textDocument, edits) {
        return { textDocument, edits };
      }
      TextDocumentEdit2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.defined(candidate) && OptionalVersionedTextDocumentIdentifier.is(candidate.textDocument) && Array.isArray(candidate.edits);
      }
      TextDocumentEdit2.is = is2;
    })(TextDocumentEdit || (TextDocumentEdit = {}));
    var CreateFile;
    (function(CreateFile2) {
      function create(uri, options, annotation) {
        let result = {
          kind: "create",
          uri
        };
        if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
          result.options = options;
        }
        if (annotation !== void 0) {
          result.annotationId = annotation;
        }
        return result;
      }
      CreateFile2.create = create;
      function is2(value) {
        let candidate = value;
        return candidate && candidate.kind === "create" && Is.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId));
      }
      CreateFile2.is = is2;
    })(CreateFile || (CreateFile = {}));
    var RenameFile;
    (function(RenameFile2) {
      function create(oldUri, newUri, options, annotation) {
        let result = {
          kind: "rename",
          oldUri,
          newUri
        };
        if (options !== void 0 && (options.overwrite !== void 0 || options.ignoreIfExists !== void 0)) {
          result.options = options;
        }
        if (annotation !== void 0) {
          result.annotationId = annotation;
        }
        return result;
      }
      RenameFile2.create = create;
      function is2(value) {
        let candidate = value;
        return candidate && candidate.kind === "rename" && Is.string(candidate.oldUri) && Is.string(candidate.newUri) && (candidate.options === void 0 || (candidate.options.overwrite === void 0 || Is.boolean(candidate.options.overwrite)) && (candidate.options.ignoreIfExists === void 0 || Is.boolean(candidate.options.ignoreIfExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId));
      }
      RenameFile2.is = is2;
    })(RenameFile || (RenameFile = {}));
    var DeleteFile;
    (function(DeleteFile2) {
      function create(uri, options, annotation) {
        let result = {
          kind: "delete",
          uri
        };
        if (options !== void 0 && (options.recursive !== void 0 || options.ignoreIfNotExists !== void 0)) {
          result.options = options;
        }
        if (annotation !== void 0) {
          result.annotationId = annotation;
        }
        return result;
      }
      DeleteFile2.create = create;
      function is2(value) {
        let candidate = value;
        return candidate && candidate.kind === "delete" && Is.string(candidate.uri) && (candidate.options === void 0 || (candidate.options.recursive === void 0 || Is.boolean(candidate.options.recursive)) && (candidate.options.ignoreIfNotExists === void 0 || Is.boolean(candidate.options.ignoreIfNotExists))) && (candidate.annotationId === void 0 || ChangeAnnotationIdentifier.is(candidate.annotationId));
      }
      DeleteFile2.is = is2;
    })(DeleteFile || (DeleteFile = {}));
    var WorkspaceEdit;
    (function(WorkspaceEdit2) {
      function is2(value) {
        let candidate = value;
        return candidate && (candidate.changes !== void 0 || candidate.documentChanges !== void 0) && (candidate.documentChanges === void 0 || candidate.documentChanges.every((change) => {
          if (Is.string(change.kind)) {
            return CreateFile.is(change) || RenameFile.is(change) || DeleteFile.is(change);
          } else {
            return TextDocumentEdit.is(change);
          }
        }));
      }
      WorkspaceEdit2.is = is2;
    })(WorkspaceEdit || (WorkspaceEdit = {}));
    var TextDocumentIdentifier;
    (function(TextDocumentIdentifier2) {
      function create(uri) {
        return { uri };
      }
      TextDocumentIdentifier2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.defined(candidate) && Is.string(candidate.uri);
      }
      TextDocumentIdentifier2.is = is2;
    })(TextDocumentIdentifier || (TextDocumentIdentifier = {}));
    var VersionedTextDocumentIdentifier;
    (function(VersionedTextDocumentIdentifier2) {
      function create(uri, version) {
        return { uri, version };
      }
      VersionedTextDocumentIdentifier2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.defined(candidate) && Is.string(candidate.uri) && Is.integer(candidate.version);
      }
      VersionedTextDocumentIdentifier2.is = is2;
    })(VersionedTextDocumentIdentifier || (VersionedTextDocumentIdentifier = {}));
    var OptionalVersionedTextDocumentIdentifier;
    (function(OptionalVersionedTextDocumentIdentifier2) {
      function create(uri, version) {
        return { uri, version };
      }
      OptionalVersionedTextDocumentIdentifier2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.defined(candidate) && Is.string(candidate.uri) && (candidate.version === null || Is.integer(candidate.version));
      }
      OptionalVersionedTextDocumentIdentifier2.is = is2;
    })(OptionalVersionedTextDocumentIdentifier || (OptionalVersionedTextDocumentIdentifier = {}));
    var TextDocumentItem;
    (function(TextDocumentItem2) {
      function create(uri, languageId, version, text) {
        return { uri, languageId, version, text };
      }
      TextDocumentItem2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.defined(candidate) && Is.string(candidate.uri) && Is.string(candidate.languageId) && Is.integer(candidate.version) && Is.string(candidate.text);
      }
      TextDocumentItem2.is = is2;
    })(TextDocumentItem || (TextDocumentItem = {}));
    var MarkupKind;
    (function(MarkupKind2) {
      MarkupKind2.PlainText = "plaintext";
      MarkupKind2.Markdown = "markdown";
      function is2(value) {
        const candidate = value;
        return candidate === MarkupKind2.PlainText || candidate === MarkupKind2.Markdown;
      }
      MarkupKind2.is = is2;
    })(MarkupKind || (MarkupKind = {}));
    var MarkupContent;
    (function(MarkupContent2) {
      function is2(value) {
        const candidate = value;
        return Is.objectLiteral(value) && MarkupKind.is(candidate.kind) && Is.string(candidate.value);
      }
      MarkupContent2.is = is2;
    })(MarkupContent || (MarkupContent = {}));
    var CompletionItemKind;
    (function(CompletionItemKind2) {
      CompletionItemKind2.Text = 1;
      CompletionItemKind2.Method = 2;
      CompletionItemKind2.Function = 3;
      CompletionItemKind2.Constructor = 4;
      CompletionItemKind2.Field = 5;
      CompletionItemKind2.Variable = 6;
      CompletionItemKind2.Class = 7;
      CompletionItemKind2.Interface = 8;
      CompletionItemKind2.Module = 9;
      CompletionItemKind2.Property = 10;
      CompletionItemKind2.Unit = 11;
      CompletionItemKind2.Value = 12;
      CompletionItemKind2.Enum = 13;
      CompletionItemKind2.Keyword = 14;
      CompletionItemKind2.Snippet = 15;
      CompletionItemKind2.Color = 16;
      CompletionItemKind2.File = 17;
      CompletionItemKind2.Reference = 18;
      CompletionItemKind2.Folder = 19;
      CompletionItemKind2.EnumMember = 20;
      CompletionItemKind2.Constant = 21;
      CompletionItemKind2.Struct = 22;
      CompletionItemKind2.Event = 23;
      CompletionItemKind2.Operator = 24;
      CompletionItemKind2.TypeParameter = 25;
    })(CompletionItemKind || (CompletionItemKind = {}));
    var InsertTextFormat;
    (function(InsertTextFormat2) {
      InsertTextFormat2.PlainText = 1;
      InsertTextFormat2.Snippet = 2;
    })(InsertTextFormat || (InsertTextFormat = {}));
    var CompletionItemTag;
    (function(CompletionItemTag2) {
      CompletionItemTag2.Deprecated = 1;
    })(CompletionItemTag || (CompletionItemTag = {}));
    var InsertReplaceEdit;
    (function(InsertReplaceEdit2) {
      function create(newText, insert, replace) {
        return { newText, insert, replace };
      }
      InsertReplaceEdit2.create = create;
      function is2(value) {
        const candidate = value;
        return candidate && Is.string(candidate.newText) && Range.is(candidate.insert) && Range.is(candidate.replace);
      }
      InsertReplaceEdit2.is = is2;
    })(InsertReplaceEdit || (InsertReplaceEdit = {}));
    var InsertTextMode;
    (function(InsertTextMode2) {
      InsertTextMode2.asIs = 1;
      InsertTextMode2.adjustIndentation = 2;
    })(InsertTextMode || (InsertTextMode = {}));
    var CompletionItemLabelDetails;
    (function(CompletionItemLabelDetails2) {
      function is2(value) {
        const candidate = value;
        return candidate && (Is.string(candidate.detail) || candidate.detail === void 0) && (Is.string(candidate.description) || candidate.description === void 0);
      }
      CompletionItemLabelDetails2.is = is2;
    })(CompletionItemLabelDetails || (CompletionItemLabelDetails = {}));
    var CompletionItem;
    (function(CompletionItem2) {
      function create(label) {
        return { label };
      }
      CompletionItem2.create = create;
    })(CompletionItem || (CompletionItem = {}));
    var CompletionList;
    (function(CompletionList2) {
      function create(items, isIncomplete) {
        return { items: items ? items : [], isIncomplete: !!isIncomplete };
      }
      CompletionList2.create = create;
    })(CompletionList || (CompletionList = {}));
    var MarkedString;
    (function(MarkedString2) {
      function fromPlainText(plainText) {
        return plainText.replace(/[\\`*_{}[\]()#+\-.!]/g, "\\$&");
      }
      MarkedString2.fromPlainText = fromPlainText;
      function is2(value) {
        const candidate = value;
        return Is.string(candidate) || Is.objectLiteral(candidate) && Is.string(candidate.language) && Is.string(candidate.value);
      }
      MarkedString2.is = is2;
    })(MarkedString || (MarkedString = {}));
    var Hover;
    (function(Hover2) {
      function is2(value) {
        let candidate = value;
        return !!candidate && Is.objectLiteral(candidate) && (MarkupContent.is(candidate.contents) || MarkedString.is(candidate.contents) || Is.typedArray(candidate.contents, MarkedString.is)) && (value.range === void 0 || Range.is(value.range));
      }
      Hover2.is = is2;
    })(Hover || (Hover = {}));
    var ParameterInformation;
    (function(ParameterInformation2) {
      function create(label, documentation) {
        return documentation ? { label, documentation } : { label };
      }
      ParameterInformation2.create = create;
    })(ParameterInformation || (ParameterInformation = {}));
    var SignatureInformation;
    (function(SignatureInformation2) {
      function create(label, documentation, ...parameters) {
        let result = { label };
        if (Is.defined(documentation)) {
          result.documentation = documentation;
        }
        if (Is.defined(parameters)) {
          result.parameters = parameters;
        } else {
          result.parameters = [];
        }
        return result;
      }
      SignatureInformation2.create = create;
    })(SignatureInformation || (SignatureInformation = {}));
    var DocumentHighlightKind;
    (function(DocumentHighlightKind2) {
      DocumentHighlightKind2.Text = 1;
      DocumentHighlightKind2.Read = 2;
      DocumentHighlightKind2.Write = 3;
    })(DocumentHighlightKind || (DocumentHighlightKind = {}));
    var DocumentHighlight;
    (function(DocumentHighlight2) {
      function create(range, kind) {
        let result = { range };
        if (Is.number(kind)) {
          result.kind = kind;
        }
        return result;
      }
      DocumentHighlight2.create = create;
    })(DocumentHighlight || (DocumentHighlight = {}));
    var SymbolKind;
    (function(SymbolKind2) {
      SymbolKind2.File = 1;
      SymbolKind2.Module = 2;
      SymbolKind2.Namespace = 3;
      SymbolKind2.Package = 4;
      SymbolKind2.Class = 5;
      SymbolKind2.Method = 6;
      SymbolKind2.Property = 7;
      SymbolKind2.Field = 8;
      SymbolKind2.Constructor = 9;
      SymbolKind2.Enum = 10;
      SymbolKind2.Interface = 11;
      SymbolKind2.Function = 12;
      SymbolKind2.Variable = 13;
      SymbolKind2.Constant = 14;
      SymbolKind2.String = 15;
      SymbolKind2.Number = 16;
      SymbolKind2.Boolean = 17;
      SymbolKind2.Array = 18;
      SymbolKind2.Object = 19;
      SymbolKind2.Key = 20;
      SymbolKind2.Null = 21;
      SymbolKind2.EnumMember = 22;
      SymbolKind2.Struct = 23;
      SymbolKind2.Event = 24;
      SymbolKind2.Operator = 25;
      SymbolKind2.TypeParameter = 26;
    })(SymbolKind || (SymbolKind = {}));
    var SymbolTag;
    (function(SymbolTag2) {
      SymbolTag2.Deprecated = 1;
    })(SymbolTag || (SymbolTag = {}));
    var SymbolInformation;
    (function(SymbolInformation2) {
      function create(name, kind, range, uri, containerName) {
        let result = {
          name,
          kind,
          location: { uri, range }
        };
        if (containerName) {
          result.containerName = containerName;
        }
        return result;
      }
      SymbolInformation2.create = create;
    })(SymbolInformation || (SymbolInformation = {}));
    var WorkspaceSymbol;
    (function(WorkspaceSymbol2) {
      function create(name, kind, uri, range) {
        return range !== void 0 ? { name, kind, location: { uri, range } } : { name, kind, location: { uri } };
      }
      WorkspaceSymbol2.create = create;
    })(WorkspaceSymbol || (WorkspaceSymbol = {}));
    var DocumentSymbol;
    (function(DocumentSymbol2) {
      function create(name, detail, kind, range, selectionRange, children) {
        let result = {
          name,
          detail,
          kind,
          range,
          selectionRange
        };
        if (children !== void 0) {
          result.children = children;
        }
        return result;
      }
      DocumentSymbol2.create = create;
      function is2(value) {
        let candidate = value;
        return candidate && Is.string(candidate.name) && Is.number(candidate.kind) && Range.is(candidate.range) && Range.is(candidate.selectionRange) && (candidate.detail === void 0 || Is.string(candidate.detail)) && (candidate.deprecated === void 0 || Is.boolean(candidate.deprecated)) && (candidate.children === void 0 || Array.isArray(candidate.children)) && (candidate.tags === void 0 || Array.isArray(candidate.tags));
      }
      DocumentSymbol2.is = is2;
    })(DocumentSymbol || (DocumentSymbol = {}));
    var CodeActionKind;
    (function(CodeActionKind2) {
      CodeActionKind2.Empty = "";
      CodeActionKind2.QuickFix = "quickfix";
      CodeActionKind2.Refactor = "refactor";
      CodeActionKind2.RefactorExtract = "refactor.extract";
      CodeActionKind2.RefactorInline = "refactor.inline";
      CodeActionKind2.RefactorRewrite = "refactor.rewrite";
      CodeActionKind2.Source = "source";
      CodeActionKind2.SourceOrganizeImports = "source.organizeImports";
      CodeActionKind2.SourceFixAll = "source.fixAll";
    })(CodeActionKind || (CodeActionKind = {}));
    var CodeActionTriggerKind;
    (function(CodeActionTriggerKind2) {
      CodeActionTriggerKind2.Invoked = 1;
      CodeActionTriggerKind2.Automatic = 2;
    })(CodeActionTriggerKind || (CodeActionTriggerKind = {}));
    var CodeActionContext;
    (function(CodeActionContext2) {
      function create(diagnostics, only, triggerKind) {
        let result = { diagnostics };
        if (only !== void 0 && only !== null) {
          result.only = only;
        }
        if (triggerKind !== void 0 && triggerKind !== null) {
          result.triggerKind = triggerKind;
        }
        return result;
      }
      CodeActionContext2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.defined(candidate) && Is.typedArray(candidate.diagnostics, Diagnostic.is) && (candidate.only === void 0 || Is.typedArray(candidate.only, Is.string)) && (candidate.triggerKind === void 0 || candidate.triggerKind === CodeActionTriggerKind.Invoked || candidate.triggerKind === CodeActionTriggerKind.Automatic);
      }
      CodeActionContext2.is = is2;
    })(CodeActionContext || (CodeActionContext = {}));
    var CodeAction;
    (function(CodeAction2) {
      function create(title, kindOrCommandOrEdit, kind) {
        let result = { title };
        let checkKind = true;
        if (typeof kindOrCommandOrEdit === "string") {
          checkKind = false;
          result.kind = kindOrCommandOrEdit;
        } else if (Command.is(kindOrCommandOrEdit)) {
          result.command = kindOrCommandOrEdit;
        } else {
          result.edit = kindOrCommandOrEdit;
        }
        if (checkKind && kind !== void 0) {
          result.kind = kind;
        }
        return result;
      }
      CodeAction2.create = create;
      function is2(value) {
        let candidate = value;
        return candidate && Is.string(candidate.title) && (candidate.diagnostics === void 0 || Is.typedArray(candidate.diagnostics, Diagnostic.is)) && (candidate.kind === void 0 || Is.string(candidate.kind)) && (candidate.edit !== void 0 || candidate.command !== void 0) && (candidate.command === void 0 || Command.is(candidate.command)) && (candidate.isPreferred === void 0 || Is.boolean(candidate.isPreferred)) && (candidate.edit === void 0 || WorkspaceEdit.is(candidate.edit));
      }
      CodeAction2.is = is2;
    })(CodeAction || (CodeAction = {}));
    var CodeLens;
    (function(CodeLens2) {
      function create(range, data) {
        let result = { range };
        if (Is.defined(data)) {
          result.data = data;
        }
        return result;
      }
      CodeLens2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.command) || Command.is(candidate.command));
      }
      CodeLens2.is = is2;
    })(CodeLens || (CodeLens = {}));
    var FormattingOptions;
    (function(FormattingOptions2) {
      function create(tabSize, insertSpaces) {
        return { tabSize, insertSpaces };
      }
      FormattingOptions2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.defined(candidate) && Is.uinteger(candidate.tabSize) && Is.boolean(candidate.insertSpaces);
      }
      FormattingOptions2.is = is2;
    })(FormattingOptions || (FormattingOptions = {}));
    var DocumentLink;
    (function(DocumentLink2) {
      function create(range, target, data) {
        return { range, target, data };
      }
      DocumentLink2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.defined(candidate) && Range.is(candidate.range) && (Is.undefined(candidate.target) || Is.string(candidate.target));
      }
      DocumentLink2.is = is2;
    })(DocumentLink || (DocumentLink = {}));
    var SelectionRange;
    (function(SelectionRange2) {
      function create(range, parent) {
        return { range, parent };
      }
      SelectionRange2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.objectLiteral(candidate) && Range.is(candidate.range) && (candidate.parent === void 0 || SelectionRange2.is(candidate.parent));
      }
      SelectionRange2.is = is2;
    })(SelectionRange || (SelectionRange = {}));
    var SemanticTokenTypes;
    (function(SemanticTokenTypes2) {
      SemanticTokenTypes2["namespace"] = "namespace";
      SemanticTokenTypes2["type"] = "type";
      SemanticTokenTypes2["class"] = "class";
      SemanticTokenTypes2["enum"] = "enum";
      SemanticTokenTypes2["interface"] = "interface";
      SemanticTokenTypes2["struct"] = "struct";
      SemanticTokenTypes2["typeParameter"] = "typeParameter";
      SemanticTokenTypes2["parameter"] = "parameter";
      SemanticTokenTypes2["variable"] = "variable";
      SemanticTokenTypes2["property"] = "property";
      SemanticTokenTypes2["enumMember"] = "enumMember";
      SemanticTokenTypes2["event"] = "event";
      SemanticTokenTypes2["function"] = "function";
      SemanticTokenTypes2["method"] = "method";
      SemanticTokenTypes2["macro"] = "macro";
      SemanticTokenTypes2["keyword"] = "keyword";
      SemanticTokenTypes2["modifier"] = "modifier";
      SemanticTokenTypes2["comment"] = "comment";
      SemanticTokenTypes2["string"] = "string";
      SemanticTokenTypes2["number"] = "number";
      SemanticTokenTypes2["regexp"] = "regexp";
      SemanticTokenTypes2["operator"] = "operator";
      SemanticTokenTypes2["decorator"] = "decorator";
    })(SemanticTokenTypes || (SemanticTokenTypes = {}));
    var SemanticTokenModifiers;
    (function(SemanticTokenModifiers2) {
      SemanticTokenModifiers2["declaration"] = "declaration";
      SemanticTokenModifiers2["definition"] = "definition";
      SemanticTokenModifiers2["readonly"] = "readonly";
      SemanticTokenModifiers2["static"] = "static";
      SemanticTokenModifiers2["deprecated"] = "deprecated";
      SemanticTokenModifiers2["abstract"] = "abstract";
      SemanticTokenModifiers2["async"] = "async";
      SemanticTokenModifiers2["modification"] = "modification";
      SemanticTokenModifiers2["documentation"] = "documentation";
      SemanticTokenModifiers2["defaultLibrary"] = "defaultLibrary";
    })(SemanticTokenModifiers || (SemanticTokenModifiers = {}));
    var SemanticTokens;
    (function(SemanticTokens2) {
      function is2(value) {
        const candidate = value;
        return Is.objectLiteral(candidate) && (candidate.resultId === void 0 || typeof candidate.resultId === "string") && Array.isArray(candidate.data) && (candidate.data.length === 0 || typeof candidate.data[0] === "number");
      }
      SemanticTokens2.is = is2;
    })(SemanticTokens || (SemanticTokens = {}));
    var InlineValueText;
    (function(InlineValueText2) {
      function create(range, text) {
        return { range, text };
      }
      InlineValueText2.create = create;
      function is2(value) {
        const candidate = value;
        return candidate !== void 0 && candidate !== null && Range.is(candidate.range) && Is.string(candidate.text);
      }
      InlineValueText2.is = is2;
    })(InlineValueText || (InlineValueText = {}));
    var InlineValueVariableLookup;
    (function(InlineValueVariableLookup2) {
      function create(range, variableName, caseSensitiveLookup) {
        return { range, variableName, caseSensitiveLookup };
      }
      InlineValueVariableLookup2.create = create;
      function is2(value) {
        const candidate = value;
        return candidate !== void 0 && candidate !== null && Range.is(candidate.range) && Is.boolean(candidate.caseSensitiveLookup) && (Is.string(candidate.variableName) || candidate.variableName === void 0);
      }
      InlineValueVariableLookup2.is = is2;
    })(InlineValueVariableLookup || (InlineValueVariableLookup = {}));
    var InlineValueEvaluatableExpression;
    (function(InlineValueEvaluatableExpression2) {
      function create(range, expression) {
        return { range, expression };
      }
      InlineValueEvaluatableExpression2.create = create;
      function is2(value) {
        const candidate = value;
        return candidate !== void 0 && candidate !== null && Range.is(candidate.range) && (Is.string(candidate.expression) || candidate.expression === void 0);
      }
      InlineValueEvaluatableExpression2.is = is2;
    })(InlineValueEvaluatableExpression || (InlineValueEvaluatableExpression = {}));
    var InlineValueContext;
    (function(InlineValueContext2) {
      function create(frameId, stoppedLocation) {
        return { frameId, stoppedLocation };
      }
      InlineValueContext2.create = create;
      function is2(value) {
        const candidate = value;
        return Is.defined(candidate) && Range.is(value.stoppedLocation);
      }
      InlineValueContext2.is = is2;
    })(InlineValueContext || (InlineValueContext = {}));
    var InlayHintKind;
    (function(InlayHintKind2) {
      InlayHintKind2.Type = 1;
      InlayHintKind2.Parameter = 2;
      function is2(value) {
        return value === 1 || value === 2;
      }
      InlayHintKind2.is = is2;
    })(InlayHintKind || (InlayHintKind = {}));
    var InlayHintLabelPart;
    (function(InlayHintLabelPart2) {
      function create(value) {
        return { value };
      }
      InlayHintLabelPart2.create = create;
      function is2(value) {
        const candidate = value;
        return Is.objectLiteral(candidate) && (candidate.tooltip === void 0 || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.location === void 0 || Location.is(candidate.location)) && (candidate.command === void 0 || Command.is(candidate.command));
      }
      InlayHintLabelPart2.is = is2;
    })(InlayHintLabelPart || (InlayHintLabelPart = {}));
    var InlayHint;
    (function(InlayHint2) {
      function create(position, label, kind) {
        const result = { position, label };
        if (kind !== void 0) {
          result.kind = kind;
        }
        return result;
      }
      InlayHint2.create = create;
      function is2(value) {
        const candidate = value;
        return Is.objectLiteral(candidate) && Position.is(candidate.position) && (Is.string(candidate.label) || Is.typedArray(candidate.label, InlayHintLabelPart.is)) && (candidate.kind === void 0 || InlayHintKind.is(candidate.kind)) && candidate.textEdits === void 0 || Is.typedArray(candidate.textEdits, TextEdit.is) && (candidate.tooltip === void 0 || Is.string(candidate.tooltip) || MarkupContent.is(candidate.tooltip)) && (candidate.paddingLeft === void 0 || Is.boolean(candidate.paddingLeft)) && (candidate.paddingRight === void 0 || Is.boolean(candidate.paddingRight));
      }
      InlayHint2.is = is2;
    })(InlayHint || (InlayHint = {}));
    var StringValue;
    (function(StringValue2) {
      function createSnippet(value) {
        return { kind: "snippet", value };
      }
      StringValue2.createSnippet = createSnippet;
    })(StringValue || (StringValue = {}));
    var InlineCompletionItem;
    (function(InlineCompletionItem2) {
      function create(insertText, filterText, range, command) {
        return { insertText, filterText, range, command };
      }
      InlineCompletionItem2.create = create;
    })(InlineCompletionItem || (InlineCompletionItem = {}));
    var InlineCompletionList;
    (function(InlineCompletionList2) {
      function create(items) {
        return { items };
      }
      InlineCompletionList2.create = create;
    })(InlineCompletionList || (InlineCompletionList = {}));
    var InlineCompletionTriggerKind;
    (function(InlineCompletionTriggerKind2) {
      InlineCompletionTriggerKind2.Invoked = 0;
      InlineCompletionTriggerKind2.Automatic = 1;
    })(InlineCompletionTriggerKind || (InlineCompletionTriggerKind = {}));
    var SelectedCompletionInfo;
    (function(SelectedCompletionInfo2) {
      function create(range, text) {
        return { range, text };
      }
      SelectedCompletionInfo2.create = create;
    })(SelectedCompletionInfo || (SelectedCompletionInfo = {}));
    var InlineCompletionContext;
    (function(InlineCompletionContext2) {
      function create(triggerKind, selectedCompletionInfo) {
        return { triggerKind, selectedCompletionInfo };
      }
      InlineCompletionContext2.create = create;
    })(InlineCompletionContext || (InlineCompletionContext = {}));
    var WorkspaceFolder;
    (function(WorkspaceFolder2) {
      function is2(value) {
        const candidate = value;
        return Is.objectLiteral(candidate) && URI.is(candidate.uri) && Is.string(candidate.name);
      }
      WorkspaceFolder2.is = is2;
    })(WorkspaceFolder || (WorkspaceFolder = {}));
    var TextDocument$1;
    (function(TextDocument2) {
      function create(uri, languageId, version, content) {
        return new FullTextDocument$1(uri, languageId, version, content);
      }
      TextDocument2.create = create;
      function is2(value) {
        let candidate = value;
        return Is.defined(candidate) && Is.string(candidate.uri) && (Is.undefined(candidate.languageId) || Is.string(candidate.languageId)) && Is.uinteger(candidate.lineCount) && Is.func(candidate.getText) && Is.func(candidate.positionAt) && Is.func(candidate.offsetAt) ? true : false;
      }
      TextDocument2.is = is2;
      function applyEdits(document, edits) {
        let text = document.getText();
        let sortedEdits = mergeSort2(edits, (a2, b) => {
          let diff = a2.range.start.line - b.range.start.line;
          if (diff === 0) {
            return a2.range.start.character - b.range.start.character;
          }
          return diff;
        });
        let lastModifiedOffset = text.length;
        for (let i = sortedEdits.length - 1; i >= 0; i--) {
          let e = sortedEdits[i];
          let startOffset = document.offsetAt(e.range.start);
          let endOffset = document.offsetAt(e.range.end);
          if (endOffset <= lastModifiedOffset) {
            text = text.substring(0, startOffset) + e.newText + text.substring(endOffset, text.length);
          } else {
            throw new Error("Overlapping edit");
          }
          lastModifiedOffset = startOffset;
        }
        return text;
      }
      TextDocument2.applyEdits = applyEdits;
      function mergeSort2(data, compare) {
        if (data.length <= 1) {
          return data;
        }
        const p = data.length / 2 | 0;
        const left = data.slice(0, p);
        const right = data.slice(p);
        mergeSort2(left, compare);
        mergeSort2(right, compare);
        let leftIdx = 0;
        let rightIdx = 0;
        let i = 0;
        while (leftIdx < left.length && rightIdx < right.length) {
          let ret = compare(left[leftIdx], right[rightIdx]);
          if (ret <= 0) {
            data[i++] = left[leftIdx++];
          } else {
            data[i++] = right[rightIdx++];
          }
        }
        while (leftIdx < left.length) {
          data[i++] = left[leftIdx++];
        }
        while (rightIdx < right.length) {
          data[i++] = right[rightIdx++];
        }
        return data;
      }
    })(TextDocument$1 || (TextDocument$1 = {}));
    let FullTextDocument$1 = class FullTextDocument {
      constructor(uri, languageId, version, content) {
        this._uri = uri;
        this._languageId = languageId;
        this._version = version;
        this._content = content;
        this._lineOffsets = void 0;
      }
      get uri() {
        return this._uri;
      }
      get languageId() {
        return this._languageId;
      }
      get version() {
        return this._version;
      }
      getText(range) {
        if (range) {
          let start = this.offsetAt(range.start);
          let end = this.offsetAt(range.end);
          return this._content.substring(start, end);
        }
        return this._content;
      }
      update(event, version) {
        this._content = event.text;
        this._version = version;
        this._lineOffsets = void 0;
      }
      getLineOffsets() {
        if (this._lineOffsets === void 0) {
          let lineOffsets = [];
          let text = this._content;
          let isLineStart = true;
          for (let i = 0; i < text.length; i++) {
            if (isLineStart) {
              lineOffsets.push(i);
              isLineStart = false;
            }
            let ch = text.charAt(i);
            isLineStart = ch === "\r" || ch === "\n";
            if (ch === "\r" && i + 1 < text.length && text.charAt(i + 1) === "\n") {
              i++;
            }
          }
          if (isLineStart && text.length > 0) {
            lineOffsets.push(text.length);
          }
          this._lineOffsets = lineOffsets;
        }
        return this._lineOffsets;
      }
      positionAt(offset) {
        offset = Math.max(Math.min(offset, this._content.length), 0);
        let lineOffsets = this.getLineOffsets();
        let low = 0, high = lineOffsets.length;
        if (high === 0) {
          return Position.create(0, offset);
        }
        while (low < high) {
          let mid = Math.floor((low + high) / 2);
          if (lineOffsets[mid] > offset) {
            high = mid;
          } else {
            low = mid + 1;
          }
        }
        let line = low - 1;
        return Position.create(line, offset - lineOffsets[line]);
      }
      offsetAt(position) {
        let lineOffsets = this.getLineOffsets();
        if (position.line >= lineOffsets.length) {
          return this._content.length;
        } else if (position.line < 0) {
          return 0;
        }
        let lineOffset = lineOffsets[position.line];
        let nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length;
        return Math.max(Math.min(lineOffset + position.character, nextLineOffset), lineOffset);
      }
      get lineCount() {
        return this.getLineOffsets().length;
      }
    };
    var Is;
    (function(Is2) {
      const toString2 = Object.prototype.toString;
      function defined(value) {
        return typeof value !== "undefined";
      }
      Is2.defined = defined;
      function undefined$1(value) {
        return typeof value === "undefined";
      }
      Is2.undefined = undefined$1;
      function boolean(value) {
        return value === true || value === false;
      }
      Is2.boolean = boolean;
      function string(value) {
        return toString2.call(value) === "[object String]";
      }
      Is2.string = string;
      function number(value) {
        return toString2.call(value) === "[object Number]";
      }
      Is2.number = number;
      function numberRange(value, min2, max) {
        return toString2.call(value) === "[object Number]" && min2 <= value && value <= max;
      }
      Is2.numberRange = numberRange;
      function integer2(value) {
        return toString2.call(value) === "[object Number]" && -2147483648 <= value && value <= 2147483647;
      }
      Is2.integer = integer2;
      function uinteger2(value) {
        return toString2.call(value) === "[object Number]" && 0 <= value && value <= 2147483647;
      }
      Is2.uinteger = uinteger2;
      function func(value) {
        return toString2.call(value) === "[object Function]";
      }
      Is2.func = func;
      function objectLiteral(value) {
        return value !== null && typeof value === "object";
      }
      Is2.objectLiteral = objectLiteral;
      function typedArray(value, check) {
        return Array.isArray(value) && value.every(check);
      }
      Is2.typedArray = typedArray;
    })(Is || (Is = {}));
    class CstNodeBuilder {
      constructor() {
        this.nodeStack = [];
      }
      get current() {
        return this.nodeStack[this.nodeStack.length - 1] ?? this.rootNode;
      }
      buildRootNode(input) {
        this.rootNode = new RootCstNodeImpl(input);
        this.rootNode.root = this.rootNode;
        this.nodeStack = [this.rootNode];
        return this.rootNode;
      }
      buildCompositeNode(feature) {
        const compositeNode = new CompositeCstNodeImpl();
        compositeNode.grammarSource = feature;
        compositeNode.root = this.rootNode;
        this.current.content.push(compositeNode);
        this.nodeStack.push(compositeNode);
        return compositeNode;
      }
      buildLeafNode(token, feature) {
        const leafNode = new LeafCstNodeImpl(token.startOffset, token.image.length, tokenToRange(token), token.tokenType, !feature);
        leafNode.grammarSource = feature;
        leafNode.root = this.rootNode;
        this.current.content.push(leafNode);
        return leafNode;
      }
      removeNode(node2) {
        const parent = node2.container;
        if (parent) {
          const index = parent.content.indexOf(node2);
          if (index >= 0) {
            parent.content.splice(index, 1);
          }
        }
      }
      addHiddenNodes(tokens2) {
        const nodes = [];
        for (const token of tokens2) {
          const leafNode = new LeafCstNodeImpl(token.startOffset, token.image.length, tokenToRange(token), token.tokenType, true);
          leafNode.root = this.rootNode;
          nodes.push(leafNode);
        }
        let current = this.current;
        let added = false;
        if (current.content.length > 0) {
          current.content.push(...nodes);
          return;
        }
        while (current.container) {
          const index = current.container.content.indexOf(current);
          if (index > 0) {
            current.container.content.splice(index, 0, ...nodes);
            added = true;
            break;
          }
          current = current.container;
        }
        if (!added) {
          this.rootNode.content.unshift(...nodes);
        }
      }
      construct(item) {
        const current = this.current;
        if (typeof item.$type === "string" && !item.$infixName) {
          this.current.astNode = item;
        }
        item.$cstNode = current;
        const node2 = this.nodeStack.pop();
        if (node2?.content.length === 0) {
          this.removeNode(node2);
        }
      }
    }
    class AbstractCstNode {
      get hidden() {
        return false;
      }
      get astNode() {
        const node2 = typeof this._astNode?.$type === "string" ? this._astNode : this.container?.astNode;
        if (!node2) {
          throw new Error("This node has no associated AST element");
        }
        return node2;
      }
      set astNode(value) {
        this._astNode = value;
      }
      get text() {
        return this.root.fullText.substring(this.offset, this.end);
      }
    }
    class LeafCstNodeImpl extends AbstractCstNode {
      get offset() {
        return this._offset;
      }
      get length() {
        return this._length;
      }
      get end() {
        return this._offset + this._length;
      }
      get hidden() {
        return this._hidden;
      }
      get tokenType() {
        return this._tokenType;
      }
      get range() {
        return this._range;
      }
      constructor(offset, length, range, tokenType, hidden = false) {
        super();
        this._hidden = hidden;
        this._offset = offset;
        this._tokenType = tokenType;
        this._length = length;
        this._range = range;
      }
    }
    class CompositeCstNodeImpl extends AbstractCstNode {
      constructor() {
        super(...arguments);
        this.content = new CstNodeContainer(this);
      }
      get offset() {
        return this.firstNonHiddenNode?.offset ?? 0;
      }
      get length() {
        return this.end - this.offset;
      }
      get end() {
        return this.lastNonHiddenNode?.end ?? 0;
      }
      get range() {
        const firstNode = this.firstNonHiddenNode;
        const lastNode = this.lastNonHiddenNode;
        if (firstNode && lastNode) {
          if (this._rangeCache === void 0) {
            const { range: firstRange } = firstNode;
            const { range: lastRange } = lastNode;
            this._rangeCache = { start: firstRange.start, end: lastRange.end.line < firstRange.start.line ? firstRange.start : lastRange.end };
          }
          return this._rangeCache;
        } else {
          return { start: Position.create(0, 0), end: Position.create(0, 0) };
        }
      }
      get firstNonHiddenNode() {
        for (const child of this.content) {
          if (!child.hidden) {
            return child;
          }
        }
        return this.content[0];
      }
      get lastNonHiddenNode() {
        for (let i = this.content.length - 1; i >= 0; i--) {
          const child = this.content[i];
          if (!child.hidden) {
            return child;
          }
        }
        return this.content[this.content.length - 1];
      }
    }
    class CstNodeContainer extends Array {
      constructor(parent) {
        super();
        this.parent = parent;
        Object.setPrototypeOf(this, CstNodeContainer.prototype);
      }
      push(...items) {
        this.addParents(items);
        return super.push(...items);
      }
      unshift(...items) {
        this.addParents(items);
        return super.unshift(...items);
      }
      splice(start, count, ...items) {
        this.addParents(items);
        return super.splice(start, count, ...items);
      }
      addParents(items) {
        for (const item of items) {
          item.container = this.parent;
        }
      }
    }
    class RootCstNodeImpl extends CompositeCstNodeImpl {
      get text() {
        return this._text.substring(this.offset, this.end);
      }
      get fullText() {
        return this._text;
      }
      constructor(input) {
        super();
        this._text = "";
        this._text = input ?? "";
      }
    }
    const DatatypeSymbol = Symbol("Datatype");
    function isDataTypeNode(node2) {
      return node2.$type === DatatypeSymbol;
    }
    const ruleSuffix = "​";
    const withRuleSuffix = (name) => name.endsWith(ruleSuffix) ? name : name + ruleSuffix;
    class AbstractLangiumParser {
      constructor(services, incomplete) {
        this._unorderedGroups = /* @__PURE__ */ new Map();
        this.allRules = /* @__PURE__ */ new Map();
        this.lexer = services.parser.Lexer;
        const tokens2 = this.lexer.definition;
        const production = services.LanguageMetaData.mode === "production";
        if (services.shared.profilers.LangiumProfiler?.isActive("parsing")) {
          this.wrapper = new ProfilerWrapper(tokens2, {
            ...services.parser.ParserConfig,
            skipValidations: production,
            errorMessageProvider: services.parser.ParserErrorMessageProvider
          }, incomplete, services.shared.profilers.LangiumProfiler.createTask("parsing", services.LanguageMetaData.languageId));
        } else {
          this.wrapper = new ChevrotainWrapper(tokens2, {
            ...services.parser.ParserConfig,
            skipValidations: production,
            errorMessageProvider: services.parser.ParserErrorMessageProvider
          }, incomplete);
        }
      }
      alternatives(idx, choices) {
        this.wrapper.wrapOr(idx, choices);
      }
      optional(idx, callback) {
        this.wrapper.wrapOption(idx, callback);
      }
      many(idx, callback) {
        this.wrapper.wrapMany(idx, callback);
      }
      atLeastOne(idx, callback) {
        this.wrapper.wrapAtLeastOne(idx, callback);
      }
      getRule(name) {
        return this.allRules.get(name);
      }
      isRecording() {
        return this.wrapper.IS_RECORDING;
      }
      get unorderedGroups() {
        return this._unorderedGroups;
      }
      getRuleStack() {
        return this.wrapper.RULE_STACK;
      }
      finalize() {
        this.wrapper.wrapSelfAnalysis();
      }
    }
    class LangiumParser extends AbstractLangiumParser {
      get current() {
        return this.stack[this.stack.length - 1];
      }
      constructor(services) {
        super(services, false);
        this.nodeBuilder = new CstNodeBuilder();
        this.stack = [];
        this.assignmentMap = /* @__PURE__ */ new Map();
        this.operatorPrecedence = /* @__PURE__ */ new Map();
        this.linker = services.references.Linker;
        this.converter = services.parser.ValueConverter;
        this.astReflection = services.shared.AstReflection;
      }
      rule(rule, impl) {
        const type = this.computeRuleType(rule);
        let infixName = void 0;
        if (isInfixRule(rule)) {
          infixName = rule.name;
          this.registerPrecedenceMap(rule);
        }
        const ruleMethod = this.wrapper.DEFINE_RULE(withRuleSuffix(rule.name), this.startImplementation(type, infixName, impl).bind(this));
        this.allRules.set(rule.name, ruleMethod);
        if (isParserRule(rule) && rule.entry) {
          this.mainRule = ruleMethod;
        }
        return ruleMethod;
      }
      registerPrecedenceMap(rule) {
        const name = rule.name;
        const map2 = /* @__PURE__ */ new Map();
        for (let i = 0; i < rule.operators.precedences.length; i++) {
          const precedence = rule.operators.precedences[i];
          for (const keyword of precedence.operators) {
            map2.set(keyword.value, {
              precedence: i,
              rightAssoc: precedence.associativity === "right"
            });
          }
        }
        this.operatorPrecedence.set(name, map2);
      }
      computeRuleType(rule) {
        if (isInfixRule(rule)) {
          return getTypeName(rule);
        } else if (rule.fragment) {
          return void 0;
        } else if (isDataTypeRule(rule)) {
          return DatatypeSymbol;
        } else {
          return getTypeName(rule);
        }
      }
      parse(input, options = {}) {
        this.nodeBuilder.buildRootNode(input);
        const lexerResult = this.lexerResult = this.lexer.tokenize(input);
        this.wrapper.input = lexerResult.tokens;
        const ruleMethod = options.rule ? this.allRules.get(options.rule) : this.mainRule;
        if (!ruleMethod) {
          throw new Error(options.rule ? `No rule found with name '${options.rule}'` : "No main rule available.");
        }
        const result = this.doParse(ruleMethod);
        this.nodeBuilder.addHiddenNodes(lexerResult.hidden);
        this.unorderedGroups.clear();
        this.lexerResult = void 0;
        linkContentToContainer(result, { deep: true });
        return {
          value: result,
          lexerErrors: lexerResult.errors,
          lexerReport: lexerResult.report,
          parserErrors: this.wrapper.errors
        };
      }
      doParse(rule) {
        let result = this.wrapper.rule(rule);
        if (this.stack.length > 0) {
          result = this.construct();
        }
        if (result === void 0) {
          throw new Error("No result from parser");
        } else if (this.stack.length > 0) {
          throw new Error("Parser stack is not empty after parsing");
        }
        return result;
      }
      startImplementation($type, infixName, implementation) {
        return (args) => {
          const createNode = !this.isRecording() && $type !== void 0;
          if (createNode) {
            const node2 = { $type };
            this.stack.push(node2);
            if ($type === DatatypeSymbol) {
              node2.value = "";
            } else if (infixName !== void 0) {
              node2.$infixName = infixName;
            }
          }
          implementation(args);
          return createNode ? this.construct() : void 0;
        };
      }
      extractHiddenTokens(token) {
        const hiddenTokens = this.lexerResult.hidden;
        if (!hiddenTokens.length) {
          return [];
        }
        const offset = token.startOffset;
        for (let i = 0; i < hiddenTokens.length; i++) {
          const token2 = hiddenTokens[i];
          if (token2.startOffset > offset) {
            return hiddenTokens.splice(0, i);
          }
        }
        return hiddenTokens.splice(0, hiddenTokens.length);
      }
      consume(idx, tokenType, feature) {
        const token = this.wrapper.wrapConsume(idx, tokenType);
        if (!this.isRecording() && this.isValidToken(token)) {
          const hiddenTokens = this.extractHiddenTokens(token);
          this.nodeBuilder.addHiddenNodes(hiddenTokens);
          const leafNode = this.nodeBuilder.buildLeafNode(token, feature);
          const { assignment, crossRef } = this.getAssignment(feature);
          const current = this.current;
          if (assignment) {
            const convertedValue = isKeyword(feature) ? token.image : this.converter.convert(token.image, leafNode);
            this.assign(assignment.operator, assignment.feature, convertedValue, leafNode, crossRef);
          } else if (isDataTypeNode(current)) {
            let text = token.image;
            if (!isKeyword(feature)) {
              text = this.converter.convert(text, leafNode).toString();
            }
            current.value += text;
          }
        }
      }
      /**
       * Most consumed parser tokens are valid. However there are two cases in which they are not valid:
       *
       * 1. They were inserted during error recovery by the parser. These tokens don't really exist and should not be further processed
       * 2. They contain invalid token ranges. This might include the special EOF token, or other tokens produced by invalid token builders.
       */
      isValidToken(token) {
        return !token.isInsertedInRecovery && !isNaN(token.startOffset) && typeof token.endOffset === "number" && !isNaN(token.endOffset);
      }
      subrule(idx, rule, fragment, feature, args) {
        let cstNode;
        if (!this.isRecording() && !fragment) {
          cstNode = this.nodeBuilder.buildCompositeNode(feature);
        }
        let result;
        try {
          result = this.wrapper.wrapSubrule(idx, rule, args);
        } finally {
          if (!this.isRecording()) {
            if (result === void 0 && !fragment) {
              result = this.construct();
            }
            if (result !== void 0 && cstNode && cstNode.length > 0) {
              this.performSubruleAssignment(result, feature, cstNode);
            }
          }
        }
      }
      performSubruleAssignment(result, feature, cstNode) {
        const { assignment, crossRef } = this.getAssignment(feature);
        if (assignment) {
          this.assign(assignment.operator, assignment.feature, result, cstNode, crossRef);
        } else if (!assignment) {
          const current = this.current;
          if (isDataTypeNode(current)) {
            current.value += result.toString();
          } else if (typeof result === "object" && result) {
            const object = this.assignWithoutOverride(result, current);
            const newItem = object;
            this.stack.pop();
            this.stack.push(newItem);
          }
        }
      }
      action($type, action) {
        if (!this.isRecording()) {
          let last = this.current;
          if (action.feature && action.operator) {
            last = this.construct();
            this.nodeBuilder.removeNode(last.$cstNode);
            const node2 = this.nodeBuilder.buildCompositeNode(action);
            node2.content.push(last.$cstNode);
            const newItem = { $type };
            this.stack.push(newItem);
            this.assign(action.operator, action.feature, last, last.$cstNode);
          } else {
            last.$type = $type;
          }
        }
      }
      construct() {
        if (this.isRecording()) {
          return void 0;
        }
        const obj = this.stack.pop();
        this.nodeBuilder.construct(obj);
        if ("$infixName" in obj) {
          return this.constructInfix(obj, this.operatorPrecedence.get(obj.$infixName));
        } else if (isDataTypeNode(obj)) {
          return this.converter.convert(obj.value, obj.$cstNode);
        } else {
          assignMandatoryProperties(this.astReflection, obj);
        }
        return obj;
      }
      constructInfix(obj, precedence) {
        const parts = obj.parts;
        if (!Array.isArray(parts) || parts.length === 0) {
          return void 0;
        }
        const operators = obj.operators;
        if (!Array.isArray(operators) || parts.length < 2) {
          return parts[0];
        }
        let lowestPrecedenceIdx = 0;
        let lowestPrecedenceValue = -1;
        for (let i = 0; i < operators.length; i++) {
          const operator = operators[i];
          const opPrecedence = precedence.get(operator) ?? {
            precedence: Infinity,
            rightAssoc: false
          };
          if (opPrecedence.precedence > lowestPrecedenceValue) {
            lowestPrecedenceValue = opPrecedence.precedence;
            lowestPrecedenceIdx = i;
          } else if (opPrecedence.precedence === lowestPrecedenceValue) {
            if (!opPrecedence.rightAssoc) {
              lowestPrecedenceIdx = i;
            }
          }
        }
        const leftOperators = operators.slice(0, lowestPrecedenceIdx);
        const rightOperators = operators.slice(lowestPrecedenceIdx + 1);
        const leftParts = parts.slice(0, lowestPrecedenceIdx + 1);
        const rightParts = parts.slice(lowestPrecedenceIdx + 1);
        const leftInfix = {
          $infixName: obj.$infixName,
          $type: obj.$type,
          $cstNode: obj.$cstNode,
          parts: leftParts,
          operators: leftOperators
        };
        const rightInfix = {
          $infixName: obj.$infixName,
          $type: obj.$type,
          $cstNode: obj.$cstNode,
          parts: rightParts,
          operators: rightOperators
        };
        const leftTree = this.constructInfix(leftInfix, precedence);
        const rightTree = this.constructInfix(rightInfix, precedence);
        return {
          $type: obj.$type,
          $cstNode: obj.$cstNode,
          left: leftTree,
          operator: operators[lowestPrecedenceIdx],
          right: rightTree
        };
      }
      getAssignment(feature) {
        if (!this.assignmentMap.has(feature)) {
          const assignment = getContainerOfType(feature, isAssignment);
          this.assignmentMap.set(feature, {
            assignment,
            crossRef: assignment && isCrossReference(assignment.terminal) ? assignment.terminal.isMulti ? "multi" : "single" : void 0
          });
        }
        return this.assignmentMap.get(feature);
      }
      assign(operator, feature, value, cstNode, crossRef) {
        const obj = this.current;
        let item;
        if (crossRef === "single" && typeof value === "string") {
          item = this.linker.buildReference(obj, feature, cstNode, value);
        } else if (crossRef === "multi" && typeof value === "string") {
          item = this.linker.buildMultiReference(obj, feature, cstNode, value);
        } else {
          item = value;
        }
        switch (operator) {
          case "=": {
            obj[feature] = item;
            break;
          }
          case "?=": {
            obj[feature] = true;
            break;
          }
          case "+=": {
            if (!Array.isArray(obj[feature])) {
              obj[feature] = [];
            }
            obj[feature].push(item);
          }
        }
      }
      assignWithoutOverride(target, source) {
        for (const [name, existingValue] of Object.entries(source)) {
          const newValue = target[name];
          if (newValue === void 0) {
            target[name] = existingValue;
          } else if (Array.isArray(newValue) && Array.isArray(existingValue)) {
            existingValue.push(...newValue);
            target[name] = existingValue;
          }
        }
        const targetCstNode = target.$cstNode;
        if (targetCstNode) {
          targetCstNode.astNode = void 0;
          target.$cstNode = void 0;
        }
        return target;
      }
      get definitionErrors() {
        return this.wrapper.definitionErrors;
      }
    }
    class AbstractParserErrorMessageProvider {
      buildMismatchTokenMessage(options) {
        return defaultParserErrorProvider.buildMismatchTokenMessage(options);
      }
      buildNotAllInputParsedMessage(options) {
        return defaultParserErrorProvider.buildNotAllInputParsedMessage(options);
      }
      buildNoViableAltMessage(options) {
        return defaultParserErrorProvider.buildNoViableAltMessage(options);
      }
      buildEarlyExitMessage(options) {
        return defaultParserErrorProvider.buildEarlyExitMessage(options);
      }
    }
    class LangiumParserErrorMessageProvider extends AbstractParserErrorMessageProvider {
      buildMismatchTokenMessage({ expected, actual }) {
        const expectedMsg = expected.LABEL ? "`" + expected.LABEL + "`" : expected.name.endsWith(":KW") ? `keyword '${expected.name.substring(0, expected.name.length - 3)}'` : `token of type '${expected.name}'`;
        return `Expecting ${expectedMsg} but found \`${actual.image}\`.`;
      }
      buildNotAllInputParsedMessage({ firstRedundant }) {
        return `Expecting end of file but found \`${firstRedundant.image}\`.`;
      }
    }
    class LangiumCompletionParser extends AbstractLangiumParser {
      constructor(services) {
        super(services, true);
        this.tokens = [];
        this.elementStack = [];
        this.lastElementStack = [];
        this.nextTokenIndex = 0;
        this.stackSize = 0;
      }
      action() {
      }
      construct() {
        return void 0;
      }
      parse(input) {
        this.resetState();
        const tokens2 = this.lexer.tokenize(input, { mode: "partial" });
        this.tokens = tokens2.tokens;
        this.wrapper.input = [...this.tokens];
        this.mainRule.call(this.wrapper, {});
        this.unorderedGroups.clear();
        return {
          tokens: this.tokens,
          elementStack: [...this.lastElementStack],
          tokenIndex: this.nextTokenIndex
        };
      }
      rule(rule, impl) {
        const ruleMethod = this.wrapper.DEFINE_RULE(withRuleSuffix(rule.name), this.startImplementation(impl).bind(this));
        this.allRules.set(rule.name, ruleMethod);
        if (rule.entry) {
          this.mainRule = ruleMethod;
        }
        return ruleMethod;
      }
      resetState() {
        this.elementStack = [];
        this.lastElementStack = [];
        this.nextTokenIndex = 0;
        this.stackSize = 0;
      }
      startImplementation(implementation) {
        return (args) => {
          const size = this.keepStackSize();
          try {
            implementation(args);
          } finally {
            this.resetStackSize(size);
          }
        };
      }
      removeUnexpectedElements() {
        this.elementStack.splice(this.stackSize);
      }
      keepStackSize() {
        const size = this.elementStack.length;
        this.stackSize = size;
        return size;
      }
      resetStackSize(size) {
        this.removeUnexpectedElements();
        this.stackSize = size;
      }
      consume(idx, tokenType, feature) {
        this.wrapper.wrapConsume(idx, tokenType);
        if (!this.isRecording()) {
          this.lastElementStack = [...this.elementStack, feature];
          this.nextTokenIndex = this.currIdx + 1;
        }
      }
      subrule(idx, rule, fragment, feature, args) {
        this.before(feature);
        this.wrapper.wrapSubrule(idx, rule, args);
        this.after(feature);
      }
      before(element) {
        if (!this.isRecording()) {
          this.elementStack.push(element);
        }
      }
      after(element) {
        if (!this.isRecording()) {
          const index = this.elementStack.lastIndexOf(element);
          if (index >= 0) {
            this.elementStack.splice(index);
          }
        }
      }
      get currIdx() {
        return this.wrapper.currIdx;
      }
    }
    const defaultConfig = {
      recoveryEnabled: true,
      nodeLocationTracking: "full",
      skipValidations: true,
      errorMessageProvider: new LangiumParserErrorMessageProvider()
    };
    class ChevrotainWrapper extends EmbeddedActionsParser {
      constructor(tokens2, config, incomplete) {
        const useDefaultLookahead = config && "maxLookahead" in config;
        super(tokens2, {
          ...defaultConfig,
          lookaheadStrategy: useDefaultLookahead ? new LLkLookaheadStrategy({ maxLookahead: config.maxLookahead }) : new LLStarLookaheadStrategy({
            // If validations are skipped, don't log the lookahead warnings
            logging: config.skipValidations ? () => {
            } : void 0,
            incomplete
          }),
          ...config
        });
      }
      get IS_RECORDING() {
        return this.RECORDING_PHASE;
      }
      DEFINE_RULE(name, impl, config) {
        return this.RULE(name, impl, config);
      }
      wrapSelfAnalysis() {
        this.performSelfAnalysis();
      }
      wrapConsume(idx, tokenType) {
        return this.consume(idx, tokenType, void 0);
      }
      wrapSubrule(idx, rule, args) {
        return this.subrule(idx, rule, {
          ARGS: [args]
        });
      }
      wrapOr(idx, choices) {
        this.or(idx, choices);
      }
      wrapOption(idx, callback) {
        this.option(idx, callback);
      }
      wrapMany(idx, callback) {
        this.many(idx, callback);
      }
      wrapAtLeastOne(idx, callback) {
        this.atLeastOne(idx, callback);
      }
      rule(rule) {
        return rule.call(this, {});
      }
    }
    class ProfilerWrapper extends ChevrotainWrapper {
      constructor(tokens2, config, incomplete, task) {
        super(tokens2, config, incomplete);
        this.task = task;
      }
      rule(rule) {
        this.task.start();
        this.task.startSubTask(this.ruleName(rule));
        try {
          return super.rule(rule);
        } finally {
          this.task.stopSubTask(this.ruleName(rule));
          this.task.stop();
        }
      }
      ruleName(rule) {
        return rule.ruleName;
      }
      subrule(idx, ruleToCall, options) {
        this.task.startSubTask(this.ruleName(ruleToCall));
        try {
          return super.subrule(idx, ruleToCall, options);
        } finally {
          this.task.stopSubTask(this.ruleName(ruleToCall));
        }
      }
    }
    function createParser(grammar, parser, tokens2) {
      const parserContext = {
        parser,
        tokens: tokens2,
        ruleNames: /* @__PURE__ */ new Map()
      };
      buildRules(parserContext, grammar);
      return parser;
    }
    function buildRules(parserContext, grammar) {
      const reachable = getAllReachableRules(grammar, false);
      const parserRules = stream(grammar.rules).filter(isParserRule).filter((rule) => reachable.has(rule));
      for (const rule of parserRules) {
        const ctx = {
          ...parserContext,
          consume: 1,
          optional: 1,
          subrule: 1,
          many: 1,
          or: 1
        };
        parserContext.parser.rule(rule, buildElement(ctx, rule.definition));
      }
      const infixRules = stream(grammar.rules).filter(isInfixRule).filter((rule) => reachable.has(rule));
      for (const rule of infixRules) {
        parserContext.parser.rule(rule, buildInfixRule(parserContext, rule));
      }
    }
    function buildInfixRule(ctx, rule) {
      const expressionRule = rule.call.rule.ref;
      if (!expressionRule) {
        throw new Error("Could not resolve reference to infix operator rule: " + rule.call.rule.$refText);
      }
      if (isTerminalRule(expressionRule)) {
        throw new Error("Cannot use terminal rule in infix expression");
      }
      const allKeywords = rule.operators.precedences.flatMap((e) => e.operators);
      const outerGroup = {
        $type: "Group",
        elements: []
      };
      const part1Assignment = {
        $container: outerGroup,
        $type: "Assignment",
        feature: "parts",
        operator: "+=",
        terminal: rule.call
      };
      const innerGroup = {
        $container: outerGroup,
        $type: "Group",
        elements: [],
        cardinality: "*"
      };
      outerGroup.elements.push(part1Assignment, innerGroup);
      const alternatives = {
        $type: "Alternatives",
        elements: allKeywords
      };
      const operatorAssignment = {
        $container: innerGroup,
        $type: "Assignment",
        feature: "operators",
        operator: "+=",
        terminal: alternatives
      };
      const part2Assignment = {
        ...part1Assignment,
        $container: innerGroup
      };
      innerGroup.elements.push(operatorAssignment, part2Assignment);
      const tokens2 = allKeywords.map((e) => ctx.tokens[e.value]);
      const orAlts = tokens2.map((token, index) => ({
        ALT: () => ctx.parser.consume(index, token, operatorAssignment)
      }));
      let subrule;
      return (args) => {
        subrule ?? (subrule = getRule(ctx, expressionRule));
        ctx.parser.subrule(0, subrule, false, part1Assignment, args);
        ctx.parser.many(0, {
          DEF: () => {
            ctx.parser.alternatives(0, orAlts);
            ctx.parser.subrule(1, subrule, false, part2Assignment, args);
          }
        });
      };
    }
    function buildElement(ctx, element, ignoreGuard = false) {
      let method;
      if (isKeyword(element)) {
        method = buildKeyword(ctx, element);
      } else if (isAction(element)) {
        method = buildAction(ctx, element);
      } else if (isAssignment(element)) {
        method = buildElement(ctx, element.terminal);
      } else if (isCrossReference(element)) {
        method = buildCrossReference(ctx, element);
      } else if (isRuleCall(element)) {
        method = buildRuleCall(ctx, element);
      } else if (isAlternatives(element)) {
        method = buildAlternatives(ctx, element);
      } else if (isUnorderedGroup(element)) {
        method = buildUnorderedGroup(ctx, element);
      } else if (isGroup$1(element)) {
        method = buildGroup(ctx, element);
      } else if (isEndOfFile(element)) {
        const idx = ctx.consume++;
        method = () => ctx.parser.consume(idx, EOF, element);
      } else {
        throw new ErrorWithLocation(element.$cstNode, `Unexpected element type: ${element.$type}`);
      }
      return wrap(ctx, ignoreGuard ? void 0 : getGuardCondition(element), method, element.cardinality);
    }
    function buildAction(ctx, action) {
      const actionType = getTypeName(action);
      return () => ctx.parser.action(actionType, action);
    }
    function buildRuleCall(ctx, ruleCall) {
      const rule = ruleCall.rule.ref;
      if (isAbstractParserRule(rule)) {
        const idx = ctx.subrule++;
        const fragment = isParserRule(rule) && rule.fragment;
        const predicate = ruleCall.arguments.length > 0 ? buildRuleCallPredicate(rule, ruleCall.arguments) : () => ({});
        let subrule;
        return (args) => {
          subrule ?? (subrule = getRule(ctx, rule));
          ctx.parser.subrule(idx, subrule, fragment, ruleCall, predicate(args));
        };
      } else if (isTerminalRule(rule)) {
        const idx = ctx.consume++;
        const method = getToken(ctx, rule.name);
        return () => ctx.parser.consume(idx, method, ruleCall);
      } else if (!rule) {
        throw new ErrorWithLocation(ruleCall.$cstNode, `Undefined rule: ${ruleCall.rule.$refText}`);
      } else {
        assertUnreachable();
      }
    }
    function buildRuleCallPredicate(rule, namedArgs) {
      const hasNamedArguments = namedArgs.some((arg) => arg.calledByName);
      if (hasNamedArguments) {
        const namedPredicates = namedArgs.map((arg) => ({
          parameterName: arg.parameter?.ref?.name,
          predicate: buildPredicate(arg.value)
        }));
        return (args) => {
          const ruleArgs = {};
          for (const { parameterName, predicate } of namedPredicates) {
            if (parameterName) {
              ruleArgs[parameterName] = predicate(args);
            }
          }
          return ruleArgs;
        };
      } else {
        const predicates = namedArgs.map((arg) => buildPredicate(arg.value));
        return (args) => {
          const ruleArgs = {};
          for (let i = 0; i < predicates.length; i++) {
            if (i < rule.parameters.length) {
              const parameterName = rule.parameters[i].name;
              const predicate = predicates[i];
              ruleArgs[parameterName] = predicate(args);
            }
          }
          return ruleArgs;
        };
      }
    }
    function buildPredicate(condition) {
      if (isDisjunction(condition)) {
        const left = buildPredicate(condition.left);
        const right = buildPredicate(condition.right);
        return (args) => left(args) || right(args);
      } else if (isConjunction(condition)) {
        const left = buildPredicate(condition.left);
        const right = buildPredicate(condition.right);
        return (args) => left(args) && right(args);
      } else if (isNegation(condition)) {
        const value = buildPredicate(condition.value);
        return (args) => !value(args);
      } else if (isParameterReference(condition)) {
        const name = condition.parameter.ref.name;
        return (args) => args !== void 0 && args[name] === true;
      } else if (isBooleanLiteral(condition)) {
        const value = Boolean(condition.true);
        return () => value;
      }
      assertUnreachable();
    }
    function buildAlternatives(ctx, alternatives) {
      if (alternatives.elements.length === 1) {
        return buildElement(ctx, alternatives.elements[0]);
      } else {
        const methods = [];
        for (const element of alternatives.elements) {
          const predicatedMethod = {
            // Since we handle the guard condition in the alternative already
            // We can ignore the group guard condition inside
            ALT: buildElement(ctx, element, true)
          };
          const guard = getGuardCondition(element);
          if (guard) {
            predicatedMethod.GATE = buildPredicate(guard);
          }
          methods.push(predicatedMethod);
        }
        const idx = ctx.or++;
        return (args) => ctx.parser.alternatives(idx, methods.map((method) => {
          const alt = {
            ALT: () => method.ALT(args)
          };
          const gate = method.GATE;
          if (gate) {
            alt.GATE = () => gate(args);
          }
          return alt;
        }));
      }
    }
    function buildUnorderedGroup(ctx, group) {
      if (group.elements.length === 1) {
        return buildElement(ctx, group.elements[0]);
      }
      const methods = [];
      for (const element of group.elements) {
        const predicatedMethod = {
          // Since we handle the guard condition in the alternative already
          // We can ignore the group guard condition inside
          ALT: buildElement(ctx, element, true)
        };
        const guard = getGuardCondition(element);
        if (guard) {
          predicatedMethod.GATE = buildPredicate(guard);
        }
        methods.push(predicatedMethod);
      }
      const orIdx = ctx.or++;
      const idFunc = (groupIdx, lParser) => {
        const stackId = lParser.getRuleStack().join("-");
        return `uGroup_${groupIdx}_${stackId}`;
      };
      const alternatives = (args) => ctx.parser.alternatives(orIdx, methods.map((method, idx) => {
        const alt = { ALT: () => true };
        const parser = ctx.parser;
        alt.ALT = () => {
          method.ALT(args);
          if (!parser.isRecording()) {
            const key = idFunc(orIdx, parser);
            if (!parser.unorderedGroups.get(key)) {
              parser.unorderedGroups.set(key, []);
            }
            const groupState = parser.unorderedGroups.get(key);
            if (typeof groupState?.[idx] === "undefined") {
              groupState[idx] = true;
            }
          }
        };
        const gate = method.GATE;
        if (gate) {
          alt.GATE = () => gate(args);
        } else {
          alt.GATE = () => {
            const trackedAlternatives = parser.unorderedGroups.get(idFunc(orIdx, parser));
            const allow = !trackedAlternatives?.[idx];
            return allow;
          };
        }
        return alt;
      }));
      const wrapped = wrap(ctx, getGuardCondition(group), alternatives, "*");
      return (args) => {
        wrapped(args);
        if (!ctx.parser.isRecording()) {
          ctx.parser.unorderedGroups.delete(idFunc(orIdx, ctx.parser));
        }
      };
    }
    function buildGroup(ctx, group) {
      const methods = group.elements.map((e) => buildElement(ctx, e));
      return (args) => methods.forEach((method) => method(args));
    }
    function getGuardCondition(element) {
      if (isGroup$1(element)) {
        return element.guardCondition;
      }
      return void 0;
    }
    function buildCrossReference(ctx, crossRef, terminal = crossRef.terminal) {
      if (!terminal) {
        if (!crossRef.type.ref) {
          throw new Error("Could not resolve reference to type: " + crossRef.type.$refText);
        }
        const assignment = findNameAssignment(crossRef.type.ref);
        const assignTerminal = assignment?.terminal;
        if (!assignTerminal) {
          throw new Error("Could not find name assignment for type: " + getTypeName(crossRef.type.ref));
        }
        return buildCrossReference(ctx, crossRef, assignTerminal);
      } else if (isRuleCall(terminal) && isParserRule(terminal.rule.ref)) {
        const rule = terminal.rule.ref;
        const idx = ctx.subrule++;
        let subrule;
        return (args) => {
          subrule ?? (subrule = getRule(ctx, rule));
          ctx.parser.subrule(idx, subrule, false, crossRef, args);
        };
      } else if (isRuleCall(terminal) && isTerminalRule(terminal.rule.ref)) {
        const idx = ctx.consume++;
        const terminalRule = getToken(ctx, terminal.rule.ref.name);
        return () => ctx.parser.consume(idx, terminalRule, crossRef);
      } else if (isKeyword(terminal)) {
        const idx = ctx.consume++;
        const keyword = getToken(ctx, terminal.value);
        return () => ctx.parser.consume(idx, keyword, crossRef);
      } else {
        throw new Error("Could not build cross reference parser");
      }
    }
    function buildKeyword(ctx, keyword) {
      const idx = ctx.consume++;
      const token = ctx.tokens[keyword.value];
      if (!token) {
        throw new Error("Could not find token for keyword: " + keyword.value);
      }
      return () => ctx.parser.consume(idx, token, keyword);
    }
    function wrap(ctx, guard, method, cardinality) {
      const gate = guard && buildPredicate(guard);
      if (!cardinality) {
        if (gate) {
          const idx = ctx.or++;
          return (args) => ctx.parser.alternatives(idx, [
            {
              ALT: () => method(args),
              GATE: () => gate(args)
            },
            {
              ALT: EMPTY_ALT(),
              GATE: () => !gate(args)
            }
          ]);
        } else {
          return method;
        }
      }
      if (cardinality === "*") {
        const idx = ctx.many++;
        return (args) => ctx.parser.many(idx, {
          DEF: () => method(args),
          GATE: gate ? () => gate(args) : void 0
        });
      } else if (cardinality === "+") {
        const idx = ctx.many++;
        if (gate) {
          const orIdx = ctx.or++;
          return (args) => ctx.parser.alternatives(orIdx, [
            {
              ALT: () => ctx.parser.atLeastOne(idx, {
                DEF: () => method(args)
              }),
              GATE: () => gate(args)
            },
            {
              ALT: EMPTY_ALT(),
              GATE: () => !gate(args)
            }
          ]);
        } else {
          return (args) => ctx.parser.atLeastOne(idx, {
            DEF: () => method(args)
          });
        }
      } else if (cardinality === "?") {
        const idx = ctx.optional++;
        return (args) => ctx.parser.optional(idx, {
          DEF: () => method(args),
          GATE: gate ? () => gate(args) : void 0
        });
      } else {
        assertUnreachable();
      }
    }
    function getRule(ctx, element) {
      const name = getRuleName(ctx, element);
      const rule = ctx.parser.getRule(name);
      if (!rule)
        throw new Error(`Rule "${name}" not found."`);
      return rule;
    }
    function getRuleName(ctx, element) {
      if (isAbstractParserRule(element)) {
        return element.name;
      } else if (ctx.ruleNames.has(element)) {
        return ctx.ruleNames.get(element);
      } else {
        let item = element;
        let parent = item.$container;
        let ruleName = element.$type;
        while (!isParserRule(parent)) {
          if (isGroup$1(parent) || isAlternatives(parent) || isUnorderedGroup(parent)) {
            const index = parent.elements.indexOf(item);
            ruleName = index.toString() + ":" + ruleName;
          }
          item = parent;
          parent = parent.$container;
        }
        const rule = parent;
        ruleName = rule.name + ":" + ruleName;
        ctx.ruleNames.set(element, ruleName);
        return ruleName;
      }
    }
    function getToken(ctx, name) {
      const token = ctx.tokens[name];
      if (!token)
        throw new Error(`Token "${name}" not found."`);
      return token;
    }
    function createCompletionParser(services) {
      const grammar = services.Grammar;
      const lexer = services.parser.Lexer;
      const parser = new LangiumCompletionParser(services);
      createParser(grammar, parser, lexer.definition);
      parser.finalize();
      return parser;
    }
    function createLangiumParser(services) {
      const parser = prepareLangiumParser(services);
      parser.finalize();
      return parser;
    }
    function prepareLangiumParser(services) {
      const grammar = services.Grammar;
      const lexer = services.parser.Lexer;
      const parser = new LangiumParser(services);
      return createParser(grammar, parser, lexer.definition);
    }
    class DefaultTokenBuilder {
      constructor() {
        this.diagnostics = [];
      }
      buildTokens(grammar, options) {
        const reachableRules = stream(getAllReachableRules(grammar, false));
        const terminalTokens = this.buildTerminalTokens(reachableRules);
        const tokens2 = this.buildKeywordTokens(reachableRules, terminalTokens, options);
        tokens2.push(...terminalTokens);
        return tokens2;
      }
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      flushLexingReport(text) {
        return { diagnostics: this.popDiagnostics() };
      }
      popDiagnostics() {
        const diagnostics = [...this.diagnostics];
        this.diagnostics = [];
        return diagnostics;
      }
      buildTerminalTokens(rules) {
        return rules.filter(isTerminalRule).filter((e) => !e.fragment).map((terminal) => this.buildTerminalToken(terminal)).toArray();
      }
      buildTerminalToken(terminal) {
        const regex = terminalRegex(terminal);
        const pattern = this.requiresCustomPattern(regex) ? this.regexPatternFunction(regex) : regex;
        const tokenType = {
          name: terminal.name,
          PATTERN: pattern
        };
        if (typeof pattern === "function") {
          tokenType.LINE_BREAKS = true;
        }
        if (terminal.hidden) {
          tokenType.GROUP = isWhitespace(regex) ? Lexer.SKIPPED : "hidden";
        }
        return tokenType;
      }
      requiresCustomPattern(regex) {
        if (regex.flags.includes("u") || regex.flags.includes("s")) {
          return true;
        } else {
          return false;
        }
      }
      regexPatternFunction(regex) {
        const stickyRegex = new RegExp(regex, regex.flags + "y");
        return (text, offset) => {
          stickyRegex.lastIndex = offset;
          const execResult = stickyRegex.exec(text);
          return execResult;
        };
      }
      buildKeywordTokens(rules, terminalTokens, options) {
        return rules.filter(isAbstractParserRule).flatMap((rule) => streamAllContents(rule).filter(isKeyword)).distinct((e) => e.value).toArray().sort((a2, b) => b.value.length - a2.value.length).map((keyword) => this.buildKeywordToken(keyword, terminalTokens, Boolean(options?.caseInsensitive)));
      }
      buildKeywordToken(keyword, terminalTokens, caseInsensitive) {
        const keywordPattern = this.buildKeywordPattern(keyword, caseInsensitive);
        const tokenType = {
          name: keyword.value,
          PATTERN: keywordPattern,
          LONGER_ALT: this.findLongerAlt(keyword, terminalTokens)
        };
        if (typeof keywordPattern === "function") {
          tokenType.LINE_BREAKS = true;
        }
        return tokenType;
      }
      buildKeywordPattern(keyword, caseInsensitive) {
        return caseInsensitive ? new RegExp(escapeRegExp(keyword.value), "i") : keyword.value;
      }
      findLongerAlt(keyword, terminalTokens) {
        return terminalTokens.reduce((longerAlts, token) => {
          const pattern = token?.PATTERN;
          if (pattern?.source && partialMatches("^" + pattern.source + "$", keyword.value)) {
            longerAlts.push(token);
          }
          return longerAlts;
        }, []);
      }
    }
    class DefaultValueConverter {
      convert(input, cstNode) {
        let feature = cstNode.grammarSource;
        if (isCrossReference(feature)) {
          feature = getCrossReferenceTerminal(feature);
        }
        if (isRuleCall(feature)) {
          const rule = feature.rule.ref;
          if (!rule) {
            throw new Error("This cst node was not parsed by a rule.");
          }
          return this.runConverter(rule, input, cstNode);
        }
        return input;
      }
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
      runConverter(rule, input, cstNode) {
        switch (rule.name.toUpperCase()) {
          case "INT":
            return ValueConverter.convertInt(input);
          case "STRING":
            return ValueConverter.convertString(input);
          case "ID":
            return ValueConverter.convertID(input);
        }
        switch (getRuleType(rule)?.toLowerCase()) {
          case "number":
            return ValueConverter.convertNumber(input);
          case "boolean":
            return ValueConverter.convertBoolean(input);
          case "bigint":
            return ValueConverter.convertBigint(input);
          case "date":
            return ValueConverter.convertDate(input);
          default:
            return input;
        }
      }
    }
    var ValueConverter;
    (function(ValueConverter2) {
      function convertString(input) {
        let result = "";
        for (let i = 1; i < input.length - 1; i++) {
          const c = input.charAt(i);
          if (c === "\\") {
            const c1 = input.charAt(++i);
            result += convertEscapeCharacter(c1);
          } else {
            result += c;
          }
        }
        return result;
      }
      ValueConverter2.convertString = convertString;
      function convertEscapeCharacter(char) {
        switch (char) {
          case "b":
            return "\b";
          case "f":
            return "\f";
          case "n":
            return "\n";
          case "r":
            return "\r";
          case "t":
            return "	";
          case "v":
            return "\v";
          case "0":
            return "\0";
          default:
            return char;
        }
      }
      function convertID(input) {
        if (input.charAt(0) === "^") {
          return input.substring(1);
        } else {
          return input;
        }
      }
      ValueConverter2.convertID = convertID;
      function convertInt(input) {
        return parseInt(input);
      }
      ValueConverter2.convertInt = convertInt;
      function convertBigint(input) {
        return BigInt(input);
      }
      ValueConverter2.convertBigint = convertBigint;
      function convertDate(input) {
        return new Date(input);
      }
      ValueConverter2.convertDate = convertDate;
      function convertNumber(input) {
        return Number(input);
      }
      ValueConverter2.convertNumber = convertNumber;
      function convertBoolean(input) {
        return input.toLowerCase() === "true";
      }
      ValueConverter2.convertBoolean = convertBoolean;
    })(ValueConverter || (ValueConverter = {}));
    var cancellation = {};
    var ral = {};
    var hasRequiredRal;
    function requireRal() {
      if (hasRequiredRal) return ral;
      hasRequiredRal = 1;
      Object.defineProperty(ral, "__esModule", { value: true });
      let _ral;
      function RAL() {
        if (_ral === void 0) {
          throw new Error(`No runtime abstraction layer installed`);
        }
        return _ral;
      }
      (function(RAL2) {
        function install(ral2) {
          if (ral2 === void 0) {
            throw new Error(`No runtime abstraction layer provided`);
          }
          _ral = ral2;
        }
        RAL2.install = install;
      })(RAL || (RAL = {}));
      ral.default = RAL;
      return ral;
    }
    var is = {};
    var hasRequiredIs;
    function requireIs() {
      if (hasRequiredIs) return is;
      hasRequiredIs = 1;
      Object.defineProperty(is, "__esModule", { value: true });
      is.stringArray = is.array = is.func = is.error = is.number = is.string = is.boolean = void 0;
      function boolean(value) {
        return value === true || value === false;
      }
      is.boolean = boolean;
      function string(value) {
        return typeof value === "string" || value instanceof String;
      }
      is.string = string;
      function number(value) {
        return typeof value === "number" || value instanceof Number;
      }
      is.number = number;
      function error(value) {
        return value instanceof Error;
      }
      is.error = error;
      function func(value) {
        return typeof value === "function";
      }
      is.func = func;
      function array(value) {
        return Array.isArray(value);
      }
      is.array = array;
      function stringArray(value) {
        return array(value) && value.every((elem) => string(elem));
      }
      is.stringArray = stringArray;
      return is;
    }
    var events = {};
    var hasRequiredEvents;
    function requireEvents() {
      if (hasRequiredEvents) return events;
      hasRequiredEvents = 1;
      Object.defineProperty(events, "__esModule", { value: true });
      events.Emitter = events.Event = void 0;
      const ral_1 = requireRal();
      var Event;
      (function(Event2) {
        const _disposable = { dispose() {
        } };
        Event2.None = function() {
          return _disposable;
        };
      })(Event || (events.Event = Event = {}));
      class CallbackList {
        add(callback, context = null, bucket) {
          if (!this._callbacks) {
            this._callbacks = [];
            this._contexts = [];
          }
          this._callbacks.push(callback);
          this._contexts.push(context);
          if (Array.isArray(bucket)) {
            bucket.push({ dispose: () => this.remove(callback, context) });
          }
        }
        remove(callback, context = null) {
          if (!this._callbacks) {
            return;
          }
          let foundCallbackWithDifferentContext = false;
          for (let i = 0, len = this._callbacks.length; i < len; i++) {
            if (this._callbacks[i] === callback) {
              if (this._contexts[i] === context) {
                this._callbacks.splice(i, 1);
                this._contexts.splice(i, 1);
                return;
              } else {
                foundCallbackWithDifferentContext = true;
              }
            }
          }
          if (foundCallbackWithDifferentContext) {
            throw new Error("When adding a listener with a context, you should remove it with the same context");
          }
        }
        invoke(...args) {
          if (!this._callbacks) {
            return [];
          }
          const ret = [], callbacks = this._callbacks.slice(0), contexts = this._contexts.slice(0);
          for (let i = 0, len = callbacks.length; i < len; i++) {
            try {
              ret.push(callbacks[i].apply(contexts[i], args));
            } catch (e) {
              (0, ral_1.default)().console.error(e);
            }
          }
          return ret;
        }
        isEmpty() {
          return !this._callbacks || this._callbacks.length === 0;
        }
        dispose() {
          this._callbacks = void 0;
          this._contexts = void 0;
        }
      }
      class Emitter {
        constructor(_options) {
          this._options = _options;
        }
        /**
         * For the public to allow to subscribe
         * to events from this Emitter
         */
        get event() {
          if (!this._event) {
            this._event = (listener, thisArgs, disposables) => {
              if (!this._callbacks) {
                this._callbacks = new CallbackList();
              }
              if (this._options && this._options.onFirstListenerAdd && this._callbacks.isEmpty()) {
                this._options.onFirstListenerAdd(this);
              }
              this._callbacks.add(listener, thisArgs);
              const result = {
                dispose: () => {
                  if (!this._callbacks) {
                    return;
                  }
                  this._callbacks.remove(listener, thisArgs);
                  result.dispose = Emitter._noop;
                  if (this._options && this._options.onLastListenerRemove && this._callbacks.isEmpty()) {
                    this._options.onLastListenerRemove(this);
                  }
                }
              };
              if (Array.isArray(disposables)) {
                disposables.push(result);
              }
              return result;
            };
          }
          return this._event;
        }
        /**
         * To be kept private to fire an event to
         * subscribers
         */
        fire(event) {
          if (this._callbacks) {
            this._callbacks.invoke.call(this._callbacks, event);
          }
        }
        dispose() {
          if (this._callbacks) {
            this._callbacks.dispose();
            this._callbacks = void 0;
          }
        }
      }
      events.Emitter = Emitter;
      Emitter._noop = function() {
      };
      return events;
    }
    var hasRequiredCancellation;
    function requireCancellation() {
      if (hasRequiredCancellation) return cancellation;
      hasRequiredCancellation = 1;
      Object.defineProperty(cancellation, "__esModule", { value: true });
      cancellation.CancellationTokenSource = cancellation.CancellationToken = void 0;
      const ral_1 = requireRal();
      const Is2 = requireIs();
      const events_1 = requireEvents();
      var CancellationToken;
      (function(CancellationToken2) {
        CancellationToken2.None = Object.freeze({
          isCancellationRequested: false,
          onCancellationRequested: events_1.Event.None
        });
        CancellationToken2.Cancelled = Object.freeze({
          isCancellationRequested: true,
          onCancellationRequested: events_1.Event.None
        });
        function is2(value) {
          const candidate = value;
          return candidate && (candidate === CancellationToken2.None || candidate === CancellationToken2.Cancelled || Is2.boolean(candidate.isCancellationRequested) && !!candidate.onCancellationRequested);
        }
        CancellationToken2.is = is2;
      })(CancellationToken || (cancellation.CancellationToken = CancellationToken = {}));
      const shortcutEvent = Object.freeze(function(callback, context) {
        const handle = (0, ral_1.default)().timer.setTimeout(callback.bind(context), 0);
        return { dispose() {
          handle.dispose();
        } };
      });
      class MutableToken {
        constructor() {
          this._isCancelled = false;
        }
        cancel() {
          if (!this._isCancelled) {
            this._isCancelled = true;
            if (this._emitter) {
              this._emitter.fire(void 0);
              this.dispose();
            }
          }
        }
        get isCancellationRequested() {
          return this._isCancelled;
        }
        get onCancellationRequested() {
          if (this._isCancelled) {
            return shortcutEvent;
          }
          if (!this._emitter) {
            this._emitter = new events_1.Emitter();
          }
          return this._emitter.event;
        }
        dispose() {
          if (this._emitter) {
            this._emitter.dispose();
            this._emitter = void 0;
          }
        }
      }
      class CancellationTokenSource {
        get token() {
          if (!this._token) {
            this._token = new MutableToken();
          }
          return this._token;
        }
        cancel() {
          if (!this._token) {
            this._token = CancellationToken.Cancelled;
          } else {
            this._token.cancel();
          }
        }
        dispose() {
          if (!this._token) {
            this._token = CancellationToken.None;
          } else if (this._token instanceof MutableToken) {
            this._token.dispose();
          }
        }
      }
      cancellation.CancellationTokenSource = CancellationTokenSource;
      return cancellation;
    }
    var cancellationExports = requireCancellation();
    function delayNextTick() {
      return new Promise((resolve) => {
        if (typeof setImmediate === "undefined") {
          setTimeout(resolve, 0);
        } else {
          setImmediate(resolve);
        }
      });
    }
    let lastTick = 0;
    let globalInterruptionPeriod = 10;
    function startCancelableOperation() {
      lastTick = performance.now();
      return new cancellationExports.CancellationTokenSource();
    }
    const OperationCancelled = Symbol("OperationCancelled");
    function isOperationCancelled(err) {
      return err === OperationCancelled;
    }
    async function interruptAndCheck(token) {
      if (token === cancellationExports.CancellationToken.None) {
        return;
      }
      const current = performance.now();
      if (current - lastTick >= globalInterruptionPeriod) {
        lastTick = current;
        await delayNextTick();
        lastTick = performance.now();
      }
      if (token.isCancellationRequested) {
        throw OperationCancelled;
      }
    }
    class Deferred {
      constructor() {
        this.promise = new Promise((resolve, reject) => {
          this.resolve = (arg) => {
            resolve(arg);
            return this;
          };
          this.reject = (err) => {
            reject(err);
            return this;
          };
        });
      }
    }
    class FullTextDocument {
      constructor(uri, languageId, version, content) {
        this._uri = uri;
        this._languageId = languageId;
        this._version = version;
        this._content = content;
        this._lineOffsets = void 0;
      }
      get uri() {
        return this._uri;
      }
      get languageId() {
        return this._languageId;
      }
      get version() {
        return this._version;
      }
      getText(range) {
        if (range) {
          const start = this.offsetAt(range.start);
          const end = this.offsetAt(range.end);
          return this._content.substring(start, end);
        }
        return this._content;
      }
      update(changes, version) {
        for (const change of changes) {
          if (FullTextDocument.isIncremental(change)) {
            const range = getWellformedRange(change.range);
            const startOffset = this.offsetAt(range.start);
            const endOffset = this.offsetAt(range.end);
            this._content = this._content.substring(0, startOffset) + change.text + this._content.substring(endOffset, this._content.length);
            const startLine = Math.max(range.start.line, 0);
            const endLine = Math.max(range.end.line, 0);
            let lineOffsets = this._lineOffsets;
            const addedLineOffsets = computeLineOffsets(change.text, false, startOffset);
            if (endLine - startLine === addedLineOffsets.length) {
              for (let i = 0, len = addedLineOffsets.length; i < len; i++) {
                lineOffsets[i + startLine + 1] = addedLineOffsets[i];
              }
            } else {
              if (addedLineOffsets.length < 1e4) {
                lineOffsets.splice(startLine + 1, endLine - startLine, ...addedLineOffsets);
              } else {
                this._lineOffsets = lineOffsets = lineOffsets.slice(0, startLine + 1).concat(addedLineOffsets, lineOffsets.slice(endLine + 1));
              }
            }
            const diff = change.text.length - (endOffset - startOffset);
            if (diff !== 0) {
              for (let i = startLine + 1 + addedLineOffsets.length, len = lineOffsets.length; i < len; i++) {
                lineOffsets[i] = lineOffsets[i] + diff;
              }
            }
          } else if (FullTextDocument.isFull(change)) {
            this._content = change.text;
            this._lineOffsets = void 0;
          } else {
            throw new Error("Unknown change event received");
          }
        }
        this._version = version;
      }
      getLineOffsets() {
        if (this._lineOffsets === void 0) {
          this._lineOffsets = computeLineOffsets(this._content, true);
        }
        return this._lineOffsets;
      }
      positionAt(offset) {
        offset = Math.max(Math.min(offset, this._content.length), 0);
        const lineOffsets = this.getLineOffsets();
        let low = 0, high = lineOffsets.length;
        if (high === 0) {
          return { line: 0, character: offset };
        }
        while (low < high) {
          const mid = Math.floor((low + high) / 2);
          if (lineOffsets[mid] > offset) {
            high = mid;
          } else {
            low = mid + 1;
          }
        }
        const line = low - 1;
        offset = this.ensureBeforeEOL(offset, lineOffsets[line]);
        return { line, character: offset - lineOffsets[line] };
      }
      offsetAt(position) {
        const lineOffsets = this.getLineOffsets();
        if (position.line >= lineOffsets.length) {
          return this._content.length;
        } else if (position.line < 0) {
          return 0;
        }
        const lineOffset = lineOffsets[position.line];
        if (position.character <= 0) {
          return lineOffset;
        }
        const nextLineOffset = position.line + 1 < lineOffsets.length ? lineOffsets[position.line + 1] : this._content.length;
        const offset = Math.min(lineOffset + position.character, nextLineOffset);
        return this.ensureBeforeEOL(offset, lineOffset);
      }
      ensureBeforeEOL(offset, lineOffset) {
        while (offset > lineOffset && isEOL(this._content.charCodeAt(offset - 1))) {
          offset--;
        }
        return offset;
      }
      get lineCount() {
        return this.getLineOffsets().length;
      }
      static isIncremental(event) {
        const candidate = event;
        return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range !== void 0 && (candidate.rangeLength === void 0 || typeof candidate.rangeLength === "number");
      }
      static isFull(event) {
        const candidate = event;
        return candidate !== void 0 && candidate !== null && typeof candidate.text === "string" && candidate.range === void 0 && candidate.rangeLength === void 0;
      }
    }
    var TextDocument;
    (function(TextDocument2) {
      function create(uri, languageId, version, content) {
        return new FullTextDocument(uri, languageId, version, content);
      }
      TextDocument2.create = create;
      function update(document, changes, version) {
        if (document instanceof FullTextDocument) {
          document.update(changes, version);
          return document;
        } else {
          throw new Error("TextDocument.update: document must be created by TextDocument.create");
        }
      }
      TextDocument2.update = update;
      function applyEdits(document, edits) {
        const text = document.getText();
        const sortedEdits = mergeSort(edits.map(getWellformedEdit), (a2, b) => {
          const diff = a2.range.start.line - b.range.start.line;
          if (diff === 0) {
            return a2.range.start.character - b.range.start.character;
          }
          return diff;
        });
        let lastModifiedOffset = 0;
        const spans = [];
        for (const e of sortedEdits) {
          const startOffset = document.offsetAt(e.range.start);
          if (startOffset < lastModifiedOffset) {
            throw new Error("Overlapping edit");
          } else if (startOffset > lastModifiedOffset) {
            spans.push(text.substring(lastModifiedOffset, startOffset));
          }
          if (e.newText.length) {
            spans.push(e.newText);
          }
          lastModifiedOffset = document.offsetAt(e.range.end);
        }
        spans.push(text.substr(lastModifiedOffset));
        return spans.join("");
      }
      TextDocument2.applyEdits = applyEdits;
    })(TextDocument || (TextDocument = {}));
    function mergeSort(data, compare) {
      if (data.length <= 1) {
        return data;
      }
      const p = data.length / 2 | 0;
      const left = data.slice(0, p);
      const right = data.slice(p);
      mergeSort(left, compare);
      mergeSort(right, compare);
      let leftIdx = 0;
      let rightIdx = 0;
      let i = 0;
      while (leftIdx < left.length && rightIdx < right.length) {
        const ret = compare(left[leftIdx], right[rightIdx]);
        if (ret <= 0) {
          data[i++] = left[leftIdx++];
        } else {
          data[i++] = right[rightIdx++];
        }
      }
      while (leftIdx < left.length) {
        data[i++] = left[leftIdx++];
      }
      while (rightIdx < right.length) {
        data[i++] = right[rightIdx++];
      }
      return data;
    }
    function computeLineOffsets(text, isAtLineStart, textOffset = 0) {
      const result = isAtLineStart ? [textOffset] : [];
      for (let i = 0; i < text.length; i++) {
        const ch = text.charCodeAt(i);
        if (isEOL(ch)) {
          if (ch === 13 && i + 1 < text.length && text.charCodeAt(i + 1) === 10) {
            i++;
          }
          result.push(textOffset + i + 1);
        }
      }
      return result;
    }
    function isEOL(char) {
      return char === 13 || char === 10;
    }
    function getWellformedRange(range) {
      const start = range.start;
      const end = range.end;
      if (start.line > end.line || start.line === end.line && start.character > end.character) {
        return { start: end, end: start };
      }
      return range;
    }
    function getWellformedEdit(textEdit) {
      const range = getWellformedRange(textEdit.range);
      if (range !== textEdit.range) {
        return { newText: textEdit.newText, range };
      }
      return textEdit;
    }
    var DocumentState;
    (function(DocumentState2) {
      DocumentState2[DocumentState2["Changed"] = 0] = "Changed";
      DocumentState2[DocumentState2["Parsed"] = 1] = "Parsed";
      DocumentState2[DocumentState2["IndexedContent"] = 2] = "IndexedContent";
      DocumentState2[DocumentState2["ComputedScopes"] = 3] = "ComputedScopes";
      DocumentState2[DocumentState2["Linked"] = 4] = "Linked";
      DocumentState2[DocumentState2["IndexedReferences"] = 5] = "IndexedReferences";
      DocumentState2[DocumentState2["Validated"] = 6] = "Validated";
    })(DocumentState || (DocumentState = {}));
    class DefaultLangiumDocumentFactory {
      constructor(services) {
        this.serviceRegistry = services.ServiceRegistry;
        this.textDocuments = services.workspace.TextDocuments;
        this.fileSystemProvider = services.workspace.FileSystemProvider;
      }
      async fromUri(uri, cancellationToken = cancellationExports.CancellationToken.None) {
        const content = await this.fileSystemProvider.readFile(uri);
        return this.createAsync(uri, content, cancellationToken);
      }
      fromTextDocument(textDocument, uri, token) {
        uri = uri ?? URI$1.parse(textDocument.uri);
        if (cancellationExports.CancellationToken.is(token)) {
          return this.createAsync(uri, textDocument, token);
        } else {
          return this.create(uri, textDocument, token);
        }
      }
      fromString(text, uri, token) {
        if (cancellationExports.CancellationToken.is(token)) {
          return this.createAsync(uri, text, token);
        } else {
          return this.create(uri, text, token);
        }
      }
      fromModel(model, uri) {
        return this.create(uri, { $model: model });
      }
      create(uri, content, options) {
        if (typeof content === "string") {
          const parseResult = this.parse(uri, content, options);
          return this.createLangiumDocument(parseResult, uri, void 0, content);
        } else if ("$model" in content) {
          const parseResult = { value: content.$model, parserErrors: [], lexerErrors: [] };
          return this.createLangiumDocument(parseResult, uri);
        } else {
          const parseResult = this.parse(uri, content.getText(), options);
          return this.createLangiumDocument(parseResult, uri, content);
        }
      }
      async createAsync(uri, content, cancelToken) {
        if (typeof content === "string") {
          const parseResult = await this.parseAsync(uri, content, cancelToken);
          return this.createLangiumDocument(parseResult, uri, void 0, content);
        } else {
          const parseResult = await this.parseAsync(uri, content.getText(), cancelToken);
          return this.createLangiumDocument(parseResult, uri, content);
        }
      }
      /**
       * Create a LangiumDocument from a given parse result.
       *
       * A TextDocument is created on demand if it is not provided as argument here. Usually this
       * should not be necessary because the main purpose of the TextDocument is to convert between
       * text ranges and offsets, which is done solely in LSP request handling.
       *
       * With the introduction of {@link update} below this method is supposed to be mainly called
       * during workspace initialization and on addition/recognition of new files, while changes in
       * existing documents are processed via {@link update}.
       */
      createLangiumDocument(parseResult, uri, textDocument, text) {
        let document;
        if (textDocument) {
          document = {
            parseResult,
            uri,
            state: DocumentState.Parsed,
            references: [],
            textDocument
          };
        } else {
          const textDocumentGetter = this.createTextDocumentGetter(uri, text);
          document = {
            parseResult,
            uri,
            state: DocumentState.Parsed,
            references: [],
            get textDocument() {
              return textDocumentGetter();
            }
          };
        }
        parseResult.value.$document = document;
        return document;
      }
      async update(document, cancellationToken) {
        const oldText = document.parseResult.value.$cstNode?.root.fullText;
        const textDocument = this.textDocuments?.get(document.uri.toString());
        const text = textDocument ? textDocument.getText() : await this.fileSystemProvider.readFile(document.uri);
        if (textDocument) {
          Object.defineProperty(document, "textDocument", {
            value: textDocument
          });
        } else {
          const textDocumentGetter = this.createTextDocumentGetter(document.uri, text);
          Object.defineProperty(document, "textDocument", {
            get: textDocumentGetter
          });
        }
        if (oldText !== text) {
          document.parseResult = await this.parseAsync(document.uri, text, cancellationToken);
          document.parseResult.value.$document = document;
        }
        document.state = DocumentState.Parsed;
        return document;
      }
      parse(uri, text, options) {
        const services = this.serviceRegistry.getServices(uri);
        return services.parser.LangiumParser.parse(text, options);
      }
      parseAsync(uri, text, cancellationToken) {
        const services = this.serviceRegistry.getServices(uri);
        return services.parser.AsyncParser.parse(text, cancellationToken);
      }
      createTextDocumentGetter(uri, text) {
        const serviceRegistry = this.serviceRegistry;
        let textDoc = void 0;
        return () => {
          return textDoc ?? (textDoc = TextDocument.create(uri.toString(), serviceRegistry.getServices(uri).LanguageMetaData.languageId, 0, text ?? ""));
        };
      }
    }
    class DefaultLangiumDocuments {
      constructor(services) {
        this.documentTrie = new UriTrie();
        this.services = services;
        this.langiumDocumentFactory = services.workspace.LangiumDocumentFactory;
        this.documentBuilder = () => services.workspace.DocumentBuilder;
      }
      get all() {
        return stream(this.documentTrie.all());
      }
      addDocument(document) {
        const uriString = document.uri.toString();
        if (this.documentTrie.has(uriString)) {
          throw new Error(`A document with the URI '${uriString}' is already present.`);
        }
        this.documentTrie.insert(uriString, document);
      }
      getDocument(uri) {
        const uriString = uri.toString();
        return this.documentTrie.find(uriString);
      }
      getDocuments(folder) {
        const uriString = folder.toString();
        return this.documentTrie.findAll(uriString);
      }
      async getOrCreateDocument(uri, cancellationToken) {
        let document = this.getDocument(uri);
        if (document) {
          return document;
        }
        document = await this.langiumDocumentFactory.fromUri(uri, cancellationToken);
        this.addDocument(document);
        return document;
      }
      createDocument(uri, text, cancellationToken) {
        if (cancellationToken) {
          return this.langiumDocumentFactory.fromString(text, uri, cancellationToken).then((document) => {
            this.addDocument(document);
            return document;
          });
        } else {
          const document = this.langiumDocumentFactory.fromString(text, uri);
          this.addDocument(document);
          return document;
        }
      }
      hasDocument(uri) {
        return this.documentTrie.has(uri.toString());
      }
      /**
       * @deprecated Since 4.2 use `DocumentBuilder.resetToState(DocumentState.Changed)` instead
       * TODO remove this for the next major release
       */
      invalidateDocument(uri) {
        const uriString = uri.toString();
        const langiumDoc = this.documentTrie.find(uriString);
        if (langiumDoc) {
          this.documentBuilder().resetToState(langiumDoc, DocumentState.Changed);
        }
        return langiumDoc;
      }
      deleteDocument(uri) {
        const uriString = uri.toString();
        const langiumDoc = this.documentTrie.find(uriString);
        if (langiumDoc) {
          langiumDoc.state = DocumentState.Changed;
          this.documentTrie.delete(uriString);
        }
        return langiumDoc;
      }
      deleteDocuments(folder) {
        const uriString = folder.toString();
        const langiumDocs = this.documentTrie.findAll(uriString);
        for (const langiumDoc of langiumDocs) {
          langiumDoc.state = DocumentState.Changed;
        }
        this.documentTrie.delete(uriString);
        return langiumDocs;
      }
    }
    const RefResolving = Symbol("RefResolving");
    class DefaultLinker {
      constructor(services) {
        this.reflection = services.shared.AstReflection;
        this.langiumDocuments = () => services.shared.workspace.LangiumDocuments;
        this.scopeProvider = services.references.ScopeProvider;
        this.astNodeLocator = services.workspace.AstNodeLocator;
        this.profiler = services.shared.profilers.LangiumProfiler;
        this.languageId = services.LanguageMetaData.languageId;
      }
      async link(document, cancelToken = cancellationExports.CancellationToken.None) {
        if (this.profiler?.isActive("linking")) {
          const task = this.profiler.createTask("linking", this.languageId);
          task.start();
          try {
            for (const node2 of streamAst(document.parseResult.value)) {
              await interruptAndCheck(cancelToken);
              streamReferences(node2).forEach((ref) => {
                const name = `${node2.$type}:${ref.property}`;
                task.startSubTask(name);
                try {
                  this.doLink(ref, document);
                } finally {
                  task.stopSubTask(name);
                }
              });
            }
          } finally {
            task.stop();
          }
        } else {
          for (const node2 of streamAst(document.parseResult.value)) {
            await interruptAndCheck(cancelToken);
            streamReferences(node2).forEach((ref) => this.doLink(ref, document));
          }
        }
      }
      doLink(refInfo, document) {
        const ref = refInfo.reference;
        if ("_ref" in ref && ref._ref === void 0) {
          ref._ref = RefResolving;
          try {
            const description = this.getCandidate(refInfo);
            if (isLinkingError(description)) {
              ref._ref = description;
            } else {
              ref._nodeDescription = description;
              const linkedNode = this.loadAstNode(description);
              ref._ref = linkedNode ?? this.createLinkingError(refInfo, description);
            }
          } catch (err) {
            console.error(`An error occurred while resolving reference to '${ref.$refText}':`, err);
            const errorMessage = err.message ?? String(err);
            ref._ref = {
              info: refInfo,
              message: `An error occurred while resolving reference to '${ref.$refText}': ${errorMessage}`
            };
          }
          document.references.push(ref);
        } else if ("_items" in ref && ref._items === void 0) {
          ref._items = RefResolving;
          try {
            const descriptions = this.getCandidates(refInfo);
            const items = [];
            if (isLinkingError(descriptions)) {
              ref._linkingError = descriptions;
            } else {
              for (const description of descriptions) {
                const linkedNode = this.loadAstNode(description);
                if (linkedNode) {
                  items.push({ ref: linkedNode, $nodeDescription: description });
                }
              }
            }
            ref._items = items;
          } catch (err) {
            ref._linkingError = {
              info: refInfo,
              message: `An error occurred while resolving reference to '${ref.$refText}': ${err}`
            };
            ref._items = [];
          }
          document.references.push(ref);
        }
      }
      unlink(document) {
        for (const ref of document.references) {
          if ("_ref" in ref) {
            ref._ref = void 0;
            delete ref._nodeDescription;
          } else if ("_items" in ref) {
            ref._items = void 0;
            delete ref._linkingError;
          }
        }
        document.references = [];
      }
      getCandidate(refInfo) {
        const scope = this.scopeProvider.getScope(refInfo);
        const description = scope.getElement(refInfo.reference.$refText);
        return description ?? this.createLinkingError(refInfo);
      }
      getCandidates(refInfo) {
        const scope = this.scopeProvider.getScope(refInfo);
        const descriptions = scope.getElements(refInfo.reference.$refText).distinct((desc) => `${desc.documentUri}#${desc.path}`).toArray();
        return descriptions.length > 0 ? descriptions : this.createLinkingError(refInfo);
      }
      buildReference(node2, property2, refNode, refText) {
        const linker = this;
        const reference = {
          $refNode: refNode,
          $refText: refText,
          _ref: void 0,
          get ref() {
            if (isAstNode(this._ref)) {
              return this._ref;
            } else if (isAstNodeDescription(this._nodeDescription)) {
              const linkedNode = linker.loadAstNode(this._nodeDescription);
              this._ref = linkedNode ?? linker.createLinkingError({ reference, container: node2, property: property2 }, this._nodeDescription);
            } else if (this._ref === void 0) {
              this._ref = RefResolving;
              const document = findRootNode(node2).$document;
              const refData = linker.getLinkedNode({ reference, container: node2, property: property2 });
              if (refData.error && document && document.state < DocumentState.ComputedScopes) {
                return this._ref = void 0;
              }
              this._ref = refData.node ?? refData.error;
              this._nodeDescription = refData.descr;
              document?.references.push(this);
            } else if (this._ref === RefResolving) {
              linker.throwCyclicReferenceError(node2, property2, refText);
            }
            return isAstNode(this._ref) ? this._ref : void 0;
          },
          get $nodeDescription() {
            return this._nodeDescription;
          },
          get error() {
            return isLinkingError(this._ref) ? this._ref : void 0;
          }
        };
        return reference;
      }
      buildMultiReference(node2, property2, refNode, refText) {
        const linker = this;
        const reference = {
          $refNode: refNode,
          $refText: refText,
          _items: void 0,
          get items() {
            if (Array.isArray(this._items)) {
              return this._items;
            } else if (this._items === void 0) {
              this._items = RefResolving;
              const document = findRootNode(node2).$document;
              const descriptions = linker.getCandidates({
                reference,
                container: node2,
                property: property2
              });
              const items = [];
              if (isLinkingError(descriptions)) {
                this._linkingError = descriptions;
              } else {
                for (const description of descriptions) {
                  const linkedNode = linker.loadAstNode(description);
                  if (linkedNode) {
                    items.push({ ref: linkedNode, $nodeDescription: description });
                  }
                }
              }
              this._items = items;
              document?.references.push(this);
            } else if (this._items === RefResolving) {
              linker.throwCyclicReferenceError(node2, property2, refText);
            }
            return Array.isArray(this._items) ? this._items : [];
          },
          get error() {
            if (this._linkingError) {
              return this._linkingError;
            }
            const refs = this.items;
            if (refs.length > 0) {
              return void 0;
            } else {
              return this._linkingError = linker.createLinkingError({ reference, container: node2, property: property2 });
            }
          }
        };
        return reference;
      }
      throwCyclicReferenceError(node2, property2, refText) {
        throw new Error(`Cyclic reference resolution detected: ${this.astNodeLocator.getAstNodePath(node2)}/${property2} (symbol '${refText}')`);
      }
      getLinkedNode(refInfo) {
        try {
          const description = this.getCandidate(refInfo);
          if (isLinkingError(description)) {
            return { error: description };
          }
          const linkedNode = this.loadAstNode(description);
          if (linkedNode) {
            return { node: linkedNode, descr: description };
          } else {
            return {
              descr: description,
              error: this.createLinkingError(refInfo, description)
            };
          }
        } catch (err) {
          console.error(`An error occurred while resolving reference to '${refInfo.reference.$refText}':`, err);
          const errorMessage = err.message ?? String(err);
          return {
            error: {
              info: refInfo,
              message: `An error occurred while resolving reference to '${refInfo.reference.$refText}': ${errorMessage}`
            }
          };
        }
      }
      loadAstNode(nodeDescription) {
        if (nodeDescription.node) {
          return nodeDescription.node;
        }
        const doc = this.langiumDocuments().getDocument(nodeDescription.documentUri);
        if (!doc) {
          return void 0;
        }
        return this.astNodeLocator.getAstNode(doc.parseResult.value, nodeDescription.path);
      }
      createLinkingError(refInfo, targetDescription) {
        const document = findRootNode(refInfo.container).$document;
        if (document && document.state < DocumentState.ComputedScopes) {
          console.warn(`Attempted reference resolution before document reached ComputedScopes state (${document.uri}).`);
        }
        const referenceType = this.reflection.getReferenceType(refInfo);
        return {
          info: refInfo,
          message: `Could not resolve reference to ${referenceType} named '${refInfo.reference.$refText}'.`,
          targetDescription
        };
      }
    }
    function isNamed(node2) {
      return typeof node2.name === "string";
    }
    class DefaultNameProvider {
      getName(node2) {
        if (isNamed(node2)) {
          return node2.name;
        }
        return void 0;
      }
      getNameNode(node2) {
        return findNodeForProperty(node2.$cstNode, "name");
      }
    }
    class DefaultReferences {
      constructor(services) {
        this.nameProvider = services.references.NameProvider;
        this.index = services.shared.workspace.IndexManager;
        this.nodeLocator = services.workspace.AstNodeLocator;
        this.documents = services.shared.workspace.LangiumDocuments;
        this.hasMultiReference = streamAst(services.Grammar).some((node2) => isCrossReference(node2) && node2.isMulti);
      }
      findDeclarations(sourceCstNode) {
        if (sourceCstNode) {
          const assignment = findAssignment(sourceCstNode);
          const nodeElem = sourceCstNode.astNode;
          if (assignment && nodeElem) {
            const reference = nodeElem[assignment.feature];
            if (isReference(reference) || isMultiReference(reference)) {
              return getReferenceNodes(reference);
            } else if (Array.isArray(reference)) {
              for (const ref of reference) {
                if ((isReference(ref) || isMultiReference(ref)) && ref.$refNode && ref.$refNode.offset <= sourceCstNode.offset && ref.$refNode.end >= sourceCstNode.end) {
                  return getReferenceNodes(ref);
                }
              }
            }
          }
          if (nodeElem) {
            const nameNode = this.nameProvider.getNameNode(nodeElem);
            if (nameNode && (nameNode === sourceCstNode || isChildNode(sourceCstNode, nameNode))) {
              return this.getSelfNodes(nodeElem);
            }
          }
        }
        return [];
      }
      /**
       * Returns all self-references for the specified node.
       * Since the node can be part of a multi-reference, this method returns all nodes that are part of the same multi-reference.
       */
      getSelfNodes(node2) {
        if (!this.hasMultiReference) {
          return [node2];
        } else {
          const references = this.index.findAllReferences(node2, this.nodeLocator.getAstNodePath(node2));
          const headNode = this.getNodeFromReferenceDescription(references.head());
          if (headNode) {
            for (const ref of streamReferences(headNode)) {
              if (isMultiReference(ref.reference) && ref.reference.items.some((item) => item.ref === node2)) {
                return ref.reference.items.map((item) => item.ref);
              }
            }
          }
          return [node2];
        }
      }
      getNodeFromReferenceDescription(ref) {
        if (!ref) {
          return void 0;
        }
        const doc = this.documents.getDocument(ref.sourceUri);
        if (doc) {
          return this.nodeLocator.getAstNode(doc.parseResult.value, ref.sourcePath);
        }
        return void 0;
      }
      findDeclarationNodes(sourceCstNode) {
        const astNodes = this.findDeclarations(sourceCstNode);
        const cstNodes = [];
        for (const astNode of astNodes) {
          const cstNode = this.nameProvider.getNameNode(astNode) ?? astNode.$cstNode;
          if (cstNode) {
            cstNodes.push(cstNode);
          }
        }
        return cstNodes;
      }
      findReferences(targetNode, options) {
        const refs = [];
        if (options.includeDeclaration) {
          refs.push(...this.getSelfReferences(targetNode));
        }
        let indexReferences = this.index.findAllReferences(targetNode, this.nodeLocator.getAstNodePath(targetNode));
        if (options.documentUri) {
          indexReferences = indexReferences.filter((ref) => UriUtils.equals(ref.sourceUri, options.documentUri));
        }
        refs.push(...indexReferences);
        return stream(refs);
      }
      getSelfReferences(targetNode) {
        const selfNodes = this.getSelfNodes(targetNode);
        const references = [];
        for (const selfNode of selfNodes) {
          const nameNode = this.nameProvider.getNameNode(selfNode);
          if (nameNode) {
            const doc = getDocument(selfNode);
            const path = this.nodeLocator.getAstNodePath(selfNode);
            references.push({
              sourceUri: doc.uri,
              sourcePath: path,
              targetUri: doc.uri,
              targetPath: path,
              segment: toDocumentSegment(nameNode),
              local: true
            });
          }
        }
        return references;
      }
    }
    class MultiMap {
      constructor(elements) {
        this.map = /* @__PURE__ */ new Map();
        if (elements) {
          for (const [key, value] of elements) {
            this.add(key, value);
          }
        }
      }
      /**
       * The total number of values in the multimap.
       */
      get size() {
        return Reduction.sum(stream(this.map.values()).map((a2) => a2.length));
      }
      /**
       * Clear all entries in the multimap.
       */
      clear() {
        this.map.clear();
      }
      /**
       * Operates differently depending on whether a `value` is given:
       *  * With a value, this method deletes the specific key / value pair from the multimap.
       *  * Without a value, all values associated with the given key are deleted.
       *
       * @returns `true` if a value existed and has been removed, or `false` if the specified
       *     key / value does not exist.
       */
      delete(key, value) {
        if (value === void 0) {
          return this.map.delete(key);
        } else {
          const values = this.map.get(key);
          if (values) {
            const index = values.indexOf(value);
            if (index >= 0) {
              if (values.length === 1) {
                this.map.delete(key);
              } else {
                values.splice(index, 1);
              }
              return true;
            }
          }
          return false;
        }
      }
      /**
       * Returns an array of all values associated with the given key. If no value exists,
       * an empty array is returned.
       *
       * _Note:_ The returned array is assumed not to be modified. Use the `set` method to add a
       * value and `delete` to remove a value from the multimap.
       */
      get(key) {
        return this.map.get(key) ?? [];
      }
      /**
       * Returns a stream of all values associated with the given key. If no value exists,
       * {@link EMPTY_STREAM} is returned.
       */
      getStream(key) {
        const values = this.map.get(key);
        return values ? stream(values) : EMPTY_STREAM;
      }
      /**
       * Operates differently depending on whether a `value` is given:
       *  * With a value, this method returns `true` if the specific key / value pair is present in the multimap.
       *  * Without a value, this method returns `true` if the given key is present in the multimap.
       */
      has(key, value) {
        if (value === void 0) {
          return this.map.has(key);
        } else {
          const values = this.map.get(key);
          if (values) {
            return values.indexOf(value) >= 0;
          }
          return false;
        }
      }
      /**
       * Add the given key / value pair to the multimap.
       */
      add(key, value) {
        if (this.map.has(key)) {
          this.map.get(key).push(value);
        } else {
          this.map.set(key, [value]);
        }
        return this;
      }
      /**
       * Add the given set of key / value pairs to the multimap.
       */
      addAll(key, values) {
        if (this.map.has(key)) {
          this.map.get(key).push(...values);
        } else {
          this.map.set(key, Array.from(values));
        }
        return this;
      }
      /**
       * Invokes the given callback function for every key / value pair in the multimap.
       */
      forEach(callbackfn) {
        this.map.forEach((array, key) => array.forEach((value) => callbackfn(value, key, this)));
      }
      /**
       * Returns an iterator of key, value pairs for every entry in the map.
       */
      [Symbol.iterator]() {
        return this.entries().iterator();
      }
      /**
       * Returns a stream of key, value pairs for every entry in the map.
       */
      entries() {
        return stream(this.map.entries()).flatMap(([key, array]) => array.map((value) => [key, value]));
      }
      /**
       * Returns a stream of keys in the map.
       */
      keys() {
        return stream(this.map.keys());
      }
      /**
       * Returns a stream of values in the map.
       */
      values() {
        return stream(this.map.values()).flat();
      }
      /**
       * Returns a stream of key, value set pairs for every key in the map.
       */
      entriesGroupedByKey() {
        return stream(this.map.entries());
      }
    }
    class BiMap {
      get size() {
        return this.map.size;
      }
      constructor(elements) {
        this.map = /* @__PURE__ */ new Map();
        this.inverse = /* @__PURE__ */ new Map();
        if (elements) {
          for (const [key, value] of elements) {
            this.set(key, value);
          }
        }
      }
      clear() {
        this.map.clear();
        this.inverse.clear();
      }
      set(key, value) {
        this.map.set(key, value);
        this.inverse.set(value, key);
        return this;
      }
      get(key) {
        return this.map.get(key);
      }
      getKey(value) {
        return this.inverse.get(value);
      }
      delete(key) {
        const value = this.map.get(key);
        if (value !== void 0) {
          this.map.delete(key);
          this.inverse.delete(value);
          return true;
        }
        return false;
      }
    }
    class DefaultScopeComputation {
      constructor(services) {
        this.nameProvider = services.references.NameProvider;
        this.descriptions = services.workspace.AstNodeDescriptionProvider;
      }
      async collectExportedSymbols(document, cancelToken = cancellationExports.CancellationToken.None) {
        return this.collectExportedSymbolsForNode(document.parseResult.value, document, void 0, cancelToken);
      }
      /**
       * Creates {@link AstNodeDescription AstNodeDescriptions} for the given {@link AstNode parentNode} and its children.
       * The list of children to be considered is determined by the function parameter {@link children}.
       * By default only the direct children of {@link parentNode} are visited, nested nodes are not exported.
       *
       * @param parentNode AST node to be exported, i.e., of which an {@link AstNodeDescription} shall be added to the returned list.
       * @param document The document containing the AST node to be exported.
       * @param children A function called with {@link parentNode} as single argument and returning an {@link Iterable} supplying the children to be visited, which must be directly or transitively contained in {@link parentNode}.
       * @param cancelToken Indicates when to cancel the current operation.
       * @throws `OperationCancelled` if a user action occurs during execution.
       * @returns A list of {@link AstNodeDescription AstNodeDescriptions} to be published to index.
       */
      async collectExportedSymbolsForNode(parentNode, document, children = streamContents, cancelToken = cancellationExports.CancellationToken.None) {
        const exports2 = [];
        this.addExportedSymbol(parentNode, exports2, document);
        for (const node2 of children(parentNode)) {
          await interruptAndCheck(cancelToken);
          this.addExportedSymbol(node2, exports2, document);
        }
        return exports2;
      }
      /**
       * Adds a single node to the list of exports if it has a name. Override this method to change how
       * symbols are exported, e.g. by modifying their exported name.
       */
      addExportedSymbol(node2, exports2, document) {
        const name = this.nameProvider.getName(node2);
        if (name) {
          exports2.push(this.descriptions.createDescription(node2, name, document));
        }
      }
      // --- local symbols gathering ---
      async collectLocalSymbols(document, cancelToken = cancellationExports.CancellationToken.None) {
        const rootNode = document.parseResult.value;
        const symbols = new MultiMap();
        for (const node2 of streamAllContents(rootNode)) {
          await interruptAndCheck(cancelToken);
          this.addLocalSymbol(node2, document, symbols);
        }
        return symbols;
      }
      /**
       * Adds a single node to the local symbols of its containing document if it has a name.
       * The default implementation makes the node visible in the subtree of its container if it does have a container.
       * Override this method to change this, e.g. by increasing the visibility to a higher level in the AST.
       */
      addLocalSymbol(node2, document, symbols) {
        const container = node2.$container;
        if (container) {
          const name = this.nameProvider.getName(node2);
          if (name) {
            symbols.add(container, this.descriptions.createDescription(node2, name, document));
          }
        }
      }
    }
    class StreamScope {
      constructor(elements, outerScope, options) {
        this.elements = elements;
        this.outerScope = outerScope;
        this.caseInsensitive = options?.caseInsensitive ?? false;
        this.concatOuterScope = options?.concatOuterScope ?? true;
      }
      getAllElements() {
        if (this.outerScope) {
          return this.elements.concat(this.outerScope.getAllElements());
        } else {
          return this.elements;
        }
      }
      getElement(name) {
        const lowerCaseName = this.caseInsensitive ? name.toLowerCase() : name;
        const local = this.caseInsensitive ? this.elements.find((e) => e.name.toLowerCase() === lowerCaseName) : this.elements.find((e) => e.name === name);
        if (local) {
          return local;
        }
        if (this.outerScope) {
          return this.outerScope.getElement(name);
        }
        return void 0;
      }
      getElements(name) {
        const lowerCaseName = this.caseInsensitive ? name.toLowerCase() : name;
        const local = this.caseInsensitive ? this.elements.filter((e) => e.name.toLowerCase() === lowerCaseName) : this.elements.filter((e) => e.name === name);
        if ((this.concatOuterScope || local.isEmpty()) && this.outerScope) {
          return local.concat(this.outerScope.getElements(name));
        } else {
          return local;
        }
      }
    }
    class MultiMapScope {
      constructor(elements, outerScope, options) {
        this.elements = new MultiMap();
        this.caseInsensitive = options?.caseInsensitive ?? false;
        this.concatOuterScope = options?.concatOuterScope ?? true;
        for (const element of elements) {
          const name = this.caseInsensitive ? element.name.toLowerCase() : element.name;
          this.elements.add(name, element);
        }
        this.outerScope = outerScope;
      }
      getElement(name) {
        const localName = this.caseInsensitive ? name.toLowerCase() : name;
        const local = this.elements.get(localName)[0];
        if (local) {
          return local;
        }
        if (this.outerScope) {
          return this.outerScope.getElement(name);
        }
        return void 0;
      }
      getElements(name) {
        const localName = this.caseInsensitive ? name.toLowerCase() : name;
        const local = this.elements.get(localName);
        if ((this.concatOuterScope || local.length === 0) && this.outerScope) {
          return stream(local).concat(this.outerScope.getElements(name));
        } else {
          return stream(local);
        }
      }
      getAllElements() {
        let elementStream = stream(this.elements.values());
        if (this.outerScope) {
          elementStream = elementStream.concat(this.outerScope.getAllElements());
        }
        return elementStream;
      }
    }
    class DisposableCache {
      constructor() {
        this.toDispose = [];
        this.isDisposed = false;
      }
      onDispose(disposable2) {
        this.toDispose.push(disposable2);
      }
      dispose() {
        this.throwIfDisposed();
        this.clear();
        this.isDisposed = true;
        this.toDispose.forEach((disposable2) => disposable2.dispose());
      }
      throwIfDisposed() {
        if (this.isDisposed) {
          throw new Error("This cache has already been disposed");
        }
      }
    }
    class SimpleCache extends DisposableCache {
      constructor() {
        super(...arguments);
        this.cache = /* @__PURE__ */ new Map();
      }
      has(key) {
        this.throwIfDisposed();
        return this.cache.has(key);
      }
      set(key, value) {
        this.throwIfDisposed();
        this.cache.set(key, value);
      }
      get(key, provider) {
        this.throwIfDisposed();
        if (this.cache.has(key)) {
          return this.cache.get(key);
        } else if (provider) {
          const value = provider();
          this.cache.set(key, value);
          return value;
        } else {
          return void 0;
        }
      }
      delete(key) {
        this.throwIfDisposed();
        return this.cache.delete(key);
      }
      clear() {
        this.throwIfDisposed();
        this.cache.clear();
      }
    }
    class ContextCache extends DisposableCache {
      constructor(converter) {
        super();
        this.cache = /* @__PURE__ */ new Map();
        this.converter = converter ?? ((value) => value);
      }
      has(contextKey, key) {
        this.throwIfDisposed();
        return this.cacheForContext(contextKey).has(key);
      }
      set(contextKey, key, value) {
        this.throwIfDisposed();
        this.cacheForContext(contextKey).set(key, value);
      }
      get(contextKey, key, provider) {
        this.throwIfDisposed();
        const contextCache = this.cacheForContext(contextKey);
        if (contextCache.has(key)) {
          return contextCache.get(key);
        } else if (provider) {
          const value = provider();
          contextCache.set(key, value);
          return value;
        } else {
          return void 0;
        }
      }
      delete(contextKey, key) {
        this.throwIfDisposed();
        return this.cacheForContext(contextKey).delete(key);
      }
      clear(contextKey) {
        this.throwIfDisposed();
        if (contextKey) {
          const mapKey = this.converter(contextKey);
          this.cache.delete(mapKey);
        } else {
          this.cache.clear();
        }
      }
      cacheForContext(contextKey) {
        const mapKey = this.converter(contextKey);
        let documentCache = this.cache.get(mapKey);
        if (!documentCache) {
          documentCache = /* @__PURE__ */ new Map();
          this.cache.set(mapKey, documentCache);
        }
        return documentCache;
      }
    }
    class WorkspaceCache extends SimpleCache {
      /**
       * Creates a new workspace cache.
       *
       * @param sharedServices Service container instance to hook into document lifecycle events.
       * @param state Optional document state on which the cache should evict.
       * If not provided, the cache will evict on `DocumentBuilder#onUpdate`.
       * *Deleted* documents are considered in both cases.
       */
      constructor(sharedServices, state) {
        super();
        if (state) {
          this.toDispose.push(sharedServices.workspace.DocumentBuilder.onBuildPhase(state, () => {
            this.clear();
          }));
          this.toDispose.push(sharedServices.workspace.DocumentBuilder.onUpdate((_changed, deleted) => {
            if (deleted.length > 0) {
              this.clear();
            }
          }));
        } else {
          this.toDispose.push(sharedServices.workspace.DocumentBuilder.onUpdate(() => {
            this.clear();
          }));
        }
      }
    }
    class DefaultScopeProvider {
      constructor(services) {
        this.reflection = services.shared.AstReflection;
        this.nameProvider = services.references.NameProvider;
        this.descriptions = services.workspace.AstNodeDescriptionProvider;
        this.indexManager = services.shared.workspace.IndexManager;
        this.globalScopeCache = new WorkspaceCache(services.shared);
      }
      getScope(context) {
        const scopes = [];
        const referenceType = this.reflection.getReferenceType(context);
        const localSymbols = getDocument(context.container).localSymbols;
        if (localSymbols) {
          let currentNode = context.container;
          do {
            if (localSymbols.has(currentNode)) {
              scopes.push(localSymbols.getStream(currentNode).filter((desc) => this.reflection.isSubtype(desc.type, referenceType)));
            }
            currentNode = currentNode.$container;
          } while (currentNode);
        }
        let result = this.getGlobalScope(referenceType, context);
        for (let i = scopes.length - 1; i >= 0; i--) {
          result = this.createScope(scopes[i], result);
        }
        return result;
      }
      /**
       * Create a scope for the given collection of AST node descriptions.
       */
      createScope(elements, outerScope, options) {
        return new StreamScope(stream(elements), outerScope, options);
      }
      /**
       * Create a scope for the given collection of AST nodes, which need to be transformed into respective
       * descriptions first. This is done using the `NameProvider` and `AstNodeDescriptionProvider` services.
       */
      createScopeForNodes(elements, outerScope, options) {
        const s = stream(elements).map((e) => {
          const name = this.nameProvider.getName(e);
          if (name) {
            return this.descriptions.createDescription(e, name);
          }
          return void 0;
        }).nonNullable();
        return new StreamScope(s, outerScope, options);
      }
      /**
       * Create a global scope filtered for the given reference type.
       */
      getGlobalScope(referenceType, _context) {
        return this.globalScopeCache.get(referenceType, () => new MultiMapScope(this.indexManager.allElements(referenceType)));
      }
    }
    function isAstNodeWithComment(node2) {
      return typeof node2.$comment === "string";
    }
    function isIntermediateReference(obj) {
      return typeof obj === "object" && !!obj && ("$ref" in obj || "$error" in obj);
    }
    class DefaultJsonSerializer {
      constructor(services) {
        this.ignoreProperties = /* @__PURE__ */ new Set(["$container", "$containerProperty", "$containerIndex", "$document", "$cstNode"]);
        this.langiumDocuments = services.shared.workspace.LangiumDocuments;
        this.astNodeLocator = services.workspace.AstNodeLocator;
        this.nameProvider = services.references.NameProvider;
        this.commentProvider = services.documentation.CommentProvider;
      }
      serialize(node2, options) {
        const serializeOptions = options ?? {};
        const specificReplacer = options?.replacer;
        const defaultReplacer = (key, value) => this.replacer(key, value, serializeOptions);
        const replacer = specificReplacer ? (key, value) => specificReplacer(key, value, defaultReplacer) : defaultReplacer;
        try {
          this.currentDocument = getDocument(node2);
          return JSON.stringify(node2, replacer, options?.space);
        } finally {
          this.currentDocument = void 0;
        }
      }
      deserialize(content, options) {
        const deserializeOptions = options ?? {};
        const root2 = JSON.parse(content);
        this.linkNode(root2, root2, deserializeOptions);
        return root2;
      }
      replacer(key, value, { refText, sourceText, textRegions, comments, uriConverter }) {
        if (this.ignoreProperties.has(key)) {
          return void 0;
        } else if (isReference(value)) {
          const refValue = value.ref;
          const $refText = refText ? value.$refText : void 0;
          if (refValue) {
            const targetDocument = getDocument(refValue);
            let targetUri = "";
            if (this.currentDocument && this.currentDocument !== targetDocument) {
              if (uriConverter) {
                targetUri = uriConverter(targetDocument.uri, refValue);
              } else {
                targetUri = targetDocument.uri.toString();
              }
            }
            const targetPath = this.astNodeLocator.getAstNodePath(refValue);
            return {
              $ref: `${targetUri}#${targetPath}`,
              $refText
            };
          } else {
            return {
              $error: value.error?.message ?? "Could not resolve reference",
              $refText
            };
          }
        } else if (isMultiReference(value)) {
          const $refText = refText ? value.$refText : void 0;
          const $refs = [];
          for (const item of value.items) {
            const refValue = item.ref;
            const targetDocument = getDocument(item.ref);
            let targetUri = "";
            if (this.currentDocument && this.currentDocument !== targetDocument) {
              if (uriConverter) {
                targetUri = uriConverter(targetDocument.uri, refValue);
              } else {
                targetUri = targetDocument.uri.toString();
              }
            }
            const targetPath = this.astNodeLocator.getAstNodePath(refValue);
            $refs.push(`${targetUri}#${targetPath}`);
          }
          return {
            $refs,
            $refText
          };
        } else if (isAstNode(value)) {
          let astNode = void 0;
          if (textRegions) {
            astNode = this.addAstNodeRegionWithAssignmentsTo({ ...value });
            if ((!key || value.$document) && astNode?.$textRegion) {
              astNode.$textRegion.documentURI = this.currentDocument?.uri.toString();
            }
          }
          if (sourceText && !key) {
            astNode ?? (astNode = { ...value });
            astNode.$sourceText = value.$cstNode?.text;
          }
          if (comments) {
            astNode ?? (astNode = { ...value });
            const comment = this.commentProvider.getComment(value);
            if (comment) {
              astNode.$comment = comment.replace(/\r/g, "");
            }
          }
          return astNode ?? value;
        } else {
          return value;
        }
      }
      addAstNodeRegionWithAssignmentsTo(node2) {
        const createDocumentSegment = (cstNode) => ({
          offset: cstNode.offset,
          end: cstNode.end,
          length: cstNode.length,
          range: cstNode.range
        });
        if (node2.$cstNode) {
          const textRegion = node2.$textRegion = createDocumentSegment(node2.$cstNode);
          const assignments = textRegion.assignments = {};
          Object.keys(node2).filter((key) => !key.startsWith("$")).forEach((key) => {
            const propertyAssignments = findNodesForProperty(node2.$cstNode, key).map(createDocumentSegment);
            if (propertyAssignments.length !== 0) {
              assignments[key] = propertyAssignments;
            }
          });
          return node2;
        }
        return void 0;
      }
      linkNode(node2, root2, options, container, containerProperty, containerIndex) {
        for (const [propertyName, item] of Object.entries(node2)) {
          if (Array.isArray(item)) {
            for (let index = 0; index < item.length; index++) {
              const element = item[index];
              if (isIntermediateReference(element)) {
                item[index] = this.reviveReference(node2, propertyName, root2, element, options);
              } else if (isAstNode(element)) {
                this.linkNode(element, root2, options, node2, propertyName, index);
              }
            }
          } else if (isIntermediateReference(item)) {
            node2[propertyName] = this.reviveReference(node2, propertyName, root2, item, options);
          } else if (isAstNode(item)) {
            this.linkNode(item, root2, options, node2, propertyName);
          }
        }
        const mutable = node2;
        mutable.$container = container;
        mutable.$containerProperty = containerProperty;
        mutable.$containerIndex = containerIndex;
      }
      reviveReference(container, property2, root2, reference, options) {
        let refText = reference.$refText;
        let error = reference.$error;
        let ref;
        if (reference.$ref) {
          const refNode = this.getRefNode(root2, reference.$ref, options.uriConverter);
          if (isAstNode(refNode)) {
            if (!refText) {
              refText = this.nameProvider.getName(refNode);
            }
            return {
              $refText: refText ?? "",
              ref: refNode
            };
          } else {
            error = refNode;
          }
        } else if (reference.$refs) {
          const refs = [];
          for (const refUri of reference.$refs) {
            const refNode = this.getRefNode(root2, refUri, options.uriConverter);
            if (isAstNode(refNode)) {
              refs.push({ ref: refNode });
            }
          }
          if (refs.length === 0) {
            ref = {
              $refText: refText ?? "",
              items: refs
            };
            error ?? (error = "Could not resolve multi-reference");
          } else {
            return {
              $refText: refText ?? "",
              items: refs
            };
          }
        }
        if (error) {
          ref ?? (ref = {
            $refText: refText ?? "",
            ref: void 0
          });
          ref.error = {
            info: {
              container,
              property: property2,
              reference: ref
            },
            message: error
          };
          return ref;
        } else {
          return void 0;
        }
      }
      getRefNode(root2, uri, uriConverter) {
        try {
          const fragmentIndex = uri.indexOf("#");
          if (fragmentIndex === 0) {
            const node3 = this.astNodeLocator.getAstNode(root2, uri.substring(1));
            if (!node3) {
              return "Could not resolve path: " + uri;
            }
            return node3;
          }
          if (fragmentIndex < 0) {
            const documentUri2 = uriConverter ? uriConverter(uri) : URI$1.parse(uri);
            const document2 = this.langiumDocuments.getDocument(documentUri2);
            if (!document2) {
              return "Could not find document for URI: " + uri;
            }
            return document2.parseResult.value;
          }
          const documentUri = uriConverter ? uriConverter(uri.substring(0, fragmentIndex)) : URI$1.parse(uri.substring(0, fragmentIndex));
          const document = this.langiumDocuments.getDocument(documentUri);
          if (!document) {
            return "Could not find document for URI: " + uri;
          }
          if (fragmentIndex === uri.length - 1) {
            return document.parseResult.value;
          }
          const node2 = this.astNodeLocator.getAstNode(document.parseResult.value, uri.substring(fragmentIndex + 1));
          if (!node2) {
            return "Could not resolve URI: " + uri;
          }
          return node2;
        } catch (err) {
          return String(err);
        }
      }
    }
    class DefaultServiceRegistry {
      /**
       * @deprecated Since 3.1.0. Use the new `fileExtensionMap` (or `languageIdMap`) property instead.
       */
      get map() {
        return this.fileExtensionMap;
      }
      constructor(services) {
        this.languageIdMap = /* @__PURE__ */ new Map();
        this.fileExtensionMap = /* @__PURE__ */ new Map();
        this.fileNameMap = /* @__PURE__ */ new Map();
        this.textDocuments = services?.workspace.TextDocuments;
      }
      register(language) {
        const data = language.LanguageMetaData;
        for (const ext of data.fileExtensions) {
          if (this.fileExtensionMap.has(ext)) {
            console.warn(`The file extension ${ext} is used by multiple languages. It is now assigned to '${data.languageId}'.`);
          }
          this.fileExtensionMap.set(ext, language);
        }
        if (data.fileNames) {
          for (const name of data.fileNames) {
            if (this.fileNameMap.has(name)) {
              console.warn(`The file name ${name} is used by multiple languages. It is now assigned to '${data.languageId}'.`);
            }
            this.fileNameMap.set(name, language);
          }
        }
        this.languageIdMap.set(data.languageId, language);
      }
      getServices(uri) {
        if (this.languageIdMap.size === 0) {
          throw new Error("The service registry is empty. Use `register` to register the services of a language.");
        }
        const languageId = this.textDocuments?.get(uri)?.languageId;
        if (languageId !== void 0) {
          const services2 = this.languageIdMap.get(languageId);
          if (services2) {
            return services2;
          }
        }
        const ext = UriUtils.extname(uri);
        const name = UriUtils.basename(uri);
        const services = this.fileNameMap.get(name) ?? this.fileExtensionMap.get(ext);
        if (!services) {
          if (languageId) {
            throw new Error(`The service registry contains no services for the extension '${ext}' for language '${languageId}'.`);
          } else {
            throw new Error(`The service registry contains no services for the extension '${ext}'.`);
          }
        }
        return services;
      }
      hasServices(uri) {
        try {
          this.getServices(uri);
          return true;
        } catch {
          return false;
        }
      }
      get all() {
        return Array.from(this.languageIdMap.values());
      }
    }
    var Module;
    (function(Module2) {
      Module2.merge = (m1, m2) => _merge(_merge({}, m1), m2);
    })(Module || (Module = {}));
    function inject(module1, module2, module3, module4, module5, module6, module7, module8, module9) {
      const module10 = [module1, module2, module3, module4, module5, module6, module7, module8, module9].reduce(_merge, {});
      return _inject(module10);
    }
    const isProxy = Symbol("isProxy");
    function eagerLoad(item) {
      if (item && item[isProxy]) {
        for (const value of Object.values(item)) {
          eagerLoad(value);
        }
      }
      return item;
    }
    function _inject(module2, injector) {
      const proxy = new Proxy({}, {
        deleteProperty: () => false,
        set: () => {
          throw new Error("Cannot set property on injected service container");
        },
        get: (obj, prop) => {
          if (prop === isProxy) {
            return true;
          } else {
            return _resolve(obj, prop, module2, injector || proxy);
          }
        },
        getOwnPropertyDescriptor: (obj, prop) => (_resolve(obj, prop, module2, injector || proxy), Object.getOwnPropertyDescriptor(obj, prop)),
        // used by for..in
        has: (_2, prop) => prop in module2,
        // used by ..in..
        ownKeys: () => [...Object.getOwnPropertyNames(module2)]
        // used by for..in
      });
      return proxy;
    }
    const __requested__ = Symbol();
    function _resolve(obj, prop, module2, injector) {
      if (prop in obj) {
        if (obj[prop] instanceof Error) {
          throw new Error("Construction failure. Please make sure that your dependencies are constructable. Cause: " + obj[prop]);
        }
        if (obj[prop] === __requested__) {
          throw new Error('Cycle detected. Please make "' + String(prop) + '" lazy. Visit https://langium.org/docs/reference/configuration-services/#resolving-cyclic-dependencies');
        }
        return obj[prop];
      } else if (prop in module2) {
        const value = module2[prop];
        obj[prop] = __requested__;
        try {
          obj[prop] = typeof value === "function" ? value(injector) : _inject(value, injector);
        } catch (error) {
          obj[prop] = error instanceof Error ? error : void 0;
          throw error;
        }
        return obj[prop];
      } else {
        return void 0;
      }
    }
    function _merge(target, source) {
      if (source) {
        for (const [key, sourceValue] of Object.entries(source)) {
          if (sourceValue !== void 0 && sourceValue !== null) {
            if (typeof sourceValue === "object") {
              const targetValue = target[key];
              if (typeof targetValue === "object" && targetValue !== null) {
                target[key] = _merge(targetValue, sourceValue);
              } else {
                target[key] = _merge({}, sourceValue);
              }
            } else {
              target[key] = sourceValue;
            }
          }
        }
      }
      return target;
    }
    class DefaultCommentProvider {
      constructor(services) {
        this.grammarConfig = () => services.parser.GrammarConfig;
      }
      getComment(node2) {
        if (isAstNodeWithComment(node2)) {
          return node2.$comment;
        }
        return findCommentNode(node2.$cstNode, this.grammarConfig().multilineCommentRules)?.text;
      }
    }
    function parseJSDoc(node2, start, options) {
      let opts;
      let position;
      if (typeof node2 === "string") {
        position = start;
        opts = options;
      } else {
        position = node2.range.start;
        opts = start;
      }
      if (!position) {
        position = Position.create(0, 0);
      }
      const lines = getLines(node2);
      const normalizedOptions = normalizeOptions(opts);
      const tokens2 = tokenize({
        lines,
        position,
        options: normalizedOptions
      });
      return parseJSDocComment({
        index: 0,
        tokens: tokens2,
        position
      });
    }
    function isJSDoc(node2, options) {
      const normalizedOptions = normalizeOptions(options);
      const lines = getLines(node2);
      if (lines.length === 0) {
        return false;
      }
      const first2 = lines[0];
      const last = lines[lines.length - 1];
      const firstRegex = normalizedOptions.start;
      const lastRegex = normalizedOptions.end;
      return Boolean(firstRegex?.exec(first2)) && Boolean(lastRegex?.exec(last));
    }
    function getLines(node2) {
      let content = "";
      if (typeof node2 === "string") {
        content = node2;
      } else {
        content = node2.text;
      }
      const lines = content.split(NEWLINE_REGEXP);
      return lines;
    }
    const tagRegex = /\s*(@([\p{L}][\p{L}\p{N}]*)?)/uy;
    const inlineTagRegex = /\{(@[\p{L}][\p{L}\p{N}]*)(\s*)([^\r\n}]+)?\}/gu;
    function tokenize(context) {
      const tokens2 = [];
      let currentLine = context.position.line;
      let currentCharacter = context.position.character;
      for (let i = 0; i < context.lines.length; i++) {
        const first2 = i === 0;
        const last = i === context.lines.length - 1;
        let line = context.lines[i];
        let index = 0;
        if (first2 && context.options.start) {
          const match = context.options.start?.exec(line);
          if (match) {
            index = match.index + match[0].length;
          }
        } else {
          const match = context.options.line?.exec(line);
          if (match) {
            index = match.index + match[0].length;
          }
        }
        if (last) {
          const match = context.options.end?.exec(line);
          if (match) {
            line = line.substring(0, match.index);
          }
        }
        line = line.substring(0, lastCharacter(line));
        const whitespaceEnd = skipWhitespace(line, index);
        if (whitespaceEnd >= line.length) {
          if (tokens2.length > 0) {
            const position = Position.create(currentLine, currentCharacter);
            tokens2.push({
              type: "break",
              content: "",
              range: Range.create(position, position)
            });
          }
        } else {
          tagRegex.lastIndex = index;
          const tagMatch = tagRegex.exec(line);
          if (tagMatch) {
            const fullMatch = tagMatch[0];
            const value = tagMatch[1];
            const start = Position.create(currentLine, currentCharacter + index);
            const end = Position.create(currentLine, currentCharacter + index + fullMatch.length);
            tokens2.push({
              type: "tag",
              content: value,
              range: Range.create(start, end)
            });
            index += fullMatch.length;
            index = skipWhitespace(line, index);
          }
          if (index < line.length) {
            const rest = line.substring(index);
            const inlineTagMatches = Array.from(rest.matchAll(inlineTagRegex));
            tokens2.push(...buildInlineTokens(inlineTagMatches, rest, currentLine, currentCharacter + index));
          }
        }
        currentLine++;
        currentCharacter = 0;
      }
      if (tokens2.length > 0 && tokens2[tokens2.length - 1].type === "break") {
        return tokens2.slice(0, -1);
      }
      return tokens2;
    }
    function buildInlineTokens(tags, line, lineIndex, characterIndex) {
      const tokens2 = [];
      if (tags.length === 0) {
        const start = Position.create(lineIndex, characterIndex);
        const end = Position.create(lineIndex, characterIndex + line.length);
        tokens2.push({
          type: "text",
          content: line,
          range: Range.create(start, end)
        });
      } else {
        let lastIndex = 0;
        for (const match of tags) {
          const matchIndex = match.index;
          const startContent = line.substring(lastIndex, matchIndex);
          if (startContent.length > 0) {
            tokens2.push({
              type: "text",
              content: line.substring(lastIndex, matchIndex),
              range: Range.create(Position.create(lineIndex, lastIndex + characterIndex), Position.create(lineIndex, matchIndex + characterIndex))
            });
          }
          let offset = startContent.length + 1;
          const tagName = match[1];
          tokens2.push({
            type: "inline-tag",
            content: tagName,
            range: Range.create(Position.create(lineIndex, lastIndex + offset + characterIndex), Position.create(lineIndex, lastIndex + offset + tagName.length + characterIndex))
          });
          offset += tagName.length;
          if (match.length === 4) {
            offset += match[2].length;
            const value = match[3];
            tokens2.push({
              type: "text",
              content: value,
              range: Range.create(Position.create(lineIndex, lastIndex + offset + characterIndex), Position.create(lineIndex, lastIndex + offset + value.length + characterIndex))
            });
          } else {
            tokens2.push({
              type: "text",
              content: "",
              range: Range.create(Position.create(lineIndex, lastIndex + offset + characterIndex), Position.create(lineIndex, lastIndex + offset + characterIndex))
            });
          }
          lastIndex = matchIndex + match[0].length;
        }
        const endContent = line.substring(lastIndex);
        if (endContent.length > 0) {
          tokens2.push({
            type: "text",
            content: endContent,
            range: Range.create(Position.create(lineIndex, lastIndex + characterIndex), Position.create(lineIndex, lastIndex + characterIndex + endContent.length))
          });
        }
      }
      return tokens2;
    }
    const nonWhitespaceRegex = /\S/;
    const whitespaceEndRegex = /\s*$/;
    function skipWhitespace(line, index) {
      const match = line.substring(index).match(nonWhitespaceRegex);
      if (match) {
        return index + match.index;
      } else {
        return line.length;
      }
    }
    function lastCharacter(line) {
      const match = line.match(whitespaceEndRegex);
      if (match && typeof match.index === "number") {
        return match.index;
      }
      return void 0;
    }
    function parseJSDocComment(context) {
      const startPosition = Position.create(context.position.line, context.position.character);
      if (context.tokens.length === 0) {
        return new JSDocCommentImpl([], Range.create(startPosition, startPosition));
      }
      const elements = [];
      while (context.index < context.tokens.length) {
        const element = parseJSDocElement(context, elements[elements.length - 1]);
        if (element) {
          elements.push(element);
        }
      }
      const start = elements[0]?.range.start ?? startPosition;
      const end = elements[elements.length - 1]?.range.end ?? startPosition;
      return new JSDocCommentImpl(elements, Range.create(start, end));
    }
    function parseJSDocElement(context, last) {
      const next = context.tokens[context.index];
      if (next.type === "tag") {
        return parseJSDocTag(context, false);
      } else if (next.type === "text" || next.type === "inline-tag") {
        return parseJSDocText(context);
      } else {
        appendEmptyLine(next, last);
        context.index++;
        return void 0;
      }
    }
    function appendEmptyLine(token, element) {
      if (element) {
        const line = new JSDocLineImpl("", token.range);
        if ("inlines" in element) {
          element.inlines.push(line);
        } else {
          element.content.inlines.push(line);
        }
      }
    }
    function parseJSDocText(context) {
      let token = context.tokens[context.index];
      const firstToken = token;
      let lastToken = token;
      const lines = [];
      while (token && token.type !== "break" && token.type !== "tag") {
        lines.push(parseJSDocInline(context));
        lastToken = token;
        token = context.tokens[context.index];
      }
      return new JSDocTextImpl(lines, Range.create(firstToken.range.start, lastToken.range.end));
    }
    function parseJSDocInline(context) {
      const token = context.tokens[context.index];
      if (token.type === "inline-tag") {
        return parseJSDocTag(context, true);
      } else {
        return parseJSDocLine(context);
      }
    }
    function parseJSDocTag(context, inline) {
      const tagToken = context.tokens[context.index++];
      const name = tagToken.content.substring(1);
      const nextToken = context.tokens[context.index];
      if (nextToken?.type === "text") {
        if (inline) {
          const docLine = parseJSDocLine(context);
          return new JSDocTagImpl(name, new JSDocTextImpl([docLine], docLine.range), inline, Range.create(tagToken.range.start, docLine.range.end));
        } else {
          const textDoc = parseJSDocText(context);
          return new JSDocTagImpl(name, textDoc, inline, Range.create(tagToken.range.start, textDoc.range.end));
        }
      } else {
        const range = tagToken.range;
        return new JSDocTagImpl(name, new JSDocTextImpl([], range), inline, range);
      }
    }
    function parseJSDocLine(context) {
      const token = context.tokens[context.index++];
      return new JSDocLineImpl(token.content, token.range);
    }
    function normalizeOptions(options) {
      if (!options) {
        return normalizeOptions({
          start: "/**",
          end: "*/",
          line: "*"
        });
      }
      const { start, end, line } = options;
      return {
        start: normalizeOption(start, true),
        end: normalizeOption(end, false),
        line: normalizeOption(line, true)
      };
    }
    function normalizeOption(option2, start) {
      if (typeof option2 === "string" || typeof option2 === "object") {
        const escaped = typeof option2 === "string" ? escapeRegExp(option2) : option2.source;
        if (start) {
          return new RegExp(`^\\s*${escaped}`);
        } else {
          return new RegExp(`\\s*${escaped}\\s*$`);
        }
      } else {
        return option2;
      }
    }
    class JSDocCommentImpl {
      constructor(elements, range) {
        this.elements = elements;
        this.range = range;
      }
      getTag(name) {
        return this.getAllTags().find((e) => e.name === name);
      }
      getTags(name) {
        return this.getAllTags().filter((e) => e.name === name);
      }
      getAllTags() {
        return this.elements.filter((e) => "name" in e);
      }
      toString() {
        let value = "";
        for (const element of this.elements) {
          if (value.length === 0) {
            value = element.toString();
          } else {
            const text = element.toString();
            value += fillNewlines(value) + text;
          }
        }
        return value.trim();
      }
      toMarkdown(options) {
        let value = "";
        for (const element of this.elements) {
          if (value.length === 0) {
            value = element.toMarkdown(options);
          } else {
            const text = element.toMarkdown(options);
            value += fillNewlines(value) + text;
          }
        }
        return value.trim();
      }
    }
    class JSDocTagImpl {
      constructor(name, content, inline, range) {
        this.name = name;
        this.content = content;
        this.inline = inline;
        this.range = range;
      }
      toString() {
        let text = `@${this.name}`;
        const content = this.content.toString();
        if (this.content.inlines.length === 1) {
          text = `${text} ${content}`;
        } else if (this.content.inlines.length > 1) {
          text = `${text}
${content}`;
        }
        if (this.inline) {
          return `{${text}}`;
        } else {
          return text;
        }
      }
      toMarkdown(options) {
        return options?.renderTag?.(this) ?? this.toMarkdownDefault(options);
      }
      toMarkdownDefault(options) {
        const content = this.content.toMarkdown(options);
        if (this.inline) {
          const rendered = renderInlineTag(this.name, content, options ?? {});
          if (typeof rendered === "string") {
            return rendered;
          }
        }
        let marker = "";
        if (options?.tag === "italic" || options?.tag === void 0) {
          marker = "*";
        } else if (options?.tag === "bold") {
          marker = "**";
        } else if (options?.tag === "bold-italic") {
          marker = "***";
        }
        let text = `${marker}@${this.name}${marker}`;
        if (this.content.inlines.length === 1) {
          text = `${text} — ${content}`;
        } else if (this.content.inlines.length > 1) {
          text = `${text}
${content}`;
        }
        if (this.inline) {
          return `{${text}}`;
        } else {
          return text;
        }
      }
    }
    function renderInlineTag(tag, content, options) {
      if (tag === "linkplain" || tag === "linkcode" || tag === "link") {
        const index = content.indexOf(" ");
        let display = content;
        if (index > 0) {
          const displayStart = skipWhitespace(content, index);
          display = content.substring(displayStart);
          content = content.substring(0, index);
        }
        if (tag === "linkcode" || tag === "link" && options.link === "code") {
          display = `\`${display}\``;
        }
        const renderedLink = options.renderLink?.(content, display) ?? renderLinkDefault(content, display);
        return renderedLink;
      }
      return void 0;
    }
    function renderLinkDefault(content, display) {
      try {
        URI$1.parse(content, true);
        return `[${display}](${content})`;
      } catch {
        return content;
      }
    }
    class JSDocTextImpl {
      constructor(lines, range) {
        this.inlines = lines;
        this.range = range;
      }
      toString() {
        let text = "";
        for (let i = 0; i < this.inlines.length; i++) {
          const inline = this.inlines[i];
          const next = this.inlines[i + 1];
          text += inline.toString();
          if (next && next.range.start.line > inline.range.start.line) {
            text += "\n";
          }
        }
        return text;
      }
      toMarkdown(options) {
        let text = "";
        for (let i = 0; i < this.inlines.length; i++) {
          const inline = this.inlines[i];
          const next = this.inlines[i + 1];
          text += inline.toMarkdown(options);
          if (next && next.range.start.line > inline.range.start.line) {
            text += "\n";
          }
        }
        return text;
      }
    }
    class JSDocLineImpl {
      constructor(text, range) {
        this.text = text;
        this.range = range;
      }
      toString() {
        return this.text;
      }
      toMarkdown() {
        return this.text;
      }
    }
    function fillNewlines(text) {
      if (text.endsWith("\n")) {
        return "\n";
      } else {
        return "\n\n";
      }
    }
    class JSDocDocumentationProvider {
      constructor(services) {
        this.indexManager = services.shared.workspace.IndexManager;
        this.commentProvider = services.documentation.CommentProvider;
      }
      getDocumentation(node2) {
        const comment = this.commentProvider.getComment(node2);
        if (comment && isJSDoc(comment)) {
          const parsedJSDoc = parseJSDoc(comment);
          return parsedJSDoc.toMarkdown({
            renderLink: (link, display) => {
              return this.documentationLinkRenderer(node2, link, display);
            },
            renderTag: (tag) => {
              return this.documentationTagRenderer(node2, tag);
            }
          });
        }
        return void 0;
      }
      documentationLinkRenderer(node2, name, display) {
        const description = this.findNameInLocalSymbols(node2, name) ?? this.findNameInGlobalScope(node2, name);
        if (description && description.nameSegment) {
          const line = description.nameSegment.range.start.line + 1;
          const character = description.nameSegment.range.start.character + 1;
          const uri = description.documentUri.with({ fragment: `L${line},${character}` });
          return `[${display}](${uri.toString()})`;
        } else {
          return void 0;
        }
      }
      documentationTagRenderer(_node, _tag) {
        return void 0;
      }
      findNameInLocalSymbols(node2, name) {
        const document = getDocument(node2);
        const precomputed = document.localSymbols;
        if (!precomputed) {
          return void 0;
        }
        let currentNode = node2;
        do {
          const allDescriptions = precomputed.getStream(currentNode);
          const description = allDescriptions.find((e) => e.name === name);
          if (description) {
            return description;
          }
          currentNode = currentNode.$container;
        } while (currentNode);
        return void 0;
      }
      findNameInGlobalScope(node2, name) {
        const description = this.indexManager.allElements().find((e) => e.name === name);
        return description;
      }
    }
    var eventsExports = requireEvents();
    class DefaultAsyncParser {
      constructor(services) {
        this.syncParser = services.parser.LangiumParser;
      }
      parse(text, _cancelToken) {
        return Promise.resolve(this.syncParser.parse(text));
      }
    }
    class DefaultLexerErrorMessageProvider {
      buildUnexpectedCharactersMessage(fullText, startOffset, length, line, column) {
        return defaultLexerErrorProvider.buildUnexpectedCharactersMessage(fullText, startOffset, length, line, column);
      }
      buildUnableToPopLexerModeMessage(token) {
        return defaultLexerErrorProvider.buildUnableToPopLexerModeMessage(token);
      }
    }
    const DEFAULT_TOKENIZE_OPTIONS = { mode: "full" };
    class DefaultLexer {
      constructor(services) {
        this.errorMessageProvider = services.parser.LexerErrorMessageProvider;
        this.tokenBuilder = services.parser.TokenBuilder;
        const tokens2 = this.tokenBuilder.buildTokens(services.Grammar, {
          caseInsensitive: services.LanguageMetaData.caseInsensitive
        });
        this.tokenTypes = this.toTokenTypeDictionary(tokens2);
        const lexerTokens = isTokenTypeDictionary(tokens2) ? Object.values(tokens2) : tokens2;
        const production = services.LanguageMetaData.mode === "production";
        this.chevrotainLexer = new Lexer(lexerTokens, {
          positionTracking: "full",
          skipValidations: production,
          errorMessageProvider: this.errorMessageProvider
        });
      }
      get definition() {
        return this.tokenTypes;
      }
      tokenize(text, _options = DEFAULT_TOKENIZE_OPTIONS) {
        const chevrotainResult = this.chevrotainLexer.tokenize(text);
        return {
          tokens: chevrotainResult.tokens,
          errors: chevrotainResult.errors,
          hidden: chevrotainResult.groups.hidden ?? [],
          report: this.tokenBuilder.flushLexingReport?.(text)
        };
      }
      toTokenTypeDictionary(buildTokens) {
        if (isTokenTypeDictionary(buildTokens))
          return buildTokens;
        const tokens2 = isIMultiModeLexerDefinition(buildTokens) ? Object.values(buildTokens.modes).flat() : buildTokens;
        const res = {};
        tokens2.forEach((token) => res[token.name] = token);
        return res;
      }
    }
    function isTokenTypeArray(tokenVocabulary) {
      return Array.isArray(tokenVocabulary) && (tokenVocabulary.length === 0 || "name" in tokenVocabulary[0]);
    }
    function isIMultiModeLexerDefinition(tokenVocabulary) {
      return tokenVocabulary && "modes" in tokenVocabulary && "defaultMode" in tokenVocabulary;
    }
    function isTokenTypeDictionary(tokenVocabulary) {
      return !isTokenTypeArray(tokenVocabulary) && !isIMultiModeLexerDefinition(tokenVocabulary);
    }
    class DefaultHydrator {
      constructor(services) {
        this.grammarElementIdMap = new BiMap();
        this.tokenTypeIdMap = new BiMap();
        this.grammar = services.Grammar;
        this.lexer = services.parser.Lexer;
        this.linker = services.references.Linker;
      }
      dehydrate(result) {
        return {
          lexerErrors: result.lexerErrors,
          lexerReport: result.lexerReport ? this.dehydrateLexerReport(result.lexerReport) : void 0,
          // We need to create shallow copies of the errors
          // The original errors inherit from the `Error` class, which is not transferable across worker threads
          parserErrors: result.parserErrors.map((e) => ({ ...e, message: e.message })),
          value: this.dehydrateAstNode(result.value, this.createDehyrationContext(result.value))
        };
      }
      dehydrateLexerReport(lexerReport) {
        return lexerReport;
      }
      createDehyrationContext(node2) {
        const astNodes = /* @__PURE__ */ new Map();
        const cstNodes = /* @__PURE__ */ new Map();
        for (const astNode of streamAst(node2)) {
          astNodes.set(astNode, {});
        }
        if (node2.$cstNode) {
          for (const cstNode of streamCst(node2.$cstNode)) {
            cstNodes.set(cstNode, {});
          }
        }
        return {
          astNodes,
          cstNodes
        };
      }
      dehydrateAstNode(node2, context) {
        const obj = context.astNodes.get(node2);
        obj.$type = node2.$type;
        obj.$containerIndex = node2.$containerIndex;
        obj.$containerProperty = node2.$containerProperty;
        if (node2.$cstNode !== void 0) {
          obj.$cstNode = this.dehydrateCstNode(node2.$cstNode, context);
        }
        for (const [name, value] of Object.entries(node2)) {
          if (name.startsWith("$")) {
            continue;
          }
          if (Array.isArray(value)) {
            const arr = [];
            obj[name] = arr;
            for (const item of value) {
              if (isAstNode(item)) {
                arr.push(this.dehydrateAstNode(item, context));
              } else if (isReference(item)) {
                arr.push(this.dehydrateReference(item, context));
              } else {
                arr.push(item);
              }
            }
          } else if (isAstNode(value)) {
            obj[name] = this.dehydrateAstNode(value, context);
          } else if (isReference(value)) {
            obj[name] = this.dehydrateReference(value, context);
          } else if (value !== void 0) {
            obj[name] = value;
          }
        }
        return obj;
      }
      dehydrateReference(reference, context) {
        const obj = {};
        obj.$refText = reference.$refText;
        if (reference.$refNode) {
          obj.$refNode = context.cstNodes.get(reference.$refNode);
        }
        return obj;
      }
      dehydrateCstNode(node2, context) {
        const cstNode = context.cstNodes.get(node2);
        if (isRootCstNode(node2)) {
          cstNode.fullText = node2.fullText;
        } else {
          cstNode.grammarSource = this.getGrammarElementId(node2.grammarSource);
        }
        cstNode.hidden = node2.hidden;
        cstNode.astNode = context.astNodes.get(node2.astNode);
        if (isCompositeCstNode(node2)) {
          cstNode.content = node2.content.map((child) => this.dehydrateCstNode(child, context));
        } else if (isLeafCstNode(node2)) {
          cstNode.tokenType = node2.tokenType.name;
          cstNode.offset = node2.offset;
          cstNode.length = node2.length;
          cstNode.startLine = node2.range.start.line;
          cstNode.startColumn = node2.range.start.character;
          cstNode.endLine = node2.range.end.line;
          cstNode.endColumn = node2.range.end.character;
        }
        return cstNode;
      }
      hydrate(result) {
        const node2 = result.value;
        const context = this.createHydrationContext(node2);
        if ("$cstNode" in node2) {
          this.hydrateCstNode(node2.$cstNode, context);
        }
        return {
          lexerErrors: result.lexerErrors,
          lexerReport: result.lexerReport,
          parserErrors: result.parserErrors,
          value: this.hydrateAstNode(node2, context)
        };
      }
      createHydrationContext(node2) {
        const astNodes = /* @__PURE__ */ new Map();
        const cstNodes = /* @__PURE__ */ new Map();
        for (const astNode of streamAst(node2)) {
          astNodes.set(astNode, {});
        }
        let root2;
        if (node2.$cstNode) {
          for (const cstNode of streamCst(node2.$cstNode)) {
            let cst;
            if ("fullText" in cstNode) {
              cst = new RootCstNodeImpl(cstNode.fullText);
              root2 = cst;
            } else if ("content" in cstNode) {
              cst = new CompositeCstNodeImpl();
            } else if ("tokenType" in cstNode) {
              cst = this.hydrateCstLeafNode(cstNode);
            }
            if (cst) {
              cstNodes.set(cstNode, cst);
              cst.root = root2;
            }
          }
        }
        return {
          astNodes,
          cstNodes
        };
      }
      hydrateAstNode(node2, context) {
        const astNode = context.astNodes.get(node2);
        astNode.$type = node2.$type;
        astNode.$containerIndex = node2.$containerIndex;
        astNode.$containerProperty = node2.$containerProperty;
        if (node2.$cstNode) {
          astNode.$cstNode = context.cstNodes.get(node2.$cstNode);
        }
        for (const [name, value] of Object.entries(node2)) {
          if (name.startsWith("$")) {
            continue;
          }
          if (Array.isArray(value)) {
            const arr = [];
            astNode[name] = arr;
            for (const item of value) {
              if (isAstNode(item)) {
                arr.push(this.setParent(this.hydrateAstNode(item, context), astNode));
              } else if (isReference(item)) {
                arr.push(this.hydrateReference(item, astNode, name, context));
              } else {
                arr.push(item);
              }
            }
          } else if (isAstNode(value)) {
            astNode[name] = this.setParent(this.hydrateAstNode(value, context), astNode);
          } else if (isReference(value)) {
            astNode[name] = this.hydrateReference(value, astNode, name, context);
          } else if (value !== void 0) {
            astNode[name] = value;
          }
        }
        return astNode;
      }
      setParent(node2, parent) {
        node2.$container = parent;
        return node2;
      }
      hydrateReference(reference, node2, name, context) {
        return this.linker.buildReference(node2, name, context.cstNodes.get(reference.$refNode), reference.$refText);
      }
      hydrateCstNode(cstNode, context, num = 0) {
        const cstNodeObj = context.cstNodes.get(cstNode);
        if (typeof cstNode.grammarSource === "number") {
          cstNodeObj.grammarSource = this.getGrammarElement(cstNode.grammarSource);
        }
        cstNodeObj.astNode = context.astNodes.get(cstNode.astNode);
        if (isCompositeCstNode(cstNodeObj)) {
          for (const child of cstNode.content) {
            const hydrated = this.hydrateCstNode(child, context, num++);
            cstNodeObj.content.push(hydrated);
          }
        }
        return cstNodeObj;
      }
      hydrateCstLeafNode(cstNode) {
        const tokenType = this.getTokenType(cstNode.tokenType);
        const offset = cstNode.offset;
        const length = cstNode.length;
        const startLine = cstNode.startLine;
        const startColumn = cstNode.startColumn;
        const endLine = cstNode.endLine;
        const endColumn = cstNode.endColumn;
        const hidden = cstNode.hidden;
        const node2 = new LeafCstNodeImpl(offset, length, {
          start: {
            line: startLine,
            character: startColumn
          },
          end: {
            line: endLine,
            character: endColumn
          }
        }, tokenType, hidden);
        return node2;
      }
      getTokenType(name) {
        return this.lexer.definition[name];
      }
      getGrammarElementId(node2) {
        if (!node2) {
          return void 0;
        }
        if (this.grammarElementIdMap.size === 0) {
          this.createGrammarElementIdMap();
        }
        return this.grammarElementIdMap.get(node2);
      }
      getGrammarElement(id) {
        if (this.grammarElementIdMap.size === 0) {
          this.createGrammarElementIdMap();
        }
        const element = this.grammarElementIdMap.getKey(id);
        return element;
      }
      createGrammarElementIdMap() {
        let id = 0;
        for (const element of streamAst(this.grammar)) {
          if (isAbstractElement(element)) {
            this.grammarElementIdMap.set(element, id++);
          }
        }
      }
    }
    var Disposable;
    (function(Disposable2) {
      function create(callback) {
        return {
          dispose: async () => await callback()
        };
      }
      Disposable2.create = create;
    })(Disposable || (Disposable = {}));
    class EmptyFileSystemProvider {
      stat(_uri) {
        throw new Error("No file system is available.");
      }
      statSync(_uri) {
        throw new Error("No file system is available.");
      }
      async exists() {
        return false;
      }
      existsSync() {
        return false;
      }
      readBinary() {
        throw new Error("No file system is available.");
      }
      readBinarySync() {
        throw new Error("No file system is available.");
      }
      readFile() {
        throw new Error("No file system is available.");
      }
      readFileSync() {
        throw new Error("No file system is available.");
      }
      async readDirectory() {
        return [];
      }
      readDirectorySync() {
        return [];
      }
    }
    const EmptyFileSystem = {
      fileSystemProvider: () => new EmptyFileSystemProvider()
    };
    const minimalGrammarModule = {
      Grammar: () => void 0,
      LanguageMetaData: () => ({
        caseInsensitive: false,
        fileExtensions: [".langium"],
        languageId: "langium"
      })
    };
    const minimalSharedGrammarModule = {
      AstReflection: () => new LangiumGrammarAstReflection()
    };
    function createMinimalGrammarServices() {
      const shared2 = inject(createDefaultSharedCoreModule(EmptyFileSystem), minimalSharedGrammarModule);
      const grammar = inject(createDefaultCoreModule({ shared: shared2 }), minimalGrammarModule);
      shared2.ServiceRegistry.register(grammar);
      return grammar;
    }
    function loadGrammarFromJson(json) {
      const services = createMinimalGrammarServices();
      const astNode = services.serializer.JsonSerializer.deserialize(json);
      services.shared.workspace.LangiumDocumentFactory.fromModel(astNode, URI$1.parse(`memory:/${astNode.name ?? "grammar"}.langium`));
      return astNode;
    }
    class DefaultAstNodeDescriptionProvider {
      constructor(services) {
        this.astNodeLocator = services.workspace.AstNodeLocator;
        this.nameProvider = services.references.NameProvider;
      }
      createDescription(node2, name, document) {
        const doc = document ?? getDocument(node2);
        name ?? (name = this.nameProvider.getName(node2));
        const path = this.astNodeLocator.getAstNodePath(node2);
        if (!name) {
          throw new Error(`Node at path ${path} has no name.`);
        }
        let nameNodeSegment;
        const nameSegmentGetter = () => nameNodeSegment ?? (nameNodeSegment = toDocumentSegment(this.nameProvider.getNameNode(node2) ?? node2.$cstNode));
        return {
          node: node2,
          name,
          get nameSegment() {
            return nameSegmentGetter();
          },
          selectionSegment: toDocumentSegment(node2.$cstNode),
          type: node2.$type,
          documentUri: doc.uri,
          path
        };
      }
    }
    class DefaultReferenceDescriptionProvider {
      constructor(services) {
        this.nodeLocator = services.workspace.AstNodeLocator;
      }
      async createDescriptions(document, cancelToken = cancellationExports.CancellationToken.None) {
        const descr = [];
        const rootNode = document.parseResult.value;
        for (const astNode of streamAst(rootNode)) {
          await interruptAndCheck(cancelToken);
          streamReferences(astNode).forEach((refInfo) => {
            if (!refInfo.reference.error) {
              descr.push(...this.createInfoDescriptions(refInfo));
            }
          });
        }
        return descr;
      }
      createInfoDescriptions(refInfo) {
        const reference = refInfo.reference;
        if (reference.error || !reference.$refNode) {
          return [];
        }
        let items = [];
        if (isReference(reference) && reference.$nodeDescription) {
          items = [reference.$nodeDescription];
        } else if (isMultiReference(reference)) {
          items = reference.items.map((e) => e.$nodeDescription).filter((e) => e !== void 0);
        }
        const sourceUri = getDocument(refInfo.container).uri;
        const sourcePath = this.nodeLocator.getAstNodePath(refInfo.container);
        const descriptions = [];
        const segment = toDocumentSegment(reference.$refNode);
        for (const item of items) {
          descriptions.push({
            sourceUri,
            sourcePath,
            targetUri: item.documentUri,
            targetPath: item.path,
            segment,
            local: UriUtils.equals(item.documentUri, sourceUri)
          });
        }
        return descriptions;
      }
    }
    class DefaultAstNodeLocator {
      constructor() {
        this.segmentSeparator = "/";
        this.indexSeparator = "@";
      }
      getAstNodePath(node2) {
        if (node2.$container) {
          const containerPath = this.getAstNodePath(node2.$container);
          const newSegment = this.getPathSegment(node2);
          const nodePath = containerPath + this.segmentSeparator + newSegment;
          return nodePath;
        }
        return "";
      }
      getPathSegment({ $containerProperty, $containerIndex }) {
        if (!$containerProperty) {
          throw new Error("Missing '$containerProperty' in AST node.");
        }
        if ($containerIndex !== void 0) {
          return $containerProperty + this.indexSeparator + $containerIndex;
        }
        return $containerProperty;
      }
      getAstNode(node2, path) {
        const segments = path.split(this.segmentSeparator);
        return segments.reduce((previousValue, currentValue) => {
          if (!previousValue || currentValue.length === 0) {
            return previousValue;
          }
          const propertyIndex = currentValue.indexOf(this.indexSeparator);
          if (propertyIndex > 0) {
            const property2 = currentValue.substring(0, propertyIndex);
            const arrayIndex = parseInt(currentValue.substring(propertyIndex + 1));
            const array = previousValue[property2];
            return array?.[arrayIndex];
          }
          return previousValue[currentValue];
        }, node2);
      }
    }
    class DefaultConfigurationProvider {
      constructor(services) {
        this._ready = new Deferred();
        this.onConfigurationSectionUpdateEmitter = new eventsExports.Emitter();
        this.settings = {};
        this.workspaceConfig = false;
        this.serviceRegistry = services.ServiceRegistry;
      }
      get ready() {
        return this._ready.promise;
      }
      initialize(params) {
        this.workspaceConfig = params.capabilities.workspace?.configuration ?? false;
      }
      async initialized(params) {
        if (this.workspaceConfig) {
          if (params.register) {
            const languages = this.serviceRegistry.all;
            params.register({
              // Listen to configuration changes for all languages
              section: languages.map((lang) => this.toSectionName(lang.LanguageMetaData.languageId))
            });
          }
          if (params.fetchConfiguration) {
            const configToUpdate = this.serviceRegistry.all.map((lang) => ({
              // Fetch the configuration changes for all languages
              section: this.toSectionName(lang.LanguageMetaData.languageId)
            }));
            const configs = await params.fetchConfiguration(configToUpdate);
            configToUpdate.forEach((conf, idx) => {
              this.updateSectionConfiguration(conf.section, configs[idx]);
            });
          }
        }
        this._ready.resolve();
      }
      /**
       *  Updates the cached configurations using the `change` notification parameters.
       *
       * @param change The parameters of a change configuration notification.
       * `settings` property of the change object could be expressed as `Record<string, Record<string, any>>`
       */
      updateConfiguration(change) {
        if (typeof change.settings !== "object" || change.settings === null) {
          return;
        }
        Object.entries(change.settings).forEach(([section, configuration2]) => {
          this.updateSectionConfiguration(section, configuration2);
          this.onConfigurationSectionUpdateEmitter.fire({ section, configuration: configuration2 });
        });
      }
      updateSectionConfiguration(section, configuration2) {
        this.settings[section] = configuration2;
      }
      /**
      * Returns a configuration value stored for the given language.
      *
      * @param language The language id
      * @param configuration Configuration name
      */
      async getConfiguration(language, configuration2) {
        await this.ready;
        const sectionName = this.toSectionName(language);
        if (this.settings[sectionName]) {
          return this.settings[sectionName][configuration2];
        }
      }
      toSectionName(languageId) {
        return `${languageId}`;
      }
      get onConfigurationSectionUpdate() {
        return this.onConfigurationSectionUpdateEmitter.event;
      }
    }
    var mainExports = requireMain$1();
    class DefaultDocumentBuilder {
      constructor(services) {
        this.updateBuildOptions = {
          // Default: run only the built-in validation checks and those in the _fast_ category (includes those without category)
          validation: {
            categories: ["built-in", "fast"]
          }
        };
        this.updateListeners = [];
        this.buildPhaseListeners = new MultiMap();
        this.documentPhaseListeners = new MultiMap();
        this.buildState = /* @__PURE__ */ new Map();
        this.documentBuildWaiters = /* @__PURE__ */ new Map();
        this.currentState = DocumentState.Changed;
        this.langiumDocuments = services.workspace.LangiumDocuments;
        this.langiumDocumentFactory = services.workspace.LangiumDocumentFactory;
        this.textDocuments = services.workspace.TextDocuments;
        this.indexManager = services.workspace.IndexManager;
        this.fileSystemProvider = services.workspace.FileSystemProvider;
        this.workspaceManager = () => services.workspace.WorkspaceManager;
        this.serviceRegistry = services.ServiceRegistry;
      }
      async build(documents, options = {}, cancelToken = cancellationExports.CancellationToken.None) {
        for (const document of documents) {
          const key = document.uri.toString();
          if (document.state === DocumentState.Validated) {
            if (typeof options.validation === "boolean" && options.validation) {
              this.resetToState(document, DocumentState.IndexedReferences);
            } else if (typeof options.validation === "object") {
              const categories = this.findMissingValidationCategories(document, options);
              if (categories.length > 0) {
                this.buildState.set(key, {
                  completed: false,
                  options: {
                    validation: {
                      categories
                    }
                  },
                  result: this.buildState.get(key)?.result
                });
                document.state = DocumentState.IndexedReferences;
              }
            }
          } else {
            this.buildState.delete(key);
          }
        }
        this.currentState = DocumentState.Changed;
        await this.emitUpdate(documents.map((e) => e.uri), []);
        await this.buildDocuments(documents, options, cancelToken);
      }
      async update(changed, deleted, cancelToken = cancellationExports.CancellationToken.None) {
        this.currentState = DocumentState.Changed;
        const deletedUris = [];
        for (const deletedUri of deleted) {
          const deletedDocs = this.langiumDocuments.deleteDocuments(deletedUri);
          for (const doc of deletedDocs) {
            deletedUris.push(doc.uri);
            this.cleanUpDeleted(doc);
          }
        }
        const changedUris = (await Promise.all(changed.map((uri) => this.findChangedUris(uri)))).flat();
        for (const changedUri of changedUris) {
          let changedDocument = this.langiumDocuments.getDocument(changedUri);
          if (changedDocument === void 0) {
            changedDocument = this.langiumDocumentFactory.fromModel({ $type: "INVALID" }, changedUri);
            changedDocument.state = DocumentState.Changed;
            this.langiumDocuments.addDocument(changedDocument);
          }
          this.resetToState(changedDocument, DocumentState.Changed);
        }
        const allChangedUris = stream(changedUris).concat(deletedUris).map((uri) => uri.toString()).toSet();
        this.langiumDocuments.all.filter((doc) => !allChangedUris.has(doc.uri.toString()) && this.shouldRelink(doc, allChangedUris)).forEach((doc) => this.resetToState(doc, DocumentState.ComputedScopes));
        await this.emitUpdate(changedUris, deletedUris);
        await interruptAndCheck(cancelToken);
        const rebuildDocuments = this.sortDocuments(this.langiumDocuments.all.filter((doc) => (
          // This includes those that were reported as changed and those that we selected for relinking
          doc.state < DocumentState.Validated || !this.buildState.get(doc.uri.toString())?.completed || this.resultsAreIncomplete(doc, this.updateBuildOptions)
        )).toArray());
        await this.buildDocuments(rebuildDocuments, this.updateBuildOptions, cancelToken);
      }
      resultsAreIncomplete(document, options) {
        return this.findMissingValidationCategories(document, options).length >= 1;
      }
      findMissingValidationCategories(document, options) {
        const state = this.buildState.get(document.uri.toString());
        const allCategories = this.serviceRegistry.getServices(document.uri).validation.ValidationRegistry.getAllValidationCategories(document);
        const executedCategories = state?.result?.validationChecks ? new Set(state?.result?.validationChecks) : state?.completed ? allCategories : /* @__PURE__ */ new Set();
        const requestedCategories = options === void 0 || options.validation === true ? allCategories : typeof options.validation === "object" ? options.validation.categories ?? allCategories : [];
        return stream(requestedCategories).filter((requested) => !executedCategories.has(requested)).toArray();
      }
      async findChangedUris(changed) {
        const document = this.langiumDocuments.getDocument(changed) ?? this.textDocuments?.get(changed);
        if (document) {
          return [changed];
        }
        try {
          const stat = await this.fileSystemProvider.stat(changed);
          if (stat.isDirectory) {
            const uris = await this.workspaceManager().searchFolder(changed);
            return uris;
          } else if (this.workspaceManager().shouldIncludeEntry(stat)) {
            return [changed];
          }
        } catch {
        }
        return [];
      }
      async emitUpdate(changed, deleted) {
        await Promise.all(this.updateListeners.map((listener) => listener(changed, deleted)));
      }
      /**
       * Sort the given documents by priority. By default, documents with an open text document are prioritized.
       * This is useful to ensure that visible documents show their diagnostics before all other documents.
       *
       * This improves the responsiveness in large workspaces as users usually don't care about diagnostics
       * in files that are currently not opened in the editor.
       */
      sortDocuments(documents) {
        let left = 0;
        let right = documents.length - 1;
        while (left < right) {
          while (left < documents.length && this.hasTextDocument(documents[left])) {
            left++;
          }
          while (right >= 0 && !this.hasTextDocument(documents[right])) {
            right--;
          }
          if (left < right) {
            [documents[left], documents[right]] = [documents[right], documents[left]];
          }
        }
        return documents;
      }
      hasTextDocument(doc) {
        return Boolean(this.textDocuments?.get(doc.uri));
      }
      /**
       * Check whether the given document should be relinked after changes were found in the given URIs.
       */
      shouldRelink(document, changedUris) {
        if (document.references.some((ref) => ref.error !== void 0)) {
          return true;
        }
        return this.indexManager.isAffected(document, changedUris);
      }
      onUpdate(callback) {
        this.updateListeners.push(callback);
        return Disposable.create(() => {
          const index = this.updateListeners.indexOf(callback);
          if (index >= 0) {
            this.updateListeners.splice(index, 1);
          }
        });
      }
      resetToState(document, state) {
        switch (state) {
          case DocumentState.Changed:
          case DocumentState.Parsed:
            this.indexManager.removeContent(document.uri);
          // Fall through
          case DocumentState.IndexedContent:
            document.localSymbols = void 0;
          // Fall through
          case DocumentState.ComputedScopes: {
            const linker = this.serviceRegistry.getServices(document.uri).references.Linker;
            linker.unlink(document);
          }
          case DocumentState.Linked:
            this.indexManager.removeReferences(document.uri);
          // Fall through
          case DocumentState.IndexedReferences:
            document.diagnostics = void 0;
            this.buildState.delete(document.uri.toString());
          // Fall through
          case DocumentState.Validated:
        }
        if (document.state > state) {
          document.state = state;
        }
      }
      cleanUpDeleted(document) {
        this.buildState.delete(document.uri.toString());
        this.indexManager.remove(document.uri);
        document.state = DocumentState.Changed;
      }
      /**
       * Build the given documents by stepping through all build phases. If a document's state indicates
       * that a certain build phase is already done, the phase is skipped for that document.
       *
       * @param documents The documents to build.
       * @param options the {@link BuildOptions} to use.
       * @param cancelToken A cancellation token that can be used to cancel the build.
       * @returns A promise that resolves when the build is done.
       */
      async buildDocuments(documents, options, cancelToken) {
        this.prepareBuild(documents, options);
        await this.runCancelable(documents, DocumentState.Parsed, cancelToken, (doc) => this.langiumDocumentFactory.update(doc, cancelToken));
        await this.runCancelable(documents, DocumentState.IndexedContent, cancelToken, (doc) => this.indexManager.updateContent(doc, cancelToken));
        await this.runCancelable(documents, DocumentState.ComputedScopes, cancelToken, async (doc) => {
          const scopeComputation = this.serviceRegistry.getServices(doc.uri).references.ScopeComputation;
          doc.localSymbols = await scopeComputation.collectLocalSymbols(doc, cancelToken);
        });
        const toBeLinked = documents.filter((doc) => this.shouldLink(doc));
        await this.runCancelable(toBeLinked, DocumentState.Linked, cancelToken, (doc) => {
          const linker = this.serviceRegistry.getServices(doc.uri).references.Linker;
          return linker.link(doc, cancelToken);
        });
        await this.runCancelable(toBeLinked, DocumentState.IndexedReferences, cancelToken, (doc) => this.indexManager.updateReferences(doc, cancelToken));
        const toBeValidated = documents.filter((doc) => {
          if (this.shouldValidate(doc)) {
            return true;
          } else {
            this.markAsCompleted(doc);
            return false;
          }
        });
        await this.runCancelable(toBeValidated, DocumentState.Validated, cancelToken, async (doc) => {
          await this.validate(doc, cancelToken);
          this.markAsCompleted(doc);
        });
      }
      markAsCompleted(document) {
        const state = this.buildState.get(document.uri.toString());
        if (state) {
          state.completed = true;
        }
      }
      /**
       * Runs prior to beginning the build process to update the {@link DocumentBuildState} for each document
       *
       * @param documents collection of documents to be built
       * @param options the {@link BuildOptions} to use
       */
      prepareBuild(documents, options) {
        for (const doc of documents) {
          const key = doc.uri.toString();
          const state = this.buildState.get(key);
          if (!state || state.completed) {
            this.buildState.set(key, {
              completed: false,
              options,
              result: state?.result
            });
          }
        }
      }
      /**
       * Runs a cancelable operation on a set of documents to bring them to a specified {@link DocumentState}.
       *
       * @param documents The array of documents to process.
       * @param targetState The target {@link DocumentState} to bring the documents to.
       * @param cancelToken A token that can be used to cancel the operation.
       * @param callback A function to be called for each document.
       * @returns A promise that resolves when all documents have been processed or the operation is canceled.
       * @throws Will throw `OperationCancelled` if the operation is canceled via a `CancellationToken`.
       */
      async runCancelable(documents, targetState, cancelToken, callback) {
        for (const document of documents) {
          if (document.state < targetState) {
            await interruptAndCheck(cancelToken);
            await callback(document);
            document.state = targetState;
            await this.notifyDocumentPhase(document, targetState, cancelToken);
          }
        }
        const targetStateDocs = documents.filter((doc) => doc.state === targetState);
        await this.notifyBuildPhase(targetStateDocs, targetState, cancelToken);
        this.currentState = targetState;
      }
      onBuildPhase(targetState, callback) {
        this.buildPhaseListeners.add(targetState, callback);
        return Disposable.create(() => {
          this.buildPhaseListeners.delete(targetState, callback);
        });
      }
      onDocumentPhase(targetState, callback) {
        this.documentPhaseListeners.add(targetState, callback);
        return Disposable.create(() => {
          this.documentPhaseListeners.delete(targetState, callback);
        });
      }
      waitUntil(state, uriOrToken, cancelToken) {
        let uri = void 0;
        if (uriOrToken && "path" in uriOrToken) {
          uri = uriOrToken;
        } else {
          cancelToken = uriOrToken;
        }
        cancelToken ?? (cancelToken = cancellationExports.CancellationToken.None);
        if (uri) {
          return this.awaitDocumentState(state, uri, cancelToken);
        } else {
          return this.awaitBuilderState(state, cancelToken);
        }
      }
      awaitDocumentState(state, uri, cancelToken) {
        const document = this.langiumDocuments.getDocument(uri);
        if (!document) {
          return Promise.reject(new mainExports.ResponseError(mainExports.LSPErrorCodes.ServerCancelled, `No document found for URI: ${uri.toString()}`));
        } else if (document.state >= state) {
          return Promise.resolve(uri);
        } else if (cancelToken.isCancellationRequested) {
          return Promise.reject(OperationCancelled);
        } else if (this.currentState >= state && state > document.state) {
          return Promise.reject(new mainExports.ResponseError(mainExports.LSPErrorCodes.RequestFailed, `Document state of ${uri.toString()} is ${DocumentState[document.state]}, requiring ${DocumentState[state]}, but workspace state is already ${DocumentState[this.currentState]}. Returning undefined.`));
        }
        return new Promise((resolve, reject) => {
          const buildDisposable = this.onDocumentPhase(state, (doc) => {
            if (UriUtils.equals(doc.uri, uri)) {
              buildDisposable.dispose();
              cancelDisposable.dispose();
              resolve(doc.uri);
            }
          });
          const cancelDisposable = cancelToken.onCancellationRequested(() => {
            buildDisposable.dispose();
            cancelDisposable.dispose();
            reject(OperationCancelled);
          });
        });
      }
      awaitBuilderState(state, cancelToken) {
        if (this.currentState >= state) {
          return Promise.resolve();
        } else if (cancelToken.isCancellationRequested) {
          return Promise.reject(OperationCancelled);
        }
        return new Promise((resolve, reject) => {
          const buildDisposable = this.onBuildPhase(state, () => {
            buildDisposable.dispose();
            cancelDisposable.dispose();
            resolve();
          });
          const cancelDisposable = cancelToken.onCancellationRequested(() => {
            buildDisposable.dispose();
            cancelDisposable.dispose();
            reject(OperationCancelled);
          });
        });
      }
      async notifyDocumentPhase(document, state, cancelToken) {
        const listeners = this.documentPhaseListeners.get(state);
        const listenersCopy = listeners.slice();
        for (const listener of listenersCopy) {
          try {
            await interruptAndCheck(cancelToken);
            await listener(document, cancelToken);
          } catch (err) {
            if (!isOperationCancelled(err)) {
              throw err;
            }
          }
        }
      }
      async notifyBuildPhase(documents, state, cancelToken) {
        if (documents.length === 0) {
          return;
        }
        const listeners = this.buildPhaseListeners.get(state);
        const listenersCopy = listeners.slice();
        for (const listener of listenersCopy) {
          await interruptAndCheck(cancelToken);
          await listener(documents, cancelToken);
        }
      }
      /**
       * Determine whether the given document should be linked during a build. The default
       * implementation checks the `eagerLinking` property of the build options. If it's set to `true`
       * or `undefined`, the document is included in the linking phase. This also affects the
       * references indexing phase, which depends on eager linking.
       */
      shouldLink(document) {
        return this.getBuildOptions(document).eagerLinking ?? true;
      }
      /**
       * Determine whether the given document should be validated during a build. The default
       * implementation checks the `validation` property of the build options. If it's set to `true`
       * or a `ValidationOptions` object, the document is included in the validation phase.
       */
      shouldValidate(document) {
        return Boolean(this.getBuildOptions(document).validation);
      }
      /**
       * Run validation checks on the given document and store the resulting diagnostics in the document.
       * If the document already contains diagnostics, the new ones are added to the list.
       */
      async validate(document, cancelToken) {
        const validator = this.serviceRegistry.getServices(document.uri).validation.DocumentValidator;
        const options = this.getBuildOptions(document);
        const validationOptions = typeof options.validation === "object" ? { ...options.validation } : {};
        validationOptions.categories = this.findMissingValidationCategories(document, options);
        const diagnostics = await validator.validateDocument(document, validationOptions, cancelToken);
        if (document.diagnostics) {
          document.diagnostics.push(...diagnostics);
        } else {
          document.diagnostics = diagnostics;
        }
        const state = this.buildState.get(document.uri.toString());
        if (state) {
          state.result ?? (state.result = {});
          if (state.result.validationChecks) {
            state.result.validationChecks = stream(state.result.validationChecks).concat(validationOptions.categories).distinct().toArray();
          } else {
            state.result.validationChecks = [...validationOptions.categories];
          }
        }
      }
      getBuildOptions(document) {
        return this.buildState.get(document.uri.toString())?.options ?? {};
      }
    }
    class DefaultIndexManager {
      constructor(services) {
        this.symbolIndex = /* @__PURE__ */ new Map();
        this.symbolByTypeIndex = new ContextCache();
        this.referenceIndex = /* @__PURE__ */ new Map();
        this.documents = services.workspace.LangiumDocuments;
        this.serviceRegistry = services.ServiceRegistry;
        this.astReflection = services.AstReflection;
      }
      findAllReferences(targetNode, astNodePath) {
        const targetDocUri = getDocument(targetNode).uri;
        const result = [];
        this.referenceIndex.forEach((docRefs) => {
          docRefs.forEach((refDescr) => {
            if (UriUtils.equals(refDescr.targetUri, targetDocUri) && refDescr.targetPath === astNodePath) {
              result.push(refDescr);
            }
          });
        });
        return stream(result);
      }
      allElements(nodeType, uris) {
        let documentUris = stream(this.symbolIndex.keys());
        if (uris) {
          documentUris = documentUris.filter((uri) => !uris || uris.has(uri));
        }
        return documentUris.map((uri) => this.getFileDescriptions(uri, nodeType)).flat();
      }
      getFileDescriptions(uri, nodeType) {
        if (!nodeType) {
          return this.symbolIndex.get(uri) ?? [];
        }
        const descriptions = this.symbolByTypeIndex.get(uri, nodeType, () => {
          const allFileDescriptions = this.symbolIndex.get(uri) ?? [];
          return allFileDescriptions.filter((e) => this.astReflection.isSubtype(e.type, nodeType));
        });
        return descriptions;
      }
      remove(uri) {
        this.removeContent(uri);
        this.removeReferences(uri);
      }
      removeContent(uri) {
        const uriString = uri.toString();
        this.symbolIndex.delete(uriString);
        this.symbolByTypeIndex.clear(uriString);
      }
      removeReferences(uri) {
        const uriString = uri.toString();
        this.referenceIndex.delete(uriString);
      }
      async updateContent(document, cancelToken = cancellationExports.CancellationToken.None) {
        const services = this.serviceRegistry.getServices(document.uri);
        const exports2 = await services.references.ScopeComputation.collectExportedSymbols(document, cancelToken);
        const uri = document.uri.toString();
        this.symbolIndex.set(uri, exports2);
        this.symbolByTypeIndex.clear(uri);
      }
      async updateReferences(document, cancelToken = cancellationExports.CancellationToken.None) {
        const services = this.serviceRegistry.getServices(document.uri);
        const indexData = await services.workspace.ReferenceDescriptionProvider.createDescriptions(document, cancelToken);
        this.referenceIndex.set(document.uri.toString(), indexData);
      }
      isAffected(document, changedUris) {
        const references = this.referenceIndex.get(document.uri.toString());
        if (!references) {
          return false;
        }
        return references.some((ref) => !ref.local && changedUris.has(ref.targetUri.toString()));
      }
    }
    class DefaultWorkspaceLock {
      constructor() {
        this.previousTokenSource = new cancellationExports.CancellationTokenSource();
        this.writeQueue = [];
        this.readQueue = [];
        this.done = true;
      }
      write(action) {
        this.cancelWrite();
        const tokenSource = startCancelableOperation();
        this.previousTokenSource = tokenSource;
        return this.enqueue(this.writeQueue, action, tokenSource.token);
      }
      read(action) {
        return this.enqueue(this.readQueue, action);
      }
      enqueue(queue, action, cancellationToken = cancellationExports.CancellationToken.None) {
        const deferred = new Deferred();
        const entry = {
          action,
          deferred,
          cancellationToken
        };
        queue.push(entry);
        this.performNextOperation();
        return deferred.promise;
      }
      async performNextOperation() {
        if (!this.done) {
          return;
        }
        const entries = [];
        if (this.writeQueue.length > 0) {
          entries.push(this.writeQueue.shift());
        } else if (this.readQueue.length > 0) {
          entries.push(...this.readQueue.splice(0, this.readQueue.length));
        } else {
          return;
        }
        this.done = false;
        await Promise.all(entries.map(async ({ action, deferred, cancellationToken }) => {
          try {
            const result = await Promise.resolve().then(() => action(cancellationToken));
            deferred.resolve(result);
          } catch (err) {
            if (isOperationCancelled(err)) {
              deferred.resolve(void 0);
            } else {
              deferred.reject(err);
            }
          }
        }));
        this.done = true;
        this.performNextOperation();
      }
      cancelWrite() {
        this.previousTokenSource.cancel();
      }
    }
    class DefaultWorkspaceManager {
      constructor(services) {
        this.initialBuildOptions = {};
        this._ready = new Deferred();
        this.serviceRegistry = services.ServiceRegistry;
        this.langiumDocuments = services.workspace.LangiumDocuments;
        this.documentBuilder = services.workspace.DocumentBuilder;
        this.fileSystemProvider = services.workspace.FileSystemProvider;
        this.mutex = services.workspace.WorkspaceLock;
      }
      get ready() {
        return this._ready.promise;
      }
      get workspaceFolders() {
        return this.folders;
      }
      initialize(params) {
        this.folders = params.workspaceFolders ?? void 0;
      }
      initialized(_params) {
        return this.mutex.write((token) => this.initializeWorkspace(this.folders ?? [], token));
      }
      async initializeWorkspace(folders, cancelToken = cancellationExports.CancellationToken.None) {
        const documents = await this.performStartup(folders);
        await interruptAndCheck(cancelToken);
        await this.documentBuilder.build(documents, this.initialBuildOptions, cancelToken);
      }
      /**
       * Performs the uninterruptable startup sequence of the workspace manager.
       * This methods loads all documents in the workspace and other documents and returns them.
       */
      async performStartup(folders) {
        const documents = [];
        const collector = (document) => {
          documents.push(document);
          if (!this.langiumDocuments.hasDocument(document.uri)) {
            this.langiumDocuments.addDocument(document);
          }
        };
        await this.loadAdditionalDocuments(folders, collector);
        const uris = [];
        await Promise.all(folders.map((wf) => this.getRootFolder(wf)).map(async (entry) => this.traverseFolder(entry, uris)));
        const uniqueUris = stream(uris).distinct((uri) => uri.toString()).filter((uri) => !this.langiumDocuments.hasDocument(uri));
        await this.loadWorkspaceDocuments(uniqueUris, collector);
        this._ready.resolve();
        return documents;
      }
      async loadWorkspaceDocuments(uris, collector) {
        await Promise.all(uris.map(async (uri) => {
          const document = await this.langiumDocuments.getOrCreateDocument(uri);
          collector(document);
        }));
      }
      /**
       * Load all additional documents that shall be visible in the context of the given workspace
       * folders and add them to the collector. This can be used to include built-in libraries of
       * your language, which can be either loaded from provided files or constructed in memory.
       */
      loadAdditionalDocuments(_folders, _collector) {
        return Promise.resolve();
      }
      /**
       * Determine the root folder of the source documents in the given workspace folder.
       * The default implementation returns the URI of the workspace folder, but you can override
       * this to return a subfolder like `src` instead.
       */
      getRootFolder(workspaceFolder2) {
        return URI$1.parse(workspaceFolder2.uri);
      }
      /**
       * Traverse the file system folder identified by the given URI and its subfolders. All
       * contained files that match the file extensions are added to the `uris` array.
       */
      async traverseFolder(folderPath, uris) {
        try {
          const content = await this.fileSystemProvider.readDirectory(folderPath);
          await Promise.all(content.map(async (entry) => {
            if (this.shouldIncludeEntry(entry)) {
              if (entry.isDirectory) {
                await this.traverseFolder(entry.uri, uris);
              } else if (entry.isFile) {
                uris.push(entry.uri);
              }
            }
          }));
        } catch (e) {
          console.error("Failure to read directory content of " + folderPath.toString(true), e);
        }
      }
      async searchFolder(uri) {
        const uris = [];
        await this.traverseFolder(uri, uris);
        return uris;
      }
      /**
       * Determine whether the given folder entry shall be included while indexing the workspace.
       */
      shouldIncludeEntry(entry) {
        const name = UriUtils.basename(entry.uri);
        if (name.startsWith(".")) {
          return false;
        }
        if (entry.isDirectory) {
          return name !== "node_modules" && name !== "out";
        } else if (entry.isFile) {
          return this.serviceRegistry.hasServices(entry.uri);
        }
        return false;
      }
    }
    function diagnosticData(code) {
      return { code };
    }
    var ValidationCategory;
    (function(ValidationCategory2) {
      ValidationCategory2.defaults = ["fast", "slow", "built-in"];
      ValidationCategory2.all = ValidationCategory2.defaults;
    })(ValidationCategory || (ValidationCategory = {}));
    class ValidationRegistry {
      constructor(services) {
        this.entries = new MultiMap();
        this.knownCategories = new Set(ValidationCategory.defaults);
        this.entriesBefore = [];
        this.entriesAfter = [];
        this.reflection = services.shared.AstReflection;
      }
      /**
       * Register a set of validation checks. Each value in the record can be either a single validation check (i.e. a function)
       * or an array of validation checks.
       *
       * @param checksRecord Set of validation checks to register.
       * @param thisObj Optional object to be used as `this` when calling the validation check functions.
       * @param category Optional category for the validation checks (defaults to `'fast'`).
       */
      register(checksRecord, thisObj = this, category = "fast") {
        if (category === "built-in") {
          throw new Error("The 'built-in' category is reserved for lexer, parser, and linker errors.");
        }
        this.knownCategories.add(category);
        for (const [type, ch] of Object.entries(checksRecord)) {
          const callbacks = ch;
          if (Array.isArray(callbacks)) {
            for (const check of callbacks) {
              const entry = {
                check: this.wrapValidationException(check, thisObj),
                category
              };
              this.addEntry(type, entry);
            }
          } else if (typeof callbacks === "function") {
            const entry = {
              check: this.wrapValidationException(callbacks, thisObj),
              category
            };
            this.addEntry(type, entry);
          } else {
            assertUnreachable();
          }
        }
      }
      wrapValidationException(check, thisObj) {
        return async (node2, accept, cancelToken) => {
          await this.handleException(() => check.call(thisObj, node2, accept, cancelToken), "An error occurred during validation", accept, node2);
        };
      }
      async handleException(functionality, messageContext, accept, node2) {
        try {
          await functionality();
        } catch (err) {
          if (isOperationCancelled(err)) {
            throw err;
          }
          console.error(`${messageContext}:`, err);
          if (err instanceof Error && err.stack) {
            console.error(err.stack);
          }
          const messageDetails = err instanceof Error ? err.message : String(err);
          accept("error", `${messageContext}: ${messageDetails}`, { node: node2 });
        }
      }
      addEntry(type, entry) {
        if (type === "AstNode") {
          this.entries.add("AstNode", entry);
          return;
        }
        for (const subtype of this.reflection.getAllSubTypes(type)) {
          this.entries.add(subtype, entry);
        }
      }
      getChecks(type, categories) {
        let checks = stream(this.entries.get(type)).concat(this.entries.get("AstNode"));
        if (categories) {
          checks = checks.filter((entry) => categories.includes(entry.category));
        }
        return checks.map((entry) => entry.check);
      }
      /**
       * Register logic which will be executed once before validating all the nodes of an AST/Langium document.
       * This helps to prepare or initialize some information which are required or reusable for the following checks on the AstNodes.
       *
       * As an example, for validating unique fully-qualified names of nodes in the AST,
       * here the map for mapping names to nodes could be established.
       * During the usual checks on the nodes, they are put into this map with their name.
       *
       * Note that this approach makes validations stateful, which is relevant e.g. when cancelling the validation.
       * Therefore it is recommended to clear stored information
       * _before_ validating an AST to validate each AST unaffected from other ASTs
       * AND _after_ validating the AST to free memory by information which are no longer used.
       *
       * @param checkBefore a set-up function which will be called once before actually validating an AST
       * @param thisObj Optional object to be used as `this` when calling the validation check functions.
       */
      registerBeforeDocument(checkBefore, thisObj = this) {
        this.entriesBefore.push(this.wrapPreparationException(checkBefore, "An error occurred during set-up of the validation", thisObj));
      }
      /**
       * Register logic which will be executed once after validating all the nodes of an AST/Langium document.
       * This helps to finally evaluate information which are collected during the checks on the AstNodes.
       *
       * As an example, for validating unique fully-qualified names of nodes in the AST,
       * here the map with all the collected nodes and their names is checked
       * and validation hints are created for all nodes with the same name.
       *
       * Note that this approach makes validations stateful, which is relevant e.g. when cancelling the validation.
       * Therefore it is recommended to clear stored information
       * _before_ validating an AST to validate each AST unaffected from other ASTs
       * AND _after_ validating the AST to free memory by information which are no longer used.
       *
       * @param checkBefore a set-up function which will be called once before actually validating an AST
       * @param thisObj Optional object to be used as `this` when calling the validation check functions.
       */
      registerAfterDocument(checkAfter, thisObj = this) {
        this.entriesAfter.push(this.wrapPreparationException(checkAfter, "An error occurred during tear-down of the validation", thisObj));
      }
      wrapPreparationException(check, messageContext, thisObj) {
        return async (rootNode, accept, categories, cancelToken) => {
          await this.handleException(() => check.call(thisObj, rootNode, accept, categories, cancelToken), messageContext, accept, rootNode);
        };
      }
      get checksBefore() {
        return this.entriesBefore;
      }
      get checksAfter() {
        return this.entriesAfter;
      }
      getAllValidationCategories(_document) {
        return this.knownCategories;
      }
    }
    const VALIDATE_EACH_NODE = Object.freeze({
      validateNode: true,
      validateChildren: true
    });
    class DefaultDocumentValidator {
      constructor(services) {
        this.validationRegistry = services.validation.ValidationRegistry;
        this.metadata = services.LanguageMetaData;
        this.profiler = services.shared.profilers.LangiumProfiler;
        this.languageId = services.LanguageMetaData.languageId;
      }
      async validateDocument(document, options = {}, cancelToken = cancellationExports.CancellationToken.None) {
        const parseResult = document.parseResult;
        const diagnostics = [];
        await interruptAndCheck(cancelToken);
        if (!options.categories || options.categories.includes("built-in")) {
          this.processLexingErrors(parseResult, diagnostics, options);
          if (options.stopAfterLexingErrors && diagnostics.some((d) => d.data?.code === DocumentValidator.LexingError)) {
            return diagnostics;
          }
          this.processParsingErrors(parseResult, diagnostics, options);
          if (options.stopAfterParsingErrors && diagnostics.some((d) => d.data?.code === DocumentValidator.ParsingError)) {
            return diagnostics;
          }
          this.processLinkingErrors(document, diagnostics, options);
          if (options.stopAfterLinkingErrors && diagnostics.some((d) => d.data?.code === DocumentValidator.LinkingError)) {
            return diagnostics;
          }
        }
        try {
          diagnostics.push(...await this.validateAst(parseResult.value, options, cancelToken));
        } catch (err) {
          if (isOperationCancelled(err)) {
            throw err;
          }
          console.error("An error occurred during validation:", err);
        }
        await interruptAndCheck(cancelToken);
        return diagnostics;
      }
      processLexingErrors(parseResult, diagnostics, _options) {
        const lexerDiagnostics = [...parseResult.lexerErrors, ...parseResult.lexerReport?.diagnostics ?? []];
        for (const lexerDiagnostic of lexerDiagnostics) {
          const severity = lexerDiagnostic.severity ?? "error";
          const diagnostic2 = {
            severity: toDiagnosticSeverity(severity),
            range: {
              start: {
                line: lexerDiagnostic.line - 1,
                character: lexerDiagnostic.column - 1
              },
              end: {
                line: lexerDiagnostic.line - 1,
                character: lexerDiagnostic.column + lexerDiagnostic.length - 1
              }
            },
            message: lexerDiagnostic.message,
            data: toDiagnosticData(severity),
            source: this.getSource()
          };
          diagnostics.push(diagnostic2);
        }
      }
      processParsingErrors(parseResult, diagnostics, _options) {
        for (const parserError of parseResult.parserErrors) {
          let range = void 0;
          if (isNaN(parserError.token.startOffset)) {
            if ("previousToken" in parserError) {
              const token = parserError.previousToken;
              if (!isNaN(token.startOffset)) {
                const position = { line: token.endLine - 1, character: token.endColumn };
                range = { start: position, end: position };
              } else {
                const position = { line: 0, character: 0 };
                range = { start: position, end: position };
              }
            }
          } else {
            range = tokenToRange(parserError.token);
          }
          if (range) {
            const diagnostic2 = {
              severity: toDiagnosticSeverity("error"),
              range,
              message: parserError.message,
              data: diagnosticData(DocumentValidator.ParsingError),
              source: this.getSource()
            };
            diagnostics.push(diagnostic2);
          }
        }
      }
      processLinkingErrors(document, diagnostics, _options) {
        for (const reference of document.references) {
          const linkingError = reference.error;
          if (linkingError) {
            const info = {
              node: linkingError.info.container,
              range: reference.$refNode?.range,
              property: linkingError.info.property,
              index: linkingError.info.index,
              data: {
                code: DocumentValidator.LinkingError,
                containerType: linkingError.info.container.$type,
                property: linkingError.info.property,
                refText: linkingError.info.reference.$refText
              }
            };
            diagnostics.push(this.toDiagnostic("error", linkingError.message, info));
          }
        }
      }
      async validateAst(rootNode, options, cancelToken = cancellationExports.CancellationToken.None) {
        const validationItems = [];
        const acceptor = (severity, message, info) => {
          validationItems.push(this.toDiagnostic(severity, message, info));
        };
        await this.validateAstBefore(rootNode, options, acceptor, cancelToken);
        await this.validateAstNodes(rootNode, options, acceptor, cancelToken);
        await this.validateAstAfter(rootNode, options, acceptor, cancelToken);
        return validationItems;
      }
      async validateAstBefore(rootNode, options, acceptor, cancelToken = cancellationExports.CancellationToken.None) {
        const checksBefore = this.validationRegistry.checksBefore;
        for (const checkBefore of checksBefore) {
          await interruptAndCheck(cancelToken);
          await checkBefore(rootNode, acceptor, options.categories ?? [], cancelToken);
        }
      }
      async validateAstNodes(rootNode, options, acceptor, cancelToken = cancellationExports.CancellationToken.None) {
        if (this.profiler?.isActive("validating")) {
          const task = this.profiler.createTask("validating", this.languageId);
          task.start();
          try {
            const nodes = streamAst(rootNode).iterator();
            for (const node2 of nodes) {
              task.startSubTask(node2.$type);
              const nodeOptions = this.validateSingleNodeOptions(node2, options);
              if (nodeOptions.validateNode) {
                try {
                  const checks = this.validationRegistry.getChecks(node2.$type, options.categories);
                  for (const check of checks) {
                    await check(node2, acceptor, cancelToken);
                  }
                } finally {
                  task.stopSubTask(node2.$type);
                }
              }
              if (!nodeOptions.validateChildren) {
                nodes.prune();
              }
            }
          } finally {
            task.stop();
          }
        } else {
          const nodes = streamAst(rootNode).iterator();
          for (const node2 of nodes) {
            await interruptAndCheck(cancelToken);
            const nodeOptions = this.validateSingleNodeOptions(node2, options);
            if (nodeOptions.validateNode) {
              const checks = this.validationRegistry.getChecks(node2.$type, options.categories);
              for (const check of checks) {
                await check(node2, acceptor, cancelToken);
              }
            }
            if (!nodeOptions.validateChildren) {
              nodes.prune();
            }
          }
        }
      }
      validateSingleNodeOptions(_node, _options) {
        return VALIDATE_EACH_NODE;
      }
      async validateAstAfter(rootNode, options, acceptor, cancelToken = cancellationExports.CancellationToken.None) {
        const checksAfter = this.validationRegistry.checksAfter;
        for (const checkAfter of checksAfter) {
          await interruptAndCheck(cancelToken);
          await checkAfter(rootNode, acceptor, options.categories ?? [], cancelToken);
        }
      }
      toDiagnostic(severity, message, info) {
        return {
          message,
          range: getDiagnosticRange(info),
          severity: toDiagnosticSeverity(severity),
          code: info.code,
          codeDescription: info.codeDescription,
          tags: info.tags,
          relatedInformation: info.relatedInformation,
          data: info.data,
          source: this.getSource()
        };
      }
      getSource() {
        return this.metadata.languageId;
      }
    }
    function getDiagnosticRange(info) {
      if (info.range) {
        return info.range;
      }
      let cstNode;
      if (typeof info.property === "string") {
        cstNode = findNodeForProperty(info.node.$cstNode, info.property, info.index);
      } else if (typeof info.keyword === "string") {
        cstNode = findNodeForKeyword(info.node.$cstNode, info.keyword, info.index);
      }
      cstNode ?? (cstNode = info.node.$cstNode);
      if (!cstNode) {
        return {
          start: { line: 0, character: 0 },
          end: { line: 0, character: 0 }
        };
      }
      return cstNode.range;
    }
    function toDiagnosticSeverity(severity) {
      switch (severity) {
        case "error":
          return 1;
        case "warning":
          return 2;
        case "info":
          return 3;
        case "hint":
          return 4;
        default:
          throw new Error("Invalid diagnostic severity: " + severity);
      }
    }
    function toDiagnosticData(severity) {
      switch (severity) {
        case "error":
          return diagnosticData(DocumentValidator.LexingError);
        case "warning":
          return diagnosticData(DocumentValidator.LexingWarning);
        case "info":
          return diagnosticData(DocumentValidator.LexingInfo);
        case "hint":
          return diagnosticData(DocumentValidator.LexingHint);
        default:
          throw new Error("Invalid diagnostic severity: " + severity);
      }
    }
    var DocumentValidator;
    (function(DocumentValidator2) {
      DocumentValidator2.LexingError = "lexing-error";
      DocumentValidator2.LexingWarning = "lexing-warning";
      DocumentValidator2.LexingInfo = "lexing-info";
      DocumentValidator2.LexingHint = "lexing-hint";
      DocumentValidator2.ParsingError = "parsing-error";
      DocumentValidator2.LinkingError = "linking-error";
    })(DocumentValidator || (DocumentValidator = {}));
    function createDefaultCoreModule(context) {
      return {
        documentation: {
          CommentProvider: (services) => new DefaultCommentProvider(services),
          DocumentationProvider: (services) => new JSDocDocumentationProvider(services)
        },
        parser: {
          AsyncParser: (services) => new DefaultAsyncParser(services),
          GrammarConfig: (services) => createGrammarConfig(services),
          LangiumParser: (services) => createLangiumParser(services),
          CompletionParser: (services) => createCompletionParser(services),
          ValueConverter: () => new DefaultValueConverter(),
          TokenBuilder: () => new DefaultTokenBuilder(),
          Lexer: (services) => new DefaultLexer(services),
          ParserErrorMessageProvider: () => new LangiumParserErrorMessageProvider(),
          LexerErrorMessageProvider: () => new DefaultLexerErrorMessageProvider()
        },
        workspace: {
          AstNodeLocator: () => new DefaultAstNodeLocator(),
          AstNodeDescriptionProvider: (services) => new DefaultAstNodeDescriptionProvider(services),
          ReferenceDescriptionProvider: (services) => new DefaultReferenceDescriptionProvider(services)
        },
        references: {
          Linker: (services) => new DefaultLinker(services),
          NameProvider: () => new DefaultNameProvider(),
          ScopeProvider: (services) => new DefaultScopeProvider(services),
          ScopeComputation: (services) => new DefaultScopeComputation(services),
          References: (services) => new DefaultReferences(services)
        },
        serializer: {
          Hydrator: (services) => new DefaultHydrator(services),
          JsonSerializer: (services) => new DefaultJsonSerializer(services)
        },
        validation: {
          DocumentValidator: (services) => new DefaultDocumentValidator(services),
          ValidationRegistry: (services) => new ValidationRegistry(services)
        },
        shared: () => context.shared
      };
    }
    function createDefaultSharedCoreModule(context) {
      return {
        ServiceRegistry: (services) => new DefaultServiceRegistry(services),
        workspace: {
          LangiumDocuments: (services) => new DefaultLangiumDocuments(services),
          LangiumDocumentFactory: (services) => new DefaultLangiumDocumentFactory(services),
          DocumentBuilder: (services) => new DefaultDocumentBuilder(services),
          IndexManager: (services) => new DefaultIndexManager(services),
          WorkspaceManager: (services) => new DefaultWorkspaceManager(services),
          FileSystemProvider: (services) => context.fileSystemProvider(services),
          WorkspaceLock: () => new DefaultWorkspaceLock(),
          ConfigurationProvider: (services) => new DefaultConfigurationProvider(services)
        },
        profilers: {}
      };
    }
    class DefaultDocumentHighlightProvider {
      constructor(services) {
        this.references = services.references.References;
        this.nameProvider = services.references.NameProvider;
        this.grammarConfig = services.parser.GrammarConfig;
      }
      getDocumentHighlight(document, params, _cancelToken) {
        const rootNode = document.parseResult.value.$cstNode;
        if (!rootNode) {
          return void 0;
        }
        const selectedNode = findDeclarationNodeAtOffset(rootNode, document.textDocument.offsetAt(params.position), this.grammarConfig.nameRegexp);
        if (!selectedNode) {
          return void 0;
        }
        const targetAstNode = this.references.findDeclarations(selectedNode);
        const highlights = [];
        for (const target of targetAstNode) {
          const includeDeclaration = UriUtils.equals(getDocument(target).uri, document.uri);
          const options = { documentUri: document.uri, includeDeclaration };
          const references = this.references.findReferences(target, options);
          highlights.push(...references.map((ref) => this.createDocumentHighlight(ref)).toArray());
        }
        return highlights;
      }
      /**
      * Override this method to determine the highlight kind of the given reference.
      */
      createDocumentHighlight(reference) {
        return mainExports$1.DocumentHighlight.create(reference.segment.range);
      }
    }
    class DefaultDocumentSymbolProvider {
      constructor(services) {
        this.nameProvider = services.references.NameProvider;
        this.nodeKindProvider = services.shared.lsp.NodeKindProvider;
      }
      getSymbols(document, _params, _cancelToken) {
        return this.getSymbol(document, document.parseResult.value);
      }
      getSymbol(document, astNode) {
        const nameNode = this.nameProvider.getNameNode(astNode);
        if (nameNode && astNode.$cstNode) {
          const computedName = this.nameProvider.getName(astNode);
          return [this.createSymbol(document, astNode, astNode.$cstNode, nameNode, computedName)];
        } else {
          return this.getChildSymbols(document, astNode) || [];
        }
      }
      createSymbol(document, astNode, cstNode, nameNode, computedName) {
        return {
          kind: this.nodeKindProvider.getSymbolKind(astNode),
          name: computedName || nameNode.text,
          range: cstNode.range,
          selectionRange: nameNode.range,
          children: this.getChildSymbols(document, astNode)
        };
      }
      getChildSymbols(document, astNode) {
        const children = [];
        for (const child of streamContents(astNode)) {
          const result = this.getSymbol(document, child);
          children.push(...result);
        }
        if (children.length > 0) {
          return children;
        }
        return void 0;
      }
    }
    class DefaultDocumentUpdateHandler {
      constructor(services) {
        this.onWatchedFilesChangeEmitter = new eventsExports.Emitter();
        this.workspaceManager = services.workspace.WorkspaceManager;
        this.documentBuilder = services.workspace.DocumentBuilder;
        this.workspaceLock = services.workspace.WorkspaceLock;
        this.serviceRegistry = services.ServiceRegistry;
        let canRegisterFileWatcher = false;
        services.lsp.LanguageServer.onInitialize((params) => {
          canRegisterFileWatcher = Boolean(params.capabilities.workspace?.didChangeWatchedFiles?.dynamicRegistration);
        });
        services.lsp.LanguageServer.onInitialized((_params) => {
          if (canRegisterFileWatcher) {
            this.registerFileWatcher(services);
          }
        });
      }
      registerFileWatcher(services) {
        const watchers = this.getWatchers();
        if (watchers.length > 0) {
          const connection2 = services.lsp.Connection;
          const options = { watchers };
          connection2?.client.register(mainExports$1.DidChangeWatchedFilesNotification.type, options);
        }
      }
      getWatchers() {
        return [{
          // We need to watch all file changes in the workspace
          // Otherwise we miss changes to directories
          // This is a limitation of specific language client implementations
          globPattern: "**/*"
        }];
      }
      fireDocumentUpdate(changed, deleted) {
        this.workspaceManager.ready.then(() => {
          this.workspaceLock.write((token) => this.documentBuilder.update(changed, deleted, token));
        }).catch((err) => {
          console.error("Workspace initialization failed. Could not perform document update.", err);
        });
      }
      didChangeContent(change) {
        this.fireDocumentUpdate([URI$1.parse(change.document.uri)], []);
      }
      didChangeWatchedFiles(params) {
        this.onWatchedFilesChangeEmitter.fire(params);
        const changedUris = stream(params.changes).filter((c) => c.type !== mainExports$1.FileChangeType.Deleted).distinct((c) => c.uri).map((c) => URI$1.parse(c.uri)).toArray();
        const deletedUris = stream(params.changes).filter((c) => c.type === mainExports$1.FileChangeType.Deleted).distinct((c) => c.uri).map((c) => URI$1.parse(c.uri)).toArray();
        this.fireDocumentUpdate(changedUris, deletedUris);
      }
      get onWatchedFilesChange() {
        return this.onWatchedFilesChangeEmitter.event;
      }
    }
    class DefaultFoldingRangeProvider {
      constructor(services) {
        this.commentNames = services.parser.GrammarConfig.multilineCommentRules;
      }
      getFoldingRanges(document, _params, _cancelToken) {
        const foldings = [];
        const acceptor = (foldingRange2) => foldings.push(foldingRange2);
        this.collectFolding(document, acceptor);
        return foldings;
      }
      collectFolding(document, acceptor) {
        const root2 = document.parseResult?.value;
        if (root2) {
          if (this.shouldProcessContent(root2)) {
            const treeIterator = streamAllContents(root2).iterator();
            let result;
            do {
              result = treeIterator.next();
              if (!result.done) {
                const node2 = result.value;
                if (this.shouldProcess(node2)) {
                  this.collectObjectFolding(document, node2, acceptor);
                }
                if (!this.shouldProcessContent(node2)) {
                  treeIterator.prune();
                }
              }
            } while (!result.done);
          }
          this.collectCommentFolding(document, root2, acceptor);
        }
      }
      /**
       * Template method to determine whether the specified `AstNode` should be handled by the folding range provider.
       * Returns true by default for all nodes. Returning false only ignores the specified node and not its content.
       * To ignore the content of a node use `shouldProcessContent`.
       */
      shouldProcess(_node) {
        return true;
      }
      /**
       * Template method to determine whether the content/children of the specified `AstNode` should be handled by the folding range provider.
       * Returns true by default for all nodes. Returning false ignores _all_ content of this node, even transitive ones.
       * For more precise control over foldings use the `shouldProcess` method.
       */
      shouldProcessContent(_node) {
        return true;
      }
      collectObjectFolding(document, node2, acceptor) {
        const cstNode = node2.$cstNode;
        if (cstNode) {
          const foldingRange2 = this.toFoldingRange(document, cstNode);
          if (foldingRange2) {
            acceptor(foldingRange2);
          }
        }
      }
      collectCommentFolding(document, node2, acceptor) {
        const cstNode = node2.$cstNode;
        if (cstNode) {
          for (const node3 of flattenCst(cstNode)) {
            if (this.commentNames.includes(node3.tokenType.name)) {
              const foldingRange2 = this.toFoldingRange(document, node3, mainExports$1.FoldingRangeKind.Comment);
              if (foldingRange2) {
                acceptor(foldingRange2);
              }
            }
          }
        }
      }
      toFoldingRange(document, node2, kind) {
        const range = node2.range;
        const start = range.start;
        let end = range.end;
        if (end.line - start.line < 2) {
          return void 0;
        }
        if (!this.includeLastFoldingLine(node2, kind)) {
          end = document.textDocument.positionAt(document.textDocument.offsetAt({ line: end.line, character: 0 }) - 1);
        }
        return mainExports$1.FoldingRange.create(start.line, end.line, start.character, end.character, kind);
      }
      /**
       * Template method to determine whether the folding range for this cst node should include its last line.
       * Returns false by default for ast nodes which end in braces and for comments.
       */
      includeLastFoldingLine(node2, kind) {
        if (kind === mainExports$1.FoldingRangeKind.Comment) {
          return false;
        }
        const nodeText = node2.text;
        const endChar = nodeText.charAt(nodeText.length - 1);
        if (endChar === "}" || endChar === ")" || endChar === "]") {
          return false;
        }
        return true;
      }
    }
    class DefaultFuzzyMatcher {
      match(query, text) {
        if (query.length === 0) {
          return true;
        }
        let matchedFirstCharacter = false;
        let previous;
        let character = 0;
        const len = text.length;
        for (let i = 0; i < len; i++) {
          const strChar = text.charCodeAt(i);
          const testChar = query.charCodeAt(character);
          if (strChar === testChar || this.toUpperCharCode(strChar) === this.toUpperCharCode(testChar)) {
            matchedFirstCharacter || (matchedFirstCharacter = previous === void 0 || // Beginning of word
            this.isWordTransition(previous, strChar));
            if (matchedFirstCharacter) {
              character++;
            }
            if (character === query.length) {
              return true;
            }
          }
          previous = strChar;
        }
        return false;
      }
      isWordTransition(previous, current) {
        return a <= previous && previous <= z && A <= current && current <= Z || // camelCase transition
        previous === _ && current !== _;
      }
      toUpperCharCode(charCode) {
        if (a <= charCode && charCode <= z) {
          return charCode - 32;
        }
        return charCode;
      }
    }
    const a = "a".charCodeAt(0);
    const z = "z".charCodeAt(0);
    const A = "A".charCodeAt(0);
    const Z = "Z".charCodeAt(0);
    const _ = "_".charCodeAt(0);
    class AstNodeHoverProvider {
      constructor(services) {
        this.references = services.references.References;
        this.grammarConfig = services.parser.GrammarConfig;
      }
      async getHoverContent(document, params) {
        const rootNode = document.parseResult?.value?.$cstNode;
        if (rootNode) {
          const offset = document.textDocument.offsetAt(params.position);
          const cstNode = findDeclarationNodeAtOffset(rootNode, offset, this.grammarConfig.nameRegexp);
          if (cstNode && cstNode.offset + cstNode.length > offset) {
            const contents = [];
            const targetNodes = this.references.findDeclarations(cstNode);
            for (const targetNode of targetNodes) {
              const content = await this.getAstNodeHoverContent(targetNode);
              if (typeof content === "string") {
                contents.push(content);
              }
            }
            if (contents.length > 0) {
              return {
                contents: {
                  kind: "markdown",
                  value: contents.join(" ")
                }
              };
            }
            if (isKeyword(cstNode.grammarSource)) {
              return this.getKeywordHoverContent(cstNode.grammarSource);
            }
          }
        }
        return void 0;
      }
      getKeywordHoverContent(node2) {
        let comment = isAstNodeWithComment(node2) ? node2.$comment : void 0;
        if (!comment) {
          comment = findCommentNode(node2.$cstNode, ["ML_COMMENT"])?.text;
        }
        if (comment && isJSDoc(comment)) {
          const content = parseJSDoc(comment).toMarkdown();
          if (content) {
            return {
              contents: {
                kind: "markdown",
                value: content
              }
            };
          }
        }
        return void 0;
      }
    }
    class MultilineCommentHoverProvider extends AstNodeHoverProvider {
      constructor(services) {
        super(services);
        this.documentationProvider = services.documentation.DocumentationProvider;
      }
      getAstNodeHoverContent(node2) {
        const content = this.documentationProvider.getDocumentation(node2);
        if (content) {
          return content;
        }
        return void 0;
      }
    }
    ({
      [mainExports$1.SemanticTokenTypes.class]: 0,
      [mainExports$1.SemanticTokenTypes.comment]: 1,
      [mainExports$1.SemanticTokenTypes.enum]: 2,
      [mainExports$1.SemanticTokenTypes.enumMember]: 3,
      [mainExports$1.SemanticTokenTypes.event]: 4,
      [mainExports$1.SemanticTokenTypes.function]: 5,
      [mainExports$1.SemanticTokenTypes.interface]: 6,
      [mainExports$1.SemanticTokenTypes.keyword]: 7,
      [mainExports$1.SemanticTokenTypes.macro]: 8,
      [mainExports$1.SemanticTokenTypes.method]: 9,
      [mainExports$1.SemanticTokenTypes.modifier]: 10,
      [mainExports$1.SemanticTokenTypes.namespace]: 11,
      [mainExports$1.SemanticTokenTypes.number]: 12,
      [mainExports$1.SemanticTokenTypes.operator]: 13,
      [mainExports$1.SemanticTokenTypes.parameter]: 14,
      [mainExports$1.SemanticTokenTypes.property]: 15,
      [mainExports$1.SemanticTokenTypes.regexp]: 16,
      [mainExports$1.SemanticTokenTypes.string]: 17,
      [mainExports$1.SemanticTokenTypes.struct]: 18,
      [mainExports$1.SemanticTokenTypes.type]: 19,
      [mainExports$1.SemanticTokenTypes.typeParameter]: 20,
      [mainExports$1.SemanticTokenTypes.variable]: 21,
      [mainExports$1.SemanticTokenTypes.decorator]: 22
    });
    ({
      [mainExports$1.SemanticTokenModifiers.abstract]: 1 << 0,
      [mainExports$1.SemanticTokenModifiers.async]: 1 << 1,
      [mainExports$1.SemanticTokenModifiers.declaration]: 1 << 2,
      [mainExports$1.SemanticTokenModifiers.defaultLibrary]: 1 << 3,
      [mainExports$1.SemanticTokenModifiers.definition]: 1 << 4,
      [mainExports$1.SemanticTokenModifiers.deprecated]: 1 << 5,
      [mainExports$1.SemanticTokenModifiers.documentation]: 1 << 6,
      [mainExports$1.SemanticTokenModifiers.modification]: 1 << 7,
      [mainExports$1.SemanticTokenModifiers.readonly]: 1 << 8,
      [mainExports$1.SemanticTokenModifiers.static]: 1 << 9
    });
    function mergeSemanticTokenProviderOptions(options) {
      const tokenTypes = [];
      const tokenModifiers = [];
      let full = true;
      let delta = true;
      let range = true;
      for (const option2 of options) {
        if (!option2) {
          continue;
        }
        option2.legend.tokenTypes.forEach((tokenType, index) => {
          const existing = tokenTypes[index];
          if (existing && existing !== tokenType) {
            throw new Error(`Cannot merge '${existing}' and '${tokenType}' token types. They use the same index ${index}.`);
          } else {
            tokenTypes[index] = tokenType;
          }
        });
        option2.legend.tokenModifiers.forEach((tokenModifier, index) => {
          const existing = tokenModifiers[index];
          if (existing && existing !== tokenModifier) {
            throw new Error(`Cannot merge '${existing}' and '${tokenModifier}' token modifier. They use the same index ${index}.`);
          } else {
            tokenModifiers[index] = tokenModifier;
          }
        });
        if (!option2.full) {
          full = false;
        } else if (typeof option2.full === "object" && !option2.full.delta) {
          delta = false;
        }
        if (!option2.range) {
          range = false;
        }
      }
      return {
        legend: {
          tokenTypes,
          tokenModifiers
        },
        full: full && { delta },
        range
      };
    }
    var SemanticTokensDecoder;
    (function(SemanticTokensDecoder2) {
      function decode(tokens2, tokenTypes, document) {
        const typeMap = /* @__PURE__ */ new Map();
        Object.entries(tokenTypes).forEach(([type, index]) => typeMap.set(index, type));
        let line = 0;
        let character = 0;
        return sliceIntoChunks(tokens2.data, 5).map((t) => {
          line += t[0];
          if (t[0] !== 0) {
            character = 0;
          }
          character += t[1];
          const length = t[2];
          const offset = document.textDocument.offsetAt({ line, character });
          return {
            offset,
            tokenType: typeMap.get(t[3]),
            tokenModifiers: t[4],
            text: document.textDocument.getText({ start: { line, character }, end: { line, character: character + length } })
          };
        });
      }
      SemanticTokensDecoder2.decode = decode;
      function sliceIntoChunks(arr, chunkSize) {
        const res = [];
        for (let i = 0; i < arr.length; i += chunkSize) {
          const chunk = arr.slice(i, i + chunkSize);
          res.push(chunk);
        }
        return res;
      }
    })(SemanticTokensDecoder || (SemanticTokensDecoder = {}));
    function mergeSignatureHelpOptions(options) {
      const triggerCharacters = [];
      const retriggerCharacters = [];
      options.forEach((option2) => {
        if (option2?.triggerCharacters) {
          triggerCharacters.push(...option2.triggerCharacters);
        }
        if (option2?.retriggerCharacters) {
          retriggerCharacters.push(...option2.retriggerCharacters);
        }
      });
      const mergedOptions = {
        triggerCharacters: triggerCharacters.length > 0 ? Array.from(new Set(triggerCharacters)).sort() : void 0,
        retriggerCharacters: retriggerCharacters.length > 0 ? Array.from(new Set(retriggerCharacters)).sort() : void 0
      };
      return mergedOptions.triggerCharacters ? mergedOptions : void 0;
    }
    class DefaultLanguageServer {
      constructor(services) {
        this.onInitializeEmitter = new mainExports.Emitter();
        this.onInitializedEmitter = new mainExports.Emitter();
        this.services = services;
      }
      get onInitialize() {
        return this.onInitializeEmitter.event;
      }
      get onInitialized() {
        return this.onInitializedEmitter.event;
      }
      async initialize(params) {
        this.eagerLoadServices();
        this.fireInitializeOnDefaultServices(params);
        this.onInitializeEmitter.fire(params);
        this.onInitializeEmitter.dispose();
        return this.buildInitializeResult(params);
      }
      /**
       * Eagerly loads all services before emitting the `onInitialize` event.
       * Ensures that all services are able to catch the event.
       */
      eagerLoadServices() {
        eagerLoad(this.services);
        this.services.ServiceRegistry.all.forEach((language) => eagerLoad(language));
      }
      hasService(callback) {
        const allServices = this.services.ServiceRegistry.all;
        return allServices.some((services) => callback(services) !== void 0);
      }
      buildInitializeResult(_params) {
        const documentUpdateHandler = this.services.lsp.DocumentUpdateHandler;
        const fileOperationOptions = this.services.lsp.FileOperationHandler?.fileOperationOptions;
        const allServices = this.services.ServiceRegistry.all;
        const hasFormattingService = this.hasService((e) => e.lsp?.Formatter);
        const formattingOnTypeOptions = allServices.map((e) => e.lsp?.Formatter?.formatOnTypeOptions).find((e) => Boolean(e));
        const hasCodeActionProvider = this.hasService((e) => e.lsp?.CodeActionProvider);
        const hasSemanticTokensProvider = this.hasService((e) => e.lsp?.SemanticTokenProvider);
        const semanticTokensOptions = mergeSemanticTokenProviderOptions(allServices.map((e) => e.lsp?.SemanticTokenProvider?.semanticTokensOptions));
        const commandNames = this.services.lsp?.ExecuteCommandHandler?.commands;
        const hasDocumentLinkProvider = this.hasService((e) => e.lsp?.DocumentLinkProvider);
        const signatureHelpOptions = mergeSignatureHelpOptions(allServices.map((e) => e.lsp?.SignatureHelp?.signatureHelpOptions));
        const hasGoToTypeProvider = this.hasService((e) => e.lsp?.TypeProvider);
        const hasGoToImplementationProvider = this.hasService((e) => e.lsp?.ImplementationProvider);
        const hasCompletionProvider = this.hasService((e) => e.lsp?.CompletionProvider);
        const completionOptions = mergeCompletionProviderOptions(allServices.map((e) => e.lsp?.CompletionProvider?.completionOptions));
        const hasReferencesProvider = this.hasService((e) => e.lsp?.ReferencesProvider);
        const hasDocumentSymbolProvider = this.hasService((e) => e.lsp?.DocumentSymbolProvider);
        const hasDefinitionProvider = this.hasService((e) => e.lsp?.DefinitionProvider);
        const hasDocumentHighlightProvider = this.hasService((e) => e.lsp?.DocumentHighlightProvider);
        const hasFoldingRangeProvider = this.hasService((e) => e.lsp?.FoldingRangeProvider);
        const hasHoverProvider = this.hasService((e) => e.lsp?.HoverProvider);
        const hasRenameProvider = this.hasService((e) => e.lsp?.RenameProvider);
        const hasCallHierarchyProvider = this.hasService((e) => e.lsp?.CallHierarchyProvider);
        const hasTypeHierarchyProvider = this.hasService((e) => e.lsp?.TypeHierarchyProvider);
        const hasCodeLensProvider = this.hasService((e) => e.lsp?.CodeLensProvider);
        const hasDeclarationProvider = this.hasService((e) => e.lsp?.DeclarationProvider);
        const hasInlayHintProvider = this.hasService((e) => e.lsp?.InlayHintProvider);
        const workspaceSymbolProvider = this.services.lsp?.WorkspaceSymbolProvider;
        const result = {
          capabilities: {
            workspace: {
              workspaceFolders: {
                supported: true
              },
              fileOperations: fileOperationOptions
            },
            executeCommandProvider: commandNames && {
              commands: commandNames
            },
            textDocumentSync: {
              change: mainExports.TextDocumentSyncKind.Incremental,
              openClose: true,
              save: Boolean(documentUpdateHandler.didSaveDocument),
              willSave: Boolean(documentUpdateHandler.willSaveDocument),
              willSaveWaitUntil: Boolean(documentUpdateHandler.willSaveDocumentWaitUntil)
            },
            completionProvider: hasCompletionProvider ? completionOptions : void 0,
            referencesProvider: hasReferencesProvider,
            documentSymbolProvider: hasDocumentSymbolProvider,
            definitionProvider: hasDefinitionProvider,
            typeDefinitionProvider: hasGoToTypeProvider,
            documentHighlightProvider: hasDocumentHighlightProvider,
            codeActionProvider: hasCodeActionProvider,
            documentFormattingProvider: hasFormattingService,
            documentRangeFormattingProvider: hasFormattingService,
            documentOnTypeFormattingProvider: formattingOnTypeOptions,
            foldingRangeProvider: hasFoldingRangeProvider,
            hoverProvider: hasHoverProvider,
            renameProvider: hasRenameProvider ? {
              prepareProvider: true
            } : void 0,
            semanticTokensProvider: hasSemanticTokensProvider ? semanticTokensOptions : void 0,
            signatureHelpProvider: signatureHelpOptions,
            implementationProvider: hasGoToImplementationProvider,
            callHierarchyProvider: hasCallHierarchyProvider ? {} : void 0,
            typeHierarchyProvider: hasTypeHierarchyProvider ? {} : void 0,
            documentLinkProvider: hasDocumentLinkProvider ? { resolveProvider: false } : void 0,
            codeLensProvider: hasCodeLensProvider ? { resolveProvider: false } : void 0,
            declarationProvider: hasDeclarationProvider,
            inlayHintProvider: hasInlayHintProvider ? { resolveProvider: false } : void 0,
            workspaceSymbolProvider: workspaceSymbolProvider ? { resolveProvider: Boolean(workspaceSymbolProvider.resolveSymbol) } : void 0
          }
        };
        return result;
      }
      initialized(params) {
        this.fireInitializedOnDefaultServices(params);
        this.onInitializedEmitter.fire(params);
        this.onInitializedEmitter.dispose();
      }
      fireInitializeOnDefaultServices(params) {
        this.services.workspace.ConfigurationProvider.initialize(params);
        this.services.workspace.WorkspaceManager.initialize(params);
      }
      fireInitializedOnDefaultServices(params) {
        const connection2 = this.services.lsp.Connection;
        const configurationParams = connection2 ? {
          ...params,
          register: (params2) => connection2.client.register(mainExports.DidChangeConfigurationNotification.type, params2),
          fetchConfiguration: (params2) => connection2.workspace.getConfiguration(params2)
        } : params;
        this.services.workspace.ConfigurationProvider.initialized(configurationParams).catch((err) => console.error("Error in ConfigurationProvider initialization:", err));
        this.services.workspace.WorkspaceManager.initialized(params).catch((err) => console.error("Error in WorkspaceManager initialization:", err));
      }
    }
    function isDocumentState(obj) {
      return typeof obj === "number";
    }
    var WorkspaceState;
    (function(WorkspaceState2) {
      WorkspaceState2.Parsed = Object.freeze({ type: "workspace", state: DocumentState.Parsed });
      WorkspaceState2.IndexedContent = Object.freeze({ type: "workspace", state: DocumentState.IndexedContent });
      WorkspaceState2.ComputedScopes = Object.freeze({ type: "workspace", state: DocumentState.ComputedScopes });
      WorkspaceState2.Linked = Object.freeze({ type: "workspace", state: DocumentState.Linked });
      WorkspaceState2.IndexedReferences = Object.freeze({ type: "workspace", state: DocumentState.IndexedReferences });
      WorkspaceState2.Validated = Object.freeze({ type: "workspace", state: DocumentState.Validated });
    })(WorkspaceState || (WorkspaceState = {}));
    function startLanguageServer(services, serviceRequirements = {}) {
      const connection2 = services.lsp.Connection;
      if (!connection2) {
        throw new Error("Starting a language server requires the languageServer.Connection service to be set.");
      }
      addDocumentUpdateHandler(connection2, services);
      addFileOperationHandler(connection2, services);
      addDiagnosticsHandler(connection2, services);
      addCompletionHandler(connection2, services, serviceRequirements.CompletionProvider);
      addFindReferencesHandler(connection2, services, serviceRequirements.ReferencesProvider);
      addDocumentSymbolHandler(connection2, services, serviceRequirements.DocumentSymbolProvider);
      addGotoDefinitionHandler(connection2, services, serviceRequirements.DefinitionProvider);
      addGoToTypeDefinitionHandler(connection2, services, serviceRequirements.TypeProvider);
      addGoToImplementationHandler(connection2, services, serviceRequirements.ImplementationProvider);
      addDocumentHighlightHandler(connection2, services, serviceRequirements.DocumentHighlightProvider);
      addFoldingRangeHandler(connection2, services, serviceRequirements.FoldingRangeProvider);
      addFormattingHandler(connection2, services, serviceRequirements.Formatter);
      addCodeActionHandler(connection2, services, serviceRequirements.CodeActionProvider);
      addRenameHandler(connection2, services, serviceRequirements.RenameProvider);
      addHoverHandler(connection2, services, serviceRequirements.HoverProvider);
      addInlayHintHandler(connection2, services, serviceRequirements.InlayHintProvider);
      addSemanticTokenHandler(connection2, services, serviceRequirements.SemanticTokenProvider);
      addExecuteCommandHandler(connection2, services);
      addSignatureHelpHandler(connection2, services, serviceRequirements.SignatureHelp);
      addCallHierarchyHandler(connection2, services, serviceRequirements.CallHierarchyProvider);
      addTypeHierarchyHandler(connection2, services, serviceRequirements.TypeHierarchyProvider);
      addCodeLensHandler(connection2, services, serviceRequirements.CodeLensProvider);
      addDocumentLinkHandler(connection2, services, serviceRequirements.DocumentLinkProvider);
      addConfigurationChangeHandler(connection2, services);
      addGoToDeclarationHandler(connection2, services, serviceRequirements.DeclarationProvider);
      addWorkspaceSymbolHandler(connection2, services, serviceRequirements.WorkspaceSymbolProvider);
      connection2.onInitialize((params) => {
        return services.lsp.LanguageServer.initialize(params);
      });
      connection2.onInitialized((params) => {
        services.lsp.LanguageServer.initialized(params);
      });
      const documents = services.workspace.TextDocuments;
      documents.listen(connection2);
      connection2.listen();
    }
    function addDocumentUpdateHandler(connection2, services) {
      const handler = services.lsp.DocumentUpdateHandler;
      const documents = services.workspace.TextDocuments;
      if (handler.didOpenDocument) {
        documents.onDidOpen((change) => handler.didOpenDocument(change));
      }
      if (handler.didChangeContent) {
        documents.onDidChangeContent((change) => handler.didChangeContent(change));
      }
      if (handler.didCloseDocument) {
        documents.onDidClose((change) => handler.didCloseDocument(change));
      }
      if (handler.didSaveDocument) {
        documents.onDidSave((change) => handler.didSaveDocument(change));
      }
      if (handler.willSaveDocument) {
        documents.onWillSave((event) => handler.willSaveDocument(event));
      }
      if (handler.willSaveDocumentWaitUntil) {
        documents.onWillSaveWaitUntil((event) => handler.willSaveDocumentWaitUntil(event));
      }
      if (handler.didChangeWatchedFiles) {
        connection2.onDidChangeWatchedFiles((params) => handler.didChangeWatchedFiles(params));
      }
    }
    function addFileOperationHandler(connection2, services) {
      const handler = services.lsp.FileOperationHandler;
      if (!handler) {
        return;
      }
      if (handler.didCreateFiles) {
        connection2.workspace.onDidCreateFiles((params) => handler.didCreateFiles(params));
      }
      if (handler.didRenameFiles) {
        connection2.workspace.onDidRenameFiles((params) => handler.didRenameFiles(params));
      }
      if (handler.didDeleteFiles) {
        connection2.workspace.onDidDeleteFiles((params) => handler.didDeleteFiles(params));
      }
      if (handler.willCreateFiles) {
        connection2.workspace.onWillCreateFiles((params) => handler.willCreateFiles(params));
      }
      if (handler.willRenameFiles) {
        connection2.workspace.onWillRenameFiles((params) => handler.willRenameFiles(params));
      }
      if (handler.willDeleteFiles) {
        connection2.workspace.onWillDeleteFiles((params) => handler.willDeleteFiles(params));
      }
    }
    function addDiagnosticsHandler(connection2, services) {
      const documentBuilder = services.workspace.DocumentBuilder;
      documentBuilder.onUpdate(async (_2, deleted) => {
        for (const uri of deleted) {
          connection2.sendDiagnostics({
            uri: uri.toString(),
            diagnostics: []
          });
        }
      });
      documentBuilder.onDocumentPhase(DocumentState.Validated, async (document) => {
        if (document.diagnostics) {
          connection2.sendDiagnostics({
            uri: document.uri.toString(),
            diagnostics: document.diagnostics
          });
        }
      });
    }
    function addCompletionHandler(connection2, services, requiredState = DocumentState.Linked) {
      connection2.onCompletion(createRequestHandler((services2, document, params, cancelToken) => {
        return services2.lsp?.CompletionProvider?.getCompletion(document, params, cancelToken);
      }, services, requiredState));
    }
    function addFindReferencesHandler(connection2, services, requiredState = WorkspaceState.IndexedReferences) {
      connection2.onReferences(createRequestHandler((services2, document, params, cancelToken) => services2.lsp?.ReferencesProvider?.findReferences(document, params, cancelToken), services, requiredState));
    }
    function addCodeActionHandler(connection2, services, requiredState = DocumentState.Validated) {
      connection2.onCodeAction(createRequestHandler((services2, document, params, cancelToken) => services2.lsp?.CodeActionProvider?.getCodeActions(document, params, cancelToken), services, requiredState));
    }
    function addDocumentSymbolHandler(connection2, services, requiredState = DocumentState.Parsed) {
      connection2.onDocumentSymbol(createRequestHandler((services2, document, params, cancelToken) => services2.lsp?.DocumentSymbolProvider?.getSymbols(document, params, cancelToken), services, requiredState));
    }
    function addGotoDefinitionHandler(connection2, services, requiredState = DocumentState.Linked) {
      connection2.onDefinition(createRequestHandler((services2, document, params, cancelToken) => services2.lsp?.DefinitionProvider?.getDefinition(document, params, cancelToken), services, requiredState));
    }
    function addGoToTypeDefinitionHandler(connection2, services, requiredState = DocumentState.Linked) {
      connection2.onTypeDefinition(createRequestHandler((services2, document, params, cancelToken) => services2.lsp?.TypeProvider?.getTypeDefinition(document, params, cancelToken), services, requiredState));
    }
    function addGoToImplementationHandler(connection2, services, requiredState = WorkspaceState.IndexedReferences) {
      connection2.onImplementation(createRequestHandler((services2, document, params, cancelToken) => services2.lsp?.ImplementationProvider?.getImplementation(document, params, cancelToken), services, requiredState));
    }
    function addGoToDeclarationHandler(connection2, services, requiredState = DocumentState.Linked) {
      connection2.onDeclaration(createRequestHandler((services2, document, params, cancelToken) => services2.lsp?.DeclarationProvider?.getDeclaration(document, params, cancelToken), services, requiredState));
    }
    function addDocumentHighlightHandler(connection2, services, requiredState = WorkspaceState.IndexedReferences) {
      connection2.onDocumentHighlight(createRequestHandler((services2, document, params, cancelToken) => services2.lsp?.DocumentHighlightProvider?.getDocumentHighlight(document, params, cancelToken), services, requiredState));
    }
    function addHoverHandler(connection2, services, requiredState = DocumentState.Linked) {
      connection2.onHover(createRequestHandler((services2, document, params, cancelToken) => services2.lsp?.HoverProvider?.getHoverContent(document, params, cancelToken), services, requiredState));
    }
    function addFoldingRangeHandler(connection2, services, requiredState = DocumentState.Parsed) {
      connection2.onFoldingRanges(createRequestHandler((services2, document, params, cancelToken) => services2.lsp?.FoldingRangeProvider?.getFoldingRanges(document, params, cancelToken), services, requiredState));
    }
    function addFormattingHandler(connection2, services, requiredState = DocumentState.Parsed) {
      connection2.onDocumentFormatting(createRequestHandler((services2, document, params, cancelToken) => services2.lsp?.Formatter?.formatDocument(document, params, cancelToken), services, requiredState));
      connection2.onDocumentRangeFormatting(createRequestHandler((services2, document, params, cancelToken) => services2.lsp?.Formatter?.formatDocumentRange(document, params, cancelToken), services, requiredState));
      connection2.onDocumentOnTypeFormatting(createRequestHandler((services2, document, params, cancelToken) => services2.lsp?.Formatter?.formatDocumentOnType(document, params, cancelToken), services, requiredState));
    }
    function addRenameHandler(connection2, services, requiredState = WorkspaceState.IndexedReferences) {
      connection2.onRenameRequest(createRequestHandler((services2, document, params, cancelToken) => services2.lsp?.RenameProvider?.rename(document, params, cancelToken), services, requiredState));
      connection2.onPrepareRename(createRequestHandler((services2, document, params, cancelToken) => services2.lsp?.RenameProvider?.prepareRename(document, params, cancelToken), services, requiredState));
    }
    function addInlayHintHandler(connection2, services, requiredState = DocumentState.IndexedReferences) {
      connection2.languages.inlayHint.on(createServerRequestHandler((services2, document, params, cancelToken) => services2.lsp?.InlayHintProvider?.getInlayHints(document, params, cancelToken), services, requiredState));
    }
    function addSemanticTokenHandler(connection2, services, requiredState = DocumentState.Linked) {
      const emptyResult = { data: [] };
      connection2.languages.semanticTokens.on(createServerRequestHandler((services2, document, params, cancelToken) => {
        if (services2.lsp?.SemanticTokenProvider) {
          return services2.lsp.SemanticTokenProvider.semanticHighlight(document, params, cancelToken);
        }
        return emptyResult;
      }, services, requiredState));
      connection2.languages.semanticTokens.onDelta(createServerRequestHandler((services2, document, params, cancelToken) => {
        if (services2.lsp?.SemanticTokenProvider) {
          return services2.lsp.SemanticTokenProvider.semanticHighlightDelta(document, params, cancelToken);
        }
        return emptyResult;
      }, services, requiredState));
      connection2.languages.semanticTokens.onRange(createServerRequestHandler((services2, document, params, cancelToken) => {
        if (services2.lsp?.SemanticTokenProvider) {
          return services2.lsp.SemanticTokenProvider.semanticHighlightRange(document, params, cancelToken);
        }
        return emptyResult;
      }, services, requiredState));
    }
    function addConfigurationChangeHandler(connection2, services) {
      connection2.onDidChangeConfiguration((change) => {
        services.workspace.ConfigurationProvider.updateConfiguration(change);
      });
    }
    function addExecuteCommandHandler(connection2, services) {
      const commandHandler = services.lsp.ExecuteCommandHandler;
      if (commandHandler) {
        connection2.onExecuteCommand(async (params, token) => {
          try {
            return await commandHandler.executeCommand(params.command, params.arguments ?? [], token);
          } catch (err) {
            return responseError(err);
          }
        });
      }
    }
    function addDocumentLinkHandler(connection2, services, requiredState = DocumentState.Parsed) {
      connection2.onDocumentLinks(createServerRequestHandler((services2, document, params, cancelToken) => services2.lsp?.DocumentLinkProvider?.getDocumentLinks(document, params, cancelToken), services, requiredState));
    }
    function addSignatureHelpHandler(connection2, services, requiredState = DocumentState.IndexedReferences) {
      connection2.onSignatureHelp(createServerRequestHandler((services2, document, params, cancelToken) => services2.lsp?.SignatureHelp?.provideSignatureHelp(document, params, cancelToken), services, requiredState));
    }
    function addCodeLensHandler(connection2, services, requiredState = DocumentState.IndexedReferences) {
      connection2.onCodeLens(createServerRequestHandler((services2, document, params, cancelToken) => services2.lsp?.CodeLensProvider?.provideCodeLens(document, params, cancelToken), services, requiredState));
    }
    function addWorkspaceSymbolHandler(connection2, services, requiredState = WorkspaceState.IndexedContent) {
      const workspaceSymbolProvider = services.lsp.WorkspaceSymbolProvider;
      if (workspaceSymbolProvider) {
        if (isDocumentState(requiredState) || requiredState.type === "document") {
          throw new Error('Workspace symbol requests are independent of a certain document, so the given document-specific required state is invalid. Provide a service requirement of type "workspace".');
        }
        const documentBuilder = services.workspace.DocumentBuilder;
        connection2.onWorkspaceSymbol(async (params, token) => {
          try {
            await documentBuilder.waitUntil(requiredState.state, token);
            return await workspaceSymbolProvider.getSymbols(params, token);
          } catch (err) {
            return responseError(err);
          }
        });
        const resolveWorkspaceSymbol = workspaceSymbolProvider.resolveSymbol?.bind(workspaceSymbolProvider);
        if (resolveWorkspaceSymbol) {
          connection2.onWorkspaceSymbolResolve(async (workspaceSymbol, token) => {
            try {
              await documentBuilder.waitUntil(requiredState.state, token);
              return await resolveWorkspaceSymbol(workspaceSymbol, token);
            } catch (err) {
              return responseError(err);
            }
          });
        }
      }
    }
    function addCallHierarchyHandler(connection2, services, requiredState = WorkspaceState.IndexedReferences) {
      connection2.languages.callHierarchy.onPrepare(createServerRequestHandler(async (services2, document, params, cancelToken) => {
        if (services2.lsp?.CallHierarchyProvider) {
          const result = await services2.lsp.CallHierarchyProvider.prepareCallHierarchy(document, params, cancelToken);
          return result ?? null;
        }
        return null;
      }, services, requiredState));
      connection2.languages.callHierarchy.onIncomingCalls(createHierarchyRequestHandler(async (services2, params, cancelToken) => {
        if (services2.lsp?.CallHierarchyProvider) {
          const result = await services2.lsp.CallHierarchyProvider.incomingCalls(params, cancelToken);
          return result ?? null;
        }
        return null;
      }, services, requiredState));
      connection2.languages.callHierarchy.onOutgoingCalls(createHierarchyRequestHandler(async (services2, params, cancelToken) => {
        if (services2.lsp?.CallHierarchyProvider) {
          const result = await services2.lsp.CallHierarchyProvider.outgoingCalls(params, cancelToken);
          return result ?? null;
        }
        return null;
      }, services, requiredState));
    }
    function addTypeHierarchyHandler(connection2, sharedServices, requiredState = WorkspaceState.IndexedReferences) {
      if (!sharedServices.ServiceRegistry.all.some((services) => services.lsp?.TypeHierarchyProvider)) {
        return;
      }
      connection2.languages.typeHierarchy.onPrepare(createServerRequestHandler(async (services, document, params, cancelToken) => {
        const result = await services.lsp?.TypeHierarchyProvider?.prepareTypeHierarchy(document, params, cancelToken);
        return result ?? null;
      }, sharedServices, requiredState));
      connection2.languages.typeHierarchy.onSupertypes(createHierarchyRequestHandler(async (services, params, cancelToken) => {
        const result = await services.lsp?.TypeHierarchyProvider?.supertypes(params, cancelToken);
        return result ?? null;
      }, sharedServices, requiredState));
      connection2.languages.typeHierarchy.onSubtypes(createHierarchyRequestHandler(async (services, params, cancelToken) => {
        const result = await services.lsp?.TypeHierarchyProvider?.subtypes(params, cancelToken);
        return result ?? null;
      }, sharedServices, requiredState));
    }
    function createHierarchyRequestHandler(serviceCall, sharedServices, requiredState) {
      const serviceRegistry = sharedServices.ServiceRegistry;
      return async (params, cancelToken) => {
        const uri = URI$1.parse(params.item.uri);
        const cancellationError = await waitUntilPhase(sharedServices, cancelToken, uri, requiredState);
        if (cancellationError) {
          return cancellationError;
        }
        if (!serviceRegistry.hasServices(uri)) {
          const errorText = `Could not find service instance for uri: '${uri}'`;
          console.debug(errorText);
          return responseError(new Error(errorText));
        }
        const language = serviceRegistry.getServices(uri);
        try {
          return await serviceCall(language, params, cancelToken);
        } catch (err) {
          return responseError(err);
        }
      };
    }
    function createServerRequestHandler(serviceCall, sharedServices, requiredState) {
      const documents = sharedServices.workspace.LangiumDocuments;
      const serviceRegistry = sharedServices.ServiceRegistry;
      return async (params, cancelToken) => {
        const uri = URI$1.parse(params.textDocument.uri);
        const cancellationError = await waitUntilPhase(sharedServices, cancelToken, uri, requiredState);
        if (cancellationError) {
          return cancellationError;
        }
        if (!serviceRegistry.hasServices(uri)) {
          const errorText = `Could not find service instance for uri: '${uri}'`;
          console.debug(errorText);
          return responseError(new Error(errorText));
        }
        const language = serviceRegistry.getServices(uri);
        try {
          const document = await documents.getOrCreateDocument(uri);
          return await serviceCall(language, document, params, cancelToken);
        } catch (err) {
          return responseError(err);
        }
      };
    }
    function createRequestHandler(serviceCall, sharedServices, requiredState) {
      const documents = sharedServices.workspace.LangiumDocuments;
      const serviceRegistry = sharedServices.ServiceRegistry;
      return async (params, cancelToken) => {
        const uri = URI$1.parse(params.textDocument.uri);
        const cancellationError = await waitUntilPhase(sharedServices, cancelToken, uri, requiredState);
        if (cancellationError) {
          return cancellationError;
        }
        if (!serviceRegistry.hasServices(uri)) {
          console.debug(`Could not find service instance for uri: '${uri.toString()}'`);
          return null;
        }
        const language = serviceRegistry.getServices(uri);
        try {
          const document = await documents.getOrCreateDocument(uri);
          return await serviceCall(language, document, params, cancelToken);
        } catch (err) {
          return responseError(err);
        }
      };
    }
    async function waitUntilPhase(services, cancelToken, uri, requiredState) {
      if (requiredState !== void 0) {
        const documentBuilder = services.workspace.DocumentBuilder;
        const workspaceManager = services.workspace.WorkspaceManager;
        try {
          await workspaceManager.ready;
          if (isDocumentState(requiredState)) {
            await documentBuilder.waitUntil(requiredState, uri, cancelToken);
          } else if (requiredState.type === "document") {
            await documentBuilder.waitUntil(requiredState.state, uri, cancelToken);
          } else {
            await documentBuilder.waitUntil(requiredState.state, cancelToken);
          }
        } catch (err) {
          return responseError(err);
        }
      }
      return void 0;
    }
    function responseError(err) {
      if (isOperationCancelled(err)) {
        return new mainExports.ResponseError(mainExports.LSPErrorCodes.RequestCancelled, "The request has been cancelled.");
      }
      if (err instanceof mainExports.ResponseError) {
        return err;
      }
      throw err;
    }
    class DefaultNodeKindProvider {
      /**
       * @remarks The default implementation returns `SymbolKind.Field` for all nodes.
       */
      getSymbolKind(_node) {
        return mainExports$1.SymbolKind.Field;
      }
      /**
       * @remarks The default implementation returns `CompletionItemKind.Reference` for all nodes.
       */
      getCompletionItemKind(_node) {
        return mainExports$1.CompletionItemKind.Reference;
      }
    }
    class DefaultReferencesProvider {
      constructor(services) {
        this.nameProvider = services.references.NameProvider;
        this.references = services.references.References;
        this.grammarConfig = services.parser.GrammarConfig;
      }
      findReferences(document, params, _cancelToken) {
        const rootNode = document.parseResult.value.$cstNode;
        if (!rootNode) {
          return [];
        }
        const selectedNode = findDeclarationNodeAtOffset(rootNode, document.textDocument.offsetAt(params.position), this.grammarConfig.nameRegexp);
        if (!selectedNode) {
          return [];
        }
        return this.getReferences(selectedNode, params, document);
      }
      getReferences(selectedNode, params, _document) {
        const locations = [];
        const targetAstNode = this.references.findDeclarations(selectedNode);
        for (const target of targetAstNode) {
          const options = { includeDeclaration: params.context.includeDeclaration };
          this.references.findReferences(target, options).forEach((reference) => {
            locations.push(mainExports$1.Location.create(reference.sourceUri.toString(), reference.segment.range));
          });
        }
        return locations;
      }
    }
    class DefaultRenameProvider {
      constructor(services) {
        this.references = services.references.References;
        this.nameProvider = services.references.NameProvider;
        this.grammarConfig = services.parser.GrammarConfig;
      }
      async rename(document, params, _cancelToken) {
        const changes = {};
        const rootNode = document.parseResult.value.$cstNode;
        if (!rootNode) {
          return void 0;
        }
        const offset = document.textDocument.offsetAt(params.position);
        const leafNode = findDeclarationNodeAtOffset(rootNode, offset, this.grammarConfig.nameRegexp);
        if (!leafNode) {
          return void 0;
        }
        const targetNodes = this.references.findDeclarations(leafNode);
        if (targetNodes.length === 0) {
          return void 0;
        }
        const targetNode = targetNodes[0];
        const options = { onlyLocal: false, includeDeclaration: true };
        const references = this.references.findReferences(targetNode, options);
        for (const ref of references) {
          const change = TextEdit.replace(ref.segment.range, params.newName);
          const uri = ref.sourceUri.toString();
          if (changes[uri]) {
            changes[uri].push(change);
          } else {
            changes[uri] = [change];
          }
        }
        return { changes };
      }
      prepareRename(document, params, _cancelToken) {
        return this.renameNodeRange(document, params.position);
      }
      renameNodeRange(doc, position) {
        const rootNode = doc.parseResult.value.$cstNode;
        const offset = doc.textDocument.offsetAt(position);
        if (rootNode) {
          const leafNode = findDeclarationNodeAtOffset(rootNode, offset, this.grammarConfig.nameRegexp);
          if (!leafNode) {
            return void 0;
          }
          const isCrossRef = this.references.findDeclarations(leafNode).length > 0;
          if (isCrossRef || this.isNameNode(leafNode)) {
            return leafNode.range;
          }
        }
        return void 0;
      }
      isNameNode(leafNode) {
        return leafNode?.astNode && isNamed(leafNode.astNode) && leafNode === this.nameProvider.getNameNode(leafNode.astNode);
      }
    }
    class DefaultWorkspaceSymbolProvider {
      constructor(services) {
        this.indexManager = services.workspace.IndexManager;
        this.nodeKindProvider = services.lsp.NodeKindProvider;
        this.fuzzyMatcher = services.lsp.FuzzyMatcher;
      }
      async getSymbols(params, cancelToken = cancellationExports.CancellationToken.None) {
        const workspaceSymbols = [];
        const query = params.query.toLowerCase();
        for (const description of this.indexManager.allElements()) {
          await interruptAndCheck(cancelToken);
          if (this.fuzzyMatcher.match(query, description.name)) {
            const symbol = this.getWorkspaceSymbol(description);
            if (symbol) {
              workspaceSymbols.push(symbol);
            }
          }
        }
        return workspaceSymbols;
      }
      getWorkspaceSymbol(astDescription) {
        const nameSegment = astDescription.nameSegment;
        if (nameSegment) {
          return {
            kind: this.nodeKindProvider.getSymbolKind(astDescription),
            name: astDescription.name,
            location: {
              range: nameSegment.range,
              uri: astDescription.documentUri.toString()
            }
          };
        } else {
          return void 0;
        }
      }
    }
    class NormalizedTextDocuments {
      constructor(configuration2) {
        this._configuration = configuration2;
        this._syncedDocuments = /* @__PURE__ */ new Map();
        this._onDidChangeContent = new mainExports$1.Emitter();
        this._onDidOpen = new mainExports$1.Emitter();
        this._onDidClose = new mainExports$1.Emitter();
        this._onDidSave = new mainExports$1.Emitter();
        this._onWillSave = new mainExports$1.Emitter();
      }
      get onDidOpen() {
        return this._onDidOpen.event;
      }
      get onDidChangeContent() {
        return this._onDidChangeContent.event;
      }
      get onWillSave() {
        return this._onWillSave.event;
      }
      onWillSaveWaitUntil(handler) {
        this._willSaveWaitUntil = handler;
      }
      get onDidSave() {
        return this._onDidSave.event;
      }
      get onDidClose() {
        return this._onDidClose.event;
      }
      get(uri) {
        return this._syncedDocuments.get(UriUtils.normalize(uri));
      }
      set(document) {
        const uri = UriUtils.normalize(document.uri);
        let result = true;
        if (this._syncedDocuments.has(uri)) {
          result = false;
        }
        this._syncedDocuments.set(uri, document);
        const toFire = Object.freeze({ document });
        this._onDidOpen.fire(toFire);
        this._onDidChangeContent.fire(toFire);
        return result;
      }
      delete(uri) {
        const uriString = UriUtils.normalize(typeof uri === "object" && "uri" in uri ? uri.uri : uri);
        const syncedDocument = this._syncedDocuments.get(uriString);
        if (syncedDocument !== void 0) {
          this._syncedDocuments.delete(uriString);
          this._onDidClose.fire(Object.freeze({ document: syncedDocument }));
        }
      }
      all() {
        return Array.from(this._syncedDocuments.values());
      }
      keys() {
        return Array.from(this._syncedDocuments.keys());
      }
      listen(connection2) {
        connection2.__textDocumentSync = mainExports$1.TextDocumentSyncKind.Incremental;
        const disposables = [];
        disposables.push(connection2.onDidOpenTextDocument((event) => {
          const td = event.textDocument;
          const uri = UriUtils.normalize(td.uri);
          const document = this._configuration.create(uri, td.languageId, td.version, td.text);
          this._syncedDocuments.set(uri, document);
          const toFire = Object.freeze({ document });
          this._onDidOpen.fire(toFire);
          this._onDidChangeContent.fire(toFire);
        }));
        disposables.push(connection2.onDidChangeTextDocument((event) => {
          const td = event.textDocument;
          const changes = event.contentChanges;
          if (changes.length === 0) {
            return;
          }
          const { version } = td;
          if (version === null || version === void 0) {
            throw new Error(`Received document change event for ${td.uri} without valid version identifier`);
          }
          const uri = UriUtils.normalize(td.uri);
          let syncedDocument = this._syncedDocuments.get(uri);
          if (syncedDocument !== void 0) {
            syncedDocument = this._configuration.update(syncedDocument, changes, version);
            this._syncedDocuments.set(uri, syncedDocument);
            this._onDidChangeContent.fire(Object.freeze({ document: syncedDocument }));
          }
        }));
        disposables.push(connection2.onDidCloseTextDocument((event) => {
          const uri = UriUtils.normalize(event.textDocument.uri);
          const syncedDocument = this._syncedDocuments.get(uri);
          if (syncedDocument !== void 0) {
            this._syncedDocuments.delete(uri);
            this._onDidClose.fire(Object.freeze({ document: syncedDocument }));
          }
        }));
        disposables.push(connection2.onWillSaveTextDocument((event) => {
          const syncedDocument = this._syncedDocuments.get(UriUtils.normalize(event.textDocument.uri));
          if (syncedDocument !== void 0) {
            this._onWillSave.fire(Object.freeze({ document: syncedDocument, reason: event.reason }));
          }
        }));
        disposables.push(connection2.onWillSaveTextDocumentWaitUntil((event, token) => {
          const syncedDocument = this._syncedDocuments.get(UriUtils.normalize(event.textDocument.uri));
          if (syncedDocument !== void 0 && this._willSaveWaitUntil) {
            return this._willSaveWaitUntil(Object.freeze({ document: syncedDocument, reason: event.reason }), token);
          } else {
            return [];
          }
        }));
        disposables.push(connection2.onDidSaveTextDocument((event) => {
          const syncedDocument = this._syncedDocuments.get(UriUtils.normalize(event.textDocument.uri));
          if (syncedDocument !== void 0) {
            this._onDidSave.fire(Object.freeze({ document: syncedDocument }));
          }
        }));
        return mainExports$1.Disposable.create(() => {
          disposables.forEach((disposable2) => disposable2.dispose());
        });
      }
    }
    class NormalizedNotebookDocuments {
      constructor(configurationOrTextDocuments) {
        this.notebookDocuments = /* @__PURE__ */ new Map();
        this.notebookCellMap = /* @__PURE__ */ new Map();
        this._onDidOpen = new mainExports$1.Emitter();
        this._onDidSave = new mainExports$1.Emitter();
        this._onDidChange = new mainExports$1.Emitter();
        this._onDidClose = new mainExports$1.Emitter();
        if ("listen" in configurationOrTextDocuments) {
          this._cellTextDocuments = configurationOrTextDocuments;
        } else {
          this._cellTextDocuments = new NormalizedTextDocuments(configurationOrTextDocuments);
        }
      }
      get cellTextDocuments() {
        return this._cellTextDocuments;
      }
      getCellTextDocument(cell) {
        return this._cellTextDocuments.get(cell.document);
      }
      getNotebookDocument(uri) {
        return this.notebookDocuments.get(UriUtils.normalize(uri));
      }
      getNotebookCell(uri) {
        const value = this.notebookCellMap.get(UriUtils.normalize(uri));
        return value && value[0];
      }
      findNotebookDocumentForCell(cell) {
        const key = typeof cell === "string" || "scheme" in cell ? cell : cell.document;
        const value = this.notebookCellMap.get(UriUtils.normalize(key));
        return value && value[1];
      }
      get onDidOpen() {
        return this._onDidOpen.event;
      }
      get onDidSave() {
        return this._onDidSave.event;
      }
      get onDidChange() {
        return this._onDidChange.event;
      }
      get onDidClose() {
        return this._onDidClose.event;
      }
      /**
       * Listens for `low level` notification on the given connection to
       * update the notebook documents managed by this instance.
       *
       * Please note that the connection only provides handlers not an event model. Therefore
       * listening on a connection will overwrite the following handlers on a connection:
       * `onDidOpenNotebookDocument`, `onDidChangeNotebookDocument`, `onDidSaveNotebookDocument`,
       *  and `onDidCloseNotebookDocument`.
       *
       * @param connection The connection to listen on.
       */
      listen(connection2) {
        const cellTextDocumentConnection = new CellTextDocumentConnection();
        const disposables = [];
        disposables.push(this.cellTextDocuments.listen(cellTextDocumentConnection));
        disposables.push(connection2.notebooks.synchronization.onDidOpenNotebookDocument((params) => {
          const uri = UriUtils.normalize(params.notebookDocument.uri);
          this.notebookDocuments.set(uri, params.notebookDocument);
          for (const cellTextDocument of params.cellTextDocuments) {
            cellTextDocumentConnection.openTextDocument({ textDocument: cellTextDocument });
          }
          this.updateCellMap(params.notebookDocument);
          this._onDidOpen.fire(params.notebookDocument);
        }));
        disposables.push(connection2.notebooks.synchronization.onDidChangeNotebookDocument((params) => {
          const uri = UriUtils.normalize(params.notebookDocument.uri);
          const notebookDocument = this.notebookDocuments.get(uri);
          if (notebookDocument === void 0) {
            return;
          }
          notebookDocument.version = params.notebookDocument.version;
          const oldMetadata = notebookDocument.metadata;
          let metadataChanged = false;
          const change = params.change;
          if (change.metadata !== void 0) {
            metadataChanged = true;
            notebookDocument.metadata = change.metadata;
          }
          const opened = [];
          const closed = [];
          const data = [];
          const text = [];
          if (change.cells !== void 0) {
            const changedCells = change.cells;
            if (changedCells.structure !== void 0) {
              const array = changedCells.structure.array;
              notebookDocument.cells.splice(array.start, array.deleteCount, ...array.cells !== void 0 ? array.cells : []);
              if (changedCells.structure.didOpen !== void 0) {
                for (const open of changedCells.structure.didOpen) {
                  cellTextDocumentConnection.openTextDocument({ textDocument: open });
                  opened.push(open.uri);
                }
              }
              if (changedCells.structure.didClose) {
                for (const close of changedCells.structure.didClose) {
                  cellTextDocumentConnection.closeTextDocument({ textDocument: close });
                  closed.push(close.uri);
                }
              }
            }
            if (changedCells.data !== void 0) {
              const cellUpdates = new Map(changedCells.data.map((cell) => [cell.document, cell]));
              for (let i = 0; i <= notebookDocument.cells.length; i++) {
                const change2 = cellUpdates.get(notebookDocument.cells[i].document);
                if (change2 !== void 0) {
                  const old = notebookDocument.cells.splice(i, 1, change2);
                  data.push({ old: old[0], new: change2 });
                  cellUpdates.delete(change2.document);
                  if (cellUpdates.size === 0) {
                    break;
                  }
                }
              }
            }
            if (changedCells.textContent !== void 0) {
              for (const cellTextDocument of changedCells.textContent) {
                cellTextDocumentConnection.changeTextDocument({ textDocument: cellTextDocument.document, contentChanges: cellTextDocument.changes });
                text.push(cellTextDocument.document.uri);
              }
            }
          }
          this.updateCellMap(notebookDocument);
          const changeEvent = { notebookDocument };
          if (metadataChanged) {
            changeEvent.metadata = { old: oldMetadata, new: notebookDocument.metadata };
          }
          const added = [];
          for (const open of opened) {
            added.push(this.getNotebookCell(open));
          }
          const removed = [];
          for (const close of closed) {
            removed.push(this.getNotebookCell(close));
          }
          const textContent = [];
          for (const change2 of text) {
            textContent.push(this.getNotebookCell(change2));
          }
          if (added.length > 0 || removed.length > 0 || data.length > 0 || textContent.length > 0) {
            changeEvent.cells = { added, removed, changed: { data, textContent } };
          }
          if (changeEvent.metadata !== void 0 || changeEvent.cells !== void 0) {
            this._onDidChange.fire(changeEvent);
          }
        }));
        disposables.push(connection2.notebooks.synchronization.onDidSaveNotebookDocument((params) => {
          const notebookDocument = this.getNotebookDocument(params.notebookDocument.uri);
          if (notebookDocument === void 0) {
            return;
          }
          this._onDidSave.fire(notebookDocument);
        }));
        disposables.push(connection2.notebooks.synchronization.onDidCloseNotebookDocument((params) => {
          const uri = UriUtils.normalize(params.notebookDocument.uri);
          const notebookDocument = this.notebookDocuments.get(uri);
          if (notebookDocument === void 0) {
            return;
          }
          this._onDidClose.fire(notebookDocument);
          for (const cellTextDocument of params.cellTextDocuments) {
            cellTextDocumentConnection.closeTextDocument({ textDocument: cellTextDocument });
          }
          this.notebookDocuments.delete(uri);
          for (const cell of notebookDocument.cells) {
            this.notebookCellMap.delete(cell.document);
          }
        }));
        return mainExports$1.Disposable.create(() => {
          disposables.forEach((disposable2) => disposable2.dispose());
        });
      }
      updateCellMap(notebookDocument) {
        for (const cell of notebookDocument.cells) {
          this.notebookCellMap.set(cell.document, [cell, notebookDocument]);
        }
      }
    }
    class CellTextDocumentConnection {
      onDidOpenTextDocument(handler) {
        this.openHandler = handler;
        return mainExports$1.Disposable.create(() => {
          this.openHandler = void 0;
        });
      }
      openTextDocument(params) {
        this.openHandler && this.openHandler(params);
      }
      onDidChangeTextDocument(handler) {
        this.changeHandler = handler;
        return mainExports$1.Disposable.create(() => {
          this.changeHandler = handler;
        });
      }
      changeTextDocument(params) {
        this.changeHandler && this.changeHandler(params);
      }
      onDidCloseTextDocument(handler) {
        this.closeHandler = handler;
        return mainExports$1.Disposable.create(() => {
          this.closeHandler = void 0;
        });
      }
      closeTextDocument(params) {
        this.closeHandler && this.closeHandler(params);
      }
      onWillSaveTextDocument() {
        return CellTextDocumentConnection.NULL_DISPOSE;
      }
      onWillSaveTextDocumentWaitUntil() {
        return CellTextDocumentConnection.NULL_DISPOSE;
      }
      onDidSaveTextDocument() {
        return CellTextDocumentConnection.NULL_DISPOSE;
      }
    }
    CellTextDocumentConnection.NULL_DISPOSE = Object.freeze({ dispose: () => {
    } });
    function createDefaultModule(context) {
      return Module.merge(createDefaultCoreModule(context), createDefaultLSPModule(context));
    }
    function createDefaultLSPModule(context) {
      return {
        lsp: {
          CompletionProvider: (services) => new DefaultCompletionProvider(services),
          DocumentSymbolProvider: (services) => new DefaultDocumentSymbolProvider(services),
          HoverProvider: (services) => new MultilineCommentHoverProvider(services),
          FoldingRangeProvider: (services) => new DefaultFoldingRangeProvider(services),
          ReferencesProvider: (services) => new DefaultReferencesProvider(services),
          DefinitionProvider: (services) => new DefaultDefinitionProvider(services),
          DocumentHighlightProvider: (services) => new DefaultDocumentHighlightProvider(services),
          RenameProvider: (services) => new DefaultRenameProvider(services)
        },
        shared: () => context.shared
      };
    }
    function createDefaultSharedModule(context) {
      return Module.merge(createDefaultSharedCoreModule(context), createDefaultSharedLSPModule(context));
    }
    function createDefaultSharedLSPModule(context) {
      return {
        lsp: {
          Connection: () => context.connection,
          LanguageServer: (services) => new DefaultLanguageServer(services),
          DocumentUpdateHandler: (services) => new DefaultDocumentUpdateHandler(services),
          WorkspaceSymbolProvider: (services) => new DefaultWorkspaceSymbolProvider(services),
          NodeKindProvider: () => new DefaultNodeKindProvider(),
          FuzzyMatcher: () => new DefaultFuzzyMatcher()
        },
        workspace: {
          TextDocuments: () => new NormalizedTextDocuments(TextDocument),
          NotebookDocuments: (services) => new NormalizedNotebookDocuments(services.workspace.TextDocuments)
        }
      };
    }
    class NodeFileSystemProvider {
      constructor() {
        this.encoding = "utf-8";
      }
      async stat(uri) {
        const stat = await fs.promises.stat(uri.fsPath);
        return {
          isFile: stat.isFile(),
          isDirectory: stat.isDirectory(),
          uri
        };
      }
      statSync(uri) {
        const stat = fs.statSync(uri.fsPath);
        return {
          isFile: stat.isFile(),
          isDirectory: stat.isDirectory(),
          uri
        };
      }
      exists(uri) {
        return new Promise((resolve) => {
          fs.stat(uri.fsPath, (err) => {
            resolve(!err);
          });
        });
      }
      existsSync(uri) {
        return fs.existsSync(uri.fsPath);
      }
      readBinary(uri) {
        return fs.promises.readFile(uri.fsPath);
      }
      readBinarySync(uri) {
        return fs.readFileSync(uri.fsPath);
      }
      readFile(uri) {
        return fs.promises.readFile(uri.fsPath, this.encoding);
      }
      readFileSync(uri) {
        return fs.readFileSync(uri.fsPath, this.encoding);
      }
      async readDirectory(uri) {
        const dirents = await fs.promises.readdir(uri.fsPath, { withFileTypes: true });
        return dirents.map((dirent) => ({
          dirent,
          // Include the raw entry, it may be useful...
          isFile: dirent.isFile(),
          isDirectory: dirent.isDirectory(),
          uri: UriUtils.joinPath(uri, dirent.name)
        }));
      }
      readDirectorySync(uri) {
        const dirents = fs.readdirSync(uri.fsPath, { withFileTypes: true });
        return dirents.map((dirent) => ({
          dirent,
          // Include the raw entry, it may be useful...
          isFile: dirent.isFile(),
          isDirectory: dirent.isDirectory(),
          uri: UriUtils.joinPath(uri, dirent.name)
        }));
      }
    }
    const NodeFileSystem = {
      fileSystemProvider: () => new NodeFileSystemProvider()
    };
    var node;
    var hasRequiredNode;
    function requireNode() {
      if (hasRequiredNode) return node;
      hasRequiredNode = 1;
      node = requireMain();
      return node;
    }
    var nodeExports = requireNode();
    const AdditiveExpr = {
      $type: "AdditiveExpr",
      left: "left",
      op: "op",
      right: "right"
    };
    const Alt = {
      $type: "Alt",
      elseBlock: "elseBlock",
      elseIfBlocks: "elseIfBlocks",
      ifBlock: "ifBlock"
    };
    const AndExpr = {
      $type: "AndExpr",
      left: "left",
      op: "op",
      right: "right"
    };
    const Assignee = {
      $type: "Assignee",
      atom: "atom",
      ids: "ids"
    };
    const Assignment = {
      $type: "Assignment",
      assignee: "assignee",
      type: "type"
    };
    const AssignmentExpr = {
      $type: "AssignmentExpr",
      assignment: "assignment",
      expr: "expr"
    };
    const AsyncMessage = {
      $type: "AsyncMessage",
      content: "content",
      from: "from",
      to: "to"
    };
    const Atom = {
      $type: "Atom"
    };
    const AtomExpr = {
      $type: "AtomExpr",
      atom: "atom"
    };
    const Block = {
      $type: "Block",
      stats: "stats"
    };
    const BooleanAtom = {
      $type: "BooleanAtom",
      value: "value"
    };
    const BraceBlock = {
      $type: "BraceBlock",
      block: "block"
    };
    const CatchBlock = {
      $type: "CatchBlock",
      braceBlock: "braceBlock",
      invocation: "invocation"
    };
    const Condition = {
      $type: "Condition"
    };
    const Creation = {
      $type: "Creation",
      body: "body",
      braceBlock: "braceBlock"
    };
    function isCreation(item) {
      return reflection.isInstance(item, Creation.$type);
    }
    const CreationBody = {
      $type: "CreationBody",
      assignment: "assignment",
      construct: "construct",
      parameters: "parameters"
    };
    const CreationExpr = {
      $type: "CreationExpr",
      creation: "creation"
    };
    const Critical = {
      $type: "Critical",
      braceBlock: "braceBlock",
      parExpr: "parExpr"
    };
    const Declaration = {
      $type: "Declaration",
      name: "name",
      type: "type"
    };
    const DigitLeadingNameAtom = {
      $type: "DigitLeadingNameAtom",
      value: "value"
    };
    const Divider = {
      $type: "Divider",
      note: "note"
    };
    const ElseBlock = {
      $type: "ElseBlock",
      braceBlock: "braceBlock"
    };
    const ElseIfBlock = {
      $type: "ElseIfBlock",
      braceBlock: "braceBlock",
      parExpr: "parExpr"
    };
    const Emoji = {
      $type: "Emoji",
      name: "name"
    };
    const EqualityExpr = {
      $type: "EqualityExpr",
      left: "left",
      op: "op",
      right: "right"
    };
    const Expr = {
      $type: "Expr"
    };
    const FinallyBlock = {
      $type: "FinallyBlock",
      braceBlock: "braceBlock"
    };
    const From = {
      $type: "From",
      emoji: "emoji",
      name: "name"
    };
    function isFrom(item) {
      return reflection.isInstance(item, From.$type);
    }
    const FromTo = {
      $type: "FromTo",
      from: "from",
      to: "to"
    };
    const Func = {
      $type: "Func",
      signatures: "signatures"
    };
    const FuncExpr = {
      $type: "FuncExpr",
      func: "func",
      to: "to"
    };
    const Group = {
      $type: "Group",
      name: "name",
      participants: "participants"
    };
    function isGroup(item) {
      return reflection.isInstance(item, Group.$type);
    }
    const IdAtom = {
      $type: "IdAtom",
      value: "value"
    };
    const IfBlock = {
      $type: "IfBlock",
      braceBlock: "braceBlock",
      parExpr: "parExpr"
    };
    const InExpr = {
      $type: "InExpr",
      left: "left",
      right: "right"
    };
    const Invocation = {
      $type: "Invocation",
      parameters: "parameters"
    };
    const Label = {
      $type: "Label",
      name: "name"
    };
    const Loop = {
      $type: "Loop",
      braceBlock: "braceBlock",
      parExpr: "parExpr"
    };
    const Message = {
      $type: "Message",
      body: "body",
      braceBlock: "braceBlock"
    };
    function isMessage(item) {
      return reflection.isInstance(item, Message.$type);
    }
    const MessageBody = {
      $type: "MessageBody",
      assignment: "assignment",
      fromTo: "fromTo",
      func: "func"
    };
    const MethodName = {
      $type: "MethodName",
      emoji: "emoji",
      name: "name"
    };
    const MoneyAtom = {
      $type: "MoneyAtom",
      value: "value"
    };
    const MultiplicationExpr = {
      $type: "MultiplicationExpr",
      left: "left",
      op: "op",
      right: "right"
    };
    const NamedParameter = {
      $type: "NamedParameter",
      name: "name",
      value: "value"
    };
    const NilAtom = {
      $type: "NilAtom",
      value: "value"
    };
    const NotExpr = {
      $type: "NotExpr",
      expr: "expr"
    };
    const NumberAtom = {
      $type: "NumberAtom",
      value: "value"
    };
    const NumberUnitAtom = {
      $type: "NumberUnitAtom",
      value: "value"
    };
    const Opt = {
      $type: "Opt",
      braceBlock: "braceBlock",
      parExpr: "parExpr"
    };
    const OrExpr = {
      $type: "OrExpr",
      left: "left",
      op: "op",
      right: "right"
    };
    const Par = {
      $type: "Par",
      braceBlock: "braceBlock",
      parExpr: "parExpr"
    };
    const Parameter = {
      $type: "Parameter"
    };
    const Parameters = {
      $type: "Parameters",
      parameters: "parameters"
    };
    const ParenthesizedExpr = {
      $type: "ParenthesizedExpr",
      expr: "expr"
    };
    const ParExpr = {
      $type: "ParExpr",
      condition: "condition"
    };
    const Participant = {
      $type: "Participant",
      color: "color",
      emoji: "emoji",
      label: "label",
      name: "name",
      participantType: "participantType",
      stereotype: "stereotype",
      width: "width"
    };
    function isParticipant(item) {
      return reflection.isInstance(item, Participant.$type);
    }
    const Prog = {
      $type: "Prog",
      block: "block",
      headElements: "headElements",
      starterExp: "starterExp",
      title: "title"
    };
    const Ref = {
      $type: "Ref",
      names: "names"
    };
    const RelationalExpr = {
      $type: "RelationalExpr",
      left: "left",
      op: "op",
      right: "right"
    };
    const Ret = {
      $type: "Ret",
      asyncMessage: "asyncMessage",
      expr: "expr",
      returnAsyncMessage: "returnAsyncMessage"
    };
    const ReturnAsyncMessage = {
      $type: "ReturnAsyncMessage",
      content: "content",
      from: "from",
      to: "to"
    };
    const Section = {
      $type: "Section",
      atom: "atom",
      braceBlock: "braceBlock"
    };
    const Signature = {
      $type: "Signature",
      invocation: "invocation",
      methodName: "methodName"
    };
    const StarterExp = {
      $type: "StarterExp",
      annotation: "annotation",
      starter: "starter"
    };
    const Stat = {
      $type: "Stat"
    };
    const Stereotype = {
      $type: "Stereotype",
      name: "name"
    };
    const StringAtom = {
      $type: "StringAtom",
      value: "value"
    };
    const Tcf = {
      $type: "Tcf",
      catchBlocks: "catchBlocks",
      finallyBlock: "finallyBlock",
      tryBlock: "tryBlock"
    };
    const TextExpr = {
      $type: "TextExpr",
      words: "words"
    };
    const Title = {
      $type: "Title",
      content: "content"
    };
    function isTitle(item) {
      return reflection.isInstance(item, Title.$type);
    }
    const To = {
      $type: "To",
      emoji: "emoji",
      name: "name"
    };
    function isTo(item) {
      return reflection.isInstance(item, To.$type);
    }
    const TryBlock = {
      $type: "TryBlock",
      braceBlock: "braceBlock"
    };
    const UnaryMinusExpr = {
      $type: "UnaryMinusExpr",
      expr: "expr"
    };
    class ZenUmlAstReflection extends AbstractAstReflection {
      types = {
        AdditiveExpr: {
          name: AdditiveExpr.$type,
          properties: {
            left: {
              name: AdditiveExpr.left
            },
            op: {
              name: AdditiveExpr.op
            },
            right: {
              name: AdditiveExpr.right
            }
          },
          superTypes: [Expr.$type]
        },
        Alt: {
          name: Alt.$type,
          properties: {
            elseBlock: {
              name: Alt.elseBlock
            },
            elseIfBlocks: {
              name: Alt.elseIfBlocks,
              defaultValue: []
            },
            ifBlock: {
              name: Alt.ifBlock
            }
          },
          superTypes: [Stat.$type]
        },
        AndExpr: {
          name: AndExpr.$type,
          properties: {
            left: {
              name: AndExpr.left
            },
            op: {
              name: AndExpr.op
            },
            right: {
              name: AndExpr.right
            }
          },
          superTypes: [Expr.$type]
        },
        Assignee: {
          name: Assignee.$type,
          properties: {
            atom: {
              name: Assignee.atom
            },
            ids: {
              name: Assignee.ids,
              defaultValue: []
            }
          },
          superTypes: []
        },
        Assignment: {
          name: Assignment.$type,
          properties: {
            assignee: {
              name: Assignment.assignee
            },
            type: {
              name: Assignment.type
            }
          },
          superTypes: []
        },
        AssignmentExpr: {
          name: AssignmentExpr.$type,
          properties: {
            assignment: {
              name: AssignmentExpr.assignment
            },
            expr: {
              name: AssignmentExpr.expr
            }
          },
          superTypes: [Expr.$type]
        },
        AsyncMessage: {
          name: AsyncMessage.$type,
          properties: {
            content: {
              name: AsyncMessage.content
            },
            from: {
              name: AsyncMessage.from
            },
            to: {
              name: AsyncMessage.to
            }
          },
          superTypes: [Stat.$type]
        },
        Atom: {
          name: Atom.$type,
          properties: {},
          superTypes: []
        },
        AtomExpr: {
          name: AtomExpr.$type,
          properties: {
            atom: {
              name: AtomExpr.atom
            }
          },
          superTypes: [Expr.$type]
        },
        Block: {
          name: Block.$type,
          properties: {
            stats: {
              name: Block.stats,
              defaultValue: []
            }
          },
          superTypes: []
        },
        BooleanAtom: {
          name: BooleanAtom.$type,
          properties: {
            value: {
              name: BooleanAtom.value
            }
          },
          superTypes: [Atom.$type]
        },
        BraceBlock: {
          name: BraceBlock.$type,
          properties: {
            block: {
              name: BraceBlock.block
            }
          },
          superTypes: []
        },
        CatchBlock: {
          name: CatchBlock.$type,
          properties: {
            braceBlock: {
              name: CatchBlock.braceBlock
            },
            invocation: {
              name: CatchBlock.invocation
            }
          },
          superTypes: []
        },
        Condition: {
          name: Condition.$type,
          properties: {},
          superTypes: []
        },
        Creation: {
          name: Creation.$type,
          properties: {
            body: {
              name: Creation.body
            },
            braceBlock: {
              name: Creation.braceBlock
            }
          },
          superTypes: [Stat.$type]
        },
        CreationBody: {
          name: CreationBody.$type,
          properties: {
            assignment: {
              name: CreationBody.assignment
            },
            construct: {
              name: CreationBody.construct
            },
            parameters: {
              name: CreationBody.parameters
            }
          },
          superTypes: []
        },
        CreationExpr: {
          name: CreationExpr.$type,
          properties: {
            creation: {
              name: CreationExpr.creation
            }
          },
          superTypes: [Expr.$type]
        },
        Critical: {
          name: Critical.$type,
          properties: {
            braceBlock: {
              name: Critical.braceBlock
            },
            parExpr: {
              name: Critical.parExpr
            }
          },
          superTypes: [Stat.$type]
        },
        Declaration: {
          name: Declaration.$type,
          properties: {
            name: {
              name: Declaration.name
            },
            type: {
              name: Declaration.type
            }
          },
          superTypes: [Parameter.$type]
        },
        DigitLeadingNameAtom: {
          name: DigitLeadingNameAtom.$type,
          properties: {
            value: {
              name: DigitLeadingNameAtom.value
            }
          },
          superTypes: [Atom.$type]
        },
        Divider: {
          name: Divider.$type,
          properties: {
            note: {
              name: Divider.note
            }
          },
          superTypes: [Stat.$type]
        },
        ElseBlock: {
          name: ElseBlock.$type,
          properties: {
            braceBlock: {
              name: ElseBlock.braceBlock
            }
          },
          superTypes: []
        },
        ElseIfBlock: {
          name: ElseIfBlock.$type,
          properties: {
            braceBlock: {
              name: ElseIfBlock.braceBlock
            },
            parExpr: {
              name: ElseIfBlock.parExpr
            }
          },
          superTypes: []
        },
        Emoji: {
          name: Emoji.$type,
          properties: {
            name: {
              name: Emoji.name
            }
          },
          superTypes: []
        },
        EqualityExpr: {
          name: EqualityExpr.$type,
          properties: {
            left: {
              name: EqualityExpr.left
            },
            op: {
              name: EqualityExpr.op
            },
            right: {
              name: EqualityExpr.right
            }
          },
          superTypes: [Expr.$type]
        },
        Expr: {
          name: Expr.$type,
          properties: {},
          superTypes: [Condition.$type, Parameter.$type]
        },
        FinallyBlock: {
          name: FinallyBlock.$type,
          properties: {
            braceBlock: {
              name: FinallyBlock.braceBlock
            }
          },
          superTypes: []
        },
        From: {
          name: From.$type,
          properties: {
            emoji: {
              name: From.emoji
            },
            name: {
              name: From.name
            }
          },
          superTypes: []
        },
        FromTo: {
          name: FromTo.$type,
          properties: {
            from: {
              name: FromTo.from
            },
            to: {
              name: FromTo.to
            }
          },
          superTypes: []
        },
        Func: {
          name: Func.$type,
          properties: {
            signatures: {
              name: Func.signatures,
              defaultValue: []
            }
          },
          superTypes: []
        },
        FuncExpr: {
          name: FuncExpr.$type,
          properties: {
            func: {
              name: FuncExpr.func
            },
            to: {
              name: FuncExpr.to
            }
          },
          superTypes: [Expr.$type]
        },
        Group: {
          name: Group.$type,
          properties: {
            name: {
              name: Group.name
            },
            participants: {
              name: Group.participants,
              defaultValue: []
            }
          },
          superTypes: []
        },
        IdAtom: {
          name: IdAtom.$type,
          properties: {
            value: {
              name: IdAtom.value
            }
          },
          superTypes: [Atom.$type]
        },
        IfBlock: {
          name: IfBlock.$type,
          properties: {
            braceBlock: {
              name: IfBlock.braceBlock
            },
            parExpr: {
              name: IfBlock.parExpr
            }
          },
          superTypes: []
        },
        InExpr: {
          name: InExpr.$type,
          properties: {
            left: {
              name: InExpr.left
            },
            right: {
              name: InExpr.right
            }
          },
          superTypes: [Condition.$type]
        },
        Invocation: {
          name: Invocation.$type,
          properties: {
            parameters: {
              name: Invocation.parameters
            }
          },
          superTypes: []
        },
        Label: {
          name: Label.$type,
          properties: {
            name: {
              name: Label.name
            }
          },
          superTypes: []
        },
        Loop: {
          name: Loop.$type,
          properties: {
            braceBlock: {
              name: Loop.braceBlock
            },
            parExpr: {
              name: Loop.parExpr
            }
          },
          superTypes: [Stat.$type]
        },
        Message: {
          name: Message.$type,
          properties: {
            body: {
              name: Message.body
            },
            braceBlock: {
              name: Message.braceBlock
            }
          },
          superTypes: [Stat.$type]
        },
        MessageBody: {
          name: MessageBody.$type,
          properties: {
            assignment: {
              name: MessageBody.assignment
            },
            fromTo: {
              name: MessageBody.fromTo
            },
            func: {
              name: MessageBody.func
            }
          },
          superTypes: []
        },
        MethodName: {
          name: MethodName.$type,
          properties: {
            emoji: {
              name: MethodName.emoji
            },
            name: {
              name: MethodName.name
            }
          },
          superTypes: []
        },
        MoneyAtom: {
          name: MoneyAtom.$type,
          properties: {
            value: {
              name: MoneyAtom.value
            }
          },
          superTypes: [Atom.$type]
        },
        MultiplicationExpr: {
          name: MultiplicationExpr.$type,
          properties: {
            left: {
              name: MultiplicationExpr.left
            },
            op: {
              name: MultiplicationExpr.op
            },
            right: {
              name: MultiplicationExpr.right
            }
          },
          superTypes: [Expr.$type]
        },
        NamedParameter: {
          name: NamedParameter.$type,
          properties: {
            name: {
              name: NamedParameter.name
            },
            value: {
              name: NamedParameter.value
            }
          },
          superTypes: [Parameter.$type]
        },
        NilAtom: {
          name: NilAtom.$type,
          properties: {
            value: {
              name: NilAtom.value
            }
          },
          superTypes: [Atom.$type]
        },
        NotExpr: {
          name: NotExpr.$type,
          properties: {
            expr: {
              name: NotExpr.expr
            }
          },
          superTypes: [Expr.$type]
        },
        NumberAtom: {
          name: NumberAtom.$type,
          properties: {
            value: {
              name: NumberAtom.value
            }
          },
          superTypes: [Atom.$type]
        },
        NumberUnitAtom: {
          name: NumberUnitAtom.$type,
          properties: {
            value: {
              name: NumberUnitAtom.value
            }
          },
          superTypes: [Atom.$type]
        },
        Opt: {
          name: Opt.$type,
          properties: {
            braceBlock: {
              name: Opt.braceBlock
            },
            parExpr: {
              name: Opt.parExpr
            }
          },
          superTypes: [Stat.$type]
        },
        OrExpr: {
          name: OrExpr.$type,
          properties: {
            left: {
              name: OrExpr.left
            },
            op: {
              name: OrExpr.op
            },
            right: {
              name: OrExpr.right
            }
          },
          superTypes: [Expr.$type]
        },
        Par: {
          name: Par.$type,
          properties: {
            braceBlock: {
              name: Par.braceBlock
            },
            parExpr: {
              name: Par.parExpr
            }
          },
          superTypes: [Stat.$type]
        },
        ParExpr: {
          name: ParExpr.$type,
          properties: {
            condition: {
              name: ParExpr.condition
            }
          },
          superTypes: []
        },
        Parameter: {
          name: Parameter.$type,
          properties: {},
          superTypes: []
        },
        Parameters: {
          name: Parameters.$type,
          properties: {
            parameters: {
              name: Parameters.parameters,
              defaultValue: []
            }
          },
          superTypes: []
        },
        ParenthesizedExpr: {
          name: ParenthesizedExpr.$type,
          properties: {
            expr: {
              name: ParenthesizedExpr.expr
            }
          },
          superTypes: [Expr.$type]
        },
        Participant: {
          name: Participant.$type,
          properties: {
            color: {
              name: Participant.color
            },
            emoji: {
              name: Participant.emoji
            },
            label: {
              name: Participant.label
            },
            name: {
              name: Participant.name
            },
            participantType: {
              name: Participant.participantType
            },
            stereotype: {
              name: Participant.stereotype
            },
            width: {
              name: Participant.width
            }
          },
          superTypes: []
        },
        Prog: {
          name: Prog.$type,
          properties: {
            block: {
              name: Prog.block
            },
            headElements: {
              name: Prog.headElements,
              defaultValue: []
            },
            starterExp: {
              name: Prog.starterExp
            },
            title: {
              name: Prog.title
            }
          },
          superTypes: []
        },
        Ref: {
          name: Ref.$type,
          properties: {
            names: {
              name: Ref.names,
              defaultValue: []
            }
          },
          superTypes: [Stat.$type]
        },
        RelationalExpr: {
          name: RelationalExpr.$type,
          properties: {
            left: {
              name: RelationalExpr.left
            },
            op: {
              name: RelationalExpr.op
            },
            right: {
              name: RelationalExpr.right
            }
          },
          superTypes: [Expr.$type]
        },
        Ret: {
          name: Ret.$type,
          properties: {
            asyncMessage: {
              name: Ret.asyncMessage
            },
            expr: {
              name: Ret.expr
            },
            returnAsyncMessage: {
              name: Ret.returnAsyncMessage
            }
          },
          superTypes: [Stat.$type]
        },
        ReturnAsyncMessage: {
          name: ReturnAsyncMessage.$type,
          properties: {
            content: {
              name: ReturnAsyncMessage.content
            },
            from: {
              name: ReturnAsyncMessage.from
            },
            to: {
              name: ReturnAsyncMessage.to
            }
          },
          superTypes: []
        },
        Section: {
          name: Section.$type,
          properties: {
            atom: {
              name: Section.atom
            },
            braceBlock: {
              name: Section.braceBlock
            }
          },
          superTypes: [Stat.$type]
        },
        Signature: {
          name: Signature.$type,
          properties: {
            invocation: {
              name: Signature.invocation
            },
            methodName: {
              name: Signature.methodName
            }
          },
          superTypes: []
        },
        StarterExp: {
          name: StarterExp.$type,
          properties: {
            annotation: {
              name: StarterExp.annotation
            },
            starter: {
              name: StarterExp.starter
            }
          },
          superTypes: []
        },
        Stat: {
          name: Stat.$type,
          properties: {},
          superTypes: []
        },
        Stereotype: {
          name: Stereotype.$type,
          properties: {
            name: {
              name: Stereotype.name
            }
          },
          superTypes: []
        },
        StringAtom: {
          name: StringAtom.$type,
          properties: {
            value: {
              name: StringAtom.value
            }
          },
          superTypes: [Atom.$type]
        },
        Tcf: {
          name: Tcf.$type,
          properties: {
            catchBlocks: {
              name: Tcf.catchBlocks,
              defaultValue: []
            },
            finallyBlock: {
              name: Tcf.finallyBlock
            },
            tryBlock: {
              name: Tcf.tryBlock
            }
          },
          superTypes: [Stat.$type]
        },
        TextExpr: {
          name: TextExpr.$type,
          properties: {
            words: {
              name: TextExpr.words,
              defaultValue: []
            }
          },
          superTypes: [Condition.$type]
        },
        Title: {
          name: Title.$type,
          properties: {
            content: {
              name: Title.content
            }
          },
          superTypes: []
        },
        To: {
          name: To.$type,
          properties: {
            emoji: {
              name: To.emoji
            },
            name: {
              name: To.name
            }
          },
          superTypes: []
        },
        TryBlock: {
          name: TryBlock.$type,
          properties: {
            braceBlock: {
              name: TryBlock.braceBlock
            }
          },
          superTypes: []
        },
        UnaryMinusExpr: {
          name: UnaryMinusExpr.$type,
          properties: {
            expr: {
              name: UnaryMinusExpr.expr
            }
          },
          superTypes: [Expr.$type]
        }
      };
    }
    const reflection = new ZenUmlAstReflection();
    let loadedZenUmlGrammar;
    const ZenUmlGrammar = () => loadedZenUmlGrammar ?? (loadedZenUmlGrammar = loadGrammarFromJson('{"$type":"Grammar","isDeclared":true,"name":"ZenUml","rules":[{"$type":"ParserRule","entry":true,"name":"Prog","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Prog"}},{"$type":"Assignment","feature":"title","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@1"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"headElements","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@2"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]}]},"cardinality":"*"},{"$type":"Assignment","feature":"starterExp","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@3"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"block","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]},"cardinality":"?"}]},"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Title","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Title"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@67"},"arguments":[]},{"$type":"Assignment","feature":"content","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@68"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Group","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Group"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@83"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},"cardinality":"?"},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@129"},"arguments":[]},{"$type":"Assignment","feature":"participants","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@4"},"arguments":[]},"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@130"},"arguments":[],"cardinality":"?"}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"StarterExp","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"StarterExp"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@71"},"arguments":[]},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@127"},"arguments":[]},{"$type":"Assignment","feature":"starter","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@128"},"arguments":[]}],"cardinality":"?"}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"StarterExp"}},{"$type":"Assignment","feature":"annotation","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@73"},"arguments":[]}}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Participant","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Participant"}},{"$type":"Assignment","feature":"participantType","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@73"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Assignment","feature":"stereotype","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"emoji","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Assignment","feature":"width","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@101"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"color","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@102"},"arguments":[]},"cardinality":"?"}],"cardinality":"?"}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Participant"}},{"$type":"Assignment","feature":"stereotype","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@5"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"Assignment","feature":"emoji","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Assignment","feature":"width","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@101"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"color","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@102"},"arguments":[]},"cardinality":"?"}],"cardinality":"?"}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Participant"}},{"$type":"Assignment","feature":"emoji","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Assignment","feature":"width","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@101"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"label","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@6"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"color","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@102"},"arguments":[]},"cardinality":"?"}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Stereotype","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Stereotype"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@108"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@109"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@116"},"arguments":[]}]}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Stereotype"}},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@117"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@108"},"arguments":[]}]},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@116"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@109"},"arguments":[]}],"cardinality":"?"}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Label","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Label"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@88"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Emoji","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Emoji"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@131"},"arguments":[]},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@132"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Name","dataType":"string","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@135"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@100"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@103"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@104"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Block","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Block"}},{"$type":"Assignment","feature":"stats","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@10"},"arguments":[]},"cardinality":"+"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Stat","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@21"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@11"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@12"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@13"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@14"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@15"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@16"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@31"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@43"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@26"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@28"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@17"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Par","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Par"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@82"},"arguments":[]},{"$type":"Assignment","feature":"parExpr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@63"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"braceBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Par"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@82"},"arguments":[]}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Opt","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Opt"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@84"},"arguments":[]},{"$type":"Assignment","feature":"parExpr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@63"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"braceBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Opt"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@84"},"arguments":[]}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Critical","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Critical"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@85"},"arguments":[]},{"$type":"Assignment","feature":"parExpr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@63"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"braceBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Critical"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@85"},"arguments":[]}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Section","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Section"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@86"},"arguments":[]},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@127"},"arguments":[]},{"$type":"Assignment","feature":"atom","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@62"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@128"},"arguments":[]}],"cardinality":"?"},{"$type":"Assignment","feature":"braceBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Section"}},{"$type":"Assignment","feature":"braceBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Section"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@86"},"arguments":[]}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Ref","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Ref"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@87"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@127"},"arguments":[]},{"$type":"Assignment","feature":"names","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@125"},"arguments":[]},{"$type":"Assignment","feature":"names","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},"cardinality":"*"}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@128"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@124"},"arguments":[],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Loop","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Loop"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@79"},"arguments":[]},{"$type":"Assignment","feature":"parExpr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@63"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"braceBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Tcf","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Tcf"}},{"$type":"Assignment","feature":"tryBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@18"},"arguments":[]}},{"$type":"Assignment","feature":"catchBlocks","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@19"},"arguments":[]},"cardinality":"*"},{"$type":"Assignment","feature":"finallyBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@20"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"TryBlock","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"TryBlock"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@89"},"arguments":[]},{"$type":"Assignment","feature":"braceBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"CatchBlock","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"CatchBlock"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@90"},"arguments":[]},{"$type":"Assignment","feature":"invocation","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@42"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"braceBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"FinallyBlock","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"FinallyBlock"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@91"},"arguments":[]},{"$type":"Assignment","feature":"braceBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Alt","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Alt"}},{"$type":"Assignment","feature":"ifBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@22"},"arguments":[]}},{"$type":"Assignment","feature":"elseIfBlocks","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@23"},"arguments":[]},"cardinality":"*"},{"$type":"Assignment","feature":"elseBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@24"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"IfBlock","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"IfBlock"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@77"},"arguments":[]},{"$type":"Assignment","feature":"parExpr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@63"},"arguments":[]}},{"$type":"Assignment","feature":"braceBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ElseIfBlock","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"ElseIfBlock"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@78"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@77"},"arguments":[]},{"$type":"Assignment","feature":"parExpr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@63"},"arguments":[]}},{"$type":"Assignment","feature":"braceBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ElseBlock","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"ElseBlock"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@78"},"arguments":[]},{"$type":"Assignment","feature":"braceBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"BraceBlock","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"BraceBlock"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@129"},"arguments":[]},{"$type":"Assignment","feature":"block","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@9"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@130"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Ret","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Ret"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@80"},"arguments":[]},{"$type":"Assignment","feature":"expr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@124"},"arguments":[],"cardinality":"?"}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Ret"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@72"},"arguments":[]},{"$type":"Assignment","feature":"asyncMessage","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@43"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Ret"}},{"$type":"Assignment","feature":"returnAsyncMessage","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@27"},"arguments":[]}}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ReturnAsyncMessage","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"ReturnAsyncMessage"}},{"$type":"Assignment","feature":"from","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@34"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@106"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"to","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@35"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@134"},"arguments":[]},{"$type":"Assignment","feature":"content","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@69"},"arguments":[]},"cardinality":"?"}],"cardinality":"?"}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Divider","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Divider"}},{"$type":"Assignment","feature":"note","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@70"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Creation","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Creation"}},{"$type":"Assignment","feature":"body","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@30"},"arguments":[]}},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@124"},"arguments":[]},{"$type":"Assignment","feature":"braceBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"CreationBody","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"CreationBody"}},{"$type":"Assignment","feature":"assignment","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@44"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@81"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Assignment","feature":"construct","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@127"},"arguments":[]},{"$type":"Assignment","feature":"parameters","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@46"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@128"},"arguments":[]}],"cardinality":"?"}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Message","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Message"}},{"$type":"Assignment","feature":"body","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@32"},"arguments":[]}},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@124"},"arguments":[]},{"$type":"Assignment","feature":"braceBlock","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@25"},"arguments":[]}}],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"MessageBody","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"MessageBody"}},{"$type":"Assignment","feature":"assignment","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@44"},"arguments":[]}},{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Assignment","feature":"fromTo","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@33"},"arguments":[]}},{"$type":"Assignment","feature":"func","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@36"},"arguments":[]},"cardinality":"?"}]},{"$type":"Assignment","feature":"func","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@37"},"arguments":[]}}],"cardinality":"?"}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"MessageBody"}},{"$type":"Assignment","feature":"fromTo","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@33"},"arguments":[]}},{"$type":"Assignment","feature":"func","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@36"},"arguments":[]},"cardinality":"?"}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"MessageBody"}},{"$type":"Assignment","feature":"func","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@37"},"arguments":[]}}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"FromTo","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"FromTo"}},{"$type":"Group","elements":[{"$type":"Assignment","feature":"from","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@34"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@107"},"arguments":[]}],"cardinality":"?"},{"$type":"Assignment","feature":"to","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@35"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@133"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"From","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"From"}},{"$type":"Assignment","feature":"emoji","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"To","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"To"}},{"$type":"Assignment","feature":"emoji","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Func","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Func"}},{"$type":"Assignment","feature":"signatures","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@38"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@133"},"arguments":[]},{"$type":"Assignment","feature":"signatures","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@38"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"BareFunc","inferredType":{"$type":"InferredType","name":"Func"},"definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Func"}},{"$type":"Assignment","feature":"signatures","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@133"},"arguments":[]},{"$type":"Assignment","feature":"signatures","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@38"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Func"}},{"$type":"Assignment","feature":"signatures","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@40"},"arguments":[]}}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Signature","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Signature"}},{"$type":"Assignment","feature":"methodName","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}},{"$type":"Assignment","feature":"invocation","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@42"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"InvokedSignature","inferredType":{"$type":"InferredType","name":"Signature"},"definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Signature"}},{"$type":"Assignment","feature":"methodName","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}},{"$type":"Assignment","feature":"invocation","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@42"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"PlainSignature","inferredType":{"$type":"InferredType","name":"Signature"},"definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Signature"}},{"$type":"Assignment","feature":"methodName","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@41"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"MethodName","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"MethodName"}},{"$type":"Assignment","feature":"emoji","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Invocation","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Invocation"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@127"},"arguments":[]},{"$type":"Assignment","feature":"parameters","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@46"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@128"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"AsyncMessage","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"AsyncMessage"}},{"$type":"Group","elements":[{"$type":"Assignment","feature":"from","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@34"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@107"},"arguments":[]}],"cardinality":"?"},{"$type":"Assignment","feature":"to","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@35"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@134"},"arguments":[]},{"$type":"Assignment","feature":"content","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@69"},"arguments":[]},"cardinality":"?"}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"AsyncMessage"}},{"$type":"Assignment","feature":"from","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@34"},"arguments":[]}},{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@119"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@107"},"arguments":[]}]},{"$type":"Assignment","feature":"to","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@35"},"arguments":[]},"cardinality":"?"}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Assignment","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Assignment"}},{"$type":"Assignment","feature":"type","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]},"cardinality":"?"},{"$type":"Assignment","feature":"assignee","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@45"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@126"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Assignee","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Assignee"}},{"$type":"Assignment","feature":"atom","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@62"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Assignee"}},{"$type":"Assignment","feature":"ids","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@135"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@100"},"arguments":[]}]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@125"},"arguments":[]},{"$type":"Assignment","feature":"ids","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@135"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@100"},"arguments":[]}]}}],"cardinality":"+"}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Assignee"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@81"},"arguments":[]}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Parameters","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Parameters"}},{"$type":"Assignment","feature":"parameters","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@47"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@125"},"arguments":[]},{"$type":"Assignment","feature":"parameters","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@47"},"arguments":[]}}],"cardinality":"*"},{"$type":"RuleCall","rule":{"$ref":"#/rules@125"},"arguments":[],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Parameter","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@48"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@49"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"NamedParameter","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"NamedParameter"}},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@135"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@100"},"arguments":[]}]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@126"},"arguments":[]},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Declaration","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Declaration"}},{"$type":"Assignment","feature":"type","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@135"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@100"},"arguments":[]}]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Expr","definition":{"$type":"RuleCall","rule":{"$ref":"#/rules@51"},"arguments":[]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExprOr","inferredType":{"$type":"InferredType","name":"Expr"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"OrExpr"},"feature":"left","operator":"="},{"$type":"Assignment","feature":"op","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@114"},"arguments":[]}},{"$type":"Assignment","feature":"right","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@52"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExprAnd","inferredType":{"$type":"InferredType","name":"Expr"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@53"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"AndExpr"},"feature":"left","operator":"="},{"$type":"Assignment","feature":"op","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@115"},"arguments":[]}},{"$type":"Assignment","feature":"right","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@53"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExprEquality","inferredType":{"$type":"InferredType","name":"Expr"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@54"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"EqualityExpr"},"feature":"left","operator":"="},{"$type":"Assignment","feature":"op","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@112"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@113"},"arguments":[]}]}},{"$type":"Assignment","feature":"right","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@54"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExprRelational","inferredType":{"$type":"InferredType","name":"Expr"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@55"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"RelationalExpr"},"feature":"left","operator":"="},{"$type":"Assignment","feature":"op","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@111"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@110"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@117"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@116"},"arguments":[]}]}},{"$type":"Assignment","feature":"right","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@55"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExprAdditive","inferredType":{"$type":"InferredType","name":"Expr"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@56"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"AdditiveExpr"},"feature":"left","operator":"="},{"$type":"Assignment","feature":"op","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@118"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@119"},"arguments":[]}]}},{"$type":"Assignment","feature":"right","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@56"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExprMultiplication","inferredType":{"$type":"InferredType","name":"Expr"},"definition":{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@57"},"arguments":[]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"MultiplicationExpr"},"feature":"left","operator":"="},{"$type":"Assignment","feature":"op","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@120"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@121"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@122"},"arguments":[]}]}},{"$type":"Assignment","feature":"right","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@57"},"arguments":[]}}],"cardinality":"*"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExprUnary","inferredType":{"$type":"InferredType","name":"Expr"},"definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"UnaryMinusExpr"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@119"},"arguments":[]},{"$type":"Assignment","feature":"expr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@57"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"NotExpr"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@123"},"arguments":[]},{"$type":"Assignment","feature":"expr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@57"},"arguments":[]}}]},{"$type":"RuleCall","rule":{"$ref":"#/rules@58"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExprPrimary","inferredType":{"$type":"InferredType","name":"Expr"},"definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"AtomExpr"}},{"$type":"Assignment","feature":"atom","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@62"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"FuncExpr"}},{"$type":"Assignment","feature":"to","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@35"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@133"},"arguments":[]},{"$type":"Assignment","feature":"func","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@36"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"FuncExpr"}},{"$type":"Assignment","feature":"func","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@59"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"CreationExpr"}},{"$type":"Assignment","feature":"creation","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@29"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"ParenthesizedExpr"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@127"},"arguments":[]},{"$type":"Assignment","feature":"expr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@128"},"arguments":[]}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"AssignmentExpr"}},{"$type":"Assignment","feature":"assignment","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@44"},"arguments":[]}},{"$type":"Assignment","feature":"expr","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]}}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ExprFunc","inferredType":{"$type":"InferredType","name":"Func"},"definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Func"}},{"$type":"Assignment","feature":"signatures","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@39"},"arguments":[]}},{"$type":"Group","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@133"},"arguments":[]},{"$type":"Assignment","feature":"signatures","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@38"},"arguments":[]}}],"cardinality":"*"}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Func"}},{"$type":"Assignment","feature":"signatures","operator":"+=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@60"},"arguments":[]}}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmojiSignature","inferredType":{"$type":"InferredType","name":"Signature"},"definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"Signature"}},{"$type":"Assignment","feature":"methodName","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@61"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"EmojiMethodName","inferredType":{"$type":"InferredType","name":"MethodName"},"definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"MethodName"}},{"$type":"Assignment","feature":"emoji","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@7"},"arguments":[]}},{"$type":"Assignment","feature":"name","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@8"},"arguments":[]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Atom","definition":{"$type":"Alternatives","elements":[{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"NumberAtom"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@101"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@98"},"arguments":[]}]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"NumberUnitAtom"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@97"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"MoneyAtom"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@99"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"BooleanAtom"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@74"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@75"},"arguments":[]}]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"IdAtom"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@135"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"DigitLeadingNameAtom"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@100"},"arguments":[]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"StringAtom"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@103"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@104"},"arguments":[]}]}}]},{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"NilAtom"}},{"$type":"Assignment","feature":"value","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@76"},"arguments":[]}}]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"ParExpr","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"ParExpr"}},{"$type":"RuleCall","rule":{"$ref":"#/rules@127"},"arguments":[]},{"$type":"Assignment","feature":"condition","operator":"=","terminal":{"$type":"RuleCall","rule":{"$ref":"#/rules@64"},"arguments":[]},"cardinality":"?"},{"$type":"RuleCall","rule":{"$ref":"#/rules@128"},"arguments":[],"cardinality":"?"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"Condition","definition":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@50"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@65"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@66"},"arguments":[]}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"InExpr","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"InExpr"}},{"$type":"Assignment","feature":"left","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@135"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@100"},"arguments":[]}]}},{"$type":"RuleCall","rule":{"$ref":"#/rules@92"},"arguments":[]},{"$type":"Assignment","feature":"right","operator":"=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@135"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@100"},"arguments":[]}]}}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"ParserRule","name":"TextExpr","definition":{"$type":"Group","elements":[{"$type":"Action","inferredType":{"$type":"InferredType","name":"TextExpr"}},{"$type":"Assignment","feature":"words","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@135"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@100"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@97"},"arguments":[]}]}},{"$type":"Assignment","feature":"words","operator":"+=","terminal":{"$type":"Alternatives","elements":[{"$type":"RuleCall","rule":{"$ref":"#/rules@135"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@100"},"arguments":[]},{"$type":"RuleCall","rule":{"$ref":"#/rules@97"},"arguments":[]}]},"cardinality":"+"}]},"entry":false,"fragment":false,"parameters":[]},{"$type":"TerminalRule","name":"TITLE","definition":{"$type":"RegexToken","regex":"/title(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TITLE_CONTENT","definition":{"$type":"RegexToken","regex":"/\\\\x01[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EVENT_PAYLOAD_LXR","definition":{"$type":"RegexToken","regex":"/\\\\x02[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"DIVIDER","definition":{"$type":"RegexToken","regex":"/\\\\x03==[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"STARTER_LXR","definition":{"$type":"RegexToken","regex":"/@[Ss]tarter(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ANNOTATION_RET","definition":{"$type":"RegexToken","regex":"/@(?:[Rr]eturn|[Rr]eply)(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ANNOTATION","definition":{"$type":"RegexToken","regex":"/@[a-zA-Z0-9_]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TRUE","definition":{"$type":"RegexToken","regex":"/true(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FALSE","definition":{"$type":"RegexToken","regex":"/false(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NIL","definition":{"$type":"RegexToken","regex":"/(?:nil|null)(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"IF","definition":{"$type":"RegexToken","regex":"/if(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ELSE","definition":{"$type":"RegexToken","regex":"/else(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"WHILE","definition":{"$type":"RegexToken","regex":"/(?:while|forEach|foreach|for|loop)(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"RETURN","definition":{"$type":"RegexToken","regex":"/return(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEW","definition":{"$type":"RegexToken","regex":"/new(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"PAR","definition":{"$type":"RegexToken","regex":"/par(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"GROUP","definition":{"$type":"RegexToken","regex":"/group(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"OPT","definition":{"$type":"RegexToken","regex":"/opt(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"CRITICAL","definition":{"$type":"RegexToken","regex":"/critical(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"SECTION","definition":{"$type":"RegexToken","regex":"/(?:section|frame)(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"REF","definition":{"$type":"RegexToken","regex":"/ref(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"AS","definition":{"$type":"RegexToken","regex":"/as(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"TRY","definition":{"$type":"RegexToken","regex":"/try(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"CATCH","definition":{"$type":"RegexToken","regex":"/catch(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FINALLY","definition":{"$type":"RegexToken","regex":"/finally(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"IN","definition":{"$type":"RegexToken","regex":"/in(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"CONSTANT","definition":{"$type":"RegexToken","regex":"/const(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"READONLY","definition":{"$type":"RegexToken","regex":"/readonly(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"STATIC","definition":{"$type":"RegexToken","regex":"/static(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"AWAIT","definition":{"$type":"RegexToken","regex":"/await(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","name":"NUMBER_UNIT","definition":{"$type":"RegexToken","regex":"/[0-9]+(?:ms|s|h|d|w|kg|g|px)(?![a-zA-Z0-9_])/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"FLOAT","definition":{"$type":"RegexToken","regex":"/[0-9]+\\\\.[0-9]*|\\\\.[0-9]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"MONEY","definition":{"$type":"RegexToken","regex":"/\\\\$[0-9.]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"DIGIT_LEADING_NAME","definition":{"$type":"RegexToken","regex":"/[0-9]+[a-zA-Z][a-zA-Z0-9_]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"INT","definition":{"$type":"RegexToken","regex":"/[0-9]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"COLOR","definition":{"$type":"RegexToken","regex":"/#[0-9a-fA-F]+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"CSTRING","definition":{"$type":"RegexToken","regex":"/\\"(?:[^\\"\\\\n\\\\r]|\\"\\")*\\"/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"USTRING","definition":{"$type":"RegexToken","regex":"/\\"[^\\"\\\\n\\\\r]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"COMMENT","definition":{"$type":"RegexToken","regex":"/\\\\/\\\\/[^\\\\n\\\\r]*/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","name":"RETURN_ARROW","definition":{"$type":"RegexToken","regex":"/-->/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ARROW","definition":{"$type":"RegexToken","regex":"/->/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"SOPEN","definition":{"$type":"RegexToken","regex":"/<</","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"SCLOSE","definition":{"$type":"RegexToken","regex":"/>>/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"GTEQ","definition":{"$type":"RegexToken","regex":"/>=/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"LTEQ","definition":{"$type":"RegexToken","regex":"/<=/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"EQ","definition":{"$type":"RegexToken","regex":"/==/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NEQ","definition":{"$type":"RegexToken","regex":"/!=/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"OR","definition":{"$type":"RegexToken","regex":"/\\\\|\\\\|/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"AND","definition":{"$type":"RegexToken","regex":"/&&/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"GT","definition":{"$type":"RegexToken","regex":"/>/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"LT","definition":{"$type":"RegexToken","regex":"/</","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"PLUS","definition":{"$type":"RegexToken","regex":"/\\\\+/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"MINUS","definition":{"$type":"RegexToken","regex":"/-/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"MULT","definition":{"$type":"RegexToken","regex":"/\\\\*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"DIV","definition":{"$type":"RegexToken","regex":"/\\\\//","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"MOD","definition":{"$type":"RegexToken","regex":"/%/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"NOT","definition":{"$type":"RegexToken","regex":"/!/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"SCOL","definition":{"$type":"RegexToken","regex":"/;/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"COMMA","definition":{"$type":"RegexToken","regex":"/,/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ASSIGN","definition":{"$type":"RegexToken","regex":"/=/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"OPAR","definition":{"$type":"RegexToken","regex":"/\\\\(/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"CPAR","definition":{"$type":"RegexToken","regex":"/\\\\)/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"OBRACE","definition":{"$type":"RegexToken","regex":"/\\\\{/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"CBRACE","definition":{"$type":"RegexToken","regex":"/\\\\}/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"LBRACKET","definition":{"$type":"RegexToken","regex":"/\\\\[/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"RBRACKET","definition":{"$type":"RegexToken","regex":"/\\\\]/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"DOT","definition":{"$type":"RegexToken","regex":"/\\\\./","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"COL","definition":{"$type":"RegexToken","regex":"/:/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","name":"ID","definition":{"$type":"RegexToken","regex":"/[_a-zA-Z][a-zA-Z0-9_]*/","parenthesized":false},"fragment":false,"hidden":false},{"$type":"TerminalRule","hidden":true,"name":"WS","definition":{"$type":"RegexToken","regex":"/[ \\\\t]+/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"CR","definition":{"$type":"RegexToken","regex":"/\\\\r|\\\\n/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"EVENT_END","definition":{"$type":"RegexToken","regex":"/\\\\x04/","parenthesized":false},"fragment":false},{"$type":"TerminalRule","hidden":true,"name":"TITLE_END","definition":{"$type":"RegexToken","regex":"/\\\\x05/","parenthesized":false},"fragment":false}],"imports":[],"interfaces":[],"types":[],"$comment":"/**\\n * ZenUML sequence-diagram grammar — Stage 2 of the ANTLR4 → Langium migration.\\n *\\n * Mirrors src/g4/sequenceParser.g4 rule-for-rule per\\n * docs/langium-migration/02-parser-rules.md §3, including ALL 25 grammar-encoded\\n * error-tolerance points (§8) and the deliberate NON-tolerances (§8 end).\\n *\\n * IMPORTANT — terminals here are PLACEHOLDERS. The authoritative token list\\n * (patterns, order, channels, mode emulation, predicates) is\\n * src/parser-langium/lexer/tokens.ts, injected via the TokenBuilder override in\\n * src/parser-langium/token-builder.ts. The parser resolves terminals BY NAME,\\n * so the names below must match that list exactly. No string keywords are used\\n * anywhere in parser rules (keywords would mint token types that do not exist\\n * in the Stage-1 list).\\n *\\n * Deliberate differences from the ANTLR parser grammar (each documented in\\n * docs/langium-migration/10-ast-mapping.md):\\n *  - EVENT_END?/TITLE_END? are dropped: those newline tokens are hidden in the\\n *    parser token vocabulary (payload terminals already exclude \\\\r\\\\n).\\n *  - expr alt #plusExpr is dropped (dead, shadowed by #additiveExpr — 07 §2).\\n *  - assignee alts CSTRING/USTRING are dropped (unreachable: atom\'s stringAtom\\n *    alternative always wins by ANTLR alternative order).\\n *  - assignee\'s comma-list alternative requires >=1 COMMA (a single ID is\\n *    always atom in ANTLR — removes a guaranteed ambiguity, same language).\\n *  - condition\'s redundant leading `atom` alternative is dropped: a lone atom\\n *    parses as Expr→AtomExpr(atom). ANTLR used the direct alt purely for the\\n *    `.atom()` accessor; the Stage-3 facade unwraps AtomExpr instead.\\n *  - textExpr requires >=2 words (a single word is always atom/Expr in ANTLR).\\n *  - messageBody/funcExpr are left-factored so that a leading `name DOT` is\\n *    ALWAYS fromTo / `to DOT` (ANTLR resolves the same way by alternative\\n *    order): the bare-func alternatives (BareFunc/ExprFunc) cannot start with\\n *    `methodName DOT`.\\n *  - emoji\'s EMOJI_SHORTCODE alternative is dropped: the ANTLR LEXER never\\n *    defines that token (parser-only reference; it can never match).\\n */"}'));
    const ZenUmlLanguageMetaData = {
      languageId: "zenuml",
      fileExtensions: [".zenuml"],
      caseInsensitive: false,
      mode: "production"
    };
    const ZenUmlGeneratedSharedModule = {
      AstReflection: () => new ZenUmlAstReflection()
    };
    const ZenUmlGeneratedModule = {
      Grammar: () => ZenUmlGrammar(),
      LanguageMetaData: () => ZenUmlLanguageMetaData,
      parser: {}
    };
    const HIDDEN_GROUP = "HIDDEN";
    const COMMENT_GROUP = "COMMENT_CHANNEL";
    const MODIFIER_GROUP = "MODIFIER_CHANNEL";
    function asMatch(image) {
      return [image];
    }
    function uniPattern(re) {
      const sticky = new RegExp(re.source, re.flags.replace("y", "") + "y");
      return (text, offset) => {
        sticky.lastIndex = offset;
        return sticky.exec(text);
      };
    }
    function lastMainTokenName(tokens2) {
      if (!tokens2 || tokens2.length === 0) return void 0;
      return tokens2[tokens2.length - 1].tokenType.name;
    }
    function restOfLine(text, offset) {
      let i = offset;
      while (i < text.length) {
        const c = text.charCodeAt(i);
        if (c === 10 || c === 13) break;
        i++;
      }
      if (i === offset) return null;
      return asMatch(text.slice(offset, i));
    }
    function singleNewline(text, offset) {
      const ch = text[offset];
      if (ch === "\n" || ch === "\r") return asMatch(ch);
      return null;
    }
    const eventPayloadExec = (text, offset, tokens2) => {
      if (lastMainTokenName(tokens2) !== "COL") return null;
      return restOfLine(text, offset);
    };
    const titleContentExec = (text, offset, tokens2) => {
      if (lastMainTokenName(tokens2) !== "TITLE") return null;
      return restOfLine(text, offset);
    };
    const eventEndExec = (text, offset, tokens2) => {
      const last = lastMainTokenName(tokens2);
      if (last !== "COL" && last !== "EVENT_PAYLOAD_LXR") return null;
      return singleNewline(text, offset);
    };
    const titleEndExec = (text, offset, tokens2) => {
      const last = lastMainTokenName(tokens2);
      if (last !== "TITLE" && last !== "TITLE_CONTENT") return null;
      return singleNewline(text, offset);
    };
    const EVENT_PAYLOAD_LXR = createToken({
      name: "EVENT_PAYLOAD_LXR",
      pattern: eventPayloadExec,
      line_breaks: false
    });
    const TITLE_CONTENT = createToken({
      name: "TITLE_CONTENT",
      pattern: titleContentExec,
      line_breaks: false
    });
    const EVENT_END = createToken({
      name: "EVENT_END",
      pattern: eventEndExec,
      line_breaks: true
    });
    const TITLE_END = createToken({
      name: "TITLE_END",
      pattern: titleEndExec,
      line_breaks: true
    });
    const DIVIDER_RE = /[ \t]*==[^\r\n]*/y;
    const dividerExec = (text, offset) => {
      if (offset !== 0) {
        const prev = text.charCodeAt(offset - 1);
        if (prev !== 10 && prev !== 13) return null;
      }
      DIVIDER_RE.lastIndex = offset;
      const m = DIVIDER_RE.exec(text);
      if (m === null) return null;
      if (m[0] === "==") return null;
      return m;
    };
    const DIVIDER = createToken({
      name: "DIVIDER",
      pattern: dividerExec,
      line_breaks: false
    });
    const WS = createToken({
      name: "WS",
      pattern: /[ \t]+/,
      group: HIDDEN_GROUP
    });
    const CR = createToken({
      name: "CR",
      pattern: /\r|\n/,
      group: HIDDEN_GROUP,
      line_breaks: true
    });
    const COMMENT = createToken({
      name: "COMMENT",
      pattern: /\/\/[^\r\n]*/,
      group: COMMENT_GROUP
    });
    const CONSTANT = createToken({
      name: "CONSTANT",
      pattern: uniPattern(/const(?![\p{L}\p{Nd}_])/u),
      group: MODIFIER_GROUP,
      line_breaks: false
    });
    const READONLY = createToken({
      name: "READONLY",
      pattern: uniPattern(/readonly(?![\p{L}\p{Nd}_])/u),
      group: MODIFIER_GROUP,
      line_breaks: false
    });
    const STATIC = createToken({
      name: "STATIC",
      pattern: uniPattern(/static(?![\p{L}\p{Nd}_])/u),
      group: MODIFIER_GROUP,
      line_breaks: false
    });
    const AWAIT = createToken({
      name: "AWAIT",
      pattern: uniPattern(/await(?![\p{L}\p{Nd}_])/u),
      group: MODIFIER_GROUP,
      line_breaks: false
    });
    const IDENT_CHAR_RE = /[\p{L}\p{Nd}_]/u;
    const titleExec = (text, offset) => {
      if (!text.startsWith("title", offset)) return null;
      const after = offset + 5;
      if (after < text.length && IDENT_CHAR_RE.test(text[after])) return null;
      const preceding = text.slice(0, offset).replace(/\/\/[^\n]*(?:\n|$)/g, "").trim();
      if (preceding.length) return null;
      let i = after;
      while (text[i] === " " || text[i] === "	") i++;
      const next = text[i];
      if (next === "." || next === "=" || next === "(") return null;
      return asMatch("title");
    };
    const TITLE = createToken({
      name: "TITLE",
      pattern: titleExec,
      line_breaks: false
    });
    const STARTER_LXR = createToken({
      name: "STARTER_LXR",
      pattern: /@[Ss]tarter(?![a-zA-Z0-9_])/
    });
    const ANNOTATION_RET = createToken({
      name: "ANNOTATION_RET",
      pattern: /@(?:[Rr]eturn|[Rr]eply)(?![a-zA-Z0-9_])/
    });
    const ANNOTATION = createToken({
      name: "ANNOTATION",
      pattern: /@[a-zA-Z0-9_]*/
    });
    const kw = (name, pattern) => createToken({ name, pattern });
    const ukw = (name, pattern) => createToken({ name, pattern: uniPattern(pattern), line_breaks: false });
    const TRUE = ukw("TRUE", /true(?![\p{L}\p{Nd}_])/u);
    const FALSE = ukw("FALSE", /false(?![\p{L}\p{Nd}_])/u);
    const NIL = ukw("NIL", /(?:nil|null)(?![\p{L}\p{Nd}_])/u);
    const IF = ukw("IF", /if(?![\p{L}\p{Nd}_])/u);
    const ELSE = ukw("ELSE", /else(?![\p{L}\p{Nd}_])/u);
    const WHILE = ukw(
      "WHILE",
      /(?:while|forEach|foreach|for|loop)(?![\p{L}\p{Nd}_])/u
    );
    const RETURN = ukw("RETURN", /return(?![\p{L}\p{Nd}_])/u);
    const NEW = ukw("NEW", /new(?![\p{L}\p{Nd}_])/u);
    const PAR = ukw("PAR", /par(?![\p{L}\p{Nd}_])/u);
    const GROUP = ukw("GROUP", /group(?![\p{L}\p{Nd}_])/u);
    const OPT = ukw("OPT", /opt(?![\p{L}\p{Nd}_])/u);
    const CRITICAL = ukw("CRITICAL", /critical(?![\p{L}\p{Nd}_])/u);
    const SECTION = ukw("SECTION", /(?:section|frame)(?![\p{L}\p{Nd}_])/u);
    const REF = ukw("REF", /ref(?![\p{L}\p{Nd}_])/u);
    const AS = ukw("AS", /as(?![\p{L}\p{Nd}_])/u);
    const TRY = ukw("TRY", /try(?![\p{L}\p{Nd}_])/u);
    const CATCH = ukw("CATCH", /catch(?![\p{L}\p{Nd}_])/u);
    const FINALLY = ukw("FINALLY", /finally(?![\p{L}\p{Nd}_])/u);
    const IN = ukw("IN", /in(?![\p{L}\p{Nd}_])/u);
    const NUMBER_UNIT = createToken({
      name: "NUMBER_UNIT",
      pattern: uniPattern(
        /(?:\d+\.\d*|\.\d+|\d+)(?:milliseconds|millisecond|ms|seconds|second|secs|sec|s|minutes|minute|mins|min|hours|hour|hrs|hr|h|days|day|d|weeks|week|w|KiB|MiB|GiB|TiB|KB|MB|GB|TB|kb|mb|gb|tb|B|rem|em|px|mm|cm|km|m|mg|kg|g)(?![\p{L}\p{Nd}_])/u
      ),
      line_breaks: false
    });
    const FLOAT = createToken({
      name: "FLOAT",
      pattern: uniPattern(/\d+\.\d*|\.\d+(?![\p{L}_])/u),
      line_breaks: false
    });
    const MONEY = createToken({
      name: "MONEY",
      pattern: uniPattern(/\$(?:\d+\.\d*|\.\d+(?![\p{L}_])|\d+)/u),
      line_breaks: false
    });
    const DIGIT_LEADING_NAME = createToken({
      name: "DIGIT_LEADING_NAME",
      pattern: uniPattern(new RegExp("[0-9]+\\p{L}[\\p{L}\\p{Nd}_]*", "u")),
      line_breaks: false
    });
    const INT = createToken({ name: "INT", pattern: /[0-9]+/ });
    const COLOR = createToken({ name: "COLOR", pattern: /#[0-9a-fA-F]+/ });
    function scanString(text, offset) {
      if (text.charCodeAt(offset) !== 34) return null;
      let i = offset + 1;
      let cstringEnd = -1;
      for (; ; ) {
        if (i >= text.length) break;
        const c = text.charCodeAt(i);
        if (c === 10 || c === 13) break;
        if (c === 34) {
          cstringEnd = i + 1;
          if (text.charCodeAt(i + 1) === 34) {
            i += 2;
          } else {
            break;
          }
        } else {
          i++;
        }
      }
      return { cstringEnd, ustringEnd: i };
    }
    const cstringExec = (text, offset) => {
      const scan = scanString(text, offset);
      if (scan === null || scan.cstringEnd < 0) return null;
      if (scan.cstringEnd < scan.ustringEnd) return null;
      return asMatch(text.slice(offset, scan.cstringEnd));
    };
    const ustringExec = (text, offset) => {
      const scan = scanString(text, offset);
      if (scan === null) return null;
      return asMatch(text.slice(offset, scan.ustringEnd));
    };
    const CSTRING = createToken({
      name: "CSTRING",
      pattern: cstringExec,
      line_breaks: false
    });
    const USTRING = createToken({
      name: "USTRING",
      pattern: ustringExec,
      line_breaks: false
    });
    const RETURN_ARROW = kw("RETURN_ARROW", /-->/);
    const ARROW = kw("ARROW", /->/);
    const SOPEN = kw("SOPEN", /<</);
    const SCLOSE = kw("SCLOSE", />>/);
    const GTEQ = kw("GTEQ", />=/);
    const LTEQ = kw("LTEQ", /<=/);
    const EQ = kw("EQ", /==/);
    const NEQ = kw("NEQ", /!=/);
    const OR = kw("OR", /\|\|/);
    const AND = kw("AND", /&&/);
    const GT = kw("GT", />/);
    const LT = kw("LT", /</);
    const PLUS = kw("PLUS", /\+/);
    const MINUS = kw("MINUS", /-/);
    const MULT = kw("MULT", /\*/);
    const DIV = kw("DIV", /\//);
    const MOD = kw("MOD", /%/);
    const POW = kw("POW", /\^/);
    const NOT = kw("NOT", /!/);
    const SCOL = kw("SCOL", /;/);
    const COMMA = kw("COMMA", /,/);
    const ASSIGN = kw("ASSIGN", /=/);
    const OPAR = kw("OPAR", /\(/);
    const CPAR = kw("CPAR", /\)/);
    const OBRACE = kw("OBRACE", /\{/);
    const CBRACE = kw("CBRACE", /\}/);
    const LBRACKET = kw("LBRACKET", /\[/);
    const RBRACKET = kw("RBRACKET", /\]/);
    const DOT = kw("DOT", /\./);
    const COL = kw("COL", /:/);
    const ID = createToken({
      name: "ID",
      pattern: uniPattern(/[\p{L}_][\p{L}\p{Nd}_]*/u),
      line_breaks: false
    });
    const OTHER = createToken({
      name: "OTHER",
      pattern: /[\s\S]/,
      line_breaks: true
    });
    const tokens = [
      // Mode-emulation tokens fire only right after COL/TITLE/payloads — they must
      // outcompete every default-mode token (payload includes spaces, `//`, etc.).
      EVENT_PAYLOAD_LXR,
      TITLE_CONTENT,
      EVENT_END,
      TITLE_END,
      // DIVIDER before WS so leading [ \t]* stays inside the DIVIDER image.
      DIVIDER,
      WS,
      CR,
      // COMMENT before DIV.
      COMMENT,
      // Modifier channel.
      CONSTANT,
      READONLY,
      STATIC,
      AWAIT,
      // Predicated soft keyword.
      TITLE,
      // Annotations: fixed forms before the generic one.
      STARTER_LXR,
      ANNOTATION_RET,
      ANNOTATION,
      // Keywords (boundary-lookahead guarded), before ID.
      TRUE,
      FALSE,
      NIL,
      IF,
      ELSE,
      WHILE,
      RETURN,
      NEW,
      PAR,
      GROUP,
      OPT,
      CRITICAL,
      SECTION,
      REF,
      AS,
      TRY,
      CATCH,
      FINALLY,
      IN,
      // Numbers: NUMBER_UNIT > FLOAT > MONEY > DIGIT_LEADING_NAME > INT.
      NUMBER_UNIT,
      FLOAT,
      MONEY,
      DIGIT_LEADING_NAME,
      INT,
      COLOR,
      // Strings: CSTRING wins ties; USTRING right after.
      CSTRING,
      USTRING,
      // Multi-char operators before their prefixes.
      RETURN_ARROW,
      ARROW,
      SOPEN,
      SCLOSE,
      GTEQ,
      LTEQ,
      EQ,
      NEQ,
      OR,
      AND,
      // Single-char operators / punctuation (FLOAT above already beat DOT).
      GT,
      LT,
      PLUS,
      MINUS,
      MULT,
      DIV,
      MOD,
      POW,
      NOT,
      SCOL,
      COMMA,
      ASSIGN,
      OPAR,
      CPAR,
      OBRACE,
      CBRACE,
      LBRACKET,
      RBRACKET,
      DOT,
      COL,
      // Identifiers.
      ID,
      // Never-fail catch-all — must stay last.
      OTHER
    ];
    const LANGIUM_HIDDEN_GROUP = "hidden";
    const HIDDEN_FOR_PARSER = /* @__PURE__ */ new Set([
      "WS",
      "CR",
      "COMMENT",
      "CONSTANT",
      "READONLY",
      "STATIC",
      "AWAIT",
      "EVENT_END",
      "TITLE_END"
    ]);
    function cloneForParser(token) {
      const config = {
        name: token.name,
        pattern: token.PATTERN
      };
      if (token.LINE_BREAKS !== void 0) {
        config.line_breaks = token.LINE_BREAKS;
      }
      if (HIDDEN_FOR_PARSER.has(token.name)) {
        config.group = LANGIUM_HIDDEN_GROUP;
      }
      return createToken(config);
    }
    const parserTokens = tokens.map(cloneForParser);
    class ZenTokenBuilder {
      buildTokens(_grammar, _options) {
        return parserTokens;
      }
    }
    class ZenLexer extends DefaultLexer {
      constructor(services) {
        super(services);
        this.chevrotainLexer = new Lexer(Object.values(this.definition), {
          positionTracking: "full",
          safeMode: true,
          errorMessageProvider: services.parser.LexerErrorMessageProvider
        });
      }
    }
    class ZenValueConverter extends DefaultValueConverter {
      runConverter(_rule, input, _cstNode) {
        return input;
      }
    }
    const ZenUmlModule = {
      parser: {
        TokenBuilder: () => new ZenTokenBuilder(),
        Lexer: (services) => new ZenLexer(services),
        ValueConverter: () => new ZenValueConverter()
      }
    };
    function collectParticipantNames(root2) {
      if (!root2) return [];
      const names = /* @__PURE__ */ new Set();
      for (const node2 of streamAllContents(root2)) {
        if (isParticipant(node2) && node2.name) names.add(node2.name);
        else if (isGroup(node2) && node2.name) names.add(node2.name);
        else if (isFrom(node2) && node2.name) names.add(node2.name);
        else if (isTo(node2) && node2.name) names.add(node2.name);
        else if (isCreation(node2)) {
          const ctor = node2.body?.construct;
          if (ctor) names.add(ctor);
        }
      }
      return [...names].sort();
    }
    class ZenUmlCompletionProvider extends DefaultCompletionProvider {
      async getCompletion(document, params, cancelToken) {
        const base = await super.getCompletion(document, params, cancelToken);
        const names = collectParticipantNames(document.parseResult?.value);
        const items = names.map((name) => ({
          label: name,
          kind: mainExports$1.CompletionItemKind.Variable,
          detail: "participant",
          sortText: `0_${name}`
          // surface known participants above keywords
        }));
        if (!base) {
          return { isIncomplete: false, items };
        }
        const existing = new Set(base.items.map((i) => i.label));
        for (const item of items) {
          if (!existing.has(item.label)) base.items.push(item);
        }
        return base;
      }
    }
    class ZenUmlHoverProvider extends AstNodeHoverProvider {
      getAstNodeHoverContent(node2) {
        if (isParticipant(node2)) {
          const type = node2.participantType ? ` \`${node2.participantType}\`` : "";
          const stereotype = node2.stereotype?.name ? ` «${node2.stereotype.name}»` : "";
          return `**Participant**${type} \`${node2.name ?? "?"}\`${stereotype}`;
        }
        if (isFrom(node2) || isTo(node2)) {
          return `**Participant** \`${node2.name ?? "?"}\``;
        }
        if (isMessage(node2)) {
          const to = node2.body?.fromTo?.to?.name;
          const method = node2.body?.func?.signatures?.[0]?.methodName?.name;
          const target = [to, method].filter(Boolean).join(".");
          return `**Message** → \`${target || "?"}\``;
        }
        if (isCreation(node2)) {
          const ctor = node2.body?.construct;
          return `**Creation** \`new ${ctor ?? "?"}\``;
        }
        if (isTitle(node2)) {
          return `**Title** — ${node2.content ?? ""}`;
        }
        return void 0;
      }
    }
    function registerZenUmlValidationChecks(services) {
      const registry = services.validation.ValidationRegistry;
      const validator = services.validation.ZenUmlValidator;
      const checks = {
        Prog: validator.checkDuplicateParticipants
      };
      registry.register(checks, validator);
    }
    class ZenUmlValidator {
      /**
       * Warn when the same participant is explicitly declared more than once in the
       * head — harmless but redundant, and usually a copy-paste mistake.
       */
      checkDuplicateParticipants(prog, accept) {
        const seen = /* @__PURE__ */ new Set();
        for (const el of prog.headElements) {
          if (!isParticipant(el) || !el.name) continue;
          if (seen.has(el.name)) {
            accept("warning", `Duplicate participant declaration: '${el.name}'.`, {
              node: el,
              property: "name"
            });
          } else {
            seen.add(el.name);
          }
        }
      }
    }
    const ZenUmlLspModule = {
      validation: {
        ZenUmlValidator: () => new ZenUmlValidator()
      },
      lsp: {
        CompletionProvider: (services) => new ZenUmlCompletionProvider(services),
        HoverProvider: (services) => new ZenUmlHoverProvider(services)
      }
    };
    function createZenUmlLspServices(context) {
      const shared2 = inject(
        createDefaultSharedModule(context),
        ZenUmlGeneratedSharedModule
      );
      const ZenUml = inject(
        createDefaultModule({ shared: shared2 }),
        ZenUmlGeneratedModule,
        // Core parser overrides are typed for LangiumCoreServices; LangiumServices
        // is a superset, and the overrides only touch core parser fields.
        ZenUmlModule,
        ZenUmlLspModule
      );
      shared2.ServiceRegistry.register(ZenUml);
      registerZenUmlValidationChecks(ZenUml);
      return { shared: shared2, ZenUml };
    }
    const connection = nodeExports.createConnection(nodeExports.ProposedFeatures.all);
    const { shared } = createZenUmlLspServices({ connection, ...NodeFileSystem });
    startLanguageServer(shared);
  }
});
export default require_main();
