UNPKG

vite-http2-proxy

Version:

An easy to use plugin to solve the problem that vite does not support http2Proxy.

76 lines (75 loc) 2.29 kB
import $ from "http2-proxy"; import k from "devcert"; const i = (o) => { throw new Error(o); }, E = () => { let o; return { name: "vite-http2-proxy", config: async (c, s) => { var e; if (s.command === "serve") try { o = (e = c.server) == null ? void 0 : e.proxy; const r = await k.certificateFor(["localhost"]); return { server: { https: { key: r.key, cert: r.cert }, proxy: void 0 } }; } catch (r) { console.error("[vite-http2-proxy]: error", r); } }, // https://cn.vitejs.dev/guide/api-plugin#vite-specific-hooks configureServer: ({ middlewares: c }) => { if (!o) { console.info("[vite-http2-proxy]: No proxy configuration found."); return; } for (const [s, e] of Object.entries(o)) { const r = typeof e == "string" ? { target: e } : e, { target: h, rewrite: a, headers: y, secure: d = !0, changeOrigin: b, cookieDomainRewrite: I } = r, m = new RegExp(s), t = typeof h == "string" ? new URL(h) : i(`Invalid target: ${s}`); t.pathname.endsWith("/") || (t.pathname += "/"); const l = /^https?:$/.test(t.protocol) ? t.protocol.slice(0, -1) : i(`Invalid protocol: ${t.href}`), v = t.port === "" ? { https: 443, http: 80 }[l] : /^\d+$/.test(t.port) ? Number(t.port) : i(`Invalid port: ${t.href}`); c.use((n, g, f) => { if (n.url && m.test(n.url)) { const x = ((a == null ? void 0 : a(n.url)) ?? n.url).replace(/^\/+/, ""), { pathname: w, search: R } = new URL(x, t); $.web( n, g, { protocol: l, port: v, hostname: t.hostname, path: w + R, onReq: async (p, u) => { u.headers = { ...u.headers, ...y }; }, rejectUnauthorized: d }, (p) => p && f(p) ); } else f(); }); } } }; }; export { E as default };