Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 20 additions & 1 deletion src/builders/build/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ import {
} from "./i18n.js";
import { updateScriptTags } from "./update-index-html.js";
import { createInternalAngularBuilder } from "./internal-angular-builder.js";
import { appendFederationLicenses, LICENSES_FILE } from "./federation-licenses.js";

const originalWrite = process.stderr.write.bind(process.stderr);

Expand Down Expand Up @@ -258,6 +259,16 @@ export async function* runBuilder(

const cachePath = resolveCachePath(context.workspaceRoot, nfBuilderOptions.cachePath);

// Angular's 3rdpartylicenses.txt only covers its own bundles, so ours are appended to it.
// A cache hit runs no esbuild and leaves no metafile, so those builds skip the cache.
const extractFederationLicenses = !runViteServer && !!ngBuilderOptions.extractLicenses;
const cacheExternalArtifacts =
nfBuilderOptions.cacheExternalArtifacts !== false && !extractFederationLicenses;

if (extractFederationLicenses && nfBuilderOptions.cacheExternalArtifacts !== false) {
logger.info("Bundling the shared externals without the cache to extract their licenses.");
}

const normalized = await normalizeFederationOptions(
{
projectName: nfBuilderOptions.projectName,
Expand All @@ -275,7 +286,7 @@ export async function* runBuilder(
dev: !!nfBuilderOptions.dev,
entryPoints,
buildNotifications: nfBuilderOptions.buildNotifications,
cacheExternalArtifacts: nfBuilderOptions.cacheExternalArtifacts !== false,
cacheExternalArtifacts,
},
createFederationCache(cachePath, new SourceFileCache(cachePath)),
);
Expand Down Expand Up @@ -727,6 +738,14 @@ export async function* runBuilder(
continue;
}

if (extractFederationLicenses) {
await appendFederationLicenses(
path.resolve(context.workspaceRoot, outputOptions.base, LICENSES_FILE),
adapter.metafiles(),
context.workspaceRoot,
);
}

// The initial output's federation artifacts were already built above; only
// rebuild on subsequent outputs, and only in watch mode.
if (first || !watch) {
Expand Down
109 changes: 109 additions & 0 deletions src/builders/build/federation-licenses.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import type { Metafile } from "esbuild";

import { appendFederationLicenses, LICENSES_FILE } from "./federation-licenses.js";
import {
EXTRACTION_FILE_SEPARATOR,
extractLicenses,
} from "../../tools/esbuild/license-extractor.js";

let ws: string;
let licensesFile: string;

function addPackage(name: string, license: string): void {
const dir = path.join(ws, "node_modules", name);
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, "package.json"), JSON.stringify({ name, version: "1.0.0", license }));
fs.writeFileSync(path.join(dir, "LICENSE"), `${name} license text\n`);
fs.writeFileSync(path.join(dir, "index.js"), "");
}

function bundleOf(...packages: string[]): Metafile {
return {
inputs: {},
outputs: {
"out/bundle.js": {
bytes: 1,
inputs: Object.fromEntries(
packages.map((name) => [`node_modules/${name}/index.js`, { bytesInOutput: 1 }]),
),
imports: [],
exports: [],
},
},
};
}

function packagesIn(licenses: string): string[] {
return [...licenses.matchAll(/^Package: (.+)$/gm)].map((match) => match[1]!);
}

beforeEach(() => {
ws = fs.mkdtempSync(path.join(os.tmpdir(), "nf-federation-licenses-"));
licensesFile = path.join(ws, "dist", LICENSES_FILE);
fs.mkdirSync(path.dirname(licensesFile));
addPackage("zone.js", "MIT");
addPackage("rxjs", "Apache-2.0");
addPackage("@ngrx/store", "MIT");
});

afterEach(() => {
fs.rmSync(ws, { recursive: true, force: true });
});

describe("appendFederationLicenses", () => {
it("appends the packages of the federation bundles after Angular's own entries", async () => {
// What Angular writes for an app build that bundled only zone.js.
const angular = await extractLicenses([bundleOf("zone.js")], ws);
fs.writeFileSync(licensesFile, angular);

await appendFederationLicenses(licensesFile, [bundleOf("rxjs", "zone.js"), bundleOf("@ngrx/store")], ws);

const licenses = fs.readFileSync(licensesFile, "utf-8");
expect(licenses.startsWith(angular)).toBe(true);
expect(packagesIn(licenses)).toEqual(["zone.js", "rxjs", "@ngrx/store"]);
expect(licenses).toContain("rxjs license text\n");
expect(licenses.endsWith(EXTRACTION_FILE_SEPARATOR)).toBe(true);
});

it("matches what Angular writes when it bundles every package itself", async () => {
fs.writeFileSync(licensesFile, await extractLicenses([bundleOf("zone.js")], ws));

await appendFederationLicenses(licensesFile, [bundleOf("rxjs", "@ngrx/store")], ws);

expect(fs.readFileSync(licensesFile, "utf-8")).toBe(
await extractLicenses([bundleOf("zone.js"), bundleOf("rxjs", "@ngrx/store")], ws),
);
});

// A watch rebuild appends to a file Angular may not have rewritten.
it("adds nothing on a second run", async () => {
fs.writeFileSync(licensesFile, await extractLicenses([bundleOf("zone.js")], ws));
await appendFederationLicenses(licensesFile, [bundleOf("rxjs")], ws);
const once = fs.readFileSync(licensesFile, "utf-8");

await appendFederationLicenses(licensesFile, [bundleOf("rxjs")], ws);

expect(fs.readFileSync(licensesFile, "utf-8")).toBe(once);
});

it("leaves the file untouched when Angular already lists every package", async () => {
const angular = await extractLicenses([bundleOf("zone.js", "rxjs")], ws);
fs.writeFileSync(licensesFile, angular);
const writeFile = vi.spyOn(fs.promises, "writeFile");

await appendFederationLicenses(licensesFile, [bundleOf("rxjs")], ws);

expect(writeFile).not.toHaveBeenCalled();
expect(fs.readFileSync(licensesFile, "utf-8")).toBe(angular);
writeFile.mockRestore();
});

it("writes nothing when Angular wrote no licenses file", async () => {
await appendFederationLicenses(licensesFile, [bundleOf("rxjs")], ws);

expect(fs.existsSync(licensesFile)).toBe(false);
});
});
40 changes: 40 additions & 0 deletions src/builders/build/federation-licenses.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import * as fs from "fs";
import type { Metafile } from "esbuild";

import {
EXTRACTION_FILE_SEPARATOR,
extractLicenses,
} from "../../tools/esbuild/license-extractor.js";

export const LICENSES_FILE = "3rdpartylicenses.txt";

export async function appendFederationLicenses(
licensesFile: string,
metafiles: Metafile[],
workspaceRoot: string,
): Promise<void> {
let written: string;
try {
written = await fs.promises.readFile(licensesFile, "utf-8");
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
throw error;
}

// Both files come from the same extractor, so a package Angular listed has the same entry.
const listed = new Set(entries(written));
const missing = entries(await extractLicenses(metafiles, workspaceRoot)).filter(
(entry) => !listed.has(entry),
);

if (missing.length > 0) {
await fs.promises.writeFile(
licensesFile,
written + missing.map((entry) => entry + EXTRACTION_FILE_SEPARATOR).join(""),
);
}
}

function entries(licenses: string): string[] {
return licenses.split(EXTRACTION_FILE_SEPARATOR).slice(1, -1);
}
2 changes: 1 addition & 1 deletion src/builders/build/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
"cacheExternalArtifacts": {
"type": "boolean",
"default": true,
"description": "Will cache the shared externals so they can be re-used between builds",
"description": "Will cache the shared externals so they can be re-used between builds. Builds that extract licenses (the Angular target's `extractLicenses`, on by default in production) bundle the shared externals without the cache, so 3rdpartylicenses.txt can list their packages.",
"alias": "cache"
},
"cachePath": {
Expand Down
42 changes: 42 additions & 0 deletions src/tools/esbuild/angular-esbuild-adapter.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,48 @@ describe('createAngularBuildAdapter', () => {
]);
});

