import * as c from "monaco-editor";
import { parseJsonPointerPath as m } from "./json-pointer-path.js";
const d = "scalar-json-pointer", g = (r, o) => {
  if (r[o] !== '"')
    return !1;
  let t = 0;
  for (let e = o - 1; e >= 0 && r[e] === "\\"; e--)
    t++;
  return t % 2 === 0;
}, k = (r, o) => {
  let t = -1;
  for (let n = o; n >= 0; n--)
    if (g(r, n)) {
      t = n;
      break;
    }
  if (t === -1)
    return null;
  let e = -1;
  for (let n = Math.max(t + 1, o); n < r.length; n++)
    if (g(r, n)) {
      e = n;
      break;
    }
  return e === -1 || e <= t ? null : { left: t, right: e };
}, b = (r) => {
  c.languages.registerLinkProvider("json", {
    provideLinks(e) {
      const n = [], l = e.getLineCount();
      for (let s = 1; s <= l; s++) {
        const a = e.getLineContent(s);
        let u = 0;
        for (; ; ) {
          const f = a.indexOf("#/", u);
          if (f === -1)
            break;
          const i = k(a, f);
          if (!i) {
            u = f + 2;
            continue;
          }
          const p = a.slice(i.left + 1, i.right);
          if (!m(p)) {
            u = i.right + 1;
            continue;
          }
          const h = new c.Range(s, i.left + 2, s, i.right + 1);
          n.push({
            range: h,
            url: c.Uri.parse(`${d}:${encodeURIComponent(p)}`),
            tooltip: "Follow link"
          }), u = i.right + 1;
        }
      }
      return { links: n };
    }
  });
  const o = c.editor.registerLinkOpener({
    open(e) {
      if (e.scheme !== d)
        return !1;
      const n = (e.path || "").replace(/^\//, ""), l = decodeURIComponent(n);
      return l ? Promise.resolve(r(l)).then(() => !0) : !1;
    }
  });
  return { linkOpener: o, dispose: () => {
    o.dispose();
  } };
};
export {
  b as ensureJsonPointerLinkSupport
};
