import { defineApp as O } from "@u-devtools/kit";
import { s as j } from "./context-DGN7u_Rt.js";
let S = [];
function h() {
  return Math.random().toString(36).slice(2);
}
function D(t) {
  const n = {};
  return t instanceof Headers ? t.forEach((s, e) => {
    n[e] = s;
  }) : typeof t == "string" && t.split(/[\r\n]+/).forEach((s) => {
    const e = s.split(": "), r = e.shift();
    r && (n[r] = e.join(": "));
  }), n;
}
function H(t, n) {
  return S.find((s) => {
    if (s.method !== "*" && s.method.toUpperCase() !== n.toUpperCase())
      return !1;
    try {
      return t.includes(s.urlMatcher) ? !0 : new RegExp(s.urlMatcher).test(t);
    } catch {
      return t.includes(s.urlMatcher);
    }
  });
}
const C = [
  "/__u-devtools",
  // RPC Bridge & Assets
  "/@vite/client",
  // Vite HMR Client
  "/@fs/",
  // Vite File System access
  "/@id/",
  // Vite Module IDs
  "node_modules/.vite",
  // Vite Pre-bundled deps
  ".hot-update.json",
  // HMR Updates
  "u-devtools-ws"
  // DevTools WebSocket
];
function g(t) {
  const n = t.toString();
  return !!(C.some((s) => n.includes(s)) || n.startsWith("data:") || n.startsWith("chrome-extension://") || n.includes("vite-hmr") || n.includes("localhost:24678"));
}
function q() {
  try {
    const t = new Error().stack || "";
    if (t.includes("node_modules/@apollo") || t.includes("apollo-client")) return "Apollo";
    if (t.includes("node_modules/@urql") || t.includes("urql")) return "Urql";
    if (t.includes("node_modules/graphql-request")) return "GraphQL Request";
    if (t.includes("node_modules/@tanstack") || t.includes("@tanstack/react-query")) return "TanStack Query";
    if (t.includes("node_modules/swr")) return "SWR";
    if (t.includes("node_modules/react-query")) return "React Query";
    if (t.includes("node_modules/axios") || t.includes("/axios/")) return "Axios";
    if (t.includes("node_modules/ky") || t.includes("/ky/")) return "Ky";
    if (t.includes("node_modules/superagent") || t.includes("/superagent/")) return "SuperAgent";
    if (t.includes("node_modules/got")) return "Got";
    if (t.includes("node_modules/node-fetch")) return "Node Fetch";
    if (t.includes("node_modules/socket.io") || t.includes("socket.io-client")) return "Socket.IO";
    if (t.includes("node_modules/ws") && !t.includes("node_modules/@u-devtools")) return "WebSocket (ws)";
    if (t.includes("node_modules/whatwg-fetch")) return "Fetch Polyfill";
    if (t.includes("@angular/common/http")) return "Angular HttpClient";
    if (t.includes("vue-axios")) return "Vue Axios";
    if (t.includes("jquery") && t.includes("ajax")) return "jQuery AJAX";
  } catch {
    return;
  }
}
function v(t, n, s) {
  const e = n["content-type"] || n["Content-Type"] || "";
  if (e.includes("application/grpc-web") || e.includes("application/grpc"))
    return { type: "grpc", operation: t.split("/").filter(Boolean).pop() || "Unknown" };
  if (s && typeof s == "object") {
    if ("query" in s) {
      let r = s.operationName;
      if (!r && typeof s.query == "string") {
        const d = s.query.match(/(query|mutation|subscription)\s+(\w+)/);
        if (d)
          r = d[2];
        else {
          const i = s.query.match(/\{\s*(\w+)/);
          i && (r = i[1]);
        }
      }
      return {
        type: "graphql",
        operation: r || "Anonymous Operation"
      };
    }
    if ("jsonrpc" in s && "method" in s)
      return {
        type: "json-rpc",
        operation: typeof s.method == "string" ? s.method : "Unknown Method"
      };
  }
  return { type: "http" };
}
const x = window.fetch, M = (t) => async (...n) => {
  const [s, e] = n, r = typeof s == "string" ? s : s instanceof Request ? s.url : String(s), d = e?.method || (s instanceof Request ? s.method : "GET"), i = Date.now(), o = h(), a = e?.headers ? D(new Headers(e.headers)) : {};
  let u = e?.body;
  if (typeof u == "string")
    try {
      u = JSON.parse(u);
    } catch {
    }
  const { type: c, operation: _ } = v(r, a, u), T = q();
  let w = d.toUpperCase();
  if (_) {
    const p = c === "graphql" ? "GQL" : c === "json-rpc" ? "RPC" : c === "grpc" ? "gRPC" : "";
    w = p ? `${p}: ${_}` : d.toUpperCase();
  }
  const l = H(r, d);
  if (l) {
    t.send("request-start", {
      id: o,
      url: r,
      method: w,
      type: "fetch",
      subType: c,
      clientLibrary: T,
      startTime: i,
      requestHeaders: a,
      requestBody: u,
      isMock: !0
      // Flag for UI
    }), l.responseDelay > 0 && await new Promise((m) => setTimeout(m, l.responseDelay));
    const p = {
      status: l.responseStatus,
      statusText: l.responseStatus === 200 ? "OK" : "Mocked",
      headers: new Headers(l.responseHeaders || { "Content-Type": "application/json" })
    }, f = new Response(l.responseBody, p);
    return t.send("request-end", {
      id: o,
      status: l.responseStatus,
      statusText: `(Mocked) ${l.responseStatus}`,
      endTime: Date.now(),
      duration: Date.now() - i
    }), t.send("request-details", {
      id: o,
      responseBody: l.responseType === "json" ? JSON.parse(l.responseBody || "{}") : l.responseBody,
      responseHeaders: l.responseHeaders
    }), f;
  }
  t.send("request-start", {
    id: o,
    url: r,
    method: w,
    type: "fetch",
    subType: c,
    clientLibrary: T,
    startTime: i,
    requestHeaders: a,
    requestBody: u,
    isMock: !1
    // Default
  });
  try {
    const p = await x(...n), f = p.headers.get("content-type") || "";
    let m;
    return f.includes("application/grpc-web") || f.includes("application/grpc") ? m = Promise.resolve("[gRPC-Web Binary Stream]") : f.includes("application/json") ? m = p.clone().json().catch(() => p.clone().text()) : f.includes("text/") || f.includes("xml") ? m = p.clone().text() : m = Promise.resolve("[Binary/Stream Data]"), m.then((b) => {
      t.send("request-details", {
        id: o,
        responseBody: b,
        responseHeaders: D(p.headers)
      });
    }), t.send("request-end", {
      id: o,
      status: p.status,
      statusText: p.statusText,
      endTime: Date.now(),
      duration: Date.now() - i
    }), p;
  } catch (p) {
    const f = p instanceof Error ? p.message : "Network Error";
    throw t.send("request-error", {
      id: o,
      error: f,
      endTime: Date.now(),
      duration: Date.now() - i
    }), p;
  }
}, y = window.XMLHttpRequest, k = y.prototype.open, B = y.prototype.setRequestHeader;
y.prototype.open = function(t, n, ...s) {
  const e = this;
  return e._udt_id = h(), e._udt_method = t, e._udt_url = n.toString(), e._udt_requestHeaders = {}, k.apply(this, [t, n, ...s]);
};
y.prototype.setRequestHeader = function(t, n) {
  const s = this;
  return !s._udt_ignored && s._udt_requestHeaders && (s._udt_requestHeaders[t] = n), B.apply(this, [t, n]);
};
const W = (t) => {
  const n = y.prototype.send;
  return y.prototype.send = function(s) {
    const e = this;
    if (e._udt_ignored)
      return n.apply(this, [s]);
    if (e._udt_start = Date.now(), typeof s == "string")
      try {
        e._udt_requestBody = JSON.parse(s);
      } catch {
        e._udt_requestBody = s;
      }
    else
      e._udt_requestBody = s;
    const r = e._udt_requestHeaders || {}, { type: d, operation: i } = e._udt_url ? v(e._udt_url, r, e._udt_requestBody) : { type: "http", operation: void 0 };
    q();
    let o = (e._udt_method || "GET").toUpperCase();
    i && (o = `${d === "graphql" ? "GQL" : d === "json-rpc" ? "RPC" : "gRPC"}: ${i}`);
    const a = e._udt_url ? H(e._udt_url, e._udt_method || "GET") : void 0;
    if (a && e._udt_id) {
      t.send("request-start", {
        id: e._udt_id,
        url: e._udt_url,
        method: o,
        type: "xhr",
        subType: d,
        startTime: e._udt_start,
        requestHeaders: e._udt_requestHeaders || {},
        requestBody: e._udt_requestBody,
        isMock: !0
      }), setTimeout(() => {
        Object.defineProperty(e, "status", {
          value: a.responseStatus,
          writable: !0,
          configurable: !0
        }), Object.defineProperty(e, "statusText", {
          value: "Mocked",
          writable: !0,
          configurable: !0
        }), Object.defineProperty(e, "readyState", {
          value: 4,
          writable: !0,
          configurable: !0
        }), Object.defineProperty(e, "responseText", {
          value: a.responseBody,
          writable: !0,
          configurable: !0
        }), Object.defineProperty(e, "response", {
          value: a.responseBody,
          writable: !0,
          configurable: !0
        });
        const u = Object.entries(a.responseHeaders || {}).map(([c, _]) => `${c}: ${_}`).join(`\r
`);
        e.getAllResponseHeaders = () => u, e.getResponseHeader = (c) => a.responseHeaders?.[c] || null, e.dispatchEvent(new Event("readystatechange")), e.dispatchEvent(new ProgressEvent("load")), e.dispatchEvent(new ProgressEvent("loadend")), t.send("request-end", {
          id: e._udt_id,
          status: a.responseStatus,
          statusText: "(Mocked)",
          endTime: Date.now(),
          duration: Date.now() - (e._udt_start || 0)
        }), t.send("request-details", {
          id: e._udt_id,
          responseBody: a.responseType === "json" ? JSON.parse(a.responseBody || "{}") : a.responseBody,
          responseHeaders: a.responseHeaders
        });
      }, a.responseDelay);
      return;
    }
    if (e._udt_id && e._udt_url) {
      const u = e._udt_requestHeaders || {}, { type: c, operation: _ } = v(e._udt_url, u, e._udt_requestBody), T = q();
      let w = (e._udt_method || "GET").toUpperCase();
      _ && (w = `${c === "graphql" ? "GQL" : c === "json-rpc" ? "RPC" : "gRPC"}: ${_}`), t.send("request-start", {
        id: e._udt_id,
        url: e._udt_url,
        method: w,
        type: "xhr",
        subType: c,
        clientLibrary: T,
        startTime: e._udt_start || Date.now(),
        requestHeaders: e._udt_requestHeaders || {},
        requestBody: e._udt_requestBody,
        isMock: !1
      });
    }
    return e.addEventListener("loadend", () => {
      if (!e._udt_id) return;
      let u = e.response;
      try {
        if (e.responseType === "" || e.responseType === "text")
          try {
            u = JSON.parse(e.responseText);
          } catch {
            u = e.responseText;
          }
      } catch {
      }
      t.send("request-details", {
        id: e._udt_id,
        responseBody: u,
        responseHeaders: D(e.getAllResponseHeaders())
      }), t.send("request-end", {
        id: e._udt_id,
        status: e.status,
        statusText: e.statusText,
        endTime: Date.now(),
        duration: Date.now() - (e._udt_start || 0)
      });
    }), e.addEventListener("error", () => {
      e._udt_id && t.send("request-error", {
        id: e._udt_id,
        error: "XHR Network Error",
        endTime: Date.now(),
        duration: Date.now() - (e._udt_start || 0)
      });
    }), n.apply(this, [s]);
  }, n;
}, E = navigator.sendBeacon, $ = (t) => (n, s) => {
  if (g(n))
    return E.call(navigator, n, s);
  const e = h(), r = Date.now(), d = n.toString();
  let i = s;
  if (typeof s == "string")
    try {
      i = JSON.parse(s);
    } catch {
    }
  const { type: o, operation: a } = v(d, {}, i), u = q();
  let c = "POST";
  a && (c = `${o === "graphql" ? "GQL" : o === "json-rpc" ? "RPC" : "gRPC"}: ${a}`), t.send("request-start", {
    id: e,
    url: d,
    method: c,
    type: "beacon",
    subType: o,
    clientLibrary: u,
    startTime: r,
    requestHeaders: {},
    requestBody: i
  });
  const _ = E.call(navigator, n, s);
  return _ ? t.send("request-end", {
    id: e,
    status: 200,
    statusText: "Queued",
    endTime: Date.now(),
    duration: 0
  }) : t.send("request-error", {
    id: e,
    error: "Beacon failed to queue",
    endTime: Date.now(),
    duration: 0
  }), _;
}, P = window.WebSocket, L = (t) => class extends P {
  constructor(s, e) {
    super(s, e), this._udt_id = h();
    const r = s.toString();
    if (this._udt_ignored = g(r) || r.includes("vite-hmr"), this._udt_ignored) return;
    const d = Date.now();
    t.send("ws-open", {
      id: this._udt_id,
      url: s.toString(),
      startTime: d,
      type: "websocket"
    });
    const i = this.send;
    this.send = (o) => (this._udt_ignored || t.send("ws-frame", {
      id: this._udt_id,
      frame: {
        id: h(),
        time: Date.now(),
        type: "send",
        data: typeof o == "object" && !(o instanceof ArrayBuffer) ? "[Binary Data]" : String(o)
      }
    }), i.call(this, o)), this.addEventListener("message", (o) => {
      this._udt_ignored || t.send("ws-frame", {
        id: this._udt_id,
        frame: {
          id: h(),
          time: Date.now(),
          type: "received",
          data: typeof o.data == "object" ? "[Binary Data]" : String(o.data)
        }
      });
    }), this.addEventListener("close", (o) => {
      this._udt_ignored || t.send("ws-close", {
        id: this._udt_id,
        endTime: Date.now(),
        code: o.code,
        reason: o.reason
      });
    }), this.addEventListener("error", () => {
      this._udt_ignored || t.send("ws-error", {
        id: this._udt_id,
        error: "WebSocket Error",
        endTime: Date.now()
      });
    });
  }
}, R = window.EventSource, N = (t) => class extends R {
  constructor(s, e) {
    super(s, e), this._udt_id = h();
    const r = s.toString();
    if (this._udt_ignored = g(r), this._udt_ignored) return;
    const d = Date.now();
    t.send("ws-open", {
      id: this._udt_id,
      url: r,
      startTime: d,
      type: "eventsource"
    }), this.addEventListener("message", (o) => {
      const a = o.type || "message", u = typeof o.data == "string" ? o.data : "[Binary Data]";
      t.send("ws-frame", {
        id: this._udt_id,
        frame: {
          id: h(),
          time: Date.now(),
          type: "received",
          data: a !== "message" ? `[${a}] ${u}` : u
        }
      });
    }), this.addEventListener("error", () => {
      t.send("ws-error", {
        id: this._udt_id,
        error: "EventSource Error (Reconnecting...)",
        endTime: Date.now()
      });
    });
    const i = this.close;
    this.close = () => {
      t.send("ws-close", {
        id: this._udt_id,
        endTime: Date.now(),
        reason: "Closed by client"
      }), i.call(this);
    };
  }
}, U = (t) => {
  if (!window.PerformanceObserver) return () => {
  };
  const n = new PerformanceObserver((s) => {
    s.getEntries().forEach((e) => {
      if (e.entryType === "resource") {
        const r = e;
        if (r.initiatorType === "xmlhttprequest" || r.initiatorType === "fetch" || r.initiatorType === "beacon" || g(r.name))
          return;
        const d = h();
        t.send("request-start", {
          id: d,
          url: r.name,
          method: "GET",
          // Resources are usually GET
          type: "resource",
          subType: "http",
          startTime: r.startTime + performance.timeOrigin,
          // Convert to Unix timestamp
          requestHeaders: {}
          // Headers unavailable via Performance API
        }), t.send("request-end", {
          id: d,
          status: 200,
          // Assume success if loaded (Performance API doesn't show status code)
          statusText: "OK",
          endTime: r.responseEnd + performance.timeOrigin,
          duration: r.duration
        }), r.transferSize > 0 && t.send("request-details", {
          id: d,
          responseBody: `[Resource Content]
Type: ${r.initiatorType}
Size: ${r.transferSize} bytes
Decoded: ${r.decodedBodySize} bytes
Duration: ${r.duration.toFixed(2)}ms`,
          responseHeaders: {}
        });
      }
    });
  });
  try {
    n.observe({ type: "resource", buffered: !0 });
  } catch {
    console.warn("[Network] PerformanceObserver not supported");
  }
  return () => n.disconnect();
}, A = (t) => {
  const n = window.WebTransport;
  return n ? class extends n {
    constructor(e, r) {
      if (super(e, r), this._udt_id = h(), this._udt_ignored = g(e), this._udt_ignored) return;
      const d = Date.now();
      t.send("ws-open", {
        id: this._udt_id,
        url: e,
        startTime: d,
        type: "webtransport"
      }), this.ready.then(() => {
      }).catch((i) => {
        this._udt_ignored || t.send("ws-error", {
          id: this._udt_id,
          error: `Connection Failed: ${i.message}`,
          endTime: Date.now()
        });
      }), this.closed.then(() => {
        this._udt_ignored || t.send("ws-close", {
          id: this._udt_id,
          endTime: Date.now(),
          reason: "Clean close"
        });
      }).catch((i) => {
        this._udt_ignored || t.send("ws-close", {
          id: this._udt_id,
          endTime: Date.now(),
          reason: `Closed with error: ${i.message}`
        });
      });
    }
  } : null;
}, X = O({
  component: void 0,
  setup({ bridge: t, onCleanup: n }) {
    const s = t;
    j({ bridge: s }), window.fetch = M(s);
    const e = W(s);
    navigator.sendBeacon = $(s), window.WebSocket = L(s), window.EventSource = N(s);
    let r;
    if (window.WebTransport) {
      r = window.WebTransport;
      const i = A(s);
      i && (window.WebTransport = i);
    }
    const d = U(s);
    s.on("update-mock-rules", (i) => {
      S = i.filter((o) => o.active), console.log("[U-DevTools] Mock rules updated:", S.length);
    }), s.on("replay", async (i) => {
      const { url: o, method: a, headers: u, body: c } = i;
      console.log("[U-DevTools] Replaying request:", a, o);
      try {
        await x(o, {
          method: a,
          headers: u || {},
          body: c ? JSON.stringify(c) : void 0
        });
      } catch (_) {
        console.error("[U-DevTools] Replay failed", _);
      }
    }), n(() => {
      console.log("[Network] Cleaning up patches"), window.fetch = x, y.prototype.open = k, y.prototype.send = e, y.prototype.setRequestHeader = B, navigator.sendBeacon = E, window.WebSocket = P, window.EventSource = R, r && (window.WebTransport = r), d();
    });
  }
});
export {
  X as default
};
