import { createWorkspaceStore as P, createActiveEntitiesStore as w } from "@scalar/api-client/store";
import { measure as f } from "@scalar/helpers/testing/measure";
import { normalize as y, upgrade as O, dereference as V } from "@scalar/openapi-parser";
import { apiReferenceConfigurationSchema as D } from "@scalar/types/api-reference";
import { computed as l, toValue as t, ref as d, watch as F } from "vue";
import { useDocumentFetcher as I } from "./useDocumentFetcher.js";
function C({
  originalDocument: i,
  dereferencedDocument: n,
  configuration: s
}) {
  const { originalDocument: h } = I({
    configuration: s
  }), u = l(() => i ? t(i) : t(h)), a = d(""), g = l(() => n ? t(n) : t(m)), m = d({
    openapi: "3.1.0",
    info: {
      title: "",
      version: ""
    },
    paths: {}
  });
  F(
    () => t(u),
    async (c) => {
      if (!c)
        return;
      const e = y(c);
      if (e === void 0) {
        console.error("Failed to parse the OpenAPI document:", c);
        return;
      }
      if (a.value = typeof e == "object" && (e.openapi || e.swagger) || "", n)
        return;
      const v = !a.value.startsWith("3.1") ? (
        // Upgrade needed
        f("upgrade", () => {
          const { specification: o } = O(e);
          return o;
        })
      ) : (
        // Skip the upgrade
        e
      ), A = await f("dereference", async () => {
        const { schema: o, errors: r } = await V(v);
        return r != null && r.length && console.warn(
          `Please open an issue on https://github.com/scalar/scalar
`,
          `Scalar OpenAPI Parser Warning:
`,
          r
        ), o === void 0 && console.error("Failed to dereference the OpenAPI document", r), o;
      });
      m.value = A;
    },
    { immediate: !0 }
  );
  const p = P({
    useLocalStorage: !1,
    ...t(s) ?? D.parse({})
  }), S = w(p);
  return {
    originalDocument: u,
    originalOpenApiVersion: a,
    dereferencedDocument: g,
    workspaceStore: p,
    activeEntitiesStore: S
  };
}
export {
  C as useDocumentSource
};
