_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/bazel/test/ng_package/example-with-ts-library/utils/index.ts_0_231 | /**
* @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 './testing';
| {
"end_byte": 231,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/ng_package/example-with-ts-library/utils/index.ts"
} |
angular/packages/bazel/test/types_bundle/bundle_entry.ts_0_284 | /**
* @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 {transitiveExport} from './transitive_fixture';
export const hello = 1;
| {
"end_byte": 284,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/types_bundle/bundle_entry.ts"
} |
angular/packages/bazel/test/types_bundle/expected_types_bundle.d.ts_0_100 | export declare const hello = 1;
export declare const transitiveExport = "transitive";
export { }
| {
"end_byte": 100,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/types_bundle/expected_types_bundle.d.ts"
} |
angular/packages/bazel/test/types_bundle/BUILD.bazel_0_674 | load("@build_bazel_rules_nodejs//:index.bzl", "generated_file_test")
load("//packages/bazel/src/types_bundle:index.bzl", "types_bundle")
load("//tools:defaults.bzl", "ts_library")
package(default_testonly = True)
ts_library(
name = "test_transitive_lib",
srcs = ["transitive_fixture.ts"],
)
ts_library(
name = "test_lib",
srcs = ["bundle_entry.ts"],
deps = [":test_transitive_lib"],
)
types_bundle(
name = "bundled_types",
entry_point = "bundle_entry.d.ts",
output_name = "output_index.d.ts",
deps = [":test_lib"],
)
generated_file_test(
name = "test",
src = "expected_types_bundle.d.ts",
generated = ":bundled_types",
)
| {
"end_byte": 674,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/types_bundle/BUILD.bazel"
} |
angular/packages/bazel/test/types_bundle/transitive_fixture.ts_0_250 | /**
* @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 transitiveExport = 'transitive';
| {
"end_byte": 250,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/types_bundle/transitive_fixture.ts"
} |
angular/packages/bazel/test/ngc-wrapped/flat_module_test.ts_0_1098 | /**
* @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 {runfiles} from '@bazel/runfiles';
import {existsSync, readFileSync} from 'fs';
import {dirname, join} from 'path';
describe('flat_module ng_module', () => {
let packageOutput: string;
let flatModuleOutFile: string;
beforeAll(() => {
packageOutput = dirname(
runfiles.resolve('angular/packages/bazel/test/ngc-wrapped/flat_module/index.mjs'),
);
flatModuleOutFile = join(packageOutput, 'flat_module.mjs');
});
it('should have a flat module out file', () => {
expect(existsSync(flatModuleOutFile)).toBe(true);
});
describe('flat module out file', () => {
it('should have a proper flat module re-export', () => {
expect(readFileSync(flatModuleOutFile, 'utf8')).toContain(`export * from './index';`);
expect(readFileSync(flatModuleOutFile, 'utf8')).toContain(
`Generated bundle index. Do not edit.`,
);
});
});
});
| {
"end_byte": 1098,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/ngc-wrapped/flat_module_test.ts"
} |
angular/packages/bazel/test/ngc-wrapped/BUILD.bazel_0_1430 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
ts_library(
name = "ngc_test_lib",
testonly = True,
srcs = [
"index_test.ts",
"test_support.ts",
"tsconfig_template.ts",
],
tsconfig = ":tsconfig.json",
deps = [
"//packages/bazel/src/ngc-wrapped:ngc_lib",
"//packages/compiler-cli",
"@npm//@bazel/runfiles",
"@npm//typescript",
],
)
# We need a filegroup so that we can refer
# .d.ts files (by default, jasmine_node_test would get the .js files).
filegroup(
name = "angular_core",
srcs = ["//packages/core"],
)
jasmine_node_test(
name = "ngc_test",
size = "small",
srcs = [":ngc_test_lib"],
data = [
":angular_core",
"//packages/bazel/test/ngc-wrapped/empty:empty_tsconfig.json",
"//packages/bazel/test/ngc-wrapped/empty:tsconfig.json",
"//packages/private/testing",
"@npm//@bazel/concatjs/third_party/github.com/bazelbuild/bazel/src/main/protobuf:worker_protocol.proto",
],
)
ts_library(
name = "flat_module_test_lib",
testonly = True,
srcs = ["flat_module_test.ts"],
tsconfig = ":tsconfig.json",
deps = [
"//packages/private/testing",
"@npm//@bazel/runfiles",
],
)
jasmine_node_test(
name = "flat_module_test",
srcs = [":flat_module_test_lib"],
data = ["//packages/bazel/test/ngc-wrapped/flat_module"],
)
| {
"end_byte": 1430,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/ngc-wrapped/BUILD.bazel"
} |
angular/packages/bazel/test/ngc-wrapped/tsconfig_template.ts_0_3237 | /**
* @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 {runfiles} from '@bazel/runfiles';
import * as path from 'path';
const EXT = /(\.ts|\.d\.ts|\.js|\.jsx|\.tsx)$/;
export interface TsConfigOptions {
defaultTsConfig: any;
outDir: string;
rootDir: string;
pathMapping: {[pattern: string]: string[]};
// e.g. //packages/core:core
target: string;
compilationTargetSrc: string[];
files: string[];
}
/**
* Creates a tsconfig based on the default tsconfig
* to adjust paths, ...
*
* @param options
*/
export function createTsConfig(options: TsConfigOptions) {
const result = options.defaultTsConfig;
return {
'compilerOptions': {
...result.compilerOptions,
'outDir': options.outDir,
'rootDir': options.rootDir,
'rootDirs': [options.rootDir],
'baseUrl': options.rootDir,
'paths': {
'*': ['./*'],
...options.pathMapping,
},
// we have to set this as the default tsconfig is made of es6 mode
'target': 'es5',
// we have to set this as the default tsconfig is made of es6 mode
'module': 'commonjs',
// if we specify declarationDir, we also have to specify
// declaration in the same tsconfig.json, otherwise ts will error.
'declaration': true,
'declarationDir': options.outDir,
'skipLibCheck': true,
},
'bazelOptions': {
...result.bazelOptions,
'workspaceName': 'angular',
'target': options.target,
// we have to set this as the default tsconfig is made of es6 mode
'es5Mode': true,
'devmode': true,
'manifest': createManifestPath(options),
'compilationTargetSrc': options.compilationTargetSrc,
// Override this property from the real tsconfig we read
// Because we ask for :empty_tsconfig.json, we get the ES6 version which
// expects to write externs, yet that doesn't work under this fixture.
'tsickleExternsPath': '',
// we don't copy the node_modules into our tmp dir, so we should look in
// the original workspace directory for it
'nodeModulesPrefix': path.join(
runfiles.resolve('npm/node_modules/typescript/package.json'),
'../../',
),
},
'files': options.files,
'angularCompilerOptions': {
...result.angularCompilerOptions,
'expectedOut': [
...options.compilationTargetSrc.map((src) => srcToExpectedOut(src, 'js', options)),
...options.compilationTargetSrc.map((src) => srcToExpectedOut(src, 'd.ts', options)),
],
},
};
}
function srcToExpectedOut(srcFile: string, suffix: string, options: TsConfigOptions): string {
const baseName = path.basename(srcFile).replace(EXT, '');
return (
path.join(
path.relative(options.rootDir, options.outDir),
path.relative(options.rootDir, path.dirname(srcFile)),
baseName,
) +
'.' +
suffix
);
}
function createManifestPath(options: TsConfigOptions): string {
return (
path.resolve(options.outDir, options.target.replace(/\/\/|@/g, '').replace(/:/g, '/')) +
'.es5.MF'
);
}
| {
"end_byte": 3237,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/ngc-wrapped/tsconfig_template.ts"
} |
angular/packages/bazel/test/ngc-wrapped/index_test.ts_0_1199 | /**
* @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 {setup} from './test_support';
describe('ngc_wrapped', () => {
it('should work', async () => {
const {read, write, runOneBuild, writeConfig, shouldExist, basePath, typesRoots} = setup();
write(
'some_project/index.ts',
`
import {Component} from '@angular/core';
import {a} from 'ambient_module';
console.log('works: ', Component);
`,
);
const typesFile = path.resolve(basePath, typesRoots, 'thing', 'index.d.ts');
write(
typesFile,
`
declare module "ambient_module" {
declare const a = 1;
}
`,
);
writeConfig({
srcTargetPath: 'some_project',
depPaths: [path.dirname(typesFile)],
});
// expect no error
expect(await runOneBuild()).toBe(true);
shouldExist('bazel-bin/some_project/index.js');
expect(read('bazel-bin/some_project/index.js')).toContain(
`console.log('works: ', core_1.Component);`,
);
});
});
| {
"end_byte": 1199,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/ngc-wrapped/index_test.ts"
} |
angular/packages/bazel/test/ngc-wrapped/test_support.ts_0_5460 | /**
* @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 {runOneBuild} from '@angular/bazel';
import {runfiles} from '@bazel/runfiles';
import * as fs from 'fs';
import * as path from 'path';
import ts from 'typescript';
import {createTsConfig} from './tsconfig_template';
export interface TestSupport {
basePath: string;
runfilesPath: string;
angularCorePath: string;
typesRoots: string;
writeConfig({
srcTargetPath,
depPaths,
pathMapping,
}: {
srcTargetPath: string;
depPaths?: string[];
pathMapping?: Array<{moduleName: string; path: string}>;
}): {compilerOptions: ts.CompilerOptions};
read(fileName: string): string;
write(fileName: string, content: string): void;
writeFiles(...mockDirs: {[fileName: string]: string}[]): void;
shouldExist(fileName: string): void;
shouldNotExist(fileName: string): void;
runOneBuild(): Promise<boolean>;
}
export function setup({
bazelBin = 'bazel-bin',
tsconfig = 'tsconfig.json',
}: {
bazelBin?: string;
tsconfig?: string;
} = {}): TestSupport {
const runfilesPath = process.env['TEST_SRCDIR'];
const basePath = makeTempDir(runfilesPath);
console.error(basePath);
const bazelBinPath = path.resolve(basePath, bazelBin);
fs.mkdirSync(bazelBinPath);
const angularCorePath = runfiles.resolve('angular/packages/core');
const tsConfigJsonPath = path.resolve(basePath, tsconfig);
const emptyTsConfig = ts.readConfigFile(
runfiles.resolve('angular/packages/bazel/test/ngc-wrapped/empty/empty_tsconfig.json'),
read,
);
const typesRoots = (emptyTsConfig as any).config.compilerOptions.typeRoots[0];
return {
basePath,
runfilesPath,
angularCorePath,
typesRoots,
write,
read,
writeFiles,
writeConfig,
shouldExist,
shouldNotExist,
runOneBuild: runOneBuildImpl,
};
// -----------------
// helpers
function mkdirp(dirname: string) {
const parent = path.dirname(dirname);
if (!fs.existsSync(parent)) {
mkdirp(parent);
}
fs.mkdirSync(dirname);
}
function write(fileName: string, content: string) {
const dir = path.dirname(fileName);
if (dir != '.') {
const newDir = path.resolve(basePath, dir);
if (!fs.existsSync(newDir)) mkdirp(newDir);
}
fs.writeFileSync(path.resolve(basePath, fileName), content, {encoding: 'utf-8'});
}
function read(fileName: string) {
return fs.readFileSync(path.resolve(basePath, fileName), {encoding: 'utf-8'});
}
function writeFiles(...mockDirs: {[fileName: string]: string}[]) {
mockDirs.forEach((dir) => {
Object.keys(dir).forEach((fileName) => {
write(fileName, dir[fileName]);
});
});
}
function writeConfig({
srcTargetPath,
depPaths = [],
pathMapping = [],
}: {
srcTargetPath: string;
depPaths?: string[];
pathMapping?: Array<{moduleName: string; path: string}>;
}) {
srcTargetPath = path.resolve(basePath, srcTargetPath);
const compilationTargetSrc = listFilesRecursive(srcTargetPath);
const target = '//' + path.relative(basePath, srcTargetPath);
const files = [...compilationTargetSrc];
depPaths = depPaths.concat([angularCorePath]);
pathMapping = pathMapping.concat([
{moduleName: '@angular/core', path: angularCorePath},
{moduleName: 'angular/packages/core', path: angularCorePath},
]);
for (const depPath of depPaths) {
files.push(...listFilesRecursive(depPath).filter((f) => f.endsWith('.d.ts')));
}
const pathMappingObj = {};
for (const mapping of pathMapping) {
pathMappingObj[mapping.moduleName] = [mapping.path];
pathMappingObj[path.posix.join(mapping.moduleName, '*')] = [
path.posix.join(mapping.path, '*'),
];
}
const emptyTsConfig = ts.readConfigFile(
runfiles.resolve('angular/packages/bazel/test/ngc-wrapped/empty/empty_tsconfig.json'),
read,
);
const tsconfig = createTsConfig({
defaultTsConfig: emptyTsConfig.config,
rootDir: basePath,
target: target,
outDir: bazelBinPath,
compilationTargetSrc,
files: files,
pathMapping: pathMappingObj,
});
write(path.resolve(basePath, tsConfigJsonPath), JSON.stringify(tsconfig, null, 2));
return tsconfig;
}
function shouldExist(fileName: string) {
if (!fs.existsSync(path.resolve(basePath, fileName))) {
throw new Error(`Expected ${fileName} to be emitted (basePath: ${basePath})`);
}
}
function shouldNotExist(fileName: string) {
if (fs.existsSync(path.resolve(basePath, fileName))) {
throw new Error(`Did not expect ${fileName} to be emitted (basePath: ${basePath})`);
}
}
async function runOneBuildImpl(): Promise<boolean> {
return runOneBuild(['@' + tsConfigJsonPath]);
}
}
function makeTempDir(baseDir: string): string {
const id = (Math.random() * 1000000).toFixed(0);
const dir = path.join(baseDir, `tmp.${id}`);
fs.mkdirSync(dir);
return dir;
}
export function listFilesRecursive(dir: string, fileList: string[] = []) {
fs.readdirSync(dir).forEach((file) => {
if (fs.statSync(path.join(dir, file)).isDirectory()) {
listFilesRecursive(path.join(dir, file), fileList);
} else {
fileList.push(path.join(dir, file));
}
});
return fileList;
}
| {
"end_byte": 5460,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/ngc-wrapped/test_support.ts"
} |
angular/packages/bazel/test/ngc-wrapped/ivy_enabled/ng_module_ivy_test.ts_0_713 | /**
* @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 {runfiles} from '@bazel/runfiles';
import {readFileSync} from 'fs';
describe('ng_module with ivy enabled', () => {
it('should generate definitions as with full compilation mode', () => {
const outputFile = runfiles.resolveWorkspaceRelative(
'packages/bazel/test/ngc-wrapped/ivy_enabled/test_module_default_compilation.mjs',
);
const fileContent = readFileSync(outputFile, 'utf8');
expect(fileContent).toContain(`static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent`);
});
});
| {
"end_byte": 713,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/ngc-wrapped/ivy_enabled/ng_module_ivy_test.ts"
} |
angular/packages/bazel/test/ngc-wrapped/ivy_enabled/test_module_default_compilation.ts_0_334 | /**
* @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 {Component} from '@angular/core';
@Component({
template: 'Hello',
standalone: false,
})
export class TestComponent {}
| {
"end_byte": 334,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/ngc-wrapped/ivy_enabled/test_module_default_compilation.ts"
} |
angular/packages/bazel/test/ngc-wrapped/ivy_enabled/BUILD.bazel_0_910 | load("@bazel_skylib//rules:build_test.bzl", "build_test")
load("//tools:defaults.bzl", "jasmine_node_test", "ng_module", "ts_library")
ts_library(
name = "ng_module_ivy_test_lib",
testonly = True,
srcs = ["ng_module_ivy_test.ts"],
tags = [],
deps = ["@npm//@bazel/runfiles"],
)
ng_module(
name = "test_module_default_compilation",
srcs = ["test_module_default_compilation.ts"],
tags = [],
deps = ["//packages/core"],
)
jasmine_node_test(
name = "ng_module_ivy_test",
srcs = [":ng_module_ivy_test_lib"],
data = [
":test_module_default_compilation",
],
tags = [],
)
ng_module(
name = "test_module_warnings_lib",
srcs = ["test_module_warnings.ts"],
strict_templates = True,
tags = [],
deps = ["//packages/core"],
)
build_test(
name = "test_module_warnings",
tags = [],
targets = [":test_module_warnings_lib"],
)
| {
"end_byte": 910,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/ngc-wrapped/ivy_enabled/BUILD.bazel"
} |
angular/packages/bazel/test/ngc-wrapped/ivy_enabled/test_module_warnings.ts_0_475 | /**
* @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 {Component} from '@angular/core';
/** Test component which contains an invalid banana in box warning. Should build successfully. */
@Component({
template: ` <div ([foo])="(bar)"></div> `,
standalone: false,
})
export class TestCmp {
bar: string = 'test';
}
| {
"end_byte": 475,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/ngc-wrapped/ivy_enabled/test_module_warnings.ts"
} |
angular/packages/bazel/test/ngc-wrapped/empty/README.md_0_55 | # Empty ng_module to capture the default tsconfig.json
| {
"end_byte": 55,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/ngc-wrapped/empty/README.md"
} |
angular/packages/bazel/test/ngc-wrapped/empty/empty.ts_0_287 | /**
* @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
*/
// Empty file for an empty ng_module
// to capture the tsconfig used by ng_module.
| {
"end_byte": 287,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/ngc-wrapped/empty/empty.ts"
} |
angular/packages/bazel/test/ngc-wrapped/empty/BUILD.bazel_0_278 | load("//tools:defaults.bzl", "ng_module")
package(default_visibility = ["//packages/bazel/test:__subpackages__"])
ng_module(
name = "empty",
srcs = ["empty.ts"],
tsconfig = ":tsconfig.json",
deps = [
"//packages/core",
"@npm//@types",
],
)
| {
"end_byte": 278,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/ngc-wrapped/empty/BUILD.bazel"
} |
angular/packages/bazel/test/ngc-wrapped/flat_module/export.ts_0_249 | /**
* @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 Test = 'This is a test export';
| {
"end_byte": 249,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/ngc-wrapped/flat_module/export.ts"
} |
angular/packages/bazel/test/ngc-wrapped/flat_module/BUILD.bazel_0_329 | load("//tools:defaults.bzl", "ng_module")
package(default_visibility = ["//packages/bazel/test:__subpackages__"])
ng_module(
name = "flat_module",
srcs = [
"export.ts",
"index.ts",
],
module_name = "flat_module",
tsconfig = ":tsconfig.json",
deps = [
"//packages/core",
],
)
| {
"end_byte": 329,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/ngc-wrapped/flat_module/BUILD.bazel"
} |
angular/packages/bazel/test/ngc-wrapped/flat_module/index.ts_0_230 | /**
* @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 './export';
| {
"end_byte": 230,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/test/ngc-wrapped/flat_module/index.ts"
} |
angular/packages/bazel/third_party/github.com/bazelbuild/bazel/src/main/protobuf/LICENSE_0_10173 |
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS | {
"end_byte": 10173,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/third_party/github.com/bazelbuild/bazel/src/main/protobuf/LICENSE"
} |
angular/packages/bazel/third_party/github.com/bazelbuild/bazel/src/main/protobuf/LICENSE_10175_11358 | APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
| {
"end_byte": 11358,
"start_byte": 10175,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/third_party/github.com/bazelbuild/bazel/src/main/protobuf/LICENSE"
} |
angular/packages/bazel/third_party/github.com/bazelbuild/bazel/src/main/protobuf/BUILD.bazel_0_320 | # Fetched from https://github.com/bazelbuild/bazel/blob/master/src/main/protobuf/worker_protocol.proto
licenses(["notice"])
package(default_visibility = ["//visibility:public"])
# BEGIN-DEV-ONLY
filegroup(
name = "package_assets",
srcs = glob(["*"]),
)
# END-DEV-ONLY
exports_files(["worker_protocol.proto"])
| {
"end_byte": 320,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/third_party/github.com/bazelbuild/bazel/src/main/protobuf/BUILD.bazel"
} |
angular/packages/bazel/src/external.bzl_0_2372 | """Allows different paths for these imports in google3.
"""
load(
# Replaced with "//@bazel/concatjs/internal:..." in published package
"@npm//@bazel/concatjs/internal:build_defs.bzl",
_tsc_wrapped_tsconfig = "tsc_wrapped_tsconfig",
)
load(
# Replaced with "//@bazel/concatjs/internal:..." in published package
"@npm//@bazel/concatjs/internal:common/compilation.bzl",
_COMMON_ATTRIBUTES = "COMMON_ATTRIBUTES",
_COMMON_OUTPUTS = "COMMON_OUTPUTS",
_DEPS_ASPECTS = "DEPS_ASPECTS",
_compile_ts = "compile_ts",
_ts_providers_dict_to_struct = "ts_providers_dict_to_struct",
)
load(
# Replaced with "//@bazel/concatjs/internal:..." in published package
"@npm//@bazel/concatjs/internal:ts_config.bzl",
_TsConfigInfo = "TsConfigInfo",
)
load(
"@build_bazel_rules_nodejs//:providers.bzl",
_LinkablePackageInfo = "LinkablePackageInfo",
_NpmPackageInfo = "NpmPackageInfo",
_js_ecma_script_module_info = "js_ecma_script_module_info",
_js_named_module_info = "js_named_module_info",
_node_modules_aspect = "node_modules_aspect",
)
load(
"@rules_nodejs//nodejs:providers.bzl",
_js_module_info = "js_module_info",
)
LinkablePackageInfo = _LinkablePackageInfo
NpmPackageInfo = _NpmPackageInfo
node_modules_aspect = _node_modules_aspect
tsc_wrapped_tsconfig = _tsc_wrapped_tsconfig
COMMON_ATTRIBUTES = _COMMON_ATTRIBUTES
COMMON_OUTPUTS = _COMMON_OUTPUTS
compile_ts = _compile_ts
DEPS_ASPECTS = _DEPS_ASPECTS
ts_providers_dict_to_struct = _ts_providers_dict_to_struct
# Should be defined as `BuildSettingInfo` from Skylib, but a dependency on
# Skylib is not necessary here because this is only used in google3 where Skylib
# is loaded differently anyways where this file is overridden.
BuildSettingInfo = provider(doc = "Not used outside google3.")
DEFAULT_API_EXTRACTOR = (
# BEGIN-DEV-ONLY
"@npm" +
# END-DEV-ONLY
"//@angular/bazel/bin:api-extractor"
)
DEFAULT_NG_COMPILER = (
# BEGIN-DEV-ONLY
"@npm" +
# END-DEV-ONLY
"//@angular/bazel/bin:ngc-wrapped"
)
DEFAULT_NG_XI18N = (
# BEGIN-DEV-ONLY
"@npm" +
# END-DEV-ONLY
"//@angular/bazel/bin:xi18n"
)
FLAT_DTS_FILE_SUFFIX = ".bundle.d.ts"
TsConfigInfo = _TsConfigInfo
js_ecma_script_module_info = _js_ecma_script_module_info
js_module_info = _js_module_info
js_named_module_info = _js_named_module_info
| {
"end_byte": 2372,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/external.bzl"
} |
angular/packages/bazel/src/ng_perf.bzl_0_860 | # 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
load("//packages/bazel/src/ng_module:ng_module.bzl", "NgPerfInfo")
def _ng_perf_flag_impl(ctx):
return NgPerfInfo(enable_perf_logging = ctx.build_setting_value)
# `ng_perf_flag` is a special `build_setting` rule which ultimately enables a command-line boolean
# flag to control whether the `ng_module` rule produces performance tracing JSON files (in Ivy mode)
# as declared outputs.
#
# It does this via the `NgPerfInfo` provider and the `perf_flag` attriubute on `ng_module`. For more
# details, see: https://docs.bazel.build/versions/master/skylark/config.html
ng_perf_flag = rule(
implementation = _ng_perf_flag_impl,
build_setting = config.bool(flag = True),
)
| {
"end_byte": 860,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_perf.bzl"
} |
angular/packages/bazel/src/BUILD.bazel_0_404 | load("//packages/bazel/src/ng_module:partial_compilation.bzl", "ng_partial_compilation_flag")
# BEGIN-DEV-ONLY
package(default_visibility = ["//packages/bazel:__subpackages__"])
filegroup(
name = "package_assets",
srcs = glob(["*"]),
)
# END-DEV-ONLY
ng_partial_compilation_flag(
name = "partial_compilation",
build_setting_default = False,
visibility = ["//visibility:public"],
)
| {
"end_byte": 404,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/BUILD.bazel"
} |
angular/packages/bazel/src/ng_package/api.ts_0_1401 | /**
* @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
*/
/**
* Interface describing a file captured in the Bazel action.
* https://docs.bazel.build/versions/main/skylark/lib/File.html.
*/
export interface BazelFileInfo {
/** Execroot-relative path pointing to the file. */
path: string;
/** The path of this file relative to its root. e.g. omitting `bazel-out/<..>/bin`. */
shortPath: string;
}
/** Interface describing an entry-point. */
export interface EntryPointInfo {
/** ES2022 index file for the APF entry-point. */
index: BazelFileInfo;
/** Flat ES2022 ES module bundle file. */
fesm2022Bundle: BazelFileInfo;
/** Index type definition file for the APF entry-point. */
typings: BazelFileInfo;
/**
* Whether the index or typing paths have been guessed. For entry-points built
* through `ts_library`, there is no explicit setting that declares the entry-point
* so the index file is guessed.
*/
guessedPaths: boolean;
}
/** Interface capturing relevant metadata for packaging. */
export interface PackageMetadata {
/** NPM package name of the output. */
npmPackageName: string;
/** Record of entry-points (including the primary one) and their info. */
entryPoints: Record<string, EntryPointInfo>;
}
| {
"end_byte": 1401,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_package/api.ts"
} |
angular/packages/bazel/src/ng_package/ng_package.bzl_0_7124 | # 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
"""Package Angular libraries for npm distribution
If all users of an Angular library use Bazel (e.g. internal usage in your company)
then you should simply add your library to the `deps` of the consuming application.
These rules exist for compatibility with non-Bazel consumers of your library.
It packages your library following the Angular Package Format, see the
specification of this format at https://goo.gl/jB3GVv
"""
load("@build_bazel_rules_nodejs//:providers.bzl", "DeclarationInfo", "JSEcmaScriptModuleInfo", "LinkablePackageInfo", "NpmPackageInfo", "node_modules_aspect")
load("@build_bazel_rules_nodejs//internal/linker:link_node_modules.bzl", "LinkerPackageMappingInfo")
load(
"@build_bazel_rules_nodejs//internal/pkg_npm:pkg_npm.bzl",
"PKG_NPM_ATTRS",
"PKG_NPM_OUTPUTS",
"create_package",
)
load("//packages/bazel/src/ng_module:partial_compilation.bzl", "partial_compilation_transition")
load("//packages/bazel/src/types_bundle:index.bzl", "bundle_type_declaration")
# Prints a debug message if "--define=VERBOSE_LOGS=true" is specified.
def _debug(vars, *args):
if "VERBOSE_LOGS" in vars.keys():
print("[ng_package.bzl]", args)
_DEFAULT_NG_PACKAGER = "//@angular/bazel/bin:packager"
_DEFAULT_ROLLUP_CONFIG_TMPL = "//:node_modules/@angular/bazel/src/ng_package/rollup.config.js"
_DEFAULT_ROLLUP = "//@angular/bazel/src/ng_package/rollup"
_NG_PACKAGE_MODULE_MAPPINGS_ATTR = "ng_package_module_mappings"
def _ng_package_module_mappings_aspect_impl(target, ctx):
mappings = dict()
for dep in ctx.rule.attr.deps:
if hasattr(dep, _NG_PACKAGE_MODULE_MAPPINGS_ATTR):
for k, v in getattr(dep, _NG_PACKAGE_MODULE_MAPPINGS_ATTR).items():
if k in mappings and mappings[k] != v:
fail(("duplicate module mapping at %s: %s maps to both %s and %s" %
(target.label, k, mappings[k], v)), "deps")
mappings[k] = v
if ((hasattr(ctx.rule.attr, "module_name") and ctx.rule.attr.module_name) or
(hasattr(ctx.rule.attr, "module_root") and ctx.rule.attr.module_root)):
mn = ctx.rule.attr.module_name
if not mn:
mn = target.label.name
mr = target.label.package
if target.label.workspace_root:
mr = "%s/%s" % (target.label.workspace_root, mr)
if ctx.rule.attr.module_root and ctx.rule.attr.module_root != ".":
if ctx.rule.attr.module_root.endswith(".ts"):
# This is the type-checking module mapping. Strip the trailing .d.ts
# as it doesn't belong in TypeScript's path mapping.
mr = "%s/%s" % (mr, ctx.rule.attr.module_root.replace(".d.ts", ""))
else:
mr = "%s/%s" % (mr, ctx.rule.attr.module_root)
if mn in mappings and mappings[mn] != mr:
fail(("duplicate module mapping at %s: %s maps to both %s and %s" %
(target.label, mn, mappings[mn], mr)), "deps")
mappings[mn] = mr
return struct(ng_package_module_mappings = mappings)
ng_package_module_mappings_aspect = aspect(
_ng_package_module_mappings_aspect_impl,
attr_aspects = ["deps"],
)
WELL_KNOWN_EXTERNALS = [
"@angular/animations",
"@angular/animations/browser",
"@angular/animations/browser/testing",
"@angular/common",
"@angular/common/http",
"@angular/common/http/testing",
"@angular/common/testing",
"@angular/common/upgrade",
"@angular/compiler",
"@angular/core",
"@angular/core/testing",
"@angular/elements",
"@angular/forms",
"@angular/localize",
"@angular/localize/init",
"@angular/platform-browser",
"@angular/platform-browser/animations",
"@angular/platform-browser/testing",
"@angular/platform-browser-dynamic",
"@angular/platform-browser-dynamic/testing",
"@angular/platform-server",
"@angular/platform-server/init",
"@angular/platform-server/testing",
"@angular/router",
"@angular/router/testing",
"@angular/router/upgrade",
"@angular/service-worker",
"@angular/service-worker/config",
"@angular/upgrade",
"@angular/upgrade/static",
"rxjs",
"rxjs/operators",
"tslib",
]
def _compute_node_modules_root(ctx):
"""Computes the node_modules root from the node_modules and deps attributes.
Args:
ctx: the starlark execution context
Returns:
The node_modules root as a string
"""
node_modules_root = None
for d in ctx.attr.deps:
if NpmPackageInfo in d:
possible_root = "/".join(["external", d[NpmPackageInfo].workspace, "node_modules"])
if not node_modules_root:
node_modules_root = possible_root
elif node_modules_root != possible_root:
fail("All npm dependencies need to come from a single workspace. Found '%s' and '%s'." % (node_modules_root, possible_root))
if not node_modules_root:
# there are no fine grained deps but we still need a node_modules_root even if its empty
node_modules_root = "external/npm/node_modules"
return node_modules_root
def _write_rollup_config(
ctx,
root_dir,
filename = "_%s.rollup.conf.js"):
"""Generate a rollup config file.
Args:
ctx: Bazel rule execution context
root_dir: root directory for module resolution (defaults to None)
filename: output filename pattern (defaults to `_%s.rollup.conf.js`)
Returns:
The rollup config file. See https://rollupjs.org/guide/en#configuration-files
"""
config = ctx.actions.declare_file(filename % ctx.label.name)
mappings = dict()
all_deps = ctx.attr.deps + ctx.attr.srcs
for dep in all_deps:
if hasattr(dep, _NG_PACKAGE_MODULE_MAPPINGS_ATTR):
for k, v in getattr(dep, _NG_PACKAGE_MODULE_MAPPINGS_ATTR).items():
if k in mappings and mappings[k] != v:
fail(("duplicate module mapping at %s: %s maps to both %s and %s" %
(dep.label, k, mappings[k], v)), "deps")
mappings[k] = v
externals = WELL_KNOWN_EXTERNALS + ctx.attr.externals
# Pass external & globals through a templated config file because on Windows there is
# an argument limit and we there might be a lot of globals which need to be passed to
# rollup.
ctx.actions.expand_template(
output = config,
template = ctx.file.rollup_config_tmpl,
substitutions = {
"TMPL_banner_file": "\"%s\"" % ctx.file.license_banner.path if ctx.file.license_banner else "undefined",
"TMPL_module_mappings": str(mappings),
"TMPL_node_modules_root": _compute_node_modules_root(ctx),
"TMPL_root_dir": root_dir,
"TMPL_workspace_name": ctx.workspace_name,
"TMPL_external": ", ".join(["'%s'" % e for e in externals]),
},
)
return config | {
"end_byte": 7124,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_package/ng_package.bzl"
} |
angular/packages/bazel/src/ng_package/ng_package.bzl_7126_10670 | def _run_rollup(ctx, bundle_name, rollup_config, entry_point, inputs, js_output, format):
map_output = ctx.actions.declare_file(js_output.basename + ".map", sibling = js_output)
args = ctx.actions.args()
args.add("--input", entry_point.path)
args.add("--config", rollup_config)
args.add("--output.file", js_output)
args.add("--output.format", format)
# After updating to build_bazel_rules_nodejs 0.27.0+, rollup has been updated to v1.3.1
# which tree shakes @__PURE__ annotations and const variables which are later amended by NGCC.
# We turn this feature off for ng_package as Angular bundles contain these and there are
# test failures if they are removed.
# See comments in:
# https://github.com/angular/angular/pull/29210
# https://github.com/angular/angular/pull/32069
args.add("--no-treeshake")
# Note: if the input has external source maps then we need to also install and use
# `rollup-plugin-sourcemaps`, which will require us to use rollup.config.js file instead
# of command line args
args.add("--sourcemap")
args.add("--preserveSymlinks")
# We will produce errors as needed. Anything else is spammy: a well-behaved
# bazel rule prints nothing on success.
args.add("--silent")
other_inputs = [rollup_config]
if ctx.file.license_banner:
other_inputs.append(ctx.file.license_banner)
ctx.actions.run(
progress_message = "ng_package: Rollup %s (%s)" % (bundle_name, entry_point.short_path),
mnemonic = "AngularPackageRollup",
inputs = inputs.to_list() + other_inputs,
outputs = [js_output, map_output],
executable = ctx.executable.rollup,
tools = [ctx.executable.rollup],
arguments = [args],
)
return [js_output, map_output]
# Serializes a file into a struct that matches the `BazelFileInfo` type in the
# packager implementation. Useful for transmission of such information.
def _serialize_file(file):
return struct(path = file.path, shortPath = file.short_path)
# Serializes a list of files into a JSON string that can be passed as CLI argument
# for the packager, matching the `BazelFileInfo[]` type in the packager implementation.
def _serialize_files_for_arg(files):
result = []
for file in files:
result.append(_serialize_file(file))
return json.encode(result)
def _find_matching_file(files, search_short_path):
for file in files:
if file.short_path == search_short_path:
return file
fail("Could not find file that is expected to exist: %s" % search_short_path)
def _is_part_of_package(file, owning_package):
return file.short_path.startswith(owning_package)
def _filter_esm_files_to_include(files, owning_package):
result = []
for file in files:
# We skip all `.externs.js` files as those should not be shipped as part of
# the ESM2022 output. The externs are empty because `ngc-wrapped` disables
# externs generation in prodmode for workspaces other than `google3`.
if file.path.endswith("externs.js"):
continue
# We omit all non-JavaScript files. These are not required for the FESM bundle
# generation and are not expected to be put into the `esm2022` output.
if not file.path.endswith(".js") and not file.path.endswith(".mjs"):
continue
if _is_part_of_package(file, owning_package):
result.append(file)
return result
# ng_package produces package that is npm-ready. | {
"end_byte": 10670,
"start_byte": 7126,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_package/ng_package.bzl"
} |
angular/packages/bazel/src/ng_package/ng_package.bzl_10671_19572 | def _ng_package_impl(ctx):
npm_package_directory = ctx.actions.declare_directory("%s.ng_pkg" % ctx.label.name)
owning_package = ctx.label.package
# The name of the primary entry-point FESM bundles. If not explicitly provided through
# the entry-point name attribute, we compute the name from the owning package
# e.g. if defined in `packages/core:npm_package`, the name is resolved to be `core`.
primary_bundle_name = \
ctx.attr.primary_bundle_name if ctx.attr.primary_bundle_name else owning_package.split("/")[-1]
# Static files are files which are simply copied over into the tree artifact. These files
# are not picked up by the entry-point bundling etc. Can also be generated by e.g. a genrule.
static_files = []
# Collect static files, and skip files outside of the current owning package.
for file in ctx.files.srcs:
if not file.short_path.startswith(owning_package):
_debug(ctx.var, "File %s is defined outside of %s but part of `srcs`, skipping." % (file, owning_package))
else:
static_files.append(file)
# These accumulators match the directory names where the files live in the
# Angular package format.
fesm2022 = []
type_files = []
# List of unscoped direct and transitive ESM sources that are provided
# by all entry-points.
unscoped_all_entry_point_esm2022 = []
# We infer the entry points to be:
# - ng_module rules in the deps (they have an "angular" provider)
# - in this package or a subpackage
# - those that have a module_name attribute (they produce flat module metadata)
collected_entry_points = []
# Name of the NPM package. The name is computed as we iterate through all
# dependencies of the `ng_package`.
npm_package_name = None
for dep in ctx.attr.deps:
if not dep.label.package.startswith(owning_package):
fail("Unexpected dependency. %s is defined outside of %s." % (dep, owning_package))
# Module name of the current entry-point. eg. @angular/core/testing
module_name = ""
# Packsge name where this entry-point is defined in,
entry_point_package = dep.label.package
# Intentionally evaluates to empty string for the main entry point
entry_point = entry_point_package[len(owning_package) + 1:]
# Whether this dependency is for the primary entry-point of the package.
is_primary_entry_point = entry_point == ""
# Collect ESM2022 and type definition source files from the dependency, including
# transitive sources which are not directly defined in the entry-point. This is
# necessary to allow for entry-points to rely on sub-targets (as a perf improvement).
unscoped_esm2022_depset = dep[JSEcmaScriptModuleInfo].sources
unscoped_types_depset = dep[DeclarationInfo].transitive_declarations
unscoped_all_entry_point_esm2022.append(unscoped_esm2022_depset)
# Extract the "module_name" from either "ts_library" or "ng_module". Both
# set the "module_name" in the provider struct.
if hasattr(dep, "module_name"):
module_name = dep.module_name
if is_primary_entry_point:
npm_package_name = module_name
if hasattr(dep, "angular") and hasattr(dep.angular, "flat_module_metadata"):
# For dependencies which are built using the "ng_module" with flat module bundles
# enabled, we determine the module name, the flat module index file, the metadata
# file and the typings entry point from the flat module metadata which is set by
# the "ng_module" rule.
ng_module_metadata = dep.angular.flat_module_metadata
module_name = ng_module_metadata.module_name
es2022_entry_point = ng_module_metadata.flat_module_out_prodmode_file
typings_entry_point = ng_module_metadata.typings_file
guessed_paths = False
_debug(
ctx.var,
"entry-point %s is built using a flat module bundle." % dep,
"using %s as main file of the entry-point" % es2022_entry_point,
)
else:
_debug(
ctx.var,
"entry-point %s does not have flat module metadata." % dep,
"guessing `index.mjs` as main file of the entry-point",
)
# Note: Using `to_list()` is expensive but we cannot get around this here as
# we need to filter out generated files and need to be able to iterate through
# typing files in order to determine the entry-point type file.
unscoped_types = unscoped_types_depset.to_list()
# Note: Using `to_list()` is expensive but we cannot get around this here as
# we need to filter out generated files to be able to detect entry-point index
# files when no flat module metadata is available.
unscoped_esm2022_list = unscoped_esm2022_depset.to_list()
# In case the dependency is built through the "ts_library" rule, or the "ng_module"
# rule does not generate a flat module bundle, we determine the index file and
# typings entry-point through the most reasonable defaults (i.e. "package/index").
es2022_entry_point = _find_matching_file(unscoped_esm2022_list, "%s/index.mjs" % entry_point_package)
typings_entry_point = _find_matching_file(unscoped_types, "%s/index.d.ts" % entry_point_package)
guessed_paths = True
bundle_name = "%s.mjs" % (primary_bundle_name if is_primary_entry_point else entry_point)
fesm2022_file = ctx.actions.declare_file("fesm2022/%s" % bundle_name)
# By default, we will bundle the typings entry-point, unless explicitly opted-out
# through the `skip_type_bundling` rule attribute.
if entry_point in ctx.attr.skip_type_bundling:
if typings_entry_point.short_path != "%s/index.d.ts" % entry_point_package:
fail(("Type bundling is explicitly disabled for `%s`, expected manual " +
"`%s/index.d.ts` to be provided.") % (entry_point, entry_point_package))
typings_file = typings_entry_point
else:
# Note: To avoid conflicts with source-file generated `index.d.ts` files we prefix the
# bundle typings file and remove the prefix later when assembling the package.
typings_file = ctx.actions.declare_file("%s__index.d.ts" % ("%s/" % entry_point if entry_point else ""))
bundle_type_declaration(
ctx = ctx,
output_file = typings_file,
entry_point = typings_entry_point,
license_banner_file = ctx.file.license_banner,
types = unscoped_types_depset,
)
type_files.append(typings_file)
# Store the collected entry point in a list of all entry-points. This
# can be later passed to the packager as a manifest.
collected_entry_points.append(struct(
module_name = module_name,
es2022_entry_point = es2022_entry_point,
fesm2022_file = fesm2022_file,
typings_file = typings_file,
guessed_paths = guessed_paths,
))
# Note: For creating the bundles, we use all the ESM2022 sources that have been
# collected from the dependencies. This allows for bundling of code that is not
# necessarily part of the owning package (with respect to the `externals` attribute)
rollup_inputs = unscoped_esm2022_depset
esm2022_config = _write_rollup_config(ctx, ctx.bin_dir.path, filename = "_%s.rollup_esm2022.conf.js")
fesm2022.extend(
_run_rollup(
ctx,
"fesm2022",
esm2022_config,
es2022_entry_point,
rollup_inputs,
fesm2022_file,
format = "esm",
),
)
# Note: Using `to_list()` is expensive but we cannot get around this here as
# we need to filter out generated files and need to be able to iterate through
# JavaScript files in order to capture the relevant package-owned `esm2022/` in the APF.
unscoped_all_entry_point_esm2022_list = depset(transitive = unscoped_all_entry_point_esm2022).to_list()
# Filter ESM2022 JavaScript inputs to files which are part of the owning package. The
# packager should not copy external files into the package.
esm2022 = _filter_esm_files_to_include(unscoped_all_entry_point_esm2022_list, owning_package)
packager_inputs = (
static_files +
type_files +
fesm2022 + esm2022
)
packager_args = ctx.actions.args()
packager_args.use_param_file("%s", use_always = True) | {
"end_byte": 19572,
"start_byte": 10671,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_package/ng_package.bzl"
} |
angular/packages/bazel/src/ng_package/ng_package.bzl_19578_27644 | # The order of arguments matters here, as they are read in order in packager.ts.
packager_args.add(npm_package_directory.path)
packager_args.add(ctx.label.package)
# Marshal the metadata into a JSON string so we can parse the data structure
# in the TypeScript program easily.
metadata_arg = {}
for m in collected_entry_points:
# The captured properties need to match the `EntryPointInfo` interface
# in the packager executable tool.
metadata_arg[m.module_name] = {
"index": _serialize_file(m.es2022_entry_point),
"fesm2022Bundle": _serialize_file(m.fesm2022_file),
"typings": _serialize_file(m.typings_file),
# If the paths for that entry-point were guessed (e.g. "ts_library" rule or
# "ng_module" without flat module bundle), we pass this information to the packager.
"guessedPaths": m.guessed_paths,
}
# Encodes the package metadata with all its entry-points into JSON so that
# it can be deserialized by the packager tool. The struct needs to match with
# the `PackageMetadata` interface in the packager tool.
packager_args.add(json.encode(struct(
npmPackageName = npm_package_name,
entryPoints = metadata_arg,
)))
if ctx.file.readme_md:
packager_inputs.append(ctx.file.readme_md)
packager_args.add(ctx.file.readme_md.path)
else:
# placeholder
packager_args.add("")
if ctx.file.license:
packager_inputs.append(ctx.file.license)
packager_args.add(ctx.file.license.path)
else:
#placeholder
packager_args.add("")
packager_args.add(_serialize_files_for_arg(fesm2022))
packager_args.add(_serialize_files_for_arg(esm2022))
packager_args.add(_serialize_files_for_arg(static_files))
packager_args.add(_serialize_files_for_arg(type_files))
ctx.actions.run(
progress_message = "Angular Packaging: building npm package %s" % str(ctx.label),
mnemonic = "AngularPackage",
inputs = packager_inputs,
outputs = [npm_package_directory],
executable = ctx.executable.ng_packager,
arguments = [packager_args],
)
# Re-use the create_package function from the nodejs npm_package rule.
package_dir = create_package(
ctx = ctx,
# Note: Static files and dependencies are already handled as part of the `ng_package` tree
# artifact, so we need to explicitly tell the `pkg_npm` helper to not care about such.
static_files = [],
deps_files = [],
nested_packages = [npm_package_directory] + ctx.files.nested_packages,
)
# Empty depset. Since these are immutable we don't need to multiple new instances.
empty_depset = depset([])
return [
DefaultInfo(files = depset([package_dir])),
# We disable propagation of the `link_node_modules` aspect. We do not want
# mappings from dependencies for the `ng_package` to leak to consumers relying
# on the NPM package target. Since we use an outgoing transition for dependencies
# the mapping paths would be different for the dependency targets and cause mapping
# conflicts if tests rely on both a `ng_package` and a transitive dep target of it.
# More details: https://github.com/bazelbuild/rules_nodejs/issues/2941.
# TODO(devversion): Consider supporting the `package_name` attribute.
LinkerPackageMappingInfo(mappings = empty_depset, node_modules_roots = empty_depset),
LinkablePackageInfo(path = package_dir.path, files = depset([package_dir])),
]
_NG_PACKAGE_DEPS_ASPECTS = [ng_package_module_mappings_aspect, node_modules_aspect]
_NG_PACKAGE_ATTRS = dict(PKG_NPM_ATTRS, **{
"srcs": attr.label_list(
doc = """JavaScript source files from the workspace.
These can use ES2022 syntax and ES Modules (import/export)""",
cfg = partial_compilation_transition,
allow_files = True,
),
"externals": attr.string_list(
doc = """List of external module that should not be bundled into the flat ESM bundles.""",
default = [],
),
"license_banner": attr.label(
doc = """A .txt file passed to the `banner` config option of rollup.
The contents of the file will be copied to the top of the resulting bundles.
Configured substitutions are applied like with other files in the package.""",
allow_single_file = [".txt"],
),
"license": attr.label(
doc = """A textfile that will be copied to the root of the npm package.""",
allow_single_file = True,
),
"deps": attr.label_list(
doc = """ Targets that produce production JavaScript outputs, such as `ts_library`.""",
aspects = _NG_PACKAGE_DEPS_ASPECTS,
providers = [JSEcmaScriptModuleInfo, DeclarationInfo],
cfg = partial_compilation_transition,
),
"readme_md": attr.label(allow_single_file = [".md"]),
"primary_bundle_name": attr.string(
doc = "Name to use when generating bundle files for the primary entry-point.",
),
"ng_packager": attr.label(
default = Label(_DEFAULT_NG_PACKAGER),
executable = True,
cfg = "exec",
),
"skip_type_bundling": attr.string_list(
default = [],
doc = """
List of entry-points for which type bundle generation should be skipped. Requires a
self-contained `index.d.ts` to be generated (i.e. with no relative imports).
Skipping of bundling might be desirable due to limitations in Microsoft's API extractor.
For example when `declare global` is used: https://github.com/microsoft/rushstack/issues/2090.
```
"", # Skips the primary entry-point from bundling.
"testing", # Skips the testing entry-point from type bundling
"select/testing", # Skips the `select/testing` entry-point
```
""",
),
"rollup": attr.label(
default = Label(_DEFAULT_ROLLUP),
executable = True,
cfg = "exec",
),
"rollup_config_tmpl": attr.label(
default = Label(_DEFAULT_ROLLUP_CONFIG_TMPL),
allow_single_file = True,
),
"_types_bundler_bin": attr.label(
default = "//packages/bazel/src/types_bundle:types_bundler",
cfg = "exec",
executable = True,
),
# Needed in order to allow for the outgoing transition on the `deps` attribute.
# https://docs.bazel.build/versions/main/skylark/config.html#user-defined-transitions.
"_allowlist_function_transition": attr.label(
default = "@bazel_tools//tools/allowlists/function_transition_allowlist",
),
})
def _ng_package_outputs(name):
"""This function computes the named outputs for an ng_package rule."""
outputs = {}
for key in PKG_NPM_OUTPUTS:
# PKG_NPM_OUTPUTS is a "normal" dict-valued outputs so it looks like
# "pack": "%{name}.pack",
# But this is a function-valued outputs.
# Bazel won't replace the %{name} token so we have to do it.
outputs[key] = PKG_NPM_OUTPUTS[key].replace("%{name}", name)
return outputs
ng_package = rule(
implementation = _ng_package_impl,
attrs = _NG_PACKAGE_ATTRS,
outputs = _ng_package_outputs,
toolchains = ["@rules_nodejs//nodejs:toolchain_type"],
)
def ng_package_macro(name, **kwargs):
"""ng_package produces an npm-ready APF package for an Angular library."""
ng_package(
name = name,
**kwargs
)
native.alias(
name = name + ".pack",
actual = select({
"@bazel_tools//src/conditions:host_windows": name + ".pack.bat",
"//conditions:default": name + ".pack.sh",
}),
)
native.alias(
name = name + ".publish",
actual = select({
"@bazel_tools//src/conditions:host_windows": name + ".publish.bat",
"//conditions:default": name + ".publish.sh",
}),
) | {
"end_byte": 27644,
"start_byte": 19578,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_package/ng_package.bzl"
} |
angular/packages/bazel/src/ng_package/rollup.config.js_0_5534 | /**
* @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
*/
// Rollup configuration
// GENERATED BY Bazel
const {nodeResolve} = require('@rollup/plugin-node-resolve');
const commonjs = require('@rollup/plugin-commonjs');
const MagicString = require('magic-string');
const sourcemaps = require('rollup-plugin-sourcemaps');
const path = require('path');
const fs = require('fs');
function log_verbose(...m) {
// This is a template file so we use __filename to output the actual filename
if (!!process.env['VERBOSE_LOGS']) console.error(`[${path.basename(__filename)}]`, ...m);
}
const workspaceName = 'TMPL_workspace_name';
const rootDir = 'TMPL_root_dir';
const bannerFile = TMPL_banner_file;
const moduleMappings = TMPL_module_mappings;
const nodeModulesRoot = 'TMPL_node_modules_root';
log_verbose(`running with
cwd: ${process.cwd()}
workspaceName: ${workspaceName}
rootDir: ${rootDir}
bannerFile: ${bannerFile}
moduleMappings: ${JSON.stringify(moduleMappings)}
nodeModulesRoot: ${nodeModulesRoot}
`);
function fileExists(filePath) {
try {
return fs.statSync(filePath).isFile();
} catch (e) {
return false;
}
}
// This resolver mimics the TypeScript Path Mapping feature, which lets us resolve
// modules based on a mapping of short names to paths.
function resolveBazel(importee, importer) {
log_verbose(`resolving '${importee}' from ${importer}`);
const baseDir = process.cwd();
function resolveInRootDir(importee) {
var candidate = path.join(baseDir, rootDir, importee);
log_verbose(`try to resolve '${importee}' at '${candidate}'`);
try {
var result = require.resolve(candidate);
return result;
} catch (e) {
return undefined;
}
}
// Since mappings are always in POSIX paths, when comparing the importee to mappings
// we should normalize the importee.
// Having it normalized is also useful to determine relative paths.
const normalizedImportee = importee.replace(/\\/g, '/');
// If import is fully qualified then resolve it directly
if (fileExists(importee)) {
log_verbose(`resolved fully qualified '${importee}'`);
return importee;
}
var resolved;
if (normalizedImportee.startsWith('./') || normalizedImportee.startsWith('../')) {
// relative import
if (importer) {
let importerRootRelative = path.dirname(importer);
const relative = path.relative(path.join(baseDir, rootDir), importerRootRelative);
if (!relative.startsWith('.')) {
importerRootRelative = relative;
}
resolved = path.join(importerRootRelative, importee);
} else {
throw new Error('cannot resolve relative paths without an importer');
}
if (resolved) resolved = resolveInRootDir(resolved);
}
if (!resolved) {
// possible workspace import or external import if importee matches a module
// mapping
for (const k in moduleMappings) {
if (normalizedImportee == k || normalizedImportee.startsWith(k + '/')) {
// replace the root module name on a mappings match
// note that the module_root attribute is intended to be used for type-checking
// so it uses eg. "index.d.ts". At runtime, we have only index.js, so we strip the
// .d.ts suffix and let node require.resolve do its thing.
var v = moduleMappings[k].replace(/\.d\.ts$/, '');
const mappedImportee = path.join(v, normalizedImportee.slice(k.length + 1));
log_verbose(`module mapped '${importee}' to '${mappedImportee}'`);
resolved = resolveInRootDir(mappedImportee);
if (resolved) break;
}
}
}
if (!resolved) {
// workspace import
const userWorkspacePath = path.relative(workspaceName, importee);
resolved = resolveInRootDir(userWorkspacePath.startsWith('..') ? importee : userWorkspacePath);
}
if (resolved) {
if (path.extname(resolved) == '.js') {
// check for .mjs file and prioritize that
const resolved_mjs = resolved.slice(0, -3) + '.mjs';
if (fileExists(resolved_mjs)) {
resolved = resolved_mjs;
}
}
log_verbose(`resolved to ${resolved}`);
} else {
log_verbose(`allowing rollup to resolve '${importee}' with node module resolution`);
}
return resolved;
}
let bannerContent = '';
if (bannerFile) {
bannerContent = fs.readFileSync(bannerFile, {encoding: 'utf-8'});
}
/** Removed license banners from input files. */
const stripBannerPlugin = {
name: 'strip-license-banner',
transform(code, _filePath) {
const banner = /(\/\**\s+\*\s@license.*?\*\/)/s.exec(code);
if (!banner) {
return;
}
const [bannerContent] = banner;
const magicString = new MagicString(code);
const pos = code.indexOf(bannerContent);
magicString.remove(pos, pos + bannerContent.length).trimStart();
return {
code: magicString.toString(),
map: magicString.generateMap({
hires: true,
}),
};
},
};
const plugins = [
{
name: 'resolveBazel',
resolveId: resolveBazel,
},
nodeResolve({
mainFields: ['es2020', 'es2015', 'module', 'browser'],
jail: process.cwd(),
customResolveOptions: {moduleDirectory: nodeModulesRoot},
}),
stripBannerPlugin,
commonjs({ignoreGlobal: true}),
sourcemaps(),
];
const config = {
plugins,
external: [TMPL_external],
output: {
banner: bannerContent,
},
};
module.exports = config;
| {
"end_byte": 5534,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_package/rollup.config.js"
} |
angular/packages/bazel/src/ng_package/packager.ts_0_1271 | /**
* @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 fs from 'fs';
import * as path from 'path';
import {BazelFileInfo, PackageMetadata} from './api';
import {analyzeFileAndEnsureNoCrossImports} from './cross_entry_points_imports';
/**
* List of known `package.json` fields which provide information about
* supported package formats and their associated entry paths.
*/
const knownFormatPackageJsonFormatFields = ['main', 'typings', 'module'] as const;
/** Union type matching known `package.json` format fields. */
type KnownPackageJsonFormatFields = (typeof knownFormatPackageJsonFormatFields)[number];
/**
* Type describing the conditional exports descriptor for an entry-point.
* https://nodejs.org/api/packages.html#packages_conditional_exports
*/
type ConditionalExport = {
types?: string;
default?: string;
};
/** Type describing a `package.json` the packager deals with. */
type PackageJson = {
[key in KnownPackageJsonFormatFields]?: string;
} & {
name: string;
type?: string;
exports?: Record<string, ConditionalExport>;
};
// Main entry-point.
main(process.argv.slice(2)); | {
"end_byte": 1271,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_package/packager.ts"
} |
angular/packages/bazel/src/ng_package/packager.ts_1273_9396 | function main(args: string[]): void {
// This utility expects all of its arguments to be specified in a params file generated by
// bazel (see https://docs.bazel.build/versions/master/skylark/lib/Args.html#use_param_file).
const paramFilePath = args[0];
// Bazel params may be surrounded with quotes
function unquoteParameter(s: string) {
return s.replace(/^'(.*)'$/, '$1');
}
// Parameters are specified in the file one per line.
const params = fs.readFileSync(paramFilePath, 'utf-8').split('\n').map(unquoteParameter);
const [
// Output directory for the npm package.
outputDirExecPath,
// The package segment of the ng_package rule's label (e.g. 'package/common').
owningPackageName,
// JSON data capturing metadata of the package being built. See `PackageMetadata`.
metadataArg,
// Path to the package's README.md.
readmeMd,
// Path to the package's LICENSE file.
licenseFile,
// List of rolled-up flat ES2022 modules
fesm2022Arg,
// List of individual ES2022 modules
esm2022Arg,
// List of static files that should be copied into the package.
staticFilesArg,
// List of all type definitions that need to packaged into the ng_package.
typeDefinitionsArg,
] = params;
const fesm2022 = JSON.parse(fesm2022Arg) as BazelFileInfo[];
const esm2022 = JSON.parse(esm2022Arg) as BazelFileInfo[];
const typeDefinitions = JSON.parse(typeDefinitionsArg) as BazelFileInfo[];
const staticFiles = JSON.parse(staticFilesArg) as BazelFileInfo[];
const metadata = JSON.parse(metadataArg) as PackageMetadata;
if (readmeMd) {
copyFile(readmeMd, 'README.md');
}
if (licenseFile) {
copyFile(licenseFile, 'LICENSE');
}
/**
* Writes a file with the specified content into the package output.
* @param outputRelativePath Relative path in the output directory where the
* file is written to.
* @param fileContent Content of the file.
*/
function writeFile(outputRelativePath: string, fileContent: string | Buffer) {
const outputPath = path.join(outputDirExecPath, outputRelativePath);
// Always ensure that the target directory exists.
fs.mkdirSync(path.dirname(outputPath), {recursive: true});
fs.writeFileSync(outputPath, fileContent);
}
/**
* Copies a file into the package output to the specified location.
* @param inputPath File that should be copied.
* @param outputRelativePath Relative path in the output directory where the
* file is written to.
*/
function copyFile(inputPath: string, outputRelativePath: string) {
const fileContent = fs.readFileSync(inputPath, 'utf8');
writeFile(outputRelativePath, fileContent);
}
/**
* Gets the relative path for the given file within the owning package. This
* assumes the file is contained in the owning package.
*
* e.g. consider the owning package is `packages/core` and the input file
* is `packages/core/testing/index.d.ts`. This function would return the
* relative path as followed: `testing/index.d.ts`.
*/
function getOwningPackageRelativePath(file: BazelFileInfo): string {
return path.relative(owningPackageName, file.shortPath);
}
/** Gets the output-relative path where the given flat ESM file should be written to. */
function getFlatEsmOutputRelativePath(file: BazelFileInfo) {
// Flat ESM files should be put into their owning package relative sub-path. e.g. if
// there is a bundle in `packages/animations/fesm2022/browser/testing.mjs` then we
// want the bundle to be stored in `fesm2022/browser/testing.mjs`. Same thing applies
// for the `fesm2022` bundles. The directory name for `fesm` is already declared as
// part of the Bazel action generating these files. See `ng_package.bzl`.
return getOwningPackageRelativePath(file);
}
/** Gets the output-relative path where the typing file is being written to. */
function getTypingOutputRelativePath(file: BazelFileInfo) {
// Type definitions are intended to be copied into the package output while preserving the
// sub-path from the owning package. e.g. a file like `packages/animations/browser/__index.d.ts`
// will end up being written to `<pkg-out>/browser/index.d.ts`. Note that types are bundled
// as a separate action in the `ng_package` Starlark rule and prefixed with `__` to avoid
// conflicts with source `index.d.ts` files. We remove this prefix here.
return getOwningPackageRelativePath(file).replace(/__index\.d\.ts$/, 'index.d.ts');
}
/**
* Gets the entry-point sub-path from the package root. e.g. if the package name
* is `@angular/cdk`, then for `@angular/cdk/a11y` just `a11y` would be returned.
*/
function getEntryPointSubpath(moduleName: string): string {
return moduleName.slice(`${metadata.npmPackageName}/`.length);
}
/**
* Gets whether the given module name resolves to a secondary entry-point.
* e.g. if the package name is `@angular/cdk`, then for `@angular/cdk/a11y`
* this would return `true`.
*/
function isSecondaryEntryPoint(moduleName: string): boolean {
return getEntryPointSubpath(moduleName) !== '';
}
const crossEntryPointFailures = esm2022.flatMap((file) =>
analyzeFileAndEnsureNoCrossImports(file, metadata),
);
if (crossEntryPointFailures.length) {
console.error(crossEntryPointFailures);
process.exit(1);
}
// Copy all FESM files into the package output.
fesm2022.forEach((f) => copyFile(f.path, getFlatEsmOutputRelativePath(f)));
// Copy all type definitions into the package, preserving the sub-path from the
// owning package. e.g. a file like `packages/animations/browser/__index.d.ts` will
// end up in `browser/index.d.ts`
typeDefinitions.forEach((f) => copyFile(f.path, getTypingOutputRelativePath(f)));
for (const file of staticFiles) {
// We copy all files into the package output while preserving the sub-path from
// the owning package. e.g. `packages/core/package.json` ends up `<pkg-out>/package.json`.
const outputRelativePath = getOwningPackageRelativePath(file);
let content = fs.readFileSync(file.path, 'utf8');
// Check and modify package.json files as necessary for publishing
if (path.basename(file.path) === 'package.json') {
const isPrimaryPackageJson = outputRelativePath === 'package.json';
const packageJson = JSON.parse(content) as PackageJson;
const packageName = packageJson['name'];
// Prevent non-primary `package.json` files which would throw-off resolution.
// Resolution in the package should only be based on the top-level `package.json`.
if (!isPrimaryPackageJson) {
throw Error(
`Found a nested "package.json" file in the package output: ${file.shortPath}.\n` +
`All information of the package should reside in the primary package file.`,
);
}
// Check if the `name` field of the `package.json` files are matching with
// name of the NPM package. This is an additional safety check.
if (packageName !== metadata.npmPackageName) {
throw Error(
`Primary "package.json" has mismatching package name. Expected the ` +
`package to be named "${metadata.npmPackageName}", but is set to: ${packageName}.`,
);
}
let newPackageJson = insertFormatFieldsIntoPackageJson(
outputRelativePath,
packageJson,
false,
);
newPackageJson = updatePrimaryPackageJson(newPackageJson);
// Update the content with the new `package.json` file content.
content = JSON.stringify(newPackageJson, null, 2);
}
writeFile(outputRelativePath, content);
}
/**
* Inserts or edits properties into the package.json file(s) in the package so that
* they point to all the right generated artifacts.
*
* @param packageJsonOutRelativePath Path where the `package.json` is stored in
* the package output.
* @param parsedPackage Parsed package.json content
* @param isGeneratedPackageJson Whether the passed package.json has been generated.
*/ | {
"end_byte": 9396,
"start_byte": 1273,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_package/packager.ts"
} |
angular/packages/bazel/src/ng_package/packager.ts_9399_15934 | function insertFormatFieldsIntoPackageJson(
packageJsonOutRelativePath: string,
parsedPackage: Readonly<PackageJson>,
isGeneratedPackageJson: boolean,
): PackageJson {
const packageJson: PackageJson = {...parsedPackage};
const packageName = packageJson['name'];
const entryPointInfo = metadata.entryPoints[packageName];
const packageJsonContainingDir = path.dirname(packageJsonOutRelativePath);
// If a package json file has been discovered that does not match any
// entry-point in the metadata, we report a warning as most likely the target
// is configured incorrectly (e.g. missing `module_name` attribute).
if (!entryPointInfo) {
// Ideally we should throw here, as we got an entry point that doesn't
// have flat module metadata / bundle index, so it may have been an
// ng_module that's missing a module_name attribute.
// However, @angular/compiler can't be an ng_module, as it's the internals
// of the ngc compiler, yet we want to build an ng_package for it.
// So ignore package.json files when we are missing data.
console.error('WARNING: no module metadata for package', packageName);
console.error(' Not updating the package.json file to point to it');
console.error(
' The ng_module for this package is possibly missing the module_name attribute ',
);
return packageJson;
}
// If we guessed the index paths for a module, and it contains an explicit `package.json`
// file that already sets format properties, we skip automatic insertion of format
// properties but report a warning in case properties have been set by accident.
if (
entryPointInfo.guessedPaths &&
!isGeneratedPackageJson &&
hasExplicitFormatProperties(packageJson)
) {
console.error('WARNING: `package.json` explicitly sets format properties (like `main`).');
console.error(
' Skipping automatic insertion of format properties as explicit ' +
'format properties are set.',
);
console.error(' Ignore this warning if explicit properties are set intentionally.');
return packageJson;
}
const fesm2022RelativeOutPath = getFlatEsmOutputRelativePath(entryPointInfo.fesm2022Bundle);
const typingsRelativeOutPath = getTypingOutputRelativePath(entryPointInfo.typings);
packageJson.module = normalizePath(
path.relative(packageJsonContainingDir, fesm2022RelativeOutPath),
);
packageJson.typings = normalizePath(
path.relative(packageJsonContainingDir, typingsRelativeOutPath),
);
return packageJson;
}
/**
* Updates the primary `package.json` file of the NPM package to specify
* the module conditional exports and the ESM module type.
*/
function updatePrimaryPackageJson(packageJson: Readonly<PackageJson>): PackageJson {
if (packageJson.type !== undefined) {
throw Error(
'The primary "package.json" file of the package sets the "type" field ' +
'that is controlled by the packager. Please unset it.',
);
}
const newPackageJson: PackageJson = {...packageJson};
newPackageJson.type = 'module';
// The `package.json` file is made publicly accessible for tools that
// might want to query information from the Angular NPM package.
insertExportMappingOrError(newPackageJson, './package.json', {default: './package.json'});
// Capture all entry-points in the `exports` field using the subpath export declarations:
// https://nodejs.org/api/packages.html#packages_subpath_exports.
for (const [moduleName, entryPoint] of Object.entries(metadata.entryPoints)) {
const subpath = isSecondaryEntryPoint(moduleName)
? `./${getEntryPointSubpath(moduleName)}`
: '.';
const fesm2022OutRelativePath = getFlatEsmOutputRelativePath(entryPoint.fesm2022Bundle);
const typesOutRelativePath = getTypingOutputRelativePath(entryPoint.typings);
// Insert the export mapping for the entry-point. We set `default` to the FESM 2022
// output, and also set the `types` condition which will be respected by TS 4.5.
// https://github.com/microsoft/TypeScript/pull/45884.
insertExportMappingOrError(newPackageJson, subpath, {
types: normalizePath(typesOutRelativePath),
// Note: The default conditions needs to be the last one.
default: normalizePath(fesm2022OutRelativePath),
});
}
return newPackageJson;
}
/**
* Inserts a subpath export mapping into the specified `package.json` object.
* @throws An error if the mapping is already defined and would conflict.
*/
function insertExportMappingOrError(
packageJson: PackageJson,
subpath: string,
mapping: ConditionalExport,
) {
if (packageJson.exports === undefined) {
packageJson.exports = {};
}
if (packageJson.exports[subpath] === undefined) {
packageJson.exports[subpath] = {};
}
const subpathExport = packageJson.exports[subpath];
// Go through all conditions that should be inserted. If the condition is already
// manually set of the subpath export, we throw an error. In general, we allow for
// additional conditions to be set. These will always precede the generated ones.
for (const conditionName of Object.keys(mapping) as [keyof ConditionalExport]) {
if (subpathExport[conditionName] !== undefined) {
throw Error(
`Found a conflicting export condition for "${subpath}". The "${conditionName}" ` +
`condition would be overridden by the packager. Please unset it.`,
);
}
// **Note**: The order of the conditions is preserved even though we are setting
// the conditions once at a time (the latest assignment will be at the end).
subpathExport[conditionName] = mapping[conditionName];
}
}
/** Whether the package explicitly sets any of the format properties (like `main`). */
function hasExplicitFormatProperties(parsedPackage: Readonly<PackageJson>): boolean {
return Object.keys(parsedPackage).some((fieldName: string) =>
knownFormatPackageJsonFormatFields.includes(fieldName as KnownPackageJsonFormatFields),
);
}
/**
* Normalizes the specified path by replacing backslash separators with Posix
* forward slash separators.
*/
function normalizePath(path: string): string {
const result = path.replace(/\\/g, '/');
return result.startsWith('.') ? result : `./${result}`;
}
} | {
"end_byte": 15934,
"start_byte": 9399,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_package/packager.ts"
} |
angular/packages/bazel/src/ng_package/cross_entry_points_imports.ts_0_4188 | /**
* @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 fs from 'fs';
import * as path from 'path';
import ts from 'typescript';
import {BazelFileInfo, EntryPointInfo, PackageMetadata} from './api';
/** Interface describing an entry-point Bazel package. */
interface EntryPointPackage {
/** Module name of the entry-point. */
name: string;
/** Execroot-relative path to the entry-point package. */
path: string;
/** Extracted info for the entry-point. */
info: EntryPointInfo;
}
/** Comment that can be used to skip a single import from being flagged. */
const skipComment = '// @ng_package: ignore-cross-repo-import';
/**
* Analyzes the given JavaScript source file and checks whether there are
* any relative imports that point to different entry-points or packages.
*
* Such imports are flagged and will be returned in the failure list. Cross
* entry-point or package imports result in duplicate code and therefore are
* forbidden (unless explicitly opted out via comment - {@link skipComment}).
*/
export function analyzeFileAndEnsureNoCrossImports(
file: BazelFileInfo,
pkg: PackageMetadata,
): string[] {
const content = fs.readFileSync(file.path, 'utf8');
const sf = ts.createSourceFile(file.path, content, ts.ScriptTarget.Latest, true);
const fileDirPath = path.posix.dirname(file.path);
const fileDebugName = file.shortPath.replace(/\.[cm]js$/, '.ts');
const failures: string[] = [];
const owningPkg = determineOwningEntryPoint(file, pkg);
if (owningPkg === null) {
throw new Error(`Could not determine owning entry-point package of: ${file.shortPath}`);
}
// TODO: Consider handling deep dynamic import expressions.
for (const st of sf.statements) {
if (!ts.isImportDeclaration(st) || !ts.isStringLiteralLike(st.moduleSpecifier)) {
continue;
}
// Skip module imports.
if (!st.moduleSpecifier.text.startsWith('.')) {
continue;
}
// Skip this import if there is an explicit skip comment.
const leadingComments = ts.getLeadingCommentRanges(sf.text, st.getFullStart());
if (
leadingComments !== undefined &&
leadingComments.some((c) => sf.text.substring(c.pos, c.end) === skipComment)
) {
continue;
}
const destinationPath = path.posix.join(fileDirPath, st.moduleSpecifier.text);
const targetPackage = determineOwningEntryPoint({path: destinationPath}, pkg);
if (targetPackage === null) {
failures.push(
`Could not determine owning entry-point package of: ${destinationPath}. Imported from: ${fileDebugName}. Is this a relative import to another full package?.\n` +
`You can skip this import by adding a comment: ${skipComment}`,
);
continue;
}
if (targetPackage.path !== owningPkg.path) {
failures.push(
`Found relative cross entry-point import in: ${fileDebugName}. Import to: ${st.moduleSpecifier.text}\n` +
`You can skip this import by adding a comment: ${skipComment}`,
);
}
}
return failures;
}
/** Determines the owning entry-point for the given JavaScript file. */
function determineOwningEntryPoint(
file: Pick<BazelFileInfo, 'path'>,
pkg: PackageMetadata,
): EntryPointPackage | null {
let owningEntryPoint: EntryPointPackage | null = null;
for (const [name, info] of Object.entries(pkg.entryPoints)) {
// Entry point directory is assumed because technically the entry-point
// could be deeper inside the entry-point source file package. This is
// unlikely though and we still catch most cases, especially in the standard
// folder layout where the APF entry-point index file resides at the top of
// the entry-point.
const assumedEntryPointDir = path.posix.dirname(info.index.path);
if (
file.path.startsWith(assumedEntryPointDir) &&
(owningEntryPoint === null || owningEntryPoint.path.length < assumedEntryPointDir.length)
) {
owningEntryPoint = {name, info, path: assumedEntryPointDir};
}
}
return owningEntryPoint;
}
| {
"end_byte": 4188,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_package/cross_entry_points_imports.ts"
} |
angular/packages/bazel/src/ng_package/BUILD.bazel_0_899 | # BEGIN-DEV-ONLY
load("//tools:defaults.bzl", "nodejs_binary", "ts_library")
package(default_visibility = ["//visibility:public"])
exports_files([
"ng_package.bzl",
"rollup.config.js",
])
ts_library(
name = "lib",
srcs = glob(["*.ts"]),
tsconfig = ":tsconfig.json",
deps = [
"@npm//@types/node",
"@npm//typescript",
],
)
filegroup(
name = "package_assets",
srcs = glob(["*.bzl"]) + [
"BUILD.bazel",
"rollup.config.js",
"//packages/bazel/src/ng_package/rollup:package_assets",
],
)
nodejs_binary(
name = "packager",
data = [
"lib",
],
entry_point = ":packager.ts",
# Disable the linker and rely on patched resolution which works better on Windows
# and is less prone to race conditions when targets build concurrently.
templated_args = ["--nobazel_run_linker"],
)
# END-DEV-ONLY
| {
"end_byte": 899,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_package/BUILD.bazel"
} |
angular/packages/bazel/src/ng_package/rollup/BUILD.bazel_0_824 | # Note: This file is shipped to NPM. It cannot use the `defaults.bzl` macro.
load("@build_bazel_rules_nodejs//:index.bzl", "nodejs_binary")
package(default_visibility = ["//visibility:public"])
filegroup(
name = "package_assets",
srcs = ["BUILD.bazel"],
)
nodejs_binary(
name = "rollup",
data = [
"@npm//@rollup/plugin-commonjs",
"@npm//@rollup/plugin-node-resolve",
"@npm//magic-string",
"@npm//rollup",
"@npm//rollup-plugin-sourcemaps",
"@npm//typescript",
],
entry_point = (
"@npm//:node_modules/rollup/dist/bin/rollup"
),
# Disable the linker and rely on patched resolution which works better on Windows
# and is less prone to race conditions when targets build concurrently.
templated_args = ["--nobazel_run_linker"],
)
| {
"end_byte": 824,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_package/rollup/BUILD.bazel"
} |
angular/packages/bazel/src/types_bundle/index.bzl_0_3961 | load("@build_bazel_rules_nodejs//:providers.bzl", "DeclarationInfo", "declaration_info")
def bundle_type_declaration(
ctx,
entry_point,
output_file,
types,
license_banner_file = None):
"""Rule helper for registering a bundle type declaration action."""
# Microsoft's API extractor requires a `package.json` file to be provided. We
# auto-generate such a file since such a file needs to exist on disk.
package_json = ctx.actions.declare_file(
"__api-extractor.json",
sibling = output_file,
)
ctx.actions.write(package_json, content = json.encode({
"name": "auto-generated-for-api-extractor",
}))
inputs = [package_json]
args = ctx.actions.args()
args.add(entry_point.path)
args.add(output_file.path)
args.add(package_json.path)
if license_banner_file:
args.add(license_banner_file.path)
inputs.append(license_banner_file)
# Pass arguments using a flag-file prefixed with `@`. This is
# a requirement for build action arguments in persistent workers.
# https://docs.bazel.build/versions/main/creating-workers.html#work-action-requirements.
args.use_param_file("@%s", use_always = True)
args.set_param_file_format("multiline")
ctx.actions.run(
mnemonic = "BundlingTypes",
inputs = depset(inputs, transitive = [types]),
outputs = [output_file],
executable = ctx.executable._types_bundler_bin,
arguments = [args],
execution_requirements = {"supports-workers": "1"},
progress_message = "Bundling types (%s)" % entry_point.short_path,
)
def _types_bundle_impl(ctx):
"""Implementation of the "types_bundle" rule."""
output = ctx.outputs.output_name
entry_point_short_path = "%s/%s" % (ctx.label.package, ctx.attr.entry_point)
entry_point_file = None
direct_types_depsets = []
type_depsets = []
for dep in ctx.attr.deps:
if DeclarationInfo in dep:
direct_types_depsets.append(dep[DeclarationInfo].declarations)
type_depsets.append(dep[DeclarationInfo].transitive_declarations)
types = depset(transitive = type_depsets)
# Note: Using `to_list()` is expensive but we cannot get around this here as
# we need to find a reference to the entry-point. We only care about direct
# types though, so the performance impact is rather low.
direct_types = depset(transitive = direct_types_depsets)
direct_types_list = direct_types.to_list()
# Iterate through the types and look for the entry point `File`.
for file in direct_types_list:
if file.short_path == entry_point_short_path:
entry_point_file = file
break
if entry_point_file == None:
fail("Could not find entry-point file: %s" % entry_point_short_path)
bundle_type_declaration(
ctx = ctx,
entry_point = entry_point_file,
output_file = output,
types = types,
)
output_depset = depset([output])
return [
DefaultInfo(files = output_depset),
declaration_info(output_depset),
]
types_bundle = rule(
implementation = _types_bundle_impl,
attrs = {
"deps": attr.label_list(
doc = "List of targets which are required for bundling the entry-point.",
providers = [DeclarationInfo],
mandatory = True,
allow_files = True,
),
"output_name": attr.output(
doc = "Output file name for the types bundle.",
mandatory = True,
),
"entry_point": attr.string(
doc = "Package-relative path to the entry-point type file which should be bundled.",
mandatory = True,
),
"_types_bundler_bin": attr.label(
default = "//packages/bazel/src/types_bundle:types_bundler",
cfg = "exec",
executable = True,
),
},
)
| {
"end_byte": 3961,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/types_bundle/index.bzl"
} |
angular/packages/bazel/src/types_bundle/BUILD.bazel_0_597 | # BEGIN-DEV-ONLY
load("//tools:defaults.bzl", "nodejs_binary", "ts_library")
package(default_visibility = ["//packages:__subpackages__"])
ts_library(
name = "lib",
srcs = [
"index.ts",
],
deps = [
"@npm//@bazel/worker",
"@npm//@microsoft/api-extractor",
"@npm//@types/node",
],
)
nodejs_binary(
name = "types_bundler",
data = [":lib"],
entry_point = ":index.ts",
visibility = ["//visibility:public"],
)
filegroup(
name = "package_assets",
srcs = [
"BUILD.bazel",
"index.bzl",
],
)
# END-DEV-ONLY
| {
"end_byte": 597,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/types_bundle/BUILD.bazel"
} |
angular/packages/bazel/src/types_bundle/index.ts_0_4800 | /**
* @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
*/
/// <reference types="node"/>
/// <reference lib="es2020"/>
import {runAsWorker, runWorkerLoop} from '@bazel/worker';
import {
Extractor,
ExtractorConfig,
ExtractorMessage,
IConfigFile,
IExtractorConfigPrepareOptions,
} from '@microsoft/api-extractor';
import * as fs from 'fs';
import * as path from 'path';
/**
* Bundles the specified entry-point and writes the output `d.ts` bundle to the specified
* output path. An optional license banner can be provided to be added to the bundle output.
*/
export async function runMain({
entryPointExecpath,
outputExecpath,
packageJsonExecpath,
licenseBannerExecpath,
}: {
entryPointExecpath: string;
outputExecpath: string;
packageJsonExecpath: string;
licenseBannerExecpath: string | undefined;
}): Promise<void> {
const configObject: IConfigFile = {
compiler: {
overrideTsconfig:
// We disable automatic `@types` resolution as this throws-off API reports
// when the API test is run outside sandbox. Instead we expect a list of
// hard-coded types that should be included. This works in non-sandbox too.
{files: [entryPointExecpath], compilerOptions: {types: [], lib: ['es2020', 'dom']}},
},
// The execroot is the working directory and it will contain all input files.
projectFolder: process.cwd(),
mainEntryPointFilePath: path.resolve(entryPointExecpath),
newlineKind: 'lf',
apiReport: {enabled: false, reportFileName: 'invalid'},
docModel: {enabled: false},
tsdocMetadata: {enabled: false},
dtsRollup: {
enabled: true,
untrimmedFilePath: path.resolve(outputExecpath),
},
};
// Resolve to an absolute path from the current working directory (i.e. execroot).
const packageJsonFullPath = path.resolve(packageJsonExecpath);
const options: IExtractorConfigPrepareOptions = {
configObject,
packageJsonFullPath,
packageJson: undefined,
configObjectFullPath: undefined,
};
const extractorConfig = ExtractorConfig.prepare(options);
const {succeeded} = Extractor.invoke(extractorConfig, {
messageCallback: handleApiExtractorMessage,
});
if (!succeeded) {
throw new Error('Type bundling failed. See error above.');
}
let bundleOutput = fs.readFileSync(outputExecpath, 'utf8');
// Strip AMD module directive comments.
bundleOutput = stripAmdModuleDirectiveComments(bundleOutput);
// Remove license comments as these are not deduped in API-extractor.
bundleOutput = bundleOutput.replace(/(\/\*\*\s+\*\s\@license(((?!\*\/).|\s)*)\*\/)/gm, '');
// Add license banner if provided.
if (licenseBannerExecpath) {
bundleOutput = `${fs.readFileSync(licenseBannerExecpath, 'utf8')}\n\n` + bundleOutput;
}
// Re-write the output file.
fs.writeFileSync(outputExecpath, bundleOutput);
}
/**
* Strip the named AMD module for compatibility from Bazel-generated type
* definitions. These may end up in the generated type bundles.
*
* e.g. `/// <amd-module name="@angular/localize/init" />` should be stripped.
*/
function stripAmdModuleDirectiveComments(content: string): string {
return content.replace(/^\/\/\/ <amd-module name=.*\/>[\r\n]+/gm, '');
}
/**
* Handles logging messages from API extractor.
*
* Certain info messages should be omitted and other messages should be printed
* to stderr to avoid worker protocol conflicts.
*/
function handleApiExtractorMessage(msg: ExtractorMessage): void {
msg.handled = true;
if (msg.messageId === 'console-compiler-version-notice' || msg.messageId === 'console-preamble') {
return;
}
if (msg.logLevel !== 'verbose' && msg.logLevel !== 'none') {
console.error(msg.text);
}
}
/** Runs one build using the specified build action command line arguments. */
async function runOneBuild(args: string[]): Promise<boolean> {
const [entryPointExecpath, outputExecpath, packageJsonExecpath, licenseBannerExecpath] = args;
try {
await runMain({entryPointExecpath, outputExecpath, packageJsonExecpath, licenseBannerExecpath});
return true;
} catch (e) {
console.error(e);
return false;
}
}
// Entry-point.
const processArgs = process.argv.slice(2);
if (runAsWorker(processArgs)) {
runWorkerLoop(runOneBuild);
} else {
// In non-worker mode we need to manually read the flag file and omit
// the leading `@` that is added as part of the worker requirements.
const flagFile = processArgs[0].substring(1);
const args = fs.readFileSync(flagFile, 'utf8').split('\n');
runOneBuild(args).then((success) => {
if (!success) {
process.exitCode = 1;
}
});
}
| {
"end_byte": 4800,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/types_bundle/index.ts"
} |
angular/packages/bazel/src/ngc-wrapped/utils.ts_0_6741 | /**
* @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
*
* @fileoverview A set of common helpers related to ng compiler wrapper.
*/
import {CompilerHost as NgCompilerHost} from '@angular/compiler-cli';
import * as fs from 'fs';
import * as path from 'path';
import ts from 'typescript';
const NODE_MODULES = 'node_modules/';
export const EXT = /(\.ts|\.d\.ts|\.js|\.jsx|\.tsx)$/;
export function relativeToRootDirs(filePath: string, rootDirs: string[]): string {
if (!filePath) return filePath;
// NB: the rootDirs should have been sorted longest-first
for (let i = 0; i < rootDirs.length; i++) {
const dir = rootDirs[i];
const rel = path.posix.relative(dir, filePath);
if (rel.indexOf('.') !== 0) return rel;
}
return filePath;
}
/**
* Adds support for the optional `fileNameToModuleName` operation to a given `ng.CompilerHost`.
*
* This is used within `ngc-wrapped` and the Bazel compilation flow, but is exported here to allow
* for other consumers of the compiler to access this same logic. For example, the xi18n operation
* in g3 configures its own `ng.CompilerHost` which also requires `fileNameToModuleName` to work
* correctly.
*/
export function patchNgHostWithFileNameToModuleName(
ngHost: NgCompilerHost,
compilerOpts: ts.CompilerOptions,
rootDirs: string[],
workspaceName: string,
compilationTargetSrc: string[],
useManifestPathsAsModuleName: boolean,
): void {
const fileNameToModuleNameCache = new Map<string, string>();
ngHost.fileNameToModuleName = (importedFilePath: string, containingFilePath?: string) => {
const cacheKey = `${importedFilePath}:${containingFilePath}`;
// Memoize this lookup to avoid expensive re-parses of the same file
// When run as a worker, the actual ts.SourceFile is cached
// but when we don't run as a worker, there is no cache.
// For one example target in g3, we saw a cache hit rate of 7590/7695
if (fileNameToModuleNameCache.has(cacheKey)) {
return fileNameToModuleNameCache.get(cacheKey)!;
}
const result = doFileNameToModuleName(importedFilePath, containingFilePath);
fileNameToModuleNameCache.set(cacheKey, result);
return result;
};
function doFileNameToModuleName(importedFilePath: string, containingFilePath?: string): string {
const relativeTargetPath = relativeToRootDirs(importedFilePath, rootDirs).replace(EXT, '');
const manifestTargetPath = `${workspaceName}/${relativeTargetPath}`;
if (useManifestPathsAsModuleName === true) {
return manifestTargetPath;
}
// Unless manifest paths are explicitly enforced, we initially check if a module name is
// set for the given source file. The compiler host from `@bazel/concatjs` sets source
// file module names if the compilation targets either UMD or AMD. To ensure that the AMD
// module names match, we first consider those.
try {
const sourceFile = ngHost.getSourceFile(importedFilePath, ts.ScriptTarget.Latest);
if (sourceFile && sourceFile.moduleName) {
return sourceFile.moduleName;
}
} catch (err) {
// File does not exist or parse error. Ignore this case and continue onto the
// other methods of resolving the module below.
}
// It can happen that the ViewEngine compiler needs to write an import in a factory file,
// and is using an ngsummary file to get the symbols.
// The ngsummary comes from an upstream ng_module rule.
// The upstream rule based its imports on ngsummary file which was generated from a
// metadata.json file that was published to npm in an Angular library.
// However, the ngsummary doesn't propagate the 'importAs' from the original metadata.json
// so we would normally not be able to supply the correct module name for it.
// For example, if the rootDir-relative filePath is
// node_modules/@angular/material/toolbar/typings/index
// we would supply a module name
// @angular/material/toolbar/typings/index
// but there is no JavaScript file to load at this path.
// This is a workaround for https://github.com/angular/angular/issues/29454
if (importedFilePath.indexOf('node_modules') >= 0) {
const maybeMetadataFile = importedFilePath.replace(EXT, '') + '.metadata.json';
if (fs.existsSync(maybeMetadataFile)) {
const moduleName = (
JSON.parse(fs.readFileSync(maybeMetadataFile, {encoding: 'utf-8'})) as {
importAs: string;
}
).importAs;
if (moduleName) {
return moduleName;
}
}
}
if (
(compilerOpts.module === ts.ModuleKind.UMD || compilerOpts.module === ts.ModuleKind.AMD) &&
ngHost.amdModuleName
) {
const amdName = ngHost.amdModuleName({fileName: importedFilePath} as ts.SourceFile);
if (amdName !== undefined) {
return amdName;
}
}
// If no AMD module name has been set for the source file by the `@bazel/concatjs` compiler
// host, and the target file is not part of a flat module node module package, we use the
// following rules (in order):
// 1. If target file is part of `node_modules/`, we use the package module name.
// 2. If no containing file is specified, or the target file is part of a different
// compilation unit, we use a Bazel manifest path. Relative paths are not possible
// since we don't have a containing file, and the target file could be located in the
// output directory, or in an external Bazel repository.
// 3. If both rules above didn't match, we compute a relative path between the source files
// since they are part of the same compilation unit.
// Note that we don't want to always use (2) because it could mean that compilation outputs
// are always leaking Bazel-specific paths, and the output is not self-contained. This could
// break `esm2015` or `esm5` output for Angular package release output
// Omit the `node_modules` prefix if the module name of an NPM package is requested.
if (relativeTargetPath.startsWith(NODE_MODULES)) {
return relativeTargetPath.slice(NODE_MODULES.length);
} else if (containingFilePath == null || !compilationTargetSrc.includes(importedFilePath)) {
return manifestTargetPath;
}
const containingFileDir = path.dirname(relativeToRootDirs(containingFilePath, rootDirs));
const relativeImportPath = path.posix.relative(containingFileDir, relativeTargetPath);
return relativeImportPath.startsWith('.') ? relativeImportPath : `./${relativeImportPath}`;
}
}
| {
"end_byte": 6741,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ngc-wrapped/utils.ts"
} |
angular/packages/bazel/src/ngc-wrapped/extract_i18n.ts_0_403 | /**
* @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
*
* @fileoverview Extracts i18n messages.
*/
// Entry point
if (require.main === module) {
const args = process.argv.slice(2);
console.error('>>> now yet implemented!');
process.exitCode = 1;
}
| {
"end_byte": 403,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ngc-wrapped/extract_i18n.ts"
} |
angular/packages/bazel/src/ngc-wrapped/README.md_0_94 | # ngc-wrapped
This is a wrapper around @angular/compiler-cli that makes ngc run under Bazel.
| {
"end_byte": 94,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ngc-wrapped/README.md"
} |
angular/packages/bazel/src/ngc-wrapped/ngc-wrapped-main.ts_0_388 | /**
* @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 {main} from './index';
main(process.argv.slice(2))
.then((exitCode) => (process.exitCode = exitCode))
.catch((e) => {
console.error(e);
process.exitCode = 1;
});
| {
"end_byte": 388,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ngc-wrapped/ngc-wrapped-main.ts"
} |
angular/packages/bazel/src/ngc-wrapped/BUILD.bazel_0_1737 | # BEGIN-DEV-ONLY
load("//tools:defaults.bzl", "nodejs_binary", "ts_library")
ts_library(
name = "ngc_lib",
srcs = [
"extract_i18n.ts",
"index.ts",
"ngc-wrapped-main.ts",
"utils.ts",
],
module_name = "@angular/bazel",
visibility = [
"//packages/bazel:__pkg__",
"//packages/bazel/test/ngc-wrapped:__subpackages__",
],
deps = [
"//packages/compiler-cli",
"//packages/compiler-cli/private",
"@npm//@bazel/concatjs",
"@npm//@types/node",
"@npm//typescript",
"@npm//typescript:typescript__typings",
],
)
nodejs_binary(
name = "ngc-wrapped",
data = [
":ngc_lib",
"//packages/bazel/third_party/github.com/bazelbuild/bazel/src/main/protobuf:worker_protocol.proto",
],
entry_point = ":ngc-wrapped-main.ts",
# Disables the Bazel node modules linker. The node module linker is unreliable for the
# persistent worker executable, as it would rely on the `node_modules/` folder in the
# execroot that can be shared in non-sandbox environments or for persistent workers.
# https://docs.bazel.build/versions/main/command-line-reference.html#flag--worker_sandboxing.
templated_args = ["--nobazel_run_linker"],
visibility = ["//visibility:public"],
)
nodejs_binary(
name = "xi18n",
data = [
":ngc_lib",
],
entry_point = ":extract_i18n.ts",
# Follows the same reasoning as for the actual `ngc-wrapped` target.
templated_args = ["--nobazel_run_linker"],
visibility = ["//visibility:public"],
)
filegroup(
name = "package_assets",
srcs = ["BUILD.bazel"],
visibility = ["//packages/bazel:__subpackages__"],
)
# END-DEV-ONLY
| {
"end_byte": 1737,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ngc-wrapped/BUILD.bazel"
} |
angular/packages/bazel/src/ngc-wrapped/index.ts_0_4834 | /**
* @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
*/
// `tsc-wrapped` helpers are not exposed in the primary `@bazel/concatjs` entry-point.
import * as ng from '@angular/compiler-cli';
import {PerfPhase} from '@angular/compiler-cli/private/bazel';
import tscw from '@bazel/concatjs/internal/tsc_wrapped/index.js';
import * as fs from 'fs';
import * as path from 'path';
import ts from 'typescript';
import {EXT, patchNgHostWithFileNameToModuleName as patchNgHost, relativeToRootDirs} from './utils';
// Add devmode for blaze internal
interface BazelOptions extends tscw.BazelOptions {
allowedInputs?: string[];
unusedInputsListPath?: string;
}
// FIXME: we should be able to add the assets to the tsconfig so FileLoader
// knows about them
const NGC_ASSETS = /\.(css|html)$/;
const BAZEL_BIN = /\b(blaze|bazel)-out\b.*?\bbin\b/;
// Note: We compile the content of node_modules with plain ngc command line.
const ALL_DEPS_COMPILED_WITH_BAZEL = false;
export async function main(args: string[]) {
if (tscw.runAsWorker(args)) {
await tscw.runWorkerLoop(runOneBuild);
} else {
return (await runOneBuild(args)) ? 0 : 1;
}
return 0;
}
/** The one FileCache instance used in this process. */
const fileCache = new tscw.FileCache<ts.SourceFile>(tscw.debug);
export async function runOneBuild(
args: string[],
inputs?: {[path: string]: string},
): Promise<boolean> {
if (args[0] === '-p') {
args.shift();
}
// Strip leading at-signs, used to indicate a params file
const project = args[0].replace(/^@+/, '');
const [parsedOptions, errors] = tscw.parseTsconfig(project);
if (errors?.length) {
console.error(ng.formatDiagnostics(errors));
return false;
}
if (parsedOptions === null) {
console.error('Could not parse tsconfig. No parse diagnostics provided.');
return false;
}
const {bazelOpts, options: tsOptions, files, config} = parsedOptions;
const {errors: userErrors, options: userOptions} = ng.readConfiguration(project);
if (userErrors?.length) {
console.error(ng.formatDiagnostics(userErrors));
return false;
}
const allowedNgCompilerOptionsOverrides = new Set<string>([
'diagnostics',
'trace',
'disableExpressionLowering',
'disableTypeScriptVersionCheck',
'i18nOutLocale',
'i18nOutFormat',
'i18nOutFile',
'i18nInLocale',
'i18nInFile',
'i18nInFormat',
'i18nUseExternalIds',
'i18nInMissingTranslations',
'preserveWhitespaces',
'createExternalSymbolFactoryReexports',
'extendedDiagnostics',
'forbidOrphanComponents',
'onlyExplicitDeferDependencyImports',
'generateExtraImportsInLocalMode',
'_enableLetSyntax',
'_enableHmr',
]);
const userOverrides = Object.entries(userOptions)
.filter(([key]) => allowedNgCompilerOptionsOverrides.has(key))
.reduce(
(obj, [key, value]) => {
obj[key] = value;
return obj;
},
{} as Record<string, unknown>,
);
// Angular Compiler options are always set under Bazel. See `ng_module.bzl`.
const angularConfigRawOptions = (config as {angularCompilerOptions: ng.AngularCompilerOptions})[
'angularCompilerOptions'
];
const compilerOpts: ng.AngularCompilerOptions = {
...userOverrides,
...angularConfigRawOptions,
...tsOptions,
};
// These are options passed through from the `ng_module` rule which aren't supported
// by the `@angular/compiler-cli` and are only intended for `ngc-wrapped`.
const {expectedOut, _useManifestPathsAsModuleName} = angularConfigRawOptions;
const tsHost = ts.createCompilerHost(compilerOpts, true);
const {diagnostics} = compile({
allDepsCompiledWithBazel: ALL_DEPS_COMPILED_WITH_BAZEL,
useManifestPathsAsModuleName: _useManifestPathsAsModuleName,
expectedOuts: expectedOut,
compilerOpts,
tsHost,
bazelOpts,
files,
inputs,
});
if (diagnostics.length) {
console.error(ng.formatDiagnostics(diagnostics));
}
return diagnostics.every((d) => d.category !== ts.DiagnosticCategory.Error);
}
export function compile({
allDepsCompiledWithBazel = true,
useManifestPathsAsModuleName,
compilerOpts,
tsHost,
bazelOpts,
files,
inputs,
expectedOuts,
gatherDiagnostics,
bazelHost,
}: {
allDepsCompiledWithBazel?: boolean;
useManifestPathsAsModuleName?: boolean;
compilerOpts: ng.CompilerOptions;
tsHost: ts.CompilerHost;
inputs?: {[path: string]: string};
bazelOpts: BazelOptions;
files: string[];
expectedOuts: string[];
gatherDiagnostics?: (program: ng.Program) => readonly ts.Diagnostic[];
bazelHost?: tscw.CompilerHost;
}): {diagnostics: readonly ts.Diagnostic[]; program: ng.Program | undefined} | {
"end_byte": 4834,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ngc-wrapped/index.ts"
} |
angular/packages/bazel/src/ngc-wrapped/index.ts_4835_12873 | {
let fileLoader: tscw.FileLoader;
// These options are expected to be set in Bazel. See:
// https://github.com/bazelbuild/rules_nodejs/blob/591e76edc9ee0a71d604c5999af8bad7909ef2d4/packages/concatjs/internal/common/tsconfig.bzl#L246.
const baseUrl = compilerOpts.baseUrl!;
const rootDir = compilerOpts.rootDir!;
const rootDirs = compilerOpts.rootDirs!;
if (bazelOpts.maxCacheSizeMb !== undefined) {
const maxCacheSizeBytes = bazelOpts.maxCacheSizeMb * (1 << 20);
fileCache.setMaxCacheSize(maxCacheSizeBytes);
} else {
fileCache.resetMaxCacheSize();
}
if (inputs) {
fileLoader = new tscw.CachedFileLoader(fileCache);
// Resolve the inputs to absolute paths to match TypeScript internals
const resolvedInputs = new Map<string, string>();
const inputKeys = Object.keys(inputs);
for (let i = 0; i < inputKeys.length; i++) {
const key = inputKeys[i];
resolvedInputs.set(tscw.resolveNormalizedPath(key), inputs[key]);
}
fileCache.updateCache(resolvedInputs);
} else {
fileLoader = new tscw.UncachedFileLoader();
}
// Detect from compilerOpts whether the entrypoint is being invoked in Ivy mode.
if (!compilerOpts.rootDirs) {
throw new Error('rootDirs is not set!');
}
const bazelBin = compilerOpts.rootDirs.find((rootDir) => BAZEL_BIN.test(rootDir));
if (!bazelBin) {
throw new Error(`Couldn't find bazel bin in the rootDirs: ${compilerOpts.rootDirs}`);
}
const expectedOutsSet = new Set(expectedOuts.map((p) => convertToForwardSlashPath(p)));
const originalWriteFile = tsHost.writeFile.bind(tsHost);
tsHost.writeFile = (
fileName: string,
content: string,
writeByteOrderMark: boolean,
onError?: (message: string) => void,
sourceFiles?: readonly ts.SourceFile[],
) => {
const relative = relativeToRootDirs(convertToForwardSlashPath(fileName), [rootDir]);
if (expectedOutsSet.has(relative)) {
expectedOutsSet.delete(relative);
originalWriteFile(fileName, content, writeByteOrderMark, onError, sourceFiles);
}
};
if (!bazelHost) {
bazelHost = new tscw.CompilerHost(files, compilerOpts, bazelOpts, tsHost, fileLoader);
}
const delegate = bazelHost.shouldSkipTsickleProcessing.bind(bazelHost);
bazelHost.shouldSkipTsickleProcessing = (fileName: string) => {
// The base implementation of shouldSkipTsickleProcessing checks whether `fileName` is part of
// the original `srcs[]`. For Angular (Ivy) compilations, ngfactory/ngsummary files that are
// shims for original .ts files in the program should be treated identically. Thus, strip the
// '.ngfactory' or '.ngsummary' part of the filename away before calling the delegate.
return delegate(fileName.replace(/\.(ngfactory|ngsummary)\.ts$/, '.ts'));
};
// Never run the tsickle decorator transform.
// TODO(b/254054103): Remove the transform and this flag.
bazelHost.transformDecorators = false;
// By default in the `prodmode` output, we do not add annotations for closure compiler.
// Though, if we are building inside `google3`, closure annotations are desired for
// prodmode output, so we enable it by default. The defaults can be overridden by
// setting the `annotateForClosureCompiler` compiler option in the user tsconfig.
if (!bazelOpts.es5Mode && !bazelOpts.devmode) {
if (bazelOpts.workspaceName === 'google3') {
compilerOpts.annotateForClosureCompiler = true;
} else {
compilerOpts.annotateForClosureCompiler = false;
}
}
// The `annotateForClosureCompiler` Angular compiler option is not respected by default
// as ngc-wrapped handles tsickle emit on its own. This means that we need to update
// the tsickle compiler host based on the `annotateForClosureCompiler` flag.
if (compilerOpts.annotateForClosureCompiler) {
bazelHost.transformTypesToClosure = true;
}
// Patch fileExists when resolving modules, so that CompilerHost can ask TypeScript to
// resolve non-existing generated files that don't exist on disk, but are
// synthetic and added to the `programWithStubs` based on real inputs.
const origBazelHostFileExist = bazelHost.fileExists;
bazelHost.fileExists = (fileName: string) => {
if (NGC_ASSETS.test(fileName)) {
return tsHost.fileExists(fileName);
}
return origBazelHostFileExist.call(bazelHost, fileName);
};
const origBazelHostShouldNameModule = bazelHost.shouldNameModule.bind(bazelHost);
bazelHost.shouldNameModule = (fileName: string) => {
const flatModuleOutPath = path.posix.join(
bazelOpts.package,
compilerOpts.flatModuleOutFile + '.ts',
);
// The bundle index file is synthesized in bundle_index_host so it's not in the
// compilationTargetSrc.
// However we still want to give it an AMD module name for devmode.
// We can't easily tell which file is the synthetic one, so we build up the path we expect
// it to have and compare against that.
if (fileName === path.posix.join(baseUrl, flatModuleOutPath)) return true;
// Also handle the case the target is in an external repository.
// Pull the workspace name from the target which is formatted as `@wksp//package:target`
// if it the target is from an external workspace. If the target is from the local
// workspace then it will be formatted as `//package:target`.
const targetWorkspace = bazelOpts.target.split('/')[0].replace(/^@/, '');
if (
targetWorkspace &&
fileName === path.posix.join(baseUrl, 'external', targetWorkspace, flatModuleOutPath)
)
return true;
return origBazelHostShouldNameModule(fileName);
};
const ngHost = ng.createCompilerHost({options: compilerOpts, tsHost: bazelHost});
patchNgHost(
ngHost,
compilerOpts,
rootDirs,
bazelOpts.workspaceName,
bazelOpts.compilationTargetSrc,
!!useManifestPathsAsModuleName,
);
ngHost.toSummaryFileName = (fileName: string, referringSrcFileName: string) =>
path.posix.join(
bazelOpts.workspaceName,
relativeToRootDirs(fileName, rootDirs).replace(EXT, ''),
);
if (allDepsCompiledWithBazel) {
// Note: The default implementation would work as well,
// but we can be faster as we know how `toSummaryFileName` works.
// Note: We can't do this if some deps have been compiled with the command line,
// as that has a different implementation of fromSummaryFileName / toSummaryFileName
ngHost.fromSummaryFileName = (fileName: string, referringLibFileName: string) => {
const workspaceRelative = fileName.split('/').splice(1).join('/');
return tscw.resolveNormalizedPath(bazelBin, workspaceRelative) + '.d.ts';
};
}
// Patch a property on the ngHost that allows the resourceNameToModuleName function to
// report better errors.
(ngHost as any).reportMissingResource = (resourceName: string) => {
console.error(`\nAsset not found:\n ${resourceName}`);
console.error("Check that it's included in the `assets` attribute of the `ng_module` rule.\n");
};
const emitCallback: ng.TsEmitCallback<ts.EmitResult> = ({
program,
targetSourceFile,
writeFile,
cancellationToken,
emitOnlyDtsFiles,
customTransformers = {},
}) =>
program.emit(
targetSourceFile,
writeFile,
cancellationToken,
emitOnlyDtsFiles,
customTransformers,
);
if (!gatherDiagnostics) {
gatherDiagnostics = (program) =>
gatherDiagnosticsForInputsOnly(compilerOpts, bazelOpts, program);
}
const {diagnostics, emitResult, program} = ng.performCompilation({
rootNames: files,
options: compilerOpts,
host: ngHost,
emitCallback,
gatherDiagnostics,
});
let externs = '/** @externs */\n';
const hasError = diagnostics.some((diag) => diag.category === ts.DiagnosticCategory.Error);
if (!hasError) {
if (bazelOpts.manifest) {
fs.writeFileSync(bazelOpts.manifest, '// Empty. Should not be used.');
}
}
// If compilation fails unexpectedly, performCompilation returns no program. | {
"end_byte": 12873,
"start_byte": 4835,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ngc-wrapped/index.ts"
} |
angular/packages/bazel/src/ngc-wrapped/index.ts_12876_17973 | // Make sure not to crash but report the diagnostics.
if (!program) return {program, diagnostics};
if (bazelOpts.tsickleExternsPath) {
// Note: when tsickleExternsPath is provided, we always write a file as a
// marker that compilation succeeded, even if it's empty (just containing an
// @externs).
fs.writeFileSync(bazelOpts.tsickleExternsPath, externs);
}
// There might be some expected output files that are not written by the
// compiler. In this case, just write an empty file.
for (const fileName of expectedOutsSet) {
originalWriteFile(fileName, '', false);
}
if (!compilerOpts.noEmit) {
maybeWriteUnusedInputsList(program.getTsProgram(), rootDir, bazelOpts);
}
return {program, diagnostics};
}
/**
* Writes a collection of unused input files and directories which can be
* consumed by bazel to avoid triggering rebuilds if only unused inputs are
* changed.
*
* See https://bazel.build/contribute/codebase#input-discovery
*/
export function maybeWriteUnusedInputsList(
program: ts.Program,
rootDir: string,
bazelOpts: BazelOptions,
) {
if (!bazelOpts?.unusedInputsListPath) {
return;
}
if (bazelOpts.allowedInputs === undefined) {
throw new Error('`unusedInputsListPath` is set, but no list of allowed inputs provided.');
}
// ts.Program's getSourceFiles() gets populated by the sources actually
// loaded while the program is being built.
const usedFiles = new Set();
for (const sourceFile of program.getSourceFiles()) {
// Only concern ourselves with typescript files.
usedFiles.add(sourceFile.fileName);
}
// allowedInputs are absolute paths to files which may also end with /* which
// implies any files in that directory can be used.
const unusedInputs: string[] = [];
for (const f of bazelOpts.allowedInputs) {
// A ts/x file is unused if it was not found directly in the used sources.
if ((f.endsWith('.ts') || f.endsWith('.tsx')) && !usedFiles.has(f)) {
unusedInputs.push(f);
continue;
}
// TODO: Iterate over contents of allowed directories checking for used files.
}
// Bazel expects the unused input list to contain paths relative to the
// execroot directory.
// See https://docs.bazel.build/versions/main/output_directories.html
fs.writeFileSync(
bazelOpts.unusedInputsListPath,
unusedInputs.map((f) => path.relative(rootDir, f)).join('\n'),
);
}
function isCompilationTarget(bazelOpts: BazelOptions, sf: ts.SourceFile): boolean {
return bazelOpts.compilationTargetSrc.indexOf(sf.fileName) !== -1;
}
function convertToForwardSlashPath(filePath: string): string {
return filePath.replace(/\\/g, '/');
}
function gatherDiagnosticsForInputsOnly(
options: ng.CompilerOptions,
bazelOpts: BazelOptions,
ngProgram: ng.Program,
): ts.Diagnostic[] {
const tsProgram = ngProgram.getTsProgram();
// For the Ivy compiler, track the amount of time spent fetching TypeScript diagnostics.
let previousPhase = PerfPhase.Unaccounted;
if (ngProgram instanceof ng.NgtscProgram) {
previousPhase = ngProgram.compiler.perfRecorder.phase(PerfPhase.TypeScriptDiagnostics);
}
const diagnostics: ts.Diagnostic[] = [];
// These checks mirror ts.getPreEmitDiagnostics, with the important
// exception of avoiding b/30708240, which is that if you call
// program.getDeclarationDiagnostics() it somehow corrupts the emit.
diagnostics.push(...tsProgram.getOptionsDiagnostics());
diagnostics.push(...tsProgram.getGlobalDiagnostics());
const programFiles = tsProgram.getSourceFiles().filter((f) => isCompilationTarget(bazelOpts, f));
for (let i = 0; i < programFiles.length; i++) {
const sf = programFiles[i];
// Note: We only get the diagnostics for individual files
// to e.g. not check libraries.
diagnostics.push(...tsProgram.getSyntacticDiagnostics(sf));
// In local mode compilation the TS semantic check issues tons of diagnostics due to the fact
// that the file dependencies (.d.ts files) are not available in the program. So it needs to be
// disabled.
if (options.compilationMode !== 'experimental-local') {
diagnostics.push(...tsProgram.getSemanticDiagnostics(sf));
}
}
if (ngProgram instanceof ng.NgtscProgram) {
ngProgram.compiler.perfRecorder.phase(previousPhase);
}
if (!diagnostics.length) {
// only gather the angular diagnostics if we have no diagnostics
// in any other files.
diagnostics.push(...ngProgram.getNgStructuralDiagnostics());
diagnostics.push(...ngProgram.getNgSemanticDiagnostics());
}
return diagnostics;
}
/**
* @deprecated
* Kept here just for compatibility with 1P tools. To be removed soon after 1P update.
*/
export function patchNgHostWithFileNameToModuleName(
ngHost: ng.CompilerHost,
compilerOpts: ng.CompilerOptions,
bazelOpts: BazelOptions,
rootDirs: string[],
useManifestPathsAsModuleName: boolean,
): void {
patchNgHost(
ngHost,
compilerOpts,
rootDirs,
bazelOpts.workspaceName,
bazelOpts.compilationTargetSrc,
useManifestPathsAsModuleName,
);
} | {
"end_byte": 17973,
"start_byte": 12876,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ngc-wrapped/index.ts"
} |
angular/packages/bazel/src/ng_module/ng_module.bzl_0_5988 | # 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
"""Run Angular's AOT template compiler
"""
load("//packages/bazel/src/ng_module:partial_compilation.bzl", "NgPartialCompilationInfo")
load(
"//packages/bazel/src:external.bzl",
"COMMON_ATTRIBUTES",
"COMMON_OUTPUTS",
"DEFAULT_NG_COMPILER",
"DEFAULT_NG_XI18N",
"DEPS_ASPECTS",
"LinkablePackageInfo",
"NpmPackageInfo",
"TsConfigInfo",
"compile_ts",
"js_ecma_script_module_info",
"js_module_info",
"node_modules_aspect",
"ts_providers_dict_to_struct",
"tsc_wrapped_tsconfig",
)
# enable_perf_logging controls whether Ivy's performance tracing system will be enabled for any
# compilation which includes this provider.
NgPerfInfo = provider(fields = ["enable_perf_logging"])
def is_perf_requested(ctx):
return ctx.attr.perf_flag != None and ctx.attr.perf_flag[NgPerfInfo].enable_perf_logging == True
def _is_partial_compilation_enabled(ctx):
"""Whether partial compilation is enabled for this target."""
return ctx.attr._partial_compilation_flag[NgPartialCompilationInfo].enabled
def _get_ivy_compilation_mode(ctx):
"""Gets the Ivy compilation mode based on the current build settings."""
return "partial" if _is_partial_compilation_enabled(ctx) else "full"
# Return true if run with bazel (the open-sourced version of blaze), false if
# run with blaze.
def _is_bazel():
return not hasattr(native, "genmpm") # this_is_bazel
def _flat_module_out_file(ctx):
"""Provide a default for the flat_module_out_file attribute.
We cannot use the default="" parameter of ctx.attr because the value is calculated
from other attributes (name)
Args:
ctx: starlark rule execution context
Returns:
a basename used for the flat module out (no extension)
"""
if getattr(ctx.attr, "flat_module_out_file", False):
return ctx.attr.flat_module_out_file
return "%s_public_index" % ctx.label.name
def _should_produce_flat_module_outs(ctx):
"""Should we produce flat module outputs.
We only produce flat module outs when we expect the ng_module is meant to be published,
based on the presence of the module_name attribute.
Args:
ctx: starlark rule execution context
Returns:
true iff we should run the bundle_index_host to produce flat module metadata and bundle index
"""
return _is_bazel() and ctx.attr.module_name
# Calculate the expected output of the template compiler for every source in
# in the library. Most of these will be produced as empty files but it is
# unknown, without parsing, which will be empty.
def _expected_outs(ctx):
devmode_js_files = []
closure_js_files = []
declaration_files = []
transpilation_infos = []
flat_module_out_prodmode_file = None
for src in ctx.files.srcs + ctx.files.assets:
package_prefix = ctx.label.package + "/" if ctx.label.package else ""
# Strip external repository name from path if src is from external repository
# If src is from external repository, it's short_path will be ../<external_repo_name>/...
short_path = src.short_path if src.short_path[0:2] != ".." else "/".join(src.short_path.split("/")[2:])
if short_path.endswith(".ts") and not short_path.endswith(".d.ts"):
basename = short_path[len(package_prefix):-len(".ts")]
devmode_js = [".js"]
else:
continue
declarations = [f.replace(".js", ".d.ts") for f in devmode_js]
for devmode_ext in devmode_js:
devmode_js_file = ctx.actions.declare_file(basename + devmode_ext)
devmode_js_files.append(devmode_js_file)
closure_ext = devmode_ext.replace(".js", ".mjs")
closure_js_file = ctx.actions.declare_file(basename + closure_ext)
closure_js_files.append(closure_js_file)
transpilation_infos.append(struct(closure = closure_js_file, devmode = devmode_js_file))
declaration_files += [ctx.actions.declare_file(basename + ext) for ext in declarations]
# We do this just when producing a flat module index for a publishable ng_module
if _should_produce_flat_module_outs(ctx):
flat_module_out_name = _flat_module_out_file(ctx)
# Note: We keep track of the prodmode flat module output for `ng_packager` which
# uses it as entry-point for producing FESM bundles.
# TODO: Remove flat module from `ng_module` and detect package entry-point reliably
# in Ivy. Related discussion: https://github.com/angular/angular/pull/36971#issuecomment-625282383.
flat_module_out_prodmode_file = ctx.actions.declare_file("%s.mjs" % flat_module_out_name)
closure_js_files.append(flat_module_out_prodmode_file)
devmode_js_files.append(ctx.actions.declare_file("%s.js" % flat_module_out_name))
bundle_index_typings = ctx.actions.declare_file("%s.d.ts" % flat_module_out_name)
declaration_files.append(bundle_index_typings)
else:
bundle_index_typings = None
dev_perf_files = []
prod_perf_files = []
# In Ivy mode, dev and prod builds both produce a .json output containing performance metrics
# from the compiler for that build.
if is_perf_requested(ctx):
dev_perf_files = [ctx.actions.declare_file(ctx.label.name + "_perf_dev.json")]
prod_perf_files = [ctx.actions.declare_file(ctx.label.name + "_perf_prod.json")]
return struct(
closure_js = closure_js_files,
devmode_js = devmode_js_files,
declarations = declaration_files,
transpilation_infos = transpilation_infos,
bundle_index_typings = bundle_index_typings,
dev_perf_files = dev_perf_files,
prod_perf_files = prod_perf_files,
flat_module_out_prodmode_file = flat_module_out_prodmode_file,
) | {
"end_byte": 5988,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_module/ng_module.bzl"
} |
angular/packages/bazel/src/ng_module/ng_module.bzl_5990_14483 | def _ngc_tsconfig(ctx, files, srcs, **kwargs):
compilation_mode = _get_ivy_compilation_mode(ctx)
is_devmode = "devmode_manifest" in kwargs
outs = _expected_outs(ctx)
if is_devmode:
expected_outs = outs.devmode_js
else:
expected_outs = outs.closure_js + outs.declarations
if not ctx.attr.type_check and ctx.attr.strict_templates:
fail("Cannot set type_check = False and strict_templates = True for ng_module()")
angular_compiler_options = {
"enableResourceInlining": ctx.attr.inline_resources,
"generateCodeForLibraries": False,
"allowEmptyCodegenFiles": True,
"fullTemplateTypeCheck": ctx.attr.type_check,
"strictTemplates": ctx.attr.strict_templates,
"compilationMode": compilation_mode,
# In Google3 we still want to use the symbol factory re-exports in order to
# not break existing apps inside Google. Unlike Bazel, Google3 does not only
# enforce strict dependencies of source files, but also for generated files
# (such as the factory files). Therefore in order to avoid that generated files
# introduce new module dependencies (which aren't explicitly declared), we need
# to enable external symbol re-exports by default when running with Blaze.
"createExternalSymbolFactoryReexports": (not _is_bazel()),
# FIXME: wrong place to de-dupe
"expectedOut": depset([o.path for o in expected_outs]).to_list(),
# We instruct the compiler to use the host for import generation in Blaze. By default,
# module names between source files of the same compilation unit are relative paths. This
# is not desired in google3 where the generated module names are used as qualified names
# for aliased exports. We disable relative paths and always use manifest paths in google3.
"_useHostForImportGeneration": (not _is_bazel()),
"_useManifestPathsAsModuleName": (not _is_bazel()),
}
if is_perf_requested(ctx):
# In Ivy mode, set the `tracePerformance` Angular compiler option to enable performance
# metric output.
if is_devmode:
perf_path = outs.dev_perf_files[0].path
else:
perf_path = outs.prod_perf_files[0].path
angular_compiler_options["tracePerformance"] = perf_path
if _should_produce_flat_module_outs(ctx):
angular_compiler_options["flatModuleId"] = ctx.attr.module_name
angular_compiler_options["flatModuleOutFile"] = _flat_module_out_file(ctx)
angular_compiler_options["flatModulePrivateSymbolPrefix"] = "_".join(
[ctx.workspace_name] + ctx.label.package.split("/") + [ctx.label.name, ""],
)
tsconfig = dict(tsc_wrapped_tsconfig(ctx, files, srcs, **kwargs), **{
"angularCompilerOptions": angular_compiler_options,
})
# For prodmode, the compilation target is set to `ES2022`. `@bazel/typecript`
# using the `create_tsconfig` function sets `ES2015` by default for prodmode
# and uses ES5 with UMD for devmode. We want to consistenly use ES2022 ESM.
# https://github.com/bazelbuild/rules_nodejs/blob/901df3868e3ceda177d3ed181205e8456a5592ea/third_party/github.com/bazelbuild/rules_typescript/internal/common/tsconfig.bzl#L195
# TODO(devversion): In the future, combine prodmode and devmode so we can get rid of the
# ambiguous terminology and concept that can result in slow-down for development workflows.
tsconfig["compilerOptions"]["target"] = "es2022"
tsconfig["compilerOptions"]["module"] = "esnext"
return tsconfig
# Extra options passed to Node when running ngc.
_EXTRA_NODE_OPTIONS_FLAGS = [
# Expose the v8 garbage collection API to JS.
"--node_options=--expose-gc",
# Show ~full stack traces, instead of cutting off after 10 items.
"--node_options=--stack-trace-limit=100",
# Give 4 GB RAM to node to allow bigger google3 modules to compile.
"--node_options=--max-old-space-size=4096",
]
def ngc_compile_action(
ctx,
label,
inputs,
outputs,
tsconfig_file,
node_opts,
locale = None,
i18n_args = [],
target_flavor = "prodmode"):
"""Helper function to create the ngc action.
This is exposed for google3 to wire up i18n replay rules, and is not intended
as part of the public API.
Args:
ctx: starlark context
label: the label of the ng_module being compiled
inputs: passed to the ngc action's inputs
outputs: passed to the ngc action's outputs
tsconfig_file: tsconfig file with settings used for the compilation
node_opts: list of strings, extra nodejs options.
locale: i18n locale, or None
i18n_args: additional command-line arguments to ngc
target_flavor: Whether prodmode or devmode output is being built.
Returns:
the parameters of the compilation which will be used to replay the ngc action for i18N.
"""
ngc_compilation_mode = "%s %s" % (_get_ivy_compilation_mode(ctx), target_flavor)
mnemonic = "AngularTemplateCompile"
progress_message = "Compiling Angular templates (%s) %s" % (
ngc_compilation_mode,
label,
)
if locale:
mnemonic = "AngularI18NMerging"
supports_workers = "0"
progress_message = ("Recompiling Angular templates (ngc - %s) %s for locale %s" %
(target_flavor, label, locale))
else:
supports_workers = str(int(ctx.attr._supports_workers))
arguments = (list(_EXTRA_NODE_OPTIONS_FLAGS) +
["--node_options=%s" % opt for opt in node_opts])
# One at-sign makes this a params-file, enabling the worker strategy.
# Two at-signs escapes the argument so it's passed through to ngc
# rather than the contents getting expanded.
if supports_workers == "1":
arguments.append("@@" + tsconfig_file.path)
else:
arguments += ["-p", tsconfig_file.path]
arguments += i18n_args
ctx.actions.run(
progress_message = progress_message,
mnemonic = mnemonic,
inputs = inputs,
outputs = outputs,
arguments = arguments,
executable = ctx.executable.compiler,
execution_requirements = {
"supports-workers": supports_workers,
},
)
if not locale and not ctx.attr.no_i18n:
return struct(
label = label,
tsconfig = tsconfig_file,
inputs = inputs,
outputs = outputs,
compiler = ctx.executable.compiler,
)
return None
def _filter_ts_inputs(all_inputs):
# The compiler only needs to see TypeScript sources from the npm dependencies,
# but may need to look at package.json files as well.
return [
f
for f in all_inputs
if f.path.endswith(".js") or f.path.endswith(".ts") or f.path.endswith(".json")
]
def _compile_action(
ctx,
inputs,
outputs,
tsconfig_file,
node_opts,
target_flavor):
# Give the Angular compiler all the user-listed assets
file_inputs = list(ctx.files.assets)
if (type(inputs) == type([])):
file_inputs.extend(inputs)
else:
# inputs ought to be a list, but allow depset as well
# so that this can change independently of rules_typescript
# TODO(alexeagle): remove this case after update (July 2019)
file_inputs.extend(inputs.to_list())
if hasattr(ctx.attr, "node_modules"):
file_inputs.extend(_filter_ts_inputs(ctx.files.node_modules))
# If the user supplies a tsconfig.json file, the Angular compiler needs to read it
if hasattr(ctx.attr, "tsconfig") and ctx.file.tsconfig:
file_inputs.append(ctx.file.tsconfig)
if TsConfigInfo in ctx.attr.tsconfig:
file_inputs += ctx.attr.tsconfig[TsConfigInfo].deps
# Also include files from npm fine grained deps as action_inputs.
# These deps are identified by the NpmPackageInfo provider.
for d in ctx.attr.deps:
if NpmPackageInfo in d:
# Note: we can't avoid calling .to_list() on sources
file_inputs.extend(_filter_ts_inputs(d[NpmPackageInfo].sources.to_list()))
# Collect the inputs and summary files from our deps
action_inputs = depset(file_inputs)
return ngc_compile_action(ctx, ctx.label, action_inputs, outputs, tsconfig_file, node_opts, None, [], target_flavor) | {
"end_byte": 14483,
"start_byte": 5990,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_module/ng_module.bzl"
} |
angular/packages/bazel/src/ng_module/ng_module.bzl_14485_21114 | def _prodmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts):
outs = _expected_outs(ctx)
return _compile_action(ctx, inputs, outputs + outs.closure_js + outs.prod_perf_files + outs.declarations, tsconfig_file, node_opts, "prodmode")
def _devmode_compile_action(ctx, inputs, outputs, tsconfig_file, node_opts):
outs = _expected_outs(ctx)
compile_action_outputs = outputs + outs.devmode_js + outs.dev_perf_files
_compile_action(ctx, inputs, compile_action_outputs, tsconfig_file, node_opts, "devmode")
# Note: We need to define `label` and `srcs_files` as `tsc_wrapped` passes
# them and Starlark would otherwise error at runtime.
# buildifier: disable=unused-variable
def _ts_expected_outs(ctx, label, srcs_files = []):
return _expected_outs(ctx)
def ng_module_impl(ctx, ts_compile_actions):
"""Implementation function for the ng_module rule.
This is exposed so that google3 can have its own entry point that re-uses this
and is not meant as a public API.
Args:
ctx: the starlark rule context
ts_compile_actions: generates all the actions to run an ngc compilation
Returns:
the result of the ng_module rule as a dict, suitable for
conversion by ts_providers_dict_to_struct
"""
providers = ts_compile_actions(
ctx,
is_library = True,
compile_action = _prodmode_compile_action,
devmode_compile_action = _devmode_compile_action,
tsc_wrapped_tsconfig = _ngc_tsconfig,
outputs = _ts_expected_outs,
)
outs = _expected_outs(ctx)
providers["angular"] = {}
if _should_produce_flat_module_outs(ctx):
providers["angular"]["flat_module_metadata"] = struct(
module_name = ctx.attr.module_name,
typings_file = outs.bundle_index_typings,
flat_module_out_prodmode_file = outs.flat_module_out_prodmode_file,
)
return providers
def _ng_module_impl(ctx):
ts_providers = ng_module_impl(ctx, compile_ts)
# Add in new JS providers
# See design doc https://docs.google.com/document/d/1ggkY5RqUkVL4aQLYm7esRW978LgX3GUCnQirrk5E1C0/edit#
# and issue https://github.com/bazelbuild/rules_nodejs/issues/57 for more details.
ts_providers["providers"].extend([
js_module_info(
sources = ts_providers["typescript"]["es6_sources"],
deps = ctx.attr.deps,
),
js_ecma_script_module_info(
sources = ts_providers["typescript"]["es6_sources"],
deps = ctx.attr.deps,
),
# TODO: Add remaining shared JS providers from design doc
# (JSModuleInfo) and remove legacy "typescript" provider
# once it is no longer needed.
])
if ctx.attr.package_name:
path = "/".join([p for p in [ctx.bin_dir.path, ctx.label.workspace_root, ctx.label.package] if p])
ts_providers["providers"].append(LinkablePackageInfo(
package_name = ctx.attr.package_name,
package_path = ctx.attr.package_path,
path = path,
files = ts_providers["typescript"]["es6_sources"],
))
return ts_providers_dict_to_struct(ts_providers)
NG_MODULE_ATTRIBUTES = {
"srcs": attr.label_list(allow_files = [".ts"]),
"deps": attr.label_list(
doc = "Targets that are imported by this target",
aspects = [node_modules_aspect] + DEPS_ASPECTS,
),
"assets": attr.label_list(
doc = ".html and .css files needed by the Angular compiler",
allow_files = [
".css",
# TODO(alexeagle): change this to ".ng.html" when usages updated
".html",
],
),
"factories": attr.label_list(
allow_files = [".ts", ".html"],
mandatory = False,
),
"type_check": attr.bool(default = True),
"strict_templates": attr.bool(default = False),
"inline_resources": attr.bool(default = True),
"no_i18n": attr.bool(default = False),
"compiler": attr.label(
doc = """Sets a different ngc compiler binary to use for this library.
The default ngc compiler depends on the `//@angular/bazel`
target which is setup for projects that use bazel managed npm deps that
fetch the @angular/bazel npm package.
""",
default = Label(DEFAULT_NG_COMPILER),
executable = True,
cfg = "exec",
),
"ng_xi18n": attr.label(
default = Label(DEFAULT_NG_XI18N),
executable = True,
cfg = "exec",
),
"_partial_compilation_flag": attr.label(
default = "//packages/bazel/src:partial_compilation",
providers = [NgPartialCompilationInfo],
doc = "Internal attribute which points to the partial compilation build setting.",
),
# In the angular/angular monorepo, //tools:defaults.bzl wraps the ng_module rule in a macro
# which sets this attribute to the //packages/compiler-cli:ng_perf flag.
# This is done to avoid exposing the flag to user projects, which would require:
# * defining the flag within @angular/bazel and referencing it correctly here, and
# * committing to the flag and its semantics (including the format of perf JSON files)
# as something users can depend upon.
"perf_flag": attr.label(
providers = [NgPerfInfo],
doc = "Private API to control production of performance metric JSON files",
),
"_supports_workers": attr.bool(default = True),
# Matches the API of the `ts_library` rule from `@bazel/concatjs`.
# https://github.com/bazelbuild/rules_nodejs/blob/398d351a3f2a9b2ebf6fc31fb5882cce7eedfd7b/packages/typescript/internal/build_defs.bzl#L435-L446.
"package_name": attr.string(
doc = """The package name that the linker will link this `ng_module` output as.
If `package_path` is set, the linker will link this package under `<package_path>/node_modules/<package_name>`.
If `package_path` is not set, the package will be linked in the top-level workspace node_modules folder.""",
),
# Matches the API of the `ts_library` rule from `@bazel/concatjs`.
# https://github.com/bazelbuild/rules_nodejs/blob/398d351a3f2a9b2ebf6fc31fb5882cce7eedfd7b/packages/typescript/internal/build_defs.bzl#L435-L446.
"package_path": attr.string(
doc = """The package path in the workspace that the linker will link this `ng_module` output to.
If `package_path` is set, the linker will link this package under `<package_path>/node_modules/<package_name>`.
If `package_path` is not set, the package will be linked in the top-level workspace node_modules folder.""",
),
} | {
"end_byte": 21114,
"start_byte": 14485,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_module/ng_module.bzl"
} |
angular/packages/bazel/src/ng_module/ng_module.bzl_21116_25031 | NG_MODULE_RULE_ATTRS = dict(dict(COMMON_ATTRIBUTES, **NG_MODULE_ATTRIBUTES), **{
"tsconfig": attr.label(allow_single_file = True),
"node_modules": attr.label(
doc = """The npm packages which should be available during the compile.
The default value of `//typescript:typescript__typings` is
for projects that use bazel managed npm deps. This default is in place
since code compiled by ng_module will always depend on at least the
typescript default libs which are provided by
`//typescript:typescript__typings`.
This attribute is DEPRECATED. As of version 0.18.0 the recommended
approach to npm dependencies is to use fine grained npm dependencies
which are setup with the `yarn_install` or `npm_install` rules.
For example, in targets that used a `//:node_modules` filegroup,
```
ng_module(
name = "my_lib",
...
node_modules = "//:node_modules",
)
```
which specifies all files within the `//:node_modules` filegroup
to be inputs to the `my_lib`. Using fine grained npm dependencies,
`my_lib` is defined with only the npm dependencies that are
needed:
```
ng_module(
name = "my_lib",
...
deps = [
"@npm//@types/foo",
"@npm//@types/bar",
"@npm//foo",
"@npm//bar",
...
],
)
```
In this case, only the listed npm packages and their
transitive deps are includes as inputs to the `my_lib` target
which reduces the time required to setup the runfiles for this
target (see https://github.com/bazelbuild/bazel/issues/5153).
The default typescript libs are also available via the node_modules
default in this case.
The @npm external repository and the fine grained npm package
targets are setup using the `yarn_install` or `npm_install` rule
in your WORKSPACE file:
yarn_install(
name = "npm",
package_json = "//:package.json",
yarn_lock = "//:yarn.lock",
)
""",
default = Label(
# BEGIN-DEV-ONLY
"@npm" +
# END-DEV-ONLY
"//typescript:typescript__typings",
),
),
"entry_point": attr.label(allow_single_file = True),
# Default is %{name}_public_index
# The suffix points to the generated "bundle index" files that users import from
# The default is intended to avoid collisions with the users input files.
# Later packaging rules will point to these generated files as the entry point
# into the package.
# See the flatModuleOutFile documentation in
# https://github.com/angular/angular/blob/main/packages/compiler-cli/src/transformers/api.ts
"flat_module_out_file": attr.string(),
})
ng_module = rule(
implementation = _ng_module_impl,
attrs = NG_MODULE_RULE_ATTRS,
outputs = COMMON_OUTPUTS,
)
"""
Run the Angular AOT template compiler.
This rule extends the [ts_library] rule.
[ts_library]: https://bazelbuild.github.io/rules_nodejs/TypeScript.html#ts_library
"""
def ng_module_macro(tsconfig = None, **kwargs):
"""Wraps `ng_module` to set the default for the `tsconfig` attribute.
This must be a macro so that the string is converted to a label in the context of the
workspace that declares the `ng_module` target, rather than the workspace that defines
`ng_module`, or the workspace where the build is taking place.
This macro is re-exported as `ng_module` in the public API.
Args:
tsconfig: the label pointing to a tsconfig.json file
**kwargs: remaining args to pass to the ng_module rule
"""
if not tsconfig:
tsconfig = "//:tsconfig.json"
ng_module(tsconfig = tsconfig, **kwargs) | {
"end_byte": 25031,
"start_byte": 21116,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_module/ng_module.bzl"
} |
angular/packages/bazel/src/ng_module/BUILD.bazel_0_166 | # BEGIN-DEV-ONLY
package(default_visibility = ["//packages/bazel:__subpackages__"])
filegroup(
name = "package_assets",
srcs = glob(["*"]),
)
# END-DEV-ONLY
| {
"end_byte": 166,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_module/BUILD.bazel"
} |
angular/packages/bazel/src/ng_module/partial_compilation.bzl_0_852 | # 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
NgPartialCompilationInfo = provider(
fields = {"enabled": "Whether partial compilation is enabled."},
)
def _ng_partial_compilation_flag_impl(ctx):
return NgPartialCompilationInfo(enabled = ctx.build_setting_value)
ng_partial_compilation_flag = rule(
implementation = _ng_partial_compilation_flag_impl,
build_setting = config.bool(flag = True),
)
def _partial_compilation_transition_impl(_settings, _attr):
return {"//packages/bazel/src:partial_compilation": True}
partial_compilation_transition = transition(
implementation = _partial_compilation_transition_impl,
inputs = [],
outputs = ["//packages/bazel/src:partial_compilation"],
)
| {
"end_byte": 852,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/bazel/src/ng_module/partial_compilation.bzl"
} |
angular/packages/benchpress/DEVELOPER.md_0_397 | ## Publishing
The `@angular/benchpress` package is not published together with the framework and therefore
the `npm_package` Bazel target does not have the `release-with-framework` tag.
In order to publish this package manually, one can run the following command after bumping
the `version` in the `package.json` of this package:
```
yarn bazel run //packages/benchpress:npm_package.publish
``` | {
"end_byte": 397,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/DEVELOPER.md"
} |
angular/packages/benchpress/README.md_0_8123 | # Benchpress
Benchpress is a framework for e2e performance tests.
See [here for an example project](https://github.com/angular/benchpress-tree).
The sources for this package are in the main [Angular](https://github.com/angular/angular) repo. Please file issues and pull requests against that repo.
License: MIT
# Why?
There are so-called "micro benchmarks" that essentially use a stop watch in the browser to measure time
(e.g. via `performance.now()`). This approach is limited to time, and in some cases memory
(Chrome with special flags), as metric. It does not allow to measure:
- rendering time: e.g. the time the browser spends to layout or paint elements. This can e.g. used to
test the performance impact of stylesheet changes.
- garbage collection: e.g. how long the browser paused script execution, and how much memory was collected.
This can be used to stabilize script execution time, as garbage collection times are usually very
unpredictable. This data can also be used to measure and improve memory usage of applications,
as the garbage collection amount directly affects garbage collection time.
- distinguish script execution time from waiting: e.g. to measure the client side only time that is spent
in a complex user interaction, ignoring backend calls.
- measure fps to assert the smoothness of scrolling and animations.
This kind of data is already available in the DevTools of modern browsers. However, there is no standard way to
use those tools in an automated way to measure web app performance, especially not across platforms.
Benchpress tries to fill this gap, i.e. allow to access all kinds of performance metrics in an automated way.
# How it works
Benchpress uses webdriver to read out the so-called "performance log" of browsers. This contains all kinds of interesting
data, e.g. when a script started/ended executing, gc started/ended, the browser painted something to the screen, ...
As browsers are different, benchpress has plugins to normalizes these events.
# Features
* Provides a loop (so-called "Sampler") that executes the benchmark multiple times
* Automatically waits/detects until the browser is "warm"
* Reporters provide a normalized way to store results:
- console reporter
- file reporter
- Google Big Query reporter (coming soon)
* Supports micro benchmarks as well via `console.time()` / `console.timeEnd()`
- `console.time()` / `console.timeEnd()` mark the timeline in the DevTools, so it makes sense
to use them in micro benchmark to visualize and understand them, with or without benchpress.
- running micro benchmarks in benchpress leverages the already existing reporters,
the sampler and the auto warmup feature of benchpress.
# Supported browsers
* Chrome on all platforms
* Mobile Safari (iOS)
* Firefox (work in progress)
# How to write a benchmark
A benchmark in benchpress is made by an application under test
and a benchmark driver. The application under test is the
actual application consisting of html/css/js that should be tests.
A benchmark driver is a webdriver test that interacts with the
application under test.
## A simple benchmark
Let's assume we want to measure the script execution time, as well as the render time
that it takes to fill a container element with a complex html string.
The application under test could look like this:
```
index.html:
<button id="reset" onclick="reset()">Reset</button>
<button id="fill" onclick="fill()">fill innerHTML</button>
<div id="container"></div>
<script>
var container = document.getElementById('container');
var complexHtmlString = '...'; // TODO
function reset() { container.innerHTML = ''; }
function fill() {
container.innerHTML = complexHtmlString;
}
</script>
```
A benchmark driver could look like this:
```
// A runner contains the shared configuration
// and can be shared across multiple tests.
var runner = new Runner(...);
driver.get('http://myserver/index.html');
var resetBtn = driver.findElement(By.id('reset'));
var fillBtn = driver.findElement(By.id('fill'));
runner.sample({
id: 'fillElement',
// Prepare is optional...
prepare: () {
resetBtn.click();
},
execute: () {
fillBtn.click();
// Note: if fillBtn would use some asynchronous code,
// we would need to wait here for its end.
}
});
```
## Measuring in the browser
If the application under test would like to, it can measure on its own.
E.g.
```
index.html:
<button id="measure" onclick="measure()">Measure document.createElement</button>
<script>
function measure() {
console.time('createElement*10000');
for (var i=0; i<10000; i++) {
document.createElement('div');
}
console.timeEnd('createElement*10000');
}
</script>
```
When the `measure` button is clicked, it marks the timeline and creates 10000 elements.
It uses the special names `createElement*10000` to tell benchpress that the
time that was measured is for 10000 calls to createElement and that benchpress should
take the average for it.
A test driver for this would look like this:
````
driver.get('.../index.html');
var measureBtn = driver.findElement(By.id('measure'));
runner.sample({
id: 'createElement test',
microMetrics: {
'createElement': 'time to create an element (ms)'
},
execute: () {
measureBtn.click();
}
});
````
When looking into the DevTools Timeline, we see a marker as well:

### Custom Metrics Without Using `console.time`
It's also possible to measure any "user metric" within the browser
by setting a numeric value on the `window` object. For example:
```js
bootstrap(App)
.then(() => {
window.timeToBootstrap = Date.now() - performance.timing.navigationStart;
});
```
A test driver for this user metric could be written as follows:
```js
describe('home page load', function() {
it('should log load time for a 2G connection', done => {
runner.sample({
execute: () => {
browser.get(`http://localhost:8080`);
},
userMetrics: {
timeToBootstrap: 'The time in milliseconds to bootstrap'
},
providers: [
{provide: RegressionSlopeValidator.METRIC, useValue: 'timeToBootstrap'}
]
}).then(done);
});
});
```
Using this strategy, benchpress will wait until the specified property name,
`timeToBootstrap` in this case, is defined as a number on the `window` object
inside the application under test.
# Smoothness Metrics
Benchpress can also measure the "smoothness" of scrolling and animations. In order to do that, the following set of metrics can be collected by benchpress:
- `frameTime.mean`: mean frame time in ms (target: 16.6ms for 60fps)
- `frameTime.worst`: worst frame time in ms
- `frameTime.best`: best frame time in ms
- `frameTime.smooth`: percentage of frames that hit 60fps
To collect these metrics, you need to execute `console.time('frameCapture')` and `console.timeEnd('frameCapture')` either in your benchmark application or in you benchmark driver via webdriver. The metrics mentioned above will only be collected between those two calls, and it is recommended to wrap the time/timeEnd calls as closely as possible around the action you want to evaluate to get accurate measurements.
In addition to that, one extra provider needs to be passed to benchpress in tests that want to collect these metrics:
benchpress.sample(providers: [{provide: bp.Options.CAPTURE_FRAMES, useValue: true}], ... )
# Requests Metrics
Benchpress can also record the number of requests sent and count the received "encoded" bytes since [window.performance.timing.navigationStart](https://www.w3.org/TR/navigation-timing/#dom-performancetiming-navigationstart):
- `receivedData`: number of bytes received since the last navigation start
- `requestCount`: number of requests sent since the last navigation start
To collect these metrics, you need the following corresponding extra providers:
benchpress.sample(providers: [
{provide: bp.Options.RECEIVED_DATA, useValue: true},
{provide: bp.Options.REQUEST_COUNT, useValue: true}
], ... )
| {
"end_byte": 8123,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/README.md"
} |
angular/packages/benchpress/README.md_8123_11681 | # Best practices
* Use normalized environments
- metrics that are dependent on the performance of the execution environment must be executed on a normalized machine
- e.g. a real mobile device whose cpu frequency is set to a fixed value.
* see our [build script](https://github.com/angular/angular/blob/2.4.9/scripts/ci/android_cpu.sh)
* this requires root access, e.g. via a userdebug build of Android on a Google Nexus device
(see [here](https://source.android.com/source/building) and [here](https://source.android.com/source/building#obtaining-proprietary-binaries))
- e.g. a calibrated machine that does not run background jobs, has a fixed cpu frequency, ...
* Use relative comparisons
- relative comparisons are less likely to change over time and help to interpret the results of benchmarks
- e.g. compare an example written using a ui framework against a hand coded example and track the ratio
* Assert post-commit for commit ranges
- running benchmarks can take some time. Running them before every commit is usually too slow.
- when a regression is detected for a commit range, use bisection to find the problematic commit
* Repeat benchmarks multiple times in a fresh window
- run the same benchmark multiple times in a fresh window and then take the minimal average value of each benchmark run
* Use force gc with care
- forcing gc can skew the script execution time and gcTime numbers,
but might be needed to get stable gc time / gc amount numbers
* Open a new window for every test
- browsers (e.g. chrome) might keep JIT statistics over page reloads and optimize pages differently depending on what has been loaded before
# Detailed overview

Definitions:
* valid sample: a sample that represents the world that should be measured in a good way.
* complete sample: sample of all measure values collected so far
Components:
* Runner
- contains a default configuration
- creates a new injector for every sample call, via which all other components are created
* Sampler
- gets data from the metrics
- reports measure values immediately to the reporters
- loops until the validator is able to extract a valid sample out of the complete sample (see below).
- reports the valid sample and the complete sample to the reporters
* Metric
- gets measure values from the browser
- e.g. reads out performance logs, DOM values, JavaScript values
* Validator
- extracts a valid sample out of the complete sample of all measure values.
- e.g. wait until there are 10 samples and take them as valid sample (would include warmup time)
- e.g. wait until the regression slope for the metric `scriptTime` through the last 10 measure values is >=0, i.e. the values for the `scriptTime` metric are no more decreasing
* Reporter
- reports measure values, the valid sample and the complete sample to backends
- e.g. a reporter that prints to the console, a reporter that reports values into Google BigQuery, ...
* WebDriverAdapter
- abstraction over the used web driver client
- one implementation for every webdriver client
E.g. one for selenium-webdriver Node.js module, dart async webdriver, dart sync webdriver, ...
* WebDriverExtension
- implements additional methods that are standardized in the webdriver protocol using the WebDriverAdapter
- provides functionality like force gc, read out performance logs in a normalized format
- one implementation per browser, e.g. one for Chrome, one for mobile Safari, one for Firefox
| {
"end_byte": 11681,
"start_byte": 8123,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/README.md"
} |
angular/packages/benchpress/BUILD.bazel_0_994 | load("//tools:defaults.bzl", "ng_package", "ts_library")
package(default_visibility = ["//visibility:public"])
ts_library(
name = "benchpress",
srcs = glob(
[
"*.ts",
"src/**/*.ts",
],
),
# TODO(alanagius) fix benchpress to compile with es2022
devmode_target = "es2020",
prodmode_target = "es2020",
deps = [
"//packages:types",
"//packages/core",
"@npm//@types/node",
"@npm//reflect-metadata",
],
)
ng_package(
name = "npm_package",
package_name = "@angular/benchpress",
srcs = [
"README.md",
"package.json",
],
externals = [
"@angular/core",
"reflect-metadata",
],
# Do not add more to this list.
# Dependencies on the full npm_package cause long re-builds.
visibility = [
"//integration:__subpackages__",
"//modules/ssr-benchmarks:__subpackages__",
],
deps = [
":benchpress",
],
)
| {
"end_byte": 994,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/BUILD.bazel"
} |
angular/packages/benchpress/index.ts_0_1762 | /**
* @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
*/
/// <reference types="node" />
// Must be imported first, because Angular decorators throw on load.
import 'reflect-metadata';
export {InjectionToken, Injector, Provider, StaticProvider} from '@angular/core';
export {Options} from './src/common_options';
export {MeasureValues} from './src/measure_values';
export {Metric} from './src/metric';
export {MultiMetric} from './src/metric/multi_metric';
export {PerflogMetric} from './src/metric/perflog_metric';
export {UserMetric} from './src/metric/user_metric';
export {Reporter} from './src/reporter';
export {ConsoleReporter} from './src/reporter/console_reporter';
export {JsonFileReporter} from './src/reporter/json_file_reporter';
export {MultiReporter} from './src/reporter/multi_reporter';
export {Runner} from './src/runner';
export {SampleDescription} from './src/sample_description';
export {Sampler, SampleState} from './src/sampler';
export {Validator} from './src/validator';
export {RegressionSlopeValidator} from './src/validator/regression_slope_validator';
export {SizeValidator} from './src/validator/size_validator';
export {WebDriverAdapter} from './src/web_driver_adapter';
export {PerfLogEvent, PerfLogFeatures, WebDriverExtension} from './src/web_driver_extension';
export {ChromeDriverExtension} from './src/webdriver/chrome_driver_extension';
export {FirefoxDriverExtension} from './src/webdriver/firefox_driver_extension';
export {IOsDriverExtension} from './src/webdriver/ios_driver_extension';
export {SeleniumWebDriverAdapter} from './src/webdriver/selenium_webdriver_adapter';
| {
"end_byte": 1762,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/index.ts"
} |
angular/packages/benchpress/test/runner_spec.ts_0_4118 | /**
* @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 {
Injector,
Metric,
Options,
Runner,
SampleDescription,
Sampler,
SampleState,
Validator,
WebDriverAdapter,
} from '../index';
describe('runner', () => {
let injector: Injector;
let runner: Runner;
function createRunner(defaultProviders?: any[]): Runner {
if (!defaultProviders) {
defaultProviders = [];
}
runner = new Runner([
defaultProviders,
{
provide: Sampler,
useFactory: (_injector: Injector) => {
injector = _injector;
return new MockSampler();
},
deps: [Injector],
},
{provide: Metric, useFactory: () => new MockMetric(), deps: []},
{provide: Validator, useFactory: () => new MockValidator(), deps: []},
{provide: WebDriverAdapter, useFactory: () => new MockWebDriverAdapter(), deps: []},
]);
return runner;
}
it('should set SampleDescription.id', (done) => {
createRunner()
.sample({id: 'someId'})
.then((_) => injector.get(SampleDescription))
.then((desc) => {
expect(desc.id).toBe('someId');
done();
});
});
it('should merge SampleDescription.description', (done) => {
createRunner([{provide: Options.DEFAULT_DESCRIPTION, useValue: {'a': 1}}])
.sample({
id: 'someId',
providers: [{provide: Options.SAMPLE_DESCRIPTION, useValue: {'b': 2}}],
})
.then((_) => injector.get(SampleDescription))
.then((desc) => {
expect(desc.description).toEqual({
'forceGc': false,
'userAgent': 'someUserAgent',
'a': 1,
'b': 2,
'v': 11,
});
done();
});
});
it('should fill SampleDescription.metrics from the Metric', (done) => {
createRunner()
.sample({id: 'someId'})
.then((_) => injector.get(SampleDescription))
.then((desc) => {
expect(desc.metrics).toEqual({'m1': 'some metric'});
done();
});
});
it('should provide Options.EXECUTE', (done) => {
const execute = () => {};
createRunner()
.sample({id: 'someId', execute: execute})
.then((_) => {
expect(injector.get(Options.EXECUTE)).toEqual(execute);
done();
});
});
it('should provide Options.PREPARE', (done) => {
const prepare = () => {};
createRunner()
.sample({id: 'someId', prepare: prepare})
.then((_) => {
expect(injector.get(Options.PREPARE)).toEqual(prepare);
done();
});
});
it('should provide Options.MICRO_METRICS', (done) => {
createRunner()
.sample({id: 'someId', microMetrics: {'a': 'b'}})
.then((_) => {
expect(injector.get(Options.MICRO_METRICS)).toEqual({'a': 'b'});
done();
});
});
it('should overwrite providers per sample call', (done) => {
createRunner([{provide: Options.DEFAULT_DESCRIPTION, useValue: {'a': 1}}])
.sample({
id: 'someId',
providers: [{provide: Options.DEFAULT_DESCRIPTION, useValue: {'a': 2}}],
})
.then((_) => injector.get(SampleDescription))
.then((desc) => {
expect(desc.description['a']).toBe(2);
done();
});
});
});
class MockWebDriverAdapter extends WebDriverAdapter {
override executeScript(script: string): Promise<string> {
return Promise.resolve('someUserAgent');
}
override capabilities(): Promise<Map<string, any>> {
return null!;
}
}
class MockValidator extends Validator {
constructor() {
super();
}
override describe() {
return {'v': 11};
}
}
class MockMetric extends Metric {
constructor() {
super();
}
override describe() {
return {'m1': 'some metric'};
}
}
class MockSampler extends Sampler {
constructor() {
super(null!, null!, null!, null!, null!, null!, null!);
}
override sample(): Promise<SampleState> {
return Promise.resolve(new SampleState([], []));
}
}
| {
"end_byte": 4118,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/runner_spec.ts"
} |
angular/packages/benchpress/test/sampler_spec.ts_0_7479 | /**
* @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 {
Injector,
MeasureValues,
Metric,
Options,
Reporter,
Sampler,
Validator,
WebDriverAdapter,
} from '../index';
describe('sampler', () => {
let sampler: Sampler;
const EMPTY_EXECUTE = () => {};
function createSampler({
driver,
metric,
reporter,
validator,
prepare,
execute,
}: {
driver?: any;
metric?: Metric;
reporter?: Reporter;
validator?: Validator;
prepare?: any;
execute?: any;
} = {}) {
let time = 1000;
if (!metric) {
metric = new MockMetric([]);
}
if (!reporter) {
reporter = new MockReporter([]);
}
if (driver == null) {
driver = new MockDriverAdapter([]);
}
const providers = [
Options.DEFAULT_PROVIDERS,
Sampler.PROVIDERS,
{provide: Metric, useValue: metric},
{provide: Reporter, useValue: reporter},
{provide: WebDriverAdapter, useValue: driver},
{provide: Options.EXECUTE, useValue: execute},
{provide: Validator, useValue: validator},
{provide: Options.NOW, useValue: () => new Date(time++)},
];
if (prepare != null) {
providers.push({provide: Options.PREPARE, useValue: prepare});
}
sampler = Injector.create({providers}).get(Sampler);
}
it('should call the prepare and execute callbacks using WebDriverAdapter.waitFor', (done) => {
const log: any[] = [];
let count = 0;
const driver = new MockDriverAdapter([], (callback: Function) => {
const result = callback();
log.push(result);
return Promise.resolve(result);
});
createSampler({
driver: driver,
validator: createCountingValidator(2),
prepare: () => count++,
execute: () => count++,
});
sampler.sample().then((_) => {
expect(count).toBe(4);
expect(log).toEqual([0, 1, 2, 3]);
done();
});
});
it('should call prepare, beginMeasure, execute, endMeasure for every iteration', (done) => {
let workCount = 0;
const log: any[] = [];
createSampler({
metric: createCountingMetric(log),
validator: createCountingValidator(2),
prepare: () => {
log.push(`p${workCount++}`);
},
execute: () => {
log.push(`w${workCount++}`);
},
});
sampler.sample().then((_) => {
expect(log).toEqual([
'p0',
['beginMeasure'],
'w1',
['endMeasure', false, {'script': 0}],
'p2',
['beginMeasure'],
'w3',
['endMeasure', false, {'script': 1}],
]);
done();
});
});
it('should call execute, endMeasure for every iteration if there is no prepare callback', (done) => {
const log: any[] = [];
let workCount = 0;
createSampler({
metric: createCountingMetric(log),
validator: createCountingValidator(2),
execute: () => {
log.push(`w${workCount++}`);
},
prepare: null,
});
sampler.sample().then((_) => {
expect(log).toEqual([
['beginMeasure'],
'w0',
['endMeasure', true, {'script': 0}],
'w1',
['endMeasure', true, {'script': 1}],
]);
done();
});
});
it('should only collect metrics for execute and ignore metrics from prepare', (done) => {
let scriptTime = 0;
let iterationCount = 1;
createSampler({
validator: createCountingValidator(2),
metric: new MockMetric([], () => {
const result = Promise.resolve({'script': scriptTime});
scriptTime = 0;
return result;
}),
prepare: () => {
scriptTime = 1 * iterationCount;
},
execute: () => {
scriptTime = 10 * iterationCount;
iterationCount++;
},
});
sampler.sample().then((state) => {
expect(state.completeSample.length).toBe(2);
expect(state.completeSample[0]).toEqual(mv(0, 1000, {'script': 10}));
expect(state.completeSample[1]).toEqual(mv(1, 1001, {'script': 20}));
done();
});
});
it('should call the validator for every execution and store the valid sample', (done) => {
const log: any[] = [];
const validSample = [mv(null!, null!, {})];
createSampler({
metric: createCountingMetric(),
validator: createCountingValidator(2, validSample, log),
execute: EMPTY_EXECUTE,
});
sampler.sample().then((state) => {
expect(state.validSample).toBe(validSample);
// TODO(tbosch): Why does this fail??
// expect(log).toEqual([
// ['validate', [{'script': 0}], null],
// ['validate', [{'script': 0}, {'script': 1}], validSample]
// ]);
expect(log.length).toBe(2);
expect(log[0]).toEqual(['validate', [mv(0, 1000, {'script': 0})], null]);
expect(log[1]).toEqual([
'validate',
[mv(0, 1000, {'script': 0}), mv(1, 1001, {'script': 1})],
validSample,
]);
done();
});
});
it('should report the metric values', (done) => {
const log: any[] = [];
const validSample = [mv(null!, null!, {})];
createSampler({
validator: createCountingValidator(2, validSample),
metric: createCountingMetric(),
reporter: new MockReporter(log),
execute: EMPTY_EXECUTE,
});
sampler.sample().then((_) => {
// TODO(tbosch): Why does this fail??
// expect(log).toEqual([
// ['reportMeasureValues', 0, {'script': 0}],
// ['reportMeasureValues', 1, {'script': 1}],
// ['reportSample', [{'script': 0}, {'script': 1}], validSample]
// ]);
expect(log.length).toBe(3);
expect(log[0]).toEqual(['reportMeasureValues', mv(0, 1000, {'script': 0})]);
expect(log[1]).toEqual(['reportMeasureValues', mv(1, 1001, {'script': 1})]);
expect(log[2]).toEqual([
'reportSample',
[mv(0, 1000, {'script': 0}), mv(1, 1001, {'script': 1})],
validSample,
]);
done();
});
});
});
function mv(runIndex: number, time: number, values: {[key: string]: number}) {
return new MeasureValues(runIndex, new Date(time), values);
}
function createCountingValidator(count: number, validSample?: MeasureValues[], log: any[] = []) {
return new MockValidator(log, (completeSample: MeasureValues[]) => {
count--;
if (count === 0) {
return validSample || completeSample;
} else {
return null;
}
});
}
function createCountingMetric(log: any[] = []) {
let scriptTime = 0;
return new MockMetric(log, () => ({'script': scriptTime++}));
}
class MockDriverAdapter extends WebDriverAdapter {
constructor(
private _log: any[] = [],
private _waitFor: Function | null = null,
) {
super();
}
override waitFor(callback: Function): Promise<any> {
if (this._waitFor != null) {
return this._waitFor(callback);
} else {
return Promise.resolve(callback());
}
}
}
class MockValidator extends Validator {
constructor(
private _log: any[] = [],
private _validate: Function | null = null,
) {
super();
}
override validate(completeSample: MeasureValues[]): MeasureValues[] {
const stableSample = this._validate != null ? this._validate(completeSample) : completeSample;
this._log.push(['validate', completeSample, stableSample]);
return stableSample;
}
} | {
"end_byte": 7479,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/sampler_spec.ts"
} |
angular/packages/benchpress/test/sampler_spec.ts_7481_8446 | class MockMetric extends Metric {
constructor(
private _log: any[] = [],
private _endMeasure: Function | null = null,
) {
super();
}
override beginMeasure() {
this._log.push(['beginMeasure']);
return Promise.resolve(null);
}
override endMeasure(restart: boolean) {
const measureValues = this._endMeasure != null ? this._endMeasure() : {};
this._log.push(['endMeasure', restart, measureValues]);
return Promise.resolve(measureValues);
}
}
class MockReporter extends Reporter {
constructor(private _log: any[] = []) {
super();
}
override reportMeasureValues(values: MeasureValues): Promise<any> {
this._log.push(['reportMeasureValues', values]);
return Promise.resolve(null);
}
override reportSample(
completeSample: MeasureValues[],
validSample: MeasureValues[],
): Promise<any> {
this._log.push(['reportSample', completeSample, validSample]);
return Promise.resolve(null);
}
} | {
"end_byte": 8446,
"start_byte": 7481,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/sampler_spec.ts"
} |
angular/packages/benchpress/test/statistic_spec.ts_0_1333 | /**
* @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 {Statistic} from '../src/statistic';
describe('statistic', () => {
it('should calculate the mean', () => {
expect(Statistic.calculateMean([])).toBeNaN();
expect(Statistic.calculateMean([1, 2, 3])).toBe(2.0);
});
it('should calculate the standard deviation', () => {
expect(Statistic.calculateStandardDeviation([], NaN)).toBeNaN();
expect(Statistic.calculateStandardDeviation([1], 1)).toBe(0.0);
expect(Statistic.calculateStandardDeviation([2, 4, 4, 4, 5, 5, 7, 9], 5)).toBe(2.0);
});
it('should calculate the coefficient of variation', () => {
expect(Statistic.calculateCoefficientOfVariation([], NaN)).toBeNaN();
expect(Statistic.calculateCoefficientOfVariation([1], 1)).toBe(0.0);
expect(Statistic.calculateCoefficientOfVariation([2, 4, 4, 4, 5, 5, 7, 9], 5)).toBe(40.0);
});
it('should calculate the regression slope', () => {
expect(Statistic.calculateRegressionSlope([], NaN, [], NaN)).toBeNaN();
expect(Statistic.calculateRegressionSlope([1], 1, [2], 2)).toBeNaN();
expect(Statistic.calculateRegressionSlope([1, 2], 1.5, [2, 4], 3)).toBe(2.0);
});
});
| {
"end_byte": 1333,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/statistic_spec.ts"
} |
angular/packages/benchpress/test/web_driver_extension_spec.ts_0_1506 | /**
* @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 {Injector, Options, WebDriverExtension} from '../index';
(function () {
function createExtension(ids: any[], caps: any) {
return new Promise<any>((res, rej) => {
try {
res(
Injector.create({
providers: [
ids.map((id) => ({provide: id, useValue: new MockExtension(id)})),
{provide: Options.CAPABILITIES, useValue: caps},
WebDriverExtension.provideFirstSupported(ids),
],
}).get(WebDriverExtension),
);
} catch (e) {
rej(e);
}
});
}
describe('WebDriverExtension.provideFirstSupported', () => {
it('should provide the extension that matches the capabilities', (done) => {
createExtension(['m1', 'm2', 'm3'], {'browser': 'm2'}).then((m) => {
expect(m.id).toEqual('m2');
done();
});
});
it('should throw if there is no match', (done) => {
createExtension(['m1'], {'browser': 'm2'}).catch((err) => {
expect(err != null).toBe(true);
done();
});
});
});
})();
class MockExtension extends WebDriverExtension {
constructor(public id: string) {
super();
}
override supports(capabilities: {[key: string]: any}): boolean {
return capabilities['browser'] === this.id;
}
}
| {
"end_byte": 1506,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/web_driver_extension_spec.ts"
} |
angular/packages/benchpress/test/trace_event_factory.ts_0_1312 | /**
* @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 {PerfLogEvent} from '../index';
export class TraceEventFactory {
constructor(
private _cat: string,
private _pid: string,
) {}
create(ph: any, name: string, time: number, args: any = null) {
const res: PerfLogEvent = {
'name': name,
'cat': this._cat,
'ph': ph,
'ts': time,
'pid': this._pid,
};
if (args != null) {
res['args'] = args;
}
return res;
}
markStart(name: string, time: number) {
return this.create('B', name, time);
}
markEnd(name: string, time: number) {
return this.create('E', name, time);
}
start(name: string, time: number, args: any = null) {
return this.create('B', name, time, args);
}
end(name: string, time: number, args: any = null) {
return this.create('E', name, time, args);
}
instant(name: string, time: number, args: any = null) {
return this.create('I', name, time, args);
}
complete(name: string, time: number, duration: number, args: any = null) {
const res = this.create('X', name, time, args);
res['dur'] = duration;
return res;
}
}
| {
"end_byte": 1312,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/trace_event_factory.ts"
} |
angular/packages/benchpress/test/BUILD.bazel_0_667 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
ts_library(
name = "test_lib",
testonly = True,
srcs = glob(["**/*.ts"]),
# TODO(alanagius) fix benchpress to compile with es2022
devmode_target = "es2020",
prodmode_target = "es2020",
deps = [
"//packages:types",
"//packages/benchpress",
"//packages/core",
"//packages/core/testing",
"@npm//protractor",
],
)
jasmine_node_test(
name = "test",
bootstrap = ["//tools/testing:node"],
deps = [
":test_lib",
"//packages/benchpress",
"//packages/core/testing",
"@npm//protractor",
],
)
| {
"end_byte": 667,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/BUILD.bazel"
} |
angular/packages/benchpress/test/validator/size_validator_spec.ts_0_1422 | /**
* @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 {Injector, MeasureValues, SizeValidator} from '../../index';
describe('size validator', () => {
let validator: SizeValidator;
function createValidator(size: number) {
validator = Injector.create({
providers: [SizeValidator.PROVIDERS, {provide: SizeValidator.SAMPLE_SIZE, useValue: size}],
}).get(SizeValidator);
}
it('should return sampleSize as description', () => {
createValidator(2);
expect(validator.describe()).toEqual({'sampleSize': 2});
});
it('should return null while the completeSample is smaller than the given size', () => {
createValidator(2);
expect(validator.validate([])).toBe(null);
expect(validator.validate([mv(0, 0, {})])).toBe(null);
});
it('should return the last sampleSize runs when it has at least the given size', () => {
createValidator(2);
const sample = [mv(0, 0, {'a': 1}), mv(1, 1, {'b': 2}), mv(2, 2, {'c': 3})];
expect(validator.validate(sample.slice(0, 2))).toEqual(sample.slice(0, 2));
expect(validator.validate(sample)).toEqual(sample.slice(1, 3));
});
});
function mv(runIndex: number, time: number, values: {[key: string]: number}) {
return new MeasureValues(runIndex, new Date(time), values);
}
| {
"end_byte": 1422,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/validator/size_validator_spec.ts"
} |
angular/packages/benchpress/test/validator/regression_slope_validator_spec.ts_0_2363 | /**
* @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 {Injector, MeasureValues, RegressionSlopeValidator} from '../../index';
describe('regression slope validator', () => {
let validator: RegressionSlopeValidator;
function createValidator({size, metric}: {size: number; metric: string}) {
validator = Injector.create({
providers: [
RegressionSlopeValidator.PROVIDERS,
{provide: RegressionSlopeValidator.METRIC, useValue: metric},
{provide: RegressionSlopeValidator.SAMPLE_SIZE, useValue: size},
],
}).get(RegressionSlopeValidator);
}
it('should return sampleSize and metric as description', () => {
createValidator({size: 2, metric: 'script'});
expect(validator.describe()).toEqual({'sampleSize': 2, 'regressionSlopeMetric': 'script'});
});
it('should return null while the completeSample is smaller than the given size', () => {
createValidator({size: 2, metric: 'script'});
expect(validator.validate([])).toBe(null);
expect(validator.validate([mv(0, 0, {})])).toBe(null);
});
it('should return null while the regression slope is < 0', () => {
createValidator({size: 2, metric: 'script'});
expect(validator.validate([mv(0, 0, {'script': 2}), mv(1, 1, {'script': 1})])).toBe(null);
});
it('should return the last sampleSize runs when the regression slope is ==0', () => {
createValidator({size: 2, metric: 'script'});
const sample = [mv(0, 0, {'script': 1}), mv(1, 1, {'script': 1}), mv(2, 2, {'script': 1})];
expect(validator.validate(sample.slice(0, 2))).toEqual(sample.slice(0, 2));
expect(validator.validate(sample)).toEqual(sample.slice(1, 3));
});
it('should return the last sampleSize runs when the regression slope is >0', () => {
createValidator({size: 2, metric: 'script'});
const sample = [mv(0, 0, {'script': 1}), mv(1, 1, {'script': 2}), mv(2, 2, {'script': 3})];
expect(validator.validate(sample.slice(0, 2))).toEqual(sample.slice(0, 2));
expect(validator.validate(sample)).toEqual(sample.slice(1, 3));
});
});
function mv(runIndex: number, time: number, values: {[key: string]: number}) {
return new MeasureValues(runIndex, new Date(time), values);
}
| {
"end_byte": 2363,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/validator/regression_slope_validator_spec.ts"
} |
angular/packages/benchpress/test/reporter/console_reporter_spec.ts_0_3048 | /**
* @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 {COLUMN_WIDTH} from '@angular/benchpress/src/reporter/text_reporter_base';
import {StaticProvider} from '@angular/core';
import {ConsoleReporter, Injector, MeasureValues, SampleDescription} from '../../index';
describe('console reporter', () => {
let reporter: ConsoleReporter;
let log: string[];
function createReporter({
columnWidth = null,
sampleId = null,
descriptions = null,
metrics = null,
}: {
columnWidth?: number | null;
sampleId?: string | null;
descriptions?: {[key: string]: any}[] | null;
metrics?: {[key: string]: any} | null;
}) {
log = [];
if (!descriptions) {
descriptions = [];
}
if (sampleId == null) {
sampleId = 'null';
}
const providers: StaticProvider[] = [
ConsoleReporter.PROVIDERS,
{
provide: SampleDescription,
useValue: new SampleDescription(sampleId, descriptions, metrics!),
},
{provide: ConsoleReporter.PRINT, useValue: (line: string) => log.push(line)},
];
if (columnWidth != null) {
providers.push({provide: COLUMN_WIDTH, useValue: columnWidth});
}
reporter = Injector.create(providers).get(ConsoleReporter);
}
it('should print the sample id, description and table header', () => {
createReporter({
columnWidth: 8,
sampleId: 'someSample',
descriptions: [{'a': 1, 'b': 2}],
metrics: {'m1': 'some desc', 'm2': 'some other desc'},
});
expect(log).toEqual([
[
'BENCHMARK someSample',
'Description:',
'- a: 1',
'- b: 2',
'Metrics:',
'- m1: some desc',
'- m2: some other desc',
'',
' m1 | m2',
'-------- | --------',
'',
].join('\n'),
]);
});
it('should print a table row', () => {
createReporter({columnWidth: 8, metrics: {'a': '', 'b': ''}});
log = [];
reporter.reportMeasureValues(mv(0, 0, {'a': 1.23, 'b': 2}));
expect(log).toEqual([' 1.23 | 2.00']);
});
it('should print the table footer and stats when there is a valid sample', () => {
createReporter({columnWidth: 8, metrics: {'a': '', 'b': ''}});
log = [];
reporter.reportSample([], [mv(0, 0, {'a': 3, 'b': 6}), mv(1, 1, {'a': 5, 'b': 9})]);
expect(log).toEqual(['======== | ========', '4.00+-25% | 7.50+-20%']);
});
it('should print the coefficient of variation only when it is meaningful', () => {
createReporter({columnWidth: 8, metrics: {'a': '', 'b': ''}});
log = [];
reporter.reportSample([], [mv(0, 0, {'a': 3, 'b': 0}), mv(1, 1, {'a': 5, 'b': 0})]);
expect(log).toEqual(['======== | ========', '4.00+-25% | 0.00']);
});
});
function mv(runIndex: number, time: number, values: {[key: string]: number}) {
return new MeasureValues(runIndex, new Date(time), values);
}
| {
"end_byte": 3048,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/reporter/console_reporter_spec.ts"
} |
angular/packages/benchpress/test/reporter/json_file_reporter_spec.ts_0_2778 | /**
* @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 {Injector, JsonFileReporter, MeasureValues, Options, SampleDescription} from '../../index';
describe('file reporter', () => {
let loggedFile: any;
function createReporter({
sampleId,
descriptions,
metrics,
path,
}: {
sampleId: string;
descriptions: {[key: string]: any}[];
metrics: {[key: string]: string};
path: string;
}) {
const providers = [
JsonFileReporter.PROVIDERS,
{
provide: SampleDescription,
useValue: new SampleDescription(sampleId, descriptions, metrics),
},
{provide: JsonFileReporter.PATH, useValue: path},
{provide: Options.NOW, useValue: () => new Date(1234)},
{
provide: Options.WRITE_FILE,
useValue: (filename: string, content: string) => {
loggedFile = {'filename': filename, 'content': content};
return Promise.resolve(null);
},
},
];
return Injector.create({providers}).get<JsonFileReporter>(JsonFileReporter);
}
it('should write all data into a file', (done) => {
createReporter({
sampleId: 'someId',
descriptions: [{'a': 2}],
path: 'somePath',
metrics: {'a': 'script time', 'b': 'render time'},
}).reportSample(
[mv(0, 0, {'a': 3, 'b': 6})],
[mv(0, 0, {'a': 3, 'b': 6}), mv(1, 1, {'a': 5, 'b': 9})],
);
const regExp = /somePath\/someId_\d+\.json/;
expect(loggedFile['filename'].match(regExp) != null).toBe(true);
const parsedContent = JSON.parse(loggedFile['content']) as {[key: string]: any};
expect(parsedContent).toEqual({
'description': {
'id': 'someId',
'description': {'a': 2},
'metrics': {'a': 'script time', 'b': 'render time'},
},
'metricsText': ' a | b',
'stats': {'a': '4.00+-25%', 'b': '7.50+-20%'},
'statsText': ' 4.00+-25% | 7.50+-20%',
'completeSample': [
{'timeStamp': '1970-01-01T00:00:00.000Z', 'runIndex': 0, 'values': {'a': 3, 'b': 6}},
],
'validSample': [
{'timeStamp': '1970-01-01T00:00:00.000Z', 'runIndex': 0, 'values': {'a': 3, 'b': 6}},
{'timeStamp': '1970-01-01T00:00:00.001Z', 'runIndex': 1, 'values': {'a': 5, 'b': 9}},
],
'validSampleTexts': [
' 3.00 | 6.00',
' 5.00 | 9.00',
],
});
done();
});
});
function mv(runIndex: number, time: number, values: {[key: string]: number}) {
return new MeasureValues(runIndex, new Date(time), values);
}
| {
"end_byte": 2778,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/reporter/json_file_reporter_spec.ts"
} |
angular/packages/benchpress/test/reporter/multi_reporter_spec.ts_0_2176 | /**
* @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 {Injector, MeasureValues, MultiReporter, Reporter} from '../../index';
(function () {
function createReporters(ids: any[]) {
const r = Injector.create({
providers: [
ids.map((id) => ({provide: id, useValue: new MockReporter(id)})),
MultiReporter.provideWith(ids),
],
}).get<MultiReporter>(MultiReporter);
return Promise.resolve(r);
}
describe('multi reporter', () => {
it('should reportMeasureValues to all', (done) => {
const mv = new MeasureValues(0, new Date(), {});
createReporters(['m1', 'm2'])
.then((r) => r.reportMeasureValues(mv))
.then((values) => {
expect(values).toEqual([
{'id': 'm1', 'values': mv},
{'id': 'm2', 'values': mv},
]);
done();
});
});
it('should reportSample to call', (done) => {
const completeSample = [
new MeasureValues(0, new Date(), {}),
new MeasureValues(1, new Date(), {}),
];
const validSample = [completeSample[1]];
createReporters(['m1', 'm2'])
.then((r) => r.reportSample(completeSample, validSample))
.then((values) => {
expect(values).toEqual([
{'id': 'm1', 'completeSample': completeSample, 'validSample': validSample},
{'id': 'm2', 'completeSample': completeSample, 'validSample': validSample},
]);
done();
});
});
});
})();
class MockReporter extends Reporter {
constructor(private _id: string) {
super();
}
override reportMeasureValues(values: MeasureValues): Promise<{[key: string]: any}> {
return Promise.resolve({'id': this._id, 'values': values});
}
override reportSample(
completeSample: MeasureValues[],
validSample: MeasureValues[],
): Promise<{[key: string]: any}> {
return Promise.resolve({
'id': this._id,
'completeSample': completeSample,
'validSample': validSample,
});
}
}
| {
"end_byte": 2176,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/reporter/multi_reporter_spec.ts"
} |
angular/packages/benchpress/test/webdriver/chrome_driver_extension_spec.ts_0_382 | /**
* @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 {
ChromeDriverExtension,
Injector,
Options,
WebDriverAdapter,
WebDriverExtension,
} from '../../index';
import {TraceEventFactory} from '../trace_event_factory'; | {
"end_byte": 382,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/webdriver/chrome_driver_extension_spec.ts"
} |
angular/packages/benchpress/test/webdriver/chrome_driver_extension_spec.ts_384_7603 | describe('chrome driver extension', () => {
const CHROME45_USER_AGENT =
'"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2499.0 Safari/537.36"';
const HEADLESSCHROME124_USER_AGENT =
'"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/124.0.6314.0 Safari/537.36"';
let log: any[];
let extension: ChromeDriverExtension;
const blinkEvents = new TraceEventFactory('blink.console', 'pid0');
const v8Events = new TraceEventFactory('v8', 'pid0');
const v8EventsOtherProcess = new TraceEventFactory('v8', 'pid1');
const chromeTimelineEvents = new TraceEventFactory(
'disabled-by-default-devtools.timeline',
'pid0',
);
const chrome45TimelineEvents = new TraceEventFactory('devtools.timeline', 'pid0');
const chromeTimelineV8Events = new TraceEventFactory('devtools.timeline,v8', 'pid0');
const chromeBlinkTimelineEvents = new TraceEventFactory('blink,devtools.timeline', 'pid0');
const chromeBlinkUserTimingEvents = new TraceEventFactory('blink.user_timing', 'pid0');
const benchmarkEvents = new TraceEventFactory('benchmark', 'pid0');
const normEvents = new TraceEventFactory('timeline', 'pid0');
function createExtension(
perfRecords: any[] | null = null,
userAgent: string | null = null,
messageMethod = 'Tracing.dataCollected',
): WebDriverExtension {
if (!perfRecords) {
perfRecords = [];
}
if (userAgent == null) {
userAgent = CHROME45_USER_AGENT;
}
log = [];
extension = Injector.create({
providers: [
ChromeDriverExtension.PROVIDERS,
{
provide: WebDriverAdapter,
useValue: new MockDriverAdapter(log, perfRecords, messageMethod),
},
{provide: Options.USER_AGENT, useValue: userAgent},
{provide: Options.RAW_PERFLOG_PATH, useValue: null},
],
}).get(ChromeDriverExtension);
return extension;
}
it('should force gc via window.gc()', (done) => {
createExtension()
.gc()
.then((_) => {
expect(log).toEqual([['executeScript', 'window.gc()']]);
done();
});
});
it('should clear the perf logs and mark the timeline via performance.mark() on the first call', (done) => {
createExtension()
.timeBegin('someName')
.then(() => {
expect(log).toEqual([
['logs', 'performance'],
['executeScript', `performance.mark('someName-bpstart');`],
]);
done();
});
});
it('should mark the timeline via performance.mark() on the second call', (done) => {
const ext = createExtension();
ext
.timeBegin('someName')
.then((_) => {
log.splice(0, log.length);
ext.timeBegin('someName');
})
.then(() => {
expect(log).toEqual([['executeScript', `performance.mark('someName-bpstart');`]]);
done();
});
});
it('should mark the timeline via performance.mark()', (done) => {
createExtension()
.timeEnd('someName', null)
.then((_) => {
expect(log).toEqual([['executeScript', `performance.mark('someName-bpend');`]]);
done();
});
});
it('should mark the timeline via performance.mark() with start and end of a test', (done) => {
createExtension()
.timeEnd('name1', 'name2')
.then((_) => {
expect(log).toEqual([
['executeScript', `performance.mark('name1-bpend');performance.mark('name2-bpstart');`],
]);
done();
});
});
it('should normalize times to ms and forward ph and pid event properties', (done) => {
createExtension([chromeTimelineV8Events.complete('FunctionCall', 1100, 5500, null)])
.readPerfLog()
.then((events) => {
expect(events).toEqual([normEvents.complete('script', 1.1, 5.5, null)]);
done();
});
});
it('should normalize "tdur" to "dur"', (done) => {
const event: any = chromeTimelineV8Events.create('X', 'FunctionCall', 1100, null);
event['tdur'] = 5500;
createExtension([event])
.readPerfLog()
.then((events) => {
expect(events).toEqual([normEvents.complete('script', 1.1, 5.5, null)]);
done();
});
});
it('should report FunctionCall events as "script"', (done) => {
createExtension([chromeTimelineV8Events.start('FunctionCall', 0)])
.readPerfLog()
.then((events) => {
expect(events).toEqual([normEvents.start('script', 0)]);
done();
});
});
it('should report EvaluateScript events as "script"', (done) => {
createExtension([chromeTimelineV8Events.start('EvaluateScript', 0)])
.readPerfLog()
.then((events) => {
expect(events).toEqual([normEvents.start('script', 0)]);
done();
});
});
it('should report minor gc', (done) => {
createExtension([
chromeTimelineV8Events.start('MinorGC', 1000, {'usedHeapSizeBefore': 1000}),
chromeTimelineV8Events.end('MinorGC', 2000, {'usedHeapSizeAfter': 0}),
])
.readPerfLog()
.then((events) => {
expect(events.length).toEqual(2);
expect(events[0]).toEqual(
normEvents.start('gc', 1.0, {'usedHeapSize': 1000, 'majorGc': false, gcAmount: 0}),
);
expect(events[1]).toEqual(
normEvents.end('gc', 2.0, {'usedHeapSize': 0, 'majorGc': false, gcAmount: 0}),
);
done();
});
});
it('should report minor gc with GC amount', (done) => {
createExtension([
chromeTimelineV8Events.create('X', 'MinorGC', 1000, {
'usedHeapSizeBefore': 5000,
'usedHeapSizeAfter': 2000,
}),
])
.readPerfLog()
.then((events) => {
expect(events.length).toEqual(1);
expect(events[0]).toEqual({
...normEvents.create('X', 'gc', 1.0, {
'usedHeapSize': 2000,
'majorGc': false,
gcAmount: 3000,
}),
dur: 0,
});
done();
});
});
it('should report major gc', (done) => {
createExtension([
chromeTimelineV8Events.start('MajorGC', 1000, {'usedHeapSizeBefore': 1000}),
chromeTimelineV8Events.end('MajorGC', 2000, {'usedHeapSizeAfter': 0}),
])
.readPerfLog()
.then((events) => {
expect(events.length).toEqual(2);
expect(events[0]).toEqual(
normEvents.start('gc', 1.0, {'usedHeapSize': 1000, 'majorGc': true, gcAmount: 0}),
);
expect(events[1]).toEqual(
normEvents.end('gc', 2.0, {'usedHeapSize': 0, 'majorGc': true, gcAmount: 0}),
);
done();
});
});
it('should report major gc with GC amount', (done) => {
createExtension([
chromeTimelineV8Events.create('X', 'MajorGC', 1000, {
'usedHeapSizeBefore': 5000,
'usedHeapSizeAfter': 2000,
}),
])
.readPerfLog()
.then((events) => {
expect(events.length).toEqual(1);
expect(events[0]).toEqual({
...normEvents.create('X', 'gc', 1.0, {
'usedHeapSize': 2000,
'majorGc': true,
gcAmount: 3000,
}),
dur: 0,
});
done();
});
}); | {
"end_byte": 7603,
"start_byte": 384,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/webdriver/chrome_driver_extension_spec.ts"
} |
angular/packages/benchpress/test/webdriver/chrome_driver_extension_spec.ts_7607_15041 | ['Layout', 'UpdateLayerTree', 'Paint'].forEach((recordType) => {
it(`should report ${recordType} as "render"`, (done) => {
createExtension([
chrome45TimelineEvents.start(recordType, 1234),
chrome45TimelineEvents.end(recordType, 2345),
])
.readPerfLog()
.then((events) => {
expect(events).toEqual([
normEvents.start('render', 1.234),
normEvents.end('render', 2.345),
]);
done();
});
});
});
it(`should report UpdateLayoutTree as "render"`, (done) => {
createExtension([
chromeBlinkTimelineEvents.start('UpdateLayoutTree', 1234),
chromeBlinkTimelineEvents.end('UpdateLayoutTree', 2345),
])
.readPerfLog()
.then((events) => {
expect(events).toEqual([
normEvents.start('render', 1.234),
normEvents.end('render', 2.345),
]);
done();
});
});
it('should ignore FunctionCalls from webdriver', (done) => {
createExtension([
chromeTimelineV8Events.start('FunctionCall', 0, {'data': {'scriptName': 'InjectedScript'}}),
])
.readPerfLog()
.then((events) => {
expect(events).toEqual([]);
done();
});
});
it('should ignore FunctionCalls with empty scriptName', (done) => {
createExtension([chromeTimelineV8Events.start('FunctionCall', 0, {'data': {'scriptName': ''}})])
.readPerfLog()
.then((events) => {
expect(events).toEqual([]);
done();
});
});
it('should report navigationStart', (done) => {
createExtension([chromeBlinkUserTimingEvents.instant('navigationStart', 1234)])
.readPerfLog()
.then((events) => {
expect(events).toEqual([normEvents.instant('navigationStart', 1.234)]);
done();
});
});
it('should report receivedData', (done) => {
createExtension([
chrome45TimelineEvents.instant('ResourceReceivedData', 1234, {
'data': {'encodedDataLength': 987},
}),
])
.readPerfLog()
.then((events) => {
expect(events).toEqual([
normEvents.instant('receivedData', 1.234, {'encodedDataLength': 987}),
]);
done();
});
});
it('should report sendRequest', (done) => {
createExtension([
chrome45TimelineEvents.instant('ResourceSendRequest', 1234, {
'data': {'url': 'http://here', 'requestMethod': 'GET'},
}),
])
.readPerfLog()
.then((events) => {
expect(events).toEqual([
normEvents.instant('sendRequest', 1.234, {'url': 'http://here', 'method': 'GET'}),
]);
done();
});
});
describe('readPerfLog (common)', () => {
it('should execute a dummy script before reading them', (done) => {
// TODO(tbosch): This seems to be a bug in ChromeDriver:
// Sometimes it does not report the newest events of the performance log
// to the WebDriver client unless a script is executed...
createExtension([])
.readPerfLog()
.then((_) => {
expect(log).toEqual([
['executeScript', '1+1'],
['logs', 'performance'],
]);
done();
});
});
['Rasterize', 'CompositeLayers'].forEach((recordType) => {
it(`should report ${recordType} as "render"`, (done) => {
createExtension([
chromeTimelineEvents.start(recordType, 1234),
chromeTimelineEvents.end(recordType, 2345),
])
.readPerfLog()
.then((events) => {
expect(events).toEqual([
normEvents.start('render', 1.234),
normEvents.end('render', 2.345),
]);
done();
});
});
});
describe('frame metrics', () => {
it('should report ImplThreadRenderingStats as frame event', (done) => {
createExtension([
benchmarkEvents.instant('BenchmarkInstrumentation::ImplThreadRenderingStats', 1100, {
'data': {'frame_count': 1},
}),
])
.readPerfLog()
.then((events) => {
expect(events).toEqual([normEvents.instant('frame', 1.1)]);
done();
});
});
it('should not report ImplThreadRenderingStats with zero frames', (done) => {
createExtension([
benchmarkEvents.instant('BenchmarkInstrumentation::ImplThreadRenderingStats', 1100, {
'data': {'frame_count': 0},
}),
])
.readPerfLog()
.then((events) => {
expect(events).toEqual([]);
done();
});
});
it('should throw when ImplThreadRenderingStats contains more than one frame', (done) => {
createExtension([
benchmarkEvents.instant('BenchmarkInstrumentation::ImplThreadRenderingStats', 1100, {
'data': {'frame_count': 2},
}),
])
.readPerfLog()
.catch((err): any => {
expect(() => {
throw err;
}).toThrowError('multi-frame render stats not supported');
done();
});
});
});
it('should report begin timestamps', (done) => {
createExtension([blinkEvents.create('S', 'someName', 1000)])
.readPerfLog()
.then((events) => {
expect(events).toEqual([normEvents.markStart('someName', 1.0)]);
done();
});
});
it('should report end timestamps', (done) => {
createExtension([blinkEvents.create('F', 'someName', 1000)])
.readPerfLog()
.then((events) => {
expect(events).toEqual([normEvents.markEnd('someName', 1.0)]);
done();
});
});
it('should throw an error on buffer overflow', (done) => {
createExtension(
[chromeTimelineEvents.start('FunctionCall', 1234)],
CHROME45_USER_AGENT,
'Tracing.bufferUsage',
)
.readPerfLog()
.catch((err): any => {
expect(() => {
throw err;
}).toThrowError('The DevTools trace buffer filled during the test!');
done();
});
});
it('should match chrome browsers', () => {
expect(createExtension().supports({'browserName': 'chrome'})).toBe(true);
expect(createExtension().supports({'browserName': 'Chrome'})).toBe(true);
expect(createExtension().supports({'browserName': 'chrome-headless-shell'})).toBe(true);
});
it('should parse chrome version from user agent', () => {
expect(
createExtension(null, HEADLESSCHROME124_USER_AGENT).supports({
'browserName': 'chrome-headless-shell',
}),
).toBe(true);
});
});
});
class MockDriverAdapter extends WebDriverAdapter {
constructor(
private _log: any[],
private _events: any[],
private _messageMethod: string,
) {
super();
}
override executeScript(script: string) {
this._log.push(['executeScript', script]);
return Promise.resolve(null);
}
override logs(type: string): Promise<any[]> {
this._log.push(['logs', type]);
if (type === 'performance') {
return Promise.resolve(
this._events.map((event) => ({
'message': JSON.stringify(
{'message': {'method': this._messageMethod, 'params': event}},
null,
2,
),
})),
);
} else {
return null!;
}
}
} | {
"end_byte": 15041,
"start_byte": 7607,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/webdriver/chrome_driver_extension_spec.ts"
} |
angular/packages/benchpress/test/webdriver/ios_driver_extension_spec.ts_0_6114 | /**
* @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 {Injector, IOsDriverExtension, WebDriverAdapter, WebDriverExtension} from '../../index';
import {TraceEventFactory} from '../trace_event_factory';
describe('ios driver extension', () => {
let log: any[];
let extension: IOsDriverExtension;
const normEvents = new TraceEventFactory('timeline', 'pid0');
function createExtension(perfRecords: any[] | null = null): WebDriverExtension {
if (!perfRecords) {
perfRecords = [];
}
log = [];
extension = Injector.create({
providers: [
IOsDriverExtension.PROVIDERS,
{provide: WebDriverAdapter, useValue: new MockDriverAdapter(log, perfRecords)},
],
}).get(IOsDriverExtension);
return extension;
}
it('should throw on forcing gc', () => {
expect(() => createExtension().gc()).toThrowError('Force GC is not supported on iOS');
});
it('should mark the timeline via console.time()', (done) => {
createExtension()
.timeBegin('someName')
.then((_) => {
expect(log).toEqual([['executeScript', `console.time('someName');`]]);
done();
});
});
it('should mark the timeline via console.timeEnd()', (done) => {
createExtension()
.timeEnd('someName', null)
.then((_) => {
expect(log).toEqual([['executeScript', `console.timeEnd('someName');`]]);
done();
});
});
it('should mark the timeline via console.time() and console.timeEnd()', (done) => {
createExtension()
.timeEnd('name1', 'name2')
.then((_) => {
expect(log).toEqual([['executeScript', `console.timeEnd('name1');console.time('name2');`]]);
done();
});
});
describe('readPerfLog', () => {
it('should execute a dummy script before reading them', (done) => {
// TODO(tbosch): This seems to be a bug in ChromeDriver:
// Sometimes it does not report the newest events of the performance log
// to the WebDriver client unless a script is executed...
createExtension([])
.readPerfLog()
.then((_) => {
expect(log).toEqual([
['executeScript', '1+1'],
['logs', 'performance'],
]);
done();
});
});
it('should report FunctionCall records as "script"', (done) => {
createExtension([durationRecord('FunctionCall', 1, 5)])
.readPerfLog()
.then((events) => {
expect(events).toEqual([normEvents.start('script', 1), normEvents.end('script', 5)]);
done();
});
});
it('should ignore FunctionCalls from webdriver', (done) => {
createExtension([internalScriptRecord(1, 5)])
.readPerfLog()
.then((events) => {
expect(events).toEqual([]);
done();
});
});
it('should report begin time', (done) => {
createExtension([timeBeginRecord('someName', 12)])
.readPerfLog()
.then((events) => {
expect(events).toEqual([normEvents.markStart('someName', 12)]);
done();
});
});
it('should report end timestamps', (done) => {
createExtension([timeEndRecord('someName', 12)])
.readPerfLog()
.then((events) => {
expect(events).toEqual([normEvents.markEnd('someName', 12)]);
done();
});
});
[
'RecalculateStyles',
'Layout',
'UpdateLayerTree',
'Paint',
'Rasterize',
'CompositeLayers',
].forEach((recordType) => {
it(`should report ${recordType}`, (done) => {
createExtension([durationRecord(recordType, 0, 1)])
.readPerfLog()
.then((events) => {
expect(events).toEqual([normEvents.start('render', 0), normEvents.end('render', 1)]);
done();
});
});
});
it('should walk children', (done) => {
createExtension([durationRecord('FunctionCall', 1, 5, [timeBeginRecord('someName', 2)])])
.readPerfLog()
.then((events) => {
expect(events).toEqual([
normEvents.start('script', 1),
normEvents.markStart('someName', 2),
normEvents.end('script', 5),
]);
done();
});
});
it('should match safari browsers', () => {
expect(createExtension().supports({'browserName': 'safari'})).toBe(true);
expect(createExtension().supports({'browserName': 'Safari'})).toBe(true);
});
});
});
function timeBeginRecord(name: string, time: number) {
return {'type': 'Time', 'startTime': time, 'data': {'message': name}};
}
function timeEndRecord(name: string, time: number) {
return {'type': 'TimeEnd', 'startTime': time, 'data': {'message': name}};
}
function durationRecord(
type: string,
startTime: number,
endTime: number,
children: any[] | null = null,
) {
if (!children) {
children = [];
}
return {'type': type, 'startTime': startTime, 'endTime': endTime, 'children': children};
}
function internalScriptRecord(startTime: number, endTime: number) {
return {
'type': 'FunctionCall',
'startTime': startTime,
'endTime': endTime,
'data': {'scriptName': 'InjectedScript'},
};
}
class MockDriverAdapter extends WebDriverAdapter {
constructor(
private _log: any[],
private _perfRecords: any[],
) {
super();
}
override executeScript(script: string) {
this._log.push(['executeScript', script]);
return Promise.resolve(null);
}
override logs(type: string): Promise<any[]> {
this._log.push(['logs', type]);
if (type === 'performance') {
return Promise.resolve(
this._perfRecords.map(function (record) {
return {
'message': JSON.stringify(
{'message': {'method': 'Timeline.eventRecorded', 'params': {'record': record}}},
null,
2,
),
};
}),
);
} else {
return null!;
}
}
}
| {
"end_byte": 6114,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/webdriver/ios_driver_extension_spec.ts"
} |
angular/packages/benchpress/test/metric/perflog_metric_spec.ts_0_5972 | /**
* @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 {StaticProvider} from '@angular/core';
import {
Injector,
Metric,
Options,
PerfLogEvent,
PerfLogFeatures,
PerflogMetric,
WebDriverExtension,
} from '../../index';
import {TraceEventFactory} from '../trace_event_factory';
(function () {
let commandLog: any[];
const eventFactory = new TraceEventFactory('timeline', 'pid0');
function createMetric(
perfLogs: PerfLogEvent[],
perfLogFeatures: PerfLogFeatures,
{
microMetrics,
forceGc,
captureFrames,
receivedData,
requestCount,
ignoreNavigation,
}: {
microMetrics?: {[key: string]: string};
forceGc?: boolean;
captureFrames?: boolean;
receivedData?: boolean;
requestCount?: boolean;
ignoreNavigation?: boolean;
} = {},
): Metric {
commandLog = [];
if (!perfLogFeatures) {
perfLogFeatures = new PerfLogFeatures({
render: true,
gc: true,
frameCapture: true,
userTiming: true,
});
}
if (!microMetrics) {
microMetrics = {};
}
const providers: StaticProvider[] = [
Options.DEFAULT_PROVIDERS,
PerflogMetric.PROVIDERS,
{provide: Options.MICRO_METRICS, useValue: microMetrics},
{
provide: PerflogMetric.SET_TIMEOUT,
useValue: (fn: Function, millis: number) => {
commandLog.push(['setTimeout', millis]);
fn();
},
},
{
provide: WebDriverExtension,
useValue: new MockDriverExtension(perfLogs, commandLog, perfLogFeatures),
},
];
if (forceGc != null) {
providers.push({provide: Options.FORCE_GC, useValue: forceGc});
}
if (captureFrames != null) {
providers.push({provide: Options.CAPTURE_FRAMES, useValue: captureFrames});
}
if (receivedData != null) {
providers.push({provide: Options.RECEIVED_DATA, useValue: receivedData});
}
if (requestCount != null) {
providers.push({provide: Options.REQUEST_COUNT, useValue: requestCount});
}
if (ignoreNavigation != null) {
providers.push({provide: PerflogMetric.IGNORE_NAVIGATION, useValue: ignoreNavigation});
}
return Injector.create({providers}).get(PerflogMetric);
}
describe('perflog metric', () => {
function sortedKeys(stringMap: {[key: string]: any}) {
const res: string[] = [];
res.push(...Object.keys(stringMap));
res.sort();
return res;
}
it('should describe itself based on the perfLogFeatrues', () => {
expect(sortedKeys(createMetric([[]], new PerfLogFeatures()).describe())).toEqual([
'pureScriptTime',
'scriptTime',
]);
expect(
sortedKeys(createMetric([[]], new PerfLogFeatures({render: true, gc: false})).describe()),
).toEqual(['pureScriptTime', 'renderTime', 'renderTimeInScript', 'scriptTime']);
expect(sortedKeys(createMetric([[]], null!).describe())).toEqual([
'gcAmount',
'gcTime',
'gcTimeInScript',
'majorGcTime',
'pureScriptTime',
'renderTime',
'renderTimeInScript',
'scriptTime',
]);
expect(
sortedKeys(
createMetric([[]], new PerfLogFeatures({render: true, gc: true}), {
forceGc: true,
}).describe(),
),
).toEqual([
'forcedGcAmount',
'forcedGcTime',
'gcAmount',
'gcTime',
'gcTimeInScript',
'majorGcTime',
'pureScriptTime',
'renderTime',
'renderTimeInScript',
'scriptTime',
]);
expect(
sortedKeys(
createMetric([[]], new PerfLogFeatures({userTiming: true}), {
receivedData: true,
requestCount: true,
}).describe(),
),
).toEqual(['pureScriptTime', 'receivedData', 'requestCount', 'scriptTime']);
});
it('should describe itself based on micro metrics', () => {
const description = createMetric([[]], null!, {
microMetrics: {'myMicroMetric': 'someDesc'},
}).describe();
expect(description['myMicroMetric']).toEqual('someDesc');
});
it('should describe itself if frame capture is requested and available', () => {
const description = createMetric([[]], new PerfLogFeatures({frameCapture: true}), {
captureFrames: true,
}).describe();
expect(description['frameTime.mean']).not.toContain('WARNING');
expect(description['frameTime.best']).not.toContain('WARNING');
expect(description['frameTime.worst']).not.toContain('WARNING');
expect(description['frameTime.smooth']).not.toContain('WARNING');
});
it('should describe itself if frame capture is requested and not available', () => {
const description = createMetric([[]], new PerfLogFeatures({frameCapture: false}), {
captureFrames: true,
}).describe();
expect(description['frameTime.mean']).toContain('WARNING');
expect(description['frameTime.best']).toContain('WARNING');
expect(description['frameTime.worst']).toContain('WARNING');
expect(description['frameTime.smooth']).toContain('WARNING');
});
describe('beginMeasure', () => {
it('should not force gc and mark the timeline', (done) => {
const metric = createMetric([[]], null!);
metric.beginMeasure().then((_) => {
expect(commandLog).toEqual([['timeBegin', 'benchpress0']]);
done();
});
});
it('should force gc and mark the timeline', (done) => {
const metric = createMetric([[]], null!, {forceGc: true});
metric.beginMeasure().then((_) => {
expect(commandLog).toEqual([['gc'], ['timeBegin', 'benchpress0']]);
done();
});
});
}); | {
"end_byte": 5972,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/metric/perflog_metric_spec.ts"
} |
angular/packages/benchpress/test/metric/perflog_metric_spec.ts_5978_13145 | describe('endMeasure', () => {
it('should mark and aggregate events in between the marks', (done) => {
const events = [
[
eventFactory.markStart('benchpress0', 0),
eventFactory.start('script', 4),
eventFactory.end('script', 6),
eventFactory.markEnd('benchpress0', 10),
],
];
const metric = createMetric(events, null!);
metric
.beginMeasure()
.then((_) => metric.endMeasure(false))
.then((data) => {
expect(commandLog).toEqual([
['timeBegin', 'benchpress0'],
['timeEnd', 'benchpress0', null],
'readPerfLog',
]);
expect(data['scriptTime']).toBe(2);
done();
});
});
it('should mark and aggregate events since navigationStart', (done) => {
const events = [
[
eventFactory.markStart('benchpress0', 0),
eventFactory.start('script', 4),
eventFactory.end('script', 6),
eventFactory.instant('navigationStart', 7),
eventFactory.start('script', 8),
eventFactory.end('script', 9),
eventFactory.markEnd('benchpress0', 10),
],
];
const metric = createMetric(events, null!);
metric
.beginMeasure()
.then((_) => metric.endMeasure(false))
.then((data) => {
expect(data['scriptTime']).toBe(1);
done();
});
});
it('should ignore navigationStart if ignoreNavigation is set', (done) => {
const events = [
[
eventFactory.markStart('benchpress0', 0),
eventFactory.start('script', 4),
eventFactory.end('script', 6),
eventFactory.instant('navigationStart', 7),
eventFactory.start('script', 8),
eventFactory.end('script', 9),
eventFactory.markEnd('benchpress0', 10),
],
];
const metric = createMetric(events, null!, {ignoreNavigation: true});
metric
.beginMeasure()
.then((_) => metric.endMeasure(false))
.then((data) => {
expect(data['scriptTime']).toBe(3);
done();
});
});
it('should restart timing', (done) => {
const events = [
[
eventFactory.markStart('benchpress0', 0),
eventFactory.markEnd('benchpress0', 1),
eventFactory.markStart('benchpress1', 2),
],
[eventFactory.markEnd('benchpress1', 3)],
];
const metric = createMetric(events, null!);
metric
.beginMeasure()
.then((_) => metric.endMeasure(true))
.then((_) => metric.endMeasure(true))
.then((_) => {
expect(commandLog).toEqual([
['timeBegin', 'benchpress0'],
['timeEnd', 'benchpress0', 'benchpress1'],
'readPerfLog',
['timeEnd', 'benchpress1', 'benchpress2'],
'readPerfLog',
]);
done();
});
});
it('should loop and aggregate until the end mark is present', (done) => {
const events = [
[eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 1)],
[eventFactory.end('script', 2)],
[
eventFactory.start('script', 3),
eventFactory.end('script', 5),
eventFactory.markEnd('benchpress0', 10),
],
];
const metric = createMetric(events, null!);
metric
.beginMeasure()
.then((_) => metric.endMeasure(false))
.then((data) => {
expect(commandLog).toEqual([
['timeBegin', 'benchpress0'],
['timeEnd', 'benchpress0', null],
'readPerfLog',
['setTimeout', 100],
'readPerfLog',
['setTimeout', 100],
'readPerfLog',
]);
expect(data['scriptTime']).toBe(3);
done();
});
});
it('should store events after the end mark for the next call', (done) => {
const events = [
[
eventFactory.markStart('benchpress0', 0),
eventFactory.markEnd('benchpress0', 1),
eventFactory.markStart('benchpress1', 1),
eventFactory.start('script', 1),
eventFactory.end('script', 2),
],
[
eventFactory.start('script', 3),
eventFactory.end('script', 5),
eventFactory.markEnd('benchpress1', 6),
],
];
const metric = createMetric(events, null!);
metric
.beginMeasure()
.then((_) => metric.endMeasure(true))
.then((data) => {
expect(data['scriptTime']).toBe(0);
return metric.endMeasure(true);
})
.then((data) => {
expect(commandLog).toEqual([
['timeBegin', 'benchpress0'],
['timeEnd', 'benchpress0', 'benchpress1'],
'readPerfLog',
['timeEnd', 'benchpress1', 'benchpress2'],
'readPerfLog',
]);
expect(data['scriptTime']).toBe(3);
done();
});
});
describe('with forced gc', () => {
let events: PerfLogEvent[][];
beforeEach(() => {
events = [
[
eventFactory.markStart('benchpress0', 0),
eventFactory.start('script', 4),
eventFactory.end('script', 6),
eventFactory.markEnd('benchpress0', 10),
eventFactory.markStart('benchpress1', 11),
eventFactory.start('gc', 12, {'usedHeapSize': 2500}),
eventFactory.end('gc', 15, {'usedHeapSize': 1000}),
eventFactory.markEnd('benchpress1', 20),
],
];
});
it('should measure forced gc', (done) => {
const metric = createMetric(events, null!, {forceGc: true});
metric
.beginMeasure()
.then((_) => metric.endMeasure(false))
.then((data) => {
expect(commandLog).toEqual([
['gc'],
['timeBegin', 'benchpress0'],
['timeEnd', 'benchpress0', 'benchpress1'],
'readPerfLog',
['gc'],
['timeEnd', 'benchpress1', null],
'readPerfLog',
]);
expect(data['forcedGcTime']).toBe(3);
expect(data['forcedGcAmount']).toBe(1.5);
done();
});
});
it('should restart after the forced gc if needed', (done) => {
const metric = createMetric(events, null!, {forceGc: true});
metric
.beginMeasure()
.then((_) => metric.endMeasure(true))
.then((data) => {
expect(commandLog[5]).toEqual(['timeEnd', 'benchpress1', 'benchpress2']);
done();
});
});
});
}); | {
"end_byte": 13145,
"start_byte": 5978,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/metric/perflog_metric_spec.ts"
} |
angular/packages/benchpress/test/metric/perflog_metric_spec.ts_13151_22127 | describe('aggregation', () => {
function aggregate(
events: any[],
{
microMetrics,
captureFrames,
receivedData,
requestCount,
}: {
microMetrics?: {[key: string]: string};
captureFrames?: boolean;
receivedData?: boolean;
requestCount?: boolean;
} = {},
) {
events.unshift(eventFactory.markStart('benchpress0', 0));
events.push(eventFactory.markEnd('benchpress0', 10));
const metric = createMetric([events], null!, {
microMetrics: microMetrics,
captureFrames: captureFrames,
receivedData: receivedData,
requestCount: requestCount,
});
return metric.beginMeasure().then((_) => metric.endMeasure(false));
}
describe('frame metrics', () => {
it('should calculate mean frame time', (done) => {
aggregate(
[
eventFactory.markStart('frameCapture', 0),
eventFactory.instant('frame', 1),
eventFactory.instant('frame', 3),
eventFactory.instant('frame', 4),
eventFactory.markEnd('frameCapture', 5),
],
{captureFrames: true},
).then((data) => {
expect(data['frameTime.mean']).toBe((3 - 1 + (4 - 3)) / 2);
done();
});
});
it('should throw if no start event', (done) => {
aggregate([eventFactory.instant('frame', 4), eventFactory.markEnd('frameCapture', 5)], {
captureFrames: true,
}).catch((err): any => {
expect(() => {
throw err;
}).toThrowError('missing start event for frame capture');
done();
});
});
it('should throw if no end event', (done) => {
aggregate([eventFactory.markStart('frameCapture', 3), eventFactory.instant('frame', 4)], {
captureFrames: true,
}).catch((err): any => {
expect(() => {
throw err;
}).toThrowError('missing end event for frame capture');
done();
});
});
it('should throw if trying to capture twice', (done) => {
aggregate(
[eventFactory.markStart('frameCapture', 3), eventFactory.markStart('frameCapture', 4)],
{captureFrames: true},
).catch((err): any => {
expect(() => {
throw err;
}).toThrowError('can capture frames only once per benchmark run');
done();
});
});
it('should throw if trying to capture when frame capture is disabled', (done) => {
aggregate([eventFactory.markStart('frameCapture', 3)]).catch((err) => {
expect(() => {
throw err;
}).toThrowError(
'found start event for frame capture, but frame capture was not requested in benchpress',
);
done();
return null;
});
});
it('should throw if frame capture is enabled, but nothing is captured', (done) => {
aggregate([], {captureFrames: true}).catch((err): any => {
expect(() => {
throw err;
}).toThrowError('frame capture requested in benchpress, but no start event was found');
done();
});
});
it('should calculate best and worst frame time', (done) => {
aggregate(
[
eventFactory.markStart('frameCapture', 0),
eventFactory.instant('frame', 1),
eventFactory.instant('frame', 9),
eventFactory.instant('frame', 15),
eventFactory.instant('frame', 18),
eventFactory.instant('frame', 28),
eventFactory.instant('frame', 32),
eventFactory.markEnd('frameCapture', 10),
],
{captureFrames: true},
).then((data) => {
expect(data['frameTime.worst']).toBe(10);
expect(data['frameTime.best']).toBe(3);
done();
});
});
it('should calculate percentage of smoothness to be good', (done) => {
aggregate(
[
eventFactory.markStart('frameCapture', 0),
eventFactory.instant('frame', 1),
eventFactory.instant('frame', 2),
eventFactory.instant('frame', 3),
eventFactory.markEnd('frameCapture', 4),
],
{captureFrames: true},
).then((data) => {
expect(data['frameTime.smooth']).toBe(1.0);
done();
});
});
it('should calculate percentage of smoothness to be bad', (done) => {
aggregate(
[
eventFactory.markStart('frameCapture', 0),
eventFactory.instant('frame', 1),
eventFactory.instant('frame', 2),
eventFactory.instant('frame', 22),
eventFactory.instant('frame', 23),
eventFactory.instant('frame', 24),
eventFactory.markEnd('frameCapture', 4),
],
{captureFrames: true},
).then((data) => {
expect(data['frameTime.smooth']).toBe(0.75);
done();
});
});
});
it('should report a single interval', (done) => {
aggregate([eventFactory.start('script', 0), eventFactory.end('script', 5)]).then((data) => {
expect(data['scriptTime']).toBe(5);
done();
});
});
it('should sum up multiple intervals', (done) => {
aggregate([
eventFactory.start('script', 0),
eventFactory.end('script', 5),
eventFactory.start('script', 10),
eventFactory.end('script', 17),
]).then((data) => {
expect(data['scriptTime']).toBe(12);
done();
});
});
it('should ignore not started intervals', (done) => {
aggregate([eventFactory.end('script', 10)]).then((data) => {
expect(data['scriptTime']).toBe(0);
done();
});
});
it('should ignore not ended intervals', (done) => {
aggregate([eventFactory.start('script', 10)]).then((data) => {
expect(data['scriptTime']).toBe(0);
done();
});
});
it('should ignore nested intervals', (done) => {
aggregate([
eventFactory.start('script', 0),
eventFactory.start('script', 5),
eventFactory.end('script', 10),
eventFactory.end('script', 17),
]).then((data) => {
expect(data['scriptTime']).toBe(17);
done();
});
});
it('should ignore events from different processed as the start mark', (done) => {
const otherProcessEventFactory = new TraceEventFactory('timeline', 'pid1');
const metric = createMetric(
[
[
eventFactory.markStart('benchpress0', 0),
eventFactory.start('script', 0, null),
eventFactory.end('script', 5, null),
otherProcessEventFactory.start('script', 10, null),
otherProcessEventFactory.end('script', 17, null),
eventFactory.markEnd('benchpress0', 20),
],
],
null!,
);
metric
.beginMeasure()
.then((_) => metric.endMeasure(false))
.then((data) => {
expect(data['scriptTime']).toBe(5);
done();
});
});
it('should mark a run as invalid if the start and end marks are different', (done) => {
const otherProcessEventFactory = new TraceEventFactory('timeline', 'pid1');
const metric = createMetric(
[
[
eventFactory.markStart('benchpress0', 0),
eventFactory.start('script', 0, null),
eventFactory.end('script', 5, null),
otherProcessEventFactory.start('script', 10, null),
otherProcessEventFactory.end('script', 17, null),
otherProcessEventFactory.markEnd('benchpress0', 20),
],
],
null!,
);
metric
.beginMeasure()
.then((_) => metric.endMeasure(false))
.then((data) => {
expect(data['invalid']).toBe(1);
done();
});
});
it('should support scriptTime metric', (done) => {
aggregate([eventFactory.start('script', 0), eventFactory.end('script', 5)]).then((data) => {
expect(data['scriptTime']).toBe(5);
done();
});
});
it('should support renderTime metric', (done) => {
aggregate([eventFactory.start('render', 0), eventFactory.end('render', 5)]).then((data) => {
expect(data['renderTime']).toBe(5);
done();
});
}); | {
"end_byte": 22127,
"start_byte": 13151,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/metric/perflog_metric_spec.ts"
} |
angular/packages/benchpress/test/metric/perflog_metric_spec.ts_22135_28036 | it('should support renderTimeInScript metric', (done) => {
aggregate([
eventFactory.start('script', 0),
eventFactory.start('render', 1),
eventFactory.end('render', 3),
eventFactory.end('script', 5),
]).then((data) => {
expect(data['renderTimeInScript']).toBe(2);
expect(data['renderTime']).toBe(2);
expect(data['pureScriptTime']).toBe(3);
expect(data['scriptTime']).toBe(5);
done();
});
});
it('should support gcTime/gcAmount metric', (done) => {
aggregate([
eventFactory.start('gc', 0, {'usedHeapSize': 2500}),
eventFactory.end('gc', 5, {'usedHeapSize': 1000}),
]).then((data) => {
expect(data['gcTime']).toBe(5);
expect(data['gcAmount']).toBe(1.5);
expect(data['majorGcTime']).toBe(0);
done();
});
});
it('should support majorGcTime metric', (done) => {
aggregate([
eventFactory.start('gc', 0, {'usedHeapSize': 2500}),
eventFactory.end('gc', 5, {'usedHeapSize': 1000, 'majorGc': true}),
]).then((data) => {
expect(data['gcTime']).toBe(5);
expect(data['majorGcTime']).toBe(5);
done();
});
});
it('should support gcTimeInScript metric', (done) => {
aggregate([
eventFactory.start('script', 0),
eventFactory.start('gc', 1, {'usedHeapSize': 2500}),
eventFactory.end('gc', 3, {'usedHeapSize': 1000, 'majorGc': false}),
eventFactory.end('script', 5),
]).then((data) => {
expect(data['gcTimeInScript']).toBe(2);
expect(data['gcTime']).toBe(2);
expect(data['pureScriptTime']).toBe(3);
expect(data['scriptTime']).toBe(5);
done();
});
});
it('should support pureScriptTime = scriptTime-gcTime-renderTime', (done) => {
aggregate([
eventFactory.start('script', 0),
eventFactory.start('gc', 1, {'usedHeapSize': 1000}),
eventFactory.end('gc', 4, {'usedHeapSize': 0}),
eventFactory.start('render', 4),
eventFactory.end('render', 5),
eventFactory.end('script', 6),
]).then((data) => {
expect(data['scriptTime']).toBe(6);
expect(data['pureScriptTime']).toBe(2);
done();
});
});
describe('receivedData', () => {
it('should report received data since last navigationStart', (done) => {
aggregate(
[
eventFactory.instant('receivedData', 0, {'encodedDataLength': 1}),
eventFactory.instant('navigationStart', 1),
eventFactory.instant('receivedData', 2, {'encodedDataLength': 2}),
eventFactory.instant('navigationStart', 3),
eventFactory.instant('receivedData', 4, {'encodedDataLength': 4}),
eventFactory.instant('receivedData', 5, {'encodedDataLength': 8}),
],
{receivedData: true},
).then((data) => {
expect(data['receivedData']).toBe(12);
done();
});
});
});
describe('requestCount', () => {
it('should report count of requests sent since last navigationStart', (done) => {
aggregate(
[
eventFactory.instant('sendRequest', 0),
eventFactory.instant('navigationStart', 1),
eventFactory.instant('sendRequest', 2),
eventFactory.instant('navigationStart', 3),
eventFactory.instant('sendRequest', 4),
eventFactory.instant('sendRequest', 5),
],
{requestCount: true},
).then((data) => {
expect(data['requestCount']).toBe(2);
done();
});
});
});
describe('microMetrics', () => {
it('should report micro metrics', (done) => {
aggregate([eventFactory.markStart('mm1', 0), eventFactory.markEnd('mm1', 5)], {
microMetrics: {'mm1': 'micro metric 1'},
}).then((data) => {
expect(data['mm1']).toBe(5.0);
done();
});
});
it('should ignore micro metrics that were not specified', (done) => {
aggregate([eventFactory.markStart('mm1', 0), eventFactory.markEnd('mm1', 5)]).then(
(data) => {
expect(data['mm1']).toBeFalsy();
done();
},
);
});
it('should report micro metric averages', (done) => {
aggregate([eventFactory.markStart('mm1*20', 0), eventFactory.markEnd('mm1*20', 5)], {
microMetrics: {'mm1': 'micro metric 1'},
}).then((data) => {
expect(data['mm1']).toBe(5 / 20);
done();
});
});
});
});
});
})();
class MockDriverExtension extends WebDriverExtension {
constructor(
private _perfLogs: any[],
private _commandLog: any[],
private _perfLogFeatures: PerfLogFeatures,
) {
super();
}
override timeBegin(name: string): Promise<any> {
this._commandLog.push(['timeBegin', name]);
return Promise.resolve(null);
}
override timeEnd(name: string, restartName: string | null): Promise<any> {
this._commandLog.push(['timeEnd', name, restartName]);
return Promise.resolve(null);
}
override perfLogFeatures(): PerfLogFeatures {
return this._perfLogFeatures;
}
override readPerfLog(): Promise<any> {
this._commandLog.push('readPerfLog');
if (this._perfLogs.length > 0) {
const next = this._perfLogs[0];
this._perfLogs.shift();
return Promise.resolve(next);
} else {
return Promise.resolve([]);
}
}
override gc(): Promise<any> {
this._commandLog.push(['gc']);
return Promise.resolve(null);
}
} | {
"end_byte": 28036,
"start_byte": 22135,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/metric/perflog_metric_spec.ts"
} |
angular/packages/benchpress/test/metric/multi_metric_spec.ts_0_2084 | /**
* @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 {Injector, Metric, MultiMetric} from '../../index';
(function () {
function createMetric(ids: any[]) {
const m = Injector.create({
providers: [
ids.map((id) => ({provide: id, useValue: new MockMetric(id)})),
MultiMetric.provideWith(ids),
],
}).get<MultiMetric>(MultiMetric);
return Promise.resolve(m);
}
describe('multi metric', () => {
it('should merge descriptions', (done) => {
createMetric(['m1', 'm2']).then((m) => {
expect(m.describe()).toEqual({'m1': 'describe', 'm2': 'describe'});
done();
});
});
it('should merge all beginMeasure calls', (done) => {
createMetric(['m1', 'm2'])
.then((m) => m.beginMeasure())
.then((values) => {
expect(values).toEqual(['m1_beginMeasure', 'm2_beginMeasure']);
done();
});
});
[false, true].forEach((restartFlag) => {
it(`should merge all endMeasure calls for restart=${restartFlag}`, (done) => {
createMetric(['m1', 'm2'])
.then((m) => m.endMeasure(restartFlag))
.then((values) => {
expect(values).toEqual({
'm1': {'restart': restartFlag},
'm2': {'restart': restartFlag},
});
done();
});
});
});
});
})();
class MockMetric extends Metric {
constructor(private _id: string) {
super();
}
override beginMeasure(): Promise<string> {
return Promise.resolve(`${this._id}_beginMeasure`);
}
override endMeasure(restart: boolean): Promise<{[key: string]: any}> {
const result: {[key: string]: any} = {};
result[this._id] = {'restart': restart};
return Promise.resolve(result);
}
override describe(): {[key: string]: string} {
const result: {[key: string]: string} = {};
result[this._id] = 'describe';
return result;
}
}
| {
"end_byte": 2084,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/metric/multi_metric_spec.ts"
} |
angular/packages/benchpress/test/metric/user_metric_spec.ts_0_2742 | /**
* @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 {Injector, StaticProvider} from '@angular/core';
import {Options, PerfLogEvent, PerfLogFeatures, UserMetric, WebDriverAdapter} from '../../index';
(function () {
let wdAdapter: MockDriverAdapter;
function createMetric(
perfLogs: PerfLogEvent[],
perfLogFeatures: PerfLogFeatures,
{userMetrics}: {userMetrics?: {[key: string]: string}} = {},
): UserMetric {
if (!perfLogFeatures) {
perfLogFeatures = new PerfLogFeatures({
render: true,
gc: true,
frameCapture: true,
userTiming: true,
});
}
if (!userMetrics) {
userMetrics = {};
}
wdAdapter = new MockDriverAdapter();
const providers: StaticProvider[] = [
Options.DEFAULT_PROVIDERS,
UserMetric.PROVIDERS,
{provide: Options.USER_METRICS, useValue: userMetrics},
{provide: WebDriverAdapter, useValue: wdAdapter},
];
return Injector.create({providers}).get(UserMetric);
}
describe('user metric', () => {
it('should describe itself based on userMetrics', () => {
expect(
createMetric([[]], new PerfLogFeatures(), {
userMetrics: {'loadTime': 'time to load'},
}).describe(),
).toEqual({'loadTime': 'time to load'});
});
describe('endMeasure', () => {
it('should stop measuring when all properties have numeric values', (done) => {
const metric = createMetric([[]], new PerfLogFeatures(), {
userMetrics: {'loadTime': 'time to load', 'content': 'time to see content'},
});
metric
.beginMeasure()
.then(() => metric.endMeasure(true))
.then((values) => {
expect(values['loadTime']).toBe(25);
expect(values['content']).toBe(250);
done();
});
wdAdapter.data['loadTime'] = 25;
// Wait before setting 2nd property.
setTimeout(() => {
wdAdapter.data['content'] = 250;
}, 50);
}, 600);
});
});
})();
class MockDriverAdapter extends WebDriverAdapter {
data: any = {};
override executeScript(script: string): any {
// Just handles `return window.propName` ignores `delete window.propName`.
if (script.indexOf('return window.') == 0) {
const metricName = script.substring('return window.'.length);
return Promise.resolve(this.data[metricName]);
} else if (script.indexOf('delete window.') == 0) {
return Promise.resolve(null);
} else {
return Promise.reject(`Unexpected syntax: ${script}`);
}
}
}
| {
"end_byte": 2742,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/test/metric/user_metric_spec.ts"
} |
angular/packages/benchpress/src/statistic.ts_0_1304 | /**
* @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 class Statistic {
static calculateCoefficientOfVariation(sample: number[], mean: number) {
return (Statistic.calculateStandardDeviation(sample, mean) / mean) * 100;
}
static calculateMean(samples: number[]) {
let total = 0;
// TODO: use reduce
samples.forEach((x) => (total += x));
return total / samples.length;
}
static calculateStandardDeviation(samples: number[], mean: number) {
let deviation = 0;
// TODO: use reduce
samples.forEach((x) => (deviation += Math.pow(x - mean, 2)));
deviation = deviation / samples.length;
deviation = Math.sqrt(deviation);
return deviation;
}
static calculateRegressionSlope(
xValues: number[],
xMean: number,
yValues: number[],
yMean: number,
) {
// See https://en.wikipedia.org/wiki/Simple_linear_regression
let dividendSum = 0;
let divisorSum = 0;
for (let i = 0; i < xValues.length; i++) {
dividendSum += (xValues[i] - xMean) * (yValues[i] - yMean);
divisorSum += Math.pow(xValues[i] - xMean, 2);
}
return dividendSum / divisorSum;
}
}
| {
"end_byte": 1304,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/statistic.ts"
} |
angular/packages/benchpress/src/sampler.ts_0_3365 | /**
* @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 {Inject, Injectable, StaticProvider} from '@angular/core';
import {Options} from './common_options';
import {MeasureValues} from './measure_values';
import {Metric} from './metric';
import {Reporter} from './reporter';
import {Validator} from './validator';
import {WebDriverAdapter} from './web_driver_adapter';
/**
* The Sampler owns the sample loop:
* 1. calls the prepare/execute callbacks,
* 2. gets data from the metric
* 3. asks the validator for a valid sample
* 4. reports the new data to the reporter
* 5. loop until there is a valid sample
*/
@Injectable()
export class Sampler {
static PROVIDERS = <StaticProvider[]>[
{
provide: Sampler,
deps: [
WebDriverAdapter,
Metric,
Reporter,
Validator,
Options.PREPARE,
Options.EXECUTE,
Options.NOW,
],
},
];
constructor(
private _driver: WebDriverAdapter,
private _metric: Metric,
private _reporter: Reporter,
private _validator: Validator,
@Inject(Options.PREPARE) private _prepare: Function,
@Inject(Options.EXECUTE) private _execute: Function,
@Inject(Options.NOW) private _now: Function,
) {}
sample(): Promise<SampleState> {
const loop = (lastState: SampleState): Promise<SampleState> => {
return this._iterate(lastState).then((newState) => {
if (newState.validSample != null) {
return newState;
} else {
return loop(newState);
}
});
};
return loop(new SampleState([], null));
}
private _iterate(lastState: SampleState): Promise<SampleState> {
let resultPromise: Promise<SampleState | null>;
if (this._prepare !== Options.NO_PREPARE) {
resultPromise = this._driver.waitFor(this._prepare);
} else {
resultPromise = Promise.resolve(null);
}
if (this._prepare !== Options.NO_PREPARE || lastState.completeSample.length === 0) {
resultPromise = resultPromise.then((_) => this._metric.beginMeasure());
}
return resultPromise
.then((_) => this._driver.waitFor(this._execute))
.then((_) => this._metric.endMeasure(this._prepare === Options.NO_PREPARE))
.then((measureValues) => {
if (!!measureValues['invalid']) {
return lastState;
}
return this._report(lastState, measureValues);
});
}
private _report(state: SampleState, metricValues: {[key: string]: any}): Promise<SampleState> {
const measureValues = new MeasureValues(state.completeSample.length, this._now(), metricValues);
const completeSample = state.completeSample.concat([measureValues]);
const validSample = this._validator.validate(completeSample);
let resultPromise = this._reporter.reportMeasureValues(measureValues);
if (validSample != null) {
resultPromise = resultPromise.then((_) =>
this._reporter.reportSample(completeSample, validSample),
);
}
return resultPromise.then((_) => new SampleState(completeSample, validSample));
}
}
export class SampleState {
constructor(
public completeSample: MeasureValues[],
public validSample: MeasureValues[] | null,
) {}
}
| {
"end_byte": 3365,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/sampler.ts"
} |
angular/packages/benchpress/src/web_driver_adapter.ts_0_849 | /**
* @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 WebDriverAdapter bridges API differences between different WebDriver clients,
* e.g. JS vs Dart Async vs Dart Sync webdriver.
* Needs one implementation for every supported WebDriver client.
*/
export abstract class WebDriverAdapter {
waitFor(callback: Function): Promise<any> {
throw new Error('NYI');
}
executeScript(script: string): Promise<any> {
throw new Error('NYI');
}
executeAsyncScript(script: string): Promise<any> {
throw new Error('NYI');
}
capabilities(): Promise<{[key: string]: any}> {
throw new Error('NYI');
}
logs(type: string): Promise<any[]> {
throw new Error('NYI');
}
}
| {
"end_byte": 849,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/web_driver_adapter.ts"
} |
angular/packages/benchpress/src/web_driver_extension.ts_0_3116 | /**
* @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 {InjectionToken, Injector} from '@angular/core';
import {Options} from './common_options';
export type PerfLogEvent = {
[key: string]: any;
} & {
ph?: 'X' | 'B' | 'E' | 'I';
ts?: number;
dur?: number;
name?: string;
pid?: string;
args?: {
encodedDataLength?: number;
usedHeapSize?: number;
gcAmount?: number;
majorGc?: boolean;
url?: string;
method?: string;
};
};
/**
* A WebDriverExtension implements extended commands of the webdriver protocol
* for a given browser, independent of the WebDriverAdapter.
* Needs one implementation for every supported Browser.
*/
export abstract class WebDriverExtension {
static provideFirstSupported(childTokens: any[]): any[] {
const res = [
{
provide: _CHILDREN,
useFactory: (injector: Injector) => childTokens.map((token) => injector.get(token)),
deps: [Injector],
},
{
provide: WebDriverExtension,
useFactory: (children: WebDriverExtension[], capabilities: {[key: string]: any}) => {
let delegate: WebDriverExtension = undefined!;
children.forEach((extension) => {
if (extension.supports(capabilities)) {
delegate = extension;
}
});
if (!delegate) {
throw new Error('Could not find a delegate for given capabilities!');
}
return delegate;
},
deps: [_CHILDREN, Options.CAPABILITIES],
},
];
return res;
}
gc(): Promise<any> {
throw new Error('NYI');
}
timeBegin(name: string): Promise<any> {
throw new Error('NYI');
}
timeEnd(name: string, restartName: string | null): Promise<any> {
throw new Error('NYI');
}
/**
* Format:
* - cat: category of the event
* - name: event name: 'script', 'gc', 'render', ...
* - ph: phase: 'B' (begin), 'E' (end), 'X' (Complete event), 'I' (Instant event)
* - ts: timestamp in ms, e.g. 12345
* - pid: process id
* - args: arguments, e.g. {heapSize: 1234}
*
* Based on [Chrome Trace Event
*Format](https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU/edit)
**/
readPerfLog(): Promise<PerfLogEvent[]> {
throw new Error('NYI');
}
perfLogFeatures(): PerfLogFeatures {
throw new Error('NYI');
}
supports(capabilities: {[key: string]: any}): boolean {
return true;
}
}
export class PerfLogFeatures {
render: boolean;
gc: boolean;
frameCapture: boolean;
userTiming: boolean;
constructor({
render = false,
gc = false,
frameCapture = false,
userTiming = false,
}: {render?: boolean; gc?: boolean; frameCapture?: boolean; userTiming?: boolean} = {}) {
this.render = render;
this.gc = gc;
this.frameCapture = frameCapture;
this.userTiming = userTiming;
}
}
const _CHILDREN = new InjectionToken('WebDriverExtension.children');
| {
"end_byte": 3116,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/web_driver_extension.ts"
} |
angular/packages/benchpress/src/metric.ts_0_785 | /**
* @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 metric is measures values
*/
export abstract class Metric {
/**
* Starts measuring
*/
beginMeasure(): Promise<any> {
throw new Error('NYI');
}
/**
* Ends measuring and reports the data
* since the begin call.
* @param restart: Whether to restart right after this.
*/
endMeasure(restart: boolean): Promise<{[key: string]: any}> {
throw new Error('NYI');
}
/**
* Describes the metrics provided by this metric implementation.
* (e.g. units, ...)
*/
describe(): {[key: string]: string} {
throw new Error('NYI');
}
}
| {
"end_byte": 785,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/metric.ts"
} |
angular/packages/benchpress/src/sample_description.ts_0_788 | /**
* @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
*/
/**
* SampleDescription merges all available descriptions about a sample
*/
export class SampleDescription {
description: {[key: string]: any};
constructor(
public id: string,
descriptions: Array<{[key: string]: any}>,
public metrics: {[key: string]: any},
) {
this.description = {};
descriptions.forEach((description) => {
Object.keys(description).forEach((prop) => {
this.description[prop] = description[prop];
});
});
}
toJson() {
return {'id': this.id, 'description': this.description, 'metrics': this.metrics};
}
}
| {
"end_byte": 788,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/sample_description.ts"
} |
angular/packages/benchpress/src/common_options.ts_0_2371 | /**
* @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 {InjectionToken} from '@angular/core';
import * as fs from 'fs';
export class Options {
static SAMPLE_ID = new InjectionToken('Options.sampleId');
static DEFAULT_DESCRIPTION = new InjectionToken('Options.defaultDescription');
static SAMPLE_DESCRIPTION = new InjectionToken('Options.sampleDescription');
static FORCE_GC = new InjectionToken('Options.forceGc');
static NO_PREPARE = () => true;
static PREPARE = new InjectionToken('Options.prepare');
static EXECUTE = new InjectionToken('Options.execute');
static CAPABILITIES = new InjectionToken('Options.capabilities');
static USER_AGENT = new InjectionToken('Options.userAgent');
static MICRO_METRICS = new InjectionToken('Options.microMetrics');
static USER_METRICS = new InjectionToken('Options.userMetrics');
static NOW = new InjectionToken('Options.now');
static WRITE_FILE = new InjectionToken('Options.writeFile');
static RECEIVED_DATA = new InjectionToken('Options.receivedData');
static REQUEST_COUNT = new InjectionToken('Options.requestCount');
static CAPTURE_FRAMES = new InjectionToken('Options.frameCapture');
static RAW_PERFLOG_PATH = new InjectionToken('Options.rawPerflogPath');
static DEFAULT_PROVIDERS = [
{provide: Options.DEFAULT_DESCRIPTION, useValue: {}},
{provide: Options.SAMPLE_DESCRIPTION, useValue: {}},
{provide: Options.FORCE_GC, useValue: false},
{provide: Options.PREPARE, useValue: Options.NO_PREPARE},
{provide: Options.MICRO_METRICS, useValue: {}},
{provide: Options.USER_METRICS, useValue: {}},
{provide: Options.NOW, useValue: () => new Date()},
{provide: Options.RECEIVED_DATA, useValue: false},
{provide: Options.REQUEST_COUNT, useValue: false},
{provide: Options.CAPTURE_FRAMES, useValue: false},
{provide: Options.WRITE_FILE, useValue: writeFile},
{provide: Options.RAW_PERFLOG_PATH, useValue: null},
];
}
function writeFile(filename: string, content: string): Promise<any> {
return new Promise<void>(function (resolve, reject) {
fs.writeFile(filename, content, (error) => {
if (error) {
reject(error);
} else {
resolve();
}
});
});
}
| {
"end_byte": 2371,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/common_options.ts"
} |
angular/packages/benchpress/src/reporter.ts_0_575 | /**
* @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 {MeasureValues} from './measure_values';
/**
* A reporter reports measure values and the valid sample.
*/
export abstract class Reporter {
reportMeasureValues(values: MeasureValues): Promise<any> {
throw new Error('NYI');
}
reportSample(completeSample: MeasureValues[], validSample: MeasureValues[]): Promise<any> {
throw new Error('NYI');
}
}
| {
"end_byte": 575,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/reporter.ts"
} |
angular/packages/benchpress/src/sample_description_providers.ts_0_1313 | /**
* @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
*/
// Note: The providers are split into a separate file to avoid
// introducing a transitive dependency on the DI injection code
// from `@angular/core` whenever scripts like the benchmark compare script
// attempt to just use the `JsonReport` type.
import {Options} from './common_options';
import {Metric} from './metric';
import {SampleDescription} from './sample_description';
import {Validator} from './validator';
export const sampleDescriptionProviders = [
{
provide: SampleDescription,
useFactory: (
metric: Metric,
id: string,
forceGc: boolean,
userAgent: string,
validator: Validator,
defaultDesc: {[key: string]: string},
userDesc: {[key: string]: string},
) =>
new SampleDescription(
id,
[{'forceGc': forceGc, 'userAgent': userAgent}, validator.describe(), defaultDesc, userDesc],
metric.describe(),
),
deps: [
Metric,
Options.SAMPLE_ID,
Options.FORCE_GC,
Options.USER_AGENT,
Validator,
Options.DEFAULT_DESCRIPTION,
Options.SAMPLE_DESCRIPTION,
],
},
];
| {
"end_byte": 1313,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/sample_description_providers.ts"
} |
angular/packages/benchpress/src/runner.ts_0_4397 | /**
* @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 {Injector, StaticProvider} from '@angular/core';
import {Options} from './common_options';
import {Metric} from './metric';
import {MultiMetric} from './metric/multi_metric';
import {PerflogMetric} from './metric/perflog_metric';
import {UserMetric} from './metric/user_metric';
import {Reporter} from './reporter';
import {ConsoleReporter} from './reporter/console_reporter';
import {MultiReporter} from './reporter/multi_reporter';
import {sampleDescriptionProviders} from './sample_description_providers';
import {Sampler, SampleState} from './sampler';
import {Validator} from './validator';
import {RegressionSlopeValidator} from './validator/regression_slope_validator';
import {SizeValidator} from './validator/size_validator';
import {WebDriverAdapter} from './web_driver_adapter';
import {WebDriverExtension} from './web_driver_extension';
import {ChromeDriverExtension} from './webdriver/chrome_driver_extension';
import {FirefoxDriverExtension} from './webdriver/firefox_driver_extension';
import {IOsDriverExtension} from './webdriver/ios_driver_extension';
/**
* The Runner is the main entry point for executing a sample run.
* It provides defaults, creates the injector and calls the sampler.
*/
export class Runner {
constructor(private _defaultProviders: StaticProvider[] = []) {}
sample({
id,
execute,
prepare,
microMetrics,
providers,
userMetrics,
}: {
id: string;
execute?: Function;
prepare?: Function;
microMetrics?: {[key: string]: string};
providers?: StaticProvider[];
userMetrics?: {[key: string]: string};
}): Promise<SampleState> {
const sampleProviders: StaticProvider[] = [
_DEFAULT_PROVIDERS,
this._defaultProviders,
{provide: Options.SAMPLE_ID, useValue: id},
{provide: Options.EXECUTE, useValue: execute},
];
if (prepare != null) {
sampleProviders.push({provide: Options.PREPARE, useValue: prepare});
}
if (microMetrics != null) {
sampleProviders.push({provide: Options.MICRO_METRICS, useValue: microMetrics});
}
if (userMetrics != null) {
sampleProviders.push({provide: Options.USER_METRICS, useValue: userMetrics});
}
if (providers != null) {
sampleProviders.push(providers);
}
const inj = Injector.create({providers: sampleProviders});
const adapter: WebDriverAdapter = inj.get(WebDriverAdapter);
return Promise.all([
adapter.capabilities(),
adapter.executeScript('return window.navigator.userAgent;'),
]).then((args) => {
const capabilities = args[0];
const userAgent = args[1];
// This might still create instances twice. We are creating a new injector with all the
// providers.
// Only WebDriverAdapter is reused.
// TODO(vsavkin): consider changing it when toAsyncFactory is added back or when child
// injectors are handled better.
const injector = Injector.create({
providers: [
sampleProviders,
{provide: Options.CAPABILITIES, useValue: capabilities},
{provide: Options.USER_AGENT, useValue: userAgent},
{provide: WebDriverAdapter, useValue: adapter},
],
});
// TODO: With TypeScript 2.5 injector.get does not infer correctly the
// return type. Remove 'any' and investigate the issue.
const sampler = injector.get(Sampler) as any;
return sampler.sample();
});
}
}
const _DEFAULT_PROVIDERS = [
Options.DEFAULT_PROVIDERS,
Sampler.PROVIDERS,
ConsoleReporter.PROVIDERS,
RegressionSlopeValidator.PROVIDERS,
SizeValidator.PROVIDERS,
ChromeDriverExtension.PROVIDERS,
FirefoxDriverExtension.PROVIDERS,
IOsDriverExtension.PROVIDERS,
PerflogMetric.PROVIDERS,
UserMetric.PROVIDERS,
sampleDescriptionProviders,
MultiReporter.provideWith([ConsoleReporter]),
MultiMetric.provideWith([PerflogMetric, UserMetric]),
{provide: Reporter, useExisting: MultiReporter},
{provide: Validator, useExisting: RegressionSlopeValidator},
WebDriverExtension.provideFirstSupported([
ChromeDriverExtension,
FirefoxDriverExtension,
IOsDriverExtension,
]),
{provide: Metric, useExisting: MultiMetric},
];
| {
"end_byte": 4397,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/runner.ts"
} |
angular/packages/benchpress/src/measure_values.ts_0_499 | /**
* @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 class MeasureValues {
constructor(
public runIndex: number,
public timeStamp: Date,
public values: {[key: string]: any},
) {}
toJson() {
return {
'timeStamp': this.timeStamp.toJSON(),
'runIndex': this.runIndex,
'values': this.values,
};
}
}
| {
"end_byte": 499,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/measure_values.ts"
} |
angular/packages/benchpress/src/validator.ts_0_823 | /**
* @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 {MeasureValues} from './measure_values';
/**
* A Validator calculates a valid sample out of the complete sample.
* A valid sample is a sample that represents the population that should be observed
* in the correct way.
*/
export abstract class Validator {
/**
* Calculates a valid sample out of the complete sample
*/
validate(completeSample: MeasureValues[]): MeasureValues[] | null {
throw new Error('NYI');
}
/**
* Returns a Map that describes the properties of the validator
* (e.g. sample size, ...)
*/
describe(): {[key: string]: any} {
throw new Error('NYI');
}
}
| {
"end_byte": 823,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/validator.ts"
} |
angular/packages/benchpress/src/validator/regression_slope_validator.ts_0_2302 | /**
* @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 {Inject, Injectable, InjectionToken} from '@angular/core';
import {MeasureValues} from '../measure_values';
import {Statistic} from '../statistic';
import {Validator} from '../validator';
/**
* A validator that checks the regression slope of a specific metric.
* Waits for the regression slope to be >=0.
*/
@Injectable()
export class RegressionSlopeValidator extends Validator {
static SAMPLE_SIZE = new InjectionToken('RegressionSlopeValidator.sampleSize');
static METRIC = new InjectionToken('RegressionSlopeValidator.metric');
static PROVIDERS = [
{
provide: RegressionSlopeValidator,
deps: [RegressionSlopeValidator.SAMPLE_SIZE, RegressionSlopeValidator.METRIC],
},
{provide: RegressionSlopeValidator.SAMPLE_SIZE, useValue: 10},
{provide: RegressionSlopeValidator.METRIC, useValue: 'scriptTime'},
];
constructor(
@Inject(RegressionSlopeValidator.SAMPLE_SIZE) private _sampleSize: number,
@Inject(RegressionSlopeValidator.METRIC) private _metric: string,
) {
super();
}
override describe(): {[key: string]: any} {
return {'sampleSize': this._sampleSize, 'regressionSlopeMetric': this._metric};
}
override validate(completeSample: MeasureValues[]): MeasureValues[] | null {
if (completeSample.length >= this._sampleSize) {
const latestSample = completeSample.slice(
completeSample.length - this._sampleSize,
completeSample.length,
);
const xValues: number[] = [];
const yValues: number[] = [];
for (let i = 0; i < latestSample.length; i++) {
// For now, we only use the array index as x value.
// TODO(tbosch): think about whether we should use time here instead
xValues.push(i);
yValues.push(latestSample[i].values[this._metric]);
}
const regressionSlope = Statistic.calculateRegressionSlope(
xValues,
Statistic.calculateMean(xValues),
yValues,
Statistic.calculateMean(yValues),
);
return regressionSlope >= 0 ? latestSample : null;
} else {
return null;
}
}
}
| {
"end_byte": 2302,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/validator/regression_slope_validator.ts"
} |
angular/packages/benchpress/src/validator/size_validator.ts_0_1186 | /**
* @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 {Inject, Injectable, InjectionToken} from '@angular/core';
import {MeasureValues} from '../measure_values';
import {Validator} from '../validator';
/**
* A validator that waits for the sample to have a certain size.
*/
@Injectable()
export class SizeValidator extends Validator {
static SAMPLE_SIZE = new InjectionToken('SizeValidator.sampleSize');
static PROVIDERS = [
{provide: SizeValidator, deps: [SizeValidator.SAMPLE_SIZE]},
{provide: SizeValidator.SAMPLE_SIZE, useValue: 10},
];
constructor(@Inject(SizeValidator.SAMPLE_SIZE) private _sampleSize: number) {
super();
}
override describe(): {[key: string]: any} {
return {'sampleSize': this._sampleSize};
}
override validate(completeSample: MeasureValues[]): MeasureValues[] | null {
if (completeSample.length >= this._sampleSize) {
return completeSample.slice(completeSample.length - this._sampleSize, completeSample.length);
} else {
return null;
}
}
}
| {
"end_byte": 1186,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/validator/size_validator.ts"
} |
angular/packages/benchpress/src/reporter/console_reporter.ts_0_1817 | /**
* @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 {Inject, Injectable, InjectionToken} from '@angular/core';
import {MeasureValues} from '../measure_values';
import {Reporter} from '../reporter';
import {SampleDescription} from '../sample_description';
import {COLUMN_WIDTH, defaultColumnWidth, TextReporterBase} from './text_reporter_base';
/**
* A reporter for the console
*/
@Injectable()
export class ConsoleReporter extends Reporter {
static PRINT = new InjectionToken('ConsoleReporter.print');
static PROVIDERS = [
{provide: ConsoleReporter, deps: [COLUMN_WIDTH, SampleDescription, ConsoleReporter.PRINT]},
{provide: COLUMN_WIDTH, useValue: defaultColumnWidth},
{
provide: ConsoleReporter.PRINT,
useValue: function (v: any) {
// tslint:disable-next-line:no-console
console.log(v);
},
},
];
private textReporter = new TextReporterBase(this._columnWidth, this._sampleDescription);
constructor(
@Inject(COLUMN_WIDTH) private _columnWidth: number,
private _sampleDescription: SampleDescription,
@Inject(ConsoleReporter.PRINT) private _print: Function,
) {
super();
this._print(this.textReporter.description());
}
override reportMeasureValues(measureValues: MeasureValues): Promise<any> {
this._print(this.textReporter.sampleMetrics(measureValues));
return Promise.resolve(null);
}
override reportSample(
_completeSample: MeasureValues[],
validSamples: MeasureValues[],
): Promise<any> {
this._print(this.textReporter.separator());
this._print(this.textReporter.sampleStats(validSamples));
return Promise.resolve(null);
}
}
| {
"end_byte": 1817,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/reporter/console_reporter.ts"
} |
angular/packages/benchpress/src/reporter/util.ts_0_968 | /**
* @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 {MeasureValues} from '../measure_values';
import {Statistic} from '../statistic';
export function formatNum(n: number) {
return n.toFixed(2);
}
export function sortedProps(obj: {[key: string]: any}) {
return Object.keys(obj).sort();
}
export function formatStats(validSamples: MeasureValues[], metricName: string): string {
const samples = validSamples.map((measureValues) => measureValues.values[metricName]);
const mean = Statistic.calculateMean(samples);
const cv = Statistic.calculateCoefficientOfVariation(samples, mean);
const formattedMean = formatNum(mean);
// Note: Don't use the unicode character for +- as it might cause
// hickups for consoles...
return isNaN(cv) ? formattedMean : `${formattedMean}+-${Math.floor(cv)}%`;
}
| {
"end_byte": 968,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/reporter/util.ts"
} |
angular/packages/benchpress/src/reporter/json_file_reporter_types.ts_0_550 | /**
* @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 {MeasureValues} from '../measure_values';
import {SampleDescription} from '../sample_description';
export interface JsonReport {
description: SampleDescription;
metricsText: string;
stats: {[k: string]: string};
statsText: string;
completeSample: MeasureValues[];
validSample: MeasureValues[];
validSampleTexts: string[];
}
| {
"end_byte": 550,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/reporter/json_file_reporter_types.ts"
} |
angular/packages/benchpress/src/reporter/multi_reporter.ts_0_1338 | /**
* @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 {InjectionToken, Injector} from '@angular/core';
import {MeasureValues} from '../measure_values';
import {Reporter} from '../reporter';
export class MultiReporter extends Reporter {
static provideWith(childTokens: any[]): any[] {
return [
{
provide: _CHILDREN,
useFactory: (injector: Injector) => childTokens.map((token) => injector.get(token)),
deps: [Injector],
},
{
provide: MultiReporter,
useFactory: (children: Reporter[]) => new MultiReporter(children),
deps: [_CHILDREN],
},
];
}
constructor(private _reporters: Reporter[]) {
super();
}
override reportMeasureValues(values: MeasureValues): Promise<any[]> {
return Promise.all(this._reporters.map((reporter) => reporter.reportMeasureValues(values)));
}
override reportSample(
completeSample: MeasureValues[],
validSample: MeasureValues[],
): Promise<any[]> {
return Promise.all(
this._reporters.map((reporter) => reporter.reportSample(completeSample, validSample)),
);
}
}
const _CHILDREN = new InjectionToken('MultiReporter.children');
| {
"end_byte": 1338,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/benchpress/src/reporter/multi_reporter.ts"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.