// Shared bundles only gained a metafile for 3rdpartylicenses.txt; core keeps matching them by name.
it('does not set entry on shared bundles', async () => {
vi.mocked(normalizeContextOptions).mockReturnValue(
normalizedWith({ isMappingOrExposed: false }) as never
);
const ctx = makeCtx();
ctx.rebuild.mockResolvedValue({ outputFiles: [], metafile: { inputs: {}, outputs: {} } });
vi.mocked(createNodeModulesEsbuildContext).mockResolvedValue({
ctx,
pluginDisposed: Promise.resolve(),
} as never);
const adapter = await createAngularBuildAdapter(ngBuilderOptions, context);
await adapter.setup('browser-shared', {} as never);

await adapter.build('browser-shared');

expect(entriesByOutputName).toHaveBeenCalledWith(undefined, expect.anything(), '/ws');
});

it('keeps the latest metafile of each bundle, ordered by bundle name', async () => {
const [first, second, rebuilt] = [1, 2, 3].map(n => ({ inputs: {}, outputs: {}, n }));
const ctx = makeCtx();
ctx.rebuild
.mockResolvedValueOnce({ outputFiles: [], metafile: first })
.mockResolvedValueOnce({ outputFiles: [], metafile: second })
.mockResolvedValueOnce({ outputFiles: [], metafile: rebuilt });
vi.mocked(createAngularEsbuildContext).mockResolvedValue({
ctx,
pluginDisposed: Promise.resolve(),
} as never);
const adapter = await createAngularBuildAdapter(ngBuilderOptions, context);
await adapter.setup('remote-b', {} as never);
await adapter.setup('remote-a', {} as never);

await adapter.build('remote-b');
await adapter.build('remote-a');
await adapter.build('remote-b');
await adapter.disposeFederationContexts();

expect(adapter.metafiles()).toEqual([second, rebuilt]);
});

