var Pt = Object.defineProperty;
var jt = (r, n, t) => n in r ? Pt(r, n, { enumerable: !0, configurable: !0, writable: !0, value: t }) : r[n] = t;
var U = (r, n, t) => (jt(r, typeof n != "symbol" ? n + "" : n, t), t);
import z, { useEffect as J, createContext as Qe, useState as oe, useRef as Ve, useContext as et, memo as kt } from "react";
import { loader as At, useMonaco as Lt, Editor as Dt } from "@monaco-editor/react";
import { getMonacoTheme as $t, lspSubject as Ft, LspActions as G, hasAttributesString as tt, FileFolderType as Mt } from "@ws-ui/shared";
import { initServices as Wt, MonacoLanguageClient as Kt } from "monaco-languageclient";
import { ErrorAction as Yt, CloseAction as Ut } from "vscode-languageclient";
import * as c from "monaco-editor";
import { Selection as Vt, KeyMod as Q, KeyCode as ee, editor as nt, Uri as qt } from "monaco-editor";
import { WebSocketMessageReader as Bt, WebSocketMessageWriter as zt, toSocket as Gt } from "vscode-ws-jsonrpc";
import { WillSaveTextDocumentNotification as Zt, TextDocumentSaveReason as Jt, DidSaveTextDocumentNotification as Ht, WillCreateFilesRequest as Xt, WillRenameFilesRequest as Qt, WillDeleteFilesRequest as en, DidCreateFilesNotification as tn, DidRenameFilesNotification as nn, DidDeleteFilesNotification as rn } from "vscode-languageserver-protocol";
import { ICodeEditorService as qe, StandaloneServices as xe, ILanguageFeaturesService as Be, ITextModelService as ze } from "vscode/services";
var Re = { exports: {} }, te = {};
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/
var Ce, Ge;
function rt() {
  if (Ge)
    return Ce;
  Ge = 1;
  var r = Object.getOwnPropertySymbols, n = Object.prototype.hasOwnProperty, t = Object.prototype.propertyIsEnumerable;
  function i(u) {
    if (u == null)
      throw new TypeError("Object.assign cannot be called with null or undefined");
    return Object(u);
  }
  function l() {
    try {
      if (!Object.assign)
        return !1;
      var u = new String("abc");
      if (u[5] = "de", Object.getOwnPropertyNames(u)[0] === "5")
        return !1;
      for (var f = {}, s = 0; s < 10; s++)
        f["_" + String.fromCharCode(s)] = s;
      var d = Object.getOwnPropertyNames(f).map(function(b) {
        return f[b];
      });
      if (d.join("") !== "0123456789")
        return !1;
      var h = {};
      return "abcdefghijklmnopqrst".split("").forEach(function(b) {
        h[b] = b;
      }), Object.keys(Object.assign({}, h)).join("") === "abcdefghijklmnopqrst";
    } catch {
      return !1;
    }
  }
  return Ce = l() ? Object.assign : function(u, f) {
    for (var s, d = i(u), h, b = 1; b < arguments.length; b++) {
      s = Object(arguments[b]);
      for (var S in s)
        n.call(s, S) && (d[S] = s[S]);
      if (r) {
        h = r(s);
        for (var v = 0; v < h.length; v++)
          t.call(s, h[v]) && (d[h[v]] = s[h[v]]);
      }
    }
    return d;
  }, Ce;
}
/** @license React v17.0.2
 * react-jsx-runtime.production.min.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var Ze;
function on() {
  if (Ze)
    return te;
  Ze = 1, rt();
  var r = z, n = 60103;
  if (te.Fragment = 60107, typeof Symbol == "function" && Symbol.for) {
    var t = Symbol.for;
    n = t("react.element"), te.Fragment = t("react.fragment");
  }
  var i = r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, l = Object.prototype.hasOwnProperty, u = { key: !0, ref: !0, __self: !0, __source: !0 };
  function f(s, d, h) {
    var b, S = {}, v = null, O = null;
    h !== void 0 && (v = "" + h), d.key !== void 0 && (v = "" + d.key), d.ref !== void 0 && (O = d.ref);
    for (b in d)
      l.call(d, b) && !u.hasOwnProperty(b) && (S[b] = d[b]);
    if (s && s.defaultProps)
      for (b in d = s.defaultProps, d)
        S[b] === void 0 && (S[b] = d[b]);
    return { $$typeof: n, type: s, key: v, ref: O, props: S, _owner: i.current };
  }
  return te.jsx = f, te.jsxs = f, te;
}
var Ee = {};
/** @license React v17.0.2
 * react-jsx-runtime.development.js
 *
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
var Je;
function an() {
  return Je || (Je = 1, function(r) {
    process.env.NODE_ENV !== "production" && function() {
      var n = z, t = rt(), i = 60103, l = 60106;
      r.Fragment = 60107;
      var u = 60108, f = 60114, s = 60109, d = 60110, h = 60112, b = 60113, S = 60120, v = 60115, O = 60116, k = 60121, P = 60122, $ = 60117, _ = 60129, R = 60131;
      if (typeof Symbol == "function" && Symbol.for) {
        var y = Symbol.for;
        i = y("react.element"), l = y("react.portal"), r.Fragment = y("react.fragment"), u = y("react.strict_mode"), f = y("react.profiler"), s = y("react.provider"), d = y("react.context"), h = y("react.forward_ref"), b = y("react.suspense"), S = y("react.suspense_list"), v = y("react.memo"), O = y("react.lazy"), k = y("react.block"), P = y("react.server.block"), $ = y("react.fundamental"), y("react.scope"), y("react.opaque.id"), _ = y("react.debug_trace_mode"), y("react.offscreen"), R = y("react.legacy_hidden");
      }
      var g = typeof Symbol == "function" && Symbol.iterator, p = "@@iterator";
      function M(e) {
        if (e === null || typeof e != "object")
          return null;
        var o = g && e[g] || e[p];
        return typeof o == "function" ? o : null;
      }
      var F = n.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;
      function A(e) {
        {
          for (var o = arguments.length, a = new Array(o > 1 ? o - 1 : 0), m = 1; m < o; m++)
            a[m - 1] = arguments[m];
          Y("error", e, a);
        }
      }
      function Y(e, o, a) {
        {
          var m = F.ReactDebugCurrentFrame, T = m.getStackAddendum();
          T !== "" && (o += "%s", a = a.concat([T]));
          var N = a.map(function(E) {
            return "" + E;
          });
          N.unshift("Warning: " + o), Function.prototype.apply.call(console[e], console, N);
        }
      }
      var ce = !1;
      function x(e) {
        return !!(typeof e == "string" || typeof e == "function" || e === r.Fragment || e === f || e === _ || e === u || e === b || e === S || e === R || ce || typeof e == "object" && e !== null && (e.$$typeof === O || e.$$typeof === v || e.$$typeof === s || e.$$typeof === d || e.$$typeof === h || e.$$typeof === $ || e.$$typeof === k || e[0] === P));
      }
      function I(e, o, a) {
        var m = o.displayName || o.name || "";
        return e.displayName || (m !== "" ? a + "(" + m + ")" : a);
      }
      function w(e) {
        return e.displayName || "Context";
      }
      function W(e) {
        if (e == null)
          return null;
        if (typeof e.tag == "number" && A("Received an unexpected object in getComponentName(). This is likely a bug in React. Please file an issue."), typeof e == "function")
          return e.displayName || e.name || null;
        if (typeof e == "string")
          return e;
        switch (e) {
          case r.Fragment:
            return "Fragment";
          case l:
            return "Portal";
          case f:
            return "Profiler";
          case u:
            return "StrictMode";
          case b:
            return "Suspense";
          case S:
            return "SuspenseList";
        }
        if (typeof e == "object")
          switch (e.$$typeof) {
            case d:
              var o = e;
              return w(o) + ".Consumer";
            case s:
              var a = e;
              return w(a._context) + ".Provider";
            case h:
              return I(e, e.render, "ForwardRef");
            case v:
              return W(e.type);
            case k:
              return W(e._render);
            case O: {
              var m = e, T = m._payload, N = m._init;
              try {
                return W(N(T));
              } catch {
                return null;
              }
            }
          }
        return null;
      }
      var ne = 0, Se, ye, we, _e, Ie, Te, Ne;
      function Oe() {
      }
      Oe.__reactDisabledLog = !0;
      function ct() {
        {
          if (ne === 0) {
            Se = console.log, ye = console.info, we = console.warn, _e = console.error, Ie = console.group, Te = console.groupCollapsed, Ne = console.groupEnd;
            var e = {
              configurable: !0,
              enumerable: !0,
              value: Oe,
              writable: !0
            };
            Object.defineProperties(console, {
              info: e,
              log: e,
              warn: e,
              error: e,
              group: e,
              groupCollapsed: e,
              groupEnd: e
            });
          }
          ne++;
        }
      }
      function ft() {
        {
          if (ne--, ne === 0) {
            var e = {
              configurable: !0,
              enumerable: !0,
              writable: !0
            };
            Object.defineProperties(console, {
              log: t({}, e, {
                value: Se
              }),
              info: t({}, e, {
                value: ye
              }),
              warn: t({}, e, {
                value: we
              }),
              error: t({}, e, {
                value: _e
              }),
              group: t({}, e, {
                value: Ie
              }),
              groupCollapsed: t({}, e, {
                value: Te
              }),
              groupEnd: t({}, e, {
                value: Ne
              })
            });
          }
          ne < 0 && A("disabledDepth fell below zero. This is a bug in React. Please file an issue.");
        }
      }
      var fe = F.ReactCurrentDispatcher, de;
      function ae(e, o, a) {
        {
          if (de === void 0)
            try {
              throw Error();
            } catch (T) {
              var m = T.stack.trim().match(/\n( *(at )?)/);
              de = m && m[1] || "";
            }
          return `
` + de + e;
        }
      }
      var me = !1, se;
      {
        var dt = typeof WeakMap == "function" ? WeakMap : Map;
        se = new dt();
      }
      function Pe(e, o) {
        if (!e || me)
          return "";
        {
          var a = se.get(e);
          if (a !== void 0)
            return a;
        }
        var m;
        me = !0;
        var T = Error.prepareStackTrace;
        Error.prepareStackTrace = void 0;
        var N;
        N = fe.current, fe.current = null, ct();
        try {
          if (o) {
            var E = function() {
              throw Error();
            };
            if (Object.defineProperty(E.prototype, "props", {
              set: function() {
                throw Error();
              }
            }), typeof Reflect == "object" && Reflect.construct) {
              try {
                Reflect.construct(E, []);
              } catch (B) {
                m = B;
              }
              Reflect.construct(e, [], E);
            } else {
              try {
                E.call();
              } catch (B) {
                m = B;
              }
              e.call(E.prototype);
            }
          } else {
            try {
              throw Error();
            } catch (B) {
              m = B;
            }
            e();
          }
        } catch (B) {
          if (B && m && typeof B.stack == "string") {
            for (var C = B.stack.split(`
`), K = m.stack.split(`
`), L = C.length - 1, D = K.length - 1; L >= 1 && D >= 0 && C[L] !== K[D]; )
              D--;
            for (; L >= 1 && D >= 0; L--, D--)
              if (C[L] !== K[D]) {
                if (L !== 1 || D !== 1)
                  do
                    if (L--, D--, D < 0 || C[L] !== K[D]) {
                      var q = `
` + C[L].replace(" at new ", " at ");
                      return typeof e == "function" && se.set(e, q), q;
                    }
                  while (L >= 1 && D >= 0);
                break;
              }
          }
        } finally {
          me = !1, fe.current = N, ft(), Error.prepareStackTrace = T;
        }
        var X = e ? e.displayName || e.name : "", Ue = X ? ae(X) : "";
        return typeof e == "function" && se.set(e, Ue), Ue;
      }
      function je(e, o, a) {
        return Pe(e, !1);
      }
      function mt(e) {
        var o = e.prototype;
        return !!(o && o.isReactComponent);
      }
      function le(e, o, a) {
        if (e == null)
          return "";
        if (typeof e == "function")
          return Pe(e, mt(e));
        if (typeof e == "string")
          return ae(e);
        switch (e) {
          case b:
            return ae("Suspense");
          case S:
            return ae("SuspenseList");
        }
        if (typeof e == "object")
          switch (e.$$typeof) {
            case h:
              return je(e.render);
            case v:
              return le(e.type, o, a);
            case k:
              return je(e._render);
            case O: {
              var m = e, T = m._payload, N = m._init;
              try {
                return le(N(T), o, a);
              } catch {
              }
            }
          }
        return "";
      }
      var ke = {}, Ae = F.ReactDebugCurrentFrame;
      function ue(e) {
        if (e) {
          var o = e._owner, a = le(e.type, e._source, o ? o.type : null);
          Ae.setExtraStackFrame(a);
        } else
          Ae.setExtraStackFrame(null);
      }
      function gt(e, o, a, m, T) {
        {
          var N = Function.call.bind(Object.prototype.hasOwnProperty);
          for (var E in e)
            if (N(e, E)) {
              var C = void 0;
              try {
                if (typeof e[E] != "function") {
                  var K = Error((m || "React class") + ": " + a + " type `" + E + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof e[E] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`.");
                  throw K.name = "Invariant Violation", K;
                }
                C = e[E](o, E, m, a, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED");
              } catch (L) {
                C = L;
              }
              C && !(C instanceof Error) && (ue(T), A("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", m || "React class", a, E, typeof C), ue(null)), C instanceof Error && !(C.message in ke) && (ke[C.message] = !0, ue(T), A("Failed %s type: %s", a, C.message), ue(null));
            }
        }
      }
      var re = F.ReactCurrentOwner, ge = Object.prototype.hasOwnProperty, pt = {
        key: !0,
        ref: !0,
        __self: !0,
        __source: !0
      }, Le, De, pe;
      pe = {};
      function vt(e) {
        if (ge.call(e, "ref")) {
          var o = Object.getOwnPropertyDescriptor(e, "ref").get;
          if (o && o.isReactWarning)
            return !1;
        }
        return e.ref !== void 0;
      }
      function ht(e) {
        if (ge.call(e, "key")) {
          var o = Object.getOwnPropertyDescriptor(e, "key").get;
          if (o && o.isReactWarning)
            return !1;
        }
        return e.key !== void 0;
      }
      function bt(e, o) {
        if (typeof e.ref == "string" && re.current && o && re.current.stateNode !== o) {
          var a = W(re.current.type);
          pe[a] || (A('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', W(re.current.type), e.ref), pe[a] = !0);
        }
      }
      function Ct(e, o) {
        {
          var a = function() {
            Le || (Le = !0, A("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", o));
          };
          a.isReactWarning = !0, Object.defineProperty(e, "key", {
            get: a,
            configurable: !0
          });
        }
      }
      function Et(e, o) {
        {
          var a = function() {
            De || (De = !0, A("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", o));
          };
          a.isReactWarning = !0, Object.defineProperty(e, "ref", {
            get: a,
            configurable: !0
          });
        }
      }
      var Rt = function(e, o, a, m, T, N, E) {
        var C = {
          // This tag allows us to uniquely identify this as a React Element
          $$typeof: i,
          // Built-in properties that belong on the element
          type: e,
          key: o,
          ref: a,
          props: E,
          // Record the component responsible for creating this element.
          _owner: N
        };
        return C._store = {}, Object.defineProperty(C._store, "validated", {
          configurable: !1,
          enumerable: !1,
          writable: !0,
          value: !1
        }), Object.defineProperty(C, "_self", {
          configurable: !1,
          enumerable: !1,
          writable: !1,
          value: m
        }), Object.defineProperty(C, "_source", {
          configurable: !1,
          enumerable: !1,
          writable: !1,
          value: T
        }), Object.freeze && (Object.freeze(C.props), Object.freeze(C)), C;
      };
      function xt(e, o, a, m, T) {
        {
          var N, E = {}, C = null, K = null;
          a !== void 0 && (C = "" + a), ht(o) && (C = "" + o.key), vt(o) && (K = o.ref, bt(o, T));
          for (N in o)
            ge.call(o, N) && !pt.hasOwnProperty(N) && (E[N] = o[N]);
          if (e && e.defaultProps) {
            var L = e.defaultProps;
            for (N in L)
              E[N] === void 0 && (E[N] = L[N]);
          }
          if (C || K) {
            var D = typeof e == "function" ? e.displayName || e.name || "Unknown" : e;
            C && Ct(E, D), K && Et(E, D);
          }
          return Rt(e, C, K, T, m, re.current, E);
        }
      }
      var ve = F.ReactCurrentOwner, $e = F.ReactDebugCurrentFrame;
      function H(e) {
        if (e) {
          var o = e._owner, a = le(e.type, e._source, o ? o.type : null);
          $e.setExtraStackFrame(a);
        } else
          $e.setExtraStackFrame(null);
      }
      var he;
      he = !1;
      function be(e) {
        return typeof e == "object" && e !== null && e.$$typeof === i;
      }
      function Fe() {
        {
          if (ve.current) {
            var e = W(ve.current.type);
            if (e)
              return `

Check the render method of \`` + e + "`.";
          }
          return "";
        }
      }
      function St(e) {
        {
          if (e !== void 0) {
            var o = e.fileName.replace(/^.*[\\\/]/, ""), a = e.lineNumber;
            return `

Check your code at ` + o + ":" + a + ".";
          }
          return "";
        }
      }
      var Me = {};
      function yt(e) {
        {
          var o = Fe();
          if (!o) {
            var a = typeof e == "string" ? e : e.displayName || e.name;
            a && (o = `

Check the top-level render call using <` + a + ">.");
          }
          return o;
        }
      }
      function We(e, o) {
        {
          if (!e._store || e._store.validated || e.key != null)
            return;
          e._store.validated = !0;
          var a = yt(o);
          if (Me[a])
            return;
          Me[a] = !0;
          var m = "";
          e && e._owner && e._owner !== ve.current && (m = " It was passed a child from " + W(e._owner.type) + "."), H(e), A('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', a, m), H(null);
        }
      }
      function Ke(e, o) {
        {
          if (typeof e != "object")
            return;
          if (Array.isArray(e))
            for (var a = 0; a < e.length; a++) {
              var m = e[a];
              be(m) && We(m, o);
            }
          else if (be(e))
            e._store && (e._store.validated = !0);
          else if (e) {
            var T = M(e);
            if (typeof T == "function" && T !== e.entries)
              for (var N = T.call(e), E; !(E = N.next()).done; )
                be(E.value) && We(E.value, o);
          }
        }
      }
      function wt(e) {
        {
          var o = e.type;
          if (o == null || typeof o == "string")
            return;
          var a;
          if (typeof o == "function")
            a = o.propTypes;
          else if (typeof o == "object" && (o.$$typeof === h || // Note: Memo only checks outer props here.
          // Inner props are checked in the reconciler.
          o.$$typeof === v))
            a = o.propTypes;
          else
            return;
          if (a) {
            var m = W(o);
            gt(a, e.props, "prop", m, e);
          } else if (o.PropTypes !== void 0 && !he) {
            he = !0;
            var T = W(o);
            A("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", T || "Unknown");
          }
          typeof o.getDefaultProps == "function" && !o.getDefaultProps.isReactClassApproved && A("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead.");
        }
      }
      function _t(e) {
        {
          for (var o = Object.keys(e.props), a = 0; a < o.length; a++) {
            var m = o[a];
            if (m !== "children" && m !== "key") {
              H(e), A("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", m), H(null);
              break;
            }
          }
          e.ref !== null && (H(e), A("Invalid attribute `ref` supplied to `React.Fragment`."), H(null));
        }
      }
      function Ye(e, o, a, m, T, N) {
        {
          var E = x(e);
          if (!E) {
            var C = "";
            (e === void 0 || typeof e == "object" && e !== null && Object.keys(e).length === 0) && (C += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.");
            var K = St(T);
            K ? C += K : C += Fe();
            var L;
            e === null ? L = "null" : Array.isArray(e) ? L = "array" : e !== void 0 && e.$$typeof === i ? (L = "<" + (W(e.type) || "Unknown") + " />", C = " Did you accidentally export a JSX literal instead of a component?") : L = typeof e, A("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", L, C);
          }
          var D = xt(e, o, a, T, N);
          if (D == null)
            return D;
          if (E) {
            var q = o.children;
            if (q !== void 0)
              if (m)
                if (Array.isArray(q)) {
                  for (var X = 0; X < q.length; X++)
                    Ke(q[X], e);
                  Object.freeze && Object.freeze(q);
                } else
                  A("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");
              else
                Ke(q, e);
          }
          return e === r.Fragment ? _t(D) : wt(D), D;
        }
      }
      function It(e, o, a) {
        return Ye(e, o, a, !0);
      }
      function Tt(e, o, a) {
        return Ye(e, o, a, !1);
      }
      var Nt = Tt, Ot = It;
      r.jsx = Nt, r.jsxs = Ot;
    }();
  }(Ee)), Ee;
}
process.env.NODE_ENV === "production" ? Re.exports = on() : Re.exports = an();
var j = Re.exports;
class sn extends Bt {
  constructor(t, i) {
    super(t);
    U(this, "onMessage");
    this.onMessage = i;
  }
  readMessage(t) {
    this.onMessage && this.onMessage();
    const [, i] = t.split(`\r
\r
`);
    if (this.state === "initial")
      this.events.splice(0, 0, { message: i });
    else if (this.state === "listening") {
      const l = JSON.parse(i);
      this.callback(l);
    }
  }
}
class ln extends zt {
  constructor(t, i) {
    super(t);
    U(this, "onSend");
    this.onSend = i;
  }
  async write(t) {
    try {
      const i = JSON.stringify(t);
      this.socket.send(i), this.onSend && this.onSend();
    } catch (i) {
      this.errorCount++, this.fireError(i, t, this.errorCount);
    }
  }
}
const un = {
  base: "vs-dark",
  inherit: !0,
  colors: {
    "editor.background": "#313131"
  },
  rules: [
    {
      token: "",
      background: "#313131"
    }
  ]
};
function V(r) {
  return `file:///PACKAGE/Project/Sources/${r}`;
}
function it(r, n = 0) {
  setTimeout(r, n);
}
function cn(r, n) {
  const t = new Vt(
    n.startLineNumber,
    n.startColumn,
    n.endLineNumber || n.startLineNumber,
    n.endColumn || n.startColumn
  );
  it(() => {
    r.setSelection(t), r.revealRangeInCenter(t), r.focus();
  });
}
function fn(r, n, t = 0) {
  t > 0 && (n = t + n), it(() => {
    r.setPosition({ lineNumber: n, column: 1 }), r.revealLineInCenter(n), r.focus();
  });
}
function Vn(r, n, t) {
  const l = r.getModel();
  if (l && n) {
    const u = l.getLineCount();
    for (let f = 1; f <= u; f++) {
      const s = l.getLineContent(f);
      if (new RegExp(`(?:Function|function) ${t}`).test(s))
        return f;
    }
  }
  return 0;
}
const dn = {
  getServiceOverride: ({ openHandler: r }) => ({
    get [qe.toString()]() {
      const n = xe.get(qe);
      return r && n.registerCodeEditorOpenHandler(r), n;
    }
  })
}, mn = {
  getServiceOverride: () => ({
    get [Be.toString()]() {
      return xe.get(
        Be
      );
    }
  })
}, gn = {
  getServiceOverride: () => ({
    get [ze.toString()]() {
      const r = xe.get(ze);
      return r.createModelReference = (n) => Promise.resolve({ dispose: () => {
      } }), r;
    }
  })
}, pn = {
  comments: {
    lineComment: "//",
    blockComment: ["/**", "**/"]
  },
  brackets: [
    ["{", "}"],
    ["(", ")"],
    ["[", "]"]
  ],
  surroundingPairs: [
    { open: "{", close: "}" },
    { open: "[", close: "]" },
    { open: "(", close: ")" },
    { open: '"', close: '"' },
    { open: "'", close: "'" }
  ],
  autoClosingPairs: [
    { open: "(", close: ")" },
    { open: "{", close: "}" },
    { open: "[", close: "]" },
    { open: "'", close: "'", notIn: ["string", "comment"] },
    { open: '"', close: '"', notIn: ["string"] },
    { open: "`", close: "`", notIn: ["string", "comment"] },
    { open: "/**", close: " **/", notIn: ["string"] }
  ],
  autoCloseBefore: ";:.,=}])>` \n	",
  wordPattern: new RegExp(
    "(-?\\d*\\.\\d\\w*)|([^\\`\\~\\!\\@\\#\\%\\^\\&\\*\\(\\)\\-\\=\\+\\[\\{\\]\\}\\\\\\|\\;\\:\\'\\\"\\,\\.\\<\\>\\/\\?\\r\\n\\t\\f\\v ]+)|(?<=[a-zA-Z]) ?(?=[a-zA-Z])"
  ),
  indentationRules: {
    increaseIndentPattern: new RegExp(
      "(^(?![^\\s])*\\s*(class constructor))|(^(?![^\\s])*\\s*(exposed|local|\\s*){1}\\s*function{1}\\s*\\w)|(^(?![^\\s])*\\s*(If|Else|For|For each|While|Begin SQL|Case of|Use|Repeat|: *\\(.*)).*$",
      "i"
    ),
    decreaseIndentPattern: new RegExp(
      "(^(?![^\\s])*\\s*(exposed|local|\\s*){1}\\s*function{1}\\s*\\w)|(End If|End For|Else|End for each|End While|End SQL|End case|End use|Until|: *\\(.*).*$",
      "i"
    )
  },
  onEnterRules: [
    {
      beforeText: new RegExp("^exposed", "i"),
      action: { indentAction: 1 }
    }
  ]
}, vn = {
  provideCompletionItems: async (r, n) => {
    const t = r.getWordUntilPosition(n);
    return {
      suggestions: [
        {
          label: "var",
          kind: c.languages.CompletionItemKind.Snippet,
          range: new c.Range(
            n.lineNumber,
            t.startColumn,
            n.lineNumber,
            t.endColumn
          ),
          insertText: ["var ${1:var_name} : ${2:var_type}"].join(`
`),
          insertTextRules: c.languages.CompletionItemInsertTextRule.InsertAsSnippet
        },
        {
          label: "While",
          kind: c.languages.CompletionItemKind.Snippet,
          range: new c.Range(
            n.lineNumber,
            t.startColumn,
            n.lineNumber,
            t.endColumn
          ),
          insertText: [
            "While(${1:expression})",
            "	${2:body}",
            "End while"
          ].join(`
`),
          insertTextRules: c.languages.CompletionItemInsertTextRule.InsertAsSnippet
        },
        {
          label: "Case of",
          kind: c.languages.CompletionItemKind.Snippet,
          range: new c.Range(
            n.lineNumber,
            t.startColumn,
            n.lineNumber,
            t.endColumn
          ),
          insertText: [
            "Case of",
            "	:(${1:boolean_expression})",
            "		${2:body}",
            "End case"
          ].join(`
`),
          insertTextRules: c.languages.CompletionItemInsertTextRule.InsertAsSnippet
        },
        {
          label: "Else",
          kind: c.languages.CompletionItemKind.Snippet,
          range: new c.Range(
            n.lineNumber,
            t.startColumn,
            n.lineNumber,
            t.endColumn
          ),
          insertText: ["Else", "	"].join(`
`),
          insertTextRules: c.languages.CompletionItemInsertTextRule.InsertAsSnippet
        },
        {
          label: "If",
          kind: c.languages.CompletionItemKind.Snippet,
          range: new c.Range(
            n.lineNumber,
            t.startColumn,
            n.lineNumber,
            t.endColumn
          ),
          insertText: ["If (${1:expression})", "	${5:body}", "End if"].join(
            `
`
          ),
          insertTextRules: c.languages.CompletionItemInsertTextRule.InsertAsSnippet
        },
        {
          label: "For",
          kind: c.languages.CompletionItemKind.Snippet,
          range: new c.Range(
            n.lineNumber,
            t.startColumn,
            n.lineNumber,
            t.endColumn
          ),
          insertText: [
            "For(${1:counter};${2:start};${3:end}${4:;increment})",
            "	${5:body}",
            "End for"
          ].join(`
`),
          insertTextRules: c.languages.CompletionItemInsertTextRule.InsertAsSnippet
        },
        {
          label: "Function",
          kind: c.languages.CompletionItemKind.Snippet,
          range: new c.Range(
            n.lineNumber,
            t.startColumn,
            n.lineNumber,
            t.endColumn
          ),
          insertText: [
            "Function ${1:function_name}(${2:params}) -> ${3:var_name} : ${4:var_type}",
            "	${5:body}"
          ].join(`
`),
          insertTextRules: c.languages.CompletionItemInsertTextRule.InsertAsSnippet
        }
      ]
    };
  }
}, hn = {
  provideCompletionItems: async (r, n) => {
    const t = r.getWordUntilPosition(n);
    return {
      suggestions: [
        {
          label: "var",
          kind: c.languages.CompletionItemKind.Snippet,
          range: new c.Range(
            n.lineNumber,
            t.startColumn,
            n.lineNumber,
            t.endColumn
          ),
          insertText: ["var ${1:var_name} : ${2:var_type}"].join(`
`),
          insertTextRules: c.languages.CompletionItemInsertTextRule.InsertAsSnippet
        },
        {
          label: "while",
          kind: c.languages.CompletionItemKind.Snippet,
          range: new c.Range(
            n.lineNumber,
            t.startColumn,
            n.lineNumber,
            t.endColumn
          ),
          insertText: ["while(${1:expression})", "	${2:body}", "end"].join(
            `
`
          ),
          insertTextRules: c.languages.CompletionItemInsertTextRule.InsertAsSnippet
        },
        {
          label: "switch",
          kind: c.languages.CompletionItemKind.Snippet,
          range: new c.Range(
            n.lineNumber,
            t.startColumn,
            n.lineNumber,
            t.endColumn
          ),
          insertText: [
            "switch",
            "	:(${1:boolean_expression})",
            "		${2:body}",
            "end"
          ].join(`
`),
          insertTextRules: c.languages.CompletionItemInsertTextRule.InsertAsSnippet
        },
        {
          label: "else",
          kind: c.languages.CompletionItemKind.Snippet,
          range: new c.Range(
            n.lineNumber,
            t.startColumn,
            n.lineNumber,
            t.endColumn
          ),
          insertText: ["else", "	"].join(`
`),
          insertTextRules: c.languages.CompletionItemInsertTextRule.InsertAsSnippet
        },
        {
          label: "if",
          kind: c.languages.CompletionItemKind.Snippet,
          range: new c.Range(
            n.lineNumber,
            t.startColumn,
            n.lineNumber,
            t.endColumn
          ),
          insertText: ["if (${1:expression})", "	${5:body}", "end"].join(
            `
`
          ),
          insertTextRules: c.languages.CompletionItemInsertTextRule.InsertAsSnippet
        },
        {
          label: "for",
          kind: c.languages.CompletionItemKind.Snippet,
          range: new c.Range(
            n.lineNumber,
            t.startColumn,
            n.lineNumber,
            t.endColumn
          ),
          insertText: [
            "for(${1:counter},${2:start},${3:end}${4:,increment})",
            "	${5:body}",
            "end"
          ].join(`
`),
          insertTextRules: c.languages.CompletionItemInsertTextRule.InsertAsSnippet
        },
        {
          label: "function",
          kind: c.languages.CompletionItemKind.Snippet,
          range: new c.Range(
            n.lineNumber,
            t.startColumn,
            n.lineNumber,
            t.endColumn
          ),
          insertText: [
            "function ${1:function_name}(${2:params}) -> ${3:var_name} : ${4:var_type}",
            "	${5:body}"
          ].join(`
`),
          insertTextRules: c.languages.CompletionItemInsertTextRule.InsertAsSnippet
        }
      ]
    };
  }
}, bn = [
  // zoom in
  {
    keybinding: Q.CtrlCmd | ee.NumpadAdd,
    command: "editor.action.fontZoomIn"
  },
  {
    keybinding: Q.CtrlCmd | ee.Equal,
    command: "editor.action.fontZoomIn"
  },
  // zoom out
  {
    keybinding: Q.CtrlCmd | ee.NumpadSubtract,
    command: "editor.action.fontZoomOut"
  },
  {
    keybinding: Q.CtrlCmd | ee.Minus,
    command: "editor.action.fontZoomOut"
  },
  // zoom reset
  {
    keybinding: Q.CtrlCmd | ee.Numpad0,
    command: "editor.action.fontZoomReset"
  },
  {
    keybinding: Q.CtrlCmd | ee.Digit0,
    command: "editor.action.fontZoomReset"
  }
], Cn = ({ defaultZoom: r }) => (J(() => {
  r !== void 0 && nt.EditorZoom.setZoomLevel(r);
}, []), null);
({}).VITE_DISABLE_MONACO_LOADER || At.config({
  monaco: c
  // paths: {
  //   vs: "https://cdn.jsdelivr.net/npm/monaco-editor@0.41.0/min/vs",
  // },
});
const ot = Qe(void 0), qn = ({ children: r, url: n, qodly: t, defaultZoom: i, openHandler: l, language: u = "4d", defaultInited: f = !1 }) => {
  const s = Lt(), [d, h] = oe(f), [b, S] = oe(null), v = Ve(), O = Ve(0);
  J(() => {
    Wt({
      configureEditorOrViewsService: {
        enableViewsService: !1
      },
      debugLogging: !1,
      userServices: {
        // @see https://github.com/CodinGame/monaco-vscode-api#monaco-standalone-services
        ...dn.getServiceOverride({ openHandler: l }),
        ...mn.getServiceOverride(),
        ...gn.getServiceOverride()
      }
    });
  }, []), J(() => {
    n && s && k();
  }, [n, s]);
  const k = async () => {
    if (!s)
      return;
    const x = await $t();
    s.editor.defineTheme("fd-dark", x || un), s.languages.register({
      id: u,
      extensions: [".4dm", ".4qm", ".4qs"],
      aliases: ["4d", "4D"]
    }), s.languages.setLanguageConfiguration(u, pn), s.languages.registerCompletionItemProvider(
      u,
      t ? hn : vn
    ), nt.addKeybindingRules(bn), P();
  }, P = () => {
    S(null);
    let x;
    try {
      x = new WebSocket(localStorage.LSP_SERVER || n);
    } catch {
      S(new Event("INVALID_URL"));
      return;
    }
    x.onopen = $, x.onclose = _, x.onerror = R, O.current = 0;
  }, $ = async function() {
    const x = Gt(this), I = new sn(x), w = new ln(x), W = new Kt({
      name: "4D Language Client",
      clientOptions: {
        workspaceFolder: {
          uri: qt.parse("file:///PACKAGE")
        },
        // use a language id as a document selector
        documentSelector: [{ scheme: "file", language: u }],
        // disable the default error handler
        errorHandler: {
          error: () => ({ action: Yt.Continue }),
          closed: () => ({ action: Ut.DoNotRestart })
        }
      },
      // create a language client connection from the JSON RPC connection on demand
      connectionProvider: {
        get: () => Promise.resolve({
          reader: I,
          writer: w
        })
      }
    });
    v.current = W, I.onClose(() => {
      W.stop(), O.current < 3 ? setTimeout(() => {
        O.current++, P();
      }, 1e3) : S(new Event("WEBSOCKET_CLOSED"));
    }), W.needsStart() && await W.start(), h(!0);
  }, _ = () => {
  }, R = (x) => {
    S(x);
  };
  J(() => {
    const x = Ft.subscribe(({ action: I, payload: w }) => {
      switch (I) {
        case G.WILL_SAVE:
          y(w.filePath);
          break;
        case G.DID_SAVE:
          g(w.filePath, w.content);
          break;
        case G.WILL_CREATE:
          p(w.filePath);
          break;
        case G.DID_CREATE:
          A(w.filePath);
          break;
        case G.WILL_RENAME:
          M(w.oldPath, w.newPath);
          break;
        case G.DID_RENAME:
          Y(w.oldPath, w.newPath);
          break;
        case G.WILL_DELETE:
          F(w.filePath);
          break;
        case G.DID_DELETE:
          ce(w.filePath);
          break;
      }
    });
    return () => x.unsubscribe();
  }, []);
  const y = (x, I = Jt.Manual) => {
    var w;
    (w = v.current) == null || w.sendNotification(Zt.type, {
      textDocument: {
        uri: V(x)
      },
      reason: I
    });
  }, g = (x, I) => {
    var w;
    (w = v.current) == null || w.sendNotification(Ht.type, {
      textDocument: {
        uri: V(x)
      },
      text: I
    });
  }, p = (x) => {
    var I;
    (I = v.current) == null || I.sendRequest(Xt.type, {
      files: [
        {
          uri: V(x)
        }
      ]
    });
  }, M = (x, I) => {
    var w;
    (w = v.current) == null || w.sendRequest(Qt.type, {
      files: [
        {
          oldUri: V(x),
          newUri: V(I)
        }
      ]
    });
  }, F = (x) => {
    var I;
    (I = v.current) == null || I.sendRequest(en.type, {
      files: [
        {
          uri: V(x)
        }
      ]
    });
  }, A = (x) => {
    var I;
    (I = v.current) == null || I.sendNotification(tn.type, {
      files: [
        {
          uri: V(x)
        }
      ]
    });
  }, Y = (x, I) => {
    var w;
    (w = v.current) == null || w.sendNotification(nn.type, {
      files: [
        {
          oldUri: V(x),
          newUri: V(I)
        }
      ]
    });
  }, ce = (x) => {
    var I;
    (I = v.current) == null || I.sendNotification(rn.type, {
      files: [
        {
          uri: V(x)
        }
      ]
    });
  };
  return /* @__PURE__ */ j.jsxs(
    ot.Provider,
    {
      value: {
        inited: d || !!b,
        clientRef: v,
        lastError: b,
        reload: P
      },
      children: [
        r,
        /* @__PURE__ */ j.jsx(Cn, { defaultZoom: i })
      ]
    }
  );
};
function Bn() {
  const r = et(ot);
  if (r === void 0)
    throw new Error("useLSP must be used within an LSPContext");
  return r;
}
const at = Qe(
  void 0
), zn = kt(({ children: r }) => {
  const [n, t] = oe(null);
  return /* @__PURE__ */ j.jsx(
    at.Provider,
    {
      value: {
        editor: n,
        setEditor: t
      },
      children: r
    }
  );
});
function En() {
  const r = et(at), n = oe(null);
  if (r === void 0) {
    const [t, i] = n;
    return {
      editor: t,
      setEditor: i
    };
  }
  return r;
}
var st = {
  color: void 0,
  size: void 0,
  className: void 0,
  style: void 0,
  attr: void 0
}, He = z.createContext && z.createContext(st), Z = globalThis && globalThis.__assign || function() {
  return Z = Object.assign || function(r) {
    for (var n, t = 1, i = arguments.length; t < i; t++) {
      n = arguments[t];
      for (var l in n)
        Object.prototype.hasOwnProperty.call(n, l) && (r[l] = n[l]);
    }
    return r;
  }, Z.apply(this, arguments);
}, Rn = globalThis && globalThis.__rest || function(r, n) {
  var t = {};
  for (var i in r)
    Object.prototype.hasOwnProperty.call(r, i) && n.indexOf(i) < 0 && (t[i] = r[i]);
  if (r != null && typeof Object.getOwnPropertySymbols == "function")
    for (var l = 0, i = Object.getOwnPropertySymbols(r); l < i.length; l++)
      n.indexOf(i[l]) < 0 && Object.prototype.propertyIsEnumerable.call(r, i[l]) && (t[i[l]] = r[i[l]]);
  return t;
};
function lt(r) {
  return r && r.map(function(n, t) {
    return z.createElement(n.tag, Z({
      key: t
    }, n.attr), lt(n.child));
  });
}
function ut(r) {
  return function(n) {
    return z.createElement(xn, Z({
      attr: Z({}, r.attr)
    }, n), lt(r.child));
  };
}
function xn(r) {
  var n = function(t) {
    var i = r.attr, l = r.size, u = r.title, f = Rn(r, ["attr", "size", "title"]), s = l || t.size || "1em", d;
    return t.className && (d = t.className), r.className && (d = (d ? d + " " : "") + r.className), z.createElement("svg", Z({
      stroke: "currentColor",
      fill: "currentColor",
      strokeWidth: "0"
    }, t.attr, i, f, {
      className: d,
      style: Z(Z({
        color: r.color || t.color
      }, t.style), r.style),
      height: s,
      width: s,
      xmlns: "http://www.w3.org/2000/svg"
    }), u && z.createElement("title", null, u), r.children);
  };
  return He !== void 0 ? z.createElement(He.Consumer, null, function(t) {
    return n(t);
  }) : n(st);
}
function Sn(r) {
  return ut({ tag: "svg", attr: { viewBox: "0 0 24 24" }, child: [{ tag: "path", attr: { d: "M12 22C6.47715 22 2 17.5228 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22ZM12 10.5858L9.17157 7.75736L7.75736 9.17157L10.5858 12L7.75736 14.8284L9.17157 16.2426L12 13.4142L14.8284 16.2426L16.2426 14.8284L13.4142 12L16.2426 9.17157L14.8284 7.75736L12 10.5858Z" } }] })(r);
}
function yn(r) {
  return ut({ tag: "svg", attr: { viewBox: "0 0 512 512" }, child: [{ tag: "path", attr: { d: "M449.07 399.08L278.64 82.58c-12.08-22.44-44.26-22.44-56.35 0L51.87 399.08A32 32 0 0080 446.25h340.89a32 32 0 0028.18-47.17zm-198.6-1.83a20 20 0 1120-20 20 20 0 01-20 20zm21.72-201.15l-5.74 122a16 16 0 01-32 0l-5.74-121.95a21.73 21.73 0 0121.5-22.69h.21a21.74 21.74 0 0121.73 22.7z" } }] })(r);
}
const wn = ({ lspProps: { lastError: r, reload: n } }) => {
  const [t, i] = oe(!1), l = () => {
    n();
  }, u = () => {
    i(!1);
  };
  return J(() => {
    i(!!r);
  }, [r]), t ? /* @__PURE__ */ j.jsxs("div", { className: "flex items-center border-b border-fd-gray-darker bg-grey-800 px-2 py-1.5 text-xs text-grey-50", children: [
    /* @__PURE__ */ j.jsxs("span", { className: "flex flex-1 justify-center gap-1", children: [
      /* @__PURE__ */ j.jsx(yn, { className: "h-4 w-4 text-yellow-600" }),
      /* @__PURE__ */ j.jsxs("span", { children: [
        "LSP not loaded.",
        " ",
        /* @__PURE__ */ j.jsx(
          "button",
          {
            className: "text-primary-dark underline",
            onClick: l,
            children: "Reload?"
          }
        )
      ] })
    ] }),
    /* @__PURE__ */ j.jsx("button", { className: "focus:outline-none", children: /* @__PURE__ */ j.jsx(
      Sn,
      {
        className: "h-4 w-4 text-white",
        onClick: u
      }
    ) })
  ] }) : null;
}, _n = {
  provideCompletionItems: (r, n) => {
    const t = r.getWordUntilPosition(n);
    return {
      suggestions: [
        {
          label: "device:xs",
          kind: c.languages.CompletionItemKind.Snippet,
          documentation: "Media query for phone device",
          range: new c.Range(
            n.lineNumber,
            t.startColumn,
            n.lineNumber,
            t.endColumn
          ),
          insertText: [
            "@media screen and (max-width: ${1:365px}) {",
            "  self {",
            "    ${2:background-color}:${3:red};",
            "  }",
            "}"
          ].join(`
`),
          insertTextRules: c.languages.CompletionItemInsertTextRule.InsertAsSnippet
        }
      ]
    };
  }
};
function In(r, n) {
  const t = document.createElement("style");
  t.dataset.id = n, t.textContent = r, document.head.append(t);
}
function Tn(r) {
  return Array.from(document.styleSheets).find(
    (n) => n.ownerNode.getAttribute("data-id") === r
  );
}
function Nn(r, n) {
  const t = [];
  let i = [];
  const l = [], u = (g, p, M, F) => {
    t.push({
      startLineNumber: g,
      endLineNumber: M,
      startColumn: p,
      endColumn: F
    }), h(), d();
  }, f = (g) => {
    l.indexOf(g) < 0 && l.push(g);
  }, s = (g) => {
    const p = l.indexOf(g);
    p < 0 || l.splice(p, 1);
  }, d = () => {
    for (const g of l)
      try {
        g(i);
      } catch (p) {
        console.error(p);
      }
  }, h = () => {
    const g = r.getModel();
    g && (i = Pn(
      t.map((p) => [
        g.getOffsetAt({
          lineNumber: p.startLineNumber,
          column: p.startColumn
        }),
        g.getOffsetAt({
          lineNumber: p.endLineNumber,
          column: p.endColumn
        })
      ]),
      /*mergeJoins*/
      !0
    ), i.length > 0 && (i[0][0] <= 0 && (i[0][0] = Number.NEGATIVE_INFINITY), i[i.length - 1][1] >= g.getValueLength() && (i[i.length - 1][1] = Number.POSITIVE_INFINITY)));
  }, b = (g) => {
    const p = {
      isDeletion: !1,
      isAddition: !1,
      isReplacement: !1
    };
    return g.text === "" ? p.isDeletion = !0 : g.range.startLineNumber === g.range.endLineNumber && g.range.startColumn === g.range.endColumn ? p.isAddition = !0 : p.isReplacement = !0, p;
  }, S = r.onDidChangeModel((g) => {
    h(), R();
  }), v = r.onDidChangeModelContent((g) => {
    if (!g.isUndoing)
      for (const p of g.changes) {
        const M = b(p);
        if (M.isReplacement || M.isDeletion || M.isAddition) {
          const F = t.some(
            (Y) => p.range.startLineNumber >= Y.startLineNumber && p.range.endLineNumber <= Y.endLineNumber && p.range.startColumn >= Y.startColumn && p.range.endColumn <= Y.endColumn
          ), A = !F && n && p.range.startLineNumber === 1 && p.range.startColumn === 1 && !tt(p.text);
          if (F || A) {
            const Y = r.getModel();
            if (Y) {
              Y.undo();
              return;
            }
          }
        }
      }
  }), O = () => {
    S.dispose(), v.dispose();
  };
  let k = [], P = `
    .idoc-readonly-mark {
      cursor: not-allowed;
      z-index: 1;
    }
  `;
  if (P) {
    const g = "monaco-read-only";
    Tn(g) || In(P, g), P = null;
  }
  const $ = () => {
    f(R), R();
  }, _ = () => {
    s(R), k = r.deltaDecorations(k, []);
  }, R = () => {
    const g = r.getModel();
    g && (k = r.deltaDecorations(
      k,
      i.map(y(g))
    ));
  }, y = (g) => (p) => {
    const M = g.getPositionAt(p[0]), F = g.getPositionAt(p[1]);
    return {
      range: new c.Range(
        M.lineNumber,
        M.column,
        F.lineNumber,
        F.column
      ),
      options: {
        className: "idoc-readonly-mark"
      }
    };
  };
  return {
    get buffer() {
      return i;
    },
    exclude: u,
    attach: f,
    detach: s,
    dispose: O,
    show: $,
    hide: _
  };
}
function On(r, n, t) {
  let i = !1;
  const l = (_) => _[1] < _[0] ? (i = !0, [[_[1], _[0]]]) : [[..._]], u = (_) => i ? _.map((R) => R[1] > R[0] ? s(R) : R).reverse() : _;
  let f;
  const s = (_) => (f = _[1], _[1] = _[0], _[0] = f, _), d = l(r);
  let h, b, S, v, O, k, P, $;
  S = d[0];
  for (b of n)
    for (P = b[0], $ = b[1], v = 0; v < d.length; v++) {
      if (S = d[v], O = S[0], k = S[1], O < P)
        k < P ? h = [S] : k <= $ ? h = [[O, P - 1]] : h = [
          [O, P - 1],
          [$ + 1, k]
        ];
      else if (O <= $)
        if (P === Number.NEGATIVE_INFINITY) {
          const _ = $ + 1;
          h = t === 0 ? [] : [[_, k > _ ? k : _]];
        } else
          $ === Number.POSITIVE_INFINITY ? h = t === 0 ? [] : [[P - 1, P - 1]] : k <= $ ? h = t < 0 ? [[P - 1, P - 1]] : t > 0 ? [[$ + 1, $ + 1]] : [] : h = [[$ + 1, k]];
      else
        h = [S];
      if (d.splice(v, 1, ...h), d.length === 1 && d[0][1] < P)
        return u(d);
    }
  return u(d);
}
function Pn(r, n) {
  if (r.length < 2)
    return r;
  const t = [];
  let i = null, l, u;
  r = r.map(
    (f) => (f[1] < f[0] && (l = f[1], f[1] = f[0], f[1] = l), f)
  ).sort((f, s) => f[0] - s[0]), t.push(r[0]);
  for (let f = 1; f < r.length; f++)
    i = t[t.length - 1], u = r[f], i[1] === u[0] && !n ? t.push(u) : i[1] === u[0] - 1 && n ? (i[1] = u[1], t.splice(t.length - 1, 1, i)) : i[1] < u[0] ? t.push(u) : i[1] < u[1] && (i[1] = u[1], t.splice(t.length - 1, 1, i));
  return t;
}
function ie(r, n) {
  return n.bind(r);
}
class jn {
  constructor(n, t) {
    U(this, "editor");
    U(this, "intervals");
    U(this, "disposables", []);
    /**
     * Flag for `excludeIntervals`
     */
    U(this, "prefer", 1);
    U(this, "lastPrefer", 1);
    /**
     * Linked to ICodeEditor.onDidChangeCursorPosition event.
     */
    U(this, "onCursor", ie(
      this,
      function(n) {
        if (n.source === "api")
          return;
        const t = this.getApprovedSelections();
        t.length !== 0 && this.editor.setSelections(t);
      }
    ));
    U(this, "onRectangleSelectionStart", ie(this, function({ event: n }) {
      n.middleButton && (this.lastPrefer = this.prefer, this.prefer = 0, window.addEventListener("pointerup", this.onRectangleSelectionStop));
    }));
    U(this, "onRectangleSelectionStop", ie(this, function() {
      this.prefer = this.lastPrefer, window.removeEventListener("pointerup", this.onRectangleSelectionStop);
    }));
    /**
     * Linked to ICodeEditor.onKeyDown event.
     */
    U(this, "onKey", ie(this, function(n) {
      const t = n.keyCode, i = c.KeyCode;
      if (n.altKey || i.F1 <= t && t <= i.F19 || n.ctrlKey && t !== i.Backspace)
        return;
      if (t === i.UpArrow || t === i.LeftArrow || t === i.Home || t === i.PageUp) {
        this.prefer = -1;
        return;
      }
      if (t === i.DownArrow || t === i.RightArrow || t === i.End || t === i.PageDown) {
        this.prefer = 1;
        return;
      }
      const l = this.getSelections(), u = this.intervals.buffer;
      let f;
      if (t === i.Delete)
        f = (s) => s[0] === s[1] && u.find((d) => s[1] + 1 === d[0]) != null;
      else if (t === i.Backspace)
        f = (s) => s[0] === s[1] && u.find((d) => d[1] + 1 === s[0]) != null;
      else
        return;
      l.findIndex(f) !== -1 && (n.stopPropagation(), n.preventDefault());
    }));
    U(this, "getOffsetAt", ie(this, function(n) {
      let t;
      for (let i = 0; i < this.intervals.buffer.length; i++)
        if (t = this.intervals.buffer[i], n <= t[1])
          return t[0] - n < n - t[1] ? t[0] : t[1];
    }));
    var i;
    this.editor = n, this.intervals = Nn(n, t), (i = this.editor.getModel()) == null || i.setEOL(c.editor.EndOfLineSequence.LF);
  }
  enable() {
    this.disposables.push(
      this.editor.onDidChangeCursorPosition(this.onCursor),
      this.editor.onKeyDown(this.onKey),
      this.editor.onMouseDown(this.onRectangleSelectionStart)
    ), this.intervals.show();
  }
  dispose() {
    for (const n of this.disposables)
      n.dispose();
    this.disposables.splice(0);
  }
  exclude(n, t, i, l) {
    arguments.length === 1 ? this.intervals.exclude(n, 0, n, Number.MAX_SAFE_INTEGER) : this.intervals.exclude(n, t, i, l);
  }
  getApprovedSelections() {
    const n = this.editor.getModel();
    return this.getSelections().map(
      (i) => On(
        i,
        this.intervals.buffer,
        this.prefer
      )
    ).flat().map((i) => {
      const l = n.getPositionAt(i[0]), u = n.getPositionAt(i[1]);
      return new c.Selection(
        l.lineNumber,
        l.column,
        u.lineNumber,
        u.column
      );
    });
  }
  getSelections() {
    const n = this.editor.getModel();
    return (this.editor.getSelections() || []).map((t) => [
      n.getOffsetAt({
        lineNumber: t.selectionStartLineNumber,
        column: t.selectionStartColumn
      }),
      n.getOffsetAt({
        lineNumber: t.positionLineNumber,
        column: t.positionColumn
      })
    ]);
  }
}
const kn = new RegExp("^[	s]+(exposed|Function)", "i"), Xe = () => /* @__PURE__ */ j.jsx("div", { className: "absolute inset-0 animate-pulse", children: /* @__PURE__ */ j.jsx("div", { className: "w-full space-y-4 px-4 py-1", children: /* @__PURE__ */ j.jsxs("div", { className: "space-y-2", children: [
  /* @__PURE__ */ j.jsx("div", { className: "h-3 w-3/4 rounded bg-grey-200" }),
  /* @__PURE__ */ j.jsx("div", { className: "h-3 rounded bg-grey-200" }),
  /* @__PURE__ */ j.jsx("div", { className: "h-3 w-5/6 rounded bg-grey-200" }),
  /* @__PURE__ */ j.jsx("div", { className: "h-3 rounded bg-grey-200" }),
  /* @__PURE__ */ j.jsx("div", { className: "h-3 rounded bg-grey-200" })
] }) }) }), Gn = ({
  path: r,
  initialValue: n,
  theme: t = "fd-dark",
  type: i,
  language: l,
  onChange: u,
  options: f = {},
  extra: s = {},
  showAlerts: d = !1,
  lspProps: h,
  ...b
}) => {
  const { initialLineInfo: S, initialSelectionInfo: v } = s, { editor: O, setEditor: k } = En(), { inited: P } = h;
  function $(R) {
    l === "css" && R.languages.registerCompletionItemProvider("css", _n);
  }
  function _(R, y) {
    k(R);
    const g = R.getModel();
    if (g && (g.updateOptions({ insertSpaces: !1 }), R.onKeyUp(() => {
      var M;
      const p = (M = R.getPosition()) == null ? void 0 : M.lineNumber;
      if (p) {
        const F = g.getLineFirstNonWhitespaceColumn(p), A = g.getLineLength(p), Y = g.getLineContent(p);
        kn.test(Y) && R.executeEdits("edit-handler", [
          {
            range: new y.Range(
              p,
              0,
              p,
              A
            ),
            text: Y.substr(
              F - 1,
              A - F
            )
          }
        ]);
      }
    })), i === Mt.METHOD && tt(n)) {
      const p = new jn(R, !0);
      p.exclude(1, 1, 1, Number.POSITIVE_INFINITY), p.enable();
    }
  }
  return J(() => {
    if (!O)
      return;
    const { line: R, offset: y } = S || {};
    R && fn(O, R, y);
  }, [S, O]), J(() => {
    if (!O)
      return;
    const { selection: R } = v || {};
    R && cn(O, R);
  }, [v, O]), P ? /* @__PURE__ */ j.jsxs(j.Fragment, { children: [
    d ? /* @__PURE__ */ j.jsx(wn, { lspProps: h }) : null,
    /* @__PURE__ */ j.jsx(
      Dt,
      {
        options: {
          readOnly: !0,
          fontSize: 12,
          "semanticHighlighting.enabled": !0,
          ...f
        },
        path: V(r),
        value: n,
        theme: "fd-dark",
        onChange: (R) => u && u(R || ""),
        language: l,
        beforeMount: $,
        onMount: _,
        loading: /* @__PURE__ */ j.jsx(Xe, {}),
        ...b
      }
    )
  ] }) : /* @__PURE__ */ j.jsx(Xe, {});
};
export {
  wn as Alerts,
  Gn as CodeEditor,
  zn as CodeEditorProvider,
  qn as LSPProvider,
  it as _await,
  V as getFileSystemPath,
  Vn as getFunctionOffset,
  fn as jumpToLine,
  cn as jumpToSelection,
  En as useCodeEditor,
  Bn as useLSP
};
//# sourceMappingURL=index.es.js.map
