_id
stringlengths
21
254
text
stringlengths
1
93.7k
metadata
dict
angular-cli/packages/angular/build/src/builders/application/tests/options/output-mode.ts_0_1806
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { buildApplication } from '../../index'; import { OutputMode } from '../../schema'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { beforeEach(async () => { await harness.modifyFile('src/tsconfig.app.json', (content) => { const tsConfig = JSON.parse(content); tsConfig.files ??= []; tsConfig.files.push('main.server.ts', 'server.ts'); return JSON.stringify(tsConfig); }); await harness.writeFile('src/server.ts', `console.log('Hello!');`); }); describe('Option: "outputMode"', () => { it(`should not emit 'server' directory when OutputMode is Static`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, outputMode: OutputMode.Static, server: 'src/main.server.ts', ssr: { entry: 'src/server.ts' }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectDirectory('dist/server').toNotExist(); }); it(`should emit 'server' directory when OutputMode is Server`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, outputMode: OutputMode.Server, server: 'src/main.server.ts', ssr: { entry: 'src/server.ts' }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/server/main.server.mjs').toExist(); harness.expectFile('dist/server/server.mjs').toExist(); }); }); });
{ "end_byte": 1806, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/output-mode.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/service-worker_spec.ts_0_2763
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "serviceWorker"', () => { beforeEach(async () => { const manifest = { index: '/index.html', assetGroups: [ { name: 'app', installMode: 'prefetch', resources: { files: ['/favicon.ico', '/index.html'], }, }, { name: 'assets', installMode: 'lazy', updateMode: 'prefetch', resources: { files: [ '/assets/**', '/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)', ], }, }, ], }; await harness.writeFile('src/ngsw-config.json', JSON.stringify(manifest)); }); it('should not generate SW config when option is unset', async () => { harness.useTarget('build', { ...BASE_OPTIONS, serviceWorker: undefined, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/ngsw.json').toNotExist(); }); it('should not generate SW config when option is false', async () => { harness.useTarget('build', { ...BASE_OPTIONS, serviceWorker: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/ngsw.json').toNotExist(); }); it('should generate SW config when option is true', async () => { harness.useTarget('build', { ...BASE_OPTIONS, serviceWorker: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/ngsw.json').toExist(); }); it('should generate SW config referencing index output', async () => { harness.useTarget('build', { ...BASE_OPTIONS, serviceWorker: true, index: { input: 'src/index.html', output: 'index.csr.html', }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); const config = await harness.readFile('dist/browser/ngsw.json'); expect(JSON.parse(config)).toEqual(jasmine.objectContaining({ index: '/index.csr.html' })); }); }); });
{ "end_byte": 2763, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/service-worker_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/named-chunks_spec.ts_0_2167
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; const MAIN_OUTPUT = 'dist/browser/main.js'; const NAMED_LAZY_OUTPUT = 'dist/browser/lazy-module-7QZXF7K7.js'; const UNNAMED_LAZY_OUTPUT = 'dist/browser/chunk-OW5RYMPM.js'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "namedChunks"', () => { beforeEach(async () => { // Setup a lazy loaded chunk await harness.writeFiles({ 'src/lazy-module.ts': 'export const value = 42;', 'src/main.ts': `import('./lazy-module');`, }); }); it('generates named files in output when true', async () => { harness.useTarget('build', { ...BASE_OPTIONS, namedChunks: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile(MAIN_OUTPUT).toExist(); harness.expectFile(NAMED_LAZY_OUTPUT).toExist(); harness.expectFile(UNNAMED_LAZY_OUTPUT).toNotExist(); }); it('does not generate named files in output when false', async () => { harness.useTarget('build', { ...BASE_OPTIONS, namedChunks: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile(MAIN_OUTPUT).toExist(); harness.expectFile(NAMED_LAZY_OUTPUT).toNotExist(); harness.expectFile(UNNAMED_LAZY_OUTPUT).toExist(); }); it('does not generates named files in output when not present', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile(MAIN_OUTPUT).toExist(); harness.expectFile(NAMED_LAZY_OUTPUT).toNotExist(); harness.expectFile(UNNAMED_LAZY_OUTPUT).toExist(); }); }); });
{ "end_byte": 2167, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/named-chunks_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/delete-output-path_spec.ts_0_2786
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "deleteOutputPath"', () => { beforeEach(async () => { // Application code is not needed for asset tests await harness.writeFile('src/main.ts', 'console.log("TEST");'); // Add files in output await harness.writeFile('dist/a.txt', 'A'); await harness.writeFile('dist/browser/b.txt', 'B'); }); it(`should delete the output files when 'deleteOutputPath' is true`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, deleteOutputPath: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectDirectory('dist').toExist(); harness.expectFile('dist/a.txt').toNotExist(); harness.expectDirectory('dist/browser').toExist(); harness.expectFile('dist/browser/b.txt').toNotExist(); }); it(`should delete the output files when 'deleteOutputPath' is not set`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, deleteOutputPath: undefined, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectDirectory('dist').toExist(); harness.expectFile('dist/a.txt').toNotExist(); harness.expectDirectory('dist/browser').toExist(); harness.expectFile('dist/browser/b.txt').toNotExist(); }); it(`should not delete the output files when 'deleteOutputPath' is false`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, deleteOutputPath: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/a.txt').toExist(); harness.expectFile('dist/browser/b.txt').toExist(); }); it(`should not delete empty only directories when 'deleteOutputPath' is true`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, deleteOutputPath: true, }); // Add an error to prevent the build from writing files await harness.writeFile('src/main.ts', 'INVALID_CODE'); const { result } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeFalse(); harness.expectDirectory('dist').toExist(); harness.expectDirectory('dist/browser').toExist(); }); }); });
{ "end_byte": 2786, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/delete-output-path_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/styles_spec.ts_0_5056
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "styles"', () => { beforeEach(async () => { // Application code is not needed for styles tests await harness.writeFile('src/main.ts', 'console.log("TEST");'); }); it('supports an empty array value', async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: [], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/styles.css').toNotExist(); }); it('does not create an output styles file when option is not present', async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/styles.css').toNotExist(); }); describe('shorthand syntax', () => { it('processes a single style into a single output', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/test-style-a.css'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/styles.css') .content.toMatch(/\.test-a {\s*color: red;?\s*}/); harness .expectFile('dist/browser/index.html') .content.toContain('<link rel="stylesheet" href="styles.css">'); }); it('processes multiple styles into a single output', async () => { await harness.writeFiles({ 'src/test-style-a.css': '.test-a {color: red}', 'src/test-style-b.css': '.test-b {color: green}', }); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/test-style-a.css', 'src/test-style-b.css'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/styles.css') .content.toMatch(/\.test-a {\s*color: red;?\s*}/); harness .expectFile('dist/browser/styles.css') .content.toMatch(/\.test-b {\s*color: green;?\s*}/); harness .expectFile('dist/browser/index.html') .content.toContain('<link rel="stylesheet" href="styles.css">'); }); it('preserves order of multiple styles in single output', async () => { await harness.writeFiles({ 'src/test-style-a.css': '.test-a {color: red}', 'src/test-style-b.css': '.test-b {color: green}', 'src/test-style-c.css': '.test-c {color: blue}', 'src/test-style-d.css': '.test-d {color: yellow}', }); harness.useTarget('build', { ...BASE_OPTIONS, styles: [ 'src/test-style-c.css', 'src/test-style-d.css', 'src/test-style-b.css', 'src/test-style-a.css', ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/styles.css').content.toMatch( // eslint-disable-next-line max-len /\.test-c {\s*color: blue;?\s*}[\s|\S]+\.test-d {\s*color: yellow;?\s*}[\s|\S]+\.test-b {\s*color: green;?\s*}[\s|\S]+\.test-a {\s*color: red;?\s*}/m, ); }); it('fails and shows an error if style does not exist', async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/test-style-a.css'], }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeFalse(); expect(logs).toContain( jasmine.objectContaining({ level: 'error', message: jasmine.stringMatching('Could not resolve "src/test-style-a.css"'), }), ); harness.expectFile('dist/browser/styles.css').toNotExist(); }); it('shows the output style as a chunk entry in the logging output', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/test-style-a.css'], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(/styles\.css.+\d+ bytes/) }), ); }); });
{ "end_byte": 5056, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/styles_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/styles_spec.ts_5062_12748
describe('longhand syntax', () => { it('processes a single style into a single output', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/styles.css') .content.toMatch(/\.test-a {\s*color: red;?\s*}/); harness .expectFile('dist/browser/index.html') .content.toContain('<link rel="stylesheet" href="styles.css">'); }); it('processes a single style into a single output named with bundleName', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css', bundleName: 'extra' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/extra.css') .content.toMatch(/\.test-a {\s*color: red;?\s*}/); harness .expectFile('dist/browser/index.html') .content.toContain('<link rel="stylesheet" href="extra.css">'); }); it('uses default bundleName when bundleName is empty string', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css', bundleName: '' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/styles.css') .content.toMatch(/\.test-a {\s*color: red;?\s*}/); harness .expectFile('dist/browser/index.html') .content.toContain('<link rel="stylesheet" href="styles.css">'); }); it('processes multiple styles with no bundleName into a single output', async () => { await harness.writeFiles({ 'src/test-style-a.css': '.test-a {color: red}', 'src/test-style-b.css': '.test-b {color: green}', }); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css' }, { input: 'src/test-style-b.css' }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/styles.css') .content.toMatch(/\.test-a {\s*color: red;?\s*}/); harness .expectFile('dist/browser/styles.css') .content.toMatch(/\.test-b {\s*color: green;?\s*}/); harness .expectFile('dist/browser/index.html') .content.toContain('<link rel="stylesheet" href="styles.css">'); }); it('processes multiple styles with same bundleName into a single output', async () => { await harness.writeFiles({ 'src/test-style-a.css': '.test-a {color: red}', 'src/test-style-b.css': '.test-b {color: green}', }); harness.useTarget('build', { ...BASE_OPTIONS, styles: [ { input: 'src/test-style-a.css', bundleName: 'extra' }, { input: 'src/test-style-b.css', bundleName: 'extra' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/extra.css') .content.toMatch(/\.test-a {\s*color: red;?\s*}/); harness .expectFile('dist/browser/extra.css') .content.toMatch(/\.test-b {\s*color: green;?\s*}/); harness .expectFile('dist/browser/index.html') .content.toContain('<link rel="stylesheet" href="extra.css">'); }); it('processes multiple styles with different bundleNames into separate outputs', async () => { await harness.writeFiles({ 'src/test-style-a.css': '.test-a {color: red}', 'src/test-style-b.css': '.test-b {color: green}', }); harness.useTarget('build', { ...BASE_OPTIONS, styles: [ { input: 'src/test-style-a.css', bundleName: 'extra' }, { input: 'src/test-style-b.css', bundleName: 'other' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/extra.css') .content.toMatch(/\.test-a {\s*color: red;?\s*}/); harness .expectFile('dist/browser/other.css') .content.toMatch(/\.test-b {\s*color: green;?\s*}/); harness .expectFile('dist/browser/index.html') .content.toContain('<link rel="stylesheet" href="extra.css">'); harness .expectFile('dist/browser/index.html') .content.toContain('<link rel="stylesheet" href="other.css">'); }); it('preserves order of multiple styles in single output', async () => { await harness.writeFiles({ 'src/test-style-a.css': '.test-a {color: red}', 'src/test-style-b.css': '.test-b {color: green}', 'src/test-style-c.css': '.test-c {color: blue}', 'src/test-style-d.css': '.test-d {color: yellow}', }); harness.useTarget('build', { ...BASE_OPTIONS, styles: [ { input: 'src/test-style-c.css' }, { input: 'src/test-style-d.css' }, { input: 'src/test-style-b.css' }, { input: 'src/test-style-a.css' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/styles.css').content.toMatch( // eslint-disable-next-line max-len /\.test-c {\s*color: blue;?\s*}[\s|\S]+\.test-d {\s*color: yellow;?\s*}[\s|\S]+\.test-b {\s*color: green;?\s*}[\s|\S]+\.test-a {\s*color: red;?\s*}/, ); }); it('preserves order of multiple styles with different bundleNames', async () => { await harness.writeFiles({ 'src/test-style-a.css': '.test-a {color: red}', 'src/test-style-b.css': '.test-b {color: green}', 'src/test-style-c.css': '.test-c {color: blue}', 'src/test-style-d.css': '.test-d {color: yellow}', }); harness.useTarget('build', { ...BASE_OPTIONS, styles: [ { input: 'src/test-style-c.css', bundleName: 'other' }, { input: 'src/test-style-d.css', bundleName: 'extra' }, { input: 'src/test-style-b.css', bundleName: 'extra' }, { input: 'src/test-style-a.css', bundleName: 'other' }, ], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/other.css') .content.toMatch(/\.test-c {\s*color: blue;?\s*}[\s|\S]+\.test-a {\s*color: red;?\s*}/); harness .expectFile('dist/browser/extra.css') .content.toMatch( /\.test-d {\s*color: yellow;?\s*}[\s|\S]+\.test-b {\s*color: green;?\s*}/, ); harness .expectFile('dist/browser/index.html') .content.toMatch( /<link rel="stylesheet" href="other.css">\s*<link rel="stylesheet" href="extra.css">/, ); });
{ "end_byte": 12748, "start_byte": 5062, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/styles_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/styles_spec.ts_12756_16119
it('adds link element to index when inject is true', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css', inject: true }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/styles.css') .content.toMatch(/\.test-a {\s*color: red;?\s*}/); harness .expectFile('dist/browser/index.html') .content.toContain('<link rel="stylesheet" href="styles.css">'); }); it('does not add link element to index when inject is false', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css', inject: false }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); // `inject: false` causes the bundleName to be the input file name harness .expectFile('dist/browser/test-style-a.css') .content.toMatch(/\.test-a {\s*color: red;?\s*}/); harness .expectFile('dist/browser/index.html') .content.not.toContain('<link rel="stylesheet" href="test-style-a.css">'); }); it('does not add link element to index with bundleName when inject is false', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css', bundleName: 'extra', inject: false }], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/extra.css') .content.toMatch(/\.test-a {\s*color: red;?\s*}/); harness .expectFile('dist/browser/index.html') .content.not.toContain('<link rel="stylesheet" href="extra.css">'); }); it('shows the output style as a chunk entry in the logging output', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css' }], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(/styles\.css.+\d+ bytes/) }), ); }); it('shows the output style as a chunk entry with bundleName in the logging output', async () => { await harness.writeFile('src/test-style-a.css', '.test-a {color: red}'); harness.useTarget('build', { ...BASE_OPTIONS, styles: [{ input: 'src/test-style-a.css', bundleName: 'extra' }], }); const { result, logs } = await harness.executeOnce(); expect(result?.success).toBe(true); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching(/extra\.css.+\d+ bytes/) }), ); }); }); }); });
{ "end_byte": 16119, "start_byte": 12756, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/styles_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/optimization-remove-special-comments_spec.ts_0_2337
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Behavior: "removeSpecialComments"', () => { beforeEach(async () => { await harness.writeFile( 'src/styles.css', ` /* normal-comment */ /*! important-comment */ div { flex: 1 } `, ); }); it(`should retain special comments when 'removeSpecialComments' is set to 'false'`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, extractLicenses: true, styles: ['src/styles.css'], optimization: { styles: { removeSpecialComments: false, }, }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness .expectFile('dist/browser/styles.css') .content.toMatch(/\/\*! important-comment \*\/[\s\S]*div{flex:1}/); }); it(`should not retain special comments when 'removeSpecialComments' is set to 'true'`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, extractLicenses: true, styles: ['src/styles.css'], optimization: { styles: { removeSpecialComments: true, }, }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/styles.css').content.not.toContain('important-comment'); }); it(`should not retain special comments when 'removeSpecialComments' is not set`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, extractLicenses: true, styles: ['src/styles.css'], optimization: { styles: {}, }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/styles.css').content.not.toContain('important-comment'); }); }); });
{ "end_byte": 2337, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/optimization-remove-special-comments_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/style-preprocessor-options-sass_spec.ts_0_2901
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; import { logging } from '@angular-devkit/core'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "stylePreprocessorOptions.sass"', () => { it('should cause the build to fail when using `fatalDeprecations` in global styles', async () => { await harness.writeFile('src/styles.scss', 'p { color: darken(red, 10%) }'); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.scss'], stylePreprocessorOptions: { sass: { fatalDeprecations: ['color-functions'], }, }, }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBeFalse(); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('darken() is deprecated'), }), ); }); it('should succeed without `fatalDeprecations` despite using deprecated color functions', async () => { await harness.writeFiles({ 'src/styles.scss': 'p { color: darken(red, 10%) }', 'src/app/app.component.scss': 'p { color: darken(red, 10%) }', }); await harness.modifyFile('src/app/app.component.ts', (content) => { return content.replace('./app.component.css', 'app.component.scss'); }); harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.scss'], stylePreprocessorOptions: { sass: {}, }, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); }); it('should cause the build to fail when using `fatalDeprecations` in component styles', async () => { await harness.modifyFile('src/app/app.component.ts', (content) => { return content.replace('./app.component.css', 'app.component.scss'); }); await harness.writeFile('src/app/app.component.scss', 'p { color: darken(red, 10%) }'); harness.useTarget('build', { ...BASE_OPTIONS, stylePreprocessorOptions: { sass: { fatalDeprecations: ['color-functions'], }, }, }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false, }); expect(result?.success).toBeFalse(); expect(logs).not.toContain( jasmine.objectContaining<logging.LogEntry>({ message: jasmine.stringMatching('darken() is deprecated'), }), ); }); }); });
{ "end_byte": 2901, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/style-preprocessor-options-sass_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/define_spec.ts_0_2420
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "define"', () => { it('should replace a value in application code when specified as a number', async () => { harness.useTarget('build', { ...BASE_OPTIONS, define: { 'AN_INTEGER': '42', }, }); await harness.writeFile('./src/types.d.ts', 'declare const AN_INTEGER: number;'); await harness.writeFile('src/main.ts', 'console.log(AN_INTEGER);'); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.not.toContain('AN_INTEGER'); harness.expectFile('dist/browser/main.js').content.toContain('(42)'); }); it('should replace a value in application code when specified as a string', async () => { harness.useTarget('build', { ...BASE_OPTIONS, define: { 'A_STRING': '"42"', }, }); await harness.writeFile('./src/types.d.ts', 'declare const A_STRING: string;'); await harness.writeFile('src/main.ts', 'console.log(A_STRING);'); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.not.toContain('A_STRING'); harness.expectFile('dist/browser/main.js').content.toContain('("42")'); }); it('should replace a value in application code when specified as a boolean', async () => { harness.useTarget('build', { ...BASE_OPTIONS, define: { 'A_BOOLEAN': 'true', }, }); await harness.writeFile('./src/types.d.ts', 'declare const A_BOOLEAN: boolean;'); await harness.writeFile('src/main.ts', 'console.log(A_BOOLEAN);'); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.not.toContain('A_BOOLEAN'); harness.expectFile('dist/browser/main.js').content.toContain('(true)'); }); }); });
{ "end_byte": 2420, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/define_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/index_spec.ts_0_8284
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "index"', () => { beforeEach(async () => { // Application code is not needed for index tests await harness.writeFile('src/main.ts', 'console.log("TEST");'); }); describe('short form syntax', () => { it('should not generate an output file when false', async () => { harness.useTarget('build', { ...BASE_OPTIONS, index: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/index.html').toNotExist(); }); // TODO: This fails option validation when used in the CLI but not when used directly xit('should fail build when true', async () => { harness.useTarget('build', { ...BASE_OPTIONS, index: true, }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); harness.expectFile('dist/browser/index.html').toNotExist(); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('Schema validation failed') }), ); }); it('should use the provided file path to generate the output file when a string path', async () => { harness.useTarget('build', { ...BASE_OPTIONS, index: 'src/index.html', }); await harness.writeFile( 'src/index.html', '<html><head><title>TEST_123</title></head><body></body>', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/index.html').content.toContain('TEST_123'); }); // TODO: Build needs to be fixed to not throw an unhandled exception for this case xit('should fail build when a string path to non-existent file', async () => { harness.useTarget('build', { ...BASE_OPTIONS, index: 'src/not-here.html', }); const { result } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); harness.expectFile('dist/browser/index.html').toNotExist(); }); it('should generate initial preload link elements', async () => { harness.useTarget('build', { ...BASE_OPTIONS, index: { input: 'src/index.html', preloadInitial: true, }, }); // Setup an initial chunk usage for JS await harness.writeFile('src/a.ts', 'console.log("TEST");'); await harness.writeFile('src/b.ts', 'import "./a";'); await harness.writeFile('src/main.ts', 'import "./a";\n(() => import("./b"))();'); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toContain('chunk-'); harness.expectFile('dist/browser/index.html').content.toContain('modulepreload'); harness.expectFile('dist/browser/index.html').content.toContain('chunk-'); }); }); describe('long form syntax', () => { it('should use the provided input path to generate the output file when present', async () => { harness.useTarget('build', { ...BASE_OPTIONS, index: { input: 'src/index.html', }, }); await harness.writeFile( 'src/index.html', '<html><head><title>TEST_123</title></head><body></body>', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/index.html').content.toContain('TEST_123'); }); it('should use the provided output path to generate the output file when present', async () => { harness.useTarget('build', { ...BASE_OPTIONS, index: { input: 'src/index.html', output: 'output.html', }, }); await harness.writeFile( 'src/index.html', '<html><head><title>TEST_123</title></head><body></body>', ); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/output.html').content.toContain('TEST_123'); }); }); it('should generate initial preload link elements when preloadInitial is true', async () => { harness.useTarget('build', { ...BASE_OPTIONS, index: { input: 'src/index.html', preloadInitial: true, }, }); // Setup an initial chunk usage for JS await harness.writeFile('src/a.ts', 'console.log("TEST");'); await harness.writeFile('src/b.ts', 'import "./a";'); await harness.writeFile('src/main.ts', 'import "./a";\n(() => import("./b"))();'); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toContain('chunk-'); harness.expectFile('dist/browser/index.html').content.toContain('modulepreload'); harness.expectFile('dist/browser/index.html').content.toContain('chunk-'); }); it('should generate initial preload link elements when preloadInitial is undefined', async () => { harness.useTarget('build', { ...BASE_OPTIONS, index: { input: 'src/index.html', preloadInitial: undefined, }, }); // Setup an initial chunk usage for JS await harness.writeFile('src/a.ts', 'console.log("TEST");'); await harness.writeFile('src/b.ts', 'import "./a";'); await harness.writeFile('src/main.ts', 'import "./a";\n(() => import("./b"))();'); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toContain('chunk-'); harness.expectFile('dist/browser/index.html').content.toContain('modulepreload'); harness.expectFile('dist/browser/index.html').content.toContain('chunk-'); }); it('should not generate initial preload link elements when preloadInitial is false', async () => { harness.useTarget('build', { ...BASE_OPTIONS, index: { input: 'src/index.html', preloadInitial: false, }, }); // Setup an initial chunk usage for JS await harness.writeFile('src/a.ts', 'console.log("TEST");'); await harness.writeFile('src/b.ts', 'import "./a";'); await harness.writeFile('src/main.ts', 'import "./a";\n(() => import("./b"))();'); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').content.toContain('chunk-'); harness.expectFile('dist/browser/index.html').content.not.toContain('modulepreload'); harness.expectFile('dist/browser/index.html').content.not.toContain('chunk-'); }); it(`should generate 'index.csr.html' instead of 'index.html' by default when ssr is enabled.`, async () => { await harness.modifyFile('src/tsconfig.app.json', (content) => { const tsConfig = JSON.parse(content); tsConfig.files ??= []; tsConfig.files.push('main.server.ts'); return JSON.stringify(tsConfig); }); harness.useTarget('build', { ...BASE_OPTIONS, server: 'src/main.server.ts', ssr: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectDirectory('dist/server').toExist(); harness.expectFile('dist/browser/index.csr.html').toExist(); harness.expectFile('dist/browser/index.html').toNotExist(); }); }); });
{ "end_byte": 8284, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/index_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/cross-origin_spec.ts_0_3796
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { buildApplication } from '../../index'; import { CrossOrigin } from '../../schema'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "crossOrigin"', () => { beforeEach(async () => { // Application code is not needed for asset tests await harness.writeFile('src/main.ts', 'console.log("TEST");'); // Add a global stylesheet to test link elements await harness.writeFile('src/styles.css', '/* Global styles */'); // Reduce the input index HTML to a single line to simplify comparing await harness.writeFile( 'src/index.html', '<html><head><base href="/"></head><body><app-root></app-root></body></html>', ); }); it('should add the use-credentials crossorigin attribute when option is set to use-credentials', async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], crossOrigin: CrossOrigin.UseCredentials, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/index.html') .content.toEqual( `<html><head><base href="/"><link rel="stylesheet" href="styles.css" crossorigin="use-credentials"></head>` + `<body><app-root></app-root>` + `<script src="main.js" type="module" crossorigin="use-credentials"></script></body></html>`, ); }); it('should add the anonymous crossorigin attribute when option is set to anonymous', async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], crossOrigin: CrossOrigin.Anonymous, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/index.html') .content.toEqual( `<html><head><base href="/">` + `<link rel="stylesheet" href="styles.css" crossorigin="anonymous"></head>` + `<body><app-root></app-root>` + `<script src="main.js" type="module" crossorigin="anonymous"></script></body></html>`, ); }); it('should not add a crossorigin attribute when option is set to none', async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], crossOrigin: CrossOrigin.None, }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/index.html') .content.toEqual( `<html><head><base href="/">` + `<link rel="stylesheet" href="styles.css"></head>` + `<body><app-root></app-root>` + `<script src="main.js" type="module"></script></body></html>`, ); }); it('should not add a crossorigin attribute when option is not present', async () => { harness.useTarget('build', { ...BASE_OPTIONS, styles: ['src/styles.css'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness .expectFile('dist/browser/index.html') .content.toEqual( `<html><head><base href="/">` + `<link rel="stylesheet" href="styles.css"></head>` + `<body><app-root></app-root>` + `<script src="main.js" type="module"></script></body></html>`, ); }); }); });
{ "end_byte": 3796, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/cross-origin_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/polyfills_spec.ts_0_2751
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; const testsVariants: [suitName: string, baseUrl: string | undefined][] = [ ['When "baseUrl" is set to "./"', './'], [`When "baseUrl" is not set`, undefined], [`When "baseUrl" is set to non root path`, './project/foo'], ]; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { for (const [suitName, baseUrl] of testsVariants) { describe(suitName, () => { beforeEach(async () => { await harness.modifyFile('tsconfig.json', (content) => { const tsconfig = JSON.parse(content); tsconfig.compilerOptions.baseUrl = baseUrl; return JSON.stringify(tsconfig); }); }); it('uses a provided TypeScript file', async () => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: ['src/polyfills.ts'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/polyfills.js').toExist(); }); it('uses a provided JavaScript file', async () => { await harness.writeFile('src/polyfills.js', `console.log('main');`); harness.useTarget('build', { ...BASE_OPTIONS, polyfills: ['src/polyfills.js'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/polyfills.js').content.toContain(`console.log("main")`); }); it('fails and shows an error when file does not exist', async () => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: ['src/missing.ts'], }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('Could not resolve') }), ); harness.expectFile('dist/browser/polyfills.js').toNotExist(); }); it('resolves module specifiers in array', async () => { harness.useTarget('build', { ...BASE_OPTIONS, polyfills: ['zone.js', 'zone.js/testing'], }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/browser/polyfills.js').toExist(); }); }); } });
{ "end_byte": 2751, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/polyfills_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/browser_spec.ts_0_2847
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "browser"', () => { it('uses a provided TypeScript file', async () => { harness.useTarget('build', { ...BASE_OPTIONS, browser: 'src/main.ts', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').toExist(); harness.expectFile('dist/browser/index.html').toExist(); }); it('uses a provided JavaScript file', async () => { await harness.writeFile('src/main.js', `console.log('main');`); harness.useTarget('build', { ...BASE_OPTIONS, browser: 'src/main.js', }); const { result } = await harness.executeOnce(); expect(result?.success).toBe(true); harness.expectFile('dist/browser/main.js').toExist(); harness.expectFile('dist/browser/index.html').toExist(); harness.expectFile('dist/browser/main.js').content.toContain('console.log("main")'); }); it('fails and shows an error when file does not exist', async () => { harness.useTarget('build', { ...BASE_OPTIONS, browser: 'src/missing.ts', }); const { result, logs } = await harness.executeOnce({ outputLogsOnFailure: false }); expect(result?.success).toBe(false); expect(logs).toContain( jasmine.objectContaining({ message: jasmine.stringMatching('Could not resolve "') }), ); harness.expectFile('dist/browser/main.js').toNotExist(); harness.expectFile('dist/browser/index.html').toNotExist(); }); it('throws an error when given an empty string', async () => { harness.useTarget('build', { ...BASE_OPTIONS, browser: '', }); const { result, error } = await harness.executeOnce({ outputLogsOnException: false }); expect(result).toBeUndefined(); expect(error?.message).toContain('cannot be an empty string'); }); it('resolves an absolute path as relative inside the workspace root', async () => { await harness.writeFile('file.mjs', `console.log('Hello!');`); harness.useTarget('build', { ...BASE_OPTIONS, browser: '/file.mjs', }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); // Always uses the name `main.js` for the `browser` option. harness.expectFile('dist/browser/main.js').toExist(); }); }); });
{ "end_byte": 2847, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/browser_spec.ts" }
angular-cli/packages/angular/build/src/builders/application/tests/options/extract-licenses_spec.ts_0_2065
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { buildApplication } from '../../index'; import { APPLICATION_BUILDER_INFO, BASE_OPTIONS, describeBuilder } from '../setup'; describeBuilder(buildApplication, APPLICATION_BUILDER_INFO, (harness) => { describe('Option: "extractLicenses"', () => { it(`should generate '3rdpartylicenses.txt' when 'extractLicenses' is true`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, extractLicenses: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/3rdpartylicenses.txt').content.toContain('MIT'); }); it(`should not generate '3rdpartylicenses.txt' when 'extractLicenses' is false`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, extractLicenses: false, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/3rdpartylicenses.txt').toNotExist(); }); it(`should generate '3rdpartylicenses.txt' when 'extractLicenses' is not set`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/3rdpartylicenses.txt').content.toContain('MIT'); }); it(`should generate '3rdpartylicenses.txt' when 'extractLicenses' and 'localize' are true`, async () => { harness.useTarget('build', { ...BASE_OPTIONS, localize: true, extractLicenses: true, }); const { result } = await harness.executeOnce(); expect(result?.success).toBeTrue(); harness.expectFile('dist/3rdpartylicenses.txt').content.toContain('MIT'); harness.expectFile('dist/browser/en-US/main.js').toExist(); }); }); });
{ "end_byte": 2065, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/builders/application/tests/options/extract-licenses_spec.ts" }
angular-cli/packages/angular/build/src/utils/format-bytes_spec.ts_0_684
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { formatSize } from './format-bytes'; describe('formatSize', () => { it('1000 bytes to be 1kB', () => { expect(formatSize(1000)).toBe('1.00 kB'); }); it('1_000_000 bytes to be 1MB', () => { expect(formatSize(1_000_000)).toBe('1.00 MB'); }); it('1_500_000 bytes to be 1.5MB', () => { expect(formatSize(1_500_000)).toBe('1.50 MB'); }); it('1_000_000_000 bytes to be 1GB', () => { expect(formatSize(1_000_000_000)).toBe('1.00 GB'); }); });
{ "end_byte": 684, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/format-bytes_spec.ts" }
angular-cli/packages/angular/build/src/utils/format-bytes.ts_0_624
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export function formatSize(size: number): string { if (size <= 0) { return '0 bytes'; } const abbreviations = ['bytes', 'kB', 'MB', 'GB']; const index = Math.floor(Math.log(size) / Math.log(1000)); const roundedSize = size / Math.pow(1000, index); // bytes don't have a fraction const fractionDigits = index === 0 ? 0 : 2; return `${roundedSize.toFixed(fractionDigits)} ${abbreviations[index]}`; }
{ "end_byte": 624, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/format-bytes.ts" }
angular-cli/packages/angular/build/src/utils/stats-table.ts_0_8291
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { stripVTControlCharacters } from 'node:util'; import { BudgetCalculatorResult } from './bundle-calculator'; import { colors as ansiColors } from './color'; import { formatSize } from './format-bytes'; export type BundleStatsData = [ files: string, names: string, rawSize: number | string, estimatedTransferSize: number | string, ]; export interface BundleStats { initial: boolean; stats: BundleStatsData; } export function generateEsbuildBuildStatsTable( [browserStats, serverStats]: [browserStats: BundleStats[], serverStats: BundleStats[]], colors: boolean, showTotalSize: boolean, showEstimatedTransferSize: boolean, budgetFailures?: BudgetCalculatorResult[], verbose?: boolean, ): string { const bundleInfo = generateBuildStatsData( browserStats, colors, showTotalSize, showEstimatedTransferSize, budgetFailures, verbose, ); if (serverStats.length) { const m = (x: string) => (colors ? ansiColors.magenta(x) : x); if (browserStats.length) { bundleInfo.unshift([m('Browser bundles')]); // Add seperators between browser and server logs bundleInfo.push([], []); } bundleInfo.push( [m('Server bundles')], ...generateBuildStatsData(serverStats, colors, false, false, undefined, verbose), ); } return generateTableText(bundleInfo, colors); } export function generateBuildStatsTable( data: BundleStats[], colors: boolean, showTotalSize: boolean, showEstimatedTransferSize: boolean, budgetFailures?: BudgetCalculatorResult[], ): string { const bundleInfo = generateBuildStatsData( data, colors, showTotalSize, showEstimatedTransferSize, budgetFailures, true, ); return generateTableText(bundleInfo, colors); } function generateBuildStatsData( data: BundleStats[], colors: boolean, showTotalSize: boolean, showEstimatedTransferSize: boolean, budgetFailures?: BudgetCalculatorResult[], verbose?: boolean, ): (string | number)[][] { if (data.length === 0) { return []; } const g = (x: string) => (colors ? ansiColors.green(x) : x); const c = (x: string) => (colors ? ansiColors.cyan(x) : x); const r = (x: string) => (colors ? ansiColors.redBright(x) : x); const y = (x: string) => (colors ? ansiColors.yellowBright(x) : x); const bold = (x: string) => (colors ? ansiColors.bold(x) : x); const dim = (x: string) => (colors ? ansiColors.dim(x) : x); const getSizeColor = (name: string, file?: string, defaultColor = c) => { const severity = budgets.get(name) || (file && budgets.get(file)); switch (severity) { case 'warning': return y; case 'error': return r; default: return defaultColor; } }; const changedEntryChunksStats: BundleStatsData[] = []; const changedLazyChunksStats: BundleStatsData[] = []; let initialTotalRawSize = 0; let changedLazyChunksCount = 0; let initialTotalEstimatedTransferSize; const maxLazyChunksWithoutBudgetFailures = 15; const budgets = new Map<string, string>(); if (budgetFailures) { for (const { label, severity } of budgetFailures) { // In some cases a file can have multiple budget failures. // Favor error. if (label && (!budgets.has(label) || budgets.get(label) === 'warning')) { budgets.set(label, severity); } } } // Sort descending by raw size data.sort((a, b) => { if (a.stats[2] > b.stats[2]) { return -1; } if (a.stats[2] < b.stats[2]) { return 1; } return 0; }); for (const { initial, stats } of data) { const [files, names, rawSize, estimatedTransferSize] = stats; if ( !initial && !verbose && changedLazyChunksStats.length >= maxLazyChunksWithoutBudgetFailures && !budgets.has(names) && !budgets.has(files) ) { // Limit the number of lazy chunks displayed in the stats table when there is no budget failure and not in verbose mode. changedLazyChunksCount++; continue; } const getRawSizeColor = getSizeColor(names, files); let data: BundleStatsData; if (showEstimatedTransferSize) { data = [ g(files), dim(names), getRawSizeColor(typeof rawSize === 'number' ? formatSize(rawSize) : rawSize), c( typeof estimatedTransferSize === 'number' ? formatSize(estimatedTransferSize) : estimatedTransferSize, ), ]; } else { data = [ g(files), dim(names), getRawSizeColor(typeof rawSize === 'number' ? formatSize(rawSize) : rawSize), '', ]; } if (initial) { changedEntryChunksStats.push(data); if (typeof rawSize === 'number') { initialTotalRawSize += rawSize; } if (showEstimatedTransferSize && typeof estimatedTransferSize === 'number') { if (initialTotalEstimatedTransferSize === undefined) { initialTotalEstimatedTransferSize = 0; } initialTotalEstimatedTransferSize += estimatedTransferSize; } } else { changedLazyChunksStats.push(data); changedLazyChunksCount++; } } const bundleInfo: (string | number)[][] = []; const baseTitles = ['Names', 'Raw size']; if (showEstimatedTransferSize) { baseTitles.push('Estimated transfer size'); } // Entry chunks if (changedEntryChunksStats.length) { bundleInfo.push(['Initial chunk files', ...baseTitles].map(bold), ...changedEntryChunksStats); if (showTotalSize) { const initialSizeTotalColor = getSizeColor('bundle initial', undefined, (x) => x); const totalSizeElements = [ ' ', 'Initial total', initialSizeTotalColor(formatSize(initialTotalRawSize)), ]; if (showEstimatedTransferSize) { totalSizeElements.push( typeof initialTotalEstimatedTransferSize === 'number' ? formatSize(initialTotalEstimatedTransferSize) : '-', ); } bundleInfo.push([], totalSizeElements.map(bold)); } } // Seperator if (changedEntryChunksStats.length && changedLazyChunksStats.length) { bundleInfo.push([]); } // Lazy chunks if (changedLazyChunksStats.length) { bundleInfo.push(['Lazy chunk files', ...baseTitles].map(bold), ...changedLazyChunksStats); if (changedLazyChunksCount > changedLazyChunksStats.length) { bundleInfo.push([ dim( `...and ${changedLazyChunksCount - changedLazyChunksStats.length} more lazy chunks files. ` + 'Use "--verbose" to show all the files.', ), ]); } } return bundleInfo; } function generateTableText(bundleInfo: (string | number)[][], colors: boolean): string { const skipText = (value: string) => value.includes('...and '); const longest: number[] = []; for (const item of bundleInfo) { for (let i = 0; i < item.length; i++) { if (item[i] === undefined) { continue; } const currentItem = item[i].toString(); if (skipText(currentItem)) { continue; } const currentLongest = (longest[i] ??= 0); const currentItemLength = stripVTControlCharacters(currentItem).length; if (currentLongest < currentItemLength) { longest[i] = currentItemLength; } } } const seperator = colors ? ansiColors.dim(' | ') : ' | '; const outputTable: string[] = []; for (const item of bundleInfo) { for (let i = 0; i < longest.length; i++) { if (item[i] === undefined) { continue; } const currentItem = item[i].toString(); if (skipText(currentItem)) { continue; } const currentItemLength = stripVTControlCharacters(currentItem).length; const stringPad = ' '.repeat(longest[i] - currentItemLength); // Values in columns at index 2 and 3 (Raw and Estimated sizes) are always right aligned. item[i] = i >= 2 ? stringPad + currentItem : currentItem + stringPad; } outputTable.push(item.join(seperator)); } return outputTable.join('\n'); }
{ "end_byte": 8291, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/stats-table.ts" }
angular-cli/packages/angular/build/src/utils/bundle-calculator.ts_0_7637
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Budget as BudgetEntry, Type as BudgetType } from '../builders/application/schema'; import { formatSize } from './format-bytes'; // Re-export to avoid direct schema importing throughout code export { type BudgetEntry, BudgetType }; interface Size { size: number; label?: string; } export interface Threshold { limit: number; type: ThresholdType; severity: ThresholdSeverity; } enum ThresholdType { Max = 'maximum', Min = 'minimum', } export enum ThresholdSeverity { Warning = 'warning', Error = 'error', } export interface BudgetCalculatorResult { severity: ThresholdSeverity; message: string; label?: string; } export interface BudgetChunk { files?: string[]; names?: string[]; initial?: boolean; } export interface BudgetAsset { name: string; size: number; componentStyle?: boolean; } export interface BudgetStats { chunks?: BudgetChunk[]; assets?: BudgetAsset[]; } export function* calculateThresholds(budget: BudgetEntry): IterableIterator<Threshold> { if (budget.maximumWarning) { yield { limit: calculateBytes(budget.maximumWarning, budget.baseline, 1), type: ThresholdType.Max, severity: ThresholdSeverity.Warning, }; } if (budget.maximumError) { yield { limit: calculateBytes(budget.maximumError, budget.baseline, 1), type: ThresholdType.Max, severity: ThresholdSeverity.Error, }; } if (budget.minimumWarning) { yield { limit: calculateBytes(budget.minimumWarning, budget.baseline, -1), type: ThresholdType.Min, severity: ThresholdSeverity.Warning, }; } if (budget.minimumError) { yield { limit: calculateBytes(budget.minimumError, budget.baseline, -1), type: ThresholdType.Min, severity: ThresholdSeverity.Error, }; } if (budget.warning) { yield { limit: calculateBytes(budget.warning, budget.baseline, -1), type: ThresholdType.Min, severity: ThresholdSeverity.Warning, }; yield { limit: calculateBytes(budget.warning, budget.baseline, 1), type: ThresholdType.Max, severity: ThresholdSeverity.Warning, }; } if (budget.error) { yield { limit: calculateBytes(budget.error, budget.baseline, -1), type: ThresholdType.Min, severity: ThresholdSeverity.Error, }; yield { limit: calculateBytes(budget.error, budget.baseline, 1), type: ThresholdType.Max, severity: ThresholdSeverity.Error, }; } } /** * Calculates the sizes for bundles in the budget type provided. */ function calculateSizes(budget: BudgetEntry, stats: BudgetStats): Size[] { type CalculatorTypes = { new (budget: BudgetEntry, chunks: BudgetChunk[], assets: BudgetAsset[]): Calculator; }; const calculatorMap: Record<BudgetType, CalculatorTypes> = { all: AllCalculator, allScript: AllScriptCalculator, any: AnyCalculator, anyScript: AnyScriptCalculator, anyComponentStyle: AnyComponentStyleCalculator, bundle: BundleCalculator, initial: InitialCalculator, }; const ctor = calculatorMap[budget.type]; const { chunks, assets } = stats; if (!chunks) { throw new Error('Webpack stats output did not include chunk information.'); } if (!assets) { throw new Error('Webpack stats output did not include asset information.'); } const calculator = new ctor(budget, chunks, assets); return calculator.calculate(); } abstract class Calculator { constructor( protected budget: BudgetEntry, protected chunks: BudgetChunk[], protected assets: BudgetAsset[], ) {} abstract calculate(): Size[]; /** Calculates the size of the given chunk for the provided build type. */ protected calculateChunkSize(chunk: BudgetChunk): number { // No differential builds, get the chunk size by summing its assets. if (!chunk.files) { return 0; } return chunk.files .filter((file) => !file.endsWith('.map')) .map((file) => { const asset = this.assets.find((asset) => asset.name === file); if (!asset) { throw new Error(`Could not find asset for file: ${file}`); } return asset.size; }) .reduce((l, r) => l + r, 0); } protected getAssetSize(asset: BudgetAsset): number { return asset.size; } } /** * A named bundle. */ class BundleCalculator extends Calculator { calculate() { const budgetName = this.budget.name; if (!budgetName) { return []; } const size = this.chunks .filter((chunk) => chunk?.names?.includes(budgetName)) .map((chunk) => this.calculateChunkSize(chunk)) .reduce((l, r) => l + r, 0); return [{ size, label: this.budget.name }]; } } /** * The sum of all initial chunks (marked as initial). */ class InitialCalculator extends Calculator { calculate() { return [ { label: `bundle initial`, size: this.chunks .filter((chunk) => chunk.initial) .map((chunk) => this.calculateChunkSize(chunk)) .reduce((l, r) => l + r, 0), }, ]; } } /** * The sum of all the scripts portions. */ class AllScriptCalculator extends Calculator { calculate() { const size = this.assets .filter((asset) => asset.name.endsWith('.js')) .map((asset) => this.getAssetSize(asset)) .reduce((total: number, size: number) => total + size, 0); return [{ size, label: 'total scripts' }]; } } /** * All scripts and assets added together. */ class AllCalculator extends Calculator { calculate() { const size = this.assets .filter((asset) => !asset.name.endsWith('.map')) .map((asset) => this.getAssetSize(asset)) .reduce((total: number, size: number) => total + size, 0); return [{ size, label: 'total' }]; } } /** * Any script, individually. */ class AnyScriptCalculator extends Calculator { calculate() { return this.assets .filter((asset) => asset.name.endsWith('.js')) .map((asset) => ({ size: this.getAssetSize(asset), label: asset.name, })); } } /** * Any script or asset (images, css, etc). */ class AnyCalculator extends Calculator { calculate() { return this.assets .filter((asset) => !asset.name.endsWith('.map')) .map((asset) => ({ size: this.getAssetSize(asset), label: asset.name, })); } } /** * Any compoonent stylesheet */ class AnyComponentStyleCalculator extends Calculator { calculate() { return this.assets .filter((asset) => asset.componentStyle) .map((asset) => ({ size: this.getAssetSize(asset), label: asset.name, })); } } /** * Calculate the bytes given a string value. */ function calculateBytes(input: string, baseline?: string, factor: 1 | -1 = 1): number { const matches = input.trim().match(/^(\d+(?:\.\d+)?)[ \t]*(%|[kmg]?b)?$/i); if (!matches) { return NaN; } const baselineBytes = (baseline && calculateBytes(baseline)) || 0; let value = Number(matches[1]); switch (matches[2] && matches[2].toLowerCase()) { case '%': value = (baselineBytes * value) / 100; break; case 'kb': value *= 1024; break; case 'mb': value *= 1024 * 1024; break; case 'gb': value *= 1024 * 1024 * 1024; break; } if (baselineBytes === 0) { return value; } return baselineBytes + value * factor; }
{ "end_byte": 7637, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/bundle-calculator.ts" }
angular-cli/packages/angular/build/src/utils/bundle-calculator.ts_7639_9554
export function* checkBudgets( budgets: BudgetEntry[], stats: BudgetStats, checkComponentStyles?: boolean, ): IterableIterator<BudgetCalculatorResult> { // Ignore AnyComponentStyle budgets as these are handled in `AnyComponentStyleBudgetChecker` unless requested const computableBudgets = checkComponentStyles ? budgets : budgets.filter((budget) => budget.type !== BudgetType.AnyComponentStyle); for (const budget of computableBudgets) { const sizes = calculateSizes(budget, stats); for (const { size, label } of sizes) { yield* checkThresholds(calculateThresholds(budget), size, label); } } } export function* checkThresholds( thresholds: Iterable<Threshold>, size: number, label?: string, ): IterableIterator<BudgetCalculatorResult> { for (const threshold of thresholds) { switch (threshold.type) { case ThresholdType.Max: { if (size <= threshold.limit) { continue; } const sizeDifference = formatSize(size - threshold.limit); yield { severity: threshold.severity, label, message: `${label} exceeded maximum budget. Budget ${formatSize( threshold.limit, )} was not met by ${sizeDifference} with a total of ${formatSize(size)}.`, }; break; } case ThresholdType.Min: { if (size >= threshold.limit) { continue; } const sizeDifference = formatSize(threshold.limit - size); yield { severity: threshold.severity, label, message: `${label} failed to meet minimum budget. Budget ${formatSize( threshold.limit, )} was not met by ${sizeDifference} with a total of ${formatSize(size)}.`, }; break; } default: { throw new Error(`Unexpected threshold type: ${ThresholdType[threshold.type]}`); } } } }
{ "end_byte": 9554, "start_byte": 7639, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/bundle-calculator.ts" }
angular-cli/packages/angular/build/src/utils/environment-options.ts_0_3688
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { availableParallelism } from 'node:os'; function isDisabled(variable: string): boolean { return variable === '0' || variable.toLowerCase() === 'false'; } function isEnabled(variable: string): boolean { return variable === '1' || variable.toLowerCase() === 'true'; } function isPresent(variable: string | undefined): variable is string { return typeof variable === 'string' && variable !== ''; } // Optimization and mangling const debugOptimizeVariable = process.env['NG_BUILD_DEBUG_OPTIMIZE']; const debugOptimize = (() => { if (!isPresent(debugOptimizeVariable) || isDisabled(debugOptimizeVariable)) { return { mangle: true, minify: true, beautify: false, }; } const debugValue = { mangle: false, minify: false, beautify: true, }; if (isEnabled(debugOptimizeVariable)) { return debugValue; } for (const part of debugOptimizeVariable.split(',')) { switch (part.trim().toLowerCase()) { case 'mangle': debugValue.mangle = true; break; case 'minify': debugValue.minify = true; break; case 'beautify': debugValue.beautify = true; break; } } return debugValue; })(); const mangleVariable = process.env['NG_BUILD_MANGLE']; export const allowMangle = isPresent(mangleVariable) ? !isDisabled(mangleVariable) : debugOptimize.mangle; export const shouldBeautify = debugOptimize.beautify; export const allowMinify = debugOptimize.minify; /** * Some environments, like CircleCI which use Docker report a number of CPUs by the host and not the count of available. * This cause `Error: Call retries were exceeded` errors when trying to use them. * * @see https://github.com/nodejs/node/issues/28762 * @see https://github.com/webpack-contrib/terser-webpack-plugin/issues/143 * @see https://ithub.com/angular/angular-cli/issues/16860#issuecomment-588828079 * */ const maxWorkersVariable = process.env['NG_BUILD_MAX_WORKERS']; export const maxWorkers = isPresent(maxWorkersVariable) ? +maxWorkersVariable : Math.min(4, Math.max(availableParallelism() - 1, 1)); const parallelTsVariable = process.env['NG_BUILD_PARALLEL_TS']; export const useParallelTs = !isPresent(parallelTsVariable) || !isDisabled(parallelTsVariable); const debugPerfVariable = process.env['NG_BUILD_DEBUG_PERF']; export const debugPerformance = isPresent(debugPerfVariable) && isEnabled(debugPerfVariable); const watchRootVariable = process.env['NG_BUILD_WATCH_ROOT']; export const shouldWatchRoot = isPresent(watchRootVariable) && isEnabled(watchRootVariable); const typeCheckingVariable = process.env['NG_BUILD_TYPE_CHECK']; export const useTypeChecking = !isPresent(typeCheckingVariable) || !isDisabled(typeCheckingVariable); const buildLogsJsonVariable = process.env['NG_BUILD_LOGS_JSON']; export const useJSONBuildLogs = isPresent(buildLogsJsonVariable) && isEnabled(buildLogsJsonVariable); const optimizeChunksVariable = process.env['NG_BUILD_OPTIMIZE_CHUNKS']; export const shouldOptimizeChunks = isPresent(optimizeChunksVariable) && isEnabled(optimizeChunksVariable); const hmrComponentStylesVariable = process.env['NG_HMR_CSTYLES']; export const useComponentStyleHmr = !isPresent(hmrComponentStylesVariable) || !isDisabled(hmrComponentStylesVariable); const partialSsrBuildVariable = process.env['NG_BUILD_PARTIAL_SSR']; export const usePartialSsrBuild = isPresent(partialSsrBuildVariable) && isEnabled(partialSsrBuildVariable);
{ "end_byte": 3688, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/environment-options.ts" }
angular-cli/packages/angular/build/src/utils/postcss-configuration.ts_0_3210
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { readFile, readdir } from 'node:fs/promises'; import { join } from 'node:path'; export interface PostcssConfiguration { plugins: [name: string, options?: object | string][]; } interface RawPostcssConfiguration { plugins?: Record<string, object | boolean | string> | (string | [string, object])[]; } const postcssConfigurationFiles: string[] = ['postcss.config.json', '.postcssrc.json']; const tailwindConfigFiles: string[] = [ 'tailwind.config.js', 'tailwind.config.cjs', 'tailwind.config.mjs', 'tailwind.config.ts', ]; export interface SearchDirectory { root: string; files: Set<string>; } export async function generateSearchDirectories(roots: string[]): Promise<SearchDirectory[]> { return await Promise.all( roots.map((root) => readdir(root, { withFileTypes: true }).then((entries) => ({ root, files: new Set(entries.filter((entry) => entry.isFile()).map((entry) => entry.name)), })), ), ); } function findFile( searchDirectories: SearchDirectory[], potentialFiles: string[], ): string | undefined { for (const { root, files } of searchDirectories) { for (const potential of potentialFiles) { if (files.has(potential)) { return join(root, potential); } } } return undefined; } export function findTailwindConfiguration( searchDirectories: SearchDirectory[], ): string | undefined { return findFile(searchDirectories, tailwindConfigFiles); } async function readPostcssConfiguration( configurationFile: string, ): Promise<RawPostcssConfiguration> { const data = await readFile(configurationFile, 'utf-8'); const config = JSON.parse(data) as RawPostcssConfiguration; return config; } export async function loadPostcssConfiguration( searchDirectories: SearchDirectory[], ): Promise<PostcssConfiguration | undefined> { const configPath = findFile(searchDirectories, postcssConfigurationFiles); if (!configPath) { return undefined; } const raw = await readPostcssConfiguration(configPath); // If no plugins are defined, consider it equivalent to no configuration if (!raw.plugins || typeof raw.plugins !== 'object') { return undefined; } // Normalize plugin array form if (Array.isArray(raw.plugins)) { if (raw.plugins.length < 1) { return undefined; } const config: PostcssConfiguration = { plugins: [] }; for (const element of raw.plugins) { if (typeof element === 'string') { config.plugins.push([element]); } else { config.plugins.push(element); } } return config; } // Normalize plugin object map form const entries = Object.entries(raw.plugins); if (entries.length < 1) { return undefined; } const config: PostcssConfiguration = { plugins: [] }; for (const [name, options] of entries) { if (!options || (typeof options !== 'object' && typeof options !== 'string')) { continue; } config.plugins.push([name, options]); } return config; }
{ "end_byte": 3210, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/postcss-configuration.ts" }
angular-cli/packages/angular/build/src/utils/purge-cache.ts_0_1364
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { BuilderContext } from '@angular-devkit/architect'; import { readdir, rm } from 'node:fs/promises'; import { join } from 'node:path'; import { normalizeCacheOptions } from './normalize-cache'; /** Delete stale cache directories used by previous versions of build-angular. */ export async function purgeStaleBuildCache(context: BuilderContext): Promise<void> { const projectName = context.target?.project; if (!projectName) { return; } const metadata = await context.getProjectMetadata(projectName); const { basePath, path, enabled } = normalizeCacheOptions(metadata, context.workspaceRoot); if (!enabled) { return; } let baseEntries; try { baseEntries = await readdir(basePath, { withFileTypes: true }); } catch { // No purging possible if base path does not exist or cannot otherwise be accessed return; } const entriesToDelete = baseEntries .filter((d) => d.isDirectory()) .map((d) => join(basePath, d.name)) .filter((cachePath) => cachePath !== path) .map((stalePath) => rm(stalePath, { force: true, recursive: true, maxRetries: 3 })); await Promise.allSettled(entriesToDelete); }
{ "end_byte": 1364, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/purge-cache.ts" }
angular-cli/packages/angular/build/src/utils/normalize-source-maps.ts_0_753
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { SourceMapClass, SourceMapUnion } from '../builders/application/schema'; export function normalizeSourceMaps(sourceMap: SourceMapUnion): SourceMapClass { const scripts = typeof sourceMap === 'object' ? sourceMap.scripts : sourceMap; const styles = typeof sourceMap === 'object' ? sourceMap.styles : sourceMap; const hidden = (typeof sourceMap === 'object' && sourceMap.hidden) || false; const vendor = (typeof sourceMap === 'object' && sourceMap.vendor) || false; return { vendor, hidden, scripts, styles, }; }
{ "end_byte": 753, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/normalize-source-maps.ts" }
angular-cli/packages/angular/build/src/utils/service-worker.ts_0_8094
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import type { Config, Filesystem } from '@angular/service-worker/config'; import * as crypto from 'crypto'; import { existsSync, constants as fsConstants, promises as fsPromises } from 'node:fs'; import * as path from 'path'; import { BuildOutputFile, BuildOutputFileType } from '../tools/esbuild/bundler-context'; import { BuildOutputAsset } from '../tools/esbuild/bundler-execution-result'; import { assertIsError } from './error'; import { loadEsmModule } from './load-esm'; class CliFilesystem implements Filesystem { constructor( private fs: typeof fsPromises, private base: string, ) {} list(dir: string): Promise<string[]> { return this._recursiveList(this._resolve(dir), []); } read(file: string): Promise<string> { return this.fs.readFile(this._resolve(file), 'utf-8'); } async hash(file: string): Promise<string> { return crypto .createHash('sha1') .update(await this.fs.readFile(this._resolve(file))) .digest('hex'); } write(_file: string, _content: string): never { throw new Error('This should never happen.'); } private _resolve(file: string): string { return path.join(this.base, file); } private async _recursiveList(dir: string, items: string[]): Promise<string[]> { const subdirectories = []; for (const entry of await this.fs.readdir(dir)) { const entryPath = path.join(dir, entry); const stats = await this.fs.stat(entryPath); if (stats.isFile()) { // Uses posix paths since the service worker expects URLs items.push('/' + path.relative(this.base, entryPath).replace(/\\/g, '/')); } else if (stats.isDirectory()) { subdirectories.push(entryPath); } } for (const subdirectory of subdirectories) { await this._recursiveList(subdirectory, items); } return items; } } class ResultFilesystem implements Filesystem { private readonly fileReaders = new Map<string, () => Promise<Uint8Array>>(); constructor( outputFiles: BuildOutputFile[], assetFiles: { source: string; destination: string }[], ) { for (const file of outputFiles) { if (file.type === BuildOutputFileType.Media || file.type === BuildOutputFileType.Browser) { this.fileReaders.set('/' + file.path.replace(/\\/g, '/'), async () => file.contents); } } for (const file of assetFiles) { this.fileReaders.set('/' + file.destination.replace(/\\/g, '/'), () => fsPromises.readFile(file.source), ); } } async list(dir: string): Promise<string[]> { if (dir !== '/') { throw new Error('Serviceworker manifest generator should only list files from root.'); } return [...this.fileReaders.keys()]; } async read(file: string): Promise<string> { const reader = this.fileReaders.get(file); if (reader === undefined) { throw new Error('File does not exist.'); } const contents = await reader(); return Buffer.from(contents.buffer, contents.byteOffset, contents.byteLength).toString('utf-8'); } async hash(file: string): Promise<string> { const reader = this.fileReaders.get(file); if (reader === undefined) { throw new Error('File does not exist.'); } return crypto .createHash('sha1') .update(await reader()) .digest('hex'); } write(): never { throw new Error('Serviceworker manifest generator should not attempted to write.'); } } export async function augmentAppWithServiceWorker( appRoot: string, workspaceRoot: string, outputPath: string, baseHref: string, ngswConfigPath?: string, inputputFileSystem = fsPromises, outputFileSystem = fsPromises, ): Promise<void> { // Determine the configuration file path const configPath = ngswConfigPath ? path.join(workspaceRoot, ngswConfigPath) : path.join(appRoot, 'ngsw-config.json'); // Read the configuration file let config: Config | undefined; try { const configurationData = await inputputFileSystem.readFile(configPath, 'utf-8'); config = JSON.parse(configurationData) as Config; } catch (error) { assertIsError(error); if (error.code === 'ENOENT') { throw new Error( 'Error: Expected to find an ngsw-config.json configuration file' + ` in the ${appRoot} folder. Either provide one or` + ' disable Service Worker in the angular.json configuration file.', ); } else { throw error; } } const result = await augmentAppWithServiceWorkerCore( config, new CliFilesystem(outputFileSystem, outputPath), baseHref, ); const copy = async (src: string, dest: string): Promise<void> => { const resolvedDest = path.join(outputPath, dest); return inputputFileSystem === outputFileSystem ? // Native FS (Builder). inputputFileSystem.copyFile(src, resolvedDest, fsConstants.COPYFILE_FICLONE) : // memfs (Webpack): Read the file from the input FS (disk) and write it to the output FS (memory). outputFileSystem.writeFile(resolvedDest, await inputputFileSystem.readFile(src)); }; await outputFileSystem.writeFile(path.join(outputPath, 'ngsw.json'), result.manifest); for (const { source, destination } of result.assetFiles) { await copy(source, destination); } } // This is currently used by the esbuild-based builder export async function augmentAppWithServiceWorkerEsbuild( workspaceRoot: string, configPath: string, baseHref: string, indexHtml: string | undefined, outputFiles: BuildOutputFile[], assetFiles: BuildOutputAsset[], ): Promise<{ manifest: string; assetFiles: BuildOutputAsset[] }> { // Read the configuration file let config: Config | undefined; try { const configurationData = await fsPromises.readFile(configPath, 'utf-8'); config = JSON.parse(configurationData) as Config; if (indexHtml) { config.index = indexHtml; } } catch (error) { assertIsError(error); if (error.code === 'ENOENT') { // TODO: Generate an error object that can be consumed by the esbuild-based builder const message = `Service worker configuration file "${path.relative( workspaceRoot, configPath, )}" could not be found.`; throw new Error(message); } else { throw error; } } return augmentAppWithServiceWorkerCore( config, new ResultFilesystem(outputFiles, assetFiles), baseHref, ); } export async function augmentAppWithServiceWorkerCore( config: Config, serviceWorkerFilesystem: Filesystem, baseHref: string, ): Promise<{ manifest: string; assetFiles: { source: string; destination: string }[] }> { // Load ESM `@angular/service-worker/config` using the TypeScript dynamic import workaround. // Once TypeScript provides support for keeping the dynamic import this workaround can be // changed to a direct dynamic import. const GeneratorConstructor = ( await loadEsmModule<typeof import('@angular/service-worker/config')>( '@angular/service-worker/config', ) ).Generator; // Generate the manifest const generator = new GeneratorConstructor(serviceWorkerFilesystem, baseHref); const output = await generator.process(config); // Write the manifest const manifest = JSON.stringify(output, null, 2); // Find the service worker package const workerPath = require.resolve('@angular/service-worker/ngsw-worker.js'); const result = { manifest, // Main worker code assetFiles: [{ source: workerPath, destination: 'ngsw-worker.js' }], }; // If present, write the safety worker code const safetyPath = path.join(path.dirname(workerPath), 'safety-worker.js'); if (existsSync(safetyPath)) { result.assetFiles.push({ source: safetyPath, destination: 'worker-basic.min.js' }); result.assetFiles.push({ source: safetyPath, destination: 'safety-worker.js' }); } return result; }
{ "end_byte": 8094, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/service-worker.ts" }
angular-cli/packages/angular/build/src/utils/i18n-options.ts_0_6613
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import path from 'node:path'; import type { TranslationLoader } from './load-translations'; export interface LocaleDescription { files: { path: string; integrity?: string; format?: string; }[]; translation?: Record<string, unknown>; dataPath?: string; baseHref?: string; } export interface I18nOptions { inlineLocales: Set<string>; sourceLocale: string; locales: Record<string, LocaleDescription>; flatOutput?: boolean; readonly shouldInline: boolean; hasDefinedSourceLocale?: boolean; } function normalizeTranslationFileOption( option: unknown, locale: string, expectObjectInError: boolean, ): string[] { if (typeof option === 'string') { return [option]; } if (Array.isArray(option) && option.every((element) => typeof element === 'string')) { return option; } let errorMessage = `Project i18n locales translation field value for '${locale}' is malformed. `; if (expectObjectInError) { errorMessage += 'Expected a string, array of strings, or object.'; } else { errorMessage += 'Expected a string or array of strings.'; } throw new Error(errorMessage); } function ensureObject(value: unknown, name: string): asserts value is Record<string, unknown> { if (!value || typeof value !== 'object' || Array.isArray(value)) { throw new Error(`Project ${name} field is malformed. Expected an object.`); } } function ensureString(value: unknown, name: string): asserts value is string { if (typeof value !== 'string') { throw new Error(`Project ${name} field is malformed. Expected a string.`); } } export function createI18nOptions( projectMetadata: { i18n?: unknown }, inline?: boolean | string[], ): I18nOptions { const { i18n: metadata = {} } = projectMetadata; ensureObject(metadata, 'i18n'); const i18n: I18nOptions = { inlineLocales: new Set<string>(), // en-US is the default locale added to Angular applications (https://angular.dev/guide/i18n/format-data-locale) sourceLocale: 'en-US', locales: {}, get shouldInline() { return this.inlineLocales.size > 0; }, }; let rawSourceLocale; let rawSourceLocaleBaseHref; if (typeof metadata.sourceLocale === 'string') { rawSourceLocale = metadata.sourceLocale; } else if (metadata.sourceLocale !== undefined) { ensureObject(metadata.sourceLocale, 'i18n sourceLocale'); if (metadata.sourceLocale.code !== undefined) { ensureString(metadata.sourceLocale.code, 'i18n sourceLocale code'); rawSourceLocale = metadata.sourceLocale.code; } if (metadata.sourceLocale.baseHref !== undefined) { ensureString(metadata.sourceLocale.baseHref, 'i18n sourceLocale baseHref'); rawSourceLocaleBaseHref = metadata.sourceLocale.baseHref; } } if (rawSourceLocale !== undefined) { i18n.sourceLocale = rawSourceLocale; i18n.hasDefinedSourceLocale = true; } i18n.locales[i18n.sourceLocale] = { files: [], baseHref: rawSourceLocaleBaseHref, }; if (metadata.locales !== undefined) { ensureObject(metadata.locales, 'i18n locales'); for (const [locale, options] of Object.entries(metadata.locales)) { let translationFiles; let baseHref; if (options && typeof options === 'object' && 'translation' in options) { translationFiles = normalizeTranslationFileOption(options.translation, locale, false); if ('baseHref' in options) { ensureString(options.baseHref, `i18n locales ${locale} baseHref`); baseHref = options.baseHref; } } else { translationFiles = normalizeTranslationFileOption(options, locale, true); } if (locale === i18n.sourceLocale) { throw new Error( `An i18n locale ('${locale}') cannot both be a source locale and provide a translation.`, ); } i18n.locales[locale] = { files: translationFiles.map((file) => ({ path: file })), baseHref, }; } } if (inline === true) { i18n.inlineLocales.add(i18n.sourceLocale); Object.keys(i18n.locales).forEach((locale) => i18n.inlineLocales.add(locale)); } else if (inline) { for (const locale of inline) { if (!i18n.locales[locale] && i18n.sourceLocale !== locale) { throw new Error(`Requested locale '${locale}' is not defined for the project.`); } i18n.inlineLocales.add(locale); } } return i18n; } export function loadTranslations( locale: string, desc: LocaleDescription, workspaceRoot: string, loader: TranslationLoader, logger: { warn: (message: string) => void; error: (message: string) => void }, usedFormats?: Set<string>, duplicateTranslation?: 'ignore' | 'error' | 'warning', ) { let translations: Record<string, unknown> | undefined = undefined; for (const file of desc.files) { const loadResult = loader(path.join(workspaceRoot, file.path)); for (const diagnostics of loadResult.diagnostics.messages) { if (diagnostics.type === 'error') { logger.error(`Error parsing translation file '${file.path}': ${diagnostics.message}`); } else { logger.warn(`WARNING [${file.path}]: ${diagnostics.message}`); } } if (loadResult.locale !== undefined && loadResult.locale !== locale) { logger.warn( `WARNING [${file.path}]: File target locale ('${loadResult.locale}') does not match configured locale ('${locale}')`, ); } usedFormats?.add(loadResult.format); file.format = loadResult.format; file.integrity = loadResult.integrity; if (translations) { // Merge translations for (const [id, message] of Object.entries(loadResult.translations)) { if (translations[id] !== undefined) { const duplicateTranslationMessage = `[${file.path}]: Duplicate translations for message '${id}' when merging.`; switch (duplicateTranslation) { case 'ignore': break; case 'error': logger.error(`ERROR ${duplicateTranslationMessage}`); break; case 'warning': default: logger.warn(`WARNING ${duplicateTranslationMessage}`); break; } } translations[id] = message; } } else { // First or only translation file translations = loadResult.translations; } } desc.translation = translations; }
{ "end_byte": 6613, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/i18n-options.ts" }
angular-cli/packages/angular/build/src/utils/supported-browsers.ts_0_1487
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import browserslist from 'browserslist'; export function getSupportedBrowsers( projectRoot: string, logger: { warn(message: string): void }, ): string[] { browserslist.defaults = [ 'last 2 Chrome versions', 'last 1 Firefox version', 'last 2 Edge major versions', 'last 2 Safari major versions', 'last 2 iOS major versions', 'last 2 Android major versions', 'Firefox ESR', ]; // Get browsers from config or default. const browsersFromConfigOrDefault = new Set(browserslist(undefined, { path: projectRoot })); // Get browsers that support ES6 modules. const browsersThatSupportEs6 = new Set(browserslist('supports es6-module')); const unsupportedBrowsers: string[] = []; for (const browser of browsersFromConfigOrDefault) { if (!browsersThatSupportEs6.has(browser)) { browsersFromConfigOrDefault.delete(browser); unsupportedBrowsers.push(browser); } } if (unsupportedBrowsers.length) { logger.warn( `One or more browsers which are configured in the project's Browserslist configuration ` + 'will be ignored as ES5 output is not supported by the Angular CLI.\n' + `Ignored browsers: ${unsupportedBrowsers.join(', ')}`, ); } return Array.from(browsersFromConfigOrDefault); }
{ "end_byte": 1487, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/supported-browsers.ts" }
angular-cli/packages/angular/build/src/utils/url.ts_0_485
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export function urlJoin(...parts: string[]): string { const [p, ...rest] = parts; // Remove trailing slash from first part // Join all parts with `/` // Dedupe double slashes from path names return p.replace(/\/$/, '') + ('/' + rest.join('/')).replace(/\/\/+/g, '/'); }
{ "end_byte": 485, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/url.ts" }
angular-cli/packages/angular/build/src/utils/bundle-calculator_spec.ts_0_7972
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { BudgetEntry, BudgetType, ThresholdSeverity, checkBudgets } from './bundle-calculator'; const kB = 1000; describe('bundle-calculator', () => { describe('checkBudgets()', () => { it('yields maximum budgets exceeded', () => { const budgets: BudgetEntry[] = [ { type: BudgetType.Any, maximumError: '1kb', }, ]; const stats = { chunks: [], assets: [ { name: 'foo.js', size: 1.5 * kB, }, { name: 'bar.js', size: 0.5 * kB, }, ], }; const failures = Array.from(checkBudgets(budgets, stats)); expect(failures.length).toBe(1); expect(failures).toContain({ severity: ThresholdSeverity.Error, label: 'foo.js', message: jasmine.stringMatching('foo.js exceeded maximum budget.'), }); }); it('yields minimum budgets exceeded', () => { const budgets: BudgetEntry[] = [ { type: BudgetType.Any, minimumError: '1kb', }, ]; const stats = { chunks: [], assets: [ { name: 'foo.js', size: 1.5 * kB, }, { name: 'bar.js', size: 0.5 * kB, }, ], }; const failures = Array.from(checkBudgets(budgets, stats)); expect(failures.length).toBe(1); expect(failures).toContain({ severity: ThresholdSeverity.Error, label: 'bar.js', message: jasmine.stringMatching('bar.js failed to meet minimum budget.'), }); }); it('yields exceeded bundle budgets', () => { const budgets: BudgetEntry[] = [ { type: BudgetType.Bundle, name: 'foo', maximumError: '1kb', }, ]; const stats = { chunks: [ { id: 0, names: ['foo'], files: ['foo.js', 'bar.js'], }, ], assets: [ { name: 'foo.js', size: 0.75 * kB, }, { name: 'bar.js', size: 0.75 * kB, }, ], }; const failures = Array.from(checkBudgets(budgets, stats)); expect(failures.length).toBe(1); expect(failures).toContain({ severity: ThresholdSeverity.Error, label: 'foo', message: jasmine.stringMatching('foo exceeded maximum budget.'), }); }); it('yields exceeded initial budget', () => { const budgets: BudgetEntry[] = [ { type: BudgetType.Initial, maximumError: '1kb', }, ]; const stats = { chunks: [ { id: 0, initial: true, names: ['foo'], files: ['foo.js', 'bar.js'], }, ], assets: [ { name: 'foo.js', size: 0.5 * kB, }, { name: 'bar.js', size: 0.75 * kB, }, ], }; const failures = Array.from(checkBudgets(budgets, stats)); expect(failures.length).toBe(1); expect(failures).toContain({ severity: ThresholdSeverity.Error, label: 'bundle initial', message: jasmine.stringMatching('initial exceeded maximum budget.'), }); }); it('yields exceeded total scripts budget', () => { const budgets: BudgetEntry[] = [ { type: BudgetType.AllScript, maximumError: '1kb', }, ]; const stats = { chunks: [ { id: 0, initial: true, names: ['foo'], files: ['foo.js', 'bar.js'], }, ], assets: [ { name: 'foo.js', size: 0.75 * kB, }, { name: 'bar.js', size: 0.75 * kB, }, { name: 'baz.css', size: 1.5 * kB, }, ], }; const failures = Array.from(checkBudgets(budgets, stats)); expect(failures.length).toBe(1); expect(failures).toContain({ severity: ThresholdSeverity.Error, label: 'total scripts', message: jasmine.stringMatching('total scripts exceeded maximum budget.'), }); }); it('yields exceeded total budget', () => { const budgets: BudgetEntry[] = [ { type: BudgetType.All, maximumError: '1kb', }, ]; const stats = { chunks: [ { id: 0, initial: true, names: ['foo'], files: ['foo.js', 'bar.css'], }, ], assets: [ { name: 'foo.js', size: 0.75 * kB, }, { name: 'bar.css', size: 0.75 * kB, }, ], }; const failures = Array.from(checkBudgets(budgets, stats)); expect(failures.length).toBe(1); expect(failures).toContain({ severity: ThresholdSeverity.Error, label: 'total', message: jasmine.stringMatching('total exceeded maximum budget.'), }); }); it('skips component style budgets', () => { const budgets: BudgetEntry[] = [ { type: BudgetType.AnyComponentStyle, maximumError: '1kb', }, ]; const stats = { chunks: [ { id: 0, initial: true, names: ['foo'], files: ['foo.css', 'bar.js'], }, ], assets: [ { name: 'foo.css', size: 1.5 * kB, }, { name: 'bar.js', size: 0.5 * kB, }, ], }; const failures = Array.from(checkBudgets(budgets, stats)); expect(failures.length).toBe(0); }); it('yields exceeded individual script budget', () => { const budgets: BudgetEntry[] = [ { type: BudgetType.AnyScript, maximumError: '1kb', }, ]; const stats = { chunks: [ { id: 0, initial: true, names: ['foo'], files: ['foo.js', 'bar.js'], }, ], assets: [ { name: 'foo.js', size: 1.5 * kB, }, { name: 'bar.js', size: 0.5 * kB, }, ], }; const failures = Array.from(checkBudgets(budgets, stats)); expect(failures.length).toBe(1); expect(failures).toContain({ severity: ThresholdSeverity.Error, label: 'foo.js', message: jasmine.stringMatching('foo.js exceeded maximum budget.'), }); }); it('yields exceeded individual file budget', () => { const budgets: BudgetEntry[] = [ { type: BudgetType.Any, maximumError: '1kb', }, ]; const stats = { chunks: [ { id: 0, initial: true, names: ['foo'], files: ['foo.ext', 'bar.ext'], }, ], assets: [ { name: 'foo.ext', size: 1.5 * kB, }, { name: 'bar.ext', size: 0.5 * kB, }, ], }; const failures = Array.from(checkBudgets(budgets, stats)); expect(failures.length).toBe(1); expect(failures).toContain({ severity: ThresholdSeverity.Error, label: 'foo.ext', message: jasmine.stringMatching('foo.ext exceeded maximum budget.'), }); }); }); });
{ "end_byte": 7972, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/bundle-calculator_spec.ts" }
angular-cli/packages/angular/build/src/utils/normalize-optimization.ts_0_1410
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { FontsClass, OptimizationClass, OptimizationUnion, StylesClass, } from '../builders/application/schema'; export type NormalizedOptimizationOptions = Required< Omit<OptimizationClass, 'fonts' | 'styles'> > & { fonts: FontsClass; styles: StylesClass; }; export function normalizeOptimization( optimization: OptimizationUnion = true, ): NormalizedOptimizationOptions { if (typeof optimization === 'object') { const styleOptimization = !!optimization.styles; return { scripts: !!optimization.scripts, styles: typeof optimization.styles === 'object' ? optimization.styles : { minify: styleOptimization, removeSpecialComments: styleOptimization, inlineCritical: styleOptimization, }, fonts: typeof optimization.fonts === 'object' ? optimization.fonts : { inline: !!optimization.fonts, }, }; } return { scripts: optimization, styles: { minify: optimization, inlineCritical: optimization, removeSpecialComments: optimization, }, fonts: { inline: optimization, }, }; }
{ "end_byte": 1410, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/normalize-optimization.ts" }
angular-cli/packages/angular/build/src/utils/resolve-assets.ts_0_1224
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import glob from 'fast-glob'; import path from 'node:path'; export async function resolveAssets( entries: { glob: string; ignore?: string[]; input: string; output: string; flatten?: boolean; followSymlinks?: boolean; }[], root: string, ): Promise<{ source: string; destination: string }[]> { const defaultIgnore = ['.gitkeep', '**/.DS_Store', '**/Thumbs.db']; const outputFiles: { source: string; destination: string }[] = []; for (const entry of entries) { const cwd = path.resolve(root, entry.input); const files = await glob(entry.glob, { cwd, dot: true, ignore: entry.ignore ? defaultIgnore.concat(entry.ignore) : defaultIgnore, followSymbolicLinks: entry.followSymlinks, }); for (const file of files) { const src = path.join(cwd, file); const filePath = entry.flatten ? path.basename(file) : file; outputFiles.push({ source: src, destination: path.join(entry.output, filePath) }); } } return outputFiles; }
{ "end_byte": 1224, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/resolve-assets.ts" }
angular-cli/packages/angular/build/src/utils/worker-pool.ts_0_1574
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { getCompileCacheDir } from 'node:module'; import { Piscina } from 'piscina'; export type WorkerPoolOptions = ConstructorParameters<typeof Piscina>[0]; export class WorkerPool extends Piscina { constructor(options: WorkerPoolOptions) { const piscinaOptions: WorkerPoolOptions = { minThreads: 1, idleTimeout: 1000, // Web containers do not support transferable objects with receiveOnMessagePort which // is used when the Atomics based wait loop is enable. useAtomics: !process.versions.webcontainer, recordTiming: false, ...options, }; // Enable compile code caching if enabled for the main process (only exists on Node.js v22.8+). // Skip if running inside Bazel via a RUNFILES environment variable check. The cache does not work // well with Bazel's hermeticity requirements. const compileCacheDirectory = process.env['RUNFILES'] ? undefined : getCompileCacheDir?.(); if (compileCacheDirectory) { if (typeof piscinaOptions.env === 'object') { piscinaOptions.env['NODE_COMPILE_CACHE'] = compileCacheDirectory; } else { // Default behavior of `env` option is to copy current process values piscinaOptions.env = { ...process.env, 'NODE_COMPILE_CACHE': compileCacheDirectory, }; } } super(piscinaOptions); } }
{ "end_byte": 1574, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/worker-pool.ts" }
angular-cli/packages/angular/build/src/utils/normalize-cache.ts_0_1959
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { join, resolve } from 'node:path'; /** Version placeholder is replaced during the build process with actual package version */ const VERSION = '0.0.0-PLACEHOLDER'; export interface NormalizedCachedOptions { /** Whether disk cache is enabled. */ enabled: boolean; /** Disk cache path. Example: `/.angular/cache/v12.0.0`. */ path: string; /** Disk cache base path. Example: `/.angular/cache`. */ basePath: string; } interface CacheMetadata { enabled?: boolean; environment?: 'local' | 'ci' | 'all'; path?: string; } function hasCacheMetadata(value: unknown): value is { cli: { cache: CacheMetadata } } { return ( !!value && typeof value === 'object' && 'cli' in value && !!value['cli'] && typeof value['cli'] === 'object' && 'cache' in value['cli'] ); } export function normalizeCacheOptions( projectMetadata: unknown, worspaceRoot: string, ): NormalizedCachedOptions { const cacheMetadata = hasCacheMetadata(projectMetadata) ? projectMetadata.cli.cache : {}; const { // Webcontainers do not currently benefit from persistent disk caching and can lead to increased browser memory usage enabled = !process.versions.webcontainer, environment = 'local', path = '.angular/cache', } = cacheMetadata; const isCI = process.env['CI'] === '1' || process.env['CI']?.toLowerCase() === 'true'; let cacheEnabled = enabled; if (cacheEnabled) { switch (environment) { case 'ci': cacheEnabled = isCI; break; case 'local': cacheEnabled = !isCI; break; } } const cacheBasePath = resolve(worspaceRoot, path); return { enabled: cacheEnabled, basePath: cacheBasePath, path: join(cacheBasePath, VERSION), }; }
{ "end_byte": 1959, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/normalize-cache.ts" }
angular-cli/packages/angular/build/src/utils/index.ts_0_368
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export * from './normalize-asset-patterns'; export * from './normalize-optimization'; export * from './normalize-source-maps'; export * from './load-proxy-config';
{ "end_byte": 368, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index.ts" }
angular-cli/packages/angular/build/src/utils/load-proxy-config.ts_0_6206
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { isDynamicPattern } from 'fast-glob'; import { existsSync } from 'node:fs'; import { readFile } from 'node:fs/promises'; import { extname, resolve } from 'node:path'; import { pathToFileURL } from 'node:url'; import { makeRe as makeRegExpFromGlob } from 'picomatch'; import { assertIsError } from './error'; import { loadEsmModule } from './load-esm'; export async function loadProxyConfiguration( root: string, proxyConfig: string | undefined, ): Promise<Record<string, object> | undefined> { if (!proxyConfig) { return undefined; } const proxyPath = resolve(root, proxyConfig); if (!existsSync(proxyPath)) { throw new Error(`Proxy configuration file ${proxyPath} does not exist.`); } let proxyConfiguration; switch (extname(proxyPath)) { case '.json': { const content = await readFile(proxyPath, 'utf-8'); const { parse, printParseErrorCode } = await import('jsonc-parser'); const parseErrors: import('jsonc-parser').ParseError[] = []; proxyConfiguration = parse(content, parseErrors, { allowTrailingComma: true }); if (parseErrors.length > 0) { let errorMessage = `Proxy configuration file ${proxyPath} contains parse errors:`; for (const parseError of parseErrors) { const { line, column } = getJsonErrorLineColumn(parseError.offset, content); errorMessage += `\n[${line}, ${column}] ${printParseErrorCode(parseError.error)}`; } throw new Error(errorMessage); } break; } case '.mjs': // Load the ESM configuration file using the TypeScript dynamic import workaround. // Once TypeScript provides support for keeping the dynamic import this workaround can be // changed to a direct dynamic import. proxyConfiguration = (await loadEsmModule<{ default: unknown }>(pathToFileURL(proxyPath))) .default; break; case '.cjs': proxyConfiguration = require(proxyPath); break; default: // The file could be either CommonJS or ESM. // CommonJS is tried first then ESM if loading fails. try { proxyConfiguration = require(proxyPath); break; } catch (e) { assertIsError(e); if (e.code === 'ERR_REQUIRE_ESM') { // Load the ESM configuration file using the TypeScript dynamic import workaround. // Once TypeScript provides support for keeping the dynamic import this workaround can be // changed to a direct dynamic import. proxyConfiguration = (await loadEsmModule<{ default: unknown }>(pathToFileURL(proxyPath))) .default; break; } throw e; } } return normalizeProxyConfiguration(proxyConfiguration); } /** * Converts glob patterns to regular expressions to support Vite's proxy option. * Also converts the Webpack supported array form to an object form supported by both. * * @param proxy A proxy configuration object. */ function normalizeProxyConfiguration( proxy: Record<string, object> | object[], ): Record<string, object> { let normalizedProxy: Record<string, object> | undefined; if (Array.isArray(proxy)) { // Construct an object-form proxy configuration from the array normalizedProxy = {}; for (const proxyEntry of proxy) { if (!('context' in proxyEntry)) { continue; } if (!Array.isArray(proxyEntry.context)) { continue; } // Array-form entries contain a context string array with the path(s) // to use for the configuration entry. const context = proxyEntry.context; delete proxyEntry.context; for (const contextEntry of context) { if (typeof contextEntry !== 'string') { continue; } normalizedProxy[contextEntry] = proxyEntry; } } } else { normalizedProxy = proxy; } // TODO: Consider upstreaming glob support for (const key of Object.keys(normalizedProxy)) { if (key[0] !== '^' && isDynamicPattern(key)) { const pattern = makeRegExpFromGlob(key).source; normalizedProxy[pattern] = normalizedProxy[key]; delete normalizedProxy[key]; } } // Replace `pathRewrite` field with a `rewrite` function for (const proxyEntry of Object.values(normalizedProxy)) { if ( typeof proxyEntry === 'object' && '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<string, string>, )) { pathRewriteEntries.push([new RegExp(pattern), value]); } (proxyEntry as Record<string, unknown>).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. * @param content The full content of the file containing the error. * @returns An object containing the line and column */ function getJsonErrorLineColumn(offset: number, content: string) { if (offset === 0) { return { line: 1, column: 1 }; } let line = 0; let position = 0; // eslint-disable-next-line no-constant-condition while (true) { ++line; const nextNewline = content.indexOf('\n', position); if (nextNewline === -1 || nextNewline > offset) { break; } position = nextNewline + 1; } return { line, column: offset - position + 1 }; }
{ "end_byte": 6206, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/load-proxy-config.ts" }
angular-cli/packages/angular/build/src/utils/check-port.ts_0_1940
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import assert from 'node:assert'; import { createServer } from 'node:net'; import { isTTY } from './tty'; function createInUseError(port: number): Error { return new Error(`Port ${port} is already in use. Use '--port' to specify a different port.`); } export async function checkPort(port: number, host: string): Promise<number> { // Disabled due to Vite not handling port 0 and instead always using the default value (5173) // TODO: Enable this again once Vite is fixed // if (port === 0) { // return 0; // } return new Promise<number>((resolve, reject) => { const server = createServer(); server .once('error', (err: NodeJS.ErrnoException) => { if (err.code !== 'EADDRINUSE') { reject(err); return; } if (!isTTY) { reject(createInUseError(port)); return; } import('@inquirer/confirm') .then(({ default: confirm }) => confirm({ message: `Port ${port} is already in use.\nWould you like to use a different port?`, default: true, theme: { prefix: '' }, }), ) .then( (answer) => (answer ? resolve(checkPort(0, host)) : reject(createInUseError(port))), () => reject(createInUseError(port)), ); }) .once('listening', () => { // Get the actual address from the listening server instance const address = server.address(); assert( address && typeof address !== 'string', 'Port check server address should always be an object.', ); server.close(); resolve(address.port); }) .listen(port, host); }); }
{ "end_byte": 1940, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/check-port.ts" }
angular-cli/packages/angular/build/src/utils/version.ts_0_2688
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /* eslint-disable no-console */ import { createRequire } from 'node:module'; import { SemVer, satisfies } from 'semver'; export function assertCompatibleAngularVersion(projectRoot: string): void | never { let angularCliPkgJson; let angularPkgJson; // Create a custom require function for ESM compliance. // NOTE: The trailing slash is significant. const projectRequire = createRequire(projectRoot + '/'); try { const angularPackagePath = projectRequire.resolve('@angular/core/package.json'); angularPkgJson = projectRequire(angularPackagePath); } catch { console.error('You seem to not be depending on "@angular/core". This is an error.'); process.exit(2); } if (!(angularPkgJson && angularPkgJson['version'])) { console.error( 'Cannot determine versions of "@angular/core".\n' + 'This likely means your local installation is broken. Please reinstall your packages.', ); process.exit(2); } try { const angularCliPkgPath = projectRequire.resolve('@angular/cli/package.json'); angularCliPkgJson = projectRequire(angularCliPkgPath); if (!(angularCliPkgJson && angularCliPkgJson['version'])) { return; } } catch { // Not using @angular-devkit/build-angular with @angular/cli is ok too. // In this case we don't provide as many version checks. return; } if (angularCliPkgJson['version'] === '0.0.0' || angularPkgJson['version'] === '0.0.0') { // Internal CLI testing version or integration testing in the angular/angular // repository with the generated development @angular/core npm package which is versioned "0.0.0". return; } let supportedAngularSemver; try { supportedAngularSemver = projectRequire('@angular/build/package.json')['peerDependencies'][ '@angular/compiler-cli' ]; } catch { supportedAngularSemver = projectRequire('@angular-devkit/build-angular/package.json')[ 'peerDependencies' ]['@angular/compiler-cli']; } const angularVersion = new SemVer(angularPkgJson['version']); if (!satisfies(angularVersion, supportedAngularSemver, { includePrerelease: true })) { console.error( `This version of CLI is only compatible with Angular versions ${supportedAngularSemver},\n` + `but Angular version ${angularVersion} was found instead.\n` + 'Please visit the link below to find instructions on how to update Angular.\nhttps://update.angular.dev/', ); process.exit(3); } }
{ "end_byte": 2688, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/version.ts" }
angular-cli/packages/angular/build/src/utils/error.ts_0_597
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import assert from 'assert'; export function assertIsError(value: unknown): asserts value is Error & { code?: string } { const isError = value instanceof Error || // The following is needing to identify errors coming from RxJs. (typeof value === 'object' && value && 'name' in value && 'message' in value); assert(isError, 'catch clause variable is not an Error instance'); }
{ "end_byte": 597, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/error.ts" }
angular-cli/packages/angular/build/src/utils/color.ts_0_718
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { WriteStream } from 'node:tty'; export { color as colors, figures } from 'listr2'; export function supportColor(stream: NodeJS.WritableStream = process.stdout): boolean { if (stream instanceof WriteStream) { return stream.hasColors(); } try { // The hasColors function does not rely on any instance state and should ideally be static return WriteStream.prototype.hasColors(); } catch { return process.env['FORCE_COLOR'] !== undefined && process.env['FORCE_COLOR'] !== '0'; } }
{ "end_byte": 718, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/color.ts" }
angular-cli/packages/angular/build/src/utils/tty.ts_0_674
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ function _isTruthy(value: undefined | string): boolean { // Returns true if value is a string that is anything but 0 or false. return value !== undefined && value !== '0' && value.toUpperCase() !== 'FALSE'; } export function isTTY(): boolean { // If we force TTY, we always return true. const force = process.env['NG_FORCE_TTY']; if (force !== undefined) { return _isTruthy(force); } return !!process.stdout.isTTY && !_isTruthy(process.env['CI']); }
{ "end_byte": 674, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/tty.ts" }
angular-cli/packages/angular/build/src/utils/delete-output-dir.ts_0_1594
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { readdir, rm } from 'node:fs/promises'; import { join, resolve } from 'node:path'; /** * Delete an output directory, but error out if it's the root of the project. */ export async function deleteOutputDir( root: string, outputPath: string, emptyOnlyDirectories?: string[], ): Promise<void> { const resolvedOutputPath = resolve(root, outputPath); if (resolvedOutputPath === root) { throw new Error('Output path MUST not be project root directory!'); } const directoriesToEmpty = emptyOnlyDirectories ? new Set(emptyOnlyDirectories.map((directory) => join(resolvedOutputPath, directory))) : undefined; // Avoid removing the actual directory to avoid errors in cases where the output // directory is mounted or symlinked. Instead the contents are removed. let entries; try { entries = await readdir(resolvedOutputPath); } catch (error) { if (error instanceof Error && 'code' in error && error.code === 'ENOENT') { return; } throw error; } for (const entry of entries) { const fullEntry = join(resolvedOutputPath, entry); // Leave requested directories. This allows symlinks to continue to function. if (directoriesToEmpty?.has(fullEntry)) { await deleteOutputDir(resolvedOutputPath, fullEntry); continue; } await rm(fullEntry, { force: true, recursive: true, maxRetries: 3 }); } }
{ "end_byte": 1594, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/delete-output-dir.ts" }
angular-cli/packages/angular/build/src/utils/load-esm.ts_0_1203
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** * Lazily compiled dynamic import loader function. */ let load: (<T>(modulePath: string | URL) => Promise<T>) | undefined; /** * This uses a dynamic import to load a module which may be ESM. * CommonJS code can load ESM code via a dynamic import. Unfortunately, TypeScript * will currently, unconditionally downlevel dynamic import into a require call. * require calls cannot load ESM code and will result in a runtime error. To workaround * this, a Function constructor is used to prevent TypeScript from changing the dynamic import. * Once TypeScript provides support for keeping the dynamic import this workaround can * be dropped. * * @param modulePath The path of the module to load. * @returns A Promise that resolves to the dynamically imported module. */ export function loadEsmModule<T>(modulePath: string | URL): Promise<T> { load ??= new Function('modulePath', `return import(modulePath);`) as Exclude< typeof load, undefined >; return load(modulePath); }
{ "end_byte": 1203, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/load-esm.ts" }
angular-cli/packages/angular/build/src/utils/load-translations.ts_0_2903
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import type { Diagnostics } from '@angular/localize/tools'; import { createHash } from 'crypto'; import * as fs from 'fs'; import { loadEsmModule } from './load-esm'; export type TranslationLoader = (path: string) => { translations: Record<string, import('@angular/localize').ɵParsedTranslation>; format: string; locale?: string; diagnostics: Diagnostics; integrity: string; }; export async function createTranslationLoader(): Promise<TranslationLoader> { const { parsers, diagnostics } = await importParsers(); return (path: string) => { const content = fs.readFileSync(path, 'utf8'); const unusedParsers = new Map(); for (const [format, parser] of Object.entries(parsers)) { const analysis = parser.analyze(path, content); if (analysis.canParse) { // Types don't overlap here so we need to use any. // eslint-disable-next-line @typescript-eslint/no-explicit-any const { locale, translations } = parser.parse(path, content, analysis.hint as any); const integrity = 'sha256-' + createHash('sha256').update(content).digest('base64'); return { format, locale, translations, diagnostics, integrity }; } else { unusedParsers.set(parser, analysis); } } const messages: string[] = []; for (const [parser, analysis] of unusedParsers.entries()) { messages.push(analysis.diagnostics.formatDiagnostics(`*** ${parser.constructor.name} ***`)); } throw new Error( `Unsupported translation file format in ${path}. The following parsers were tried:\n` + messages.join('\n'), ); }; } async function importParsers() { try { // Load ESM `@angular/localize/tools` using the TypeScript dynamic import workaround. // Once TypeScript provides support for keeping the dynamic import this workaround can be // changed to a direct dynamic import. const { Diagnostics, ArbTranslationParser, SimpleJsonTranslationParser, Xliff1TranslationParser, Xliff2TranslationParser, XtbTranslationParser, } = await loadEsmModule<typeof import('@angular/localize/tools')>('@angular/localize/tools'); const diagnostics = new Diagnostics(); const parsers = { arb: new ArbTranslationParser(), json: new SimpleJsonTranslationParser(), xlf: new Xliff1TranslationParser(), xlf2: new Xliff2TranslationParser(), // The name ('xmb') needs to match the AOT compiler option xmb: new XtbTranslationParser(), }; return { parsers, diagnostics }; } catch { throw new Error( `Unable to load translation file parsers. Please ensure '@angular/localize' is installed.`, ); } }
{ "end_byte": 2903, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/load-translations.ts" }
angular-cli/packages/angular/build/src/utils/normalize-asset-patterns.ts_0_2660
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { statSync } from 'fs'; import assert from 'node:assert'; import * as path from 'path'; import { AssetPattern, AssetPatternClass } from '../builders/application/schema'; export class MissingAssetSourceRootException extends Error { constructor(path: string) { super(`The ${path} asset path must start with the project source root.`); } } export function normalizeAssetPatterns( assetPatterns: AssetPattern[], workspaceRoot: string, projectRoot: string, projectSourceRoot: string | undefined, ): (AssetPatternClass & { output: string })[] { if (assetPatterns.length === 0) { return []; } // When sourceRoot is not available, we default to ${projectRoot}/src. const sourceRoot = projectSourceRoot || path.join(projectRoot, 'src'); const resolvedSourceRoot = path.resolve(workspaceRoot, sourceRoot); return assetPatterns.map((assetPattern) => { // Normalize string asset patterns to objects. if (typeof assetPattern === 'string') { const assetPath = path.normalize(assetPattern); const resolvedAssetPath = path.resolve(workspaceRoot, assetPath); // Check if the string asset is within sourceRoot. if (!resolvedAssetPath.startsWith(resolvedSourceRoot)) { throw new MissingAssetSourceRootException(assetPattern); } let glob: string, input: string; let isDirectory = false; try { isDirectory = statSync(resolvedAssetPath).isDirectory(); } catch { isDirectory = true; } if (isDirectory) { // Folders get a recursive star glob. glob = '**/*'; // Input directory is their original path. input = assetPath; } else { // Files are their own glob. glob = path.basename(assetPath); // Input directory is their original dirname. input = path.dirname(assetPath); } // Output directory for both is the relative path from source root to input. const output = path.relative(resolvedSourceRoot, path.resolve(workspaceRoot, input)); assetPattern = { glob, input, output }; } else { assetPattern.output = path.join('.', assetPattern.output ?? ''); } assert(assetPattern.output !== undefined); if (assetPattern.output.startsWith('..')) { throw new Error('An asset cannot be written to a location outside of the output path.'); } return assetPattern as AssetPatternClass & { output: string }; }); }
{ "end_byte": 2660, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/normalize-asset-patterns.ts" }
angular-cli/packages/angular/build/src/utils/index-file/add-event-dispatch-contract_spec.ts_0_709
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { addEventDispatchContract } from './add-event-dispatch-contract'; describe('addEventDispatchContract', () => { it('should inline event dispatcher script', async () => { const result = await addEventDispatchContract(` <html> <head></head> <body> <h1>Hello World!</h1> </body> </html> `); expect(result).toMatch( /<body>\s*<script type="text\/javascript" id="ng-event-dispatch-contract">[\s\S]+<\/script>\s*<h1>/, ); }); });
{ "end_byte": 709, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/add-event-dispatch-contract_spec.ts" }
angular-cli/packages/angular/build/src/utils/index-file/ngcm-attribute.ts_0_1383
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { htmlRewritingStream } from './html-rewriting-stream'; /** * Defines a name of an attribute that is added to the `<body>` tag * in the `index.html` file in case a given route was configured * with `RenderMode.Client`. 'cm' is an abbreviation for "Client Mode". * * @see https://github.com/angular/angular/pull/58004 */ const CLIENT_RENDER_MODE_FLAG = 'ngcm'; /** * Transforms the provided HTML by adding the `ngcm` attribute to the `<body>` tag. * This is used in the client-side rendered (CSR) version of `index.html` to prevent hydration warnings. * * @param html The HTML markup to be transformed. * @returns A promise that resolves to the transformed HTML string with the necessary modifications. */ export async function addNgcmAttribute(html: string): Promise<string> { const { rewriter, transformedContent } = await htmlRewritingStream(html); rewriter.on('startTag', (tag) => { if ( tag.tagName === 'body' && !tag.attrs.some((attr) => attr.name === CLIENT_RENDER_MODE_FLAG) ) { tag.attrs.push({ name: CLIENT_RENDER_MODE_FLAG, value: '' }); } rewriter.emitStartTag(tag); }); return transformedContent(); }
{ "end_byte": 1383, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/ngcm-attribute.ts" }
angular-cli/packages/angular/build/src/utils/index-file/html-rewriting-stream.ts_0_1279
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import type { RewritingStream } from 'parse5-html-rewriting-stream'; import { loadEsmModule } from '../load-esm'; // Export helper types for the rewriter export type StartTag = Parameters<RewritingStream['emitStartTag']>[0]; export type EndTag = Parameters<RewritingStream['emitEndTag']>[0]; export type { RewritingStream }; export async function htmlRewritingStream(content: string): Promise<{ rewriter: RewritingStream; transformedContent: () => Promise<string>; }> { const { RewritingStream } = await loadEsmModule<typeof import('parse5-html-rewriting-stream')>( 'parse5-html-rewriting-stream', ); const rewriter = new RewritingStream(); return { rewriter, transformedContent: () => pipeline(Readable.from(content), rewriter, async function (source) { const chunks = []; for await (const chunk of source) { chunks.push(Buffer.from(chunk)); } return Buffer.concat(chunks).toString('utf-8'); }), }; }
{ "end_byte": 1279, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/html-rewriting-stream.ts" }
angular-cli/packages/angular/build/src/utils/index-file/nonce.ts_0_1833
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { htmlRewritingStream } from './html-rewriting-stream'; /** * Pattern matching the name of the Angular nonce attribute. Note that this is * case-insensitive, because HTML attribute names are case-insensitive as well. */ const NONCE_ATTR_PATTERN = /ngCspNonce/i; /** * Finds the `ngCspNonce` value and copies it to all inline `<style>` and `<script> `tags. * @param html Markup that should be processed. */ export async function addNonce(html: string): Promise<string> { const nonce = await findNonce(html); if (!nonce) { return html; } const { rewriter, transformedContent } = await htmlRewritingStream(html); rewriter.on('startTag', (tag) => { if ( (tag.tagName === 'style' || tag.tagName === 'script') && !tag.attrs.some((attr) => attr.name === 'nonce') ) { tag.attrs.push({ name: 'nonce', value: nonce }); } rewriter.emitStartTag(tag); }); return transformedContent(); } /** Finds the Angular nonce in an HTML string. */ async function findNonce(html: string): Promise<string | null> { // Inexpensive check to avoid parsing the HTML when we're sure there's no nonce. if (!NONCE_ATTR_PATTERN.test(html)) { return null; } const { rewriter, transformedContent } = await htmlRewritingStream(html); let nonce: string | null = null; rewriter.on('startTag', (tag) => { const nonceAttr = tag.attrs.find((attr) => NONCE_ATTR_PATTERN.test(attr.name)); if (nonceAttr?.value) { nonce = nonceAttr.value; rewriter.stop(); // Stop parsing since we've found the nonce. } }); await transformedContent(); return nonce; }
{ "end_byte": 1833, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/nonce.ts" }
angular-cli/packages/angular/build/src/utils/index-file/augment-index-html.ts_0_1849
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { createHash } from 'node:crypto'; import { extname } from 'node:path'; import { loadEsmModule } from '../load-esm'; import { htmlRewritingStream } from './html-rewriting-stream'; import { VALID_SELF_CLOSING_TAGS } from './valid-self-closing-tags'; export type LoadOutputFileFunctionType = (file: string) => Promise<string>; export type CrossOriginValue = 'none' | 'anonymous' | 'use-credentials'; export type Entrypoint = [name: string, isModule: boolean]; export interface AugmentIndexHtmlOptions { /* Input contents */ html: string; baseHref?: string; deployUrl?: string; sri: boolean; /** crossorigin attribute setting of elements that provide CORS support */ crossOrigin?: CrossOriginValue; /* * Files emitted by the build. */ files: FileInfo[]; /* * Function that loads a file used. * This allows us to use different routines within the IndexHtmlWebpackPlugin and * when used without this plugin. */ loadOutputFile: LoadOutputFileFunctionType; /** Used to sort the inseration of files in the HTML file */ entrypoints: Entrypoint[]; /** Used to set the document default locale */ lang?: string; hints?: { url: string; mode: string; as?: string }[]; imageDomains?: string[]; } export interface FileInfo { file: string; name?: string; extension: string; } /* * Helper function used by the IndexHtmlWebpackPlugin. * Can also be directly used by builder, e. g. in order to generate an index.html * after processing several configurations in order to build different sets of * bundles for differential serving. */ // eslint-disable-next-line max-lines-per-function
{ "end_byte": 1849, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/augment-index-html.ts" }
angular-cli/packages/angular/build/src/utils/index-file/augment-index-html.ts_1850_9787
export async function augmentIndexHtml( params: AugmentIndexHtmlOptions, ): Promise<{ content: string; warnings: string[]; errors: string[] }> { const { loadOutputFile, files, entrypoints, sri, deployUrl = '', lang, baseHref, html, imageDomains, } = params; const warnings: string[] = []; const errors: string[] = []; let { crossOrigin = 'none' } = params; if (sri && crossOrigin === 'none') { crossOrigin = 'anonymous'; } const stylesheets = new Set<string>(); const scripts = new Map</** file name */ string, /** isModule */ boolean>(); // Sort files in the order we want to insert them by entrypoint for (const [entrypoint, isModule] of entrypoints) { for (const { extension, file, name } of files) { if (name !== entrypoint || scripts.has(file) || stylesheets.has(file)) { continue; } switch (extension) { case '.js': // Also, non entrypoints need to be loaded as no module as they can contain problematic code. scripts.set(file, isModule); break; case '.mjs': if (!isModule) { // It would be very confusing to link an `*.mjs` file in a non-module script context, // so we disallow it entirely. throw new Error('`.mjs` files *must* set `isModule` to `true`.'); } scripts.set(file, true /* isModule */); break; case '.css': stylesheets.add(file); break; } } } let scriptTags: string[] = []; for (const [src, isModule] of scripts) { const attrs = [`src="${deployUrl}${src}"`]; // This is also need for non entry-points as they may contain problematic code. if (isModule) { attrs.push('type="module"'); } else { attrs.push('defer'); } if (crossOrigin !== 'none') { attrs.push(`crossorigin="${crossOrigin}"`); } if (sri) { const content = await loadOutputFile(src); attrs.push(generateSriAttributes(content)); } scriptTags.push(`<script ${attrs.join(' ')}></script>`); } let headerLinkTags: string[] = []; let bodyLinkTags: string[] = []; for (const src of stylesheets) { const attrs = [`rel="stylesheet"`, `href="${deployUrl}${src}"`]; if (crossOrigin !== 'none') { attrs.push(`crossorigin="${crossOrigin}"`); } if (sri) { const content = await loadOutputFile(src); attrs.push(generateSriAttributes(content)); } headerLinkTags.push(`<link ${attrs.join(' ')}>`); } if (params.hints?.length) { for (const hint of params.hints) { const attrs = [`rel="${hint.mode}"`, `href="${deployUrl}${hint.url}"`]; if (hint.mode !== 'modulepreload' && crossOrigin !== 'none') { // Value is considered anonymous by the browser when not present or empty attrs.push(crossOrigin === 'anonymous' ? 'crossorigin' : `crossorigin="${crossOrigin}"`); } if (hint.mode === 'preload' || hint.mode === 'prefetch') { switch (extname(hint.url)) { case '.js': attrs.push('as="script"'); break; case '.css': attrs.push('as="style"'); break; default: if (hint.as) { attrs.push(`as="${hint.as}"`); } break; } } if ( sri && (hint.mode === 'preload' || hint.mode === 'prefetch' || hint.mode === 'modulepreload') ) { const content = await loadOutputFile(hint.url); attrs.push(generateSriAttributes(content)); } const tag = `<link ${attrs.join(' ')}>`; if (hint.mode === 'modulepreload') { // Module preloads should be placed by the inserted script elements in the body since // they are only useful in combination with the scripts. bodyLinkTags.push(tag); } else { headerLinkTags.push(tag); } } } const dir = lang ? await getLanguageDirection(lang, warnings) : undefined; const { rewriter, transformedContent } = await htmlRewritingStream(html); const baseTagExists = html.includes('<base'); const foundPreconnects = new Set<string>(); rewriter .on('startTag', (tag, rawTagHtml) => { switch (tag.tagName) { case 'html': // Adjust document locale if specified if (isString(lang)) { updateAttribute(tag, 'lang', lang); } if (dir) { updateAttribute(tag, 'dir', dir); } break; case 'head': // Base href should be added before any link, meta tags if (!baseTagExists && isString(baseHref)) { rewriter.emitStartTag(tag); rewriter.emitRaw(`<base href="${baseHref}">`); return; } break; case 'base': // Adjust base href if specified if (isString(baseHref)) { updateAttribute(tag, 'href', baseHref); } break; case 'link': if (readAttribute(tag, 'rel') === 'preconnect') { const href = readAttribute(tag, 'href'); if (href) { foundPreconnects.add(href); } } break; default: if (tag.selfClosing && !VALID_SELF_CLOSING_TAGS.has(tag.tagName)) { errors.push(`Invalid self-closing element in index HTML file: '${rawTagHtml}'.`); return; } } rewriter.emitStartTag(tag); }) .on('endTag', (tag) => { switch (tag.tagName) { case 'head': for (const linkTag of headerLinkTags) { rewriter.emitRaw(linkTag); } if (imageDomains) { for (const imageDomain of imageDomains) { if (!foundPreconnects.has(imageDomain)) { rewriter.emitRaw(`<link rel="preconnect" href="${imageDomain}" data-ngimg>`); } } } headerLinkTags = []; break; case 'body': for (const linkTag of bodyLinkTags) { rewriter.emitRaw(linkTag); } bodyLinkTags = []; // Add script tags for (const scriptTag of scriptTags) { rewriter.emitRaw(scriptTag); } scriptTags = []; break; } rewriter.emitEndTag(tag); }); const content = await transformedContent(); return { content: headerLinkTags.length || scriptTags.length ? // In case no body/head tags are not present (dotnet partial templates) headerLinkTags.join('') + scriptTags.join('') + content : content, warnings, errors, }; } function generateSriAttributes(content: string): string { const algo = 'sha384'; const hash = createHash(algo).update(content, 'utf8').digest('base64'); return `integrity="${algo}-${hash}"`; } function updateAttribute( tag: { attrs: { name: string; value: string }[] }, name: string, value: string, ): void { const index = tag.attrs.findIndex((a) => a.name === name); const newValue = { name, value }; if (index === -1) { tag.attrs.push(newValue); } else { tag.attrs[index] = newValue; } } function readAttribute( tag: { attrs: { name: string; value: string }[] }, name: string, ): string | undefined { const targetAttr = tag.attrs.find((attr) => attr.name === name); return targetAttr ? targetAttr.value : undefined; } function isString(value: unknown): value is string { return typeof value === 'string'; } async function getLanguageDirection( locale: string, warnings: string[], ): Promise<string | undefined> { const dir = await getLanguageDirectionFromLocales(locale); if (!dir) { warnings.push( `Locale data for '${locale}' cannot be found. 'dir' attribute will not be set for this locale.`, ); } return dir; }
{ "end_byte": 9787, "start_byte": 1850, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/augment-index-html.ts" }
angular-cli/packages/angular/build/src/utils/index-file/augment-index-html.ts_9789_10463
async function getLanguageDirectionFromLocales(locale: string): Promise<string | undefined> { try { const localeData = ( await loadEsmModule<typeof import('@angular/common/locales/en')>( `@angular/common/locales/${locale}`, ) ).default; const dir = localeData[localeData.length - 2]; return isString(dir) ? dir : undefined; } catch { // In some cases certain locales might map to files which are named only with language id. // Example: `en-US` -> `en`. const [languageId] = locale.split('-', 1); if (languageId !== locale) { return getLanguageDirectionFromLocales(languageId); } } return undefined; }
{ "end_byte": 10463, "start_byte": 9789, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/augment-index-html.ts" }
angular-cli/packages/angular/build/src/utils/index-file/inline-critical-css_spec.ts_0_5012
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { tags } from '@angular-devkit/core'; import { InlineCriticalCssProcessor } from './inline-critical-css'; describe('InlineCriticalCssProcessor', () => { const styles: Record<string, string> = { '/dist/styles.css': ` body { margin: 0; } html { color: white; } `, '/dist/theme.css': ` span { color: blue; } p { color: blue; } `, }; const readAsset = async (file: string): Promise<string> => { const content = styles[file]; if (content) { return content; } throw new Error('Cannot read asset.'); }; const getContent = (deployUrl: string, bodyContent = ''): string => { return ` <html> <head> <link href="${deployUrl}styles.css" rel="stylesheet"> <link href="${deployUrl}theme.css" rel="stylesheet"> </head> <body>${bodyContent}</body> </html>`; }; it('should inline critical css', async () => { const inlineFontsProcessor = new InlineCriticalCssProcessor({ readAsset, }); const { content } = await inlineFontsProcessor.process(getContent(''), { outputPath: '/dist/', }); expect(content).toContain( `<link href="styles.css" rel="stylesheet" media="print" onload="this.media='all'">`, ); expect(content).toContain( `<link href="theme.css" rel="stylesheet" media="print" onload="this.media='all'">`, ); expect(content).not.toContain('color: blue'); expect(tags.stripIndents`${content}`).toContain(tags.stripIndents` <style> body { margin: 0; } html { color: white; } </style>`); }); it('should inline critical css when using deployUrl', async () => { const inlineFontsProcessor = new InlineCriticalCssProcessor({ readAsset, deployUrl: 'http://cdn.com', }); const { content } = await inlineFontsProcessor.process(getContent('http://cdn.com/'), { outputPath: '/dist/', }); expect(content).toContain( `<link href="http://cdn.com/styles.css" rel="stylesheet" media="print" onload="this.media='all'">`, ); expect(content).toContain( `<link href="http://cdn.com/theme.css" rel="stylesheet" media="print" onload="this.media='all'">`, ); expect(tags.stripIndents`${content}`).toContain(tags.stripIndents` <style> body { margin: 0; } html { color: white; } </style>`); }); it('should compress inline critical css when minify is enabled', async () => { const inlineFontsProcessor = new InlineCriticalCssProcessor({ readAsset, minify: true, }); const { content } = await inlineFontsProcessor.process(getContent(''), { outputPath: '/dist/', }); expect(content).toContain( `<link href="styles.css" rel="stylesheet" media="print" onload="this.media='all'">`, ); expect(content).toContain( `<link href="theme.css" rel="stylesheet" media="print" onload="this.media='all'">`, ); expect(content).toContain('<style>body{margin:0}html{color:white}</style>'); }); it('should process the inline `onload` handlers if a CSP nonce is specified', async () => { const inlineCssProcessor = new InlineCriticalCssProcessor({ readAsset, }); const { content } = await inlineCssProcessor.process( getContent('', '<app ngCspNonce="{% nonce %}"></app>'), { outputPath: '/dist/', }, ); expect(content).toContain( '<link href="styles.css" rel="stylesheet" media="print" ngCspMedia="all">', ); expect(content).toContain( '<link href="theme.css" rel="stylesheet" media="print" ngCspMedia="all">', ); // Nonces shouldn't be added inside the `noscript` tags. expect(content).toContain('<noscript><link href="theme.css" rel="stylesheet"></noscript>'); expect(content).toContain('<script nonce="{% nonce %}">'); expect(tags.stripIndents`${content}`).toContain(tags.stripIndents` <style nonce="{% nonce %}"> body { margin: 0; } html { color: white; } </style>`); }); it('should not modify the document for external stylesheets', async () => { const inlineCssProcessor = new InlineCriticalCssProcessor({ readAsset, }); const initialContent = ` <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://google.com/styles.css" /> </head> <body> <app ngCspNonce="{% nonce %}"></app> </body> </html> `; const { content } = await inlineCssProcessor.process(initialContent, { outputPath: '/dist/', }); expect(tags.stripIndents`${content}`).toContain(tags.stripIndents` <head> <meta charset="utf-8"> <link rel="stylesheet" href="https://google.com/styles.css"> </head> `); }); });
{ "end_byte": 5012, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/inline-critical-css_spec.ts" }
angular-cli/packages/angular/build/src/utils/index-file/nonce_spec.ts_0_2820
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { addNonce } from './nonce'; describe('addNonce', () => { it('should add the nonce expression to all inline style tags', async () => { const result = await addNonce(` <html> <head> <style>.a {color: red;}</style> <style>.b {color: blue;}</style> </head> <body> <app ngCspNonce="{% nonce %}"></app> </body> </html> `); expect(result).toContain('<style nonce="{% nonce %}">.a {color: red;}</style>'); expect(result).toContain('<style nonce="{% nonce %}">.b {color: blue;}</style>'); }); it('should add a lowercase nonce expression to style tags', async () => { const result = await addNonce(` <html> <head> <style>.a {color: red;}</style> </head> <body> <app ngcspnonce="{% nonce %}"></app> </body> </html> `); expect(result).toContain('<style nonce="{% nonce %}">.a {color: red;}</style>'); }); it('should preserve any pre-existing nonces', async () => { const result = await addNonce(` <html> <head> <style>.a {color: red;}</style> <style nonce="{% otherNonce %}">.b {color: blue;}</style> </head> <body> <app ngCspNonce="{% nonce %}"></app> </body> </html> `); expect(result).toContain('<style nonce="{% nonce %}">.a {color: red;}</style>'); expect(result).toContain('<style nonce="{% otherNonce %}">.b {color: blue;}</style>'); }); it('should use the first nonce that is defined on the page', async () => { const result = await addNonce(` <html> <head> <style>.a {color: red;}</style> </head> <body> <app ngCspNonce="{% nonce %}"></app> <other-app ngCspNonce="{% otherNonce %}"></other-app> </body> </html> `); expect(result).toContain('<style nonce="{% nonce %}">.a {color: red;}</style>'); }); it('should to all script tags', async () => { const result = await addNonce(` <html> <head> </head> <body> <app ngCspNonce="{% nonce %}"></app> <script>console.log('foo');</script> <script src="./main.js"></script> <script>console.log('bar');</script> </body> </html> `); expect(result).toContain(`<script nonce="{% nonce %}">console.log('foo');</script>`); expect(result).toContain('<script src="./main.js" nonce="{% nonce %}"></script>'); expect(result).toContain(`<script nonce="{% nonce %}">console.log('bar');</script>`); }); });
{ "end_byte": 2820, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/nonce_spec.ts" }
angular-cli/packages/angular/build/src/utils/index-file/auto-csp.ts_0_7490
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as crypto from 'node:crypto'; import { StartTag, htmlRewritingStream } from './html-rewriting-stream'; /** * The hash function to use for hash directives to use in the CSP. */ const HASH_FUNCTION = 'sha256'; /** * Store the appropriate attributes of a sourced script tag to generate the loader script. */ interface SrcScriptTag { src: string; type?: string; async: boolean; defer: boolean; } /** * Get the specified attribute or return undefined if the tag doesn't have that attribute. * * @param tag StartTag of the <script> * @returns */ function getScriptAttributeValue(tag: StartTag, attrName: string): string | undefined { return tag.attrs.find((attr) => attr.name === attrName)?.value; } /** * Checks whether a particular string is a MIME type associated with JavaScript, according to * https://developer.mozilla.org/en-US/docs/Web/HTTP/MIME_types#textjavascript * * @param mimeType a string that may be a MIME type * @returns whether the string is a MIME type that is associated with JavaScript */ function isJavascriptMimeType(mimeType: string): boolean { return mimeType.split(';')[0] === 'text/javascript'; } /** * Which of the type attributes on the script tag we should try passing along * based on https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script/type * @param scriptType the `type` attribute on the `<script>` tag under question * @returns whether to add the script tag to the dynamically loaded script tag */ function shouldDynamicallyLoadScriptTagBasedOnType(scriptType: string | undefined): boolean { return ( scriptType === undefined || scriptType === '' || scriptType === 'module' || isJavascriptMimeType(scriptType) ); } /** * Calculates a CSP compatible hash of an inline script. * @param scriptText Text between opening and closing script tag. Has to * include whitespaces and newlines! * @returns The hash of the text formatted appropriately for CSP. */ export function hashTextContent(scriptText: string): string { const hash = crypto.createHash(HASH_FUNCTION).update(scriptText, 'utf-8').digest('base64'); return `'${HASH_FUNCTION}-${hash}'`; } /** * Finds all `<script>` tags and creates a dynamic script loading block for consecutive `<script>` with `src` attributes. * Hashes all scripts, both inline and generated dynamic script loading blocks. * Inserts a `<meta>` tag at the end of the `<head>` of the document with the generated hash-based CSP. * * @param html Markup that should be processed. * @returns The transformed HTML that contains the `<meta>` tag CSP and dynamic loader scripts. */ export async function autoCsp(html: string, unsafeEval = false): Promise<string> { const { rewriter, transformedContent } = await htmlRewritingStream(html); let openedScriptTag: StartTag | undefined = undefined; let scriptContent: SrcScriptTag[] = []; const hashes: string[] = []; /** * Generates the dynamic loading script and puts it in the rewriter and adds the hash of the dynamic * loader script to the collection of hashes to add to the <meta> tag CSP. */ function emitLoaderScript() { const loaderScript = createLoaderScript(scriptContent); hashes.push(hashTextContent(loaderScript)); rewriter.emitRaw(`<script>${loaderScript}</script>`); scriptContent = []; } rewriter.on('startTag', (tag, html) => { if (tag.tagName === 'script') { openedScriptTag = tag; const src = getScriptAttributeValue(tag, 'src'); if (src) { // If there are any interesting attributes, note them down. const scriptType = getScriptAttributeValue(tag, 'type'); if (shouldDynamicallyLoadScriptTagBasedOnType(scriptType)) { scriptContent.push({ src: src, type: scriptType, async: getScriptAttributeValue(tag, 'async') !== undefined, defer: getScriptAttributeValue(tag, 'defer') !== undefined, }); return; // Skip writing my script tag until we've read it all. } } } // We are encountering the first start tag that's not <script src="..."> after a string of // consecutive <script src="...">. <script> tags without a src attribute will also end a chain // of src attributes that can be loaded in a single loader script, so those will end up here. // // The first place when we can determine this to be the case is // during the first opening tag that's not <script src="...">, where we need to insert the // dynamic loader script before continuing on with writing the rest of the tags. // (One edge case is where there are no more opening tags after the last <script src="..."> is // closed, but this case is handled below with the final </body> tag.) if (scriptContent.length > 0) { emitLoaderScript(); } rewriter.emitStartTag(tag); }); rewriter.on('text', (tag, html) => { if (openedScriptTag && !getScriptAttributeValue(openedScriptTag, 'src')) { hashes.push(hashTextContent(html)); } rewriter.emitText(tag); }); rewriter.on('endTag', (tag, html) => { if (openedScriptTag && tag.tagName === 'script') { const src = getScriptAttributeValue(openedScriptTag, 'src'); const scriptType = getScriptAttributeValue(openedScriptTag, 'type'); openedScriptTag = undefined; // Return early to avoid writing the closing </script> tag if it's a part of the // dynamic loader script. if (src && shouldDynamicallyLoadScriptTagBasedOnType(scriptType)) { return; } } if (tag.tagName === 'body' || tag.tagName === 'html') { // Write the loader script if a string of <script>s were the last opening tag of the document. if (scriptContent.length > 0) { emitLoaderScript(); } } rewriter.emitEndTag(tag); }); const rewritten = await transformedContent(); // Second pass to add the header const secondPass = await htmlRewritingStream(rewritten); secondPass.rewriter.on('startTag', (tag, _) => { secondPass.rewriter.emitStartTag(tag); if (tag.tagName === 'head') { // See what hashes we came up with! secondPass.rewriter.emitRaw( `<meta http-equiv="Content-Security-Policy" content="${getStrictCsp(hashes, { enableBrowserFallbacks: true, enableTrustedTypes: false, enableUnsafeEval: unsafeEval, })}">`, ); } }); return secondPass.transformedContent(); } /** * Returns a strict Content Security Policy for mitigating XSS. * For more details read csp.withgoogle.com. * If you modify this CSP, make sure it has not become trivially bypassable by * checking the policy using csp-evaluator.withgoogle.com. * * @param hashes A list of sha-256 hashes of trusted inline scripts. * @param enableTrustedTypes If Trusted Types should be enabled for scripts. * @param enableBrowserFallbacks If fallbacks for older browsers should be * added. This is will not weaken the policy as modern browsers will ignore * the fallbacks. * @param enableUnsafeEval If you cannot remove all uses of eval(), you can * still set a strict CSP, but you will have to use the 'unsafe-eval' * keyword which will make your policy slightly less secure. */
{ "end_byte": 7490, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/auto-csp.ts" }
angular-cli/packages/angular/build/src/utils/index-file/auto-csp.ts_7491_11172
function getStrictCsp( hashes?: string[], // default CSP options cspOptions: { enableBrowserFallbacks?: boolean; enableTrustedTypes?: boolean; enableUnsafeEval?: boolean; } = { enableBrowserFallbacks: true, enableTrustedTypes: false, enableUnsafeEval: false, }, ): string { hashes = hashes || []; const strictCspTemplate: Record<string, string[]> = { // 'strict-dynamic' allows hashed scripts to create new scripts. 'script-src': [`'strict-dynamic'`, ...hashes], // Restricts `object-src` to disable dangerous plugins like Flash. 'object-src': [`'none'`], // Restricts `base-uri` to block the injection of `<base>` tags. This // prevents attackers from changing the locations of scripts loaded from // relative URLs. 'base-uri': [`'self'`], }; // Adds fallbacks for browsers not compatible to CSP3 and CSP2. // These fallbacks are ignored by modern browsers in presence of hashes, // and 'strict-dynamic'. if (cspOptions.enableBrowserFallbacks) { // Fallback for Safari. All modern browsers supporting strict-dynamic will // ignore the 'https:' fallback. strictCspTemplate['script-src'].push('https:'); // 'unsafe-inline' is only ignored in presence of a hash or nonce. if (hashes.length > 0) { strictCspTemplate['script-src'].push(`'unsafe-inline'`); } } // If enabled, dangerous DOM sinks will only accept typed objects instead of // strings. if (cspOptions.enableTrustedTypes) { strictCspTemplate['require-trusted-types-for'] = ['script']; } // If enabled, `eval()`-calls will be allowed, making the policy slightly // less secure. if (cspOptions.enableUnsafeEval) { strictCspTemplate['script-src'].push(`'unsafe-eval'`); } return Object.entries(strictCspTemplate) .map(([directive, values]) => { return `${directive} ${values.join(' ')};`; }) .join(''); } /** * Returns JS code for dynamically loading sourced (external) scripts. * @param srcList A list of paths for scripts that should be loaded. */ function createLoaderScript(srcList: SrcScriptTag[], enableTrustedTypes = false): string { if (!srcList.length) { throw new Error('Cannot create a loader script with no scripts to load.'); } const srcListFormatted = srcList .map((s) => { // URI encoding means value can't escape string, JS, or HTML context. const srcAttr = encodeURI(s.src).replaceAll("'", "\\'"); // Can only be 'module' or a JS MIME type or an empty string. const typeAttr = s.type ? "'" + s.type + "'" : undefined; const asyncAttr = s.async ? 'true' : 'false'; const deferAttr = s.defer ? 'true' : 'false'; return `['${srcAttr}', ${typeAttr}, ${asyncAttr}, ${deferAttr}]`; }) .join(); return enableTrustedTypes ? ` var scripts = [${srcListFormatted}]; var policy = self.trustedTypes && self.trustedTypes.createPolicy ? self.trustedTypes.createPolicy('angular#auto-csp', {createScriptURL: function(u) { return scripts.includes(u) ? u : null; }}) : { createScriptURL: function(u) { return u; } }; scripts.forEach(function(scriptUrl) { var s = document.createElement('script'); s.src = policy.createScriptURL(scriptUrl[0]); s.type = scriptUrl[1]; s.async = !!scriptUrl[2]; s.defer = !!scriptUrl[3]; document.body.appendChild(s); });\n` : ` var scripts = [${srcListFormatted}]; scripts.forEach(function(scriptUrl) { var s = document.createElement('script'); s.src = scriptUrl[0]; s.type = scriptUrl[1]; s.async = !!scriptUrl[2]; s.defer = !!scriptUrl[3]; document.body.appendChild(s); });\n`; }
{ "end_byte": 11172, "start_byte": 7491, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/auto-csp.ts" }
angular-cli/packages/angular/build/src/utils/index-file/inline-critical-css.ts_0_8235
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import Beasties from 'beasties'; import { readFile } from 'node:fs/promises'; /** * Pattern used to extract the media query set by Beasties in an `onload` handler. */ const MEDIA_SET_HANDLER_PATTERN = /^this\.media=["'](.*)["'];?$/; /** * Name of the attribute used to save the Beasties media query so it can be re-assigned on load. */ const CSP_MEDIA_ATTR = 'ngCspMedia'; /** * Script that dynamically updates the `media` attribute of `<link>` tags based on a custom attribute (`CSP_MEDIA_ATTR`). * * NOTE: * We do not use `document.querySelectorAll('link').forEach((s) => s.addEventListener('load', ...)` * because load events are not always triggered reliably on Chrome. * See: https://github.com/angular/angular-cli/issues/26932 and https://crbug.com/1521256 * * The script: * - Ensures the event target is a `<link>` tag with the `CSP_MEDIA_ATTR` attribute. * - Updates the `media` attribute with the value of `CSP_MEDIA_ATTR` and then removes the attribute. * - Removes the event listener when all relevant `<link>` tags have been processed. * - Uses event capturing (the `true` parameter) since load events do not bubble up the DOM. */ const LINK_LOAD_SCRIPT_CONTENT = ` (() => { const CSP_MEDIA_ATTR = '${CSP_MEDIA_ATTR}'; const documentElement = document.documentElement; // Listener for load events on link tags. const listener = (e) => { const target = e.target; if ( !target || target.tagName !== 'LINK' || !target.hasAttribute(CSP_MEDIA_ATTR) ) { return; } target.media = target.getAttribute(CSP_MEDIA_ATTR); target.removeAttribute(CSP_MEDIA_ATTR); if (!document.head.querySelector(\`link[\${CSP_MEDIA_ATTR}]\`)) { documentElement.removeEventListener('load', listener); } }; documentElement.addEventListener('load', listener, true); })();`; export interface InlineCriticalCssProcessOptions { outputPath: string; } export interface InlineCriticalCssProcessorOptions { minify?: boolean; deployUrl?: string; readAsset?: (path: string) => Promise<string>; } /** Partial representation of an `HTMLElement`. */ interface PartialHTMLElement { getAttribute(name: string): string | null; setAttribute(name: string, value: string): void; hasAttribute(name: string): boolean; removeAttribute(name: string): void; appendChild(child: PartialHTMLElement): void; insertBefore(newNode: PartialHTMLElement, referenceNode?: PartialHTMLElement): void; remove(): void; name: string; textContent: string; tagName: string | null; children: PartialHTMLElement[]; next: PartialHTMLElement | null; prev: PartialHTMLElement | null; } /** Partial representation of an HTML `Document`. */ interface PartialDocument { head: PartialHTMLElement; createElement(tagName: string): PartialHTMLElement; querySelector(selector: string): PartialHTMLElement | null; } /* eslint-disable @typescript-eslint/no-unsafe-declaration-merging */ // We use Typescript declaration merging because `embedLinkedStylesheet` it's not declared in // the `Beasties` types which means that we can't call the `super` implementation. interface BeastiesBase { embedLinkedStylesheet(link: PartialHTMLElement, document: PartialDocument): Promise<unknown>; } class BeastiesBase extends Beasties {} /* eslint-enable @typescript-eslint/no-unsafe-declaration-merging */ class BeastiesExtended extends BeastiesBase { readonly warnings: string[] = []; readonly errors: string[] = []; private addedCspScriptsDocuments = new WeakSet<PartialDocument>(); private documentNonces = new WeakMap<PartialDocument, string | null>(); constructor( private readonly optionsExtended: InlineCriticalCssProcessorOptions & InlineCriticalCssProcessOptions, ) { super({ logger: { warn: (s: string) => this.warnings.push(s), error: (s: string) => this.errors.push(s), info: () => {}, }, logLevel: 'warn', path: optionsExtended.outputPath, publicPath: optionsExtended.deployUrl, compress: !!optionsExtended.minify, pruneSource: false, reduceInlineStyles: false, mergeStylesheets: false, // Note: if `preload` changes to anything other than `media`, the logic in // `embedLinkedStylesheet` will have to be updated. preload: 'media', noscriptFallback: true, inlineFonts: true, }); } public override readFile(path: string): Promise<string> { const readAsset = this.optionsExtended.readAsset; return readAsset ? readAsset(path) : readFile(path, 'utf-8'); } /** * Override of the Beasties `embedLinkedStylesheet` method * that makes it work with Angular's CSP APIs. */ override async embedLinkedStylesheet( link: PartialHTMLElement, document: PartialDocument, ): Promise<unknown> { if (link.getAttribute('media') === 'print' && link.next?.name === 'noscript') { // Workaround for https://github.com/GoogleChromeLabs/critters/issues/64 // NB: this is only needed for the webpack based builders. const media = link.getAttribute('onload')?.match(MEDIA_SET_HANDLER_PATTERN); if (media) { link.removeAttribute('onload'); link.setAttribute('media', media[1]); link?.next?.remove(); } } const returnValue = await super.embedLinkedStylesheet(link, document); const cspNonce = this.findCspNonce(document); if (cspNonce) { const beastiesMedia = link.getAttribute('onload')?.match(MEDIA_SET_HANDLER_PATTERN); if (beastiesMedia) { // If there's a Beasties-generated `onload` handler and the file has an Angular CSP nonce, // we have to remove the handler, because it's incompatible with CSP. We save the value // in a different attribute and we generate a script tag with the nonce that uses // `addEventListener` to apply the media query instead. link.removeAttribute('onload'); link.setAttribute(CSP_MEDIA_ATTR, beastiesMedia[1]); this.conditionallyInsertCspLoadingScript(document, cspNonce, link); } // Ideally we would hook in at the time Beasties inserts the `style` tags, but there isn't // a way of doing that at the moment so we fall back to doing it any time a `link` tag is // inserted. We mitigate it by only iterating the direct children of the `<head>` which // should be pretty shallow. document.head.children.forEach((child) => { if (child.tagName === 'style' && !child.hasAttribute('nonce')) { child.setAttribute('nonce', cspNonce); } }); } return returnValue; } /** * Finds the CSP nonce for a specific document. */ private findCspNonce(document: PartialDocument): string | null { if (this.documentNonces.has(document)) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return this.documentNonces.get(document)!; } // HTML attribute are case-insensitive, but the parser used by Beasties is case-sensitive. const nonceElement = document.querySelector('[ngCspNonce], [ngcspnonce]'); const cspNonce = nonceElement?.getAttribute('ngCspNonce') || nonceElement?.getAttribute('ngcspnonce') || null; this.documentNonces.set(document, cspNonce); return cspNonce; } /** * Inserts the `script` tag that swaps the critical CSS at runtime, * if one hasn't been inserted into the document already. */ private conditionallyInsertCspLoadingScript( document: PartialDocument, nonce: string, link: PartialHTMLElement, ): void { if (this.addedCspScriptsDocuments.has(document)) { return; } const script = document.createElement('script'); script.setAttribute('nonce', nonce); script.textContent = LINK_LOAD_SCRIPT_CONTENT; // Prepend the script to the head since it needs to // run as early as possible, before the `link` tags. document.head.insertBefore(script, link); this.addedCspScriptsDocuments.add(document); } }
{ "end_byte": 8235, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/inline-critical-css.ts" }
angular-cli/packages/angular/build/src/utils/index-file/inline-critical-css.ts_8237_8992
export class InlineCriticalCssProcessor { constructor(protected readonly options: InlineCriticalCssProcessorOptions) {} async process( html: string, options: InlineCriticalCssProcessOptions, ): Promise<{ content: string; warnings: string[]; errors: string[] }> { const beasties = new BeastiesExtended({ ...this.options, ...options }); const content = await beasties.process(html); return { // Clean up value from value less attributes. // This is caused because parse5 always requires attributes to have a string value. // nomodule="" defer="" -> nomodule defer. content: content.replace(/(\s(?:defer|nomodule))=""/g, '$1'), errors: beasties.errors, warnings: beasties.warnings, }; } }
{ "end_byte": 8992, "start_byte": 8237, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/inline-critical-css.ts" }
angular-cli/packages/angular/build/src/utils/index-file/augment-index-html_spec.ts_0_7762
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { tags } from '@angular-devkit/core'; import { AugmentIndexHtmlOptions, augmentIndexHtml } from './augment-index-html'; describe('augment-index-html', () => { const indexGeneratorOptions: AugmentIndexHtmlOptions = { html: '<html><head></head><body></body></html>', baseHref: '/', sri: false, files: [], loadOutputFile: async (_fileName: string) => '', entrypoints: [ ['scripts', false], ['polyfills', true], ['main', true], ['styles', false], ], }; const oneLineHtml = (html: TemplateStringsArray) => tags.stripIndents`${html}`.replace(/(>\s+)/g, '>'); it('can generate index.html', async () => { const { content } = await augmentIndexHtml({ ...indexGeneratorOptions, files: [ { file: 'styles.css', extension: '.css', name: 'styles' }, { file: 'runtime.js', extension: '.js', name: 'main' }, { file: 'main.js', extension: '.js', name: 'main' }, { file: 'runtime.js', extension: '.js', name: 'polyfills' }, { file: 'polyfills.js', extension: '.js', name: 'polyfills' }, ], }); expect(content).toEqual(oneLineHtml` <html> <head><base href="/"> <link rel="stylesheet" href="styles.css"> </head> <body> <script src="runtime.js" type="module"></script> <script src="polyfills.js" type="module"></script> <script src="main.js" type="module"></script> </body> </html> `); }); it('should replace base href value', async () => { const { content } = await augmentIndexHtml({ ...indexGeneratorOptions, html: '<html><head><base href="/"></head><body></body></html>', baseHref: '/Apps/', }); expect(content).toEqual(oneLineHtml` <html> <head><base href="/Apps/"> </head> <body> </body> </html> `); }); it('should add lang and dir LTR attribute for French (fr)', async () => { const { content } = await augmentIndexHtml({ ...indexGeneratorOptions, lang: 'fr', }); expect(content).toEqual(oneLineHtml` <html lang="fr" dir="ltr"> <head> <base href="/"> </head> <body> </body> </html> `); }); it('should add lang and dir RTL attribute for Pashto (ps)', async () => { const { content } = await augmentIndexHtml({ ...indexGeneratorOptions, lang: 'ps', }); expect(content).toEqual(oneLineHtml` <html lang="ps" dir="rtl"> <head> <base href="/"> </head> <body> </body> </html> `); }); it(`should fallback to use language ID to set the dir attribute (en-US)`, async () => { const { content, warnings } = await augmentIndexHtml({ ...indexGeneratorOptions, lang: 'en-US', }); expect(warnings).toHaveSize(0); expect(content).toEqual(oneLineHtml` <html lang="en-US" dir="ltr"> <head> <base href="/"> </head> <body> </body> </html> `); }); it(`should work when lang (locale) is not provided by '@angular/common'`, async () => { const { content, warnings } = await augmentIndexHtml({ ...indexGeneratorOptions, lang: 'xx-XX', }); expect(warnings).toEqual([ `Locale data for 'xx-XX' cannot be found. 'dir' attribute will not be set for this locale.`, ]); expect(content).toEqual(oneLineHtml` <html lang="xx-XX"> <head> <base href="/"> </head> <body> </body> </html> `); }); it(`should add script and link tags even when body and head element doesn't exist`, async () => { const { content } = await augmentIndexHtml({ ...indexGeneratorOptions, html: `<app-root></app-root>`, files: [ { file: 'styles.css', extension: '.css', name: 'styles' }, { file: 'runtime.js', extension: '.js', name: 'main' }, { file: 'main.js', extension: '.js', name: 'main' }, { file: 'runtime.js', extension: '.js', name: 'polyfills' }, { file: 'polyfills.js', extension: '.js', name: 'polyfills' }, ], }); expect(content).toEqual(oneLineHtml` <link rel="stylesheet" href="styles.css"> <script src="runtime.js" type="module"></script> <script src="polyfills.js" type="module"></script> <script src="main.js" type="module"></script> <app-root></app-root> `); }); it(`should add preconnect and dns-prefetch hints when provided with cross origin`, async () => { const { content, warnings } = await augmentIndexHtml({ ...indexGeneratorOptions, hints: [ { mode: 'preconnect', url: 'http://example.com' }, { mode: 'dns-prefetch', url: 'http://example.com' }, ], }); expect(warnings).toHaveSize(0); expect(content).toEqual(oneLineHtml` <html> <head> <base href="/"> <link rel="preconnect" href="http://example.com"> <link rel="dns-prefetch" href="http://example.com"> </head> <body> </body> </html> `); }); it(`should add preconnect and dns-prefetch hints when provided with "use-credentials" cross origin`, async () => { const { content, warnings } = await augmentIndexHtml({ ...indexGeneratorOptions, crossOrigin: 'use-credentials', hints: [ { mode: 'preconnect', url: 'http://example.com' }, { mode: 'dns-prefetch', url: 'http://example.com' }, ], }); expect(warnings).toHaveSize(0); expect(content).toEqual(oneLineHtml` <html> <head> <base href="/"> <link rel="preconnect" href="http://example.com" crossorigin="use-credentials"> <link rel="dns-prefetch" href="http://example.com" crossorigin="use-credentials"> </head> <body> </body> </html> `); }); it(`should add preconnect and dns-prefetch hints when provided with "anonymous" cross origin`, async () => { const { content, warnings } = await augmentIndexHtml({ ...indexGeneratorOptions, crossOrigin: 'anonymous', hints: [ { mode: 'preconnect', url: 'http://example.com' }, { mode: 'dns-prefetch', url: 'http://example.com' }, ], }); expect(warnings).toHaveSize(0); expect(content).toEqual(oneLineHtml` <html> <head> <base href="/"> <link rel="preconnect" href="http://example.com" crossorigin> <link rel="dns-prefetch" href="http://example.com" crossorigin> </head> <body> </body> </html> `); }); it(`should add preconnect and dns-prefetch hints when provided with "none" cross origin`, async () => { const { content, warnings } = await augmentIndexHtml({ ...indexGeneratorOptions, crossOrigin: 'none', hints: [ { mode: 'preconnect', url: 'http://example.com' }, { mode: 'dns-prefetch', url: 'http://example.com' }, ], }); expect(warnings).toHaveSize(0); expect(content).toEqual(oneLineHtml` <html> <head> <base href="/"> <link rel="preconnect" href="http://example.com"> <link rel="dns-prefetch" href="http://example.com"> </head> <body> </body> </html> `); });
{ "end_byte": 7762, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/augment-index-html_spec.ts" }
angular-cli/packages/angular/build/src/utils/index-file/augment-index-html_spec.ts_7766_15178
it(`should add preconnect and dns-prefetch hints when provided with no cross origin`, async () => { const { content, warnings } = await augmentIndexHtml({ ...indexGeneratorOptions, hints: [ { mode: 'preconnect', url: 'http://example.com' }, { mode: 'dns-prefetch', url: 'http://example.com' }, ], }); expect(warnings).toHaveSize(0); expect(content).toEqual(oneLineHtml` <html> <head> <base href="/"> <link rel="preconnect" href="http://example.com"> <link rel="dns-prefetch" href="http://example.com"> </head> <body> </body> </html> `); }); it(`should add modulepreload hint when provided`, async () => { const { content, warnings } = await augmentIndexHtml({ ...indexGeneratorOptions, hints: [ { mode: 'modulepreload', url: 'x.js' }, { mode: 'modulepreload', url: 'y/z.js' }, ], }); expect(warnings).toHaveSize(0); expect(content).toEqual(oneLineHtml` <html> <head> <base href="/"> </head> <body> <link rel="modulepreload" href="x.js"> <link rel="modulepreload" href="y/z.js"> </body> </html> `); }); it(`should add modulepreload hint with no crossorigin attribute when provided with cross origin set`, async () => { const { content, warnings } = await augmentIndexHtml({ ...indexGeneratorOptions, crossOrigin: 'anonymous', hints: [ { mode: 'modulepreload', url: 'x.js' }, { mode: 'modulepreload', url: 'y/z.js' }, ], }); expect(warnings).toHaveSize(0); expect(content).toEqual(oneLineHtml` <html> <head> <base href="/"> </head> <body> <link rel="modulepreload" href="x.js"> <link rel="modulepreload" href="y/z.js"> </body> </html> `); }); it(`should add prefetch/preload hints with as=script when specified with a JS url`, async () => { const { content, warnings } = await augmentIndexHtml({ ...indexGeneratorOptions, hints: [ { mode: 'prefetch', url: 'x.js' }, { mode: 'preload', url: 'y/z.js' }, ], }); expect(warnings).toHaveSize(0); expect(content).toEqual(oneLineHtml` <html> <head> <base href="/"> <link rel="prefetch" href="x.js" as="script"> <link rel="preload" href="y/z.js" as="script"> </head> <body> </body> </html> `); }); it(`should add prefetch/preload hints with as=style when specified with a CSS url`, async () => { const { content, warnings } = await augmentIndexHtml({ ...indexGeneratorOptions, hints: [ { mode: 'prefetch', url: 'x.css' }, { mode: 'preload', url: 'y/z.css' }, ], }); expect(warnings).toHaveSize(0); expect(content).toEqual(oneLineHtml` <html> <head> <base href="/"> <link rel="prefetch" href="x.css" as="style"> <link rel="preload" href="y/z.css" as="style"> </head> <body> </body> </html> `); }); it(`should add prefetch/preload hints with as=style when specified with a URL and an 'as' option`, async () => { const { content, warnings } = await augmentIndexHtml({ ...indexGeneratorOptions, hints: [ { mode: 'prefetch', url: 'https://example.com/x?a=1', as: 'style' }, { mode: 'preload', url: 'http://example.com/y?b=2', as: 'style' }, ], }); expect(warnings).toHaveSize(0); expect(content).toEqual(oneLineHtml` <html> <head> <base href="/"> <link rel="prefetch" href="https://example.com/x?a=1" as="style"> <link rel="preload" href="http://example.com/y?b=2" as="style"> </head> <body> </body> </html> `); }); it('should add `.mjs` script tags', async () => { const { content } = await augmentIndexHtml({ ...indexGeneratorOptions, files: [{ file: 'main.mjs', extension: '.mjs', name: 'main' }], entrypoints: [['main', true /* isModule */]], }); expect(content).toContain('<script src="main.mjs" type="module"></script>'); }); it('should reject non-module `.mjs` scripts', async () => { const options: AugmentIndexHtmlOptions = { ...indexGeneratorOptions, files: [{ file: 'main.mjs', extension: '.mjs', name: 'main' }], entrypoints: [['main', false /* isModule */]], }; await expectAsync(augmentIndexHtml(options)).toBeRejectedWithError( '`.mjs` files *must* set `isModule` to `true`.', ); }); it('should add image domain preload tags', async () => { const imageDomains = ['https://www.example.com', 'https://www.example2.com']; const { content, warnings } = await augmentIndexHtml({ ...indexGeneratorOptions, imageDomains, }); expect(content).toEqual(oneLineHtml` <html> <head> <base href="/"> <link rel="preconnect" href="https://www.example.com" data-ngimg> <link rel="preconnect" href="https://www.example2.com" data-ngimg> </head> <body> </body> </html> `); }); it('should add no image preconnects if provided empty domain list', async () => { const imageDomains: Array<string> = []; const { content, warnings } = await augmentIndexHtml({ ...indexGeneratorOptions, imageDomains, }); expect(content).toEqual(oneLineHtml` <html> <head> <base href="/"> </head> <body> </body> </html> `); }); it('should not add duplicate preconnects', async () => { const imageDomains = ['https://www.example1.com', 'https://www.example2.com']; const { content, warnings } = await augmentIndexHtml({ ...indexGeneratorOptions, html: '<html><head><link rel="preconnect" href="https://www.example1.com"></head><body></body></html>', imageDomains, }); expect(content).toEqual(oneLineHtml` <html> <head> <base href="/"> <link rel="preconnect" href="https://www.example1.com"> <link rel="preconnect" href="https://www.example2.com" data-ngimg> </head> <body> </body> </html> `); }); it('should add image preconnects if it encounters preconnect elements for other resources', async () => { const imageDomains = ['https://www.example2.com', 'https://www.example3.com']; const { content } = await augmentIndexHtml({ ...indexGeneratorOptions, html: '<html><head><link rel="preconnect" href="https://www.example1.com"></head><body></body></html>', imageDomains, }); expect(content).toEqual(oneLineHtml` <html> <head> <base href="/"> <link rel="preconnect" href="https://www.example1.com"> <link rel="preconnect" href="https://www.example2.com" data-ngimg> <link rel="preconnect" href="https://www.example3.com" data-ngimg> </head> <body> </body> </html> `); });
{ "end_byte": 15178, "start_byte": 7766, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/augment-index-html_spec.ts" }
angular-cli/packages/angular/build/src/utils/index-file/augment-index-html_spec.ts_15182_16071
describe('self-closing tags', () => { it('should return an error when used on a not supported element', async () => { const { errors } = await augmentIndexHtml({ ...indexGeneratorOptions, html: ` <html> <body> <app-root /> </body> </html>' `, }); expect(errors.length).toEqual(1); expect(errors).toEqual([`Invalid self-closing element in index HTML file: '<app-root />'.`]); }); it('should not return an error when used on a supported element', async () => { const { errors } = await augmentIndexHtml({ ...indexGeneratorOptions, html: ` <html> <body> <br /> <app-root><app-root> </body> </html>' `, }); expect(errors.length).toEqual(0); }); }); });
{ "end_byte": 16071, "start_byte": 15182, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/augment-index-html_spec.ts" }
angular-cli/packages/angular/build/src/utils/index-file/index-html-generator.ts_0_7012
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { readFile } from 'node:fs/promises'; import { join } from 'node:path'; import { NormalizedCachedOptions } from '../normalize-cache'; import { NormalizedOptimizationOptions } from '../normalize-optimization'; import { addEventDispatchContract } from './add-event-dispatch-contract'; import { CrossOriginValue, Entrypoint, FileInfo, augmentIndexHtml } from './augment-index-html'; import { autoCsp } from './auto-csp'; import { InlineCriticalCssProcessor } from './inline-critical-css'; import { InlineFontsProcessor } from './inline-fonts'; import { addNgcmAttribute } from './ngcm-attribute'; import { addNonce } from './nonce'; type IndexHtmlGeneratorPlugin = ( html: string, options: IndexHtmlGeneratorProcessOptions, ) => Promise<string | IndexHtmlPluginTransformResult> | string; export type HintMode = 'prefetch' | 'preload' | 'modulepreload' | 'preconnect' | 'dns-prefetch'; export interface IndexHtmlGeneratorProcessOptions { lang: string | undefined; baseHref: string | undefined; outputPath: string; files: FileInfo[]; hints?: { url: string; mode: HintMode; as?: string }[]; } export interface AutoCspOptions { unsafeEval: boolean; } export interface IndexHtmlGeneratorOptions { indexPath: string; deployUrl?: string; sri?: boolean; entrypoints: Entrypoint[]; postTransform?: IndexHtmlTransform; crossOrigin?: CrossOriginValue; optimization?: NormalizedOptimizationOptions; cache?: NormalizedCachedOptions; imageDomains?: string[]; generateDedicatedSSRContent?: boolean; autoCsp?: AutoCspOptions; } export type IndexHtmlTransform = (content: string) => Promise<string>; export interface IndexHtmlPluginTransformResult { content: string; warnings: string[]; errors: string[]; } export interface IndexHtmlProcessResult { csrContent: string; ssrContent?: string; warnings: string[]; errors: string[]; } export class IndexHtmlGenerator { private readonly plugins: IndexHtmlGeneratorPlugin[]; private readonly csrPlugins: IndexHtmlGeneratorPlugin[] = []; private readonly ssrPlugins: IndexHtmlGeneratorPlugin[] = []; constructor(readonly options: IndexHtmlGeneratorOptions) { const extraCommonPlugins: IndexHtmlGeneratorPlugin[] = []; if (options?.optimization?.fonts.inline) { extraCommonPlugins.push(inlineFontsPlugin(this), addNonce); } // Common plugins this.plugins = [augmentIndexHtmlPlugin(this), ...extraCommonPlugins, postTransformPlugin(this)]; // CSR plugins if (options?.optimization?.styles?.inlineCritical) { this.csrPlugins.push(inlineCriticalCssPlugin(this)); } this.csrPlugins.push(addNoncePlugin()); // SSR plugins if (options.generateDedicatedSSRContent) { this.csrPlugins.push(addNgcmAttributePlugin()); this.ssrPlugins.push(addEventDispatchContractPlugin(), addNoncePlugin()); } // Auto-CSP (as the last step) if (options.autoCsp) { if (options.generateDedicatedSSRContent) { throw new Error('Cannot set both SSR and auto-CSP at the same time.'); } this.csrPlugins.push(autoCspPlugin(options.autoCsp.unsafeEval)); } } async process(options: IndexHtmlGeneratorProcessOptions): Promise<IndexHtmlProcessResult> { let content = await this.readIndex(this.options.indexPath); const warnings: string[] = []; const errors: string[] = []; content = await this.runPlugins(content, this.plugins, options, warnings, errors); const [csrContent, ssrContent] = await Promise.all([ this.runPlugins(content, this.csrPlugins, options, warnings, errors), this.ssrPlugins.length ? this.runPlugins(content, this.ssrPlugins, options, warnings, errors) : undefined, ]); return { ssrContent, csrContent, warnings, errors, }; } private async runPlugins( content: string, plugins: IndexHtmlGeneratorPlugin[], options: IndexHtmlGeneratorProcessOptions, warnings: string[], errors: string[], ): Promise<string> { for (const plugin of plugins) { const result = await plugin(content, options); if (typeof result === 'string') { content = result; } else { content = result.content; if (result.warnings.length) { warnings.push(...result.warnings); } if (result.errors.length) { errors.push(...result.errors); } } } return content; } async readAsset(path: string): Promise<string> { try { return await readFile(path, 'utf-8'); } catch { throw new Error(`Failed to read asset "${path}".`); } } protected async readIndex(path: string): Promise<string> { try { return new TextDecoder('utf-8').decode(await readFile(path)); } catch (cause) { throw new Error(`Failed to read index HTML file "${path}".`, { cause }); } } } function augmentIndexHtmlPlugin(generator: IndexHtmlGenerator): IndexHtmlGeneratorPlugin { const { deployUrl, crossOrigin, sri = false, entrypoints, imageDomains } = generator.options; return async (html, options) => { const { lang, baseHref, outputPath = '', files, hints } = options; return augmentIndexHtml({ html, baseHref, deployUrl, crossOrigin, sri, lang, entrypoints, loadOutputFile: (filePath) => generator.readAsset(join(outputPath, filePath)), imageDomains, files, hints, }); }; } function inlineFontsPlugin({ options }: IndexHtmlGenerator): IndexHtmlGeneratorPlugin { const inlineFontsProcessor = new InlineFontsProcessor({ minify: options.optimization?.styles.minify, }); return async (html) => inlineFontsProcessor.process(html); } function inlineCriticalCssPlugin(generator: IndexHtmlGenerator): IndexHtmlGeneratorPlugin { const inlineCriticalCssProcessor = new InlineCriticalCssProcessor({ minify: generator.options.optimization?.styles.minify, deployUrl: generator.options.deployUrl, readAsset: (filePath) => generator.readAsset(filePath), }); return async (html, options) => inlineCriticalCssProcessor.process(html, { outputPath: options.outputPath }); } function addNoncePlugin(): IndexHtmlGeneratorPlugin { return (html) => addNonce(html); } function autoCspPlugin(unsafeEval: boolean): IndexHtmlGeneratorPlugin { return (html) => autoCsp(html, unsafeEval); } function postTransformPlugin({ options }: IndexHtmlGenerator): IndexHtmlGeneratorPlugin { return async (html) => (options.postTransform ? options.postTransform(html) : html); } function addEventDispatchContractPlugin(): IndexHtmlGeneratorPlugin { return (html) => addEventDispatchContract(html); } function addNgcmAttributePlugin(): IndexHtmlGeneratorPlugin { return (html) => addNgcmAttribute(html); }
{ "end_byte": 7012, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/index-html-generator.ts" }
angular-cli/packages/angular/build/src/utils/index-file/inline-fonts.ts_0_1137
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { HttpsProxyAgent } from 'https-proxy-agent'; import { createHash } from 'node:crypto'; import { readFile, rm, writeFile } from 'node:fs/promises'; import * as https from 'node:https'; import { join } from 'node:path'; import { NormalizedCachedOptions } from '../normalize-cache'; import { htmlRewritingStream } from './html-rewriting-stream'; interface FontProviderDetails { preconnectUrl: string; } export interface InlineFontsOptions { minify?: boolean; cache?: NormalizedCachedOptions; } const SUPPORTED_PROVIDERS: Record<string, FontProviderDetails> = { 'fonts.googleapis.com': { preconnectUrl: 'https://fonts.gstatic.com', }, 'use.typekit.net': { preconnectUrl: 'https://use.typekit.net', }, }; /** * Hash algorithm used for cached files. */ const CONTENT_HASH_ALGORITHM = 'sha256'; /** * String length of the SHA-256 content hash stored in cached files. */ const CONTENT_HASH_LENGTH = 64;
{ "end_byte": 1137, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/inline-fonts.ts" }
angular-cli/packages/angular/build/src/utils/index-file/inline-fonts.ts_1139_9127
export class InlineFontsProcessor { private readonly cachePath: string | undefined; constructor(private options: InlineFontsOptions) { const { path: cacheDirectory, enabled } = this.options.cache || {}; if (cacheDirectory && enabled) { this.cachePath = join(cacheDirectory, 'angular-build-fonts'); } } async process(content: string): Promise<string> { const hrefList: string[] = []; const existingPreconnect = new Set<string>(); // Collector link tags with href const { rewriter: collectorStream, transformedContent: initCollectorStream } = await htmlRewritingStream(content); collectorStream.on('startTag', (tag) => { const { tagName, attrs } = tag; if (tagName !== 'link') { return; } let hrefValue: string | undefined; let relValue: string | undefined; for (const { name, value } of attrs) { switch (name) { case 'rel': relValue = value; break; case 'href': hrefValue = value; break; } if (hrefValue && relValue) { switch (relValue) { case 'stylesheet': // <link rel="stylesheet" href="https://example.com/main.css"> hrefList.push(hrefValue); break; case 'preconnect': // <link rel="preconnect" href="https://example.com"> existingPreconnect.add(hrefValue.replace(/\/$/, '')); break; } return; } } }); void initCollectorStream().catch(() => { // We don't really care about any errors here because it just initializes // the rewriting stream, as we are waiting for `finish` below. }); await new Promise((resolve) => collectorStream.on('finish', resolve)); // Download stylesheets const hrefsContent = new Map<string, string>(); const newPreconnectUrls = new Set<string>(); for (const hrefItem of hrefList) { const url = this.createNormalizedUrl(hrefItem); if (!url) { continue; } const content = await this.processURL(url); if (content === undefined) { continue; } hrefsContent.set(hrefItem, content); // Add preconnect const preconnectUrl = this.getFontProviderDetails(url)?.preconnectUrl; if (preconnectUrl && !existingPreconnect.has(preconnectUrl)) { newPreconnectUrls.add(preconnectUrl); } } if (hrefsContent.size === 0) { return content; } // Replace link with style tag. const { rewriter, transformedContent } = await htmlRewritingStream(content); rewriter.on('startTag', (tag) => { const { tagName, attrs } = tag; switch (tagName) { case 'head': rewriter.emitStartTag(tag); for (const url of newPreconnectUrls) { rewriter.emitRaw(`<link rel="preconnect" href="${url}" crossorigin>`); } break; case 'link': { const hrefAttr = attrs.some(({ name, value }) => name === 'rel' && value === 'stylesheet') && attrs.find(({ name, value }) => name === 'href' && hrefsContent.has(value)); if (hrefAttr) { const href = hrefAttr.value; const cssContent = hrefsContent.get(href); rewriter.emitRaw(`<style>${cssContent}</style>`); } else { rewriter.emitStartTag(tag); } break; } default: rewriter.emitStartTag(tag); break; } }); return transformedContent(); } private async getResponse(url: URL): Promise<string> { let cacheFile; if (this.cachePath) { const key = createHash(CONTENT_HASH_ALGORITHM).update(`${url}`).digest('hex'); cacheFile = join(this.cachePath, key); } if (cacheFile) { try { const data = await readFile(cacheFile, 'utf8'); // Check for valid content via stored hash if (data.length > CONTENT_HASH_LENGTH) { const storedHash = data.slice(0, CONTENT_HASH_LENGTH); const content = data.slice(CONTENT_HASH_LENGTH); const contentHash = createHash(CONTENT_HASH_ALGORITHM).update(content).digest('base64'); if (storedHash === contentHash) { // Return valid content return content; } else { // Delete corrupted cache content await rm(cacheFile); } } } catch {} } let agent: HttpsProxyAgent<string> | undefined; const httpsProxy = process.env.HTTPS_PROXY ?? process.env.https_proxy; if (httpsProxy) { agent = new HttpsProxyAgent(httpsProxy); } const data = await new Promise<string>((resolve, reject) => { let rawResponse = ''; https .get( url, { agent, headers: { /** * Always use a Windows UA. This is because Google fonts will including hinting in fonts for Windows. * Hinting is a technique used with Windows files to improve appearance however * results in 20-50% larger file sizes. * * @see http://google3/java/com/google/fonts/css/OpenSansWebFontsCssBuilder.java?l=22 * @see https://fonts.google.com/knowledge/glossary/hinting (short) * @see https://glyphsapp.com/learn/hinting-manual-truetype-hinting (deep dive) */ 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36', }, }, (res) => { if (res.statusCode !== 200) { reject( new Error( `Inlining of fonts failed. ${url} returned status code: ${res.statusCode}.`, ), ); return; } res.on('data', (chunk) => (rawResponse += chunk)).on('end', () => resolve(rawResponse)); }, ) .on('error', (e) => reject( new Error( `Inlining of fonts failed. An error has occurred while retrieving ${url} over the internet.\n` + e.message, ), ), ); }); if (cacheFile) { try { const dataHash = createHash(CONTENT_HASH_ALGORITHM).update(data).digest('hex'); await writeFile(cacheFile, dataHash + data); } catch {} } return data; } async processURL(url: string | URL): Promise<string | undefined> { const normalizedURL = url instanceof URL ? url : this.createNormalizedUrl(url); if (!normalizedURL) { return; } const provider = this.getFontProviderDetails(normalizedURL); if (!provider) { return undefined; } let cssContent = await this.getResponse(normalizedURL); if (this.options.minify) { cssContent = cssContent // Comments. .replace(/\/\*([\s\S]*?)\*\//g, '') // New lines. .replace(/\n/g, '') // Safe spaces. .replace(/\s?[{:;]\s+/g, (s) => s.trim()); } return cssContent; } canInlineRequest(url: string): boolean { const normalizedUrl = this.createNormalizedUrl(url); return normalizedUrl ? !!this.getFontProviderDetails(normalizedUrl) : false; } private getFontProviderDetails(url: URL): FontProviderDetails | undefined { return SUPPORTED_PROVIDERS[url.hostname]; } private createNormalizedUrl(value: string): URL | undefined { // Need to convert '//' to 'https://' because the URL parser will fail with '//'. const url = new URL(value.startsWith('//') ? `https:${value}` : value, 'resolve://'); switch (url.protocol) { case 'http:': case 'https:': url.protocol = 'https:'; return url; default: return undefined; } } }
{ "end_byte": 9127, "start_byte": 1139, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/inline-fonts.ts" }
angular-cli/packages/angular/build/src/utils/index-file/ngcm-attribute_spec.ts_0_899
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { addNgcmAttribute } from './ngcm-attribute'; describe('addNgcmAttribute', () => { it('should add the ngcm attribute to the <body> tag', async () => { const result = await addNgcmAttribute(` <html> <head></head> <body><p>hello world!</p></body> </html> `); expect(result).toContain('<body ngcm=""><p>hello world!</p></body>'); }); it('should not override an existing ngcm attribute', async () => { const result = await addNgcmAttribute(` <html> <head></head> <body ngcm="foo"><p>hello world!</p></body> </html> `); expect(result).toContain('<body ngcm="foo"><p>hello world!</p></body>'); }); });
{ "end_byte": 899, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/ngcm-attribute_spec.ts" }
angular-cli/packages/angular/build/src/utils/index-file/inline-fonts_spec.ts_0_4018
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { InlineFontsProcessor } from './inline-fonts'; describe('InlineFontsProcessor', () => { describe('Google fonts', () => { const content = ` <html> <head> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> </head> <body></body> </html>`; it('works with // protocol', async () => { const inlineFontsProcessor = new InlineFontsProcessor({ minify: false, }); const html = await inlineFontsProcessor.process(content.replace('https://', '//')); expect(html).toContain(`format('woff2');`); }); it('should inline supported fonts and icons in HTML', async () => { const inlineFontsProcessor = new InlineFontsProcessor({ minify: false, }); const html = await inlineFontsProcessor.process(` <html> <head> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="theme.css" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet"> </head> <body></body> </html>`); expect(html).not.toContain( 'href="https://fonts.googleapis.com/css?family=Roboto:300,400,500"', ); expect(html).not.toContain('href="https://fonts.googleapis.com/icon?family=Material+Icons"'); expect(html).toContain('href="theme.css"'); expect(html).toContain(`font-family: 'Roboto'`); expect(html).toContain(`font-family: 'Material Icons'`); }); it('should inline multiple fonts from a single request with minification enabled', async () => { const inlineFontsProcessor = new InlineFontsProcessor({ minify: true, }); const html = await inlineFontsProcessor.process(` <html> <head> <link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500%7CGoogle+Sans:400,500%7CRoboto+Mono:400,500%7CMaterial+Icons&display=swap" rel="stylesheet"> <link href="theme.css" rel="stylesheet"> </head> <body></body> </html>`); expect(html).toContain(`'Google Sans'`); expect(html).toContain(`'Roboto'`); expect(html).toContain(`'Roboto Mono'`); expect(html).toContain(`'Material Icons'`); }); it('works with http protocol', async () => { const inlineFontsProcessor = new InlineFontsProcessor({ minify: false, }); const html = await inlineFontsProcessor.process(content.replace('https://', 'http://')); expect(html).toContain(`format('woff2');`); }); it('should remove comments and line breaks when `minifyInlinedCSS` is true', async () => { const inlineFontsProcessor = new InlineFontsProcessor({ minify: true, }); const html = await inlineFontsProcessor.process(content); expect(html).not.toContain('/*'); expect(html).toContain(';font-style:normal;'); }); it('should add preconnect hint', async () => { const inlineFontsProcessor = new InlineFontsProcessor({ minify: false, }); const html = await inlineFontsProcessor.process(content); expect(html).toContain( `<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>`, ); }); }); describe('Adobe Typekit fonts', () => { const content = ` <html> <head> <link href="https://use.typekit.net/plm1izr.css" rel="stylesheet"> </head> <body></body> </html>`; it('should add preconnect hint', async () => { const inlineFontsProcessor = new InlineFontsProcessor({ minify: false, }); const html = await inlineFontsProcessor.process(content); expect(html).toContain(`<link rel="preconnect" href="https://use.typekit.net" crossorigin>`); }); }); });
{ "end_byte": 4018, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/inline-fonts_spec.ts" }
angular-cli/packages/angular/build/src/utils/index-file/valid-self-closing-tags.ts_0_1346
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ /** A list of valid self closing HTML elements */ export const VALID_SELF_CLOSING_TAGS = new Set([ 'area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr', /** SVG tags */ 'animate', 'animateMotion', 'animateTransform', 'circle', 'ellipse', 'feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence', 'line', 'path', 'polygon', 'polyline', 'rect', 'text', 'tspan', 'linearGradient', 'radialGradient', 'stop', 'image', 'pattern', 'defs', 'g', 'marker', 'mask', 'style', 'symbol', 'use', 'view', /** MathML tags */ 'mspace', 'mphantom', 'mrow', 'mfrac', 'msqrt', 'mroot', 'mstyle', 'merror', 'mpadded', 'mtable', ]);
{ "end_byte": 1346, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/valid-self-closing-tags.ts" }
angular-cli/packages/angular/build/src/utils/index-file/add-event-dispatch-contract.ts_0_921
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { readFile } from 'node:fs/promises'; import { htmlRewritingStream } from './html-rewriting-stream'; let jsActionContractScript: string; export async function addEventDispatchContract(html: string): Promise<string> { const { rewriter, transformedContent } = await htmlRewritingStream(html); jsActionContractScript ??= '<script type="text/javascript" id="ng-event-dispatch-contract">' + (await readFile(require.resolve('@angular/core/event-dispatch-contract.min.js'), 'utf-8')) + '</script>'; rewriter.on('startTag', (tag) => { rewriter.emitStartTag(tag); if (tag.tagName === 'body') { rewriter.emitRaw(jsActionContractScript); } }); return transformedContent(); }
{ "end_byte": 921, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/add-event-dispatch-contract.ts" }
angular-cli/packages/angular/build/src/utils/index-file/auto-csp_spec.ts_0_5921
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { autoCsp, hashTextContent } from './auto-csp'; // Utility function to grab the meta tag CSPs from the HTML response. const getCsps = (html: string) => { return Array.from( html.matchAll(/<meta http-equiv="Content-Security-Policy" content="([^"]*)">/g), ).map((m) => m[1]); // Only capture group. }; const ONE_HASH_CSP = /script-src 'strict-dynamic' 'sha256-[^']+' https: 'unsafe-inline';object-src 'none';base-uri 'self';/; const FOUR_HASH_CSP = /script-src 'strict-dynamic' (?:'sha256-[^']+' ){4}https: 'unsafe-inline';object-src 'none';base-uri 'self';/; describe('auto-csp', () => { it('should rewrite a single inline script', async () => { const result = await autoCsp(` <html> <head> </head> <body> <script>console.log('foo');</script> <div>Some text </div> </body> </html> `); const csps = getCsps(result); expect(csps.length).toBe(1); expect(csps[0]).toMatch(ONE_HASH_CSP); expect(csps[0]).toContain(hashTextContent("console.log('foo');")); }); it('should rewrite a single source script', async () => { const result = await autoCsp(` <html> <head> </head> <body> <script src="./main.js"></script> <div>Some text </div> </body> </html> `); const csps = getCsps(result); expect(csps.length).toBe(1); expect(csps[0]).toMatch(ONE_HASH_CSP); expect(result).toContain(`var scripts = [['./main.js', undefined, false, false]];`); }); it('should rewrite a single source script in place', async () => { const result = await autoCsp(` <html> <head> </head> <body> <div>Some text</div> <script src="./main.js"></script> </body> </html> `); const csps = getCsps(result); expect(csps.length).toBe(1); expect(csps[0]).toMatch(ONE_HASH_CSP); // Our loader script appears after the HTML text content. expect(result).toMatch( /Some text<\/div>\s*<script>\s*var scripts = \[\['.\/main.js', undefined, false, false\]\];/, ); }); it('should rewrite a multiple source scripts with attributes', async () => { const result = await autoCsp(` <html> <head> </head> <body> <script src="./main1.js"></script> <script async src="./main2.js"></script> <script type="module" async defer src="./main3.js"></script> <script type="application/not-javascript" src="./main4.js"></script> <div>Some text </div> </body> </html> `); const csps = getCsps(result); expect(csps.length).toBe(1); expect(csps[0]).toMatch(ONE_HASH_CSP); expect(result).toContain( // eslint-disable-next-line max-len `var scripts = [['./main1.js', undefined, false, false],['./main2.js', undefined, true, false],['./main3.js', 'module', true, true]];`, ); // Only one loader script is created. expect(Array.from(result.matchAll(/<script>/g)).length).toEqual(1); }); it('should rewrite source scripts with weird URLs', async () => { const result = await autoCsp(` <html> <head> </head> <body> <script src="/foo&amp;bar"></script> <script src="/one'two\\'three\\\\'four\\\\\\'five"></script> <script src="/one&two&amp;three&amp;amp;four"></script> <script src="./</script>"></script> <div>Some text </div> </body> </html> `); const csps = getCsps(result); expect(csps.length).toBe(1); expect(csps[0]).toMatch(ONE_HASH_CSP); // &amp; encodes correctly expect(result).toContain(`'/foo&bar'`); // Impossible to escape a string and create invalid loader JS with a ' // (Quotes and backslashes work) expect(result).toContain(`'/one\\'two%5C\\'three%5C%5C\\'four%5C%5C%5C\\'five'`); // HTML entities work expect(result).toContain(`'/one&two&three&amp;four'`); // Cannot escape JS context to HTML expect(result).toContain(`'./%3C/script%3E'`); }); it('should rewrite all script tags', async () => { const result = await autoCsp(` <html> <head> </head> <body> <script>console.log('foo');</script> <script src="./main.js"></script> <script src="./main2.js"></script> <script>console.log('bar');</script> <script src="./main3.js"></script> <script src="./main4.js"></script> <div>Some text </div> </body> </html> `); const csps = getCsps(result); expect(csps.length).toBe(1); // Exactly four hashes for the four scripts that remain (inline, loader, inline, loader). expect(csps[0]).toMatch(FOUR_HASH_CSP); expect(csps[0]).toContain(hashTextContent("console.log('foo');")); expect(csps[0]).toContain(hashTextContent("console.log('bar');")); // Loader script for main.js and main2.js appear after 'foo' and before 'bar'. expect(result).toMatch( // eslint-disable-next-line max-len /console.log\('foo'\);<\/script>\s*<script>\s*var scripts = \[\['.\/main.js', undefined, false, false\],\['.\/main2.js', undefined, false, false\]\];[\s\S]*console.log\('bar'\);/, ); // Loader script for main3.js and main4.js appear after 'bar'. expect(result).toMatch( // eslint-disable-next-line max-len /console.log\('bar'\);<\/script>\s*<script>\s*var scripts = \[\['.\/main3.js', undefined, false, false\],\['.\/main4.js', undefined, false, false\]\];/, ); // Exactly 4 scripts should be left. expect(Array.from(result.matchAll(/<script>/g)).length).toEqual(4); }); });
{ "end_byte": 5921, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/index-file/auto-csp_spec.ts" }
angular-cli/packages/angular/build/src/utils/server-rendering/load-esm-from-memory.ts_0_1866
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import type { ApplicationRef, Type } from '@angular/core'; import type { ɵextractRoutesAndCreateRouteTree, ɵgetOrCreateAngularServerApp } from '@angular/ssr'; import { assertIsError } from '../error'; import { loadEsmModule } from '../load-esm'; /** * Represents the exports available from the main server bundle. */ interface MainServerBundleExports { default: (() => Promise<ApplicationRef>) | Type<unknown>; ɵextractRoutesAndCreateRouteTree: typeof ɵextractRoutesAndCreateRouteTree; ɵgetOrCreateAngularServerApp: typeof ɵgetOrCreateAngularServerApp; } /** * Represents the exports available from the server bundle. */ interface ServerBundleExports { reqHandler?: unknown; } export function loadEsmModuleFromMemory( path: './main.server.mjs', ): Promise<MainServerBundleExports>; export function loadEsmModuleFromMemory(path: './server.mjs'): Promise<ServerBundleExports>; export function loadEsmModuleFromMemory( path: './main.server.mjs' | './server.mjs', ): Promise<MainServerBundleExports | ServerBundleExports> { return loadEsmModule(new URL(path, 'memory://')).catch((e) => { assertIsError(e); // While the error is an 'instanceof Error', it is extended with non transferable properties // and cannot be transferred from a worker when using `--import`. This results in the error object // displaying as '[Object object]' when read outside of the worker. Therefore, we reconstruct the error message here. const error: Error & { code?: string } = new Error(e.message); error.stack = e.stack; error.name = e.name; error.code = e.code; throw error; }) as Promise<MainServerBundleExports>; }
{ "end_byte": 1866, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/server-rendering/load-esm-from-memory.ts" }
angular-cli/packages/angular/build/src/utils/server-rendering/utils.ts_0_715
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import type { createRequestHandler } from '@angular/ssr'; import type { createNodeRequestHandler } from '@angular/ssr/node'; export function isSsrNodeRequestHandler( value: unknown, ): value is ReturnType<typeof createNodeRequestHandler> { return typeof value === 'function' && '__ng_node_request_handler__' in value; } export function isSsrRequestHandler( value: unknown, ): value is ReturnType<typeof createRequestHandler> { return typeof value === 'function' && '__ng_request_handler__' in value; }
{ "end_byte": 715, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/server-rendering/utils.ts" }
angular-cli/packages/angular/build/src/utils/server-rendering/routes-extractor-worker.ts_0_1827
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { workerData } from 'worker_threads'; import { OutputMode } from '../../builders/application/schema'; import { ESMInMemoryFileLoaderWorkerData } from './esm-in-memory-loader/loader-hooks'; import { patchFetchToLoadInMemoryAssets } from './fetch-patch'; import { DEFAULT_URL, launchServer } from './launch-server'; import { loadEsmModuleFromMemory } from './load-esm-from-memory'; import { RoutersExtractorWorkerResult } from './models'; export interface ExtractRoutesWorkerData extends ESMInMemoryFileLoaderWorkerData { outputMode: OutputMode | undefined; } /** * This is passed as workerData when setting up the worker via the `piscina` package. */ const { outputMode, hasSsrEntry } = workerData as { outputMode: OutputMode | undefined; hasSsrEntry: boolean; }; let serverURL = DEFAULT_URL; /** Renders an application based on a provided options. */ async function extractRoutes(): Promise<RoutersExtractorWorkerResult> { const { ɵextractRoutesAndCreateRouteTree: extractRoutesAndCreateRouteTree } = await loadEsmModuleFromMemory('./main.server.mjs'); const { routeTree, errors } = await extractRoutesAndCreateRouteTree( serverURL, undefined /** manifest */, true /** invokeGetPrerenderParams */, outputMode === OutputMode.Server /** includePrerenderFallbackRoutes */, ); return { errors, serializedRouteTree: routeTree.toObject(), }; } async function initialize() { if (outputMode !== undefined && hasSsrEntry) { serverURL = await launchServer(); } patchFetchToLoadInMemoryAssets(serverURL); return extractRoutes; } export default initialize();
{ "end_byte": 1827, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/server-rendering/routes-extractor-worker.ts" }
angular-cli/packages/angular/build/src/utils/server-rendering/prerender.ts_0_8417
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { readFile } from 'node:fs/promises'; import { extname, join, posix } from 'node:path'; import { pathToFileURL } from 'node:url'; import { NormalizedApplicationBuildOptions } from '../../builders/application/options'; import { OutputMode } from '../../builders/application/schema'; import { BuildOutputFile, BuildOutputFileType } from '../../tools/esbuild/bundler-context'; import { BuildOutputAsset } from '../../tools/esbuild/bundler-execution-result'; import { assertIsError } from '../error'; import { urlJoin } from '../url'; import { WorkerPool } from '../worker-pool'; import { RouteRenderMode, RoutersExtractorWorkerResult, RoutesExtractorWorkerData, SerializableRouteTreeNode, WritableSerializableRouteTreeNode, } from './models'; import type { RenderWorkerData } from './render-worker'; type PrerenderOptions = NormalizedApplicationBuildOptions['prerenderOptions']; type AppShellOptions = NormalizedApplicationBuildOptions['appShellOptions']; /** * Represents the output of a prerendering process. * * The key is the file path, and the value is an object containing the following properties: * * - `content`: The HTML content or output generated for the corresponding file path. * - `appShellRoute`: A boolean flag indicating whether the content is an app shell. * * @example * { * '/index.html': { content: '<html>...</html>', appShell: false }, * '/shell/index.html': { content: '<html>...</html>', appShellRoute: true } * } */ type PrerenderOutput = Record<string, { content: string; appShellRoute: boolean }>; export async function prerenderPages( workspaceRoot: string, baseHref: string, appShellOptions: AppShellOptions | undefined, prerenderOptions: PrerenderOptions | undefined, outputFiles: Readonly<BuildOutputFile[]>, assets: Readonly<BuildOutputAsset[]>, outputMode: OutputMode | undefined, sourcemap = false, maxThreads = 1, ): Promise<{ output: PrerenderOutput; warnings: string[]; errors: string[]; serializableRouteTreeNode: SerializableRouteTreeNode; }> { const outputFilesForWorker: Record<string, string> = {}; const serverBundlesSourceMaps = new Map<string, string>(); const warnings: string[] = []; const errors: string[] = []; for (const { text, path, type } of outputFiles) { if (type !== BuildOutputFileType.ServerApplication && type !== BuildOutputFileType.ServerRoot) { continue; } // Contains the server runnable application code if (extname(path) === '.map') { serverBundlesSourceMaps.set(path.slice(0, -4), text); } else { outputFilesForWorker[path] = text; } } // Inline sourcemap into JS file. This is needed to make Node.js resolve sourcemaps // when using `--enable-source-maps` when using in memory files. for (const [filePath, map] of serverBundlesSourceMaps) { const jsContent = outputFilesForWorker[filePath]; if (jsContent) { outputFilesForWorker[filePath] = jsContent + `\n//# sourceMappingURL=` + `data:application/json;base64,${Buffer.from(map).toString('base64')}`; } } serverBundlesSourceMaps.clear(); const assetsReversed: Record</** Destination */ string, /** Source */ string> = {}; for (const { source, destination } of assets) { assetsReversed[addLeadingSlash(destination.replace(/\\/g, posix.sep))] = source; } // Get routes to prerender const { errors: extractionErrors, serializedRouteTree: serializableRouteTreeNode } = await getAllRoutes( workspaceRoot, baseHref, outputFilesForWorker, assetsReversed, appShellOptions, prerenderOptions, sourcemap, outputMode, ).catch((err) => { return { errors: [ `An error occurred while extracting routes.\n\n${err.stack ?? err.message ?? err}`, ], serializedRouteTree: [], }; }); errors.push(...extractionErrors); const serializableRouteTreeNodeForPrerender: WritableSerializableRouteTreeNode = []; for (const metadata of serializableRouteTreeNode) { if (outputMode !== OutputMode.Static && metadata.redirectTo) { // Skip redirects if output mode is not static. continue; } if (metadata.route.includes('*')) { // Skip catch all routes from prerender. continue; } switch (metadata.renderMode) { case undefined: /* Legacy building mode */ case RouteRenderMode.Prerender: case RouteRenderMode.AppShell: serializableRouteTreeNodeForPrerender.push(metadata); break; case RouteRenderMode.Server: if (outputMode === OutputMode.Static) { errors.push( `Route '${metadata.route}' is configured with server render mode, but the build 'outputMode' is set to 'static'.`, ); } break; } } if (!serializableRouteTreeNodeForPrerender.length || errors.length > 0) { return { errors, warnings, output: {}, serializableRouteTreeNode, }; } // Render routes const { errors: renderingErrors, output } = await renderPages( baseHref, sourcemap, serializableRouteTreeNodeForPrerender, maxThreads, workspaceRoot, outputFilesForWorker, assetsReversed, appShellOptions, outputMode, ); errors.push(...renderingErrors); return { errors, warnings, output, serializableRouteTreeNode, }; } async function renderPages( baseHref: string, sourcemap: boolean, serializableRouteTreeNode: SerializableRouteTreeNode, maxThreads: number, workspaceRoot: string, outputFilesForWorker: Record<string, string>, assetFilesForWorker: Record<string, string>, appShellOptions: AppShellOptions | undefined, outputMode: OutputMode | undefined, ): Promise<{ output: PrerenderOutput; errors: string[]; }> { const output: PrerenderOutput = {}; const errors: string[] = []; const workerExecArgv = [ '--import', // Loader cannot be an absolute path on Windows. pathToFileURL(join(__dirname, 'esm-in-memory-loader/register-hooks.js')).href, ]; if (sourcemap) { workerExecArgv.push('--enable-source-maps'); } const renderWorker = new WorkerPool({ filename: require.resolve('./render-worker'), maxThreads: Math.min(serializableRouteTreeNode.length, maxThreads), workerData: { workspaceRoot, outputFiles: outputFilesForWorker, assetFiles: assetFilesForWorker, outputMode, hasSsrEntry: !!outputFilesForWorker['server.mjs'], } as RenderWorkerData, execArgv: workerExecArgv, }); try { const renderingPromises: Promise<void>[] = []; const appShellRoute = appShellOptions && addLeadingSlash(appShellOptions.route); const baseHrefWithLeadingSlash = addLeadingSlash(baseHref); for (const { route, redirectTo, renderMode } of serializableRouteTreeNode) { // Remove base href from file output path. const routeWithoutBaseHref = addLeadingSlash( route.slice(baseHrefWithLeadingSlash.length - 1), ); const outPath = posix.join(removeLeadingSlash(routeWithoutBaseHref), 'index.html'); if (typeof redirectTo === 'string') { output[outPath] = { content: generateRedirectStaticPage(redirectTo), appShellRoute: false }; continue; } const isAppShellRoute = renderMode === RouteRenderMode.AppShell || // Legacy handling (renderMode === undefined && appShellRoute === routeWithoutBaseHref); const render: Promise<string | null> = renderWorker.run({ url: route, isAppShellRoute }); const renderResult: Promise<void> = render .then((content) => { if (content !== null) { output[outPath] = { content, appShellRoute: isAppShellRoute }; } }) .catch((err) => { errors.push( `An error occurred while prerendering route '${route}'.\n\n${err.stack ?? err.message ?? err.code ?? err}`, ); void renderWorker.destroy(); }); renderingPromises.push(renderResult); } await Promise.all(renderingPromises); } finally { void renderWorker.destroy(); } return { errors, output, }; }
{ "end_byte": 8417, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/server-rendering/prerender.ts" }
angular-cli/packages/angular/build/src/utils/server-rendering/prerender.ts_8419_11436
async function getAllRoutes( workspaceRoot: string, baseHref: string, outputFilesForWorker: Record<string, string>, assetFilesForWorker: Record<string, string>, appShellOptions: AppShellOptions | undefined, prerenderOptions: PrerenderOptions | undefined, sourcemap: boolean, outputMode: OutputMode | undefined, ): Promise<{ serializedRouteTree: SerializableRouteTreeNode; errors: string[] }> { const { routesFile, discoverRoutes } = prerenderOptions ?? {}; const routes: WritableSerializableRouteTreeNode = []; if (appShellOptions) { routes.push({ route: urlJoin(baseHref, appShellOptions.route), }); } if (routesFile) { const routesFromFile = (await readFile(routesFile, 'utf8')).split(/\r?\n/); for (const route of routesFromFile) { routes.push({ route: urlJoin(baseHref, route.trim()), }); } } if (!discoverRoutes) { return { errors: [], serializedRouteTree: routes }; } const workerExecArgv = [ '--import', // Loader cannot be an absolute path on Windows. pathToFileURL(join(__dirname, 'esm-in-memory-loader/register-hooks.js')).href, ]; if (sourcemap) { workerExecArgv.push('--enable-source-maps'); } const renderWorker = new WorkerPool({ filename: require.resolve('./routes-extractor-worker'), maxThreads: 1, workerData: { workspaceRoot, outputFiles: outputFilesForWorker, assetFiles: assetFilesForWorker, outputMode, hasSsrEntry: !!outputFilesForWorker['server.mjs'], } as RoutesExtractorWorkerData, execArgv: workerExecArgv, }); try { const { serializedRouteTree, errors }: RoutersExtractorWorkerResult = await renderWorker.run( {}, ); return { errors, serializedRouteTree: [...routes, ...serializedRouteTree] }; } catch (err) { assertIsError(err); return { errors: [ `An error occurred while extracting routes.\n\n${err.stack ?? err.message ?? err.code ?? err}`, ], serializedRouteTree: [], }; } finally { void renderWorker.destroy(); } } function addLeadingSlash(value: string): string { return value.charAt(0) === '/' ? value : '/' + value; } function removeLeadingSlash(value: string): string { return value.charAt(0) === '/' ? value.slice(1) : value; } /** * Generates a static HTML page with a meta refresh tag to redirect the user to a specified URL. * * This function creates a simple HTML page that performs a redirect using a meta tag. * It includes a fallback link in case the meta-refresh doesn't work. * * @param url - The URL to which the page should redirect. * @returns The HTML content of the static redirect page. */ function generateRedirectStaticPage(url: string): string { return ` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Redirecting</title> <meta http-equiv="refresh" content="0; url=${url}"> </head> <body> <pre>Redirecting to <a href="${url}">${url}</a></pre> </body> </html> `.trim(); }
{ "end_byte": 11436, "start_byte": 8419, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/server-rendering/prerender.ts" }
angular-cli/packages/angular/build/src/utils/server-rendering/launch-server.ts_0_2075
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import assert from 'node:assert'; import { createServer } from 'node:http'; import { loadEsmModule } from '../load-esm'; import { loadEsmModuleFromMemory } from './load-esm-from-memory'; import { isSsrNodeRequestHandler, isSsrRequestHandler } from './utils'; export const DEFAULT_URL = new URL('http://ng-localhost/'); /** * Launches a server that handles local requests. * * @returns A promise that resolves to the URL of the running server. */ export async function launchServer(): Promise<URL> { const { reqHandler } = await loadEsmModuleFromMemory('./server.mjs'); const { createWebRequestFromNodeRequest, writeResponseToNodeResponse } = await loadEsmModule<typeof import('@angular/ssr/node')>('@angular/ssr/node'); if (!isSsrNodeRequestHandler(reqHandler) && !isSsrRequestHandler(reqHandler)) { return DEFAULT_URL; } const server = createServer((req, res) => { (async () => { // handle request if (isSsrNodeRequestHandler(reqHandler)) { await reqHandler(req, res, (e) => { throw e; }); } else { const webRes = await reqHandler(createWebRequestFromNodeRequest(req)); if (webRes) { await writeResponseToNodeResponse(webRes, res); } else { res.statusCode = 501; res.end('Not Implemented.'); } } })().catch((e) => { res.statusCode = 500; res.end('Internal Server Error.'); // eslint-disable-next-line no-console console.error(e); }); }); server.unref(); await new Promise<void>((resolve) => server.listen(0, 'localhost', resolve)); const serverAddress = server.address(); assert(serverAddress, 'Server address should be defined.'); assert(typeof serverAddress !== 'string', 'Server address should not be a string.'); return new URL(`http://localhost:${serverAddress.port}/`); }
{ "end_byte": 2075, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/server-rendering/launch-server.ts" }
angular-cli/packages/angular/build/src/utils/server-rendering/manifest.ts_0_5915
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { INDEX_HTML_CSR, INDEX_HTML_SERVER, NormalizedApplicationBuildOptions, getLocaleBaseHref, } from '../../builders/application/options'; import type { BuildOutputFile } from '../../tools/esbuild/bundler-context'; import type { PrerenderedRoutesRecord } from '../../tools/esbuild/bundler-execution-result'; export const SERVER_APP_MANIFEST_FILENAME = 'angular-app-manifest.mjs'; export const SERVER_APP_ENGINE_MANIFEST_FILENAME = 'angular-app-engine-manifest.mjs'; const MAIN_SERVER_OUTPUT_FILENAME = 'main.server.mjs'; /** * A mapping of unsafe characters to their escaped Unicode equivalents. */ const UNSAFE_CHAR_MAP: Record<string, string> = { '`': '\\`', '$': '\\$', '\\': '\\\\', }; /** * Escapes unsafe characters in a given string by replacing them with * their Unicode escape sequences. * * @param str - The string to be escaped. * @returns The escaped string where unsafe characters are replaced. */ function escapeUnsafeChars(str: string): string { return str.replace(/[$`\\]/g, (c) => UNSAFE_CHAR_MAP[c]); } /** * Generates the server manifest for the App Engine environment. * * This manifest is used to configure the server-side rendering (SSR) setup for the * Angular application when deployed to Google App Engine. It includes the entry points * for different locales and the base HREF for the application. * * @param i18nOptions - The internationalization options for the application build. This * includes settings for inlining locales and determining the output structure. * @param baseHref - The base HREF for the application. This is used to set the base URL * for all relative URLs in the application. * @param perenderedRoutes - A record mapping static paths to their associated data. * @returns A string representing the content of the SSR server manifest for App Engine. */ export function generateAngularServerAppEngineManifest( i18nOptions: NormalizedApplicationBuildOptions['i18nOptions'], baseHref: string | undefined, perenderedRoutes: PrerenderedRoutesRecord | undefined = {}, ): string { const entryPointsContent: string[] = []; if (i18nOptions.shouldInline) { for (const locale of i18nOptions.inlineLocales) { const importPath = './' + (i18nOptions.flatOutput ? '' : locale + '/') + MAIN_SERVER_OUTPUT_FILENAME; let localeWithBaseHref = getLocaleBaseHref('', i18nOptions, locale) || '/'; // Remove leading and trailing slashes. const start = localeWithBaseHref[0] === '/' ? 1 : 0; const end = localeWithBaseHref[localeWithBaseHref.length - 1] === '/' ? -1 : undefined; localeWithBaseHref = localeWithBaseHref.slice(start, end); entryPointsContent.push(`['${localeWithBaseHref}', () => import('${importPath}')]`); } } else { entryPointsContent.push(`['', () => import('./${MAIN_SERVER_OUTPUT_FILENAME}')]`); } const staticHeaders: string[] = []; for (const [path, { headers }] of Object.entries(perenderedRoutes)) { if (!headers) { continue; } const headersValues: string[] = []; for (const [name, value] of Object.entries(headers)) { headersValues.push(`['${name}', '${encodeURIComponent(value)}']`); } staticHeaders.push(`['${path}', [${headersValues.join(', ')}]]`); } const manifestContent = ` export default { basePath: '${baseHref ?? '/'}', entryPoints: new Map([${entryPointsContent.join(', \n')}]), staticPathsHeaders: new Map([${staticHeaders.join(', \n')}]), }; `; return manifestContent; } /** * Generates the server manifest for the standard Node.js environment. * * This manifest is used to configure the server-side rendering (SSR) setup for the * Angular application when running in a standard Node.js environment. It includes * information about the bootstrap module, whether to inline critical CSS, and any * additional HTML and CSS output files. * * @param additionalHtmlOutputFiles - A map of additional HTML output files generated * during the build process, keyed by their file paths. * @param outputFiles - An array of all output files from the build process, including * JavaScript and CSS files. * @param inlineCriticalCss - A boolean indicating whether critical CSS should be inlined * in the server-side rendered pages. * @param routes - An optional array of route definitions for the application, used for * server-side rendering and routing. * @param locale - An optional string representing the locale or language code to be used for * the application, helping with localization and rendering content specific to the locale. * * @returns A string representing the content of the SSR server manifest for the Node.js * environment. */ export function generateAngularServerAppManifest( additionalHtmlOutputFiles: Map<string, BuildOutputFile>, outputFiles: BuildOutputFile[], inlineCriticalCss: boolean, routes: readonly unknown[] | undefined, locale: string | undefined, ): string { const serverAssetsContent: string[] = []; for (const file of [...additionalHtmlOutputFiles.values(), ...outputFiles]) { if ( file.path === INDEX_HTML_SERVER || file.path === INDEX_HTML_CSR || (inlineCriticalCss && file.path.endsWith('.css')) ) { serverAssetsContent.push(`['${file.path}', async () => \`${escapeUnsafeChars(file.text)}\`]`); } } const manifestContent = ` export default { bootstrap: () => import('./main.server.mjs').then(m => m.default), inlineCriticalCss: ${inlineCriticalCss}, routes: ${JSON.stringify(routes, undefined, 2)}, assets: new Map([${serverAssetsContent.join(', \n')}]), locale: ${locale !== undefined ? `'${locale}'` : undefined}, }; `; return manifestContent; }
{ "end_byte": 5915, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/server-rendering/manifest.ts" }
angular-cli/packages/angular/build/src/utils/server-rendering/fetch-patch.ts_0_2047
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { lookup as lookupMimeType } from 'mrmime'; import { readFile } from 'node:fs/promises'; import { extname } from 'node:path'; import { workerData } from 'node:worker_threads'; /** * This is passed as workerData when setting up the worker via the `piscina` package. */ const { assetFiles } = workerData as { assetFiles: Record</** Destination */ string, /** Source */ string>; }; const assetsCache: Map<string, { headers: undefined | Record<string, string>; content: Buffer }> = new Map(); export function patchFetchToLoadInMemoryAssets(baseURL: URL): void { const originalFetch = globalThis.fetch; const patchedFetch: typeof fetch = async (input, init) => { let url: URL; if (input instanceof URL) { url = input; } else if (typeof input === 'string') { url = new URL(input); } else if (typeof input === 'object' && 'url' in input) { url = new URL(input.url); } else { return originalFetch(input, init); } const { hostname } = url; const pathname = decodeURIComponent(url.pathname); if (hostname !== baseURL.hostname || !assetFiles[pathname]) { // Only handle relative requests or files that are in assets. return originalFetch(input, init); } const cachedAsset = assetsCache.get(pathname); if (cachedAsset) { const { content, headers } = cachedAsset; return new Response(content, { headers, }); } const extension = extname(pathname); const mimeType = lookupMimeType(extension); const content = await readFile(assetFiles[pathname]); const headers = mimeType ? { 'Content-Type': mimeType, } : undefined; assetsCache.set(pathname, { headers, content }); return new Response(content, { headers, }); }; globalThis.fetch = patchedFetch; }
{ "end_byte": 2047, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/server-rendering/fetch-patch.ts" }
angular-cli/packages/angular/build/src/utils/server-rendering/models.ts_0_1368
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import type { RenderMode, ɵextractRoutesAndCreateRouteTree } from '@angular/ssr'; import { ESMInMemoryFileLoaderWorkerData } from './esm-in-memory-loader/loader-hooks'; type Writeable<T extends readonly unknown[]> = T extends readonly (infer U)[] ? U[] : never; export interface RoutesExtractorWorkerData extends ESMInMemoryFileLoaderWorkerData { assetFiles: Record</** Destination */ string, /** Source */ string>; } export type SerializableRouteTreeNode = ReturnType< Awaited<ReturnType<typeof ɵextractRoutesAndCreateRouteTree>>['routeTree']['toObject'] >; export type WritableSerializableRouteTreeNode = Writeable<SerializableRouteTreeNode>; export interface RoutersExtractorWorkerResult { serializedRouteTree: SerializableRouteTreeNode; errors: string[]; } /** * Local copy of `RenderMode` exported from `@angular/ssr`. * This constant is needed to handle interop between CommonJS (CJS) and ES Modules (ESM) formats. * * It maps `RenderMode` enum values to their corresponding numeric identifiers. */ export const RouteRenderMode: Record<keyof typeof RenderMode, RenderMode> = { AppShell: 0, Server: 1, Client: 2, Prerender: 3, };
{ "end_byte": 1368, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/server-rendering/models.ts" }
angular-cli/packages/angular/build/src/utils/server-rendering/render-worker.ts_0_1854
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { workerData } from 'worker_threads'; import type { OutputMode } from '../../builders/application/schema'; import type { ESMInMemoryFileLoaderWorkerData } from './esm-in-memory-loader/loader-hooks'; import { patchFetchToLoadInMemoryAssets } from './fetch-patch'; import { DEFAULT_URL, launchServer } from './launch-server'; import { loadEsmModuleFromMemory } from './load-esm-from-memory'; export interface RenderWorkerData extends ESMInMemoryFileLoaderWorkerData { assetFiles: Record</** Destination */ string, /** Source */ string>; outputMode: OutputMode | undefined; hasSsrEntry: boolean; } export interface RenderOptions { url: string; } /** * This is passed as workerData when setting up the worker via the `piscina` package. */ const { outputMode, hasSsrEntry } = workerData as { outputMode: OutputMode | undefined; hasSsrEntry: boolean; }; let serverURL = DEFAULT_URL; /** * Renders each route in routes and writes them to <outputPath>/<route>/index.html. */ async function renderPage({ url }: RenderOptions): Promise<string | null> { const { ɵgetOrCreateAngularServerApp: getOrCreateAngularServerApp } = await loadEsmModuleFromMemory('./main.server.mjs'); const angularServerApp = getOrCreateAngularServerApp(); const response = await angularServerApp.renderStatic( new URL(url, serverURL), AbortSignal.timeout(30_000), ); return response ? response.text() : null; } async function initialize() { if (outputMode !== undefined && hasSsrEntry) { serverURL = await launchServer(); } patchFetchToLoadInMemoryAssets(serverURL); return renderPage; } export default initialize();
{ "end_byte": 1854, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/server-rendering/render-worker.ts" }
angular-cli/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/register-hooks.ts_0_428
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { register } from 'node:module'; import { pathToFileURL } from 'node:url'; import { workerData } from 'node:worker_threads'; register('./loader-hooks.js', { parentURL: pathToFileURL(__filename), data: workerData });
{ "end_byte": 428, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/register-hooks.ts" }
angular-cli/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/loader-hooks.ts_0_5137
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import assert from 'node:assert'; import { randomUUID } from 'node:crypto'; import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; import { fileURLToPath } from 'url'; import { JavaScriptTransformer } from '../../../tools/esbuild/javascript-transformer'; /** * Node.js ESM loader to redirect imports to in memory files. * @see: https://nodejs.org/api/esm.html#loaders for more information about loaders. */ const MEMORY_URL_SCHEME = 'memory://'; export interface ESMInMemoryFileLoaderWorkerData { outputFiles: Record<string, string>; workspaceRoot: string; } let memoryVirtualRootUrl: string; let outputFiles: Record<string, string>; const javascriptTransformer = new JavaScriptTransformer( // Always enable JIT linking to support applications built with and without AOT. // In a development environment the additional scope information does not // have a negative effect unlike production where final output size is relevant. { sourcemap: true, jit: true }, 1, ); export function initialize(data: ESMInMemoryFileLoaderWorkerData) { // This path does not actually exist but is used to overlay the in memory files with the // actual filesystem for resolution purposes. // A custom URL schema (such as `memory://`) cannot be used for the resolve output because // the in-memory files may use `import.meta.url` in ways that assume a file URL. // `createRequire` is one example of this usage. memoryVirtualRootUrl = pathToFileURL( join(data.workspaceRoot, `.angular/prerender-root/${randomUUID()}/`), ).href; outputFiles = data.outputFiles; } export function resolve( specifier: string, context: { parentURL: undefined | string }, nextResolve: Function, ) { // In-memory files loaded from external code will contain a memory scheme if (specifier.startsWith(MEMORY_URL_SCHEME)) { let memoryUrl; try { memoryUrl = new URL(specifier); } catch { assert.fail('External code attempted to use malformed memory scheme: ' + specifier); } // Resolve with a URL based from the virtual filesystem root return { format: 'module', shortCircuit: true, url: new URL(memoryUrl.pathname.slice(1), memoryVirtualRootUrl).href, }; } // Use next/default resolve if the parent is not from the virtual root if (!context.parentURL?.startsWith(memoryVirtualRootUrl)) { return nextResolve(specifier, context); } // Check for `./` and `../` relative specifiers const isRelative = specifier[0] === '.' && (specifier[1] === '/' || (specifier[1] === '.' && specifier[2] === '/')); // Relative specifiers from memory file should be based from the parent memory location if (isRelative) { let specifierUrl; try { specifierUrl = new URL(specifier, context.parentURL); } catch {} if ( specifierUrl?.pathname && Object.hasOwn(outputFiles, specifierUrl.href.slice(memoryVirtualRootUrl.length)) ) { return { format: 'module', shortCircuit: true, url: specifierUrl.href, }; } assert.fail( `In-memory ESM relative file should always exist: '${context.parentURL}' --> '${specifier}'`, ); } // Update the parent URL to allow for module resolution for the workspace. // This handles bare specifiers (npm packages) and absolute paths. // Defer to the next hook in the chain, which would be the // Node.js default resolve if this is the last user-specified loader. return nextResolve(specifier, { ...context, parentURL: new URL('index.js', memoryVirtualRootUrl).href, }); } export async function load(url: string, context: { format?: string | null }, nextLoad: Function) { const { format } = context; // Load the file from memory if the URL is based in the virtual root if (url.startsWith(memoryVirtualRootUrl)) { const source = outputFiles[url.slice(memoryVirtualRootUrl.length)]; assert(source !== undefined, 'Resolved in-memory ESM file should always exist: ' + url); // In-memory files have already been transformer during bundling and can be returned directly return { format, shortCircuit: true, source, }; } // Only module files potentially require transformation. Angular libraries that would // need linking are ESM only. if (format === 'module' && isFileProtocol(url)) { const filePath = fileURLToPath(url); const source = await javascriptTransformer.transformFile(filePath); return { format, shortCircuit: true, source, }; } // Let Node.js handle all other URLs. return nextLoad(url); } function isFileProtocol(url: string): boolean { return url.startsWith('file://'); } function handleProcessExit(): void { void javascriptTransformer.close(); } process.once('exit', handleProcessExit); process.once('SIGINT', handleProcessExit); process.once('uncaughtException', handleProcessExit);
{ "end_byte": 5137, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/build/src/utils/server-rendering/esm-in-memory-loader/loader-hooks.ts" }
angular-cli/packages/angular/create/README.md_0_515
# `@angular/create` ## Create an Angular CLI workspace Scaffold an Angular CLI workspace without needing to install the Angular CLI globally. All of the [ng new](https://angular.dev/cli/new) options and features are supported. ## Usage ### npm ``` npm init @angular@latest [project-name] -- [...options] ``` ### yarn ``` yarn create @angular [project-name] [...options] ``` ### pnpm ``` pnpm create @angular [project-name] [...options] ``` ### bun ``` bun create @angular [project-name] [...options] ```
{ "end_byte": 515, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/create/README.md" }
angular-cli/packages/angular/create/BUILD.bazel_0_846
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.dev/license load("//tools:defaults.bzl", "pkg_npm", "ts_library") licenses(["notice"]) ts_library( name = "create", package_name = "@angular/create", srcs = ["src/index.ts"], deps = [ "//packages/angular/cli:angular-cli", "@npm//@types/node", ], ) genrule( name = "license", srcs = ["//:LICENSE"], outs = ["LICENSE"], cmd = "cp $(execpath //:LICENSE) $@", ) pkg_npm( name = "npm_package", pkg_deps = [ "//packages/angular/cli:package.json", ], tags = ["release-package"], visibility = ["//visibility:public"], deps = [ ":README.md", ":create", ":license", ], )
{ "end_byte": 846, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/create/BUILD.bazel" }
angular-cli/packages/angular/create/src/index.ts_0_1060
#!/usr/bin/env node /** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { spawnSync } from 'child_process'; import { join } from 'path'; const binPath = join(require.resolve('@angular/cli/package.json'), '../bin/ng.js'); const args = process.argv.slice(2); const hasPackageManagerArg = args.some((a) => a.startsWith('--package-manager')); if (!hasPackageManagerArg) { // Ex: yarn/1.22.18 npm/? node/v16.15.1 linux x64 const packageManager = process.env['npm_config_user_agent']?.split('/')[0]; if (packageManager && ['npm', 'pnpm', 'yarn', 'cnpm', 'bun'].includes(packageManager)) { args.push('--package-manager', packageManager); } } // Invoke ng new with any parameters provided. const { error } = spawnSync(process.execPath, [binPath, 'new', ...args], { stdio: 'inherit', }); if (error) { // eslint-disable-next-line no-console console.error(error); process.exitCode = 1; }
{ "end_byte": 1060, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/angular/create/src/index.ts" }
angular-cli/packages/ngtools/webpack/README.md_0_3452
# Angular Compiler Webpack Plugin Webpack 5.x plugin for the Angular Ahead-of-Time compiler. The plugin also supports Angular JIT mode. When this plugin is used outside of the Angular CLI, the Ivy linker will also be needed to support the usage of Angular libraries. An example configuration of the Babel-based Ivy linker is provided in the linker section. For additional information regarding the linker, please see: https://angular.dev/tools/libraries/creating-libraries#consuming-partial-ivy-code-outside-the-angular-cli ## Usage In your webpack config, add the following plugin and loader. ```typescript import { AngularWebpackPlugin } from '@ngtools/webpack'; exports = { /* ... */ module: { rules: [ /* ... */ { test: /\.[jt]sx?$/, loader: '@ngtools/webpack', }, ], }, plugins: [ new AngularWebpackPlugin({ tsconfig: 'path/to/tsconfig.json', // ... other options as needed }), ], }; ``` The loader works with webpack plugin to compile the application's TypeScript. It is important to include both, and to not include any other TypeScript loader. ## Options - `tsconfig` [default: `tsconfig.json`] - The path to the application's TypeScript Configuration file. In the `tsconfig.json`, you can pass options to the Angular Compiler with `angularCompilerOptions`. Relative paths will be resolved from the Webpack compilation's context. - `compilerOptions` [default: none] - Overrides options in the application's TypeScript Configuration file (`tsconfig.json`). - `jitMode` [default: `false`] - Enables JIT compilation and do not refactor the code to bootstrap. This replaces `templateUrl: "string"` with `template: require("string")` (and similar for styles) to allow for webpack to properly link the resources. - `directTemplateLoading` [default: `true`] - Causes the plugin to load component templates (HTML) directly from the filesystem. This is more efficient if only using the `raw-loader` to load component templates. Do not enable this option if additional loaders are configured for component templates. - `fileReplacements` [default: none] - Allows replacing TypeScript files with other TypeScript files in the build. This option acts on fully resolved file paths. - `inlineStyleFileExtension` [default: none] - When set inline component styles will be processed by Webpack as files with the provided extension. ## Ivy Linker The Ivy linker can be setup by using the Webpack `babel-loader` package. If not already installed, add the `babel-loader` package using your project's package manager. Then in your webpack config, add the `babel-loader` with the following configuration. If the `babel-loader` is already present in your configuration, the linker plugin can be added to the existing loader configuration as well. Enabling caching for the `babel-loader` is recommended to avoid reprocessing libraries on every build. For additional information regarding the `babel-loader` package, please see: https://github.com/babel/babel-loader/tree/main#readme ```typescript import linkerPlugin from '@angular/compiler-cli/linker/babel'; exports = { /* ... */ module: { rules: [ /* ... */ { test: /\.[cm]?js$/, use: { loader: 'babel-loader', options: { cacheDirectory: true, compact: false, plugins: [linkerPlugin], }, }, }, ], }, }; ```
{ "end_byte": 3452, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/README.md" }
angular-cli/packages/ngtools/webpack/BUILD.bazel_0_2088
# Copyright Google Inc. All Rights Reserved. # # Use of this source code is governed by an MIT-style license that can be # found in the LICENSE file at https://angular.dev/license load("@npm//@angular/build-tooling/bazel/api-golden:index.bzl", "api_golden_test_npm_package") load("@npm//@bazel/jasmine:index.bzl", "jasmine_node_test") load("//tools:defaults.bzl", "pkg_npm", "ts_library") licenses(["notice"]) package(default_visibility = ["//visibility:public"]) ts_library( name = "webpack", package_name = "@ngtools/webpack", srcs = glob( include = [ "src/**/*.ts", ], exclude = [ "src/**/*_spec.ts", "src/**/*_spec_helpers.ts", ], ), data = [ "package.json", ], module_name = "@ngtools/webpack", module_root = "src/index.d.ts", deps = [ "@npm//@angular/compiler-cli", "@npm//@types/node", "@npm//typescript", "@npm//webpack", ], ) ts_library( name = "webpack_test_lib", testonly = True, srcs = glob( include = [ "src/**/*_spec.ts", "src/**/*_spec_helpers.ts", ], ), deps = [ ":webpack", "//packages/angular_devkit/core", "@npm//@angular/compiler", "@npm//jasmine", "@npm//typescript", ], ) jasmine_node_test( name = "webpack_test", srcs = [":webpack_test_lib"], deps = [ "@npm//jasmine", "@npm//source-map", "@npm//tslib", ], ) genrule( name = "license", srcs = ["//:LICENSE"], outs = ["LICENSE"], cmd = "cp $(execpath //:LICENSE) $@", ) pkg_npm( name = "npm_package", tags = ["release-package"], deps = [ ":README.md", ":license", ":webpack", ], ) api_golden_test_npm_package( name = "ngtools_webpack_api", data = [ ":npm_package", "//goldens:public-api", ], golden_dir = "angular_cli/goldens/public-api/ngtools/webpack", npm_package = "angular_cli/packages/ngtools/webpack/npm_package", )
{ "end_byte": 2088, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/BUILD.bazel" }
angular-cli/packages/ngtools/webpack/src/paths-plugin.ts_0_8642
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as path from 'path'; import { CompilerOptions } from 'typescript'; import type { Resolver } from 'webpack'; // eslint-disable-next-line @typescript-eslint/no-empty-interface export interface TypeScriptPathsPluginOptions extends Pick<CompilerOptions, 'paths' | 'baseUrl'> {} // Extract ResolverRequest type from Webpack types since it is not directly exported type ResolverRequest = NonNullable<Parameters<Parameters<Resolver['resolve']>[4]>[2]>; interface PathPluginResolverRequest extends ResolverRequest { context?: { issuer?: string; }; typescriptPathMapped?: boolean; } interface PathPattern { starIndex: number; prefix: string; suffix?: string; potentials: { hasStar: boolean; prefix: string; suffix?: string }[]; } export class TypeScriptPathsPlugin { private baseUrl?: string; private patterns?: PathPattern[]; constructor(options?: TypeScriptPathsPluginOptions) { if (options) { this.update(options); } } /** * Update the plugin with new path mapping option values. * The options will also be preprocessed to reduce the overhead of individual resolve actions * during a build. * * @param options The `paths` and `baseUrl` options from TypeScript's `CompilerOptions`. */ update(options: TypeScriptPathsPluginOptions): void { this.baseUrl = options.baseUrl; this.patterns = undefined; if (options.paths) { for (const [pattern, potentials] of Object.entries(options.paths)) { // Ignore any entries that would not result in a new mapping if (potentials.length === 0 || potentials.every((potential) => potential === '*')) { continue; } const starIndex = pattern.indexOf('*'); let prefix = pattern; let suffix; if (starIndex > -1) { prefix = pattern.slice(0, starIndex); if (starIndex < pattern.length - 1) { suffix = pattern.slice(starIndex + 1); } } this.patterns ??= []; this.patterns.push({ starIndex, prefix, suffix, potentials: potentials.map((potential) => { const potentialStarIndex = potential.indexOf('*'); if (potentialStarIndex === -1) { return { hasStar: false, prefix: potential }; } return { hasStar: true, prefix: potential.slice(0, potentialStarIndex), suffix: potentialStarIndex < potential.length - 1 ? potential.slice(potentialStarIndex + 1) : undefined, }; }), }); } // Sort patterns so that exact matches take priority then largest prefix match this.patterns?.sort((a, b) => { if (a.starIndex === -1) { return -1; } else if (b.starIndex === -1) { return 1; } else { return b.starIndex - a.starIndex; } }); } } apply(resolver: Resolver): void { const target = resolver.ensureHook('resolve'); // To support synchronous resolvers this hook cannot be promise based. // Webpack supports synchronous resolution with `tap` and `tapAsync` hooks. resolver .getHook('described-resolve') .tapAsync( 'TypeScriptPathsPlugin', (request: PathPluginResolverRequest, resolveContext, callback) => { // Preprocessing of the options will ensure that `patterns` is either undefined or has elements to check if (!this.patterns) { callback(); return; } if (!request || request.typescriptPathMapped) { callback(); return; } const originalRequest = request.request || request.path; if (!originalRequest) { callback(); return; } // Only work on Javascript/TypeScript issuers. if (!request?.context?.issuer?.match(/\.[cm]?[jt]sx?$/)) { callback(); return; } // Absolute requests are not mapped if (path.isAbsolute(originalRequest)) { callback(); return; } switch (originalRequest[0]) { case '.': // Relative requests are not mapped callback(); return; case '!': // Ignore all webpack special requests if (originalRequest.length > 1 && originalRequest[1] === '!') { callback(); return; } break; } // A generator is used to limit the amount of replacements requests that need to be created. // For example, if the first one resolves, any others are not needed and do not need // to be created. const requests = this.createReplacementRequests(request, originalRequest); const tryResolve = () => { const next = requests.next(); if (next.done) { callback(); return; } resolver.doResolve( target, next.value, '', resolveContext, (error: Error | null | undefined, result: ResolverRequest | null | undefined) => { if (error) { callback(error); } else if (result) { callback(undefined, result); } else { tryResolve(); } }, ); }; tryResolve(); }, ); } *findReplacements(originalRequest: string): IterableIterator<string> { if (!this.patterns) { return; } // check if any path mapping rules are relevant for (const { starIndex, prefix, suffix, potentials } of this.patterns) { let partial; if (starIndex === -1) { // No star means an exact match is required if (prefix === originalRequest) { partial = ''; } } else if (starIndex === 0 && !suffix) { // Everything matches a single wildcard pattern ("*") partial = originalRequest; } else if (!suffix) { // No suffix means the star is at the end of the pattern if (originalRequest.startsWith(prefix)) { partial = originalRequest.slice(prefix.length); } } else { // Star was in the middle of the pattern if (originalRequest.startsWith(prefix) && originalRequest.endsWith(suffix)) { partial = originalRequest.substring( prefix.length, originalRequest.length - suffix.length, ); } } // If request was not matched, move on to the next pattern if (partial === undefined) { continue; } // Create the full replacement values based on the original request and the potentials // for the successfully matched pattern. for (const { hasStar, prefix, suffix } of potentials) { let replacement = prefix; if (hasStar) { replacement += partial; if (suffix) { replacement += suffix; } } yield replacement; } } } *createReplacementRequests( request: PathPluginResolverRequest, originalRequest: string, ): IterableIterator<PathPluginResolverRequest> { for (const replacement of this.findReplacements(originalRequest)) { const targetPath = path.resolve(this.baseUrl ?? '', replacement); // Resolution in the original callee location, but with the updated request // to point to the mapped target location. yield { ...request, request: targetPath, typescriptPathMapped: true, }; // If there is no extension. i.e. the target does not refer to an explicit // file, then this is a candidate for module/package resolution. const canBeModule = path.extname(targetPath) === ''; if (canBeModule) { // Resolution in the target location, preserving the original request. // This will work with the `resolve-in-package` resolution hook, supporting // package exports for e.g. locally-built APF libraries. yield { ...request, path: targetPath, typescriptPathMapped: true, }; } } } }
{ "end_byte": 8642, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/paths-plugin.ts" }
angular-cli/packages/ngtools/webpack/src/resource_loader.ts_0_802
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import assert from 'node:assert'; import { Buffer } from 'node:buffer'; import * as path from 'node:path'; import * as vm from 'node:vm'; import type { Asset, Compilation } from 'webpack'; import { addError } from './ivy/diagnostics'; import { normalizePath } from './ivy/paths'; import { CompilationWithInlineAngularResource, InlineAngularResourceLoaderPath, InlineAngularResourceSymbol, } from './loaders/inline-resource'; import { NG_COMPONENT_RESOURCE_QUERY } from './transformers/replace_resources'; interface CompilationOutput { content: string; map?: string; success: boolean; }
{ "end_byte": 802, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/resource_loader.ts" }
angular-cli/packages/ngtools/webpack/src/resource_loader.ts_804_10653
export class WebpackResourceLoader { private _parentCompilation?: Compilation; private _fileDependencies = new Map<string, Set<string>>(); private _reverseDependencies = new Map<string, Set<string>>(); private fileCache?: Map<string, CompilationOutput>; private assetCache?: Map<string, Asset>; private modifiedResources = new Set<string>(); private outputPathCounter = 1; private readonly inlineDataLoaderPath = InlineAngularResourceLoaderPath; constructor(shouldCache: boolean) { if (shouldCache) { this.fileCache = new Map(); this.assetCache = new Map(); } } update(parentCompilation: Compilation, changedFiles?: Iterable<string>) { this._parentCompilation = parentCompilation; // Update resource cache and modified resources this.modifiedResources.clear(); if (changedFiles) { for (const changedFile of changedFiles) { const changedFileNormalized = normalizePath(changedFile); this.assetCache?.delete(changedFileNormalized); for (const affectedResource of this.getAffectedResources(changedFile)) { const affectedResourceNormalized = normalizePath(affectedResource); this.fileCache?.delete(affectedResourceNormalized); this.modifiedResources.add(affectedResource); for (const effectedDependencies of this.getResourceDependencies( affectedResourceNormalized, )) { this.assetCache?.delete(normalizePath(effectedDependencies)); } } } } else { this.fileCache?.clear(); this.assetCache?.clear(); } // Re-emit all assets for un-effected files if (this.assetCache) { for (const [, { name, source, info }] of this.assetCache) { this._parentCompilation.emitAsset(name, source, info); } } } clearParentCompilation() { this._parentCompilation = undefined; } getModifiedResourceFiles() { return this.modifiedResources; } getResourceDependencies(filePath: string) { return this._fileDependencies.get(filePath) || []; } getAffectedResources(file: string) { return this._reverseDependencies.get(file) || []; } setAffectedResources(file: string, resources: Iterable<string>) { this._reverseDependencies.set(file, new Set(resources)); } // eslint-disable-next-line max-lines-per-function private async _compile( filePath?: string, data?: string, fileExtension?: string, resourceType?: 'style' | 'template', containingFile?: string, ): Promise<CompilationOutput> { if (!this._parentCompilation) { throw new Error('WebpackResourceLoader cannot be used without parentCompilation'); } const { context, webpack } = this._parentCompilation.compiler; const { EntryPlugin, NormalModule, library, node, sources, util: { createHash }, } = webpack; const getEntry = (): string => { if (filePath) { return `${filePath}?${NG_COMPONENT_RESOURCE_QUERY}`; } else if (resourceType) { return ( // app.component.ts-2.css?ngResource!=!@ngtools/webpack/src/loaders/inline-resource.js!app.component.ts `${containingFile}-${this.outputPathCounter}.${fileExtension}` + `?${NG_COMPONENT_RESOURCE_QUERY}!=!${this.inlineDataLoaderPath}!${containingFile}` ); } else if (data) { // Create a special URL for reading the resource from memory return `angular-resource:${resourceType},${createHash('xxhash64') .update(data) .digest('hex')}`; } throw new Error(`"filePath", "resourceType" or "data" must be specified.`); }; const entry = getEntry(); // Simple sanity check. if (filePath?.match(/\.[jt]s$/)) { throw new Error( `Cannot use a JavaScript or TypeScript file (${filePath}) in a component's styleUrls or templateUrl.`, ); } const outputFilePath = filePath || `${containingFile}-angular-inline--${this.outputPathCounter++}.${ resourceType === 'template' ? 'html' : 'css' }`; const outputOptions = { filename: outputFilePath, library: { type: 'var', name: 'resource', }, }; const childCompiler = this._parentCompilation.createChildCompiler( 'angular-compiler:resource', outputOptions, [ new node.NodeTemplatePlugin(), new node.NodeTargetPlugin(), new EntryPlugin(context, entry, { name: 'resource' }), new library.EnableLibraryPlugin('var'), ], ); childCompiler.hooks.thisCompilation.tap( 'angular-compiler', (compilation, { normalModuleFactory }) => { // If no data is provided, the resource will be read from the filesystem if (data !== undefined) { normalModuleFactory.hooks.resolveForScheme .for('angular-resource') .tap('angular-compiler', (resourceData) => { if (filePath) { resourceData.path = filePath; resourceData.resource = filePath; } return true; }); NormalModule.getCompilationHooks(compilation) .readResourceForScheme.for('angular-resource') .tap('angular-compiler', () => data); (compilation as CompilationWithInlineAngularResource)[InlineAngularResourceSymbol] = data; } compilation.hooks.additionalAssets.tap('angular-compiler', () => { const asset = compilation.assets[outputFilePath]; if (!asset) { return; } try { const output = this._evaluate(outputFilePath, asset.source().toString()); if (typeof output === 'string') { compilation.assets[outputFilePath] = new sources.RawSource(output); } } catch (error) { assert(error instanceof Error, 'catch clause variable is not an Error instance'); // Use compilation errors, as otherwise webpack will choke addError(compilation, error.message); } }); }, ); let finalContent: string | undefined; childCompiler.hooks.compilation.tap('angular-compiler', (childCompilation) => { childCompilation.hooks.processAssets.tap( { name: 'angular-compiler', stage: webpack.Compilation.PROCESS_ASSETS_STAGE_REPORT }, () => { finalContent = childCompilation.assets[outputFilePath]?.source().toString(); for (const { files } of childCompilation.chunks) { for (const file of files) { childCompilation.deleteAsset(file); } } }, ); }); return new Promise<CompilationOutput>((resolve, reject) => { childCompiler.runAsChild((error, _, childCompilation) => { if (error) { reject(error); return; } else if (!childCompilation) { reject(new Error('Unknown child compilation error')); return; } // Workaround to attempt to reduce memory usage of child compilations. // This removes the child compilation from the main compilation and manually propagates // all dependencies, warnings, and errors. const parent = childCompiler.parentCompilation; if (parent) { parent.children = parent.children.filter((child) => child !== childCompilation); let fileDependencies: Set<string> | undefined; for (const dependency of childCompilation.fileDependencies) { // Skip paths that do not appear to be files (have no extension). // `fileDependencies` can contain directories and not just files which can // cause incorrect cache invalidation on rebuilds. if (!path.extname(dependency)) { continue; } if (data && containingFile && dependency.endsWith(entry)) { // use containing file if the resource was inline parent.fileDependencies.add(containingFile); } else { parent.fileDependencies.add(dependency); } // Save the dependencies for this resource. if (filePath) { const resolvedFile = normalizePath(dependency); const entry = this._reverseDependencies.get(resolvedFile); if (entry) { entry.add(filePath); } else { this._reverseDependencies.set(resolvedFile, new Set([filePath])); } if (fileDependencies) { fileDependencies.add(dependency); } else { fileDependencies = new Set([dependency]); this._fileDependencies.set(filePath, fileDependencies); } } } parent.contextDependencies.addAll(childCompilation.contextDependencies); parent.missingDependencies.addAll(childCompilation.missingDependencies); parent.buildDependencies.addAll(childCompilation.buildDependencies); parent.warnings.push(...childCompilation.warnings); parent.errors.push(...childCompilation.errors); if (this.assetCache) { for (const { info, name, source } of childCompilation.getAssets()) { // Use the originating file as the cache key if present // Otherwise, generate a cache key based on the generated name const cacheKey = info.sourceFilename ?? `!![GENERATED]:${name}`; this.assetCache.set(cacheKey, { info, name, source }); } } } resolve({ content: finalContent ?? '', success: childCompilation.errors?.length === 0, }); }); }); }
{ "end_byte": 10653, "start_byte": 804, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/resource_loader.ts" }
angular-cli/packages/ngtools/webpack/src/resource_loader.ts_10657_12425
private _evaluate(filename: string, source: string): string | null { // Evaluate code // css-loader requires the btoa function to exist to correctly generate inline sourcemaps const context: { btoa: (input: string) => string; resource?: string | { default?: string } } = { btoa(input) { return Buffer.from(input).toString('base64'); }, }; try { vm.runInNewContext(source, context, { filename }); } catch { // Error are propagated through the child compilation. return null; } if (typeof context.resource === 'string') { return context.resource; } else if (typeof context.resource?.default === 'string') { return context.resource.default; } throw new Error(`The loader "${filename}" didn't return a string.`); } async get(filePath: string): Promise<string> { const normalizedFile = normalizePath(filePath); let compilationResult = this.fileCache?.get(normalizedFile); if (compilationResult === undefined) { // cache miss so compile resource compilationResult = await this._compile(filePath); // Only cache if compilation was successful if (this.fileCache && compilationResult.success) { this.fileCache.set(normalizedFile, compilationResult); } } return compilationResult.content; } async process( data: string, fileExtension: string | undefined, resourceType: 'template' | 'style', containingFile?: string, ): Promise<string> { if (data.trim().length === 0) { return ''; } const compilationResult = await this._compile( undefined, data, fileExtension, resourceType, containingFile, ); return compilationResult.content; } }
{ "end_byte": 12425, "start_byte": 10657, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/resource_loader.ts" }
angular-cli/packages/ngtools/webpack/src/index.ts_0_344
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export { AngularWebpackLoaderPath, AngularWebpackPlugin, type AngularWebpackPluginOptions, imageDomains, default, } from './ivy';
{ "end_byte": 344, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/index.ts" }
angular-cli/packages/ngtools/webpack/src/benchmark.ts_0_581
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ // Internal benchmark reporting flag. // Use with CLI --no-progress flag for best results. // This should be false for commited code. const _benchmark = false; /* eslint-disable no-console */ export function time(label: string) { if (_benchmark) { console.time(label); } } export function timeEnd(label: string) { if (_benchmark) { console.timeEnd(label); } }
{ "end_byte": 581, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/benchmark.ts" }
angular-cli/packages/ngtools/webpack/src/ivy/plugin.ts_0_2413
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import type { CompilerHost, CompilerOptions, NgtscProgram } from '@angular/compiler-cli'; import { strict as assert } from 'assert'; import * as ts from 'typescript'; import type { Compilation, Compiler, Module, NormalModule } from 'webpack'; import { TypeScriptPathsPlugin } from '../paths-plugin'; import { WebpackResourceLoader } from '../resource_loader'; import { SourceFileCache } from './cache'; import { DiagnosticsReporter, addError, addWarning, createDiagnosticsReporter, } from './diagnostics'; import { augmentHostWithCaching, augmentHostWithDependencyCollection, augmentHostWithReplacements, augmentHostWithResources, augmentHostWithSubstitutions, augmentProgramWithVersioning, } from './host'; import { externalizePath, normalizePath } from './paths'; import { AngularPluginSymbol, EmitFileResult, FileEmitter, FileEmitterCollection } from './symbol'; import { InputFileSystemSync, createWebpackSystem } from './system'; import { createAotTransformers, createJitTransformers, mergeTransformers } from './transformation'; /** * The threshold used to determine whether Angular file diagnostics should optimize for full programs * or single files. If the number of affected files for a build is more than the threshold, full * program optimization will be used. */ const DIAGNOSTICS_AFFECTED_THRESHOLD = 1; export const imageDomains = new Set<string>(); export interface AngularWebpackPluginOptions { tsconfig: string; compilerOptions?: CompilerOptions; fileReplacements: Record<string, string>; substitutions: Record<string, string>; directTemplateLoading: boolean; emitClassMetadata: boolean; emitNgModuleScope: boolean; emitSetClassDebugInfo?: boolean; jitMode: boolean; inlineStyleFileExtension?: string; } /** * The Angular compilation state that is maintained across each Webpack compilation. */ interface AngularCompilationState { resourceLoader?: WebpackResourceLoader; previousUnused?: Set<string>; pathsPlugin: TypeScriptPathsPlugin; } const PLUGIN_NAME = 'angular-compiler'; const compilationFileEmitters = new WeakMap<Compilation, FileEmitterCollection>(); interface FileEmitHistoryItem { length: number; hash: Uint8Array; }
{ "end_byte": 2413, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/ivy/plugin.ts" }
angular-cli/packages/ngtools/webpack/src/ivy/plugin.ts_2415_11741
export class AngularWebpackPlugin { private readonly pluginOptions: AngularWebpackPluginOptions; private compilerCliModule?: typeof import('@angular/compiler-cli'); private compilerCliToolingModule?: typeof import('@angular/compiler-cli/private/tooling'); private watchMode?: boolean; private ngtscNextProgram?: NgtscProgram; private builder?: ts.EmitAndSemanticDiagnosticsBuilderProgram; private sourceFileCache?: SourceFileCache; private webpackCache?: ReturnType<Compilation['getCache']>; private webpackCreateHash?: Compiler['webpack']['util']['createHash']; private readonly fileDependencies = new Map<string, Set<string>>(); private readonly requiredFilesToEmit = new Set<string>(); private readonly requiredFilesToEmitCache = new Map<string, EmitFileResult | undefined>(); private readonly fileEmitHistory = new Map<string, FileEmitHistoryItem>(); constructor(options: Partial<AngularWebpackPluginOptions> = {}) { this.pluginOptions = { emitClassMetadata: false, emitNgModuleScope: false, jitMode: false, fileReplacements: {}, substitutions: {}, directTemplateLoading: true, tsconfig: 'tsconfig.json', ...options, }; } private get compilerCli(): typeof import('@angular/compiler-cli') { // The compilerCliModule field is guaranteed to be defined during a compilation // due to the `beforeCompile` hook. Usage of this property accessor prior to the // hook execution is an implementation error. assert.ok(this.compilerCliModule, `'@angular/compiler-cli' used prior to Webpack compilation.`); return this.compilerCliModule; } private get compilerCliTooling(): typeof import('@angular/compiler-cli/private/tooling') { // The compilerCliToolingModule field is guaranteed to be defined during a compilation // due to the `beforeCompile` hook. Usage of this property accessor prior to the // hook execution is an implementation error. assert.ok( this.compilerCliToolingModule, `'@angular/compiler-cli' used prior to Webpack compilation.`, ); return this.compilerCliToolingModule; } get options(): AngularWebpackPluginOptions { return this.pluginOptions; } apply(compiler: Compiler): void { const { NormalModuleReplacementPlugin, util } = compiler.webpack; this.webpackCreateHash = util.createHash; // Setup file replacements with webpack for (const [key, value] of Object.entries(this.pluginOptions.fileReplacements)) { new NormalModuleReplacementPlugin( new RegExp('^' + key.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&') + '$'), value, ).apply(compiler); } // Set resolver options const pathsPlugin = new TypeScriptPathsPlugin(); compiler.hooks.afterResolvers.tap(PLUGIN_NAME, (compiler) => { compiler.resolverFactory.hooks.resolveOptions .for('normal') .tap(PLUGIN_NAME, (resolveOptions) => { resolveOptions.plugins ??= []; resolveOptions.plugins.push(pathsPlugin); return resolveOptions; }); }); // Load the compiler-cli if not already available compiler.hooks.beforeCompile.tapPromise(PLUGIN_NAME, () => this.initializeCompilerCli()); const compilationState: AngularCompilationState = { pathsPlugin }; compiler.hooks.thisCompilation.tap(PLUGIN_NAME, (compilation) => { try { this.setupCompilation(compilation, compilationState); } catch (error) { addError( compilation, `Failed to initialize Angular compilation - ${ error instanceof Error ? error.message : error }`, ); } }); } private setupCompilation(compilation: Compilation, state: AngularCompilationState): void { const compiler = compilation.compiler; // Register plugin to ensure deterministic emit order in multi-plugin usage const emitRegistration = this.registerWithCompilation(compilation); this.watchMode = compiler.watchMode; // Initialize webpack cache if (!this.webpackCache && compilation.options.cache) { this.webpackCache = compilation.getCache(PLUGIN_NAME); } // Initialize the resource loader if not already setup if (!state.resourceLoader) { state.resourceLoader = new WebpackResourceLoader(this.watchMode); } // Setup and read TypeScript and Angular compiler configuration const { compilerOptions, rootNames, errors } = this.loadConfiguration(); // Create diagnostics reporter and report configuration file errors const diagnosticsReporter = createDiagnosticsReporter(compilation, (diagnostic) => this.compilerCli.formatDiagnostics([diagnostic]), ); diagnosticsReporter(errors); // Update TypeScript path mapping plugin with new configuration state.pathsPlugin.update(compilerOptions); // Create a Webpack-based TypeScript compiler host const system = createWebpackSystem( // Webpack lacks an InputFileSytem type definition with sync functions compiler.inputFileSystem as InputFileSystemSync, normalizePath(compiler.context), ); const host = ts.createIncrementalCompilerHost(compilerOptions, system); // Setup source file caching and reuse cache from previous compilation if present let cache = this.sourceFileCache; let changedFiles; if (cache) { changedFiles = new Set<string>(); for (const changedFile of [ ...(compiler.modifiedFiles ?? []), ...(compiler.removedFiles ?? []), ]) { const normalizedChangedFile = normalizePath(changedFile); // Invalidate file dependencies this.fileDependencies.delete(normalizedChangedFile); // Invalidate existing cache cache.invalidate(normalizedChangedFile); changedFiles.add(normalizedChangedFile); } } else { // Initialize a new cache cache = new SourceFileCache(); // Only store cache if in watch mode if (this.watchMode) { this.sourceFileCache = cache; } } augmentHostWithCaching(host, cache); const moduleResolutionCache = ts.createModuleResolutionCache( host.getCurrentDirectory(), host.getCanonicalFileName.bind(host), compilerOptions, ); // Setup source file dependency collection augmentHostWithDependencyCollection(host, this.fileDependencies, moduleResolutionCache); // Setup resource loading state.resourceLoader.update(compilation, changedFiles); augmentHostWithResources(host, state.resourceLoader, { directTemplateLoading: this.pluginOptions.directTemplateLoading, inlineStyleFileExtension: this.pluginOptions.inlineStyleFileExtension, }); // Setup source file adjustment options augmentHostWithReplacements(host, this.pluginOptions.fileReplacements, moduleResolutionCache); augmentHostWithSubstitutions(host, this.pluginOptions.substitutions); // Create the file emitter used by the webpack loader const { fileEmitter, builder, internalFiles } = this.pluginOptions.jitMode ? this.updateJitProgram(compilerOptions, rootNames, host, diagnosticsReporter) : this.updateAotProgram( compilerOptions, rootNames, host, diagnosticsReporter, state.resourceLoader, ); // Set of files used during the unused TypeScript file analysis const currentUnused = new Set<string>(); for (const sourceFile of builder.getSourceFiles()) { if (internalFiles?.has(sourceFile)) { continue; } // Ensure all program files are considered part of the compilation and will be watched. // Webpack does not normalize paths. Therefore, we need to normalize the path with FS seperators. compilation.fileDependencies.add(externalizePath(sourceFile.fileName)); // Add all non-declaration files to the initial set of unused files. The set will be // analyzed and pruned after all Webpack modules are finished building. if (!sourceFile.isDeclarationFile) { currentUnused.add(normalizePath(sourceFile.fileName)); } } compilation.hooks.finishModules.tapPromise(PLUGIN_NAME, async (modules) => { // Rebuild any remaining AOT required modules await this.rebuildRequiredFiles(modules, compilation, fileEmitter); // Clear out the Webpack compilation to avoid an extra retaining reference state.resourceLoader?.clearParentCompilation(); // Analyze program for unused files if (compilation.errors.length > 0) { return; } for (const webpackModule of modules) { const resource = (webpackModule as NormalModule).resource; if (resource) { this.markResourceUsed(normalizePath(resource), currentUnused); } } for (const unused of currentUnused) { if (state.previousUnused?.has(unused)) { continue; } addWarning( compilation, `${unused} is part of the TypeScript compilation but it's unused.\n` + `Add only entry points to the 'files' or 'include' properties in your tsconfig.`, ); } state.previousUnused = currentUnused; }); // Store file emitter for loader usage emitRegistration.update(fileEmitter); }
{ "end_byte": 11741, "start_byte": 2415, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/ivy/plugin.ts" }
angular-cli/packages/ngtools/webpack/src/ivy/plugin.ts_11745_15362
private registerWithCompilation(compilation: Compilation) { let fileEmitters = compilationFileEmitters.get(compilation); if (!fileEmitters) { fileEmitters = new FileEmitterCollection(); compilationFileEmitters.set(compilation, fileEmitters); compilation.compiler.webpack.NormalModule.getCompilationHooks(compilation).loader.tap( PLUGIN_NAME, (context) => { const loaderContext = context as typeof context & { [AngularPluginSymbol]?: FileEmitterCollection; }; loaderContext[AngularPluginSymbol] = fileEmitters; }, ); } const emitRegistration = fileEmitters.register(); return emitRegistration; } private markResourceUsed(normalizedResourcePath: string, currentUnused: Set<string>): void { if (!currentUnused.has(normalizedResourcePath)) { return; } currentUnused.delete(normalizedResourcePath); const dependencies = this.fileDependencies.get(normalizedResourcePath); if (!dependencies) { return; } for (const dependency of dependencies) { this.markResourceUsed(normalizePath(dependency), currentUnused); } } private async rebuildRequiredFiles( modules: Iterable<Module>, compilation: Compilation, fileEmitter: FileEmitter, ): Promise<void> { if (this.requiredFilesToEmit.size === 0) { return; } const filesToRebuild = new Set<string>(); for (const requiredFile of this.requiredFilesToEmit) { const history = await this.getFileEmitHistory(requiredFile); if (history) { const emitResult = await fileEmitter(requiredFile); if ( emitResult?.content === undefined || history.length !== emitResult.content.length || emitResult.hash === undefined || Buffer.compare(history.hash, emitResult.hash) !== 0 ) { // New emit result is different so rebuild using new emit result this.requiredFilesToEmitCache.set(requiredFile, emitResult); filesToRebuild.add(requiredFile); } } else { // No emit history so rebuild filesToRebuild.add(requiredFile); } } if (filesToRebuild.size > 0) { const rebuild = (webpackModule: Module) => new Promise<void>((resolve) => compilation.rebuildModule(webpackModule, () => resolve())); const modulesToRebuild = []; for (const webpackModule of modules) { const resource = (webpackModule as NormalModule).resource; if (resource && filesToRebuild.has(normalizePath(resource))) { modulesToRebuild.push(webpackModule); } } await Promise.all(modulesToRebuild.map((webpackModule) => rebuild(webpackModule))); } this.requiredFilesToEmit.clear(); this.requiredFilesToEmitCache.clear(); } private loadConfiguration() { const { options: compilerOptions, rootNames, errors, } = this.compilerCli.readConfiguration( this.pluginOptions.tsconfig, this.pluginOptions.compilerOptions, ); compilerOptions.noEmitOnError = false; compilerOptions.suppressOutputPathCheck = true; compilerOptions.outDir = undefined; compilerOptions.inlineSources = compilerOptions.sourceMap; compilerOptions.inlineSourceMap = false; compilerOptions.mapRoot = undefined; compilerOptions.sourceRoot = undefined; compilerOptions.allowEmptyCodegenFiles = false; compilerOptions.annotationsAs = 'decorators'; compilerOptions.enableResourceInlining = false; return { compilerOptions, rootNames, errors }; }
{ "end_byte": 15362, "start_byte": 11745, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/ivy/plugin.ts" }
angular-cli/packages/ngtools/webpack/src/ivy/plugin.ts_15366_24190
private updateAotProgram( compilerOptions: CompilerOptions, rootNames: string[], host: CompilerHost, diagnosticsReporter: DiagnosticsReporter, resourceLoader: WebpackResourceLoader, ) { // Create the Angular specific program that contains the Angular compiler const angularProgram = new this.compilerCli.NgtscProgram( rootNames, compilerOptions, host, this.ngtscNextProgram, ); const angularCompiler = angularProgram.compiler; // The `ignoreForEmit` return value can be safely ignored when emitting. Only files // that will be bundled (requested by Webpack) will be emitted. Combined with TypeScript's // eliding of type only imports, this will cause type only files to be automatically ignored. // Internal Angular type check files are also not resolvable by the bundler. Even if they // were somehow errantly imported, the bundler would error before an emit was attempted. // Diagnostics are still collected for all files which requires using `ignoreForDiagnostics`. const { ignoreForDiagnostics, ignoreForEmit } = angularCompiler; // SourceFile versions are required for builder programs. // The wrapped host inside NgtscProgram adds additional files that will not have versions. const typeScriptProgram = angularProgram.getTsProgram(); augmentProgramWithVersioning(typeScriptProgram); let builder: ts.BuilderProgram | ts.EmitAndSemanticDiagnosticsBuilderProgram; if (this.watchMode) { builder = this.builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram( typeScriptProgram, host, this.builder, ); this.ngtscNextProgram = angularProgram; } else { // When not in watch mode, the startup cost of the incremental analysis can be avoided by // using an abstract builder that only wraps a TypeScript program. builder = ts.createAbstractBuilder(typeScriptProgram, host); } // Update semantic diagnostics cache const affectedFiles = new Set<ts.SourceFile>(); // Analyze affected files when in watch mode for incremental type checking if ('getSemanticDiagnosticsOfNextAffectedFile' in builder) { // eslint-disable-next-line no-constant-condition while (true) { const result = builder.getSemanticDiagnosticsOfNextAffectedFile(undefined, (sourceFile) => { // If the affected file is a TTC shim, add the shim's original source file. // This ensures that changes that affect TTC are typechecked even when the changes // are otherwise unrelated from a TS perspective and do not result in Ivy codegen changes. // For example, changing @Input property types of a directive used in another component's // template. if ( ignoreForDiagnostics.has(sourceFile) && sourceFile.fileName.endsWith('.ngtypecheck.ts') ) { // This file name conversion relies on internal compiler logic and should be converted // to an official method when available. 15 is length of `.ngtypecheck.ts` const originalFilename = sourceFile.fileName.slice(0, -15) + '.ts'; const originalSourceFile = builder.getSourceFile(originalFilename); if (originalSourceFile) { affectedFiles.add(originalSourceFile); } return true; } return false; }); if (!result) { break; } affectedFiles.add(result.affected as ts.SourceFile); } } // Collect program level diagnostics const diagnostics = [ ...angularCompiler.getOptionDiagnostics(), ...builder.getOptionsDiagnostics(), ...builder.getGlobalDiagnostics(), ]; diagnosticsReporter(diagnostics); // Collect source file specific diagnostics for (const sourceFile of builder.getSourceFiles()) { if (!ignoreForDiagnostics.has(sourceFile)) { diagnosticsReporter(builder.getSyntacticDiagnostics(sourceFile)); diagnosticsReporter(builder.getSemanticDiagnostics(sourceFile)); } } const transformers = createAotTransformers(builder, this.pluginOptions, imageDomains); const getDependencies = (sourceFile: ts.SourceFile) => { const dependencies = []; for (const resourcePath of angularCompiler.getResourceDependencies(sourceFile)) { dependencies.push( resourcePath, // Retrieve all dependencies of the resource (stylesheet imports, etc.) ...resourceLoader.getResourceDependencies(resourcePath), ); } return dependencies; }; // Required to support asynchronous resource loading // Must be done before creating transformers or getting template diagnostics const pendingAnalysis = angularCompiler .analyzeAsync() .then(() => { this.requiredFilesToEmit.clear(); for (const sourceFile of builder.getSourceFiles()) { if (sourceFile.isDeclarationFile) { continue; } // Collect sources that are required to be emitted if ( !ignoreForEmit.has(sourceFile) && !angularCompiler.incrementalCompilation.safeToSkipEmit(sourceFile) ) { this.requiredFilesToEmit.add(normalizePath(sourceFile.fileName)); // If required to emit, diagnostics may have also changed if (!ignoreForDiagnostics.has(sourceFile)) { affectedFiles.add(sourceFile); } } else if ( this.sourceFileCache && !affectedFiles.has(sourceFile) && !ignoreForDiagnostics.has(sourceFile) ) { // Use cached Angular diagnostics for unchanged and unaffected files const angularDiagnostics = this.sourceFileCache.getAngularDiagnostics(sourceFile); if (angularDiagnostics) { diagnosticsReporter(angularDiagnostics); } } } // Collect new Angular diagnostics for files affected by changes const OptimizeFor = this.compilerCli.OptimizeFor; const optimizeDiagnosticsFor = affectedFiles.size <= DIAGNOSTICS_AFFECTED_THRESHOLD ? OptimizeFor.SingleFile : OptimizeFor.WholeProgram; for (const affectedFile of affectedFiles) { const angularDiagnostics = angularCompiler.getDiagnosticsForFile( affectedFile, optimizeDiagnosticsFor, ); diagnosticsReporter(angularDiagnostics); this.sourceFileCache?.updateAngularDiagnostics(affectedFile, angularDiagnostics); } return { emitter: this.createFileEmitter( builder, mergeTransformers(angularCompiler.prepareEmit().transformers, transformers), getDependencies, (sourceFile) => { this.requiredFilesToEmit.delete(normalizePath(sourceFile.fileName)); angularCompiler.incrementalCompilation.recordSuccessfulEmit(sourceFile); }, ), }; }) .catch((err) => ({ errorMessage: err instanceof Error ? err.message : `${err}` })); const analyzingFileEmitter: FileEmitter = async (file) => { const analysis = await pendingAnalysis; if ('errorMessage' in analysis) { throw new Error(analysis.errorMessage); } return analysis.emitter(file); }; return { fileEmitter: analyzingFileEmitter, builder, internalFiles: ignoreForEmit, }; } private updateJitProgram( compilerOptions: CompilerOptions, rootNames: readonly string[], host: CompilerHost, diagnosticsReporter: DiagnosticsReporter, ) { let builder; if (this.watchMode) { builder = this.builder = ts.createEmitAndSemanticDiagnosticsBuilderProgram( rootNames, compilerOptions, host, this.builder, ); } else { // When not in watch mode, the startup cost of the incremental analysis can be avoided by // using an abstract builder that only wraps a TypeScript program. builder = ts.createAbstractBuilder(rootNames, compilerOptions, host); } const diagnostics = [ ...builder.getOptionsDiagnostics(), ...builder.getGlobalDiagnostics(), ...builder.getSyntacticDiagnostics(), // Gather incremental semantic diagnostics ...builder.getSemanticDiagnostics(), ]; diagnosticsReporter(diagnostics); const transformers = createJitTransformers( builder, this.compilerCliTooling, this.pluginOptions, ); return { fileEmitter: this.createFileEmitter(builder, transformers, () => []), builder, internalFiles: undefined, }; }
{ "end_byte": 24190, "start_byte": 15366, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/ivy/plugin.ts" }
angular-cli/packages/ngtools/webpack/src/ivy/plugin.ts_24194_27571
private createFileEmitter( program: ts.BuilderProgram, transformers: ts.CustomTransformers = {}, getExtraDependencies: (sourceFile: ts.SourceFile) => Iterable<string>, onAfterEmit?: (sourceFile: ts.SourceFile) => void, ): FileEmitter { return async (file: string) => { const filePath = normalizePath(file); if (this.requiredFilesToEmitCache.has(filePath)) { return this.requiredFilesToEmitCache.get(filePath); } const sourceFile = program.getSourceFile(filePath); if (!sourceFile) { return undefined; } let content: string | undefined; let map: string | undefined; program.emit( sourceFile, (filename, data) => { if (filename.endsWith('.map')) { map = data; } else if (filename.endsWith('.js')) { content = data; } }, undefined, undefined, transformers, ); onAfterEmit?.(sourceFile); // Capture emit history info for Angular rebuild analysis const hash = content ? (await this.addFileEmitHistory(filePath, content)).hash : undefined; const dependencies = [ ...(this.fileDependencies.get(filePath) || []), ...getExtraDependencies(sourceFile), ].map(externalizePath); return { content, map, dependencies, hash }; }; } private async initializeCompilerCli(): Promise<void> { // This uses a dynamic import to load `@angular/compiler-cli` which may be ESM. // CommonJS code can load ESM code via a dynamic import. Unfortunately, TypeScript // will currently, unconditionally downlevel dynamic import into a require call. // require calls cannot load ESM code and will result in a runtime error. To workaround // this, a Function constructor is used to prevent TypeScript from changing the dynamic import. // Once TypeScript provides support for keeping the dynamic import this workaround can // be dropped. this.compilerCliModule ??= await new Function(`return import('@angular/compiler-cli');`)(); this.compilerCliToolingModule ??= await new Function( `return import('@angular/compiler-cli/private/tooling');`, )(); } private async addFileEmitHistory( filePath: string, content: string, ): Promise<FileEmitHistoryItem> { assert.ok(this.webpackCreateHash, 'File emitter is used prior to Webpack compilation'); const historyData: FileEmitHistoryItem = { length: content.length, hash: this.webpackCreateHash('xxhash64').update(content).digest() as Uint8Array, }; if (this.webpackCache) { const history = await this.getFileEmitHistory(filePath); if (!history || Buffer.compare(history.hash, historyData.hash) !== 0) { // Hash doesn't match or item doesn't exist. await this.webpackCache.storePromise(filePath, null, historyData); } } else if (this.watchMode) { // The in memory file emit history is only required during watch mode. this.fileEmitHistory.set(filePath, historyData); } return historyData; } private async getFileEmitHistory(filePath: string): Promise<FileEmitHistoryItem | undefined> { return this.webpackCache ? this.webpackCache.getPromise<FileEmitHistoryItem | undefined>(filePath, null) : this.fileEmitHistory.get(filePath); } }
{ "end_byte": 27571, "start_byte": 24194, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/ivy/plugin.ts" }
angular-cli/packages/ngtools/webpack/src/ivy/loader.ts_0_2552
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as path from 'path'; import type { LoaderContext } from 'webpack'; import { AngularPluginSymbol, FileEmitterCollection } from './symbol'; const JS_FILE_REGEXP = /\.[cm]?js$/; export function angularWebpackLoader(this: LoaderContext<unknown>, content: string, map: string) { const callback = this.async(); if (!callback) { throw new Error('Invalid webpack version'); } const fileEmitter = ( this as LoaderContext<unknown> & { [AngularPluginSymbol]?: FileEmitterCollection } )[AngularPluginSymbol]; if (!fileEmitter || typeof fileEmitter !== 'object') { if (JS_FILE_REGEXP.test(this.resourcePath)) { // Passthrough for JS files when no plugin is used this.callback(undefined, content, map); return; } callback(new Error('The Angular Webpack loader requires the AngularWebpackPlugin.')); return; } fileEmitter .emit(this.resourcePath) .then((result) => { if (!result) { if (JS_FILE_REGEXP.test(this.resourcePath)) { // Return original content for JS files if not compiled by TypeScript ("allowJs") this.callback(undefined, content, map); } else { // File is not part of the compilation const message = `${this.resourcePath} is missing from the TypeScript compilation. ` + `Please make sure it is in your tsconfig via the 'files' or 'include' property.`; callback(new Error(message)); } return; } result.dependencies.forEach((dependency) => this.addDependency(dependency)); let resultContent = result.content || ''; let resultMap; if (result.map) { resultContent = resultContent.replace(/^\/\/# sourceMappingURL=[^\r\n]*/gm, ''); resultMap = JSON.parse(result.map) as Exclude< Parameters<typeof callback>[2], string | undefined >; resultMap.sources = resultMap.sources.map((source: string) => path.join(path.dirname(this.resourcePath), source), ); } callback(undefined, resultContent, resultMap); }) .catch((err) => { // The below is needed to hide stacktraces from users. const message = err instanceof Error ? err.message : err; callback(new Error(message)); }); } export { angularWebpackLoader as default };
{ "end_byte": 2552, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/ivy/loader.ts" }
angular-cli/packages/ngtools/webpack/src/ivy/symbol.ts_0_1468
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ export const AngularPluginSymbol = Symbol.for('@ngtools/webpack[angular-compiler]'); export interface EmitFileResult { content?: string; map?: string; dependencies: readonly string[]; hash?: Uint8Array; } export type FileEmitter = (file: string) => Promise<EmitFileResult | undefined>; export class FileEmitterRegistration { #fileEmitter?: FileEmitter; update(emitter: FileEmitter): void { this.#fileEmitter = emitter; } emit(file: string): Promise<EmitFileResult | undefined> { if (!this.#fileEmitter) { throw new Error('Emit attempted before Angular Webpack plugin initialization.'); } return this.#fileEmitter(file); } } export class FileEmitterCollection { #registrations: FileEmitterRegistration[] = []; register(): FileEmitterRegistration { const registration = new FileEmitterRegistration(); this.#registrations.push(registration); return registration; } async emit(file: string): Promise<EmitFileResult | undefined> { if (this.#registrations.length === 1) { return this.#registrations[0].emit(file); } for (const registration of this.#registrations) { const result = await registration.emit(file); if (result) { return result; } } } }
{ "end_byte": 1468, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/ivy/symbol.ts" }
angular-cli/packages/ngtools/webpack/src/ivy/cache.ts_0_971
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import * as ts from 'typescript'; export class SourceFileCache extends Map<string, ts.SourceFile> { private readonly angularDiagnostics = new Map<ts.SourceFile, ts.Diagnostic[]>(); invalidate(file: string): void { const sourceFile = this.get(file); if (sourceFile) { this.delete(file); this.angularDiagnostics.delete(sourceFile); } } updateAngularDiagnostics(sourceFile: ts.SourceFile, diagnostics: ts.Diagnostic[]): void { if (diagnostics.length > 0) { this.angularDiagnostics.set(sourceFile, diagnostics); } else { this.angularDiagnostics.delete(sourceFile); } } getAngularDiagnostics(sourceFile: ts.SourceFile): ts.Diagnostic[] | undefined { return this.angularDiagnostics.get(sourceFile); } }
{ "end_byte": 971, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/ivy/cache.ts" }
angular-cli/packages/ngtools/webpack/src/ivy/diagnostics.ts_0_1152
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.dev/license */ import { Diagnostic, DiagnosticCategory } from 'typescript'; import type { Compilation } from 'webpack'; export type DiagnosticsReporter = (diagnostics: readonly Diagnostic[]) => void; export function createDiagnosticsReporter( compilation: Compilation, formatter: (diagnostic: Diagnostic) => string, ): DiagnosticsReporter { return (diagnostics) => { for (const diagnostic of diagnostics) { const text = formatter(diagnostic); if (diagnostic.category === DiagnosticCategory.Error) { addError(compilation, text); } else { addWarning(compilation, text); } } }; } export function addWarning(compilation: Compilation, message: string): void { compilation.warnings.push(new compilation.compiler.webpack.WebpackError(message)); } export function addError(compilation: Compilation, message: string): void { compilation.errors.push(new compilation.compiler.webpack.WebpackError(message)); }
{ "end_byte": 1152, "start_byte": 0, "url": "https://github.com/angular/angular-cli/blob/main/packages/ngtools/webpack/src/ivy/diagnostics.ts" }