// Prefixes a container's redirect Location with our proxy path so the browser stays on
// /containers/:id/proxy/:port/... instead of escaping to the container's bare URL.
export function rewriteProxyLocationHeader(location: string, proxyPrefix: string): string {
if (location.startsWith('//')) return location;
if (location.startsWith('/')) return `${proxyPrefix}${location}`;
return location;
}
// Rewrites root-relative URLs in a container's HTML response so assets (including Vite's
// HMR and @fs paths) load through the proxy prefix. Injects a tag for the rest.
export function rewriteProxyHtml(html: string, proxyPrefix: string): string {
const attrPattern = /\b(href|src|action|poster)=("|')\/(?!\/)/gi;
const srcsetPattern = /\bsrcset=("|')\/(?!\/)/gi;
const cssUrlPattern = /url\((["']?)\/(?!\/)/gi;
const viteClientPattern = /(["'`])\/(@vite\/client|@react-refresh|src\/|node_modules\/|@fs\/)/g;
const withBaseTag = html.includes(']*)>/i, `
`);
return withBaseTag
.replace(attrPattern, (_match, attr, quote) => `${attr}=${quote}${proxyPrefix}/`)
.replace(srcsetPattern, (_match, quote) => `srcset=${quote}${proxyPrefix}/`)
.replace(cssUrlPattern, (_match, quote) => `url(${quote}${proxyPrefix}/`)
.replace(viteClientPattern, (_match, quote, path) => `${quote}${proxyPrefix}/${path}`);
}