From 7d3fd226c56a132d63d9c9fbb329f974296d69d3 Mon Sep 17 00:00:00 2001 From: Charles Lyding <19598772+clydin@users.noreply.github.com> Date: Fri, 28 Jul 2023 13:09:58 -0400 Subject: [PATCH] fix(@angular-devkit/build-angular): support dev server proxy pathRewrite field in Vite-based server The development server proxy configuration file for Webpack supports a `pathRewrite` field that is not directly supported by the underlying Vite development server when using the application or esbuild- browser builders. To provide equivalent support, especially for JSON file-based proxy configurations, the `pathRewrite` field is now converted internally to a proxy `rewrite` function. --- .../builders/dev-server/load-proxy-config.ts | 41 +++++++++++++++++-- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/packages/angular_devkit/build_angular/src/builders/dev-server/load-proxy-config.ts b/packages/angular_devkit/build_angular/src/builders/dev-server/load-proxy-config.ts index 14f7c7140f4b..3f9206c2f9e4 100644 --- a/packages/angular_devkit/build_angular/src/builders/dev-server/load-proxy-config.ts +++ b/packages/angular_devkit/build_angular/src/builders/dev-server/load-proxy-config.ts @@ -95,9 +95,9 @@ export async function loadProxyConfiguration( * @param proxy A proxy configuration object. */ function normalizeProxyConfiguration( - proxy: Record | object[], -): Record { - let normalizedProxy: Record | undefined; + proxy: Record | object[], +): Record { + let normalizedProxy: Record | undefined; if (Array.isArray(proxy)) { // Construct an object-form proxy configuration from the array @@ -135,9 +135,44 @@ function normalizeProxyConfiguration( } } + // Replace `pathRewrite` field with a `rewrite` function + for (const proxyEntry of Object.values(normalizedProxy)) { + if ( + 'pathRewrite' in proxyEntry && + proxyEntry.pathRewrite && + typeof proxyEntry.pathRewrite === 'object' + ) { + // Preprocess path rewrite entries + const pathRewriteEntries: [RegExp, string][] = []; + for (const [pattern, value] of Object.entries( + proxyEntry.pathRewrite as Record, + )) { + pathRewriteEntries.push([new RegExp(pattern), value]); + } + + (proxyEntry as Record).rewrite = pathRewriter.bind( + undefined, + pathRewriteEntries, + ); + + delete proxyEntry.pathRewrite; + } + } + return normalizedProxy; } +function pathRewriter(pathRewriteEntries: [RegExp, string][], path: string): string { + for (const [pattern, value] of pathRewriteEntries) { + const updated = path.replace(pattern, value); + if (path !== updated) { + return updated; + } + } + + return path; +} + /** * Calculates the line and column for an error offset in the content of a JSON file. * @param location The offset error location from the beginning of the content.