// #181: writing outFile.text decoded binary assets as UTF-8, replacing invalid bytes with U+FFFD.
it('writes binary outputs byte for byte', async () => {
const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0xff, 0xfe, 0x00, 0x80]);
Expand Down
14 changes: 11 additions & 3 deletions src/tools/esbuild/angular-esbuild-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,8 @@ function writeOutputs(
export interface AngularBuildAdapter extends NFBuildAdapter {
// Disposes every mapping and exposed context, leaving esbuild running for the app build.
disposeFederationContexts(): Promise<void>;
// The latest metafile of each bundle built so far, ordered by bundle name.
metafiles(): esbuild.Metafile[];
}

export async function createAngularBuildAdapter(
Expand All @@ -63,6 +65,7 @@ export async function createAngularBuildAdapter(
const sharedBundleSettings = await resolveSharedBundleSettings(ngBuilderOptions, context);
const externalsCacheKey = createExternalsCacheKey(sharedBundleSettings);
const bundleContextCache = new Map<string, EsbuildContextResult>();
const metafilesByBundle = new Map<string, esbuild.Metafile>();

const disposeWhere = async (
matches: (entry: EsbuildContextResult, name: string) => boolean
Expand Down Expand Up @@ -142,9 +145,11 @@ export async function createAngularBuildAdapter(
bundleContext.cache.bundlerCache.invalidate(new Set(opts.modifiedFiles));
}
const result = await bundleContext.ctx.rebuild();
// Without `entry`, core matches hashed entries by file name (core#193).
if (result.metafile) metafilesByBundle.set(name, result.metafile);
// Without `entry`, core matches hashed entries by file name (core#193). Shared bundles
// aren't hashed and keep that matching; their metafile is only there for the licenses.
const entryByOutputName = entriesByOutputName(
result.metafile,
bundleContext.isMappingOrExposed ? result.metafile : undefined,
bundleContext.entryPoints,
context.workspaceRoot
);
Expand All @@ -158,5 +163,8 @@ export async function createAngularBuildAdapter(
}
};

return { externalsCacheKey, setup, build, dispose, disposeFederationContexts };
const metafiles = () =>
[...metafilesByBundle.keys()].sort().map(name => metafilesByBundle.get(name)!);

return { externalsCacheKey, setup, build, dispose, disposeFederationContexts, metafiles };
}
87 changes: 87 additions & 0 deletions src/tools/esbuild/license-extractor.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
import * as fs from 'fs';
import { createRequire } from 'module';
import * as os from 'os';
import * as path from 'path';
import type { Metafile } from 'esbuild';

import { EXTRACTION_FILE_SEPARATOR, extractLicenses } from './license-extractor.js';

// Angular's original, loaded by absolute file path because the exports map blocks the
// `@angular/build/src/...` specifier (#153). Test-only: used as the reference implementation.
const require = createRequire(import.meta.url);
const angularBuildRoot = path.dirname(require.resolve('@angular/build/package.json'));
const angular = require(path.join(angularBuildRoot, 'src/tools/esbuild/license-extractor.js')) as {
extractLicenses: (metafiles: Metafile[], rootDirectory: string) => Promise<string>;
};

let ws: string;

function write(rel: string, content: string): void {
const file = path.join(ws, rel);
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, content);
}

function metafile(inputs: Record<string, number>): Metafile {
return {
inputs: {},
outputs: {
'out/bundle.js': {
bytes: 1,
inputs: Object.fromEntries(
Object.entries(inputs).map(([input, bytesInOutput]) => [input, { bytesInOutput }])
),
imports: [],
exports: [],
},
},
};
}

beforeEach(() => {
ws = fs.mkdtempSync(path.join(os.tmpdir(), 'nf-license-extractor-'));
write('node_modules/mit-pkg/package.json', JSON.stringify({ name: 'mit-pkg', version: '1.0.0', license: 'MIT' }));
write('node_modules/mit-pkg/LICENSE', 'MIT text\n');
write('node_modules/mit-pkg/index.js', '');
write(
'node_modules/@scope/custom/package.json',
JSON.stringify({ name: '@scope/custom', version: '2.0.0', license: 'SEE LICENSE IN terms.txt' })
);
write('node_modules/@scope/custom/terms.txt', 'Custom terms\n');
write('node_modules/@scope/custom/dist/index.js', '');
write('node_modules/no-file/package.json', JSON.stringify({ name: 'no-file', version: '3.0.0', license: 'ISC' }));
write('node_modules/no-file/index.js', '');
write('node_modules/shaken/package.json', JSON.stringify({ name: 'shaken', version: '4.0.0', license: 'MIT' }));
write('node_modules/shaken/index.js', '');
});

afterEach(() => {
fs.rmSync(ws, { recursive: true, force: true });
});

describe('extractLicenses', () => {
const metafiles = () => [
metafile({
'src/app.ts': 10,
'node_modules/mit-pkg/index.js': 10,
'node_modules/@scope/custom/dist/index.js': 10,
'node_modules/no-file/index.js': 10,
'node_modules/shaken/index.js': 0,
}),
metafile({ 'node_modules/mit-pkg/index.js': 5 }),
];

it('produces the same file as @angular/build', async () => {
expect(await extractLicenses(metafiles(), ws)).toBe(await angular.extractLicenses(metafiles(), ws));
});

it('lists each package once, without tree-shaken ones', async () => {
const entries = (await extractLicenses(metafiles(), ws)).split(EXTRACTION_FILE_SEPARATOR);

expect(entries.map(entry => entry.match(/^Package: (.+)$/m)?.[1]).filter(Boolean)).toEqual([
'mit-pkg',
'@scope/custom',
'no-file',
]);
});
});
Loading