refactor: remove toplevel property accesses (#29329)

PR Close #29329
This commit is contained in:
Filipe Silva 2019-05-02 16:44:24 +01:00 committed by Jason Aden
parent 739e5a4f53
commit ac34a1429b
32 changed files with 231 additions and 253 deletions

View File

@ -3,7 +3,7 @@
"master": {
"uncompressed": {
"runtime": 1497,
"main": 164945,
"main": 166739,
"polyfills": 43626
}
}

View File

@ -1,14 +1,3 @@
import "@angular/animations";
import "@angular/core";
function isNode() {
return "undefined" !== typeof process;
}
const _isNode = isNode();
if (_isNode || "undefined" !== typeof Element) if (_isNode || Element.prototype.matches) ; else {
const proto = Element.prototype;
const fn = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector;
}

View File

@ -3,14 +3,3 @@ import "tslib";
import "@angular/animations";
import "@angular/core";
function isNode() {
return "undefined" !== typeof process;
}
var _isNode = isNode();
if (_isNode || "undefined" !== typeof Element) if (_isNode || Element.prototype.matches) ; else {
var proto = Element.prototype;
var fn_1 = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector;
}

View File

@ -3,7 +3,3 @@ import "@angular/core";
import "rxjs";
import "rxjs/operators";
const elProto = Element.prototype;
const matches = elProto.matches || elProto.matchesSelector || elProto.mozMatchesSelector || elProto.msMatchesSelector || elProto.oMatchesSelector || elProto.webkitMatchesSelector;

View File

@ -5,7 +5,3 @@ import "@angular/core";
import "rxjs";
import "rxjs/operators";
var elProto = Element.prototype;
var matches = elProto.matches || elProto.matchesSelector || elProto.mozMatchesSelector || elProto.msMatchesSelector || elProto.oMatchesSelector || elProto.webkitMatchesSelector;

View File

@ -1,17 +1,3 @@
import "@angular/common";
import { ɵglobal } from "@angular/core";
let nodeContains;
if (ɵglobal["Node"]) nodeContains = ɵglobal["Node"].prototype.contains || function(node) {
return !!(16 & this.compareDocumentPosition(node));
};
const ɵ0 = function(v) {
return "__zone_symbol__" + v;
};
const __symbol__ = "undefined" !== typeof Zone && Zone["__symbol__"] || ɵ0;
const blackListedEvents = "undefined" !== typeof Zone && Zone[__symbol__("BLACK_LISTED_EVENTS")];
import "@angular/core";

View File

@ -2,18 +2,4 @@ import "tslib";
import "@angular/common";
import { ɵglobal } from "@angular/core";
var nodeContains;
if (ɵglobal["Node"]) nodeContains = ɵglobal["Node"].prototype.contains || function(node) {
return !!(16 & this.compareDocumentPosition(node));
};
var ɵ0 = function(v) {
return "__zone_symbol__" + v;
};
var __symbol__ = "undefined" !== typeof Zone && Zone["__symbol__"] || ɵ0;
var blackListedEvents = "undefined" !== typeof Zone && Zone[__symbol__("BLACK_LISTED_EVENTS")];
import "@angular/core";

View File

@ -155,6 +155,7 @@
"sauce-connect": "https://saucelabs.com/downloads/sc-4.5.1-linux.tar.gz",
"semver": "5.4.1",
"tslint-eslint-rules": "4.1.1",
"tslint-no-toplevel-property-access": "0.0.2",
"tsutils": "2.27.2",
"universal-analytics": "0.4.15",
"vlq": "0.2.2",

View File

@ -34,9 +34,10 @@ export class WebAnimationsStyleNormalizer extends AnimationStyleNormalizer {
}
}
const DIMENSIONAL_PROP_MAP = makeBooleanMap(
const DIMENSIONAL_PROP_MAP =
(() => makeBooleanMap(
'width,height,minWidth,minHeight,maxWidth,maxHeight,left,top,bottom,right,fontSize,outlineWidth,outlineOffset,paddingTop,paddingLeft,paddingBottom,paddingRight,marginTop,marginLeft,marginBottom,marginRight,borderRadius,borderWidth,borderTopWidth,borderLeftWidth,borderRightWidth,borderBottomWidth,textIndent,perspective'
.split(','));
.split(',')))();
function makeBooleanMap(keys: string[]): {[key: string]: boolean} {
const map: {[key: string]: boolean} = {};

View File

@ -158,16 +158,20 @@ if (_isNode || typeof Element !== 'undefined') {
// this is well supported in all browsers
_contains = (elm1: any, elm2: any) => { return elm1.contains(elm2) as boolean; };
_matches = (() => {
if (_isNode || Element.prototype.matches) {
_matches = (element: any, selector: string) => element.matches(selector);
return (element: any, selector: string) => element.matches(selector);
} else {
const proto = Element.prototype as any;
const fn = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector ||
proto.oMatchesSelector || proto.webkitMatchesSelector;
if (fn) {
_matches = (element: any, selector: string) => fn.apply(element, [selector]);
return (element: any, selector: string) => fn.apply(element, [selector]);
} else {
return _matches;
}
}
})();
_query = (element: any, selector: string, multi: boolean): any[] => {
let results: any[] = [];

View File

@ -117,7 +117,6 @@ const enum OptionFlags {
CheckParent = 1 << 2,
Default = CheckSelf | CheckParent
}
const NULL_INJECTOR = Injector.NULL;
const NO_NEW_LINE = 'ɵ';
export class StaticInjector implements Injector {
@ -127,7 +126,7 @@ export class StaticInjector implements Injector {
private _records: Map<any, Record>;
constructor(
providers: StaticProvider[], parent: Injector = NULL_INJECTOR, source: string|null = null) {
providers: StaticProvider[], parent: Injector = Injector.NULL, source: string|null = null) {
this.parent = parent;
this.source = source;
const records = this._records = new Map<any, Record>();
@ -304,7 +303,7 @@ function resolveToken(
records,
// If we don't know how to resolve dependency and we should not check parent for it,
// than pass in Null injector.
!childRecord && !(options & OptionFlags.CheckParent) ? NULL_INJECTOR : parent,
!childRecord && !(options & OptionFlags.CheckParent) ? Injector.NULL : parent,
options & OptionFlags.Optional ? null : Injector.THROW_IF_NOT_FOUND,
InjectFlags.Default));
}

View File

@ -19,6 +19,10 @@ export const EMPTY_ARRAY: any[] = [];
// freezing the values prevents any code from accidentally inserting new values in
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
// These property accesses can be ignored because ngDevMode will be set to false
// when optimizing code and the whole if statement will be dropped.
// tslint:disable-next-line:no-toplevel-property-access
Object.freeze(EMPTY_OBJ);
// tslint:disable-next-line:no-toplevel-property-access
Object.freeze(EMPTY_ARRAY);
}

View File

@ -45,7 +45,7 @@ import {getComponentViewByIndex, getNativeByIndex, getNativeByTNode, getTNode, i
* A permanent marker promise which signifies that the current CD tree is
* clean.
*/
const _CLEAN_PROMISE = Promise.resolve(null);
const _CLEAN_PROMISE = (() => Promise.resolve(null))();
export const enum BindingDirection {
Input,

View File

@ -241,10 +241,10 @@ export class NodeInjectorFactory {
}
}
const FactoryPrototype = NodeInjectorFactory.prototype;
export function isFactory(obj: any): obj is NodeInjectorFactory {
// See: https://jsperf.com/instanceof-vs-getprototypeof
return obj !== null && typeof obj == 'object' && Object.getPrototypeOf(obj) == FactoryPrototype;
return obj !== null && typeof obj == 'object' &&
Object.getPrototypeOf(obj) == NodeInjectorFactory.prototype;
}
// Note: This hack is necessary so we don't erroneously get a circular dependency

View File

@ -17,7 +17,8 @@ import * as sanitization from '../../sanitization/sanitization';
*
* This should be kept up to date with the public exports of @angular/core.
*/
export const angularCoreEnv: {[name: string]: Function} = {
export const angularCoreEnv: {[name: string]: Function} =
(() => ({
'ΔdefineBase': r3.ΔdefineBase,
'ΔdefineComponent': r3.ΔdefineComponent,
'ΔdefineDirective': r3.ΔdefineDirective,
@ -138,4 +139,4 @@ export const angularCoreEnv: {[name: string]: Function} = {
'ΔsanitizeScript': sanitization.ΔsanitizeScript,
'ΔsanitizeUrl': sanitization.ΔsanitizeUrl,
'ΔsanitizeUrlOrResourceUrl': sanitization.ΔsanitizeUrlOrResourceUrl,
};
}))();

View File

@ -48,9 +48,10 @@ export function stringifyForError(value: any) {
export const defaultScheduler =
(() =>
(typeof requestAnimationFrame !== 'undefined' && requestAnimationFrame || // browser only
setTimeout // everything else
).bind(global);
).bind(global))();
/**
*

View File

@ -19,6 +19,10 @@ export const EMPTY_ARRAY: any[] = [];
// freezing the values prevents any code from accidentally inserting new values in
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
// These property accesses can be ignored because ngDevMode will be set to false
// when optimizing code and the whole if statement will be dropped.
// tslint:disable-next-line:no-toplevel-property-access
Object.freeze(EMPTY_OBJ);
// tslint:disable-next-line:no-toplevel-property-access
Object.freeze(EMPTY_ARRAY);
}

View File

@ -6,8 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
const promise: Promise<any> = Promise.resolve(0);
const promise: Promise<any> = (() => Promise.resolve(0))();
declare const Zone: any;

View File

@ -16,8 +16,12 @@ declare global {
* NOTE: changes to the `ngI18nClosureMode` name must be synced with `compiler-cli/src/tooling.ts`.
*/
if (typeof ngI18nClosureMode === 'undefined') {
// These property accesses can be ignored because ngI18nClosureMode will be set to false
// when optimizing code and the whole if statement will be dropped.
// Make sure to refer to ngI18nClosureMode as ['ngI18nClosureMode'] for closure.
// tslint:disable-next-line:no-toplevel-property-access
global['ngI18nClosureMode'] =
// TODO(FW-1250): validate that this actually, you know, works.
// tslint:disable-next-line:no-toplevel-property-access
typeof goog !== 'undefined' && typeof goog.getMsg === 'function';
}

View File

@ -50,9 +50,6 @@
{
"name": "FLAGS"
},
{
"name": "FactoryPrototype"
},
{
"name": "HEADER_OFFSET"
},

View File

@ -41,9 +41,6 @@
{
"name": "FLAGS"
},
{
"name": "FactoryPrototype"
},
{
"name": "HEADER_OFFSET"
},

View File

@ -83,9 +83,6 @@
{
"name": "FLAGS"
},
{
"name": "FactoryPrototype"
},
{
"name": "HEADER_OFFSET"
},

View File

@ -7,9 +7,11 @@
*/
import {ComponentFactoryResolver, Injector, Type} from '@angular/core';
const elProto = Element.prototype as any;
const matches = elProto.matches || elProto.matchesSelector || elProto.mozMatchesSelector ||
const matches = (() => {
const elProto = Element.prototype as any;
return elProto.matches || elProto.matchesSelector || elProto.mozMatchesSelector ||
elProto.msMatchesSelector || elProto.oMatchesSelector || elProto.webkitMatchesSelector;
})();
/**
* Provide methods for scheduling the execution of a callback.

View File

@ -23,7 +23,7 @@ export const formDirectiveProvider: any = {
useExisting: forwardRef(() => NgForm)
};
const resolvedPromise = Promise.resolve(null);
const resolvedPromise = (() => Promise.resolve(null))();
/**
* @description

View File

@ -43,7 +43,7 @@ export const formControlBinding: any = {
* - this is just one extra run no matter how many `ngModel` have been changed.
* - this is a general problem when using `exportAs` for directives!
*/
const resolvedPromise = Promise.resolve(null);
const resolvedPromise = (() => Promise.resolve(null))();
/**
* @description

View File

@ -185,7 +185,7 @@ function urlEncodeParams(params: {[key: string]: any}): URLSearchParams {
const noop = function() {};
const w = typeof window == 'object' ? window : noop;
const FormData = (w as any /** TODO #9100 */)['FormData'] || noop;
const Blob = (w as any /** TODO #9100 */)['Blob'] || noop;
const FormData = (() => (w as any /** TODO #9100 */)['FormData'] || noop)();
const Blob = (() => (w as any /** TODO #9100 */)['Blob'] || noop)();
export const ArrayBuffer: ArrayBufferConstructor =
(w as any /** TODO #9100 */)['ArrayBuffer'] || noop;
(() => (w as any /** TODO #9100 */)['ArrayBuffer'] || noop)();

View File

@ -63,13 +63,15 @@ const _chromeNumKeyPadMap = {
'\x90': 'NumLock'
};
let nodeContains: (a: any, b: any) => boolean;
if (global['Node']) {
nodeContains = global['Node'].prototype.contains || function(node) {
const nodeContains: (a: any, b: any) => boolean = (() => {
if (global['Node']) {
return global['Node'].prototype.contains || function(node: any) {
return !!(this.compareDocumentPosition(node) & 16);
};
}
}
return undefined as any;
})();
/**
* A `DomAdapter` powered by full browser DOM APIs.

View File

@ -6,13 +6,14 @@
* found in the LICENSE file at https://angular.io/license
*/
import * as core from '@angular/core';
import {APP_INITIALIZER, ApplicationRef, DebugNode, NgProbeToken, NgZone, Optional, Provider, getDebugNode} from '@angular/core';
import {exportNgVar} from '../util';
const CORE_TOKENS = {
'ApplicationRef': core.ApplicationRef,
'NgZone': core.NgZone,
};
const CORE_TOKENS = (() => ({
'ApplicationRef': ApplicationRef,
'NgZone': NgZone,
}))();
const INSPECT_GLOBAL_NAME = 'probe';
const CORE_TOKENS_GLOBAL_NAME = 'coreTokens';
@ -22,17 +23,17 @@ const CORE_TOKENS_GLOBAL_NAME = 'coreTokens';
* null if the given native element does not have an Angular view associated
* with it.
*/
export function inspectNativeElement(element: any): core.DebugNode|null {
return core.getDebugNode(element);
export function inspectNativeElement(element: any): DebugNode|null {
return getDebugNode(element);
}
export function _createNgProbe(coreTokens: core.NgProbeToken[]): any {
export function _createNgProbe(coreTokens: NgProbeToken[]): any {
exportNgVar(INSPECT_GLOBAL_NAME, inspectNativeElement);
exportNgVar(CORE_TOKENS_GLOBAL_NAME, {...CORE_TOKENS, ..._ngProbeTokensToMap(coreTokens || [])});
return () => inspectNativeElement;
}
function _ngProbeTokensToMap(tokens: core.NgProbeToken[]): {[name: string]: any} {
function _ngProbeTokensToMap(tokens: NgProbeToken[]): {[name: string]: any} {
return tokens.reduce((prev: any, t: any) => (prev[t.name] = t.token, prev), {});
}
@ -48,12 +49,12 @@ export const ELEMENT_PROBE_PROVIDERS__POST_R3__ = [];
/**
* Providers which support debugging Angular applications (e.g. via `ng.probe`).
*/
export const ELEMENT_PROBE_PROVIDERS__PRE_R3__: core.Provider[] = [
export const ELEMENT_PROBE_PROVIDERS__PRE_R3__: Provider[] = [
{
provide: core.APP_INITIALIZER,
provide: APP_INITIALIZER,
useFactory: _createNgProbe,
deps: [
[core.NgProbeToken, new core.Optional()],
[NgProbeToken, new Optional()],
],
multi: true,
},

View File

@ -231,7 +231,7 @@ class DefaultDomRenderer2 implements Renderer2 {
}
}
const AT_CHARCODE = '@'.charCodeAt(0);
const AT_CHARCODE = (() => '@'.charCodeAt(0))();
function checkNoSyntheticProp(name: string, nameKind: string) {
if (name.charCodeAt(0) === AT_CHARCODE) {
throw new Error(

View File

@ -18,9 +18,8 @@ import {EventManagerPlugin} from './event_manager';
* addEventListener by 3x.
*/
const __symbol__ =
(typeof Zone !== 'undefined') && (Zone as any)['__symbol__'] || function(v: string): string {
return '__zone_symbol__' + v;
};
(() => (typeof Zone !== 'undefined') && (Zone as any)['__symbol__'] ||
function(v: string): string { return '__zone_symbol__' + v; })();
const ADD_EVENT_LISTENER: 'addEventListener' = __symbol__('addEventListener');
const REMOVE_EVENT_LISTENER: 'removeEventListener' = __symbol__('removeEventListener');
@ -35,13 +34,18 @@ const NATIVE_REMOVE_LISTENER = 'removeEventListener';
const stopSymbol = '__zone_symbol__propagationStopped';
const stopMethodSymbol = '__zone_symbol__stopImmediatePropagation';
const blackListedEvents: string[] =
const blackListedMap = (() => {
const blackListedEvents: string[] =
(typeof Zone !== 'undefined') && (Zone as any)[__symbol__('BLACK_LISTED_EVENTS')];
let blackListedMap: {[eventName: string]: string};
if (blackListedEvents) {
blackListedMap = {};
blackListedEvents.forEach(eventName => { blackListedMap[eventName] = eventName; });
}
if (blackListedEvents) {
const res: {[eventName: string]: string} = {};
blackListedEvents.forEach(eventName => { res[eventName] = eventName; });
return res;
}
return undefined;
})();
const isBlackListedEvent = function(eventName: string) {
if (!blackListedMap) {

View File

@ -2,7 +2,8 @@
"rulesDirectory": [
"dist/tools/tslint",
"node_modules/vrsource-tslint-rules/rules",
"node_modules/tslint-eslint-rules/dist/rules"
"node_modules/tslint-eslint-rules/dist/rules",
"node_modules/tslint-no-toplevel-property-access/rules"
],
"rules": {
"file-header": [
@ -18,6 +19,18 @@
"no-jasmine-focus": true,
"no-var-keyword": true,
"require-internal-with-underscore": true,
"no-toplevel-property-access": [
true,
"packages/animations/src/",
"packages/animations/browser/",
"packages/common/src/",
"packages/core/src/",
"packages/elements/src/",
"packages/forms/src/",
"packages/http/src/",
"packages/platform-browser/src/",
"packages/router/src/"
],
"semicolon": [
true
],

View File

@ -10977,6 +10977,11 @@ tslint-eslint-rules@4.1.1:
tslib "^1.0.0"
tsutils "^1.4.0"
tslint-no-toplevel-property-access@0.0.2:
version "0.0.2"
resolved "https://registry.yarnpkg.com/tslint-no-toplevel-property-access/-/tslint-no-toplevel-property-access-0.0.2.tgz#c9b19bbd525ea7b8577e5ada601cc8625b4ed004"
integrity sha512-Oc+UUurlGLBkgeUSGxMoTpRUpaXsjqzQCEAYrYQyuU8330fi5FKlye5n53y87EJ24AlfdoxMPV7DJfFOADapfg==
tslint@5.7.0:
version "5.7.0"
resolved "https://registry.yarnpkg.com/tslint/-/tslint-5.7.0.tgz#c25e0d0c92fa1201c2bc30e844e08e682b4f3552"