76 lines
2.4 KiB
TypeScript
76 lines
2.4 KiB
TypeScript
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
import type { ClientRequest, IncomingMessage as ProxyIncomingMessage } from "node:http";
|
|
import type { ProxyOptions } from "vite";
|
|
import { MENU_SITE_ORIGIN, isMenuSlugProxyPath, stripMenuPreviewCacheParam, toMenuSitePath } from "./src/config/menuPreview";
|
|
|
|
const stripFrameHeaders = (_proxyRes: ProxyIncomingMessage, _req: IncomingMessage, res: ServerResponse) => {
|
|
res.removeHeader("x-frame-options");
|
|
res.removeHeader("content-security-policy");
|
|
};
|
|
|
|
const stripPreviewPageHeaders = (_proxyRes: ProxyIncomingMessage, _req: IncomingMessage, res: ServerResponse) => {
|
|
stripFrameHeaders(_proxyRes, _req, res);
|
|
res.removeHeader("cache-control");
|
|
res.removeHeader("etag");
|
|
res.removeHeader("last-modified");
|
|
res.setHeader("cache-control", "no-store, no-cache, must-revalidate");
|
|
res.setHeader("pragma", "no-cache");
|
|
res.setHeader("expires", "0");
|
|
};
|
|
|
|
const menuAssetProxy = (): ProxyOptions => ({
|
|
target: MENU_SITE_ORIGIN,
|
|
changeOrigin: true,
|
|
secure: true,
|
|
configure: (proxy) => {
|
|
proxy.on("proxyRes", stripFrameHeaders);
|
|
},
|
|
});
|
|
|
|
export const createMenuPreviewProxy = (): Record<string, ProxyOptions> => ({
|
|
"/assets/fonts": menuAssetProxy(),
|
|
"/assets/images": menuAssetProxy(),
|
|
"/_next": menuAssetProxy(),
|
|
"/icons": menuAssetProxy(),
|
|
});
|
|
|
|
export const shouldProxyMenuSlugRequest = (url: string | undefined) => {
|
|
if (!url) return false;
|
|
|
|
const pathname = url.split("?")[0] ?? "";
|
|
if (pathname.startsWith("/@") || pathname.startsWith("/src/") || pathname.startsWith("/node_modules/")) {
|
|
return false;
|
|
}
|
|
|
|
if (
|
|
pathname.startsWith("/assets/fonts/") ||
|
|
pathname.startsWith("/assets/images/") ||
|
|
pathname.startsWith("/_next/") ||
|
|
pathname.startsWith("/icons/")
|
|
) {
|
|
return false;
|
|
}
|
|
|
|
if (pathname.startsWith("/assets/")) {
|
|
return false;
|
|
}
|
|
|
|
return isMenuSlugProxyPath(pathname);
|
|
};
|
|
|
|
export const getMenuSiteTargetUrl = (url: string) => {
|
|
const [pathname, search = ""] = url.split("?");
|
|
const menuPath = toMenuSitePath(pathname ?? "");
|
|
if (!menuPath) return null;
|
|
return `${MENU_SITE_ORIGIN}${menuPath}${stripMenuPreviewCacheParam(search)}`;
|
|
};
|
|
|
|
export const createMenuSlugProxyAgent = () => ({
|
|
configure: (proxy: { on: (event: string, handler: (...args: unknown[]) => void) => void }) => {
|
|
proxy.on("proxyReq", (proxyReq: ClientRequest) => {
|
|
proxyReq.removeHeader("origin");
|
|
});
|
|
proxy.on("proxyRes", stripPreviewPageHeaders);
|
|
},
|
|
});
|