"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var overrides_exports = {};
__export(overrides_exports, {
  OverridesTab: () => OverridesTab
});
module.exports = __toCommonJS(overrides_exports);
var import_react = __toESM(require("react"));
var import_overrides = require("./../../lib/overrides.js");
var import_button = require("../components/button.js");
var import_theme = require("../theme.js");
const SCAN_PORT_START = 52e3;
const SCAN_PORT_END = 52005;
const FETCH_TIMEOUT_MS = 500;
const OVERRIDE_QUERY_KEY = "wix-ricos-override";
const STATIC_OVERRIDES_COOKIE = "wixStaticsVersions";
const STATIC_OVERRIDES_ARTIFACT_ID = "wix-ricos";
const JSDELIVR_PACKAGE_URL = "https://data.jsdelivr.com/v1/packages/npm/@wix/ricos";
const VERSION_CUTOFF = "10.93.0";
const VERSIONS_INITIAL_VISIBLE = 15;
const fetchRegistryWithTimeout = async (url, timeoutMs) => {
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
  try {
    const res = await fetch(url, { signal: controller.signal });
    if (res.ok) {
      return await res.json();
    }
  } catch {
  } finally {
    clearTimeout(timeoutId);
  }
  return null;
};
const probePort = async (port) => {
  const registry = await fetchRegistryWithTimeout(
    `https://localhost:${port}/local-servers`,
    FETCH_TIMEOUT_MS
  );
  if (!registry) {
    return null;
  }
  return Object.entries(registry).map(([portStr, info]) => ({
    port: Number(portStr),
    branch: info.branch,
    startedAt: info.startedAt
  }));
};
const discoverServers = async () => {
  const ports = [];
  for (let p = SCAN_PORT_START; p <= SCAN_PORT_END; p++) {
    ports.push(p);
  }
  const results = await Promise.all(ports.map(probePort));
  for (const servers of results) {
    if (servers && servers.length > 0) {
      return servers.sort((a, b) => a.port - b.port);
    }
  }
  return [];
};
const compareSemver = (a, b) => {
  const pa = a.split(".").map(Number);
  const pb = b.split(".").map(Number);
  for (let i = 0; i < 3; i++) {
    if (pa[i] !== pb[i]) {
      return pa[i] - pb[i];
    }
  }
  return 0;
};
const loadPublishedVersions = async () => {
  const res = await fetch(JSDELIVR_PACKAGE_URL);
  if (!res.ok) {
    throw new Error(`jsDelivr returned HTTP ${res.status}`);
  }
  const data = await res.json();
  const latest = data.tags?.latest;
  return (data.versions || []).map((v) => v.version).filter((v) => /^\d+\.\d+\.\d+$/.test(v)).filter((v) => compareSemver(v, VERSION_CUTOFF) >= 0).map((v) => ({ version: v, isLatest: v === latest }));
};
const buildOverrideQuery = (value) => `${OVERRIDE_QUERY_KEY}=${encodeURIComponent(value)}`;
const buildOverrideHref = (value) => {
  const url = new URL(window.location.href);
  url.searchParams.set(OVERRIDE_QUERY_KEY, value);
  return url.toString();
};
const OPEN_LINK_TITLE = "Open with this override (Shift/Cmd-click for new tab)";
const isLocalhostUrl = (value) => value.startsWith("http://localhost") || value.startsWith("https://localhost");
const portFromLocalhostUrl = (value) => {
  try {
    return Number(new URL(value).port) || null;
  } catch {
    return null;
  }
};
const formatTimestampAgo = (epoch) => {
  if (!epoch) {
    return "";
  }
  const diffSeconds = Math.floor((Date.now() - epoch) / 1e3);
  if (diffSeconds < 60) {
    return `${diffSeconds}s ago`;
  }
  const diffMinutes = Math.floor(diffSeconds / 60);
  if (diffMinutes < 60) {
    return `${diffMinutes}m ago`;
  }
  const diffHours = Math.floor(diffMinutes / 60);
  if (diffHours < 24) {
    return `${diffHours}h ago`;
  }
  return `${Math.floor(diffHours / 24)}d ago`;
};
const clearWixRicosFromStaticsCookie = () => {
  if (typeof document === "undefined") {
    return;
  }
  const raw = document.cookie.split("; ").find((c) => c.startsWith(`${STATIC_OVERRIDES_COOKIE}=`));
  if (!raw) {
    return;
  }
  const value = raw.slice(STATIC_OVERRIDES_COOKIE.length + 1);
  const remaining = value.split("|").filter((entry) => !entry.startsWith(`${STATIC_OVERRIDES_ARTIFACT_ID}#`)).join("|");
  const hostParts = window.location.hostname.split(".");
  const parentDomain = hostParts.length > 1 ? `.${hostParts.slice(-2).join(".")}` : void 0;
  const domains = [void 0, parentDomain];
  for (const domain of domains) {
    const domainAttr = domain ? `; domain=${domain}` : "";
    if (remaining) {
      document.cookie = `${STATIC_OVERRIDES_COOKIE}=${remaining}; path=/${domainAttr}`;
    } else {
      document.cookie = `${STATIC_OVERRIDES_COOKIE}=; path=/${domainAttr}; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
    }
  }
};
const copyToClipboard = async (text) => {
  try {
    await navigator.clipboard.writeText(text);
    return true;
  } catch {
    return false;
  }
};
const SECTION_TITLE_STYLE = {
  fontWeight: 600,
  marginBottom: 4
};
const SECTION_DESCRIPTION_STYLE = {
  fontSize: 12,
  color: import_theme.mainTheme.white60
};
const SECTION_HEADER_ROW_STYLE = {
  display: "flex",
  justifyContent: "space-between",
  alignItems: "flex-start",
  gap: 12
};
const TABLE_STYLE = {
  width: "100%",
  borderCollapse: "collapse",
  fontSize: 13
};
const TABLE_HEADER_ROW_STYLE = {
  textAlign: "left",
  color: import_theme.mainTheme.white60
};
const TABLE_HEADER_CELL_STYLE = {
  padding: "4px 8px",
  fontWeight: 500
};
const TABLE_ROW_STYLE = {
  borderTop: `1px solid ${import_theme.mainTheme.white10}`
};
const ACTIVE_BADGE_STYLE = {
  marginLeft: 6,
  fontSize: 10,
  padding: "1px 5px",
  borderRadius: 2,
  background: import_theme.jsonTreeTheme.base0B,
  color: import_theme.mainTheme.mainBg
};
const INPUT_STYLE = {
  background: "transparent",
  color: import_theme.mainTheme.text,
  padding: "4px 8px",
  border: `1px solid ${import_theme.mainTheme.white20}`,
  borderRadius: 2,
  fontSize: 13,
  fontFamily: "monospace"
};
const OverridesTab = () => {
  const [servers, setServers] = import_react.default.useState(null);
  const [scanning, setScanning] = import_react.default.useState(false);
  const [publishedVersions, setPublishedVersions] = import_react.default.useState(null);
  const [versionsLoading, setVersionsLoading] = import_react.default.useState(false);
  const [versionsError, setVersionsError] = import_react.default.useState(null);
  const [versionFilter, setVersionFilter] = import_react.default.useState("");
  const [showAllVersions, setShowAllVersions] = import_react.default.useState(false);
  const [copiedValue, setCopiedValue] = import_react.default.useState(null);
  const [manualInput, setManualInput] = import_react.default.useState("");
  const currentOverride = import_react.default.useMemo(() => (0, import_overrides.getOverrideValue)(), []);
  const runScan = import_react.default.useCallback(async () => {
    setScanning(true);
    const MIN_SCANNING_MS = 400;
    const minDelay = new Promise((resolve) => setTimeout(resolve, MIN_SCANNING_MS));
    try {
      const [results] = await Promise.all([discoverServers(), minDelay]);
      setServers(results);
    } finally {
      setScanning(false);
    }
  }, []);
  import_react.default.useEffect(() => {
    void runScan();
  }, [runScan]);
  const loadVersions = import_react.default.useCallback(async () => {
    setVersionsLoading(true);
    setVersionsError(null);
    try {
      setPublishedVersions(await loadPublishedVersions());
    } catch (e) {
      setVersionsError(e instanceof Error ? e.message : String(e));
    } finally {
      setVersionsLoading(false);
    }
  }, []);
  import_react.default.useEffect(() => {
    void loadVersions();
  }, [loadVersions]);
  const handleCopy = async (value) => {
    if (await copyToClipboard(buildOverrideQuery(value))) {
      setCopiedValue(value);
      setTimeout(() => setCopiedValue((prev) => prev === value ? null : prev), 1500);
    }
  };
  const handleApply = (value) => {
    const url = new URL(window.location.href);
    url.searchParams.set(OVERRIDE_QUERY_KEY, value);
    window.location.assign(url.toString());
  };
  const handleClearOverride = () => {
    const url = new URL(window.location.href);
    url.searchParams.delete(OVERRIDE_QUERY_KEY);
    clearWixRicosFromStaticsCookie();
    window.location.assign(url.toString());
  };
  const isServerActive = (port) => currentOverride !== null && isLocalhostUrl(currentOverride) && portFromLocalhostUrl(currentOverride) === port;
  const isVersionActive = (version) => currentOverride === version;
  const filteredVersions = (publishedVersions || []).filter(
    (v) => versionFilter === "" || v.version.includes(versionFilter)
  );
  const visibleVersions = showAllVersions ? filteredVersions : filteredVersions.slice(0, VERSIONS_INITIAL_VISIBLE);
  const trimmedManualInput = manualInput.trim();
  const isManualInputApplyable = trimmedManualInput.length > 0 && trimmedManualInput !== currentOverride;
  return /* @__PURE__ */ import_react.default.createElement("div", { style: { padding: "12px 16px", color: import_theme.mainTheme.text } }, /* @__PURE__ */ import_react.default.createElement("div", { style: SECTION_HEADER_ROW_STYLE }, /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("div", { style: SECTION_TITLE_STYLE }, "@wix/ricos overrides"), /* @__PURE__ */ import_react.default.createElement("div", { style: SECTION_DESCRIPTION_STYLE }, "Load a different ", /* @__PURE__ */ import_react.default.createElement("code", null, "@wix/ricos"), " build into this page via", " ", /* @__PURE__ */ import_react.default.createElement("code", null, OVERRIDE_QUERY_KEY), ". Pick a local dev server, a published version, or paste an arbitrary value."), /* @__PURE__ */ import_react.default.createElement("div", { style: { marginTop: 8, fontSize: 12, color: import_theme.mainTheme.white60 } }, "Current override:", " ", currentOverride ? /* @__PURE__ */ import_react.default.createElement("span", { style: { color: import_theme.jsonTreeTheme.base0B, fontFamily: "monospace" } }, currentOverride) : /* @__PURE__ */ import_react.default.createElement("span", null, "none"))), /* @__PURE__ */ import_react.default.createElement(import_button.Button, { onClick: handleClearOverride, disabled: !currentOverride }, "Clear override")), /* @__PURE__ */ import_react.default.createElement("div", { style: { marginTop: 24 } }, /* @__PURE__ */ import_react.default.createElement("div", { style: SECTION_HEADER_ROW_STYLE }, /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("div", { style: SECTION_TITLE_STYLE }, "Local dev servers"), /* @__PURE__ */ import_react.default.createElement("div", { style: SECTION_DESCRIPTION_STYLE }, "Running ", /* @__PURE__ */ import_react.default.createElement("code", null, "yarn workspace @wix/ricos watch"), " servers on", " ", /* @__PURE__ */ import_react.default.createElement("code", null, "https://localhost:", SCAN_PORT_START, "–", SCAN_PORT_END), ".")), /* @__PURE__ */ import_react.default.createElement(import_button.Button, { onClick: runScan, disabled: scanning }, scanning ? "Scanning…" : "Rescan")), /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      style: {
        marginTop: 12,
        opacity: scanning && servers !== null ? 0.4 : 1,
        transition: "opacity .15s"
      }
    },
    servers === null ? /* @__PURE__ */ import_react.default.createElement("div", { style: { color: import_theme.mainTheme.white60 } }, "Scanning…") : servers.length === 0 ? /* @__PURE__ */ import_react.default.createElement("div", { style: { color: import_theme.mainTheme.white60, fontSize: 12 } }, "No local servers found. Start one with", " ", /* @__PURE__ */ import_react.default.createElement("code", { style: { background: import_theme.mainTheme.white10, padding: "2px 4px", borderRadius: 2 } }, "yarn workspace @wix/ricos watch"), ", then visit", " ", /* @__PURE__ */ import_react.default.createElement(
      "a",
      {
        href: `https://localhost:${SCAN_PORT_START}/local-servers`,
        target: "_blank",
        rel: "noreferrer",
        style: { color: import_theme.jsonTreeTheme.base0D }
      },
      "https://localhost:",
      SCAN_PORT_START
    ), " ", "once to accept the self-signed certificate.") : /* @__PURE__ */ import_react.default.createElement("table", { style: TABLE_STYLE }, /* @__PURE__ */ import_react.default.createElement("thead", null, /* @__PURE__ */ import_react.default.createElement("tr", { style: TABLE_HEADER_ROW_STYLE }, /* @__PURE__ */ import_react.default.createElement("th", { style: TABLE_HEADER_CELL_STYLE }, "Port"), /* @__PURE__ */ import_react.default.createElement("th", { style: TABLE_HEADER_CELL_STYLE }, "Branch"), /* @__PURE__ */ import_react.default.createElement("th", { style: TABLE_HEADER_CELL_STYLE }, "Started"), /* @__PURE__ */ import_react.default.createElement("th", { style: TABLE_HEADER_CELL_STYLE }))), /* @__PURE__ */ import_react.default.createElement("tbody", null, servers.map((server) => {
      const overrideValue = `https://localhost:${server.port}`;
      const isCurrent = isServerActive(server.port);
      return /* @__PURE__ */ import_react.default.createElement("tr", { key: server.port, style: TABLE_ROW_STYLE }, /* @__PURE__ */ import_react.default.createElement("td", { style: { padding: "6px 8px", fontFamily: "monospace" } }, server.port, isCurrent && /* @__PURE__ */ import_react.default.createElement("span", { style: ACTIVE_BADGE_STYLE }, "active")), /* @__PURE__ */ import_react.default.createElement("td", { style: { padding: "6px 8px", fontFamily: "monospace" } }, server.branch || "unknown"), /* @__PURE__ */ import_react.default.createElement("td", { style: { padding: "6px 8px", color: import_theme.mainTheme.white60 } }, formatTimestampAgo(server.startedAt)), /* @__PURE__ */ import_react.default.createElement("td", { style: { padding: "6px 8px", textAlign: "right", whiteSpace: "nowrap" } }, /* @__PURE__ */ import_react.default.createElement(import_button.Button, { onClick: () => handleCopy(overrideValue) }, copiedValue === overrideValue ? "Copied" : "Copy"), /* @__PURE__ */ import_react.default.createElement(import_button.Button, { onClick: () => handleApply(overrideValue), disabled: isCurrent }, "Apply & reload"), /* @__PURE__ */ import_react.default.createElement(import_button.Button, { href: buildOverrideHref(overrideValue), title: OPEN_LINK_TITLE }, "↗")));
    })))
  )), /* @__PURE__ */ import_react.default.createElement("div", { style: { marginTop: 24 } }, /* @__PURE__ */ import_react.default.createElement("div", { style: SECTION_TITLE_STYLE }, "Custom override"), /* @__PURE__ */ import_react.default.createElement("div", { style: SECTION_DESCRIPTION_STYLE }, "Any semver (e.g. ", /* @__PURE__ */ import_react.default.createElement("code", null, "11.0.1"), "), CI fingerprint hash, or", " ", /* @__PURE__ */ import_react.default.createElement("code", null, "https://localhost:PORT"), " URL."), /* @__PURE__ */ import_react.default.createElement(
    "form",
    {
      onSubmit: (e) => {
        e.preventDefault();
        if (isManualInputApplyable) {
          handleApply(trimmedManualInput);
        }
      },
      style: { marginTop: 8, display: "flex", alignItems: "center", gap: 8 }
    },
    /* @__PURE__ */ import_react.default.createElement(
      "input",
      {
        type: "text",
        placeholder: "11.0.1 / hex hash / https://localhost:52000",
        value: manualInput,
        onChange: (e) => setManualInput(e.currentTarget.value),
        style: { ...INPUT_STYLE, flex: 1, minWidth: 240 }
      }
    ),
    /* @__PURE__ */ import_react.default.createElement(
      import_button.Button,
      {
        type: "button",
        onClick: () => handleCopy(trimmedManualInput),
        disabled: trimmedManualInput.length === 0
      },
      copiedValue === trimmedManualInput && trimmedManualInput ? "Copied" : "Copy"
    ),
    /* @__PURE__ */ import_react.default.createElement(import_button.Button, { type: "submit", disabled: !isManualInputApplyable }, "Apply & reload"),
    /* @__PURE__ */ import_react.default.createElement(
      import_button.Button,
      {
        href: isManualInputApplyable ? buildOverrideHref(trimmedManualInput) : "",
        disabled: !isManualInputApplyable,
        title: OPEN_LINK_TITLE
      },
      "↗"
    )
  )), /* @__PURE__ */ import_react.default.createElement("div", { style: { marginTop: 24 } }, /* @__PURE__ */ import_react.default.createElement("div", { style: SECTION_HEADER_ROW_STYLE }, /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("div", { style: SECTION_TITLE_STYLE }, "Published versions"), /* @__PURE__ */ import_react.default.createElement("div", { style: SECTION_DESCRIPTION_STYLE }, "From jsDelivr (", /* @__PURE__ */ import_react.default.createElement("code", null, "data.jsdelivr.com"), "), filtered to ", VERSION_CUTOFF, "+.")), /* @__PURE__ */ import_react.default.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8 } }, publishedVersions !== null && /* @__PURE__ */ import_react.default.createElement(
    "input",
    {
      type: "text",
      placeholder: "Filter…",
      value: versionFilter,
      onChange: (e) => {
        setVersionFilter(e.currentTarget.value);
        setShowAllVersions(false);
      },
      style: { ...INPUT_STYLE, width: 140 }
    }
  ), /* @__PURE__ */ import_react.default.createElement(import_button.Button, { onClick: loadVersions, disabled: versionsLoading }, versionsLoading ? "Loading…" : "Reload"))), /* @__PURE__ */ import_react.default.createElement("div", { style: { marginTop: 12 } }, versionsError ? /* @__PURE__ */ import_react.default.createElement("div", { style: { color: import_theme.jsonTreeTheme.base08, fontSize: 12 } }, "Failed to load versions: ", versionsError) : publishedVersions === null ? /* @__PURE__ */ import_react.default.createElement("div", { style: { color: import_theme.mainTheme.white60 } }, "Loading…") : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("table", { style: TABLE_STYLE }, /* @__PURE__ */ import_react.default.createElement("tbody", null, visibleVersions.map((entry) => {
    const isCurrent = isVersionActive(entry.version);
    return /* @__PURE__ */ import_react.default.createElement("tr", { key: entry.version, style: TABLE_ROW_STYLE }, /* @__PURE__ */ import_react.default.createElement("td", { style: { padding: "6px 8px", fontFamily: "monospace" } }, entry.version, entry.isLatest && /* @__PURE__ */ import_react.default.createElement(
      "span",
      {
        style: {
          ...ACTIVE_BADGE_STYLE,
          background: import_theme.mainTheme.white20,
          color: import_theme.mainTheme.text
        }
      },
      "latest"
    ), isCurrent && /* @__PURE__ */ import_react.default.createElement("span", { style: ACTIVE_BADGE_STYLE }, "active")), /* @__PURE__ */ import_react.default.createElement(
      "td",
      {
        style: { padding: "6px 8px", textAlign: "right", whiteSpace: "nowrap" }
      },
      /* @__PURE__ */ import_react.default.createElement(import_button.Button, { onClick: () => handleCopy(entry.version) }, copiedValue === entry.version ? "Copied" : "Copy"),
      /* @__PURE__ */ import_react.default.createElement(import_button.Button, { onClick: () => handleApply(entry.version), disabled: isCurrent }, "Apply & reload"),
      /* @__PURE__ */ import_react.default.createElement(import_button.Button, { href: buildOverrideHref(entry.version), title: OPEN_LINK_TITLE }, "↗")
    ));
  }))), !showAllVersions && filteredVersions.length > visibleVersions.length && /* @__PURE__ */ import_react.default.createElement("div", { style: { marginTop: 8, textAlign: "center" } }, /* @__PURE__ */ import_react.default.createElement(import_button.Button, { onClick: () => setShowAllVersions(true) }, "Show all (", filteredVersions.length - visibleVersions.length, " more)")), filteredVersions.length === 0 && /* @__PURE__ */ import_react.default.createElement("div", { style: { color: import_theme.mainTheme.white60, fontSize: 12, padding: "8px 0" } }, "No versions match the filter.")))));
};
//# sourceMappingURL=overrides.js.map
