Skip to content
This repository was archived by the owner on Apr 4, 2025. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
transformJavascript,
} from '../helpers/transform-javascript';
import { getFoldFileTransformer } from '../transforms/class-fold';
import { getForcePureCallTransformer, testForcePureCall } from '../transforms/force-pure-call';
import { getImportTslibTransformer, testImportTslib } from '../transforms/import-tslib';
import { getPrefixClassesTransformer, testPrefixClasses } from '../transforms/prefix-classes';
import { getPrefixFunctionsTransformer } from '../transforms/prefix-functions';
Expand Down Expand Up @@ -141,6 +142,10 @@ export function buildOptimizer(options: BuildOptimizerOptions): TransformJavascr
getTransforms.unshift(getWrapEnumsTransformer);
}

if (testForcePureCall(content)) {
getTransforms.unshift(getForcePureCallTransformer);
}

const transformJavascriptOpts: TransformJavascriptOptions = {
content: content,
inputFilePath: options.inputFilePath,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,31 +11,45 @@ import { join } from 'path';
import { buildOptimizer } from './build-optimizer';


if (process.argv.length < 3 || process.argv.length > 4) {
if (process.argv.length < 3 || process.argv.length > 5) {
throw new Error(`
build-optimizer should be called with either one or two arguments:

build-optimizer input.js
build-optimizer input.js output.js

An additional '--side-effects-free' flag can be used after other arguments to force
optimizations for side effect free modules.

By default the side effect free optimizations are only applied to Angular modules via a regex
based path whitelist (e.g. /[\\/]node_modules[\\/]@angular[\\/]core[\\/]/ ).
`);
}

const currentDir = process.cwd();

const inputFile = process.argv[2];
const tsOrJsRegExp = /\.(j|t)s$/;
const sideEffectFreeFlag = '--side-effect-free';
let isSideEffectFree = false;

if (!inputFile.match(tsOrJsRegExp)) {
throw new Error(`Input file must be .js or .ts.`);
}

if (process.argv[3] === sideEffectFreeFlag || process.argv[4] === sideEffectFreeFlag) {
process.argv.pop();
isSideEffectFree = true;
}

// Use provided output file, or add the .bo suffix before the extension.
const outputFile = process.argv[3] || inputFile.replace(tsOrJsRegExp, (subStr) => `.bo${subStr}`);

const boOutput = buildOptimizer({
inputFilePath: join(currentDir, inputFile),
outputFilePath: join(currentDir, outputFile),
emitSourceMap: true,
isSideEffectFree,
});

if (boOutput.emitSkipped) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import * as ts from 'typescript';


const pureFunctionComment = '@__PURE__';
const callExprWhitelist = [
'makeDecorator',
'makePropDecorator',
'makeParamDecorator',
'makeMetadataCtor',

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of listing them here, would it not be better to to leave some kind of comment in the original source code which would mark the function as pure? This way as functions are discovered they can be added automatically not just by Angular team but by application developers?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see this is a hack for the

But it sounds like from reading the Issue that the comment is there but it is in a wrong location?

];

export function testForcePureCall(content: string) {
// Should match be /\/\*@__PURE__\*\/ (makeDecorator|etc)\(/, where 'etc' is all others in the
// whitelist, separated by '|';
const regex = [
/\/\*@__PURE__\*\/ /,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

#__PURE__ is also valid per https://github.com/mishoo/UglifyJS2

`(${callExprWhitelist.join('|')})`,
/\(/,
].map(x => typeof x === 'string' ? x : x.source).join('');

return new RegExp(regex).test(content);
}

// This transform exists as a workaround for the following TS issues:
// - https://github.com/Microsoft/TypeScript/issues/17689
// - https://github.com/Microsoft/TypeScript/issues/17606
// It forces call expressions in a whitelist to have a leading PURE comment.
// Once TS fixes this problem for call expressions, Build Optimizer should be updated and this
// transform removed.
export function getForcePureCallTransformer(): ts.TransformerFactory<ts.SourceFile> {
return (context: ts.TransformationContext): ts.Transformer<ts.SourceFile> => {

const transformer: ts.Transformer<ts.SourceFile> = (sf: ts.SourceFile) => {

const visitor: ts.Visitor = (node: ts.Node): ts.Node => {

// Check if node is a TS whitelisted call expression and add comment.
if (isWhitelistedCallExpression(node)) {
const newNode = ts.addSyntheticLeadingComment(
node, ts.SyntaxKind.MultiLineCommentTrivia, pureFunctionComment, false);

// Replace node with modified one.
return ts.visitEachChild(newNode, visitor, context);
}

return ts.visitEachChild(node, visitor, context);
};

return ts.visitEachChild(sf, visitor, context);
};

return transformer;
};
}

function isWhitelistedCallExpression(node: ts.Node) {
if (!ts.isCallExpression(node)) {
return false;
}

if (!ts.isIdentifier(node.expression)) {
return false;
}

if (callExprWhitelist.indexOf(node.expression.text) === -1) {
return false;
}

return true;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import { tags } from '@angular-devkit/core';
import { transformJavascript } from '../helpers/transform-javascript';
import { getForcePureCallTransformer, testForcePureCall } from './force-pure-call';


const transform = (content: string) => transformJavascript(
{ content, getTransforms: [getForcePureCallTransformer] }).content;

describe('force-pure-call', () => {
it('forces pure call on makeDecorator', () => {
const input = tags.stripIndent`
var Component = /*@__PURE__*/ makeDecorator('Component', function (c) {
if (c === void 0) { c = {}; }
return (Object.assign({ changeDetection: ChangeDetectionStrategy.Default }, c));
}, Directive);
`;

expect(testForcePureCall(input)).toBeTruthy();
expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${input}`);
});

it('forces pure call on makeDecorator', () => {
// tslint:disable:max-line-length
const input = tags.stripIndent`
var Input = /*@__PURE__*/ makePropDecorator('Input', function (bindingPropertyName) { return ({ bindingPropertyName: bindingPropertyName }); });
`;

expect(testForcePureCall(input)).toBeTruthy();
expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${input}`);
});

it('forces pure call on makeDecorator', () => {
// tslint:disable:max-line-length
const input = tags.stripIndent`
var Inject = /*@__PURE__*/ makeParamDecorator('Inject', function (token) { return ({ token: token }); });
`;

expect(testForcePureCall(input)).toBeTruthy();
expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${input}`);
});

it('forces pure call on makeDecorator', () => {
const input = tags.stripIndent`
var /** @type {?} */ metaCtor = /*@__PURE__*/ makeMetadataCtor(props);
`;

expect(testForcePureCall(input)).toBeTruthy();
expect(tags.oneLine`${transform(input)}`).toEqual(tags.oneLine`${input}`);
});

it('tests false for files that do not have pure call already', () => {
const input = tags.stripIndent`
var /** @type {?} */ metaCtor = makeMetadataCtor(props);
`;

expect(testForcePureCall(input)).toBeFalsy();
});
});