Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(@angular-devkit/build-angular): ensure all build resources are served in esbuild dev server #24975

Merged
merged 2 commits into from Apr 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Expand Up @@ -172,6 +172,7 @@
"loader-utils": "3.2.1",
"magic-string": "0.30.0",
"mini-css-extract-plugin": "2.7.5",
"mrmime": "1.0.1",
"ng-packagr": "16.0.0-next.2",
"node-fetch": "^2.2.0",
"npm": "^8.11.0",
Expand Down
1 change: 1 addition & 0 deletions packages/angular_devkit/build_angular/BUILD.bazel
Expand Up @@ -157,6 +157,7 @@ ts_library(
"@npm//loader-utils",
"@npm//magic-string",
"@npm//mini-css-extract-plugin",
"@npm//mrmime",
"@npm//ng-packagr",
"@npm//open",
"@npm//ora",
Expand Down
1 change: 1 addition & 0 deletions packages/angular_devkit/build_angular/package.json
Expand Up @@ -45,6 +45,7 @@
"loader-utils": "3.2.1",
"magic-string": "0.30.0",
"mini-css-extract-plugin": "2.7.5",
"mrmime": "1.0.1",
"open": "8.4.2",
"ora": "5.4.1",
"parse5-html-rewriting-stream": "7.0.0",
Expand Down
Expand Up @@ -8,6 +8,7 @@

import type { BuilderContext } from '@angular-devkit/architect';
import type { json } from '@angular-devkit/core';
import { lookup as lookupMimeType } from 'mrmime';
import assert from 'node:assert';
import { BinaryLike, createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
Expand All @@ -21,7 +22,7 @@ import type { NormalizedDevServerOptions } from './options';
import type { DevServerBuilderOutput } from './webpack-server';

interface OutputFileRecord {
text: string;
contents: Uint8Array;
size: number;
hash?: Buffer;
updated: boolean;
Expand Down Expand Up @@ -69,7 +70,7 @@ export async function* serveWithVite(
// Skip analysis of sourcemaps
if (filePath.endsWith('.map')) {
outputFiles.set(filePath, {
text: file.text,
contents: file.contents,
size: file.contents.byteLength,
updated: false,
});
Expand All @@ -82,7 +83,7 @@ export async function* serveWithVite(
if (existingRecord && existingRecord.size === file.contents.byteLength) {
// Only hash existing file when needed
if (existingRecord.hash === undefined) {
existingRecord.hash = hashContent(existingRecord.text);
existingRecord.hash = hashContent(existingRecord.contents);
}

// Compare against latest result output
Expand All @@ -95,7 +96,7 @@ export async function* serveWithVite(
}

outputFiles.set(filePath, {
text: file.text,
contents: file.contents,
size: file.contents.byteLength,
hash: fileHash,
updated: true,
Expand Down Expand Up @@ -213,25 +214,59 @@ async function setupServer(
},
load(id) {
const [file] = id.split('?', 1);
const code = outputFiles.get(file)?.text;
const code = outputFiles.get(file)?.contents;
const map = outputFiles.get(file + '.map')?.contents;

return (
code && {
code,
map: outputFiles.get(file + '.map')?.text,
code: code && Buffer.from(code).toString('utf-8'),
map: map && Buffer.from(map).toString('utf-8'),
}
);
},
configureServer(server) {
// Assets get handled first
// Assets and resources get handled first
server.middlewares.use(function angularAssetsMiddleware(req, res, next) {
if (req.url) {
// Rewrite all build assets to a vite raw fs URL
const assetSource = assets.get(req.url);
if (assetSource !== undefined) {
req.url = `/@fs/${assetSource}`;
if (req.url === undefined || res.writableEnded) {
return;
}

// Parse the incoming request.
// The base of the URL is unused but required to parse the URL.
const parsedUrl = new URL(req.url, 'http://localhost');
const extension = path.extname(parsedUrl.pathname);

// Rewrite all build assets to a vite raw fs URL
const assetSourcePath = assets.get(parsedUrl.pathname);
if (assetSourcePath !== undefined) {
req.url = `/@fs/${assetSourcePath}`;
next();

return;
}

// Resource files are handled directly.
// Global stylesheets (CSS files) are currently considered resources to workaround
// dev server sourcemap issues with stylesheets.
if (extension !== '.js' && extension !== '.html') {
const outputFile = outputFiles.get(parsedUrl.pathname);
if (outputFile) {
const mimeType = lookupMimeType(extension);
if (mimeType) {
res.setHeader('Content-Type', mimeType);
}
res.setHeader('Cache-Control', 'no-cache');
if (serverOptions.headers) {
Object.entries(serverOptions.headers).forEach(([name, value]) =>
res.setHeader(name, value),
);
}
res.end(outputFile.contents);

return;
}
}

next();
});

Expand All @@ -240,10 +275,14 @@ async function setupServer(
return () =>
server.middlewares.use(function angularIndexMiddleware(req, res, next) {
if (req.url === '/' || req.url === `/index.html`) {
const rawHtml = outputFiles.get('/index.html')?.text;
const rawHtml = outputFiles.get('/index.html')?.contents;
if (rawHtml) {
server
.transformIndexHtml(req.url, rawHtml, req.originalUrl)
.transformIndexHtml(
req.url,
Buffer.from(rawHtml).toString('utf-8'),
req.originalUrl,
)
.then((processedHtml) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('Cache-Control', 'no-cache');
Expand Down
Expand Up @@ -67,6 +67,8 @@ export function normalizeAssetPatterns(
const output = path.relative(resolvedSourceRoot, path.resolve(workspaceRoot, input));

assetPattern = { glob, input, output };
} else {
assetPattern.output = path.join('.', assetPattern.output);
}

if (assetPattern.output.startsWith('..')) {
Expand Down
5 changes: 5 additions & 0 deletions yarn.lock
Expand Up @@ -8617,6 +8617,11 @@ mkdirp@^0.5.1, mkdirp@^0.5.5, mkdirp@~0.5.1:
dependencies:
minimist "^1.2.6"

mrmime@1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/mrmime/-/mrmime-1.0.1.tgz#5f90c825fad4bdd41dc914eff5d1a8cfdaf24f27"
integrity sha512-hzzEagAgDyoU1Q6yg5uI+AorQgdvMCur3FcKf7NhMKWsaYg+RnbTyHRa/9IlLF9rf455MOCtcqqrQQ83pPP7Uw==

ms@2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"
Expand Down