refactor(): use const and let instead of var

This commit is contained in:
Joao Dias 2016-11-12 14:08:58 +01:00 committed by Victor Berchet
parent 73593d4bf3
commit 77ee27c59e
435 changed files with 4637 additions and 4663 deletions

View File

@ -10,7 +10,7 @@ declare var exportFunction: any;
declare var unsafeWindow: any; declare var unsafeWindow: any;
exportFunction(function() { exportFunction(function() {
var curTime = unsafeWindow.performance.now(); const curTime = unsafeWindow.performance.now();
(<any>self).port.emit('startProfiler', curTime); (<any>self).port.emit('startProfiler', curTime);
}, unsafeWindow, {defineAs: 'startProfiler'}); }, unsafeWindow, {defineAs: 'startProfiler'});
@ -28,11 +28,11 @@ exportFunction(function() {
}, unsafeWindow, {defineAs: 'forceGC'}); }, unsafeWindow, {defineAs: 'forceGC'});
exportFunction(function(name: string) { exportFunction(function(name: string) {
var curTime = unsafeWindow.performance.now(); const curTime = unsafeWindow.performance.now();
(<any>self).port.emit('markStart', name, curTime); (<any>self).port.emit('markStart', name, curTime);
}, unsafeWindow, {defineAs: 'markStart'}); }, unsafeWindow, {defineAs: 'markStart'});
exportFunction(function(name: string) { exportFunction(function(name: string) {
var curTime = unsafeWindow.performance.now(); const curTime = unsafeWindow.performance.now();
(<any>self).port.emit('markEnd', name, curTime); (<any>self).port.emit('markEnd', name, curTime);
}, unsafeWindow, {defineAs: 'markEnd'}); }, unsafeWindow, {defineAs: 'markEnd'});

View File

@ -6,9 +6,9 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
var {Cc, Ci, Cu} = require('chrome'); const {Cc, Ci, Cu} = require('chrome');
var os = Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService); const os = Cc['@mozilla.org/observer-service;1'].getService(Ci.nsIObserverService);
var ParserUtil = require('./parser_util'); const ParserUtil = require('./parser_util');
class Profiler { class Profiler {
private _profiler: any; private _profiler: any;
@ -26,8 +26,8 @@ class Profiler {
stop() { this._profiler.StopProfiler(); } stop() { this._profiler.StopProfiler(); }
getProfilePerfEvents() { getProfilePerfEvents() {
var profileData = this._profiler.getProfileData(); const profileData = this._profiler.getProfileData();
var perfEvents = ParserUtil.convertPerfProfileToEvents(profileData); let perfEvents = ParserUtil.convertPerfProfileToEvents(profileData);
perfEvents = this._mergeMarkerEvents(perfEvents); perfEvents = this._mergeMarkerEvents(perfEvents);
perfEvents.sort(function(event1: any, event2: any) { perfEvents.sort(function(event1: any, event2: any) {
return event1.ts - event2.ts; return event1.ts - event2.ts;
@ -55,9 +55,9 @@ function forceGC() {
os.notifyObservers(null, 'child-gc-request', null); os.notifyObservers(null, 'child-gc-request', null);
}; };
var mod = require('sdk/page-mod'); const mod = require('sdk/page-mod');
var data = require('sdk/self').data; const data = require('sdk/self').data;
var profiler = new Profiler(); const profiler = new Profiler();
mod.PageMod({ mod.PageMod({
include: ['*'], include: ['*'],
contentScriptFile: data.url('installed_script.js'), contentScriptFile: data.url('installed_script.js'),

View File

@ -12,11 +12,11 @@
* within the perf profile. * within the perf profile.
*/ */
export function convertPerfProfileToEvents(perfProfile: any): any[] { export function convertPerfProfileToEvents(perfProfile: any): any[] {
var inProgressEvents = new Map(); // map from event name to start time const inProgressEvents = new Map(); // map from event name to start time
var finishedEvents: {[key: string]: any}[] = []; // Event[] finished events const finishedEvents: {[key: string]: any}[] = []; // Event[] finished events
var addFinishedEvent = function(eventName: string, startTime: number, endTime: number) { const addFinishedEvent = function(eventName: string, startTime: number, endTime: number) {
var categorizedEventName = categorizeEvent(eventName); const categorizedEventName = categorizeEvent(eventName);
var args: {[key: string]: any} = undefined; let args: {[key: string]: any} = undefined;
if (categorizedEventName == 'gc') { if (categorizedEventName == 'gc') {
// TODO: We cannot measure heap size at the moment // TODO: We cannot measure heap size at the moment
args = {usedHeapSize: 0}; args = {usedHeapSize: 0};
@ -31,17 +31,17 @@ export function convertPerfProfileToEvents(perfProfile: any): any[] {
} }
}; };
var samples = perfProfile.threads[0].samples; const samples = perfProfile.threads[0].samples;
// In perf profile, firefox samples all the frames in set time intervals. Here // In perf profile, firefox samples all the frames in set time intervals. Here
// we go through all the samples and construct the start and end time for each // we go through all the samples and construct the start and end time for each
// event. // event.
for (var i = 0; i < samples.length; ++i) { for (let i = 0; i < samples.length; ++i) {
var sample = samples[i]; const sample = samples[i];
var sampleTime = sample.time; const sampleTime = sample.time;
// Add all the frames into a set so it's easier/faster to find the set // Add all the frames into a set so it's easier/faster to find the set
// differences // differences
var sampleFrames = new Set(); const sampleFrames = new Set();
sample.frames.forEach(function(frame: {[key: string]: any}) { sample.frames.forEach(function(frame: {[key: string]: any}) {
sampleFrames.add(frame['location']); sampleFrames.add(frame['location']);
}); });
@ -49,7 +49,7 @@ export function convertPerfProfileToEvents(perfProfile: any): any[] {
// If an event is in the inProgressEvents map, but not in the current sample, // If an event is in the inProgressEvents map, but not in the current sample,
// then it must have just finished. We add this event to the finishedEvents // then it must have just finished. We add this event to the finishedEvents
// array and remove it from the inProgressEvents map. // array and remove it from the inProgressEvents map.
var previousSampleTime = (i == 0 ? /* not used */ -1 : samples[i - 1].time); const previousSampleTime = (i == 0 ? /* not used */ -1 : samples[i - 1].time);
inProgressEvents.forEach(function(startTime, eventName) { inProgressEvents.forEach(function(startTime, eventName) {
if (!(sampleFrames.has(eventName))) { if (!(sampleFrames.has(eventName))) {
addFinishedEvent(eventName, startTime, previousSampleTime); addFinishedEvent(eventName, startTime, previousSampleTime);
@ -69,7 +69,7 @@ export function convertPerfProfileToEvents(perfProfile: any): any[] {
// If anything is still in progress, we need to included it as a finished event // If anything is still in progress, we need to included it as a finished event
// since recording ended. // since recording ended.
var lastSampleTime = samples[samples.length - 1].time; const lastSampleTime = samples[samples.length - 1].time;
inProgressEvents.forEach(function(startTime, eventName) { inProgressEvents.forEach(function(startTime, eventName) {
addFinishedEvent(eventName, startTime, lastSampleTime); addFinishedEvent(eventName, startTime, lastSampleTime);
}); });

View File

@ -6,15 +6,15 @@
* found in the LICENSE file at https://angular.io/license * found in the LICENSE file at https://angular.io/license
*/ */
var q = require('q'); const q = require('q');
var FirefoxProfile = require('firefox-profile'); const FirefoxProfile = require('firefox-profile');
var jpm = require('jpm/lib/xpi'); const jpm = require('jpm/lib/xpi');
var pathUtil = require('path'); const pathUtil = require('path');
var PERF_ADDON_PACKAGE_JSON_DIR = '..'; const PERF_ADDON_PACKAGE_JSON_DIR = '..';
exports.getAbsolutePath = function(path: string) { exports.getAbsolutePath = function(path: string) {
var normalizedPath = pathUtil.normalize(path); const normalizedPath = pathUtil.normalize(path);
if (pathUtil.resolve(normalizedPath) == normalizedPath) { if (pathUtil.resolve(normalizedPath) == normalizedPath) {
// Already absolute path // Already absolute path
return normalizedPath; return normalizedPath;
@ -24,12 +24,12 @@ exports.getAbsolutePath = function(path: string) {
}; };
exports.getFirefoxProfile = function(extensionPath: string) { exports.getFirefoxProfile = function(extensionPath: string) {
var deferred = q.defer(); const deferred = q.defer();
var firefoxProfile = new FirefoxProfile(); const firefoxProfile = new FirefoxProfile();
firefoxProfile.addExtensions([extensionPath], () => { firefoxProfile.addExtensions([extensionPath], () => {
firefoxProfile.encoded((encodedProfile: any) => { firefoxProfile.encoded((encodedProfile: any) => {
var multiCapabilities = [{browserName: 'firefox', firefox_profile: encodedProfile}]; const multiCapabilities = [{browserName: 'firefox', firefox_profile: encodedProfile}];
deferred.resolve(multiCapabilities); deferred.resolve(multiCapabilities);
}); });
}); });
@ -38,10 +38,10 @@ exports.getFirefoxProfile = function(extensionPath: string) {
}; };
exports.getFirefoxProfileWithExtension = function() { exports.getFirefoxProfileWithExtension = function() {
var absPackageJsonDir = pathUtil.join(__dirname, PERF_ADDON_PACKAGE_JSON_DIR); const absPackageJsonDir = pathUtil.join(__dirname, PERF_ADDON_PACKAGE_JSON_DIR);
var packageJson = require(pathUtil.join(absPackageJsonDir, 'package.json')); const packageJson = require(pathUtil.join(absPackageJsonDir, 'package.json'));
var savedCwd = process.cwd(); const savedCwd = process.cwd();
process.chdir(absPackageJsonDir); process.chdir(absPackageJsonDir);
return jpm(packageJson).then((xpiPath: string) => { return jpm(packageJson).then((xpiPath: string) => {

View File

@ -55,9 +55,9 @@ export class MultiMetric extends Metric {
} }
function mergeStringMaps(maps: {[key: string]: string}[]): {[key: string]: string} { function mergeStringMaps(maps: {[key: string]: string}[]): {[key: string]: string} {
var result: {[key: string]: string} = {}; const result: {[key: string]: string} = {};
maps.forEach(map => { Object.keys(map).forEach(prop => { result[prop] = map[prop]; }); }); maps.forEach(map => { Object.keys(map).forEach(prop => { result[prop] = map[prop]; }); });
return result; return result;
} }
var _CHILDREN = new OpaqueToken('MultiMetric.children'); const _CHILDREN = new OpaqueToken('MultiMetric.children');

View File

@ -56,7 +56,7 @@ export class PerflogMetric extends Metric {
} }
describe(): {[key: string]: string} { describe(): {[key: string]: string} {
var res: {[key: string]: any} = { const res: {[key: string]: any} = {
'scriptTime': 'script execution time in ms, including gc and render', 'scriptTime': 'script execution time in ms, including gc and render',
'pureScriptTime': 'script execution time in ms, without gc nor render' 'pureScriptTime': 'script execution time in ms, without gc nor render'
}; };
@ -80,7 +80,7 @@ export class PerflogMetric extends Metric {
} }
if (this._captureFrames) { if (this._captureFrames) {
if (!this._perfLogFeatures.frameCapture) { if (!this._perfLogFeatures.frameCapture) {
var warningMsg = 'WARNING: Metric requested, but not supported by driver'; const warningMsg = 'WARNING: Metric requested, but not supported by driver';
// using dot syntax for metric name to keep them grouped together in console reporter // using dot syntax for metric name to keep them grouped together in console reporter
res['frameTime.mean'] = warningMsg; res['frameTime.mean'] = warningMsg;
res['frameTime.worst'] = warningMsg; res['frameTime.worst'] = warningMsg;
@ -93,14 +93,14 @@ export class PerflogMetric extends Metric {
res['frameTime.smooth'] = 'percentage of frames that hit 60fps'; res['frameTime.smooth'] = 'percentage of frames that hit 60fps';
} }
} }
for (let name in this._microMetrics) { for (const name in this._microMetrics) {
res[name] = this._microMetrics[name]; res[name] = this._microMetrics[name];
} }
return res; return res;
} }
beginMeasure(): Promise<any> { beginMeasure(): Promise<any> {
var resultPromise = Promise.resolve(null); let resultPromise = Promise.resolve(null);
if (this._forceGc) { if (this._forceGc) {
resultPromise = resultPromise.then((_) => this._driverExtension.gc()); resultPromise = resultPromise.then((_) => this._driverExtension.gc());
} }
@ -119,7 +119,7 @@ export class PerflogMetric extends Metric {
private _endPlainMeasureAndMeasureForceGc(restartMeasure: boolean) { private _endPlainMeasureAndMeasureForceGc(restartMeasure: boolean) {
return this._endMeasure(true).then((measureValues) => { return this._endMeasure(true).then((measureValues) => {
// disable frame capture for measurements during forced gc // disable frame capture for measurements during forced gc
var originalFrameCaptureValue = this._captureFrames; const originalFrameCaptureValue = this._captureFrames;
this._captureFrames = false; this._captureFrames = false;
return this._driverExtension.gc() return this._driverExtension.gc()
.then((_) => this._endMeasure(restartMeasure)) .then((_) => this._endMeasure(restartMeasure))
@ -137,8 +137,8 @@ export class PerflogMetric extends Metric {
} }
private _endMeasure(restart: boolean): Promise<{[key: string]: number}> { private _endMeasure(restart: boolean): Promise<{[key: string]: number}> {
var markName = this._markName(this._measureCount - 1); const markName = this._markName(this._measureCount - 1);
var nextMarkName = restart ? this._markName(this._measureCount++) : null; const nextMarkName = restart ? this._markName(this._measureCount++) : null;
return this._driverExtension.timeEnd(markName, nextMarkName) return this._driverExtension.timeEnd(markName, nextMarkName)
.then((_) => this._readUntilEndMark(markName)); .then((_) => this._readUntilEndMark(markName));
} }
@ -150,26 +150,26 @@ export class PerflogMetric extends Metric {
} }
return this._driverExtension.readPerfLog().then((events) => { return this._driverExtension.readPerfLog().then((events) => {
this._addEvents(events); this._addEvents(events);
var result = this._aggregateEvents(this._remainingEvents, markName); const result = this._aggregateEvents(this._remainingEvents, markName);
if (result) { if (result) {
this._remainingEvents = events; this._remainingEvents = events;
return result; return result;
} }
var resolve: (result: any) => void; let resolve: (result: any) => void;
var promise = new Promise(res => { resolve = res; }); const promise = new Promise(res => { resolve = res; });
this._setTimeout(() => resolve(this._readUntilEndMark(markName, loopCount + 1)), 100); this._setTimeout(() => resolve(this._readUntilEndMark(markName, loopCount + 1)), 100);
return promise; return promise;
}); });
} }
private _addEvents(events: PerfLogEvent[]) { private _addEvents(events: PerfLogEvent[]) {
var needSort = false; let needSort = false;
events.forEach(event => { events.forEach(event => {
if (event['ph'] === 'X') { if (event['ph'] === 'X') {
needSort = true; needSort = true;
var startEvent: PerfLogEvent = {}; const startEvent: PerfLogEvent = {};
var endEvent: PerfLogEvent = {}; const endEvent: PerfLogEvent = {};
for (let prop in event) { for (const prop in event) {
startEvent[prop] = event[prop]; startEvent[prop] = event[prop];
endEvent[prop] = event[prop]; endEvent[prop] = event[prop];
} }
@ -185,14 +185,14 @@ export class PerflogMetric extends Metric {
if (needSort) { if (needSort) {
// Need to sort because of the ph==='X' events // Need to sort because of the ph==='X' events
this._remainingEvents.sort((a, b) => { this._remainingEvents.sort((a, b) => {
var diff = a['ts'] - b['ts']; const diff = a['ts'] - b['ts'];
return diff > 0 ? 1 : diff < 0 ? -1 : 0; return diff > 0 ? 1 : diff < 0 ? -1 : 0;
}); });
} }
} }
private _aggregateEvents(events: PerfLogEvent[], markName: string): {[key: string]: number} { private _aggregateEvents(events: PerfLogEvent[], markName: string): {[key: string]: number} {
var result: {[key: string]: number} = {'scriptTime': 0, 'pureScriptTime': 0}; const result: {[key: string]: number} = {'scriptTime': 0, 'pureScriptTime': 0};
if (this._perfLogFeatures.gc) { if (this._perfLogFeatures.gc) {
result['gcTime'] = 0; result['gcTime'] = 0;
result['majorGcTime'] = 0; result['majorGcTime'] = 0;
@ -207,7 +207,7 @@ export class PerflogMetric extends Metric {
result['frameTime.worst'] = 0; result['frameTime.worst'] = 0;
result['frameTime.smooth'] = 0; result['frameTime.smooth'] = 0;
} }
for (let name in this._microMetrics) { for (const name in this._microMetrics) {
result[name] = 0; result[name] = 0;
} }
if (this._receivedData) { if (this._receivedData) {
@ -217,11 +217,11 @@ export class PerflogMetric extends Metric {
result['requestCount'] = 0; result['requestCount'] = 0;
} }
var markStartEvent: PerfLogEvent = null; let markStartEvent: PerfLogEvent = null;
var markEndEvent: PerfLogEvent = null; let markEndEvent: PerfLogEvent = null;
events.forEach((event) => { events.forEach((event) => {
var ph = event['ph']; const ph = event['ph'];
var name = event['name']; const name = event['name'];
if (ph === 'B' && name === markName) { if (ph === 'B' && name === markName) {
markStartEvent = event; markStartEvent = event;
} else if (ph === 'I' && name === 'navigationStart') { } else if (ph === 'I' && name === 'navigationStart') {
@ -237,23 +237,23 @@ export class PerflogMetric extends Metric {
return null; return null;
} }
var gcTimeInScript = 0; let gcTimeInScript = 0;
var renderTimeInScript = 0; let renderTimeInScript = 0;
var frameTimestamps: number[] = []; const frameTimestamps: number[] = [];
var frameTimes: number[] = []; const frameTimes: number[] = [];
var frameCaptureStartEvent: PerfLogEvent = null; let frameCaptureStartEvent: PerfLogEvent = null;
var frameCaptureEndEvent: PerfLogEvent = null; let frameCaptureEndEvent: PerfLogEvent = null;
var intervalStarts: {[key: string]: PerfLogEvent} = {}; const intervalStarts: {[key: string]: PerfLogEvent} = {};
var intervalStartCount: {[key: string]: number} = {}; const intervalStartCount: {[key: string]: number} = {};
var inMeasureRange = false; let inMeasureRange = false;
events.forEach((event) => { events.forEach((event) => {
var ph = event['ph']; const ph = event['ph'];
var name = event['name']; let name = event['name'];
var microIterations = 1; let microIterations = 1;
var microIterationsMatch = name.match(_MICRO_ITERATIONS_REGEX); const microIterationsMatch = name.match(_MICRO_ITERATIONS_REGEX);
if (microIterationsMatch) { if (microIterationsMatch) {
name = microIterationsMatch[1]; name = microIterationsMatch[1];
microIterations = parseInt(microIterationsMatch[2], 10); microIterations = parseInt(microIterationsMatch[2], 10);
@ -307,15 +307,15 @@ export class PerflogMetric extends Metric {
} else if ((ph === 'E') && intervalStarts[name]) { } else if ((ph === 'E') && intervalStarts[name]) {
intervalStartCount[name]--; intervalStartCount[name]--;
if (intervalStartCount[name] === 0) { if (intervalStartCount[name] === 0) {
var startEvent = intervalStarts[name]; const startEvent = intervalStarts[name];
var duration = (event['ts'] - startEvent['ts']); const duration = (event['ts'] - startEvent['ts']);
intervalStarts[name] = null; intervalStarts[name] = null;
if (name === 'gc') { if (name === 'gc') {
result['gcTime'] += duration; result['gcTime'] += duration;
var amount = const amount =
(startEvent['args']['usedHeapSize'] - event['args']['usedHeapSize']) / 1000; (startEvent['args']['usedHeapSize'] - event['args']['usedHeapSize']) / 1000;
result['gcAmount'] += amount; result['gcAmount'] += amount;
var majorGc = event['args']['majorGc']; const majorGc = event['args']['majorGc'];
if (majorGc && majorGc) { if (majorGc && majorGc) {
result['majorGcTime'] += duration; result['majorGcTime'] += duration;
} }
@ -351,7 +351,7 @@ export class PerflogMetric extends Metric {
private _addFrameMetrics(result: {[key: string]: number}, frameTimes: any[]) { private _addFrameMetrics(result: {[key: string]: number}, frameTimes: any[]) {
result['frameTime.mean'] = frameTimes.reduce((a, b) => a + b, 0) / frameTimes.length; result['frameTime.mean'] = frameTimes.reduce((a, b) => a + b, 0) / frameTimes.length;
var firstFrame = frameTimes[0]; const firstFrame = frameTimes[0];
result['frameTime.worst'] = frameTimes.reduce((a, b) => a > b ? a : b, firstFrame); result['frameTime.worst'] = frameTimes.reduce((a, b) => a > b ? a : b, firstFrame);
result['frameTime.best'] = frameTimes.reduce((a, b) => a < b ? a : b, firstFrame); result['frameTime.best'] = frameTimes.reduce((a, b) => a < b ? a : b, firstFrame);
result['frameTime.smooth'] = result['frameTime.smooth'] =
@ -361,11 +361,11 @@ export class PerflogMetric extends Metric {
private _markName(index: number) { return `${_MARK_NAME_PREFIX}${index}`; } private _markName(index: number) { return `${_MARK_NAME_PREFIX}${index}`; }
} }
var _MICRO_ITERATIONS_REGEX = /(.+)\*(\d+)$/; const _MICRO_ITERATIONS_REGEX = /(.+)\*(\d+)$/;
var _MAX_RETRY_COUNT = 20; const _MAX_RETRY_COUNT = 20;
var _MARK_NAME_PREFIX = 'benchpress'; const _MARK_NAME_PREFIX = 'benchpress';
var _MARK_NAME_FRAME_CAPUTRE = 'frameCapture'; const _MARK_NAME_FRAME_CAPUTRE = 'frameCapture';
// using 17ms as a somewhat looser threshold, instead of 16.6666ms // using 17ms as a somewhat looser threshold, instead of 16.6666ms
var _FRAME_TIME_SMOOTH_THRESHOLD = 17; const _FRAME_TIME_SMOOTH_THRESHOLD = 17;

View File

@ -33,12 +33,12 @@ export class UserMetric extends Metric {
endMeasure(restart: boolean): Promise<{[key: string]: any}> { endMeasure(restart: boolean): Promise<{[key: string]: any}> {
let resolve: (result: any) => void; let resolve: (result: any) => void;
let reject: (error: any) => void; let reject: (error: any) => void;
let promise = new Promise((res, rej) => { const promise = new Promise((res, rej) => {
resolve = res; resolve = res;
reject = rej; reject = rej;
}); });
let adapter = this._wdAdapter; const adapter = this._wdAdapter;
let names = Object.keys(this._userMetrics); const names = Object.keys(this._userMetrics);
function getAndClearValues() { function getAndClearValues() {
Promise.all(names.map(name => adapter.executeScript(`return window.${name}`))) Promise.all(names.map(name => adapter.executeScript(`return window.${name}`)))
@ -46,7 +46,7 @@ export class UserMetric extends Metric {
if (values.every(v => typeof v === 'number')) { if (values.every(v => typeof v === 'number')) {
Promise.all(names.map(name => adapter.executeScript(`delete window.${name}`))) Promise.all(names.map(name => adapter.executeScript(`delete window.${name}`)))
.then((_: any[]) => { .then((_: any[]) => {
let map: {[k: string]: any} = {}; const map: {[k: string]: any} = {};
for (let i = 0, n = names.length; i < n; i++) { for (let i = 0, n = names.length; i < n; i++) {
map[names[i]] = values[i]; map[names[i]] = values[i];
} }

View File

@ -28,8 +28,8 @@ export class ConsoleReporter extends Reporter {
]; ];
private static _lpad(value: string, columnWidth: number, fill = ' ') { private static _lpad(value: string, columnWidth: number, fill = ' ') {
var result = ''; let result = '';
for (var i = 0; i < columnWidth - value.length; i++) { for (let i = 0; i < columnWidth - value.length; i++) {
result += fill; result += fill;
} }
return result + value; return result + value;
@ -49,7 +49,7 @@ export class ConsoleReporter extends Reporter {
private _printDescription(sampleDescription: SampleDescription) { private _printDescription(sampleDescription: SampleDescription) {
this._print(`BENCHMARK ${sampleDescription.id}`); this._print(`BENCHMARK ${sampleDescription.id}`);
this._print('Description:'); this._print('Description:');
var props = sortedProps(sampleDescription.description); const props = sortedProps(sampleDescription.description);
props.forEach((prop) => { this._print(`- ${prop}: ${sampleDescription.description[prop]}`); }); props.forEach((prop) => { this._print(`- ${prop}: ${sampleDescription.description[prop]}`); });
this._print('Metrics:'); this._print('Metrics:');
this._metricNames.forEach((metricName) => { this._metricNames.forEach((metricName) => {
@ -61,8 +61,8 @@ export class ConsoleReporter extends Reporter {
} }
reportMeasureValues(measureValues: MeasureValues): Promise<any> { reportMeasureValues(measureValues: MeasureValues): Promise<any> {
var formattedValues = this._metricNames.map(metricName => { const formattedValues = this._metricNames.map(metricName => {
var value = measureValues.values[metricName]; const value = measureValues.values[metricName];
return formatNum(value); return formatNum(value);
}); });
this._printStringRow(formattedValues); this._printStringRow(formattedValues);

View File

@ -38,7 +38,7 @@ export class JsonFileReporter extends Reporter {
sortedProps(this._description.metrics).forEach((metricName) => { sortedProps(this._description.metrics).forEach((metricName) => {
stats[metricName] = formatStats(validSample, metricName); stats[metricName] = formatStats(validSample, metricName);
}); });
var content = JSON.stringify( const content = JSON.stringify(
{ {
'description': this._description, 'description': this._description,
'stats': stats, 'stats': stats,
@ -46,7 +46,7 @@ export class JsonFileReporter extends Reporter {
'validSample': validSample, 'validSample': validSample,
}, },
null, 2); null, 2);
var filePath = `${this._path}/${this._description.id}_${this._now().getTime()}.json`; const filePath = `${this._path}/${this._description.id}_${this._now().getTime()}.json`;
return this._writeFile(filePath, content); return this._writeFile(filePath, content);
} }
} }

View File

@ -39,4 +39,4 @@ export class MultiReporter extends Reporter {
} }
} }
var _CHILDREN = new OpaqueToken('MultiReporter.children'); const _CHILDREN = new OpaqueToken('MultiReporter.children');

View File

@ -18,10 +18,10 @@ export function sortedProps(obj: {[key: string]: any}) {
} }
export function formatStats(validSamples: MeasureValues[], metricName: string): string { export function formatStats(validSamples: MeasureValues[], metricName: string): string {
var samples = validSamples.map(measureValues => measureValues.values[metricName]); const samples = validSamples.map(measureValues => measureValues.values[metricName]);
var mean = Statistic.calculateMean(samples); const mean = Statistic.calculateMean(samples);
var cv = Statistic.calculateCoefficientOfVariation(samples, mean); const cv = Statistic.calculateCoefficientOfVariation(samples, mean);
var formattedMean = formatNum(mean); const formattedMean = formatNum(mean);
// Note: Don't use the unicode character for +- as it might cause // Note: Don't use the unicode character for +- as it might cause
// hickups for consoles... // hickups for consoles...
return isNaN(cv) ? formattedMean : `${formattedMean}+-${Math.floor(cv)}%`; return isNaN(cv) ? formattedMean : `${formattedMean}+-${Math.floor(cv)}%`;

View File

@ -45,7 +45,7 @@ export class Runner {
providers?: Provider[], providers?: Provider[],
userMetrics?: {[key: string]: string} userMetrics?: {[key: string]: string}
}): Promise<SampleState> { }): Promise<SampleState> {
var sampleProviders: Provider[] = [ const sampleProviders: Provider[] = [
_DEFAULT_PROVIDERS, this._defaultProviders, {provide: Options.SAMPLE_ID, useValue: id}, _DEFAULT_PROVIDERS, this._defaultProviders, {provide: Options.SAMPLE_ID, useValue: id},
{provide: Options.EXECUTE, useValue: execute} {provide: Options.EXECUTE, useValue: execute}
]; ];
@ -62,33 +62,33 @@ export class Runner {
sampleProviders.push(providers); sampleProviders.push(providers);
} }
var inj = ReflectiveInjector.resolveAndCreate(sampleProviders); const inj = ReflectiveInjector.resolveAndCreate(sampleProviders);
var adapter: WebDriverAdapter = inj.get(WebDriverAdapter); const adapter: WebDriverAdapter = inj.get(WebDriverAdapter);
return Promise return Promise
.all([adapter.capabilities(), adapter.executeScript('return window.navigator.userAgent;')]) .all([adapter.capabilities(), adapter.executeScript('return window.navigator.userAgent;')])
.then((args) => { .then((args) => {
var capabilities = args[0]; const capabilities = args[0];
var userAgent = args[1]; const userAgent = args[1];
// This might still create instances twice. We are creating a new injector with all the // This might still create instances twice. We are creating a new injector with all the
// providers. // providers.
// Only WebDriverAdapter is reused. // Only WebDriverAdapter is reused.
// TODO vsavkin consider changing it when toAsyncFactory is added back or when child // TODO vsavkin consider changing it when toAsyncFactory is added back or when child
// injectors are handled better. // injectors are handled better.
var injector = ReflectiveInjector.resolveAndCreate([ const injector = ReflectiveInjector.resolveAndCreate([
sampleProviders, {provide: Options.CAPABILITIES, useValue: capabilities}, sampleProviders, {provide: Options.CAPABILITIES, useValue: capabilities},
{provide: Options.USER_AGENT, useValue: userAgent}, {provide: Options.USER_AGENT, useValue: userAgent},
{provide: WebDriverAdapter, useValue: adapter} {provide: WebDriverAdapter, useValue: adapter}
]); ]);
var sampler = injector.get(Sampler); const sampler = injector.get(Sampler);
return sampler.sample(); return sampler.sample();
}); });
} }
} }
var _DEFAULT_PROVIDERS = [ const _DEFAULT_PROVIDERS = [
Options.DEFAULT_PROVIDERS, Options.DEFAULT_PROVIDERS,
Sampler.PROVIDERS, Sampler.PROVIDERS,
ConsoleReporter.PROVIDERS, ConsoleReporter.PROVIDERS,

View File

@ -49,7 +49,7 @@ export class Sampler {
} }
private _iterate(lastState: SampleState): Promise<SampleState> { private _iterate(lastState: SampleState): Promise<SampleState> {
var resultPromise: Promise<SampleState>; let resultPromise: Promise<SampleState>;
if (this._prepare !== Options.NO_PREPARE) { if (this._prepare !== Options.NO_PREPARE) {
resultPromise = this._driver.waitFor(this._prepare); resultPromise = this._driver.waitFor(this._prepare);
} else { } else {
@ -64,10 +64,10 @@ export class Sampler {
} }
private _report(state: SampleState, metricValues: {[key: string]: any}): Promise<SampleState> { private _report(state: SampleState, metricValues: {[key: string]: any}): Promise<SampleState> {
var measureValues = new MeasureValues(state.completeSample.length, this._now(), metricValues); const measureValues = new MeasureValues(state.completeSample.length, this._now(), metricValues);
var completeSample = state.completeSample.concat([measureValues]); const completeSample = state.completeSample.concat([measureValues]);
var validSample = this._validator.validate(completeSample); const validSample = this._validator.validate(completeSample);
var resultPromise = this._reporter.reportMeasureValues(measureValues); let resultPromise = this._reporter.reportMeasureValues(measureValues);
if (isPresent(validSample)) { if (isPresent(validSample)) {
resultPromise = resultPromise =
resultPromise.then((_) => this._reporter.reportSample(completeSample, validSample)); resultPromise.then((_) => this._reporter.reportSample(completeSample, validSample));

View File

@ -12,14 +12,14 @@ export class Statistic {
} }
static calculateMean(samples: number[]) { static calculateMean(samples: number[]) {
var total = 0; let total = 0;
// TODO: use reduce // TODO: use reduce
samples.forEach(x => total += x); samples.forEach(x => total += x);
return total / samples.length; return total / samples.length;
} }
static calculateStandardDeviation(samples: number[], mean: number) { static calculateStandardDeviation(samples: number[], mean: number) {
var deviation = 0; let deviation = 0;
// TODO: use reduce // TODO: use reduce
samples.forEach(x => deviation += Math.pow(x - mean, 2)); samples.forEach(x => deviation += Math.pow(x - mean, 2));
deviation = deviation / (samples.length); deviation = deviation / (samples.length);
@ -30,9 +30,9 @@ export class Statistic {
static calculateRegressionSlope( static calculateRegressionSlope(
xValues: number[], xMean: number, yValues: number[], yMean: number) { xValues: number[], xMean: number, yValues: number[], yMean: number) {
// See http://en.wikipedia.org/wiki/Simple_linear_regression // See http://en.wikipedia.org/wiki/Simple_linear_regression
var dividendSum = 0; let dividendSum = 0;
var divisorSum = 0; let divisorSum = 0;
for (var i = 0; i < xValues.length; i++) { for (let i = 0; i < xValues.length; i++) {
dividendSum += (xValues[i] - xMean) * (yValues[i] - yMean); dividendSum += (xValues[i] - xMean) * (yValues[i] - yMean);
divisorSum += Math.pow(xValues[i] - xMean, 2); divisorSum += Math.pow(xValues[i] - xMean, 2);
} }

View File

@ -34,7 +34,7 @@ export type PerfLogEvent = {
*/ */
export abstract class WebDriverExtension { export abstract class WebDriverExtension {
static provideFirstSupported(childTokens: any[]): any[] { static provideFirstSupported(childTokens: any[]): any[] {
var res = [ const res = [
{ {
provide: _CHILDREN, provide: _CHILDREN,
useFactory: (injector: Injector) => childTokens.map(token => injector.get(token)), useFactory: (injector: Injector) => childTokens.map(token => injector.get(token)),
@ -43,7 +43,7 @@ export abstract class WebDriverExtension {
{ {
provide: WebDriverExtension, provide: WebDriverExtension,
useFactory: (children: WebDriverExtension[], capabilities: {[key: string]: any}) => { useFactory: (children: WebDriverExtension[], capabilities: {[key: string]: any}) => {
var delegate: WebDriverExtension; let delegate: WebDriverExtension;
children.forEach(extension => { children.forEach(extension => {
if (extension.supports(capabilities)) { if (extension.supports(capabilities)) {
delegate = extension; delegate = extension;
@ -101,4 +101,4 @@ export class PerfLogFeatures {
} }
} }
var _CHILDREN = new OpaqueToken('WebDriverExtension.children'); const _CHILDREN = new OpaqueToken('WebDriverExtension.children');

View File

@ -34,7 +34,7 @@ export class ChromeDriverExtension extends WebDriverExtension {
if (!userAgent) { if (!userAgent) {
return -1; return -1;
} }
var v = userAgent.split(/Chrom(e|ium)\//g)[2]; let v = userAgent.split(/Chrom(e|ium)\//g)[2];
if (!v) { if (!v) {
return -1; return -1;
} }
@ -52,7 +52,7 @@ export class ChromeDriverExtension extends WebDriverExtension {
} }
timeEnd(name: string, restartName: string = null): Promise<any> { timeEnd(name: string, restartName: string = null): Promise<any> {
var script = `console.timeEnd('${name}');`; let script = `console.timeEnd('${name}');`;
if (restartName) { if (restartName) {
script += `console.time('${restartName}');`; script += `console.time('${restartName}');`;
} }
@ -67,9 +67,9 @@ export class ChromeDriverExtension extends WebDriverExtension {
return this._driver.executeScript('1+1') return this._driver.executeScript('1+1')
.then((_) => this._driver.logs('performance')) .then((_) => this._driver.logs('performance'))
.then((entries) => { .then((entries) => {
var events: PerfLogEvent[] = []; const events: PerfLogEvent[] = [];
entries.forEach(entry => { entries.forEach(entry => {
var message = JSON.parse(entry['message'])['message']; const message = JSON.parse(entry['message'])['message'];
if (message['method'] === 'Tracing.dataCollected') { if (message['method'] === 'Tracing.dataCollected') {
events.push(message['params']); events.push(message['params']);
} }
@ -95,8 +95,8 @@ export class ChromeDriverExtension extends WebDriverExtension {
} }
private _convertEvent(event: {[key: string]: any}, categories: string[]) { private _convertEvent(event: {[key: string]: any}, categories: string[]) {
var name = event['name']; const name = event['name'];
var args = event['args']; const args = event['args'];
if (this._isEvent(categories, name, ['blink.console'])) { if (this._isEvent(categories, name, ['blink.console'])) {
return normalizeEvent(event, {'name': name}); return normalizeEvent(event, {'name': name});
} else if (this._isEvent( } else if (this._isEvent(
@ -109,7 +109,7 @@ export class ChromeDriverExtension extends WebDriverExtension {
// new surfaces framework (not broadly enabled yet) // new surfaces framework (not broadly enabled yet)
// 3rd choice: BenchmarkInstrumentation::ImplThreadRenderingStats - fallback event that is // 3rd choice: BenchmarkInstrumentation::ImplThreadRenderingStats - fallback event that is
// always available if something is rendered // always available if something is rendered
var frameCount = event['args']['data']['frame_count']; const frameCount = event['args']['data']['frame_count'];
if (frameCount > 1) { if (frameCount > 1) {
throw new Error('multi-frame render stats not supported'); throw new Error('multi-frame render stats not supported');
} }
@ -122,14 +122,14 @@ export class ChromeDriverExtension extends WebDriverExtension {
categories, name, ['disabled-by-default-devtools.timeline'], 'CompositeLayers')) { categories, name, ['disabled-by-default-devtools.timeline'], 'CompositeLayers')) {
return normalizeEvent(event, {'name': 'render'}); return normalizeEvent(event, {'name': 'render'});
} else if (this._isEvent(categories, name, ['devtools.timeline', 'v8'], 'MajorGC')) { } else if (this._isEvent(categories, name, ['devtools.timeline', 'v8'], 'MajorGC')) {
var normArgs = { const normArgs = {
'majorGc': true, 'majorGc': true,
'usedHeapSize': args['usedHeapSizeAfter'] !== undefined ? args['usedHeapSizeAfter'] : 'usedHeapSize': args['usedHeapSizeAfter'] !== undefined ? args['usedHeapSizeAfter'] :
args['usedHeapSizeBefore'] args['usedHeapSizeBefore']
}; };
return normalizeEvent(event, {'name': 'gc', 'args': normArgs}); return normalizeEvent(event, {'name': 'gc', 'args': normArgs});
} else if (this._isEvent(categories, name, ['devtools.timeline', 'v8'], 'MinorGC')) { } else if (this._isEvent(categories, name, ['devtools.timeline', 'v8'], 'MinorGC')) {
var normArgs = { const normArgs = {
'majorGc': false, 'majorGc': false,
'usedHeapSize': args['usedHeapSizeAfter'] !== undefined ? args['usedHeapSizeAfter'] : 'usedHeapSize': args['usedHeapSizeAfter'] !== undefined ? args['usedHeapSizeAfter'] :
args['usedHeapSizeBefore'] args['usedHeapSizeBefore']
@ -151,11 +151,11 @@ export class ChromeDriverExtension extends WebDriverExtension {
this._isEvent(categories, name, ['devtools.timeline'], 'Paint')) { this._isEvent(categories, name, ['devtools.timeline'], 'Paint')) {
return normalizeEvent(event, {'name': 'render'}); return normalizeEvent(event, {'name': 'render'});
} else if (this._isEvent(categories, name, ['devtools.timeline'], 'ResourceReceivedData')) { } else if (this._isEvent(categories, name, ['devtools.timeline'], 'ResourceReceivedData')) {
let normArgs = {'encodedDataLength': args['data']['encodedDataLength']}; const normArgs = {'encodedDataLength': args['data']['encodedDataLength']};
return normalizeEvent(event, {'name': 'receivedData', 'args': normArgs}); return normalizeEvent(event, {'name': 'receivedData', 'args': normArgs});
} else if (this._isEvent(categories, name, ['devtools.timeline'], 'ResourceSendRequest')) { } else if (this._isEvent(categories, name, ['devtools.timeline'], 'ResourceSendRequest')) {
let data = args['data']; const data = args['data'];
let normArgs = {'url': data['url'], 'method': data['requestMethod']}; const normArgs = {'url': data['url'], 'method': data['requestMethod']};
return normalizeEvent(event, {'name': 'sendRequest', 'args': normArgs}); return normalizeEvent(event, {'name': 'sendRequest', 'args': normArgs});
} else if (this._isEvent(categories, name, ['blink.user_timing'], 'navigationStart')) { } else if (this._isEvent(categories, name, ['blink.user_timing'], 'navigationStart')) {
return normalizeEvent(event, {'name': 'navigationStart'}); return normalizeEvent(event, {'name': 'navigationStart'});
@ -168,7 +168,7 @@ export class ChromeDriverExtension extends WebDriverExtension {
private _isEvent( private _isEvent(
eventCategories: string[], eventName: string, expectedCategories: string[], eventCategories: string[], eventName: string, expectedCategories: string[],
expectedName: string = null): boolean { expectedName: string = null): boolean {
var hasCategories = expectedCategories.reduce( const hasCategories = expectedCategories.reduce(
(value, cat) => value && eventCategories.indexOf(cat) !== -1, true); (value, cat) => value && eventCategories.indexOf(cat) !== -1, true);
return !expectedName ? hasCategories : hasCategories && eventName === expectedName; return !expectedName ? hasCategories : hasCategories && eventName === expectedName;
} }
@ -183,7 +183,7 @@ export class ChromeDriverExtension extends WebDriverExtension {
} }
function normalizeEvent(chromeEvent: {[key: string]: any}, data: PerfLogEvent): PerfLogEvent { function normalizeEvent(chromeEvent: {[key: string]: any}, data: PerfLogEvent): PerfLogEvent {
var ph = chromeEvent['ph'].toUpperCase(); let ph = chromeEvent['ph'].toUpperCase();
if (ph === 'S') { if (ph === 'S') {
ph = 'B'; ph = 'B';
} else if (ph === 'F') { } else if (ph === 'F') {
@ -192,16 +192,16 @@ function normalizeEvent(chromeEvent: {[key: string]: any}, data: PerfLogEvent):
// mark events from navigation timing // mark events from navigation timing
ph = 'I'; ph = 'I';
} }
var result: {[key: string]: any} = const result: {[key: string]: any} =
{'pid': chromeEvent['pid'], 'ph': ph, 'cat': 'timeline', 'ts': chromeEvent['ts'] / 1000}; {'pid': chromeEvent['pid'], 'ph': ph, 'cat': 'timeline', 'ts': chromeEvent['ts'] / 1000};
if (ph === 'X') { if (ph === 'X') {
var dur = chromeEvent['dur']; let dur = chromeEvent['dur'];
if (dur === undefined) { if (dur === undefined) {
dur = chromeEvent['tdur']; dur = chromeEvent['tdur'];
} }
result['dur'] = !dur ? 0.0 : dur / 1000; result['dur'] = !dur ? 0.0 : dur / 1000;
} }
for (let prop in data) { for (const prop in data) {
result[prop] = data[prop]; result[prop] = data[prop];
} }
return result; return result;

View File

@ -34,7 +34,7 @@ export class FirefoxDriverExtension extends WebDriverExtension {
} }
timeEnd(name: string, restartName: string = null): Promise<any> { timeEnd(name: string, restartName: string = null): Promise<any> {
var script = 'window.markEnd("' + name + '");'; let script = 'window.markEnd("' + name + '");';
if (isPresent(restartName)) { if (isPresent(restartName)) {
script += 'window.markStart("' + restartName + '");'; script += 'window.markStart("' + restartName + '");';
} }

View File

@ -25,7 +25,7 @@ export class IOsDriverExtension extends WebDriverExtension {
} }
timeEnd(name: string, restartName: string = null): Promise<any> { timeEnd(name: string, restartName: string = null): Promise<any> {
var script = `console.timeEnd('${name}');`; let script = `console.timeEnd('${name}');`;
if (isPresent(restartName)) { if (isPresent(restartName)) {
script += `console.time('${restartName}');`; script += `console.time('${restartName}');`;
} }
@ -39,9 +39,9 @@ export class IOsDriverExtension extends WebDriverExtension {
return this._driver.executeScript('1+1') return this._driver.executeScript('1+1')
.then((_) => this._driver.logs('performance')) .then((_) => this._driver.logs('performance'))
.then((entries) => { .then((entries) => {
var records: any[] = []; const records: any[] = [];
entries.forEach(entry => { entries.forEach(entry => {
var message = JSON.parse(entry['message'])['message']; const message = JSON.parse(entry['message'])['message'];
if (message['method'] === 'Timeline.eventRecorded') { if (message['method'] === 'Timeline.eventRecorded') {
records.push(message['params']['record']); records.push(message['params']['record']);
} }
@ -56,11 +56,11 @@ export class IOsDriverExtension extends WebDriverExtension {
events = []; events = [];
} }
records.forEach((record) => { records.forEach((record) => {
var endEvent: PerfLogEvent = null; let endEvent: PerfLogEvent = null;
var type = record['type']; const type = record['type'];
var data = record['data']; const data = record['data'];
var startTime = record['startTime']; const startTime = record['startTime'];
var endTime = record['endTime']; const endTime = record['endTime'];
if (type === 'FunctionCall' && (data == null || data['scriptName'] !== 'InjectedScript')) { if (type === 'FunctionCall' && (data == null || data['scriptName'] !== 'InjectedScript')) {
events.push(createStartEvent('script', startTime)); events.push(createStartEvent('script', startTime));
@ -95,7 +95,7 @@ export class IOsDriverExtension extends WebDriverExtension {
function createEvent( function createEvent(
ph: 'X' | 'B' | 'E' | 'B' | 'E', name: string, time: number, args: any = null) { ph: 'X' | 'B' | 'E' | 'B' | 'E', name: string, time: number, args: any = null) {
var result: PerfLogEvent = { const result: PerfLogEvent = {
'cat': 'timeline', 'cat': 'timeline',
'name': name, 'name': name,
'ts': time, 'ts': time,

View File

@ -8,7 +8,7 @@
require('core-js'); require('core-js');
require('reflect-metadata'); require('reflect-metadata');
var testHelper = require('../../src/firefox_extension/lib/test_helper.js'); const testHelper = require('../../src/firefox_extension/lib/test_helper.js');
exports.config = { exports.config = {
specs: ['spec.js', 'sample_benchmark.js'], specs: ['spec.js', 'sample_benchmark.js'],

View File

@ -10,10 +10,10 @@ import {convertPerfProfileToEvents} from '../../src/firefox_extension/lib/parser
function assertEventsEqual(actualEvents: any[], expectedEvents: any[]) { function assertEventsEqual(actualEvents: any[], expectedEvents: any[]) {
expect(actualEvents.length == expectedEvents.length); expect(actualEvents.length == expectedEvents.length);
for (var i = 0; i < actualEvents.length; ++i) { for (let i = 0; i < actualEvents.length; ++i) {
var actualEvent = actualEvents[i]; const actualEvent = actualEvents[i];
var expectedEvent = expectedEvents[i]; const expectedEvent = expectedEvents[i];
for (var key in actualEvent) { for (const key in actualEvent) {
expect(actualEvent[key]).toEqual(expectedEvent[key]); expect(actualEvent[key]).toEqual(expectedEvent[key]);
} }
} }
@ -22,17 +22,17 @@ function assertEventsEqual(actualEvents: any[], expectedEvents: any[]) {
export function main() { export function main() {
describe('convertPerfProfileToEvents', function() { describe('convertPerfProfileToEvents', function() {
it('should convert single instantaneous event', function() { it('should convert single instantaneous event', function() {
var profileData = { const profileData = {
threads: [ threads: [
{samples: [{time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}]} {samples: [{time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}]}
] ]
}; };
var perfEvents = convertPerfProfileToEvents(profileData); const perfEvents = convertPerfProfileToEvents(profileData);
assertEventsEqual(perfEvents, [{ph: 'X', ts: 1, name: 'script'}]); assertEventsEqual(perfEvents, [{ph: 'X', ts: 1, name: 'script'}]);
}); });
it('should convert single non-instantaneous event', function() { it('should convert single non-instantaneous event', function() {
var profileData = { const profileData = {
threads: [{ threads: [{
samples: [ samples: [
{time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, {time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]},
@ -41,13 +41,13 @@ export function main() {
] ]
}] }]
}; };
var perfEvents = convertPerfProfileToEvents(profileData); const perfEvents = convertPerfProfileToEvents(profileData);
assertEventsEqual( assertEventsEqual(
perfEvents, [{ph: 'B', ts: 1, name: 'script'}, {ph: 'E', ts: 100, name: 'script'}]); perfEvents, [{ph: 'B', ts: 1, name: 'script'}, {ph: 'E', ts: 100, name: 'script'}]);
}); });
it('should convert multiple instantaneous events', function() { it('should convert multiple instantaneous events', function() {
var profileData = { const profileData = {
threads: [{ threads: [{
samples: [ samples: [
{time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, {time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]},
@ -55,13 +55,13 @@ export function main() {
] ]
}] }]
}; };
var perfEvents = convertPerfProfileToEvents(profileData); const perfEvents = convertPerfProfileToEvents(profileData);
assertEventsEqual( assertEventsEqual(
perfEvents, [{ph: 'X', ts: 1, name: 'script'}, {ph: 'X', ts: 2, name: 'render'}]); perfEvents, [{ph: 'X', ts: 1, name: 'script'}, {ph: 'X', ts: 2, name: 'render'}]);
}); });
it('should convert multiple mixed events', function() { it('should convert multiple mixed events', function() {
var profileData = { const profileData = {
threads: [{ threads: [{
samples: [ samples: [
{time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, {time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]},
@ -71,7 +71,7 @@ export function main() {
] ]
}] }]
}; };
var perfEvents = convertPerfProfileToEvents(profileData); const perfEvents = convertPerfProfileToEvents(profileData);
assertEventsEqual(perfEvents, [ assertEventsEqual(perfEvents, [
{ph: 'X', ts: 1, name: 'script'}, {ph: 'X', ts: 2, name: 'render'}, {ph: 'X', ts: 1, name: 'script'}, {ph: 'X', ts: 2, name: 'render'},
{ph: 'B', ts: 5, name: 'script'}, {ph: 'E', ts: 10, name: 'script'} {ph: 'B', ts: 5, name: 'script'}, {ph: 'E', ts: 10, name: 'script'}
@ -79,13 +79,13 @@ export function main() {
}); });
it('should add args to gc events', function() { it('should add args to gc events', function() {
var profileData = {threads: [{samples: [{time: 1, frames: [{location: 'forceGC'}]}]}]}; const profileData = {threads: [{samples: [{time: 1, frames: [{location: 'forceGC'}]}]}]};
var perfEvents = convertPerfProfileToEvents(profileData); const perfEvents = convertPerfProfileToEvents(profileData);
assertEventsEqual(perfEvents, [{ph: 'X', ts: 1, name: 'gc', args: {usedHeapSize: 0}}]); assertEventsEqual(perfEvents, [{ph: 'X', ts: 1, name: 'gc', args: {usedHeapSize: 0}}]);
}); });
it('should skip unknown events', function() { it('should skip unknown events', function() {
var profileData = { const profileData = {
threads: [{ threads: [{
samples: [ samples: [
{time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]}, {time: 1, frames: [{location: 'FirefoxDriver.prototype.executeScript'}]},
@ -93,7 +93,7 @@ export function main() {
] ]
}] }]
}; };
var perfEvents = convertPerfProfileToEvents(profileData); const perfEvents = convertPerfProfileToEvents(profileData);
assertEventsEqual(perfEvents, [{ph: 'X', ts: 1, name: 'script'}]); assertEventsEqual(perfEvents, [{ph: 'X', ts: 1, name: 'script'}]);
}); });
}); });

View File

@ -8,8 +8,8 @@
import {$, browser} from 'protractor'; import {$, browser} from 'protractor';
var benchpress = require('../../index.js'); const benchpress = require('../../index.js');
var runner = new benchpress.Runner([ const runner = new benchpress.Runner([
// use protractor as Webdriver client // use protractor as Webdriver client
benchpress.SeleniumWebDriverAdapter.PROTRACTOR_PROVIDERS, benchpress.SeleniumWebDriverAdapter.PROTRACTOR_PROVIDERS,
// use RegressionSlopeValidator to validate samples // use RegressionSlopeValidator to validate samples

View File

@ -8,9 +8,9 @@
import {browser} from 'protractor'; import {browser} from 'protractor';
var assertEventsContainsName = function(events: any[], eventName: string) { const assertEventsContainsName = function(events: any[], eventName: string) {
var found = false; let found = false;
for (var i = 0; i < events.length; ++i) { for (let i = 0; i < events.length; ++i) {
if (events[i].name == eventName) { if (events[i].name == eventName) {
found = true; found = true;
break; break;
@ -20,7 +20,7 @@ var assertEventsContainsName = function(events: any[], eventName: string) {
}; };
describe('firefox extension', function() { describe('firefox extension', function() {
var TEST_URL = 'http://localhost:8001/playground/src/hello_world/index.html'; const TEST_URL = 'http://localhost:8001/playground/src/hello_world/index.html';
it('should measure performance', function() { it('should measure performance', function() {
browser.sleep(3000); // wait for extension to load browser.sleep(3000); // wait for extension to load

View File

@ -11,7 +11,7 @@ import {Metric, MultiMetric, ReflectiveInjector} from '../../index';
export function main() { export function main() {
function createMetric(ids: any[]) { function createMetric(ids: any[]) {
var m = ReflectiveInjector const m = ReflectiveInjector
.resolveAndCreate([ .resolveAndCreate([
ids.map(id => ({provide: id, useValue: new MockMetric(id)})), ids.map(id => ({provide: id, useValue: new MockMetric(id)})),
MultiMetric.provideWith(ids) MultiMetric.provideWith(ids)
@ -56,13 +56,13 @@ class MockMetric extends Metric {
beginMeasure(): Promise<string> { return Promise.resolve(`${this._id}_beginMeasure`); } beginMeasure(): Promise<string> { return Promise.resolve(`${this._id}_beginMeasure`); }
endMeasure(restart: boolean): Promise<{[key: string]: any}> { endMeasure(restart: boolean): Promise<{[key: string]: any}> {
var result: {[key: string]: any} = {}; const result: {[key: string]: any} = {};
result[this._id] = {'restart': restart}; result[this._id] = {'restart': restart};
return Promise.resolve(result); return Promise.resolve(result);
} }
describe(): {[key: string]: string} { describe(): {[key: string]: string} {
var result: {[key: string]: string} = {}; const result: {[key: string]: string} = {};
result[this._id] = 'describe'; result[this._id] = 'describe';
return result; return result;
} }

View File

@ -14,8 +14,8 @@ import {isPresent} from '../../src/facade/lang';
import {TraceEventFactory} from '../trace_event_factory'; import {TraceEventFactory} from '../trace_event_factory';
export function main() { export function main() {
var commandLog: any[]; let commandLog: any[];
var eventFactory = new TraceEventFactory('timeline', 'pid0'); const eventFactory = new TraceEventFactory('timeline', 'pid0');
function createMetric( function createMetric(
perfLogs: PerfLogEvent[], perfLogFeatures: PerfLogFeatures, perfLogs: PerfLogEvent[], perfLogFeatures: PerfLogFeatures,
@ -34,7 +34,7 @@ export function main() {
if (!microMetrics) { if (!microMetrics) {
microMetrics = {}; microMetrics = {};
} }
var providers: Provider[] = [ const providers: Provider[] = [
Options.DEFAULT_PROVIDERS, PerflogMetric.PROVIDERS, Options.DEFAULT_PROVIDERS, PerflogMetric.PROVIDERS,
{provide: Options.MICRO_METRICS, useValue: microMetrics}, { {provide: Options.MICRO_METRICS, useValue: microMetrics}, {
provide: PerflogMetric.SET_TIMEOUT, provide: PerflogMetric.SET_TIMEOUT,
@ -66,7 +66,7 @@ export function main() {
describe('perflog metric', () => { describe('perflog metric', () => {
function sortedKeys(stringMap: {[key: string]: any}) { function sortedKeys(stringMap: {[key: string]: any}) {
var res: string[] = []; const res: string[] = [];
res.push(...Object.keys(stringMap)); res.push(...Object.keys(stringMap));
res.sort(); res.sort();
return res; return res;
@ -102,13 +102,13 @@ export function main() {
}); });
it('should describe itself based on micro metrics', () => { it('should describe itself based on micro metrics', () => {
var description = const description =
createMetric([[]], null, {microMetrics: {'myMicroMetric': 'someDesc'}}).describe(); createMetric([[]], null, {microMetrics: {'myMicroMetric': 'someDesc'}}).describe();
expect(description['myMicroMetric']).toEqual('someDesc'); expect(description['myMicroMetric']).toEqual('someDesc');
}); });
it('should describe itself if frame capture is requested and available', () => { it('should describe itself if frame capture is requested and available', () => {
var description = createMetric([[]], new PerfLogFeatures({frameCapture: true}), { const description = createMetric([[]], new PerfLogFeatures({frameCapture: true}), {
captureFrames: true captureFrames: true
}).describe(); }).describe();
expect(description['frameTime.mean']).not.toContain('WARNING'); expect(description['frameTime.mean']).not.toContain('WARNING');
@ -118,7 +118,7 @@ export function main() {
}); });
it('should describe itself if frame capture is requested and not available', () => { it('should describe itself if frame capture is requested and not available', () => {
var description = createMetric([[]], new PerfLogFeatures({frameCapture: false}), { const description = createMetric([[]], new PerfLogFeatures({frameCapture: false}), {
captureFrames: true captureFrames: true
}).describe(); }).describe();
expect(description['frameTime.mean']).toContain('WARNING'); expect(description['frameTime.mean']).toContain('WARNING');
@ -131,7 +131,7 @@ export function main() {
it('should not force gc and mark the timeline', it('should not force gc and mark the timeline',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var metric = createMetric([[]], null); const metric = createMetric([[]], null);
metric.beginMeasure().then((_) => { metric.beginMeasure().then((_) => {
expect(commandLog).toEqual([['timeBegin', 'benchpress0']]); expect(commandLog).toEqual([['timeBegin', 'benchpress0']]);
@ -141,7 +141,7 @@ export function main() {
it('should force gc and mark the timeline', it('should force gc and mark the timeline',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var metric = createMetric([[]], null, {forceGc: true}); const metric = createMetric([[]], null, {forceGc: true});
metric.beginMeasure().then((_) => { metric.beginMeasure().then((_) => {
expect(commandLog).toEqual([['gc'], ['timeBegin', 'benchpress0']]); expect(commandLog).toEqual([['gc'], ['timeBegin', 'benchpress0']]);
@ -155,11 +155,11 @@ export function main() {
it('should mark and aggregate events in between the marks', it('should mark and aggregate events in between the marks',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var events = [[ const events = [[
eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4), eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4),
eventFactory.end('script', 6), eventFactory.markEnd('benchpress0', 10) eventFactory.end('script', 6), eventFactory.markEnd('benchpress0', 10)
]]; ]];
var metric = createMetric(events, null); const metric = createMetric(events, null);
metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => {
expect(commandLog).toEqual([ expect(commandLog).toEqual([
['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', null], 'readPerfLog' ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', null], 'readPerfLog'
@ -172,13 +172,13 @@ export function main() {
it('should mark and aggregate events since navigationStart', it('should mark and aggregate events since navigationStart',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var events = [[ const events = [[
eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4), eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4),
eventFactory.end('script', 6), eventFactory.instant('navigationStart', 7), eventFactory.end('script', 6), eventFactory.instant('navigationStart', 7),
eventFactory.start('script', 8), eventFactory.end('script', 9), eventFactory.start('script', 8), eventFactory.end('script', 9),
eventFactory.markEnd('benchpress0', 10) eventFactory.markEnd('benchpress0', 10)
]]; ]];
var metric = createMetric(events, null); const metric = createMetric(events, null);
metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => {
expect(data['scriptTime']).toBe(1); expect(data['scriptTime']).toBe(1);
@ -187,7 +187,7 @@ export function main() {
})); }));
it('should restart timing', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { it('should restart timing', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var events = [ const events = [
[ [
eventFactory.markStart('benchpress0', 0), eventFactory.markStart('benchpress0', 0),
eventFactory.markEnd('benchpress0', 1), eventFactory.markEnd('benchpress0', 1),
@ -195,7 +195,7 @@ export function main() {
], ],
[eventFactory.markEnd('benchpress1', 3)] [eventFactory.markEnd('benchpress1', 3)]
]; ];
var metric = createMetric(events, null); const metric = createMetric(events, null);
metric.beginMeasure() metric.beginMeasure()
.then((_) => metric.endMeasure(true)) .then((_) => metric.endMeasure(true))
.then((_) => metric.endMeasure(true)) .then((_) => metric.endMeasure(true))
@ -211,7 +211,7 @@ export function main() {
it('should loop and aggregate until the end mark is present', it('should loop and aggregate until the end mark is present',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var events = [ const events = [
[eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 1)], [eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 1)],
[eventFactory.end('script', 2)], [eventFactory.end('script', 2)],
[ [
@ -219,7 +219,7 @@ export function main() {
eventFactory.markEnd('benchpress0', 10) eventFactory.markEnd('benchpress0', 10)
] ]
]; ];
var metric = createMetric(events, null); const metric = createMetric(events, null);
metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => {
expect(commandLog).toEqual([ expect(commandLog).toEqual([
['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', null], 'readPerfLog', ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', null], 'readPerfLog',
@ -233,7 +233,7 @@ export function main() {
it('should store events after the end mark for the next call', it('should store events after the end mark for the next call',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var events = [ const events = [
[ [
eventFactory.markStart('benchpress0', 0), eventFactory.markEnd('benchpress0', 1), eventFactory.markStart('benchpress0', 0), eventFactory.markEnd('benchpress0', 1),
eventFactory.markStart('benchpress1', 1), eventFactory.start('script', 1), eventFactory.markStart('benchpress1', 1), eventFactory.start('script', 1),
@ -244,7 +244,7 @@ export function main() {
eventFactory.markEnd('benchpress1', 6) eventFactory.markEnd('benchpress1', 6)
] ]
]; ];
var metric = createMetric(events, null); const metric = createMetric(events, null);
metric.beginMeasure() metric.beginMeasure()
.then((_) => metric.endMeasure(true)) .then((_) => metric.endMeasure(true))
.then((data) => { .then((data) => {
@ -263,7 +263,7 @@ export function main() {
})); }));
describe('with forced gc', () => { describe('with forced gc', () => {
var events: PerfLogEvent[][]; let events: PerfLogEvent[][];
beforeEach(() => { beforeEach(() => {
events = [[ events = [[
eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4), eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 4),
@ -276,7 +276,7 @@ export function main() {
}); });
it('should measure forced gc', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { it('should measure forced gc', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var metric = createMetric(events, null, {forceGc: true}); const metric = createMetric(events, null, {forceGc: true});
metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => { metric.beginMeasure().then((_) => metric.endMeasure(false)).then((data) => {
expect(commandLog).toEqual([ expect(commandLog).toEqual([
['gc'], ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', 'benchpress1'], ['gc'], ['timeBegin', 'benchpress0'], ['timeEnd', 'benchpress0', 'benchpress1'],
@ -291,7 +291,7 @@ export function main() {
it('should restart after the forced gc if needed', it('should restart after the forced gc if needed',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var metric = createMetric(events, null, {forceGc: true}); const metric = createMetric(events, null, {forceGc: true});
metric.beginMeasure().then((_) => metric.endMeasure(true)).then((data) => { metric.beginMeasure().then((_) => metric.endMeasure(true)).then((data) => {
expect(commandLog[5]).toEqual(['timeEnd', 'benchpress1', 'benchpress2']); expect(commandLog[5]).toEqual(['timeEnd', 'benchpress1', 'benchpress2']);
@ -313,7 +313,7 @@ export function main() {
} = {}) { } = {}) {
events.unshift(eventFactory.markStart('benchpress0', 0)); events.unshift(eventFactory.markStart('benchpress0', 0));
events.push(eventFactory.markEnd('benchpress0', 10)); events.push(eventFactory.markEnd('benchpress0', 10));
var metric = createMetric([events], null, { const metric = createMetric([events], null, {
microMetrics: microMetrics, microMetrics: microMetrics,
captureFrames: captureFrames, captureFrames: captureFrames,
receivedData: receivedData, receivedData: receivedData,
@ -502,8 +502,8 @@ export function main() {
it('should ignore events from different processed as the start mark', it('should ignore events from different processed as the start mark',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var otherProcessEventFactory = new TraceEventFactory('timeline', 'pid1'); const otherProcessEventFactory = new TraceEventFactory('timeline', 'pid1');
var metric = createMetric( const metric = createMetric(
[[ [[
eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 0, null), eventFactory.markStart('benchpress0', 0), eventFactory.start('script', 0, null),
eventFactory.end('script', 5, null), eventFactory.end('script', 5, null),
@ -685,7 +685,7 @@ class MockDriverExtension extends WebDriverExtension {
readPerfLog(): Promise<any> { readPerfLog(): Promise<any> {
this._commandLog.push('readPerfLog'); this._commandLog.push('readPerfLog');
if (this._perfLogs.length > 0) { if (this._perfLogs.length > 0) {
var next = this._perfLogs[0]; const next = this._perfLogs[0];
this._perfLogs.shift(); this._perfLogs.shift();
return Promise.resolve(next); return Promise.resolve(next);
} else { } else {

View File

@ -12,7 +12,7 @@ import {AsyncTestCompleter, describe, expect, inject, it} from '@angular/core/te
import {Options, PerfLogEvent, PerfLogFeatures, UserMetric, WebDriverAdapter} from '../../index'; import {Options, PerfLogEvent, PerfLogFeatures, UserMetric, WebDriverAdapter} from '../../index';
export function main() { export function main() {
var wdAdapter: MockDriverAdapter; let wdAdapter: MockDriverAdapter;
function createMetric( function createMetric(
perfLogs: PerfLogEvent[], perfLogFeatures: PerfLogFeatures, perfLogs: PerfLogEvent[], perfLogFeatures: PerfLogFeatures,
@ -25,7 +25,7 @@ export function main() {
userMetrics = {}; userMetrics = {};
} }
wdAdapter = new MockDriverAdapter(); wdAdapter = new MockDriverAdapter();
var providers: Provider[] = [ const providers: Provider[] = [
Options.DEFAULT_PROVIDERS, UserMetric.PROVIDERS, Options.DEFAULT_PROVIDERS, UserMetric.PROVIDERS,
{provide: Options.USER_METRICS, useValue: userMetrics}, {provide: Options.USER_METRICS, useValue: userMetrics},
{provide: WebDriverAdapter, useValue: wdAdapter} {provide: WebDriverAdapter, useValue: wdAdapter}
@ -45,7 +45,7 @@ export function main() {
describe('endMeasure', () => { describe('endMeasure', () => {
it('should stop measuring when all properties have numeric values', it('should stop measuring when all properties have numeric values',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
let metric = createMetric( const metric = createMetric(
[[]], new PerfLogFeatures(), [[]], new PerfLogFeatures(),
{userMetrics: {'loadTime': 'time to load', 'content': 'time to see content'}}); {userMetrics: {'loadTime': 'time to load', 'content': 'time to see content'}});
metric.beginMeasure() metric.beginMeasure()
@ -71,7 +71,7 @@ class MockDriverAdapter extends WebDriverAdapter {
executeScript(script: string): any { executeScript(script: string): any {
// Just handles `return window.propName` ignores `delete window.propName`. // Just handles `return window.propName` ignores `delete window.propName`.
if (script.indexOf('return window.') == 0) { if (script.indexOf('return window.') == 0) {
let metricName = script.substring('return window.'.length); const metricName = script.substring('return window.'.length);
return Promise.resolve(this.data[metricName]); return Promise.resolve(this.data[metricName]);
} else if (script.indexOf('delete window.') == 0) { } else if (script.indexOf('delete window.') == 0) {
return Promise.resolve(null); return Promise.resolve(null);

View File

@ -14,8 +14,8 @@ import {isBlank, isPresent} from '../../src/facade/lang';
export function main() { export function main() {
describe('console reporter', () => { describe('console reporter', () => {
var reporter: ConsoleReporter; let reporter: ConsoleReporter;
var log: string[]; let log: string[];
function createReporter( function createReporter(
{columnWidth = null, sampleId = null, descriptions = null, metrics = null}: { {columnWidth = null, sampleId = null, descriptions = null, metrics = null}: {
@ -31,7 +31,7 @@ export function main() {
if (sampleId == null) { if (sampleId == null) {
sampleId = 'null'; sampleId = 'null';
} }
var providers: Provider[] = [ const providers: Provider[] = [
ConsoleReporter.PROVIDERS, { ConsoleReporter.PROVIDERS, {
provide: SampleDescription, provide: SampleDescription,
useValue: new SampleDescription(sampleId, descriptions, metrics) useValue: new SampleDescription(sampleId, descriptions, metrics)

View File

@ -13,7 +13,7 @@ import {isPresent} from '../../src/facade/lang';
export function main() { export function main() {
describe('file reporter', () => { describe('file reporter', () => {
var loggedFile: any; let loggedFile: any;
function createReporter({sampleId, descriptions, metrics, path}: { function createReporter({sampleId, descriptions, metrics, path}: {
sampleId: string, sampleId: string,
@ -21,7 +21,7 @@ export function main() {
metrics: {[key: string]: string}, metrics: {[key: string]: string},
path: string path: string
}) { }) {
var providers = [ const providers = [
JsonFileReporter.PROVIDERS, { JsonFileReporter.PROVIDERS, {
provide: SampleDescription, provide: SampleDescription,
useValue: new SampleDescription(sampleId, descriptions, metrics) useValue: new SampleDescription(sampleId, descriptions, metrics)
@ -49,9 +49,9 @@ export function main() {
.reportSample( .reportSample(
[mv(0, 0, {'a': 3, 'b': 6})], [mv(0, 0, {'a': 3, 'b': 6})],
[mv(0, 0, {'a': 3, 'b': 6}), mv(1, 1, {'a': 5, 'b': 9})]); [mv(0, 0, {'a': 3, 'b': 6}), mv(1, 1, {'a': 5, 'b': 9})]);
var regExp = /somePath\/someId_\d+\.json/; const regExp = /somePath\/someId_\d+\.json/;
expect(isPresent(loggedFile['filename'].match(regExp))).toBe(true); expect(isPresent(loggedFile['filename'].match(regExp))).toBe(true);
var parsedContent = JSON.parse(loggedFile['content']); const parsedContent = JSON.parse(loggedFile['content']);
expect(parsedContent).toEqual({ expect(parsedContent).toEqual({
'description': { 'description': {
'id': 'someId', 'id': 'someId',

View File

@ -12,7 +12,7 @@ import {MeasureValues, MultiReporter, ReflectiveInjector, Reporter} from '../../
export function main() { export function main() {
function createReporters(ids: any[]) { function createReporters(ids: any[]) {
var r = ReflectiveInjector const r = ReflectiveInjector
.resolveAndCreate([ .resolveAndCreate([
ids.map(id => ({provide: id, useValue: new MockReporter(id)})), ids.map(id => ({provide: id, useValue: new MockReporter(id)})),
MultiReporter.provideWith(ids) MultiReporter.provideWith(ids)
@ -25,7 +25,7 @@ export function main() {
it('should reportMeasureValues to all', it('should reportMeasureValues to all',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var mv = new MeasureValues(0, new Date(), {}); const mv = new MeasureValues(0, new Date(), {});
createReporters(['m1', 'm2']).then((r) => r.reportMeasureValues(mv)).then((values) => { createReporters(['m1', 'm2']).then((r) => r.reportMeasureValues(mv)).then((values) => {
expect(values).toEqual([{'id': 'm1', 'values': mv}, {'id': 'm2', 'values': mv}]); expect(values).toEqual([{'id': 'm1', 'values': mv}, {'id': 'm2', 'values': mv}]);
@ -34,9 +34,9 @@ export function main() {
})); }));
it('should reportSample to call', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { it('should reportSample to call', inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var completeSample = const completeSample =
[new MeasureValues(0, new Date(), {}), new MeasureValues(1, new Date(), {})]; [new MeasureValues(0, new Date(), {}), new MeasureValues(1, new Date(), {})];
var validSample = [completeSample[1]]; const validSample = [completeSample[1]];
createReporters(['m1', 'm2']) createReporters(['m1', 'm2'])
.then((r) => r.reportSample(completeSample, validSample)) .then((r) => r.reportSample(completeSample, validSample))

View File

@ -12,8 +12,8 @@ import {Injector, Metric, Options, ReflectiveInjector, Runner, SampleDescription
export function main() { export function main() {
describe('runner', () => { describe('runner', () => {
var injector: ReflectiveInjector; let injector: ReflectiveInjector;
var runner: Runner; let runner: Runner;
function createRunner(defaultProviders: any[] = null): Runner { function createRunner(defaultProviders: any[] = null): Runner {
if (!defaultProviders) { if (!defaultProviders) {
@ -76,7 +76,7 @@ export function main() {
it('should provide Options.EXECUTE', it('should provide Options.EXECUTE',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var execute = () => {}; const execute = () => {};
createRunner().sample({id: 'someId', execute: execute}).then((_) => { createRunner().sample({id: 'someId', execute: execute}).then((_) => {
expect(injector.get(Options.EXECUTE)).toEqual(execute); expect(injector.get(Options.EXECUTE)).toEqual(execute);
async.done(); async.done();
@ -85,7 +85,7 @@ export function main() {
it('should provide Options.PREPARE', it('should provide Options.PREPARE',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var prepare = () => {}; const prepare = () => {};
createRunner().sample({id: 'someId', prepare: prepare}).then((_) => { createRunner().sample({id: 'someId', prepare: prepare}).then((_) => {
expect(injector.get(Options.PREPARE)).toEqual(prepare); expect(injector.get(Options.PREPARE)).toEqual(prepare);
async.done(); async.done();

View File

@ -12,10 +12,10 @@ import {MeasureValues, Metric, Options, ReflectiveInjector, Reporter, Sampler, V
import {isBlank, isPresent} from '../src/facade/lang'; import {isBlank, isPresent} from '../src/facade/lang';
export function main() { export function main() {
var EMPTY_EXECUTE = () => {}; const EMPTY_EXECUTE = () => {};
describe('sampler', () => { describe('sampler', () => {
var sampler: Sampler; let sampler: Sampler;
function createSampler({driver, metric, reporter, validator, prepare, execute}: { function createSampler({driver, metric, reporter, validator, prepare, execute}: {
driver?: any, driver?: any,
@ -25,7 +25,7 @@ export function main() {
prepare?: any, prepare?: any,
execute?: any execute?: any
} = {}) { } = {}) {
var time = 1000; let time = 1000;
if (!metric) { if (!metric) {
metric = new MockMetric([]); metric = new MockMetric([]);
} }
@ -35,7 +35,7 @@ export function main() {
if (isBlank(driver)) { if (isBlank(driver)) {
driver = new MockDriverAdapter([]); driver = new MockDriverAdapter([]);
} }
var providers = [ const providers = [
Options.DEFAULT_PROVIDERS, Sampler.PROVIDERS, {provide: Metric, useValue: metric}, Options.DEFAULT_PROVIDERS, Sampler.PROVIDERS, {provide: Metric, useValue: metric},
{provide: Reporter, useValue: reporter}, {provide: WebDriverAdapter, useValue: driver}, {provide: Reporter, useValue: reporter}, {provide: WebDriverAdapter, useValue: driver},
{provide: Options.EXECUTE, useValue: execute}, {provide: Validator, useValue: validator}, {provide: Options.EXECUTE, useValue: execute}, {provide: Validator, useValue: validator},
@ -50,10 +50,10 @@ export function main() {
it('should call the prepare and execute callbacks using WebDriverAdapter.waitFor', it('should call the prepare and execute callbacks using WebDriverAdapter.waitFor',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var log: any[] = []; const log: any[] = [];
var count = 0; let count = 0;
var driver = new MockDriverAdapter([], (callback: Function) => { const driver = new MockDriverAdapter([], (callback: Function) => {
var result = callback(); const result = callback();
log.push(result); log.push(result);
return Promise.resolve(result); return Promise.resolve(result);
}); });
@ -73,8 +73,8 @@ export function main() {
it('should call prepare, beginMeasure, execute, endMeasure for every iteration', it('should call prepare, beginMeasure, execute, endMeasure for every iteration',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var workCount = 0; let workCount = 0;
var log: any[] = []; const log: any[] = [];
createSampler({ createSampler({
metric: createCountingMetric(log), metric: createCountingMetric(log),
validator: createCountingValidator(2), validator: createCountingValidator(2),
@ -98,8 +98,8 @@ export function main() {
it('should call execute, endMeasure for every iteration if there is no prepare callback', it('should call execute, endMeasure for every iteration if there is no prepare callback',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var log: any[] = []; const log: any[] = [];
var workCount = 0; let workCount = 0;
createSampler({ createSampler({
metric: createCountingMetric(log), metric: createCountingMetric(log),
validator: createCountingValidator(2), validator: createCountingValidator(2),
@ -120,14 +120,14 @@ export function main() {
it('should only collect metrics for execute and ignore metrics from prepare', it('should only collect metrics for execute and ignore metrics from prepare',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var scriptTime = 0; let scriptTime = 0;
var iterationCount = 1; let iterationCount = 1;
createSampler({ createSampler({
validator: createCountingValidator(2), validator: createCountingValidator(2),
metric: new MockMetric( metric: new MockMetric(
[], [],
() => { () => {
var result = Promise.resolve({'script': scriptTime}); const result = Promise.resolve({'script': scriptTime});
scriptTime = 0; scriptTime = 0;
return result; return result;
}), }),
@ -147,8 +147,8 @@ export function main() {
it('should call the validator for every execution and store the valid sample', it('should call the validator for every execution and store the valid sample',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var log: any[] = []; const log: any[] = [];
var validSample = [mv(null, null, {})]; const validSample = [mv(null, null, {})];
createSampler({ createSampler({
metric: createCountingMetric(), metric: createCountingMetric(),
@ -174,8 +174,8 @@ export function main() {
it('should report the metric values', it('should report the metric values',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var log: any[] = []; const log: any[] = [];
var validSample = [mv(null, null, {})]; const validSample = [mv(null, null, {})];
createSampler({ createSampler({
validator: createCountingValidator(2, validSample), validator: createCountingValidator(2, validSample),
metric: createCountingMetric(), metric: createCountingMetric(),
@ -220,7 +220,7 @@ function createCountingValidator(
} }
function createCountingMetric(log: any[] = []) { function createCountingMetric(log: any[] = []) {
var scriptTime = 0; let scriptTime = 0;
return new MockMetric(log, () => ({'script': scriptTime++})); return new MockMetric(log, () => ({'script': scriptTime++}));
} }
@ -239,7 +239,8 @@ class MockDriverAdapter extends WebDriverAdapter {
class MockValidator extends Validator { class MockValidator extends Validator {
constructor(private _log: any[] = [], private _validate: Function = null) { super(); } constructor(private _log: any[] = [], private _validate: Function = null) { super(); }
validate(completeSample: MeasureValues[]): MeasureValues[] { validate(completeSample: MeasureValues[]): MeasureValues[] {
var stableSample = isPresent(this._validate) ? this._validate(completeSample) : completeSample; const stableSample =
isPresent(this._validate) ? this._validate(completeSample) : completeSample;
this._log.push(['validate', completeSample, stableSample]); this._log.push(['validate', completeSample, stableSample]);
return stableSample; return stableSample;
} }
@ -252,7 +253,7 @@ class MockMetric extends Metric {
return Promise.resolve(null); return Promise.resolve(null);
} }
endMeasure(restart: boolean) { endMeasure(restart: boolean) {
var measureValues = isPresent(this._endMeasure) ? this._endMeasure() : {}; const measureValues = isPresent(this._endMeasure) ? this._endMeasure() : {};
this._log.push(['endMeasure', restart, measureValues]); this._log.push(['endMeasure', restart, measureValues]);
return Promise.resolve(measureValues); return Promise.resolve(measureValues);
} }

View File

@ -13,7 +13,7 @@ export class TraceEventFactory {
constructor(private _cat: string, private _pid: string) {} constructor(private _cat: string, private _pid: string) {}
create(ph: any, name: string, time: number, args: any = null) { create(ph: any, name: string, time: number, args: any = null) {
var res: const res:
PerfLogEvent = {'name': name, 'cat': this._cat, 'ph': ph, 'ts': time, 'pid': this._pid}; PerfLogEvent = {'name': name, 'cat': this._cat, 'ph': ph, 'ts': time, 'pid': this._pid};
if (isPresent(args)) { if (isPresent(args)) {
res['args'] = args; res['args'] = args;
@ -34,7 +34,7 @@ export class TraceEventFactory {
} }
complete(name: string, time: number, duration: number, args: any = null) { complete(name: string, time: number, duration: number, args: any = null) {
var res = this.create('X', name, time, args); const res = this.create('X', name, time, args);
res['dur'] = duration; res['dur'] = duration;
return res; return res;
} }

View File

@ -12,7 +12,7 @@ import {MeasureValues, ReflectiveInjector, RegressionSlopeValidator} from '../..
export function main() { export function main() {
describe('regression slope validator', () => { describe('regression slope validator', () => {
var validator: RegressionSlopeValidator; let validator: RegressionSlopeValidator;
function createValidator({size, metric}: {size: number, metric: string}) { function createValidator({size, metric}: {size: number, metric: string}) {
validator = ReflectiveInjector validator = ReflectiveInjector
@ -42,14 +42,14 @@ export function main() {
it('should return the last sampleSize runs when the regression slope is ==0', () => { it('should return the last sampleSize runs when the regression slope is ==0', () => {
createValidator({size: 2, metric: 'script'}); createValidator({size: 2, metric: 'script'});
var sample = [mv(0, 0, {'script': 1}), mv(1, 1, {'script': 1}), mv(2, 2, {'script': 1})]; 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.slice(0, 2))).toEqual(sample.slice(0, 2));
expect(validator.validate(sample)).toEqual(sample.slice(1, 3)); expect(validator.validate(sample)).toEqual(sample.slice(1, 3));
}); });
it('should return the last sampleSize runs when the regression slope is >0', () => { it('should return the last sampleSize runs when the regression slope is >0', () => {
createValidator({size: 2, metric: 'script'}); createValidator({size: 2, metric: 'script'});
var sample = [mv(0, 0, {'script': 1}), mv(1, 1, {'script': 2}), mv(2, 2, {'script': 3})]; 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.slice(0, 2))).toEqual(sample.slice(0, 2));
expect(validator.validate(sample)).toEqual(sample.slice(1, 3)); expect(validator.validate(sample)).toEqual(sample.slice(1, 3));
}); });

View File

@ -12,7 +12,7 @@ import {MeasureValues, ReflectiveInjector, SizeValidator} from '../../index';
export function main() { export function main() {
describe('size validator', () => { describe('size validator', () => {
var validator: SizeValidator; let validator: SizeValidator;
function createValidator(size: number) { function createValidator(size: number) {
validator = validator =
@ -35,7 +35,7 @@ export function main() {
it('should return the last sampleSize runs when it has at least the given size', () => { it('should return the last sampleSize runs when it has at least the given size', () => {
createValidator(2); createValidator(2);
var sample = [mv(0, 0, {'a': 1}), mv(1, 1, {'b': 2}), mv(2, 2, {'c': 3})]; 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.slice(0, 2))).toEqual(sample.slice(0, 2));
expect(validator.validate(sample)).toEqual(sample.slice(1, 3)); expect(validator.validate(sample)).toEqual(sample.slice(1, 3));
}); });

View File

@ -14,23 +14,23 @@ import {TraceEventFactory} from '../trace_event_factory';
export function main() { export function main() {
describe('chrome driver extension', () => { describe('chrome driver extension', () => {
var CHROME45_USER_AGENT = 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"'; '"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"';
var log: any[]; let log: any[];
var extension: ChromeDriverExtension; let extension: ChromeDriverExtension;
var blinkEvents = new TraceEventFactory('blink.console', 'pid0'); const blinkEvents = new TraceEventFactory('blink.console', 'pid0');
var v8Events = new TraceEventFactory('v8', 'pid0'); const v8Events = new TraceEventFactory('v8', 'pid0');
var v8EventsOtherProcess = new TraceEventFactory('v8', 'pid1'); const v8EventsOtherProcess = new TraceEventFactory('v8', 'pid1');
var chromeTimelineEvents = const chromeTimelineEvents =
new TraceEventFactory('disabled-by-default-devtools.timeline', 'pid0'); new TraceEventFactory('disabled-by-default-devtools.timeline', 'pid0');
var chrome45TimelineEvents = new TraceEventFactory('devtools.timeline', 'pid0'); const chrome45TimelineEvents = new TraceEventFactory('devtools.timeline', 'pid0');
var chromeTimelineV8Events = new TraceEventFactory('devtools.timeline,v8', 'pid0'); const chromeTimelineV8Events = new TraceEventFactory('devtools.timeline,v8', 'pid0');
var chromeBlinkTimelineEvents = new TraceEventFactory('blink,devtools.timeline', 'pid0'); const chromeBlinkTimelineEvents = new TraceEventFactory('blink,devtools.timeline', 'pid0');
var chromeBlinkUserTimingEvents = new TraceEventFactory('blink.user_timing', 'pid0'); const chromeBlinkUserTimingEvents = new TraceEventFactory('blink.user_timing', 'pid0');
var benchmarkEvents = new TraceEventFactory('benchmark', 'pid0'); const benchmarkEvents = new TraceEventFactory('benchmark', 'pid0');
var normEvents = new TraceEventFactory('timeline', 'pid0'); const normEvents = new TraceEventFactory('timeline', 'pid0');
function createExtension( function createExtension(
perfRecords: any[] = null, userAgent: string = null, perfRecords: any[] = null, userAgent: string = null,
@ -101,7 +101,7 @@ export function main() {
it('should normalize "tdur" to "dur"', it('should normalize "tdur" to "dur"',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var event: any = chromeTimelineV8Events.create('X', 'FunctionCall', 1100, null); const event: any = chromeTimelineV8Events.create('X', 'FunctionCall', 1100, null);
event['tdur'] = 5500; event['tdur'] = 5500;
createExtension([event]).readPerfLog().then((events) => { createExtension([event]).readPerfLog().then((events) => {
expect(events).toEqual([ expect(events).toEqual([

View File

@ -13,10 +13,10 @@ import {TraceEventFactory} from '../trace_event_factory';
export function main() { export function main() {
describe('ios driver extension', () => { describe('ios driver extension', () => {
var log: any[]; let log: any[];
var extension: IOsDriverExtension; let extension: IOsDriverExtension;
var normEvents = new TraceEventFactory('timeline', 'pid0'); const normEvents = new TraceEventFactory('timeline', 'pid0');
function createExtension(perfRecords: any[] = null): WebDriverExtension { function createExtension(perfRecords: any[] = null): WebDriverExtension {
if (!perfRecords) { if (!perfRecords) {

View File

@ -150,13 +150,13 @@ export class NgFor implements DoCheck, OnChanges {
} }
for (let i = 0, ilen = this._viewContainer.length; i < ilen; i++) { for (let i = 0, ilen = this._viewContainer.length; i < ilen; i++) {
let viewRef = <EmbeddedViewRef<NgForRow>>this._viewContainer.get(i); const viewRef = <EmbeddedViewRef<NgForRow>>this._viewContainer.get(i);
viewRef.context.index = i; viewRef.context.index = i;
viewRef.context.count = ilen; viewRef.context.count = ilen;
} }
changes.forEachIdentityChange((record: any) => { changes.forEachIdentityChange((record: any) => {
let viewRef = <EmbeddedViewRef<NgForRow>>this._viewContainer.get(record.currentIndex); const viewRef = <EmbeddedViewRef<NgForRow>>this._viewContainer.get(record.currentIndex);
viewRef.context.$implicit = record.item; viewRef.context.$implicit = record.item;
}); });
} }

View File

@ -118,7 +118,7 @@ export class NgSwitch {
private _updateDefaultCases(useDefault: boolean) { private _updateDefaultCases(useDefault: boolean) {
if (this._defaultViews && useDefault !== this._defaultUsed) { if (this._defaultViews && useDefault !== this._defaultUsed) {
this._defaultUsed = useDefault; this._defaultUsed = useDefault;
for (var i = 0; i < this._defaultViews.length; i++) { for (let i = 0; i < this._defaultViews.length; i++) {
const defaultView = this._defaultViews[i]; const defaultView = this._defaultViews[i];
defaultView.enforceState(useDefault); defaultView.enforceState(useDefault);
} }

View File

@ -64,19 +64,19 @@ export class HashLocationStrategy extends LocationStrategy {
path(includeHash: boolean = false): string { path(includeHash: boolean = false): string {
// the hash value is always prefixed with a `#` // the hash value is always prefixed with a `#`
// and if it is empty then it will stay empty // and if it is empty then it will stay empty
var path = this._platformLocation.hash; let path = this._platformLocation.hash;
if (!isPresent(path)) path = '#'; if (!isPresent(path)) path = '#';
return path.length > 0 ? path.substring(1) : path; return path.length > 0 ? path.substring(1) : path;
} }
prepareExternalUrl(internal: string): string { prepareExternalUrl(internal: string): string {
var url = Location.joinWithSlash(this._baseHref, internal); const url = Location.joinWithSlash(this._baseHref, internal);
return url.length > 0 ? ('#' + url) : url; return url.length > 0 ? ('#' + url) : url;
} }
pushState(state: any, title: string, path: string, queryParams: string) { pushState(state: any, title: string, path: string, queryParams: string) {
var url = this.prepareExternalUrl(path + Location.normalizeQueryParams(queryParams)); let url = this.prepareExternalUrl(path + Location.normalizeQueryParams(queryParams));
if (url.length == 0) { if (url.length == 0) {
url = this._platformLocation.pathname; url = this._platformLocation.pathname;
} }
@ -84,7 +84,7 @@ export class HashLocationStrategy extends LocationStrategy {
} }
replaceState(state: any, title: string, path: string, queryParams: string) { replaceState(state: any, title: string, path: string, queryParams: string) {
var url = this.prepareExternalUrl(path + Location.normalizeQueryParams(queryParams)); let url = this.prepareExternalUrl(path + Location.normalizeQueryParams(queryParams));
if (url.length == 0) { if (url.length == 0) {
url = this._platformLocation.pathname; url = this._platformLocation.pathname;
} }

View File

@ -156,7 +156,7 @@ export class Location {
if (end.length == 0) { if (end.length == 0) {
return start; return start;
} }
var slashes = 0; let slashes = 0;
if (start.endsWith('/')) { if (start.endsWith('/')) {
slashes++; slashes++;
} }

View File

@ -79,12 +79,12 @@ export class PathLocationStrategy extends LocationStrategy {
} }
pushState(state: any, title: string, url: string, queryParams: string) { pushState(state: any, title: string, url: string, queryParams: string) {
var externalUrl = this.prepareExternalUrl(url + Location.normalizeQueryParams(queryParams)); const externalUrl = this.prepareExternalUrl(url + Location.normalizeQueryParams(queryParams));
this._platformLocation.pushState(state, title, externalUrl); this._platformLocation.pushState(state, title, externalUrl);
} }
replaceState(state: any, title: string, url: string, queryParams: string) { replaceState(state: any, title: string, url: string, queryParams: string) {
var externalUrl = this.prepareExternalUrl(url + Location.normalizeQueryParams(queryParams)); const externalUrl = this.prepareExternalUrl(url + Location.normalizeQueryParams(queryParams));
this._platformLocation.replaceState(state, title, externalUrl); this._platformLocation.replaceState(state, title, externalUrl);
} }

View File

@ -37,7 +37,7 @@ function formatNumber(
} }
if (digits) { if (digits) {
let parts = digits.match(_NUMBER_FORMAT_REGEXP); const parts = digits.match(_NUMBER_FORMAT_REGEXP);
if (parts === null) { if (parts === null) {
throw new Error(`${digits} is not a valid digit info for number pipes`); throw new Error(`${digits} is not a valid digit info for number pipes`);
} }

View File

@ -65,7 +65,7 @@ export function main() {
it('should add and remove classes based on changes to the expression object', async(() => { it('should add and remove classes based on changes to the expression object', async(() => {
fixture = createTestComponent('<div [ngClass]="objExpr"></div>'); fixture = createTestComponent('<div [ngClass]="objExpr"></div>');
let objExpr = getComponent().objExpr; const objExpr = getComponent().objExpr;
detectChangesAndExpectClassName('foo'); detectChangesAndExpectClassName('foo');
@ -134,7 +134,7 @@ export function main() {
it('should add and remove classes based on changes to the expression', async(() => { it('should add and remove classes based on changes to the expression', async(() => {
fixture = createTestComponent('<div [ngClass]="arrExpr"></div>'); fixture = createTestComponent('<div [ngClass]="arrExpr"></div>');
let arrExpr = getComponent().arrExpr; const arrExpr = getComponent().arrExpr;
detectChangesAndExpectClassName('foo'); detectChangesAndExpectClassName('foo');
arrExpr.push('bar'); arrExpr.push('bar');
@ -259,7 +259,7 @@ export function main() {
it('should co-operate with the class attribute', async(() => { it('should co-operate with the class attribute', async(() => {
fixture = createTestComponent('<div [ngClass]="objExpr" class="init foo"></div>'); fixture = createTestComponent('<div [ngClass]="objExpr" class="init foo"></div>');
let objExpr = getComponent().objExpr; const objExpr = getComponent().objExpr;
objExpr['bar'] = true; objExpr['bar'] = true;
detectChangesAndExpectClassName('init foo bar'); detectChangesAndExpectClassName('init foo bar');
@ -273,7 +273,7 @@ export function main() {
it('should co-operate with the interpolated class attribute', async(() => { it('should co-operate with the interpolated class attribute', async(() => {
fixture = createTestComponent(`<div [ngClass]="objExpr" class="{{'init foo'}}"></div>`); fixture = createTestComponent(`<div [ngClass]="objExpr" class="{{'init foo'}}"></div>`);
let objExpr = getComponent().objExpr; const objExpr = getComponent().objExpr;
objExpr['bar'] = true; objExpr['bar'] = true;
detectChangesAndExpectClassName(`init foo bar`); detectChangesAndExpectClassName(`init foo bar`);
@ -288,7 +288,7 @@ export function main() {
it('should co-operate with the class attribute and binding to it', async(() => { it('should co-operate with the class attribute and binding to it', async(() => {
fixture = fixture =
createTestComponent(`<div [ngClass]="objExpr" class="init" [class]="'foo'"></div>`); createTestComponent(`<div [ngClass]="objExpr" class="init" [class]="'foo'"></div>`);
let objExpr = getComponent().objExpr; const objExpr = getComponent().objExpr;
objExpr['bar'] = true; objExpr['bar'] = true;
detectChangesAndExpectClassName(`init foo bar`); detectChangesAndExpectClassName(`init foo bar`);
@ -304,7 +304,7 @@ export function main() {
const template = const template =
'<div class="init foo" [ngClass]="objExpr" [class.baz]="condition"></div>'; '<div class="init foo" [ngClass]="objExpr" [class.baz]="condition"></div>';
fixture = createTestComponent(template); fixture = createTestComponent(template);
let objExpr = getComponent().objExpr; const objExpr = getComponent().objExpr;
detectChangesAndExpectClassName('init foo baz'); detectChangesAndExpectClassName('init foo baz');
@ -322,7 +322,7 @@ export function main() {
async(() => { async(() => {
const template = '<div class="init" [ngClass]="objExpr" [class]="strExpr"></div>'; const template = '<div class="init" [ngClass]="objExpr" [class]="strExpr"></div>';
fixture = createTestComponent(template); fixture = createTestComponent(template);
let cmp = getComponent(); const cmp = getComponent();
detectChangesAndExpectClassName('init foo'); detectChangesAndExpectClassName('init foo');

View File

@ -19,10 +19,10 @@ export function main() {
describe('AsyncPipe', () => { describe('AsyncPipe', () => {
describe('Observable', () => { describe('Observable', () => {
var emitter: EventEmitter<any>; let emitter: EventEmitter<any>;
var pipe: AsyncPipe; let pipe: AsyncPipe;
var ref: any; let ref: any;
var message = {}; const message = {};
beforeEach(() => { beforeEach(() => {
emitter = new EventEmitter(); emitter = new EventEmitter();
@ -62,7 +62,7 @@ export function main() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(emitter); pipe.transform(emitter);
var newEmitter = new EventEmitter(); const newEmitter = new EventEmitter();
expect(pipe.transform(newEmitter)).toBe(null); expect(pipe.transform(newEmitter)).toBe(null);
emitter.emit(message); emitter.emit(message);
@ -104,14 +104,14 @@ export function main() {
}); });
describe('Promise', () => { describe('Promise', () => {
var message = new Object(); const message = new Object();
var pipe: AsyncPipe; let pipe: AsyncPipe;
var resolve: (result: any) => void; let resolve: (result: any) => void;
var reject: (error: any) => void; let reject: (error: any) => void;
var promise: Promise<any>; let promise: Promise<any>;
var ref: SpyChangeDetectorRef; let ref: SpyChangeDetectorRef;
// adds longer timers for passing tests in IE // adds longer timers for passing tests in IE
var timer = (getDOM() && browserDetection.isIE) ? 50 : 10; const timer = (getDOM() && browserDetection.isIE) ? 50 : 10;
beforeEach(() => { beforeEach(() => {
promise = new Promise((res, rej) => { promise = new Promise((res, rej) => {
@ -154,7 +154,7 @@ export function main() {
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
pipe.transform(promise); pipe.transform(promise);
var promise = new Promise<any>(() => {}); promise = new Promise<any>(() => {});
expect(pipe.transform(promise)).toBe(null); expect(pipe.transform(promise)).toBe(null);
// this should not affect the pipe, so it should return WrappedValue // this should not affect the pipe, so it should return WrappedValue
@ -168,7 +168,7 @@ export function main() {
it('should request a change detection check upon receiving a new value', it('should request a change detection check upon receiving a new value',
inject([AsyncTestCompleter], (async: AsyncTestCompleter) => { inject([AsyncTestCompleter], (async: AsyncTestCompleter) => {
var markForCheck = ref.spy('markForCheck'); const markForCheck = ref.spy('markForCheck');
pipe.transform(promise); pipe.transform(promise);
resolve(message); resolve(message);
@ -202,14 +202,14 @@ export function main() {
describe('null', () => { describe('null', () => {
it('should return null when given null', () => { it('should return null when given null', () => {
var pipe = new AsyncPipe(null); const pipe = new AsyncPipe(null);
expect(pipe.transform(null)).toEqual(null); expect(pipe.transform(null)).toEqual(null);
}); });
}); });
describe('other types', () => { describe('other types', () => {
it('should throw when given an invalid object', () => { it('should throw when given an invalid object', () => {
var pipe = new AsyncPipe(null); const pipe = new AsyncPipe(null);
expect(() => pipe.transform(<any>'some bogus object')).toThrowError(); expect(() => pipe.transform(<any>'some bogus object')).toThrowError();
}); });
}); });

View File

@ -62,7 +62,7 @@ export function main() {
describe('transform', () => { describe('transform', () => {
it('should format each component correctly', () => { it('should format each component correctly', () => {
let dateFixtures: any = { const dateFixtures: any = {
'y': '2015', 'y': '2015',
'yy': '15', 'yy': '15',
'M': '6', 'M': '6',
@ -75,7 +75,7 @@ export function main() {
'EEEE': 'Monday' 'EEEE': 'Monday'
}; };
let isoStringWithoutTimeFixtures: any = { const isoStringWithoutTimeFixtures: any = {
'y': '2015', 'y': '2015',
'yy': '15', 'yy': '15',
'M': '1', 'M': '1',
@ -128,7 +128,7 @@ export function main() {
}); });
it('should format common multi component patterns', () => { it('should format common multi component patterns', () => {
let dateFixtures: any = { const dateFixtures: any = {
'EEE, M/d/y': 'Mon, 6/15/2015', 'EEE, M/d/y': 'Mon, 6/15/2015',
'EEE, M/d': 'Mon, 6/15', 'EEE, M/d': 'Mon, 6/15',
'MMM d': 'Jun 15', 'MMM d': 'Jun 15',
@ -157,7 +157,7 @@ export function main() {
}); });
it('should format with pattern aliases', () => { it('should format with pattern aliases', () => {
let dateFixtures: any = { const dateFixtures: any = {
'MM/dd/yyyy': '06/15/2015', 'MM/dd/yyyy': '06/15/2015',
'fullDate': 'Monday, June 15, 2015', 'fullDate': 'Monday, June 15, 2015',
'longDate': 'June 15, 2015', 'longDate': 'June 15, 2015',

View File

@ -12,10 +12,10 @@ import {beforeEach, describe, expect, it} from '@angular/core/testing/testing_in
export function main() { export function main() {
describe('I18nPluralPipe', () => { describe('I18nPluralPipe', () => {
var localization: NgLocalization; let localization: NgLocalization;
var pipe: I18nPluralPipe; let pipe: I18nPluralPipe;
var mapping = { const mapping = {
'=0': 'No messages.', '=0': 'No messages.',
'=1': 'One message.', '=1': 'One message.',
'many': 'Many messages.', 'many': 'Many messages.',
@ -32,27 +32,27 @@ export function main() {
describe('transform', () => { describe('transform', () => {
it('should return 0 text if value is 0', () => { it('should return 0 text if value is 0', () => {
var val = pipe.transform(0, mapping); const val = pipe.transform(0, mapping);
expect(val).toEqual('No messages.'); expect(val).toEqual('No messages.');
}); });
it('should return 1 text if value is 1', () => { it('should return 1 text if value is 1', () => {
var val = pipe.transform(1, mapping); const val = pipe.transform(1, mapping);
expect(val).toEqual('One message.'); expect(val).toEqual('One message.');
}); });
it('should return category messages', () => { it('should return category messages', () => {
var val = pipe.transform(4, mapping); const val = pipe.transform(4, mapping);
expect(val).toEqual('Many messages.'); expect(val).toEqual('Many messages.');
}); });
it('should interpolate the value into the text where indicated', () => { it('should interpolate the value into the text where indicated', () => {
var val = pipe.transform(6, mapping); const val = pipe.transform(6, mapping);
expect(val).toEqual('There are 6 messages, that is 6.'); expect(val).toEqual('There are 6 messages, that is 6.');
}); });
it('should use "" if value is undefined', () => { it('should use "" if value is undefined', () => {
var val = pipe.transform(void(0), mapping); const val = pipe.transform(void(0), mapping);
expect(val).toEqual(''); expect(val).toEqual('');
}); });

View File

@ -13,10 +13,10 @@ import {expect} from '@angular/platform-browser/testing/matchers';
export function main() { export function main() {
describe('JsonPipe', () => { describe('JsonPipe', () => {
var regNewLine = '\n'; const regNewLine = '\n';
var inceptionObj: any; let inceptionObj: any;
var inceptionObjString: string; let inceptionObjString: string;
var pipe: JsonPipe; let pipe: JsonPipe;
function normalize(obj: string): string { return obj.replace(regNewLine, ''); } function normalize(obj: string): string { return obj.replace(regNewLine, ''); }
@ -39,14 +39,14 @@ export function main() {
() => { expect(pipe.transform(inceptionObj)).toEqual(inceptionObjString); }); () => { expect(pipe.transform(inceptionObj)).toEqual(inceptionObjString); });
it('should return JSON-formatted string even when normalized', () => { it('should return JSON-formatted string even when normalized', () => {
var dream1 = normalize(pipe.transform(inceptionObj)); const dream1 = normalize(pipe.transform(inceptionObj));
var dream2 = normalize(inceptionObjString); const dream2 = normalize(inceptionObjString);
expect(dream1).toEqual(dream2); expect(dream1).toEqual(dream2);
}); });
it('should return JSON-formatted string similar to Json.stringify', () => { it('should return JSON-formatted string similar to Json.stringify', () => {
var dream1 = normalize(pipe.transform(inceptionObj)); const dream1 = normalize(pipe.transform(inceptionObj));
var dream2 = normalize(JSON.stringify(inceptionObj, null, 2)); const dream2 = normalize(JSON.stringify(inceptionObj, null, 2));
expect(dream1).toEqual(dream2); expect(dream1).toEqual(dream2);
}); });
}); });
@ -63,8 +63,8 @@ export function main() {
}); });
it('should work with mutable objects', async(() => { it('should work with mutable objects', async(() => {
let fixture = TestBed.createComponent(TestComp); const fixture = TestBed.createComponent(TestComp);
let mutable: number[] = [1]; const mutable: number[] = [1];
fixture.componentInstance.data = mutable; fixture.componentInstance.data = mutable;
fixture.detectChanges(); fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('[\n 1\n]'); expect(fixture.nativeElement).toHaveText('[\n 1\n]');

View File

@ -11,9 +11,9 @@ import {beforeEach, describe, expect, it} from '@angular/core/testing/testing_in
export function main() { export function main() {
describe('LowerCasePipe', () => { describe('LowerCasePipe', () => {
var upper: string; let upper: string;
var lower: string; let lower: string;
var pipe: LowerCasePipe; let pipe: LowerCasePipe;
beforeEach(() => { beforeEach(() => {
lower = 'something'; lower = 'something';
@ -23,14 +23,14 @@ export function main() {
describe('transform', () => { describe('transform', () => {
it('should return lowercase', () => { it('should return lowercase', () => {
var val = pipe.transform(upper); const val = pipe.transform(upper);
expect(val).toEqual(lower); expect(val).toEqual(lower);
}); });
it('should lowercase when there is a new value', () => { it('should lowercase when there is a new value', () => {
var val = pipe.transform(upper); const val = pipe.transform(upper);
expect(val).toEqual(lower); expect(val).toEqual(lower);
var val2 = pipe.transform('WAT'); const val2 = pipe.transform('WAT');
expect(val2).toEqual('wat'); expect(val2).toEqual('wat');
}); });

View File

@ -13,7 +13,7 @@ import {browserDetection} from '@angular/platform-browser/testing/browser_util';
export function main() { export function main() {
describe('Number pipes', () => { describe('Number pipes', () => {
describe('DecimalPipe', () => { describe('DecimalPipe', () => {
var pipe: DecimalPipe; let pipe: DecimalPipe;
beforeEach(() => { pipe = new DecimalPipe('en-US'); }); beforeEach(() => { pipe = new DecimalPipe('en-US'); });
@ -44,7 +44,7 @@ export function main() {
}); });
describe('PercentPipe', () => { describe('PercentPipe', () => {
var pipe: PercentPipe; let pipe: PercentPipe;
beforeEach(() => { pipe = new PercentPipe('en-US'); }); beforeEach(() => { pipe = new PercentPipe('en-US'); });
@ -60,7 +60,7 @@ export function main() {
}); });
describe('CurrencyPipe', () => { describe('CurrencyPipe', () => {
var pipe: CurrencyPipe; let pipe: CurrencyPipe;
beforeEach(() => { pipe = new CurrencyPipe('en-US'); }); beforeEach(() => { pipe = new CurrencyPipe('en-US'); });

View File

@ -13,9 +13,9 @@ import {expect} from '@angular/platform-browser/testing/matchers';
export function main() { export function main() {
describe('SlicePipe', () => { describe('SlicePipe', () => {
var list: number[]; let list: number[];
var str: string; let str: string;
var pipe: SlicePipe; let pipe: SlicePipe;
beforeEach(() => { beforeEach(() => {
list = [1, 2, 3, 4, 5]; list = [1, 2, 3, 4, 5];
@ -93,8 +93,8 @@ export function main() {
}); });
it('should work with mutable arrays', async(() => { it('should work with mutable arrays', async(() => {
let fixture = TestBed.createComponent(TestComp); const fixture = TestBed.createComponent(TestComp);
let mutable: number[] = [1, 2]; const mutable: number[] = [1, 2];
fixture.componentInstance.data = mutable; fixture.componentInstance.data = mutable;
fixture.detectChanges(); fixture.detectChanges();
expect(fixture.nativeElement).toHaveText('2'); expect(fixture.nativeElement).toHaveText('2');

View File

@ -11,9 +11,9 @@ import {beforeEach, describe, expect, it} from '@angular/core/testing/testing_in
export function main() { export function main() {
describe('UpperCasePipe', () => { describe('UpperCasePipe', () => {
var upper: string; let upper: string;
var lower: string; let lower: string;
var pipe: UpperCasePipe; let pipe: UpperCasePipe;
beforeEach(() => { beforeEach(() => {
lower = 'something'; lower = 'something';
@ -24,14 +24,14 @@ export function main() {
describe('transform', () => { describe('transform', () => {
it('should return uppercase', () => { it('should return uppercase', () => {
var val = pipe.transform(lower); const val = pipe.transform(lower);
expect(val).toEqual(upper); expect(val).toEqual(upper);
}); });
it('should uppercase when there is a new value', () => { it('should uppercase when there is a new value', () => {
var val = pipe.transform(lower); const val = pipe.transform(lower);
expect(val).toEqual(upper); expect(val).toEqual(upper);
var val2 = pipe.transform('wat'); const val2 = pipe.transform('wat');
expect(val2).toEqual('WAT'); expect(val2).toEqual('WAT');
}); });

View File

@ -34,8 +34,8 @@ export class SpyLocation implements Location {
path(): string { return this._history[this._historyIndex].path; } path(): string { return this._history[this._historyIndex].path; }
isCurrentPathEqualTo(path: string, query: string = ''): boolean { isCurrentPathEqualTo(path: string, query: string = ''): boolean {
var givenPath = path.endsWith('/') ? path.substring(0, path.length - 1) : path; const givenPath = path.endsWith('/') ? path.substring(0, path.length - 1) : path;
var currPath = const currPath =
this.path().endsWith('/') ? this.path().substring(0, this.path().length - 1) : this.path(); this.path().endsWith('/') ? this.path().substring(0, this.path().length - 1) : this.path();
return currPath == givenPath + (query.length > 0 ? ('?' + query) : ''); return currPath == givenPath + (query.length > 0 ? ('?' + query) : '');
@ -66,12 +66,12 @@ export class SpyLocation implements Location {
this._history.push(new LocationState(path, query)); this._history.push(new LocationState(path, query));
this._historyIndex = this._history.length - 1; this._historyIndex = this._history.length - 1;
var locationState = this._history[this._historyIndex - 1]; const locationState = this._history[this._historyIndex - 1];
if (locationState.path == path && locationState.query == query) { if (locationState.path == path && locationState.query == query) {
return; return;
} }
var url = path + (query.length > 0 ? ('?' + query) : ''); const url = path + (query.length > 0 ? ('?' + query) : '');
this.urlChanges.push(url); this.urlChanges.push(url);
this._subject.emit({'url': url, 'pop': false}); this._subject.emit({'url': url, 'pop': false});
} }
@ -79,7 +79,7 @@ export class SpyLocation implements Location {
replaceState(path: string, query: string = '') { replaceState(path: string, query: string = '') {
path = this.prepareExternalUrl(path); path = this.prepareExternalUrl(path);
var history = this._history[this._historyIndex]; const history = this._history[this._historyIndex];
if (history.path == path && history.query == query) { if (history.path == path && history.query == query) {
return; return;
} }
@ -87,7 +87,7 @@ export class SpyLocation implements Location {
history.path = path; history.path = path;
history.query = query; history.query = query;
var url = path + (query.length > 0 ? ('?' + query) : ''); const url = path + (query.length > 0 ? ('?' + query) : '');
this.urlChanges.push('replace: ' + url); this.urlChanges.push('replace: ' + url);
} }

View File

@ -44,20 +44,20 @@ export class MockLocationStrategy extends LocationStrategy {
pushState(ctx: any, title: string, path: string, query: string): void { pushState(ctx: any, title: string, path: string, query: string): void {
this.internalTitle = title; this.internalTitle = title;
var url = path + (query.length > 0 ? ('?' + query) : ''); const url = path + (query.length > 0 ? ('?' + query) : '');
this.internalPath = url; this.internalPath = url;
var externalUrl = this.prepareExternalUrl(url); const externalUrl = this.prepareExternalUrl(url);
this.urlChanges.push(externalUrl); this.urlChanges.push(externalUrl);
} }
replaceState(ctx: any, title: string, path: string, query: string): void { replaceState(ctx: any, title: string, path: string, query: string): void {
this.internalTitle = title; this.internalTitle = title;
var url = path + (query.length > 0 ? ('?' + query) : ''); const url = path + (query.length > 0 ? ('?' + query) : '');
this.internalPath = url; this.internalPath = url;
var externalUrl = this.prepareExternalUrl(url); const externalUrl = this.prepareExternalUrl(url);
this.urlChanges.push('replace: ' + externalUrl); this.urlChanges.push('replace: ' + externalUrl);
} }
@ -68,7 +68,7 @@ export class MockLocationStrategy extends LocationStrategy {
back(): void { back(): void {
if (this.urlChanges.length > 0) { if (this.urlChanges.length > 0) {
this.urlChanges.pop(); this.urlChanges.pop();
var nextUrl = this.urlChanges.length > 0 ? this.urlChanges[this.urlChanges.length - 1] : ''; const nextUrl = this.urlChanges.length > 0 ? this.urlChanges[this.urlChanges.length - 1] : '';
this.simulatePopState(nextUrl); this.simulatePopState(nextUrl);
} }
} }

View File

@ -19,9 +19,9 @@ describe('template codegen output', () => {
it('should apply the animate states to the element', (done) => { it('should apply the animate states to the element', (done) => {
const compFixture = createComponent(AnimateCmp); const compFixture = createComponent(AnimateCmp);
var debugElement = compFixture.debugElement; const debugElement = compFixture.debugElement;
var targetDebugElement = findTargetElement(<DebugElement>debugElement); const targetDebugElement = findTargetElement(<DebugElement>debugElement);
compFixture.componentInstance.setAsOpen(); compFixture.componentInstance.setAsOpen();
compFixture.detectChanges(); compFixture.detectChanges();
@ -45,9 +45,9 @@ describe('template codegen output', () => {
it('should apply the default animate state to the element', (done) => { it('should apply the default animate state to the element', (done) => {
const compFixture = createComponent(AnimateCmp); const compFixture = createComponent(AnimateCmp);
var debugElement = compFixture.debugElement; const debugElement = compFixture.debugElement;
var targetDebugElement = findTargetElement(<DebugElement>debugElement); const targetDebugElement = findTargetElement(<DebugElement>debugElement);
compFixture.componentInstance.setAsSomethingElse(); compFixture.componentInstance.setAsSomethingElse();
compFixture.detectChanges(); compFixture.detectChanges();

View File

@ -15,8 +15,8 @@ import {createComponent} from './util';
describe('content projection', () => { describe('content projection', () => {
it('should support entryComponents in components', () => { it('should support entryComponents in components', () => {
var compFixture = createComponent(CompWithEntryComponents); const compFixture = createComponent(CompWithEntryComponents);
var cf = compFixture.componentInstance.cfr.resolveComponentFactory(BasicComp); const cf = compFixture.componentInstance.cfr.resolveComponentFactory(BasicComp);
expect(cf.componentType).toBe(BasicComp); expect(cf.componentType).toBe(BasicComp);
}); });

View File

@ -13,10 +13,10 @@ import {createComponent} from './util';
describe('content projection', () => { describe('content projection', () => {
it('should support basic content projection', () => { it('should support basic content projection', () => {
var mainCompFixture = createComponent(ProjectingComp); const mainCompFixture = createComponent(ProjectingComp);
var debugElement = mainCompFixture.debugElement; const debugElement = mainCompFixture.debugElement;
var compWithProjection = debugElement.query(By.directive(CompWithNgContent)); const compWithProjection = debugElement.query(By.directive(CompWithNgContent));
expect(compWithProjection.children.length).toBe(1); expect(compWithProjection.children.length).toBe(1);
expect(compWithProjection.children[0].attributes['greeting']).toEqual('Hello world!'); expect(compWithProjection.children[0].attributes['greeting']).toEqual('Hello world!');
}); });

View File

@ -14,18 +14,18 @@ import {createComponent} from './util';
describe('child queries', () => { describe('child queries', () => {
it('should support compiling child queries', () => { it('should support compiling child queries', () => {
var childQueryCompFixture = createComponent(CompWithChildQuery); const childQueryCompFixture = createComponent(CompWithChildQuery);
var debugElement = childQueryCompFixture.debugElement; const debugElement = childQueryCompFixture.debugElement;
var compWithChildren = debugElement.query(By.directive(CompWithChildQuery)); const compWithChildren = debugElement.query(By.directive(CompWithChildQuery));
expect(childQueryCompFixture.componentInstance.child).toBeDefined(); expect(childQueryCompFixture.componentInstance.child).toBeDefined();
expect(childQueryCompFixture.componentInstance.child instanceof CompForChildQuery).toBe(true); expect(childQueryCompFixture.componentInstance.child instanceof CompForChildQuery).toBe(true);
}); });
it('should support compiling children queries', () => { it('should support compiling children queries', () => {
var childQueryCompFixture = createComponent(CompWithChildQuery); const childQueryCompFixture = createComponent(CompWithChildQuery);
var debugElement = childQueryCompFixture.debugElement; const debugElement = childQueryCompFixture.debugElement;
var compWithChildren = debugElement.query(By.directive(CompWithChildQuery)); const compWithChildren = debugElement.query(By.directive(CompWithChildQuery));
childQueryCompFixture.detectChanges(); childQueryCompFixture.detectChanges();

View File

@ -91,7 +91,7 @@ export class Extractor {
elementSchemaRegistry, normalizer, staticReflector); elementSchemaRegistry, normalizer, staticReflector);
// TODO(vicb): implicit tags & attributes // TODO(vicb): implicit tags & attributes
let messageBundle = new compiler.MessageBundle(htmlParser, [], {}); const messageBundle = new compiler.MessageBundle(htmlParser, [], {});
return new Extractor( return new Extractor(
options, program, compilerHost, staticReflector, messageBundle, reflectorHost, resolver); options, program, compilerHost, staticReflector, messageBundle, reflectorHost, resolver);

View File

@ -34,7 +34,7 @@ export class PathMappedReflectorHost extends ReflectorHost {
getCanonicalFileName(fileName: string): string { getCanonicalFileName(fileName: string): string {
if (!fileName) return fileName; if (!fileName) return fileName;
// NB: the rootDirs should have been sorted longest-first // NB: the rootDirs should have been sorted longest-first
for (let dir of this.options.rootDirs || []) { for (const dir of this.options.rootDirs || []) {
if (fileName.indexOf(dir) === 0) { if (fileName.indexOf(dir) === 0) {
fileName = fileName.substring(dir.length); fileName = fileName.substring(dir.length);
} }
@ -86,7 +86,7 @@ export class PathMappedReflectorHost extends ReflectorHost {
return resolved && resolved.replace(EXT, '') === importedFile.replace(EXT, ''); return resolved && resolved.replace(EXT, '') === importedFile.replace(EXT, '');
}; };
let importModuleName = importedFile.replace(EXT, ''); const importModuleName = importedFile.replace(EXT, '');
const parts = importModuleName.split(path.sep).filter(p => !!p); const parts = importModuleName.split(path.sep).filter(p => !!p);
let foundRelativeImport: string; let foundRelativeImport: string;
for (let index = parts.length - 1; index >= 0; index--) { for (let index = parts.length - 1; index >= 0; index--) {

View File

@ -40,7 +40,7 @@ export class ReflectorHost implements StaticReflectorHost, ImportGenerator {
this.genDir = path.normalize(path.join(this.options.genDir, '.')).replace(/\\/g, '/'); this.genDir = path.normalize(path.join(this.options.genDir, '.')).replace(/\\/g, '/');
this.context = context || new NodeReflectorHostContext(compilerHost); this.context = context || new NodeReflectorHostContext(compilerHost);
var genPath: string = path.relative(this.basePath, this.genDir); const genPath: string = path.relative(this.basePath, this.genDir);
this.isGenDirChildOfRootDir = genPath === '' || !genPath.startsWith('..'); this.isGenDirChildOfRootDir = genPath === '' || !genPath.startsWith('..');
} }
@ -67,13 +67,13 @@ export class ReflectorHost implements StaticReflectorHost, ImportGenerator {
}; };
protected normalizeAssetUrl(url: string): string { protected normalizeAssetUrl(url: string): string {
let assetUrl = AssetUrl.parse(url); const assetUrl = AssetUrl.parse(url);
const path = assetUrl ? `${assetUrl.packageName}/${assetUrl.modulePath}` : null; const path = assetUrl ? `${assetUrl.packageName}/${assetUrl.modulePath}` : null;
return this.getCanonicalFileName(path); return this.getCanonicalFileName(path);
} }
protected resolveAssetUrl(url: string, containingFile: string): string { protected resolveAssetUrl(url: string, containingFile: string): string {
let assetUrl = this.normalizeAssetUrl(url); const assetUrl = this.normalizeAssetUrl(url);
if (assetUrl) { if (assetUrl) {
return this.getCanonicalFileName(this.resolve(assetUrl, containingFile)); return this.getCanonicalFileName(this.resolve(assetUrl, containingFile));
} }
@ -110,7 +110,7 @@ export class ReflectorHost implements StaticReflectorHost, ImportGenerator {
// drop extension // drop extension
importedFile = importedFile.replace(EXT, ''); importedFile = importedFile.replace(EXT, '');
var nodeModulesIndex = importedFile.indexOf(NODE_MODULES); const nodeModulesIndex = importedFile.indexOf(NODE_MODULES);
const importModule = nodeModulesIndex === -1 ? const importModule = nodeModulesIndex === -1 ?
null : null :
importedFile.substring(nodeModulesIndex + NODE_MODULES.length); importedFile.substring(nodeModulesIndex + NODE_MODULES.length);
@ -141,7 +141,7 @@ export class ReflectorHost implements StaticReflectorHost, ImportGenerator {
} }
private dotRelative(from: string, to: string): string { private dotRelative(from: string, to: string): string {
var rPath: string = path.relative(from, to).replace(/\\/g, '/'); const rPath: string = path.relative(from, to).replace(/\\/g, '/');
return rPath.startsWith('.') ? rPath : './' + rPath; return rPath.startsWith('.') ? rPath : './' + rPath;
} }
@ -149,7 +149,7 @@ export class ReflectorHost implements StaticReflectorHost, ImportGenerator {
* Moves the path into `genDir` folder while preserving the `node_modules` directory. * Moves the path into `genDir` folder while preserving the `node_modules` directory.
*/ */
private rewriteGenDirPath(filepath: string) { private rewriteGenDirPath(filepath: string) {
var nodeModulesIndex = filepath.indexOf(NODE_MODULES); const nodeModulesIndex = filepath.indexOf(NODE_MODULES);
if (nodeModulesIndex !== -1) { if (nodeModulesIndex !== -1) {
// If we are in node_modulse, transplant them into `genDir`. // If we are in node_modulse, transplant them into `genDir`.
return path.join(this.genDir, filepath.substring(nodeModulesIndex)); return path.join(this.genDir, filepath.substring(nodeModulesIndex));
@ -172,7 +172,7 @@ export class ReflectorHost implements StaticReflectorHost, ImportGenerator {
} }
try { try {
let assetUrl = this.normalizeAssetUrl(module); const assetUrl = this.normalizeAssetUrl(module);
if (assetUrl) { if (assetUrl) {
module = assetUrl; module = assetUrl;
} }
@ -288,7 +288,7 @@ export class ReflectorHost implements StaticReflectorHost, ImportGenerator {
} }
return resolvedModulePath; return resolvedModulePath;
}; };
let metadata = this.getResolverMetadata(filePath); const metadata = this.getResolverMetadata(filePath);
if (metadata) { if (metadata) {
// If we have metadata for the symbol, this is the original exporting location. // If we have metadata for the symbol, this is the original exporting location.
if (metadata.metadata[symbolName]) { if (metadata.metadata[symbolName]) {

View File

@ -88,7 +88,7 @@ export class StaticReflector implements ReflectorReader {
public annotations(type: StaticSymbol): any[] { public annotations(type: StaticSymbol): any[] {
let annotations = this.annotationCache.get(type); let annotations = this.annotationCache.get(type);
if (!annotations) { if (!annotations) {
let classMetadata = this.getTypeMetadata(type); const classMetadata = this.getTypeMetadata(type);
if (classMetadata['decorators']) { if (classMetadata['decorators']) {
annotations = this.simplify(type, classMetadata['decorators']); annotations = this.simplify(type, classMetadata['decorators']);
} else { } else {
@ -102,10 +102,10 @@ export class StaticReflector implements ReflectorReader {
public propMetadata(type: StaticSymbol): {[key: string]: any} { public propMetadata(type: StaticSymbol): {[key: string]: any} {
let propMetadata = this.propertyCache.get(type); let propMetadata = this.propertyCache.get(type);
if (!propMetadata) { if (!propMetadata) {
let classMetadata = this.getTypeMetadata(type); const classMetadata = this.getTypeMetadata(type);
let members = classMetadata ? classMetadata['members'] : {}; const members = classMetadata ? classMetadata['members'] : {};
propMetadata = mapStringMap(members, (propData, propName) => { propMetadata = mapStringMap(members, (propData, propName) => {
let prop = (<any[]>propData) const prop = (<any[]>propData)
.find(a => a['__symbolic'] == 'property' || a['__symbolic'] == 'method'); .find(a => a['__symbolic'] == 'property' || a['__symbolic'] == 'method');
if (prop && prop['decorators']) { if (prop && prop['decorators']) {
return this.simplify(type, prop['decorators']); return this.simplify(type, prop['decorators']);
@ -125,21 +125,21 @@ export class StaticReflector implements ReflectorReader {
try { try {
let parameters = this.parameterCache.get(type); let parameters = this.parameterCache.get(type);
if (!parameters) { if (!parameters) {
let classMetadata = this.getTypeMetadata(type); const classMetadata = this.getTypeMetadata(type);
let members = classMetadata ? classMetadata['members'] : null; const members = classMetadata ? classMetadata['members'] : null;
let ctorData = members ? members['__ctor__'] : null; const ctorData = members ? members['__ctor__'] : null;
if (ctorData) { if (ctorData) {
let ctor = (<any[]>ctorData).find(a => a['__symbolic'] == 'constructor'); const ctor = (<any[]>ctorData).find(a => a['__symbolic'] == 'constructor');
let parameterTypes = <any[]>this.simplify(type, ctor['parameters'] || []); const parameterTypes = <any[]>this.simplify(type, ctor['parameters'] || []);
let parameterDecorators = <any[]>this.simplify(type, ctor['parameterDecorators'] || []); const parameterDecorators = <any[]>this.simplify(type, ctor['parameterDecorators'] || []);
parameters = []; parameters = [];
parameterTypes.forEach((paramType, index) => { parameterTypes.forEach((paramType, index) => {
let nestedResult: any[] = []; const nestedResult: any[] = [];
if (paramType) { if (paramType) {
nestedResult.push(paramType); nestedResult.push(paramType);
} }
let decorators = parameterDecorators ? parameterDecorators[index] : null; const decorators = parameterDecorators ? parameterDecorators[index] : null;
if (decorators) { if (decorators) {
nestedResult.push(...decorators); nestedResult.push(...decorators);
} }
@ -273,7 +273,7 @@ export class StaticReflector implements ReflectorReader {
function simplifyCall(expression: any) { function simplifyCall(expression: any) {
let callContext: {[name: string]: string}|undefined = undefined; let callContext: {[name: string]: string}|undefined = undefined;
if (expression['__symbolic'] == 'call') { if (expression['__symbolic'] == 'call') {
let target = expression['expression']; const target = expression['expression'];
let functionSymbol: StaticSymbol; let functionSymbol: StaticSymbol;
let targetFunction: any; let targetFunction: any;
if (target) { if (target) {
@ -316,7 +316,7 @@ export class StaticReflector implements ReflectorReader {
for (let i = 0; i < parameters.length; i++) { for (let i = 0; i < parameters.length; i++) {
functionScope.define(parameters[i], args[i]); functionScope.define(parameters[i], args[i]);
} }
let oldScope = scope; const oldScope = scope;
let result: any; let result: any;
try { try {
scope = functionScope.done(); scope = functionScope.done();
@ -347,19 +347,19 @@ export class StaticReflector implements ReflectorReader {
return expression; return expression;
} }
if (expression instanceof Array) { if (expression instanceof Array) {
let result: any[] = []; const result: any[] = [];
for (let item of (<any>expression)) { for (const item of (<any>expression)) {
// Check for a spread expression // Check for a spread expression
if (item && item.__symbolic === 'spread') { if (item && item.__symbolic === 'spread') {
let spreadArray = simplify(item.expression); const spreadArray = simplify(item.expression);
if (Array.isArray(spreadArray)) { if (Array.isArray(spreadArray)) {
for (let spreadItem of spreadArray) { for (const spreadItem of spreadArray) {
result.push(spreadItem); result.push(spreadItem);
} }
continue; continue;
} }
} }
let value = simplify(item); const value = simplify(item);
if (shouldIgnore(value)) { if (shouldIgnore(value)) {
continue; continue;
} }
@ -466,8 +466,8 @@ export class StaticReflector implements ReflectorReader {
return null; return null;
case 'reference': case 'reference':
if (!expression.module) { if (!expression.module) {
let name: string = expression['name']; const name: string = expression['name'];
let localValue = scope.resolve(name); const localValue = scope.resolve(name);
if (localValue != BindingScope.missing) { if (localValue != BindingScope.missing) {
return localValue; return localValue;
} }
@ -614,7 +614,7 @@ function mapStringMap(input: {[key: string]: any}, transform: (value: any, key:
if (!input) return {}; if (!input) return {};
const result: {[key: string]: any} = {}; const result: {[key: string]: any} = {};
Object.keys(input).forEach((key) => { Object.keys(input).forEach((key) => {
let value = transform(input[key], key); const value = transform(input[key], key);
if (!shouldIgnore(value)) { if (!shouldIgnore(value)) {
result[key] = value; result[key] = value;
} }

View File

@ -21,7 +21,7 @@ export class MockContext implements ReflectorHostContext {
directoryExists(path: string): boolean { return typeof this.getEntry(path) === 'object'; } directoryExists(path: string): boolean { return typeof this.getEntry(path) === 'object'; }
readFile(fileName: string): string|undefined { readFile(fileName: string): string|undefined {
let data = this.getEntry(fileName); const data = this.getEntry(fileName);
if (typeof data === 'string') { if (typeof data === 'string') {
return data; return data;
} }
@ -29,9 +29,9 @@ export class MockContext implements ReflectorHostContext {
} }
writeFile(fileName: string, data: string): void { writeFile(fileName: string, data: string): void {
let parts = fileName.split('/'); const parts = fileName.split('/');
let name = parts.pop(); const name = parts.pop();
let entry = this.getEntry(parts); const entry = this.getEntry(parts);
if (entry && typeof entry !== 'string') { if (entry && typeof entry !== 'string') {
entry[name] = data; entry[name] = data;
} }
@ -48,11 +48,11 @@ export class MockContext implements ReflectorHostContext {
parts = normalize(parts); parts = normalize(parts);
let current = this.files; let current = this.files;
while (parts.length) { while (parts.length) {
let part = parts.shift(); const part = parts.shift();
if (typeof current === 'string') { if (typeof current === 'string') {
return undefined; return undefined;
} }
let next = (<Directory>current)[part]; const next = (<Directory>current)[part];
if (next === undefined) { if (next === undefined) {
return undefined; return undefined;
} }
@ -72,9 +72,9 @@ export class MockContext implements ReflectorHostContext {
} }
function normalize(parts: string[]): string[] { function normalize(parts: string[]): string[] {
let result: string[] = []; const result: string[] = [];
while (parts.length) { while (parts.length) {
let part = parts.shift(); const part = parts.shift();
switch (part) { switch (part) {
case '.': case '.':
break; break;
@ -102,7 +102,7 @@ export class MockCompilerHost implements ts.CompilerHost {
getSourceFile( getSourceFile(
fileName: string, languageVersion: ts.ScriptTarget, fileName: string, languageVersion: ts.ScriptTarget,
onError?: (message: string) => void): ts.SourceFile { onError?: (message: string) => void): ts.SourceFile {
let sourceText = this.context.readFile(fileName); const sourceText = this.context.readFile(fileName);
if (sourceText) { if (sourceText) {
return ts.createSourceFile(fileName, sourceText, languageVersion); return ts.createSourceFile(fileName, sourceText, languageVersion);
} else { } else {

View File

@ -14,11 +14,11 @@ import {ReflectorHost} from '../src/reflector_host';
import {Directory, Entry, MockCompilerHost, MockContext} from './mocks'; import {Directory, Entry, MockCompilerHost, MockContext} from './mocks';
describe('reflector_host', () => { describe('reflector_host', () => {
var context: MockContext; let context: MockContext;
var host: ts.CompilerHost; let host: ts.CompilerHost;
var program: ts.Program; let program: ts.Program;
var reflectorNestedGenDir: ReflectorHost; let reflectorNestedGenDir: ReflectorHost;
var reflectorSiblingGenDir: ReflectorHost; let reflectorSiblingGenDir: ReflectorHost;
beforeEach(() => { beforeEach(() => {
context = new MockContext('/tmp/src', clone(FILES)); context = new MockContext('/tmp/src', clone(FILES));
@ -29,7 +29,7 @@ describe('reflector_host', () => {
}, },
host); host);
// Force a typecheck // Force a typecheck
let errors = program.getSemanticDiagnostics(); const errors = program.getSemanticDiagnostics();
if (errors && errors.length) { if (errors && errors.length) {
throw new Error('Expected no errors'); throw new Error('Expected no errors');
} }
@ -122,7 +122,7 @@ describe('reflector_host', () => {
}); });
it('should provide the import locations for angular', () => { it('should provide the import locations for angular', () => {
let {coreDecorators, diDecorators, diMetadata, animationMetadata, provider} = const {coreDecorators, diDecorators, diMetadata, animationMetadata, provider} =
reflectorNestedGenDir.angularImportLocations(); reflectorNestedGenDir.angularImportLocations();
expect(coreDecorators).toEqual('@angular/core/src/metadata'); expect(coreDecorators).toEqual('@angular/core/src/metadata');
expect(diDecorators).toEqual('@angular/core/src/di/metadata'); expect(diDecorators).toEqual('@angular/core/src/di/metadata');
@ -163,8 +163,8 @@ describe('reflector_host', () => {
it('should be produce the same symbol if asked twice', () => { it('should be produce the same symbol if asked twice', () => {
let foo1 = reflectorNestedGenDir.getStaticSymbol('main.ts', 'foo'); const foo1 = reflectorNestedGenDir.getStaticSymbol('main.ts', 'foo');
let foo2 = reflectorNestedGenDir.getStaticSymbol('main.ts', 'foo'); const foo2 = reflectorNestedGenDir.getStaticSymbol('main.ts', 'foo');
expect(foo1).toBe(foo2); expect(foo1).toBe(foo2);
}); });
@ -320,8 +320,8 @@ function clone(entry: Entry): Entry {
if (typeof entry === 'string') { if (typeof entry === 'string') {
return entry; return entry;
} else { } else {
let result: Directory = {}; const result: Directory = {};
for (let name in entry) { for (const name in entry) {
result[name] = clone(entry[name]); result[name] = clone(entry[name]);
} }
return result; return result;

View File

@ -17,7 +17,7 @@ import * as ts from 'typescript';
const TS_EXT = /(^.|(?!\.d)..)\.ts$/; const TS_EXT = /(^.|(?!\.d)..)\.ts$/;
describe('StaticReflector', () => { describe('StaticReflector', () => {
let noContext = new StaticSymbol('', ''); const noContext = new StaticSymbol('', '');
let host: StaticReflectorHost; let host: StaticReflectorHost;
let reflector: StaticReflector; let reflector: StaticReflector;
@ -31,36 +31,37 @@ describe('StaticReflector', () => {
} }
it('should get annotations for NgFor', () => { it('should get annotations for NgFor', () => {
let NgFor = host.findDeclaration('angular2/src/common/directives/ng_for', 'NgFor'); const NgFor = host.findDeclaration('angular2/src/common/directives/ng_for', 'NgFor');
let annotations = reflector.annotations(NgFor); const annotations = reflector.annotations(NgFor);
expect(annotations.length).toEqual(1); expect(annotations.length).toEqual(1);
let annotation = annotations[0]; const annotation = annotations[0];
expect(annotation.selector).toEqual('[ngFor][ngForOf]'); expect(annotation.selector).toEqual('[ngFor][ngForOf]');
expect(annotation.inputs).toEqual(['ngForTrackBy', 'ngForOf', 'ngForTemplate']); expect(annotation.inputs).toEqual(['ngForTrackBy', 'ngForOf', 'ngForTemplate']);
}); });
it('should get constructor for NgFor', () => { it('should get constructor for NgFor', () => {
let NgFor = host.findDeclaration('angular2/src/common/directives/ng_for', 'NgFor'); const NgFor = host.findDeclaration('angular2/src/common/directives/ng_for', 'NgFor');
let ViewContainerRef = const ViewContainerRef =
host.findDeclaration('angular2/src/core/linker/view_container_ref', 'ViewContainerRef'); host.findDeclaration('angular2/src/core/linker/view_container_ref', 'ViewContainerRef');
let TemplateRef = host.findDeclaration('angular2/src/core/linker/template_ref', 'TemplateRef'); const TemplateRef =
let IterableDiffers = host.findDeclaration( host.findDeclaration('angular2/src/core/linker/template_ref', 'TemplateRef');
const IterableDiffers = host.findDeclaration(
'angular2/src/core/change_detection/differs/iterable_differs', 'IterableDiffers'); 'angular2/src/core/change_detection/differs/iterable_differs', 'IterableDiffers');
let ChangeDetectorRef = host.findDeclaration( const ChangeDetectorRef = host.findDeclaration(
'angular2/src/core/change_detection/change_detector_ref', 'ChangeDetectorRef'); 'angular2/src/core/change_detection/change_detector_ref', 'ChangeDetectorRef');
let parameters = reflector.parameters(NgFor); const parameters = reflector.parameters(NgFor);
expect(parameters).toEqual([ expect(parameters).toEqual([
[ViewContainerRef], [TemplateRef], [IterableDiffers], [ChangeDetectorRef] [ViewContainerRef], [TemplateRef], [IterableDiffers], [ChangeDetectorRef]
]); ]);
}); });
it('should get annotations for HeroDetailComponent', () => { it('should get annotations for HeroDetailComponent', () => {
let HeroDetailComponent = const HeroDetailComponent =
host.findDeclaration('src/app/hero-detail.component', 'HeroDetailComponent'); host.findDeclaration('src/app/hero-detail.component', 'HeroDetailComponent');
let annotations = reflector.annotations(HeroDetailComponent); const annotations = reflector.annotations(HeroDetailComponent);
expect(annotations.length).toEqual(1); expect(annotations.length).toEqual(1);
let annotation = annotations[0]; const annotation = annotations[0];
expect(annotation.selector).toEqual('my-hero-detail'); expect(annotation.selector).toEqual('my-hero-detail');
expect(annotation.animations).toEqual([trigger('myAnimation', [ expect(annotation.animations).toEqual([trigger('myAnimation', [
state('state1', style({'background': 'white'})), state('state1', style({'background': 'white'})),
@ -73,40 +74,40 @@ describe('StaticReflector', () => {
}); });
it('should throw and exception for unsupported metadata versions', () => { it('should throw and exception for unsupported metadata versions', () => {
let e = host.findDeclaration('src/version-error', 'e'); const e = host.findDeclaration('src/version-error', 'e');
expect(() => reflector.annotations(e)) expect(() => reflector.annotations(e))
.toThrow(new Error( .toThrow(new Error(
'Metadata version mismatch for module /tmp/src/version-error.d.ts, found version 100, expected 1')); 'Metadata version mismatch for module /tmp/src/version-error.d.ts, found version 100, expected 1'));
}); });
it('should get and empty annotation list for an unknown class', () => { it('should get and empty annotation list for an unknown class', () => {
let UnknownClass = host.findDeclaration('src/app/app.component', 'UnknownClass'); const UnknownClass = host.findDeclaration('src/app/app.component', 'UnknownClass');
let annotations = reflector.annotations(UnknownClass); const annotations = reflector.annotations(UnknownClass);
expect(annotations).toEqual([]); expect(annotations).toEqual([]);
}); });
it('should get propMetadata for HeroDetailComponent', () => { it('should get propMetadata for HeroDetailComponent', () => {
let HeroDetailComponent = const HeroDetailComponent =
host.findDeclaration('src/app/hero-detail.component', 'HeroDetailComponent'); host.findDeclaration('src/app/hero-detail.component', 'HeroDetailComponent');
let props = reflector.propMetadata(HeroDetailComponent); const props = reflector.propMetadata(HeroDetailComponent);
expect(props['hero']).toBeTruthy(); expect(props['hero']).toBeTruthy();
expect(props['onMouseOver']).toEqual([new HostListener('mouseover', ['$event'])]); expect(props['onMouseOver']).toEqual([new HostListener('mouseover', ['$event'])]);
}); });
it('should get an empty object from propMetadata for an unknown class', () => { it('should get an empty object from propMetadata for an unknown class', () => {
let UnknownClass = host.findDeclaration('src/app/app.component', 'UnknownClass'); const UnknownClass = host.findDeclaration('src/app/app.component', 'UnknownClass');
let properties = reflector.propMetadata(UnknownClass); const properties = reflector.propMetadata(UnknownClass);
expect(properties).toEqual({}); expect(properties).toEqual({});
}); });
it('should get empty parameters list for an unknown class ', () => { it('should get empty parameters list for an unknown class ', () => {
let UnknownClass = host.findDeclaration('src/app/app.component', 'UnknownClass'); const UnknownClass = host.findDeclaration('src/app/app.component', 'UnknownClass');
let parameters = reflector.parameters(UnknownClass); const parameters = reflector.parameters(UnknownClass);
expect(parameters).toEqual([]); expect(parameters).toEqual([]);
}); });
it('should provide context for errors reported by the collector', () => { it('should provide context for errors reported by the collector', () => {
let SomeClass = host.findDeclaration('src/error-reporting', 'SomeClass'); const SomeClass = host.findDeclaration('src/error-reporting', 'SomeClass');
expect(() => reflector.annotations(SomeClass)) expect(() => reflector.annotations(SomeClass))
.toThrow(new Error( .toThrow(new Error(
'Error encountered resolving symbol values statically. A reasonable error message (position 13:34 in the original .ts file), resolving symbol ErrorSym in /tmp/src/error-references.d.ts, resolving symbol Link2 in /tmp/src/error-references.d.ts, resolving symbol Link1 in /tmp/src/error-references.d.ts, resolving symbol SomeClass in /tmp/src/error-reporting.d.ts, resolving symbol SomeClass in /tmp/src/error-reporting.d.ts')); 'Error encountered resolving symbol values statically. A reasonable error message (position 13:34 in the original .ts file), resolving symbol ErrorSym in /tmp/src/error-references.d.ts, resolving symbol Link2 in /tmp/src/error-references.d.ts, resolving symbol Link1 in /tmp/src/error-references.d.ts, resolving symbol SomeClass in /tmp/src/error-reporting.d.ts, resolving symbol SomeClass in /tmp/src/error-reporting.d.ts'));
@ -128,7 +129,7 @@ describe('StaticReflector', () => {
}); });
it('should simplify an object to a copy of the object', () => { it('should simplify an object to a copy of the object', () => {
let expr = {a: 1, b: 2, c: 3}; const expr = {a: 1, b: 2, c: 3};
expect(simplify(noContext, expr)).toEqual(expr); expect(simplify(noContext, expr)).toEqual(expr);
}); });
@ -292,7 +293,7 @@ describe('StaticReflector', () => {
}); });
it('should simplify an object index', () => { it('should simplify an object index', () => {
let expr = {__symbolic: 'select', expression: {a: 1, b: 2, c: 3}, member: 'b'}; const expr = {__symbolic: 'select', expression: {a: 1, b: 2, c: 3}, member: 'b'};
expect(simplify(noContext, expr)).toBe(2); expect(simplify(noContext, expr)).toBe(2);
}); });
@ -373,7 +374,7 @@ describe('StaticReflector', () => {
}); });
it('should be able to get metadata from a ts file', () => { it('should be able to get metadata from a ts file', () => {
let metadata = reflector.getModuleMetadata('/tmp/src/custom-decorator-reference.ts'); const metadata = reflector.getModuleMetadata('/tmp/src/custom-decorator-reference.ts');
expect(metadata).toEqual({ expect(metadata).toEqual({
__symbolic: 'module', __symbolic: 'module',
version: 1, version: 1,
@ -404,7 +405,7 @@ describe('StaticReflector', () => {
}); });
it('should be able to get metadata for a class containing a custom decorator', () => { it('should be able to get metadata for a class containing a custom decorator', () => {
let props = reflector.propMetadata( const props = reflector.propMetadata(
host.getStaticSymbol('/tmp/src/custom-decorator-reference.ts', 'Foo')); host.getStaticSymbol('/tmp/src/custom-decorator-reference.ts', 'Foo'));
expect(props).toEqual({foo: []}); expect(props).toEqual({foo: []});
}); });
@ -477,8 +478,8 @@ class MockReflectorHost implements StaticReflectorHost {
getCanonicalFileName(fileName: string): string { return fileName; } getCanonicalFileName(fileName: string): string { return fileName; }
getStaticSymbol(declarationFile: string, name: string, members?: string[]): StaticSymbol { getStaticSymbol(declarationFile: string, name: string, members?: string[]): StaticSymbol {
var cacheKey = `${declarationFile}:${name}${members?'.'+members.join('.'):''}`; const cacheKey = `${declarationFile}:${name}${members?'.'+members.join('.'):''}`;
var result = this.staticTypeCache.get(cacheKey); let result = this.staticTypeCache.get(cacheKey);
if (!result) { if (!result) {
result = new StaticSymbol(declarationFile, name, members); result = new StaticSymbol(declarationFile, name, members);
this.staticTypeCache.set(cacheKey, result); this.staticTypeCache.set(cacheKey, result);
@ -491,7 +492,7 @@ class MockReflectorHost implements StaticReflectorHost {
function splitPath(path: string): string[] { return path.split(/\/|\\/g); } function splitPath(path: string): string[] { return path.split(/\/|\\/g); }
function resolvePath(pathParts: string[]): string { function resolvePath(pathParts: string[]): string {
let result: string[] = []; const result: string[] = [];
pathParts.forEach((part, index) => { pathParts.forEach((part, index) => {
switch (part) { switch (part) {
case '': case '':
@ -510,9 +511,9 @@ class MockReflectorHost implements StaticReflectorHost {
function pathTo(from: string, to: string): string { function pathTo(from: string, to: string): string {
let result = to; let result = to;
if (to.startsWith('.')) { if (to.startsWith('.')) {
let fromParts = splitPath(from); const fromParts = splitPath(from);
fromParts.pop(); // remove the file name. fromParts.pop(); // remove the file name.
let toParts = splitPath(to); const toParts = splitPath(to);
result = resolvePath(fromParts.concat(toParts)); result = resolvePath(fromParts.concat(toParts));
} }
return result; return result;
@ -530,7 +531,7 @@ class MockReflectorHost implements StaticReflectorHost {
} }
getMetadataFor(moduleId: string): any { getMetadataFor(moduleId: string): any {
let data: {[key: string]: any} = { const data: {[key: string]: any} = {
'/tmp/angular2/src/common/forms-deprecated/directives.d.ts': [{ '/tmp/angular2/src/common/forms-deprecated/directives.d.ts': [{
'__symbolic': 'module', '__symbolic': 'module',
'version': 1, 'version': 1,
@ -1072,11 +1073,11 @@ class MockReflectorHost implements StaticReflectorHost {
if (data[moduleId] && moduleId.match(TS_EXT)) { if (data[moduleId] && moduleId.match(TS_EXT)) {
let text = data[moduleId]; const text = data[moduleId];
if (typeof text === 'string') { if (typeof text === 'string') {
let sf = ts.createSourceFile( const sf = ts.createSourceFile(
moduleId, data[moduleId], ts.ScriptTarget.ES5, /* setParentNodes */ true); moduleId, data[moduleId], ts.ScriptTarget.ES5, /* setParentNodes */ true);
let diagnostics: ts.Diagnostic[] = (<any>sf).parseDiagnostics; const diagnostics: ts.Diagnostic[] = (<any>sf).parseDiagnostics;
if (diagnostics && diagnostics.length) { if (diagnostics && diagnostics.length) {
throw Error(`Error encountered during parse of file ${moduleId}`); throw Error(`Error encountered during parse of file ${moduleId}`);
} }

View File

@ -29,19 +29,19 @@ export class AnimationCompiler {
} }
} }
var _ANIMATION_FACTORY_ELEMENT_VAR = o.variable('element'); const _ANIMATION_FACTORY_ELEMENT_VAR = o.variable('element');
var _ANIMATION_DEFAULT_STATE_VAR = o.variable('defaultStateStyles'); const _ANIMATION_DEFAULT_STATE_VAR = o.variable('defaultStateStyles');
var _ANIMATION_FACTORY_VIEW_VAR = o.variable('view'); const _ANIMATION_FACTORY_VIEW_VAR = o.variable('view');
var _ANIMATION_FACTORY_VIEW_CONTEXT = _ANIMATION_FACTORY_VIEW_VAR.prop('animationContext'); const _ANIMATION_FACTORY_VIEW_CONTEXT = _ANIMATION_FACTORY_VIEW_VAR.prop('animationContext');
var _ANIMATION_FACTORY_RENDERER_VAR = _ANIMATION_FACTORY_VIEW_VAR.prop('renderer'); const _ANIMATION_FACTORY_RENDERER_VAR = _ANIMATION_FACTORY_VIEW_VAR.prop('renderer');
var _ANIMATION_CURRENT_STATE_VAR = o.variable('currentState'); const _ANIMATION_CURRENT_STATE_VAR = o.variable('currentState');
var _ANIMATION_NEXT_STATE_VAR = o.variable('nextState'); const _ANIMATION_NEXT_STATE_VAR = o.variable('nextState');
var _ANIMATION_PLAYER_VAR = o.variable('player'); const _ANIMATION_PLAYER_VAR = o.variable('player');
var _ANIMATION_TIME_VAR = o.variable('totalTime'); const _ANIMATION_TIME_VAR = o.variable('totalTime');
var _ANIMATION_START_STATE_STYLES_VAR = o.variable('startStateStyles'); const _ANIMATION_START_STATE_STYLES_VAR = o.variable('startStateStyles');
var _ANIMATION_END_STATE_STYLES_VAR = o.variable('endStateStyles'); const _ANIMATION_END_STATE_STYLES_VAR = o.variable('endStateStyles');
var _ANIMATION_COLLECTED_STYLES = o.variable('collectedStyles'); const _ANIMATION_COLLECTED_STYLES = o.variable('collectedStyles');
var EMPTY_MAP = o.literalMap([]); const EMPTY_MAP = o.literalMap([]);
class _AnimationBuilder implements AnimationAstVisitor { class _AnimationBuilder implements AnimationAstVisitor {
private _fnVarName: string; private _fnVarName: string;
@ -55,7 +55,7 @@ class _AnimationBuilder implements AnimationAstVisitor {
} }
visitAnimationStyles(ast: AnimationStylesAst, context: _AnimationBuilderContext): o.Expression { visitAnimationStyles(ast: AnimationStylesAst, context: _AnimationBuilderContext): o.Expression {
var stylesArr: any[] = []; const stylesArr: any[] = [];
if (context.isExpectingFirstStyleStep) { if (context.isExpectingFirstStyleStep) {
stylesArr.push(_ANIMATION_START_STATE_STYLES_VAR); stylesArr.push(_ANIMATION_START_STATE_STYLES_VAR);
context.isExpectingFirstStyleStep = false; context.isExpectingFirstStyleStep = false;
@ -86,8 +86,8 @@ class _AnimationBuilder implements AnimationAstVisitor {
return this._visitEndStateAnimation(ast, context); return this._visitEndStateAnimation(ast, context);
} }
var startingStylesExpr = ast.startingStyles.visit(this, context); const startingStylesExpr = ast.startingStyles.visit(this, context);
var keyframeExpressions = const keyframeExpressions =
ast.keyframes.map(keyframeEntry => keyframeEntry.visit(this, context)); ast.keyframes.map(keyframeEntry => keyframeEntry.visit(this, context));
return this._callAnimateMethod( return this._callAnimateMethod(
ast, startingStylesExpr, o.literalArr(keyframeExpressions), context); ast, startingStylesExpr, o.literalArr(keyframeExpressions), context);
@ -95,9 +95,9 @@ class _AnimationBuilder implements AnimationAstVisitor {
/** @internal */ /** @internal */
_visitEndStateAnimation(ast: AnimationStepAst, context: _AnimationBuilderContext): o.Expression { _visitEndStateAnimation(ast: AnimationStepAst, context: _AnimationBuilderContext): o.Expression {
var startingStylesExpr = ast.startingStyles.visit(this, context); const startingStylesExpr = ast.startingStyles.visit(this, context);
var keyframeExpressions = ast.keyframes.map(keyframe => keyframe.visit(this, context)); const keyframeExpressions = ast.keyframes.map(keyframe => keyframe.visit(this, context));
var keyframesExpr = const keyframesExpr =
o.importExpr(resolveIdentifier(Identifiers.balanceAnimationKeyframes)).callFn([ o.importExpr(resolveIdentifier(Identifiers.balanceAnimationKeyframes)).callFn([
_ANIMATION_COLLECTED_STYLES, _ANIMATION_END_STATE_STYLES_VAR, _ANIMATION_COLLECTED_STYLES, _ANIMATION_END_STATE_STYLES_VAR,
o.literalArr(keyframeExpressions) o.literalArr(keyframeExpressions)
@ -119,14 +119,14 @@ class _AnimationBuilder implements AnimationAstVisitor {
visitAnimationSequence(ast: AnimationSequenceAst, context: _AnimationBuilderContext): visitAnimationSequence(ast: AnimationSequenceAst, context: _AnimationBuilderContext):
o.Expression { o.Expression {
var playerExprs = ast.steps.map(step => step.visit(this, context)); const playerExprs = ast.steps.map(step => step.visit(this, context));
return o.importExpr(resolveIdentifier(Identifiers.AnimationSequencePlayer)).instantiate([ return o.importExpr(resolveIdentifier(Identifiers.AnimationSequencePlayer)).instantiate([
o.literalArr(playerExprs) o.literalArr(playerExprs)
]); ]);
} }
visitAnimationGroup(ast: AnimationGroupAst, context: _AnimationBuilderContext): o.Expression { visitAnimationGroup(ast: AnimationGroupAst, context: _AnimationBuilderContext): o.Expression {
var playerExprs = ast.steps.map(step => step.visit(this, context)); const playerExprs = ast.steps.map(step => step.visit(this, context));
return o.importExpr(resolveIdentifier(Identifiers.AnimationGroupPlayer)).instantiate([ return o.importExpr(resolveIdentifier(Identifiers.AnimationGroupPlayer)).instantiate([
o.literalArr(playerExprs) o.literalArr(playerExprs)
]); ]);
@ -134,7 +134,7 @@ class _AnimationBuilder implements AnimationAstVisitor {
visitAnimationStateDeclaration( visitAnimationStateDeclaration(
ast: AnimationStateDeclarationAst, context: _AnimationBuilderContext): void { ast: AnimationStateDeclarationAst, context: _AnimationBuilderContext): void {
var flatStyles: {[key: string]: string | number} = {}; const flatStyles: {[key: string]: string | number} = {};
_getStylesArray(ast).forEach( _getStylesArray(ast).forEach(
entry => { Object.keys(entry).forEach(key => { flatStyles[key] = entry[key]; }); }); entry => { Object.keys(entry).forEach(key => { flatStyles[key] = entry[key]; }); });
context.stateMap.registerState(ast.stateName, flatStyles); context.stateMap.registerState(ast.stateName, flatStyles);
@ -142,8 +142,8 @@ class _AnimationBuilder implements AnimationAstVisitor {
visitAnimationStateTransition( visitAnimationStateTransition(
ast: AnimationStateTransitionAst, context: _AnimationBuilderContext): any { ast: AnimationStateTransitionAst, context: _AnimationBuilderContext): any {
var steps = ast.animation.steps; const steps = ast.animation.steps;
var lastStep = steps[steps.length - 1]; const lastStep = steps[steps.length - 1];
if (_isEndStateAnimateStep(lastStep)) { if (_isEndStateAnimateStep(lastStep)) {
context.endStateAnimateStep = <AnimationStepAst>lastStep; context.endStateAnimateStep = <AnimationStepAst>lastStep;
} }
@ -151,7 +151,7 @@ class _AnimationBuilder implements AnimationAstVisitor {
context.totalTransitionTime = 0; context.totalTransitionTime = 0;
context.isExpectingFirstStyleStep = true; context.isExpectingFirstStyleStep = true;
var stateChangePreconditions: o.Expression[] = []; const stateChangePreconditions: o.Expression[] = [];
ast.stateChanges.forEach(stateChange => { ast.stateChanges.forEach(stateChange => {
stateChangePreconditions.push( stateChangePreconditions.push(
@ -167,14 +167,14 @@ class _AnimationBuilder implements AnimationAstVisitor {
} }
}); });
var animationPlayerExpr = ast.animation.visit(this, context); const animationPlayerExpr = ast.animation.visit(this, context);
var reducedStateChangesPrecondition = stateChangePreconditions.reduce((a, b) => a.or(b)); const reducedStateChangesPrecondition = stateChangePreconditions.reduce((a, b) => a.or(b));
var precondition = const precondition =
_ANIMATION_PLAYER_VAR.equals(o.NULL_EXPR).and(reducedStateChangesPrecondition); _ANIMATION_PLAYER_VAR.equals(o.NULL_EXPR).and(reducedStateChangesPrecondition);
var animationStmt = _ANIMATION_PLAYER_VAR.set(animationPlayerExpr).toStmt(); const animationStmt = _ANIMATION_PLAYER_VAR.set(animationPlayerExpr).toStmt();
var totalTimeStmt = _ANIMATION_TIME_VAR.set(o.literal(context.totalTransitionTime)).toStmt(); const totalTimeStmt = _ANIMATION_TIME_VAR.set(o.literal(context.totalTransitionTime)).toStmt();
return new o.IfStmt(precondition, [animationStmt, totalTimeStmt]); return new o.IfStmt(precondition, [animationStmt, totalTimeStmt]);
} }
@ -186,7 +186,7 @@ class _AnimationBuilder implements AnimationAstVisitor {
// this should always be defined even if the user overrides it // this should always be defined even if the user overrides it
context.stateMap.registerState(DEFAULT_STATE, {}); context.stateMap.registerState(DEFAULT_STATE, {});
var statements: o.Statement[] = []; const statements: o.Statement[] = [];
statements.push(_ANIMATION_FACTORY_VIEW_CONTEXT statements.push(_ANIMATION_FACTORY_VIEW_CONTEXT
.callMethod( .callMethod(
'cancelActiveAnimation', 'cancelActiveAnimation',
@ -221,7 +221,7 @@ class _AnimationBuilder implements AnimationAstVisitor {
_ANIMATION_END_STATE_STYLES_VAR.equals(o.NULL_EXPR), _ANIMATION_END_STATE_STYLES_VAR.equals(o.NULL_EXPR),
[_ANIMATION_END_STATE_STYLES_VAR.set(_ANIMATION_DEFAULT_STATE_VAR).toStmt()])); [_ANIMATION_END_STATE_STYLES_VAR.set(_ANIMATION_DEFAULT_STATE_VAR).toStmt()]));
var RENDER_STYLES_FN = o.importExpr(resolveIdentifier(Identifiers.renderStyles)); const RENDER_STYLES_FN = o.importExpr(resolveIdentifier(Identifiers.renderStyles));
// before we start any animation we want to clear out the starting // before we start any animation we want to clear out the starting
// styles from the element's style property (since they were placed // styles from the element's style property (since they were placed
@ -297,16 +297,16 @@ class _AnimationBuilder implements AnimationAstVisitor {
} }
build(ast: AnimationAst): AnimationEntryCompileResult { build(ast: AnimationAst): AnimationEntryCompileResult {
var context = new _AnimationBuilderContext(); const context = new _AnimationBuilderContext();
var fnStatement = ast.visit(this, context).toDeclStmt(this._fnVarName); const fnStatement = ast.visit(this, context).toDeclStmt(this._fnVarName);
var fnVariable = o.variable(this._fnVarName); const fnVariable = o.variable(this._fnVarName);
var lookupMap: any[] = []; const lookupMap: any[] = [];
Object.keys(context.stateMap.states).forEach(stateName => { Object.keys(context.stateMap.states).forEach(stateName => {
const value = context.stateMap.states[stateName]; const value = context.stateMap.states[stateName];
var variableValue = EMPTY_MAP; let variableValue = EMPTY_MAP;
if (isPresent(value)) { if (isPresent(value)) {
let styleMap: any[] = []; const styleMap: any[] = [];
Object.keys(value).forEach(key => { styleMap.push([key, o.literal(value[key])]); }); Object.keys(value).forEach(key => { styleMap.push([key, o.literal(value[key])]); });
variableValue = o.literalMap(styleMap); variableValue = o.literalMap(styleMap);
} }
@ -331,7 +331,7 @@ class _AnimationBuilderStateMap {
private _states: {[key: string]: {[prop: string]: string | number}} = {}; private _states: {[key: string]: {[prop: string]: string | number}} = {};
get states() { return this._states; } get states() { return this._states; }
registerState(name: string, value: {[prop: string]: string | number} = null): void { registerState(name: string, value: {[prop: string]: string | number} = null): void {
var existingEntry = this._states[name]; const existingEntry = this._states[name];
if (!existingEntry) { if (!existingEntry) {
this._states[name] = value; this._states[name] = value;
} }
@ -339,7 +339,7 @@ class _AnimationBuilderStateMap {
} }
function _compareToAnimationStateExpr(value: o.Expression, animationState: string): o.Expression { function _compareToAnimationStateExpr(value: o.Expression, animationState: string): o.Expression {
var emptyStateLiteral = o.literal(EMPTY_STATE); const emptyStateLiteral = o.literal(EMPTY_STATE);
switch (animationState) { switch (animationState) {
case EMPTY_STATE: case EMPTY_STATE:
return value.equals(emptyStateLiteral); return value.equals(emptyStateLiteral);
@ -356,8 +356,8 @@ function _isEndStateAnimateStep(step: AnimationAst): boolean {
// the final animation step is characterized by having only TWO // the final animation step is characterized by having only TWO
// keyframe values and it must have zero styles for both keyframes // keyframe values and it must have zero styles for both keyframes
if (step instanceof AnimationStepAst && step.duration > 0 && step.keyframes.length == 2) { if (step instanceof AnimationStepAst && step.duration > 0 && step.keyframes.length == 2) {
var styles1 = _getStylesArray(step.keyframes[0])[0]; const styles1 = _getStylesArray(step.keyframes[0])[0];
var styles2 = _getStylesArray(step.keyframes[1])[0]; const styles2 = _getStylesArray(step.keyframes[1])[0];
return Object.keys(styles1).length === 0 && Object.keys(styles2).length === 0; return Object.keys(styles1).length === 0 && Object.keys(styles2).length === 0;
} }
return false; return false;

View File

@ -72,11 +72,11 @@ export class AnimationParser {
} }
parseEntry(entry: CompileAnimationEntryMetadata): AnimationEntryParseResult { parseEntry(entry: CompileAnimationEntryMetadata): AnimationEntryParseResult {
var errors: AnimationParseError[] = []; const errors: AnimationParseError[] = [];
var stateStyles: {[key: string]: AnimationStylesAst} = {}; const stateStyles: {[key: string]: AnimationStylesAst} = {};
var transitions: CompileAnimationStateTransitionMetadata[] = []; const transitions: CompileAnimationStateTransitionMetadata[] = [];
var stateDeclarationAsts: AnimationStateDeclarationAst[] = []; const stateDeclarationAsts: AnimationStateDeclarationAst[] = [];
entry.definitions.forEach(def => { entry.definitions.forEach(def => {
if (def instanceof CompileAnimationStateDeclarationMetadata) { if (def instanceof CompileAnimationStateDeclarationMetadata) {
_parseAnimationDeclarationStates(def, this._schema, errors).forEach(ast => { _parseAnimationDeclarationStates(def, this._schema, errors).forEach(ast => {
@ -88,10 +88,10 @@ export class AnimationParser {
} }
}); });
var stateTransitionAsts = transitions.map( const stateTransitionAsts = transitions.map(
transDef => _parseAnimationStateTransition(transDef, stateStyles, this._schema, errors)); transDef => _parseAnimationStateTransition(transDef, stateStyles, this._schema, errors));
var ast = new AnimationEntryAst(entry.name, stateDeclarationAsts, stateTransitionAsts); const ast = new AnimationEntryAst(entry.name, stateDeclarationAsts, stateTransitionAsts);
return new AnimationEntryParseResult(ast, errors); return new AnimationEntryParseResult(ast, errors);
} }
} }
@ -99,9 +99,9 @@ export class AnimationParser {
function _parseAnimationDeclarationStates( function _parseAnimationDeclarationStates(
stateMetadata: CompileAnimationStateDeclarationMetadata, schema: ElementSchemaRegistry, stateMetadata: CompileAnimationStateDeclarationMetadata, schema: ElementSchemaRegistry,
errors: AnimationParseError[]): AnimationStateDeclarationAst[] { errors: AnimationParseError[]): AnimationStateDeclarationAst[] {
var normalizedStyles = _normalizeStyleMetadata(stateMetadata.styles, {}, schema, errors, false); const normalizedStyles = _normalizeStyleMetadata(stateMetadata.styles, {}, schema, errors, false);
var defStyles = new AnimationStylesAst(normalizedStyles); const defStyles = new AnimationStylesAst(normalizedStyles);
var states = stateMetadata.stateNameExpr.split(/\s*,\s*/); const states = stateMetadata.stateNameExpr.split(/\s*,\s*/);
return states.map(state => new AnimationStateDeclarationAst(state, defStyles)); return states.map(state => new AnimationStateDeclarationAst(state, defStyles));
} }
@ -109,19 +109,19 @@ function _parseAnimationStateTransition(
transitionStateMetadata: CompileAnimationStateTransitionMetadata, transitionStateMetadata: CompileAnimationStateTransitionMetadata,
stateStyles: {[key: string]: AnimationStylesAst}, schema: ElementSchemaRegistry, stateStyles: {[key: string]: AnimationStylesAst}, schema: ElementSchemaRegistry,
errors: AnimationParseError[]): AnimationStateTransitionAst { errors: AnimationParseError[]): AnimationStateTransitionAst {
var styles = new StylesCollection(); const styles = new StylesCollection();
var transitionExprs: AnimationStateTransitionExpression[] = []; const transitionExprs: AnimationStateTransitionExpression[] = [];
var transitionStates = transitionStateMetadata.stateChangeExpr.split(/\s*,\s*/); const transitionStates = transitionStateMetadata.stateChangeExpr.split(/\s*,\s*/);
transitionStates.forEach( transitionStates.forEach(
expr => { transitionExprs.push(..._parseAnimationTransitionExpr(expr, errors)); }); expr => { transitionExprs.push(..._parseAnimationTransitionExpr(expr, errors)); });
var entry = _normalizeAnimationEntry(transitionStateMetadata.steps); const entry = _normalizeAnimationEntry(transitionStateMetadata.steps);
var animation = _normalizeStyleSteps(entry, stateStyles, schema, errors); const animation = _normalizeStyleSteps(entry, stateStyles, schema, errors);
var animationAst = _parseTransitionAnimation(animation, 0, styles, stateStyles, errors); const animationAst = _parseTransitionAnimation(animation, 0, styles, stateStyles, errors);
if (errors.length == 0) { if (errors.length == 0) {
_fillAnimationAstStartingKeyframes(animationAst, styles, errors); _fillAnimationAstStartingKeyframes(animationAst, styles, errors);
} }
var stepsAst: AnimationWithStepsAst = (animationAst instanceof AnimationWithStepsAst) ? const stepsAst: AnimationWithStepsAst = (animationAst instanceof AnimationWithStepsAst) ?
animationAst : animationAst :
new AnimationSequenceAst([animationAst]); new AnimationSequenceAst([animationAst]);
@ -143,22 +143,22 @@ function _parseAnimationAlias(alias: string, errors: AnimationParseError[]): str
function _parseAnimationTransitionExpr( function _parseAnimationTransitionExpr(
eventStr: string, errors: AnimationParseError[]): AnimationStateTransitionExpression[] { eventStr: string, errors: AnimationParseError[]): AnimationStateTransitionExpression[] {
var expressions: AnimationStateTransitionExpression[] = []; const expressions: AnimationStateTransitionExpression[] = [];
if (eventStr[0] == ':') { if (eventStr[0] == ':') {
eventStr = _parseAnimationAlias(eventStr, errors); eventStr = _parseAnimationAlias(eventStr, errors);
} }
var match = eventStr.match(/^(\*|[-\w]+)\s*(<?[=-]>)\s*(\*|[-\w]+)$/); const match = eventStr.match(/^(\*|[-\w]+)\s*(<?[=-]>)\s*(\*|[-\w]+)$/);
if (!isPresent(match) || match.length < 4) { if (!isPresent(match) || match.length < 4) {
errors.push(new AnimationParseError(`the provided ${eventStr} is not of a supported format`)); errors.push(new AnimationParseError(`the provided ${eventStr} is not of a supported format`));
return expressions; return expressions;
} }
var fromState = match[1]; const fromState = match[1];
var separator = match[2]; const separator = match[2];
var toState = match[3]; const toState = match[3];
expressions.push(new AnimationStateTransitionExpression(fromState, toState)); expressions.push(new AnimationStateTransitionExpression(fromState, toState));
var isFullAnyStateExpr = fromState == ANY_STATE && toState == ANY_STATE; const isFullAnyStateExpr = fromState == ANY_STATE && toState == ANY_STATE;
if (separator[0] == '<' && !isFullAnyStateExpr) { if (separator[0] == '<' && !isFullAnyStateExpr) {
expressions.push(new AnimationStateTransitionExpression(toState, fromState)); expressions.push(new AnimationStateTransitionExpression(toState, fromState));
} }
@ -174,7 +174,7 @@ function _normalizeStyleMetadata(
entry: CompileAnimationStyleMetadata, stateStyles: {[key: string]: AnimationStylesAst}, entry: CompileAnimationStyleMetadata, stateStyles: {[key: string]: AnimationStylesAst},
schema: ElementSchemaRegistry, errors: AnimationParseError[], schema: ElementSchemaRegistry, errors: AnimationParseError[],
permitStateReferences: boolean): {[key: string]: string | number}[] { permitStateReferences: boolean): {[key: string]: string | number}[] {
var normalizedStyles: {[key: string]: string | number}[] = []; const normalizedStyles: {[key: string]: string | number}[] = [];
entry.styles.forEach(styleEntry => { entry.styles.forEach(styleEntry => {
if (typeof styleEntry === 'string') { if (typeof styleEntry === 'string') {
if (permitStateReferences) { if (permitStateReferences) {
@ -184,13 +184,13 @@ function _normalizeStyleMetadata(
`State based animations cannot contain references to other states`)); `State based animations cannot contain references to other states`));
} }
} else { } else {
var stylesObj = <Styles>styleEntry; const stylesObj = <Styles>styleEntry;
var normalizedStylesObj: Styles = {}; const normalizedStylesObj: Styles = {};
Object.keys(stylesObj).forEach(propName => { Object.keys(stylesObj).forEach(propName => {
var normalizedProp = schema.normalizeAnimationStyleProperty(propName); const normalizedProp = schema.normalizeAnimationStyleProperty(propName);
var normalizedOutput = const normalizedOutput =
schema.normalizeAnimationStyleValue(normalizedProp, propName, stylesObj[propName]); schema.normalizeAnimationStyleValue(normalizedProp, propName, stylesObj[propName]);
var normalizationError = normalizedOutput['error']; const normalizationError = normalizedOutput['error'];
if (normalizationError) { if (normalizationError) {
errors.push(new AnimationParseError(normalizationError)); errors.push(new AnimationParseError(normalizationError));
} }
@ -205,7 +205,7 @@ function _normalizeStyleMetadata(
function _normalizeStyleSteps( function _normalizeStyleSteps(
entry: CompileAnimationMetadata, stateStyles: {[key: string]: AnimationStylesAst}, entry: CompileAnimationMetadata, stateStyles: {[key: string]: AnimationStylesAst},
schema: ElementSchemaRegistry, errors: AnimationParseError[]): CompileAnimationMetadata { schema: ElementSchemaRegistry, errors: AnimationParseError[]): CompileAnimationMetadata {
var steps = _normalizeStyleStepEntry(entry, stateStyles, schema, errors); const steps = _normalizeStyleStepEntry(entry, stateStyles, schema, errors);
return (entry instanceof CompileAnimationGroupMetadata) ? return (entry instanceof CompileAnimationGroupMetadata) ?
new CompileAnimationGroupMetadata(steps) : new CompileAnimationGroupMetadata(steps) :
new CompileAnimationSequenceMetadata(steps); new CompileAnimationSequenceMetadata(steps);
@ -214,8 +214,8 @@ function _normalizeStyleSteps(
function _mergeAnimationStyles( function _mergeAnimationStyles(
stylesList: any[], newItem: {[key: string]: string | number} | string) { stylesList: any[], newItem: {[key: string]: string | number} | string) {
if (typeof newItem === 'object' && newItem !== null && stylesList.length > 0) { if (typeof newItem === 'object' && newItem !== null && stylesList.length > 0) {
var lastIndex = stylesList.length - 1; const lastIndex = stylesList.length - 1;
var lastItem = stylesList[lastIndex]; const lastItem = stylesList[lastIndex];
if (typeof lastItem === 'object' && lastItem !== null) { if (typeof lastItem === 'object' && lastItem !== null) {
stylesList[lastIndex] = StringMapWrapper.merge( stylesList[lastIndex] = StringMapWrapper.merge(
<{[key: string]: string | number}>lastItem, <{[key: string]: string | number}>newItem); <{[key: string]: string | number}>lastItem, <{[key: string]: string | number}>newItem);
@ -228,15 +228,15 @@ function _mergeAnimationStyles(
function _normalizeStyleStepEntry( function _normalizeStyleStepEntry(
entry: CompileAnimationMetadata, stateStyles: {[key: string]: AnimationStylesAst}, entry: CompileAnimationMetadata, stateStyles: {[key: string]: AnimationStylesAst},
schema: ElementSchemaRegistry, errors: AnimationParseError[]): CompileAnimationMetadata[] { schema: ElementSchemaRegistry, errors: AnimationParseError[]): CompileAnimationMetadata[] {
var steps: CompileAnimationMetadata[]; let steps: CompileAnimationMetadata[];
if (entry instanceof CompileAnimationWithStepsMetadata) { if (entry instanceof CompileAnimationWithStepsMetadata) {
steps = entry.steps; steps = entry.steps;
} else { } else {
return [entry]; return [entry];
} }
var newSteps: CompileAnimationMetadata[] = []; const newSteps: CompileAnimationMetadata[] = [];
var combinedStyles: Styles[]; let combinedStyles: Styles[];
steps.forEach(step => { steps.forEach(step => {
if (step instanceof CompileAnimationStyleMetadata) { if (step instanceof CompileAnimationStyleMetadata) {
// this occurs when a style step is followed by a previous style step // this occurs when a style step is followed by a previous style step
@ -262,7 +262,7 @@ function _normalizeStyleStepEntry(
if (step instanceof CompileAnimationAnimateMetadata) { if (step instanceof CompileAnimationAnimateMetadata) {
// we do not recurse into CompileAnimationAnimateMetadata since // we do not recurse into CompileAnimationAnimateMetadata since
// those style steps are not going to be squashed // those style steps are not going to be squashed
var animateStyleValue = (<CompileAnimationAnimateMetadata>step).styles; const animateStyleValue = (<CompileAnimationAnimateMetadata>step).styles;
if (animateStyleValue instanceof CompileAnimationStyleMetadata) { if (animateStyleValue instanceof CompileAnimationStyleMetadata) {
animateStyleValue.styles = animateStyleValue.styles =
_normalizeStyleMetadata(animateStyleValue, stateStyles, schema, errors, true); _normalizeStyleMetadata(animateStyleValue, stateStyles, schema, errors, true);
@ -272,7 +272,7 @@ function _normalizeStyleStepEntry(
}); });
} }
} else if (step instanceof CompileAnimationWithStepsMetadata) { } else if (step instanceof CompileAnimationWithStepsMetadata) {
let innerSteps = _normalizeStyleStepEntry(step, stateStyles, schema, errors); const innerSteps = _normalizeStyleStepEntry(step, stateStyles, schema, errors);
step = step instanceof CompileAnimationGroupMetadata ? step = step instanceof CompileAnimationGroupMetadata ?
new CompileAnimationGroupMetadata(innerSteps) : new CompileAnimationGroupMetadata(innerSteps) :
new CompileAnimationSequenceMetadata(innerSteps); new CompileAnimationSequenceMetadata(innerSteps);
@ -294,12 +294,12 @@ function _normalizeStyleStepEntry(
function _resolveStylesFromState( function _resolveStylesFromState(
stateName: string, stateStyles: {[key: string]: AnimationStylesAst}, stateName: string, stateStyles: {[key: string]: AnimationStylesAst},
errors: AnimationParseError[]) { errors: AnimationParseError[]) {
var styles: Styles[] = []; const styles: Styles[] = [];
if (stateName[0] != ':') { if (stateName[0] != ':') {
errors.push(new AnimationParseError(`Animation states via styles must be prefixed with a ":"`)); errors.push(new AnimationParseError(`Animation states via styles must be prefixed with a ":"`));
} else { } else {
var normalizedStateName = stateName.substring(1); const normalizedStateName = stateName.substring(1);
var value = stateStyles[normalizedStateName]; const value = stateStyles[normalizedStateName];
if (!isPresent(value)) { if (!isPresent(value)) {
errors.push(new AnimationParseError( errors.push(new AnimationParseError(
`Unable to apply styles due to missing a state: "${normalizedStateName}"`)); `Unable to apply styles due to missing a state: "${normalizedStateName}"`));
@ -322,8 +322,8 @@ function _parseAnimationKeyframes(
keyframeSequence: CompileAnimationKeyframesSequenceMetadata, currentTime: number, keyframeSequence: CompileAnimationKeyframesSequenceMetadata, currentTime: number,
collectedStyles: StylesCollection, stateStyles: {[key: string]: AnimationStylesAst}, collectedStyles: StylesCollection, stateStyles: {[key: string]: AnimationStylesAst},
errors: AnimationParseError[]): AnimationKeyframeAst[] { errors: AnimationParseError[]): AnimationKeyframeAst[] {
var totalEntries = keyframeSequence.steps.length; const totalEntries = keyframeSequence.steps.length;
var totalOffsets = 0; let totalOffsets = 0;
keyframeSequence.steps.forEach(step => totalOffsets += (isPresent(step.offset) ? 1 : 0)); keyframeSequence.steps.forEach(step => totalOffsets += (isPresent(step.offset) ? 1 : 0));
if (totalOffsets > 0 && totalOffsets < totalEntries) { if (totalOffsets > 0 && totalOffsets < totalEntries) {
@ -332,15 +332,15 @@ function _parseAnimationKeyframes(
totalOffsets = totalEntries; totalOffsets = totalEntries;
} }
var limit = totalEntries - 1; let limit = totalEntries - 1;
var margin = totalOffsets == 0 ? (1 / limit) : 0; const margin = totalOffsets == 0 ? (1 / limit) : 0;
var rawKeyframes: any[] /** TODO #9100 */ = []; const rawKeyframes: any[] /** TODO #9100 */ = [];
var index = 0; let index = 0;
var doSortKeyframes = false; let doSortKeyframes = false;
var lastOffset = 0; let lastOffset = 0;
keyframeSequence.steps.forEach(styleMetadata => { keyframeSequence.steps.forEach(styleMetadata => {
var offset = styleMetadata.offset; let offset = styleMetadata.offset;
var keyframeStyles: Styles = {}; const keyframeStyles: Styles = {};
styleMetadata.styles.forEach(entry => { styleMetadata.styles.forEach(entry => {
Object.keys(entry).forEach(prop => { Object.keys(entry).forEach(prop => {
if (prop != 'offset') { if (prop != 'offset') {
@ -364,23 +364,23 @@ function _parseAnimationKeyframes(
rawKeyframes.sort((a, b) => a[0] <= b[0] ? -1 : 1); rawKeyframes.sort((a, b) => a[0] <= b[0] ? -1 : 1);
} }
var firstKeyframe = rawKeyframes[0]; let firstKeyframe = rawKeyframes[0];
if (firstKeyframe[0] != _INITIAL_KEYFRAME) { if (firstKeyframe[0] != _INITIAL_KEYFRAME) {
rawKeyframes.splice(0, 0, firstKeyframe = [_INITIAL_KEYFRAME, {}]); rawKeyframes.splice(0, 0, firstKeyframe = [_INITIAL_KEYFRAME, {}]);
} }
var firstKeyframeStyles = firstKeyframe[1]; const firstKeyframeStyles = firstKeyframe[1];
limit = rawKeyframes.length - 1; limit = rawKeyframes.length - 1;
var lastKeyframe = rawKeyframes[limit]; let lastKeyframe = rawKeyframes[limit];
if (lastKeyframe[0] != _TERMINAL_KEYFRAME) { if (lastKeyframe[0] != _TERMINAL_KEYFRAME) {
rawKeyframes.push(lastKeyframe = [_TERMINAL_KEYFRAME, {}]); rawKeyframes.push(lastKeyframe = [_TERMINAL_KEYFRAME, {}]);
limit++; limit++;
} }
var lastKeyframeStyles = lastKeyframe[1]; const lastKeyframeStyles = lastKeyframe[1];
for (let i = 1; i <= limit; i++) { for (let i = 1; i <= limit; i++) {
let entry = rawKeyframes[i]; const entry = rawKeyframes[i];
let styles = entry[1]; const styles = entry[1];
Object.keys(styles).forEach(prop => { Object.keys(styles).forEach(prop => {
if (!isPresent(firstKeyframeStyles[prop])) { if (!isPresent(firstKeyframeStyles[prop])) {
@ -390,8 +390,8 @@ function _parseAnimationKeyframes(
} }
for (let i = limit - 1; i >= 0; i--) { for (let i = limit - 1; i >= 0; i--) {
let entry = rawKeyframes[i]; const entry = rawKeyframes[i];
let styles = entry[1]; const styles = entry[1];
Object.keys(styles).forEach(prop => { Object.keys(styles).forEach(prop => {
if (!isPresent(lastKeyframeStyles[prop])) { if (!isPresent(lastKeyframeStyles[prop])) {
@ -407,21 +407,21 @@ function _parseAnimationKeyframes(
function _parseTransitionAnimation( function _parseTransitionAnimation(
entry: CompileAnimationMetadata, currentTime: number, collectedStyles: StylesCollection, entry: CompileAnimationMetadata, currentTime: number, collectedStyles: StylesCollection,
stateStyles: {[key: string]: AnimationStylesAst}, errors: AnimationParseError[]): AnimationAst { stateStyles: {[key: string]: AnimationStylesAst}, errors: AnimationParseError[]): AnimationAst {
var ast: any /** TODO #9100 */; let ast: any /** TODO #9100 */;
var playTime = 0; let playTime = 0;
var startingTime = currentTime; const startingTime = currentTime;
if (entry instanceof CompileAnimationWithStepsMetadata) { if (entry instanceof CompileAnimationWithStepsMetadata) {
var maxDuration = 0; let maxDuration = 0;
var steps: any[] /** TODO #9100 */ = []; const steps: any[] /** TODO #9100 */ = [];
var isGroup = entry instanceof CompileAnimationGroupMetadata; const isGroup = entry instanceof CompileAnimationGroupMetadata;
var previousStyles: any /** TODO #9100 */; let previousStyles: any /** TODO #9100 */;
entry.steps.forEach(entry => { entry.steps.forEach(entry => {
// these will get picked up by the next step... // these will get picked up by the next step...
var time = isGroup ? startingTime : currentTime; const time = isGroup ? startingTime : currentTime;
if (entry instanceof CompileAnimationStyleMetadata) { if (entry instanceof CompileAnimationStyleMetadata) {
entry.styles.forEach(stylesEntry => { entry.styles.forEach(stylesEntry => {
// by this point we know that we only have stringmap values // by this point we know that we only have stringmap values
var map = stylesEntry as Styles; const map = stylesEntry as Styles;
Object.keys(map).forEach( Object.keys(map).forEach(
prop => { collectedStyles.insertAtTime(prop, time, map[prop]); }); prop => { collectedStyles.insertAtTime(prop, time, map[prop]); });
}); });
@ -429,26 +429,26 @@ function _parseTransitionAnimation(
return; return;
} }
var innerAst = _parseTransitionAnimation(entry, time, collectedStyles, stateStyles, errors); const innerAst = _parseTransitionAnimation(entry, time, collectedStyles, stateStyles, errors);
if (isPresent(previousStyles)) { if (isPresent(previousStyles)) {
if (entry instanceof CompileAnimationWithStepsMetadata) { if (entry instanceof CompileAnimationWithStepsMetadata) {
let startingStyles = new AnimationStylesAst(previousStyles); const startingStyles = new AnimationStylesAst(previousStyles);
steps.push(new AnimationStepAst(startingStyles, [], 0, 0, '')); steps.push(new AnimationStepAst(startingStyles, [], 0, 0, ''));
} else { } else {
var innerStep = <AnimationStepAst>innerAst; const innerStep = <AnimationStepAst>innerAst;
innerStep.startingStyles.styles.push(...previousStyles); innerStep.startingStyles.styles.push(...previousStyles);
} }
previousStyles = null; previousStyles = null;
} }
var astDuration = innerAst.playTime; const astDuration = innerAst.playTime;
currentTime += astDuration; currentTime += astDuration;
playTime += astDuration; playTime += astDuration;
maxDuration = Math.max(astDuration, maxDuration); maxDuration = Math.max(astDuration, maxDuration);
steps.push(innerAst); steps.push(innerAst);
}); });
if (isPresent(previousStyles)) { if (isPresent(previousStyles)) {
let startingStyles = new AnimationStylesAst(previousStyles); const startingStyles = new AnimationStylesAst(previousStyles);
steps.push(new AnimationStepAst(startingStyles, [], 0, 0, '')); steps.push(new AnimationStepAst(startingStyles, [], 0, 0, ''));
} }
if (isGroup) { if (isGroup) {
@ -459,18 +459,18 @@ function _parseTransitionAnimation(
ast = new AnimationSequenceAst(steps); ast = new AnimationSequenceAst(steps);
} }
} else if (entry instanceof CompileAnimationAnimateMetadata) { } else if (entry instanceof CompileAnimationAnimateMetadata) {
var timings = _parseTimeExpression(entry.timings, errors); const timings = _parseTimeExpression(entry.timings, errors);
var styles = entry.styles; const styles = entry.styles;
var keyframes: any /** TODO #9100 */; let keyframes: any /** TODO #9100 */;
if (styles instanceof CompileAnimationKeyframesSequenceMetadata) { if (styles instanceof CompileAnimationKeyframesSequenceMetadata) {
keyframes = keyframes =
_parseAnimationKeyframes(styles, currentTime, collectedStyles, stateStyles, errors); _parseAnimationKeyframes(styles, currentTime, collectedStyles, stateStyles, errors);
} else { } else {
let styleData = <CompileAnimationStyleMetadata>styles; const styleData = <CompileAnimationStyleMetadata>styles;
let offset = _TERMINAL_KEYFRAME; const offset = _TERMINAL_KEYFRAME;
let styleAst = new AnimationStylesAst(styleData.styles as Styles[]); const styleAst = new AnimationStylesAst(styleData.styles as Styles[]);
var keyframe = new AnimationKeyframeAst(offset, styleAst); const keyframe = new AnimationKeyframeAst(offset, styleAst);
keyframes = [keyframe]; keyframes = [keyframe];
} }
@ -499,10 +499,10 @@ function _fillAnimationAstStartingKeyframes(
ast: AnimationAst, collectedStyles: StylesCollection, errors: AnimationParseError[]): void { ast: AnimationAst, collectedStyles: StylesCollection, errors: AnimationParseError[]): void {
// steps that only contain style will not be filled // steps that only contain style will not be filled
if ((ast instanceof AnimationStepAst) && ast.keyframes.length > 0) { if ((ast instanceof AnimationStepAst) && ast.keyframes.length > 0) {
var keyframes = ast.keyframes; const keyframes = ast.keyframes;
if (keyframes.length == 1) { if (keyframes.length == 1) {
var endKeyframe = keyframes[0]; const endKeyframe = keyframes[0];
var startKeyframe = _createStartKeyframeFromEndKeyframe( const startKeyframe = _createStartKeyframeFromEndKeyframe(
endKeyframe, ast.startTime, ast.playTime, collectedStyles, errors); endKeyframe, ast.startTime, ast.playTime, collectedStyles, errors);
ast.keyframes = [startKeyframe, endKeyframe]; ast.keyframes = [startKeyframe, endKeyframe];
} }
@ -513,10 +513,10 @@ function _fillAnimationAstStartingKeyframes(
function _parseTimeExpression( function _parseTimeExpression(
exp: string | number, errors: AnimationParseError[]): _AnimationTimings { exp: string | number, errors: AnimationParseError[]): _AnimationTimings {
var regex = /^([\.\d]+)(m?s)(?:\s+([\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?/i; const regex = /^([\.\d]+)(m?s)(?:\s+([\.\d]+)(m?s))?(?:\s+([-a-z]+(?:\(.+?\))?))?/i;
var duration: number; let duration: number;
var delay: number = 0; let delay: number = 0;
var easing: string = null; let easing: string = null;
if (typeof exp === 'string') { if (typeof exp === 'string') {
const matches = exp.match(regex); const matches = exp.match(regex);
if (matches === null) { if (matches === null) {
@ -524,24 +524,24 @@ function _parseTimeExpression(
return new _AnimationTimings(0, 0, null); return new _AnimationTimings(0, 0, null);
} }
var durationMatch = parseFloat(matches[1]); let durationMatch = parseFloat(matches[1]);
var durationUnit = matches[2]; const durationUnit = matches[2];
if (durationUnit == 's') { if (durationUnit == 's') {
durationMatch *= _ONE_SECOND; durationMatch *= _ONE_SECOND;
} }
duration = Math.floor(durationMatch); duration = Math.floor(durationMatch);
var delayMatch = matches[3]; const delayMatch = matches[3];
var delayUnit = matches[4]; const delayUnit = matches[4];
if (isPresent(delayMatch)) { if (isPresent(delayMatch)) {
var delayVal: number = parseFloat(delayMatch); let delayVal: number = parseFloat(delayMatch);
if (isPresent(delayUnit) && delayUnit == 's') { if (isPresent(delayUnit) && delayUnit == 's') {
delayVal *= _ONE_SECOND; delayVal *= _ONE_SECOND;
} }
delay = Math.floor(delayVal); delay = Math.floor(delayVal);
} }
var easingVal = matches[5]; const easingVal = matches[5];
if (!isBlank(easingVal)) { if (!isBlank(easingVal)) {
easing = easingVal; easing = easingVal;
} }
@ -555,15 +555,15 @@ function _parseTimeExpression(
function _createStartKeyframeFromEndKeyframe( function _createStartKeyframeFromEndKeyframe(
endKeyframe: AnimationKeyframeAst, startTime: number, duration: number, endKeyframe: AnimationKeyframeAst, startTime: number, duration: number,
collectedStyles: StylesCollection, errors: AnimationParseError[]): AnimationKeyframeAst { collectedStyles: StylesCollection, errors: AnimationParseError[]): AnimationKeyframeAst {
var values: Styles = {}; const values: Styles = {};
var endTime = startTime + duration; const endTime = startTime + duration;
endKeyframe.styles.styles.forEach((styleData: Styles) => { endKeyframe.styles.styles.forEach((styleData: Styles) => {
Object.keys(styleData).forEach(prop => { Object.keys(styleData).forEach(prop => {
const val = styleData[prop]; const val = styleData[prop];
if (prop == 'offset') return; if (prop == 'offset') return;
var resultIndex = collectedStyles.indexOfAtOrBeforeTime(prop, startTime); const resultIndex = collectedStyles.indexOfAtOrBeforeTime(prop, startTime);
var resultEntry: any /** TODO #9100 */, nextEntry: any /** TODO #9100 */, let resultEntry: any /** TODO #9100 */, nextEntry: any /** TODO #9100 */,
value: any /** TODO #9100 */; value: any /** TODO #9100 */;
if (isPresent(resultIndex)) { if (isPresent(resultIndex)) {
resultEntry = collectedStyles.getByIndex(prop, resultIndex); resultEntry = collectedStyles.getByIndex(prop, resultIndex);

View File

@ -20,16 +20,16 @@ export class StylesCollection {
styles: {[key: string]: StylesCollectionEntry[]} = {}; styles: {[key: string]: StylesCollectionEntry[]} = {};
insertAtTime(property: string, time: number, value: string|number) { insertAtTime(property: string, time: number, value: string|number) {
var tuple = new StylesCollectionEntry(time, value); const tuple = new StylesCollectionEntry(time, value);
var entries = this.styles[property]; let entries = this.styles[property];
if (!isPresent(entries)) { if (!isPresent(entries)) {
entries = this.styles[property] = []; entries = this.styles[property] = [];
} }
// insert this at the right stop in the array // insert this at the right stop in the array
// this way we can keep it sorted // this way we can keep it sorted
var insertionIndex = 0; let insertionIndex = 0;
for (var i = entries.length - 1; i >= 0; i--) { for (let i = entries.length - 1; i >= 0; i--) {
if (entries[i].time <= time) { if (entries[i].time <= time) {
insertionIndex = i + 1; insertionIndex = i + 1;
break; break;
@ -40,7 +40,7 @@ export class StylesCollection {
} }
getByIndex(property: string, index: number): StylesCollectionEntry { getByIndex(property: string, index: number): StylesCollectionEntry {
var items = this.styles[property]; const items = this.styles[property];
if (isPresent(items)) { if (isPresent(items)) {
return index >= items.length ? null : items[index]; return index >= items.length ? null : items[index];
} }
@ -48,9 +48,9 @@ export class StylesCollection {
} }
indexOfAtOrBeforeTime(property: string, time: number): number { indexOfAtOrBeforeTime(property: string, time: number): number {
var entries = this.styles[property]; const entries = this.styles[property];
if (isPresent(entries)) { if (isPresent(entries)) {
for (var i = entries.length - 1; i >= 0; i--) { for (let i = entries.length - 1; i >= 0; i--) {
if (entries[i].time <= time) return i; if (entries[i].time <= time) return i;
} }
} }

View File

@ -17,7 +17,7 @@ export function assertArrayOfStrings(identifier: string, value: any) {
if (!Array.isArray(value)) { if (!Array.isArray(value)) {
throw new Error(`Expected '${identifier}' to be an array of strings.`); throw new Error(`Expected '${identifier}' to be an array of strings.`);
} }
for (var i = 0; i < value.length; i += 1) { for (let i = 0; i < value.length; i += 1) {
if (typeof value[i] !== 'string') { if (typeof value[i] !== 'string') {
throw new Error(`Expected '${identifier}' to be an array of strings.`); throw new Error(`Expected '${identifier}' to be an array of strings.`);
} }

View File

@ -376,9 +376,9 @@ export class CompileDirectiveMetadata implements CompileMetadataWithIdentifier {
entryComponents?: CompileIdentifierMetadata[], entryComponents?: CompileIdentifierMetadata[],
template?: CompileTemplateMetadata template?: CompileTemplateMetadata
} = {}): CompileDirectiveMetadata { } = {}): CompileDirectiveMetadata {
var hostListeners: {[key: string]: string} = {}; const hostListeners: {[key: string]: string} = {};
var hostProperties: {[key: string]: string} = {}; const hostProperties: {[key: string]: string} = {};
var hostAttributes: {[key: string]: string} = {}; const hostAttributes: {[key: string]: string} = {};
if (isPresent(host)) { if (isPresent(host)) {
Object.keys(host).forEach(key => { Object.keys(host).forEach(key => {
const value = host[key]; const value = host[key];
@ -392,21 +392,21 @@ export class CompileDirectiveMetadata implements CompileMetadataWithIdentifier {
} }
}); });
} }
var inputsMap: {[key: string]: string} = {}; const inputsMap: {[key: string]: string} = {};
if (isPresent(inputs)) { if (isPresent(inputs)) {
inputs.forEach((bindConfig: string) => { inputs.forEach((bindConfig: string) => {
// canonical syntax: `dirProp: elProp` // canonical syntax: `dirProp: elProp`
// if there is no `:`, use dirProp = elProp // if there is no `:`, use dirProp = elProp
var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]); const parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
inputsMap[parts[0]] = parts[1]; inputsMap[parts[0]] = parts[1];
}); });
} }
var outputsMap: {[key: string]: string} = {}; const outputsMap: {[key: string]: string} = {};
if (isPresent(outputs)) { if (isPresent(outputs)) {
outputs.forEach((bindConfig: string) => { outputs.forEach((bindConfig: string) => {
// canonical syntax: `dirProp: elProp` // canonical syntax: `dirProp: elProp`
// if there is no `:`, use dirProp = elProp // if there is no `:`, use dirProp = elProp
var parts = splitAtColon(bindConfig, [bindConfig, bindConfig]); const parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
outputsMap[parts[0]] = parts[1]; outputsMap[parts[0]] = parts[1];
}); });
} }
@ -516,7 +516,7 @@ export class CompileDirectiveMetadata implements CompileMetadataWithIdentifier {
*/ */
export function createHostComponentMeta(compMeta: CompileDirectiveMetadata): export function createHostComponentMeta(compMeta: CompileDirectiveMetadata):
CompileDirectiveMetadata { CompileDirectiveMetadata {
var template = CssSelector.parse(compMeta.selector)[0].getMatchingElementTemplate(); const template = CssSelector.parse(compMeta.selector)[0].getMatchingElementTemplate();
return CompileDirectiveMetadata.create({ return CompileDirectiveMetadata.create({
type: new CompileTypeMetadata({ type: new CompileTypeMetadata({
reference: Object, reference: Object,

View File

@ -142,7 +142,7 @@ function _mergeOptions(optionsArr: CompilerOptions[]): CompilerOptions {
} }
function _lastDefined<T>(args: T[]): T { function _lastDefined<T>(args: T[]): T {
for (var i = args.length - 1; i >= 0; i--) { for (let i = args.length - 1; i >= 0; i--) {
if (args[i] !== undefined) { if (args[i] !== undefined) {
return args[i]; return args[i];
} }
@ -151,7 +151,7 @@ function _lastDefined<T>(args: T[]): T {
} }
function _mergeArrays(parts: any[][]): any[] { function _mergeArrays(parts: any[][]): any[] {
let result: any[] = []; const result: any[] = [];
parts.forEach((part) => part && result.push(...part)); parts.forEach((part) => part && result.push(...part));
return result; return result;
} }

View File

@ -30,7 +30,7 @@ export function createCheckBindingField(builder: ClassBuilder): CheckBindingFiel
export function createCheckBindingStmt( export function createCheckBindingStmt(
evalResult: ConvertPropertyBindingResult, fieldExpr: o.ReadPropExpr, evalResult: ConvertPropertyBindingResult, fieldExpr: o.ReadPropExpr,
throwOnChangeVar: o.Expression, actions: o.Statement[]): o.Statement[] { throwOnChangeVar: o.Expression, actions: o.Statement[]): o.Statement[] {
var condition: o.Expression = o.importExpr(resolveIdentifier(Identifiers.checkBinding)).callFn([ let condition: o.Expression = o.importExpr(resolveIdentifier(Identifiers.checkBinding)).callFn([
throwOnChangeVar, fieldExpr, evalResult.currValExpr throwOnChangeVar, fieldExpr, evalResult.currValExpr
]); ]);
if (evalResult.forceUpdate) { if (evalResult.forceUpdate) {

View File

@ -58,7 +58,7 @@ export function convertPropertyBinding(
} }
if (visitor.needsValueUnwrapper) { if (visitor.needsValueUnwrapper) {
var initValueUnwrapperStmt = VAL_UNWRAPPER_VAR.callMethod('reset', []).toStmt(); const initValueUnwrapperStmt = VAL_UNWRAPPER_VAR.callMethod('reset', []).toStmt();
stmts.push(initValueUnwrapperStmt); stmts.push(initValueUnwrapperStmt);
} }
stmts.push(currValExpr.set(outputExpr).toDeclStmt(null, [o.StmtModifier.Final])); stmts.push(currValExpr.set(outputExpr).toDeclStmt(null, [o.StmtModifier.Final]));
@ -86,14 +86,14 @@ export function convertActionBinding(
} }
const visitor = const visitor =
new _AstToIrVisitor(builder, nameResolver, implicitReceiver, null, bindingId, true); new _AstToIrVisitor(builder, nameResolver, implicitReceiver, null, bindingId, true);
let actionStmts: o.Statement[] = []; const actionStmts: o.Statement[] = [];
flattenStatements(action.visit(visitor, _Mode.Statement), actionStmts); flattenStatements(action.visit(visitor, _Mode.Statement), actionStmts);
prependTemporaryDecls(visitor.temporaryCount, bindingId, actionStmts); prependTemporaryDecls(visitor.temporaryCount, bindingId, actionStmts);
var lastIndex = actionStmts.length - 1; const lastIndex = actionStmts.length - 1;
var preventDefaultVar: o.ReadVarExpr = null; let preventDefaultVar: o.ReadVarExpr = null;
if (lastIndex >= 0) { if (lastIndex >= 0) {
var lastStatement = actionStmts[lastIndex]; const lastStatement = actionStmts[lastIndex];
var returnExpr = convertStmtIntoExpression(lastStatement); const returnExpr = convertStmtIntoExpression(lastStatement);
if (returnExpr) { if (returnExpr) {
// Note: We need to cast the result of the method call to dynamic, // Note: We need to cast the result of the method call to dynamic,
// as it might be a void method! // as it might be a void method!
@ -112,7 +112,7 @@ export function convertActionBinding(
*/ */
export function createSharedBindingVariablesIfNeeded(stmts: o.Statement[]): o.Statement[] { export function createSharedBindingVariablesIfNeeded(stmts: o.Statement[]): o.Statement[] {
const unwrapperStmts: o.Statement[] = []; const unwrapperStmts: o.Statement[] = [];
var readVars = o.findReadVarNames(stmts); const readVars = o.findReadVarNames(stmts);
if (readVars.has(VAL_UNWRAPPER_VAR.name)) { if (readVars.has(VAL_UNWRAPPER_VAR.name)) {
unwrapperStmts.push( unwrapperStmts.push(
VAL_UNWRAPPER_VAR VAL_UNWRAPPER_VAR
@ -175,7 +175,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
private bindingId: string, private isAction: boolean) {} private bindingId: string, private isAction: boolean) {}
visitBinary(ast: cdAst.Binary, mode: _Mode): any { visitBinary(ast: cdAst.Binary, mode: _Mode): any {
var op: o.BinaryOperator; let op: o.BinaryOperator;
switch (ast.operation) { switch (ast.operation) {
case '+': case '+':
op = o.BinaryOperator.Plus; op = o.BinaryOperator.Plus;
@ -303,7 +303,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
} }
visitLiteralMap(ast: cdAst.LiteralMap, mode: _Mode): any { visitLiteralMap(ast: cdAst.LiteralMap, mode: _Mode): any {
let parts: any[] = []; const parts: any[] = [];
for (let i = 0; i < ast.keys.length; i++) { for (let i = 0; i < ast.keys.length; i++) {
parts.push([ast.keys[i], this.visit(ast.values[i], _Mode.Expression)]); parts.push([ast.keys[i], this.visit(ast.values[i], _Mode.Expression)]);
} }
@ -330,9 +330,9 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
} else { } else {
const args = this.visitAll(ast.args, _Mode.Expression); const args = this.visitAll(ast.args, _Mode.Expression);
let result: any = null; let result: any = null;
let receiver = this.visit(ast.receiver, _Mode.Expression); const receiver = this.visit(ast.receiver, _Mode.Expression);
if (receiver === this._implicitReceiver) { if (receiver === this._implicitReceiver) {
var varExpr = this._getLocal(ast.name); const varExpr = this._getLocal(ast.name);
if (isPresent(varExpr)) { if (isPresent(varExpr)) {
result = varExpr.callFn(args); result = varExpr.callFn(args);
} }
@ -354,7 +354,7 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
return this.convertSafeAccess(ast, leftMostSafe, mode); return this.convertSafeAccess(ast, leftMostSafe, mode);
} else { } else {
let result: any = null; let result: any = null;
var receiver = this.visit(ast.receiver, _Mode.Expression); const receiver = this.visit(ast.receiver, _Mode.Expression);
if (receiver === this._implicitReceiver) { if (receiver === this._implicitReceiver) {
result = this._getLocal(ast.name); result = this._getLocal(ast.name);
} }
@ -366,9 +366,9 @@ class _AstToIrVisitor implements cdAst.AstVisitor {
} }
visitPropertyWrite(ast: cdAst.PropertyWrite, mode: _Mode): any { visitPropertyWrite(ast: cdAst.PropertyWrite, mode: _Mode): any {
let receiver: o.Expression = this.visit(ast.receiver, _Mode.Expression); const receiver: o.Expression = this.visit(ast.receiver, _Mode.Expression);
if (receiver === this._implicitReceiver) { if (receiver === this._implicitReceiver) {
var varExpr = this._getLocal(ast.name); const varExpr = this._getLocal(ast.name);
if (isPresent(varExpr)) { if (isPresent(varExpr)) {
throw new Error('Cannot assign to a reference or variable!'); throw new Error('Cannot assign to a reference or variable!');
} }
@ -580,11 +580,11 @@ function createCachedLiteralArray(builder: ClassBuilder, values: o.Expression[])
if (values.length === 0) { if (values.length === 0) {
return o.importExpr(resolveIdentifier(Identifiers.EMPTY_ARRAY)); return o.importExpr(resolveIdentifier(Identifiers.EMPTY_ARRAY));
} }
var proxyExpr = o.THIS_EXPR.prop(`_arr_${builder.fields.length}`); const proxyExpr = o.THIS_EXPR.prop(`_arr_${builder.fields.length}`);
var proxyParams: o.FnParam[] = []; const proxyParams: o.FnParam[] = [];
var proxyReturnEntries: o.Expression[] = []; const proxyReturnEntries: o.Expression[] = [];
for (var i = 0; i < values.length; i++) { for (let i = 0; i < values.length; i++) {
var paramName = `p${i}`; const paramName = `p${i}`;
proxyParams.push(new o.FnParam(paramName)); proxyParams.push(new o.FnParam(paramName));
proxyReturnEntries.push(o.variable(paramName)); proxyReturnEntries.push(o.variable(paramName));
} }
@ -605,7 +605,7 @@ function createCachedLiteralMap(
const proxyParams: o.FnParam[] = []; const proxyParams: o.FnParam[] = [];
const proxyReturnEntries: [string, o.Expression][] = []; const proxyReturnEntries: [string, o.Expression][] = [];
const values: o.Expression[] = []; const values: o.Expression[] = [];
for (var i = 0; i < entries.length; i++) { for (let i = 0; i < entries.length; i++) {
const paramName = `p${i}`; const paramName = `p${i}`;
proxyParams.push(new o.FnParam(paramName)); proxyParams.push(new o.FnParam(paramName));
proxyReturnEntries.push([entries[i][0], o.variable(paramName)]); proxyReturnEntries.push([entries[i][0], o.variable(paramName)]);

View File

@ -40,7 +40,7 @@ export function createPureProxy(
fn: o.Expression, argCount: number, pureProxyProp: o.ReadPropExpr, fn: o.Expression, argCount: number, pureProxyProp: o.ReadPropExpr,
builder: {fields: o.ClassField[], ctorStmts: {push: (stmt: o.Statement) => void}}) { builder: {fields: o.ClassField[], ctorStmts: {push: (stmt: o.Statement) => void}}) {
builder.fields.push(new o.ClassField(pureProxyProp.name, null)); builder.fields.push(new o.ClassField(pureProxyProp.name, null));
var pureProxyId = const pureProxyId =
argCount < Identifiers.pureProxies.length ? Identifiers.pureProxies[argCount] : null; argCount < Identifiers.pureProxies.length ? Identifiers.pureProxies[argCount] : null;
if (!pureProxyId) { if (!pureProxyId) {
throw new Error(`Unsupported number of argument for pure functions: ${argCount}`); throw new Error(`Unsupported number of argument for pure functions: ${argCount}`);

View File

@ -53,7 +53,7 @@ export function writeToRenderer(
.toStmt()); .toStmt());
break; break;
case PropertyBindingType.Style: case PropertyBindingType.Style:
var strValue: o.Expression = renderValue.callMethod('toString', []); let strValue: o.Expression = renderValue.callMethod('toString', []);
if (isPresent(boundProp.unit)) { if (isPresent(boundProp.unit)) {
strValue = strValue.plus(o.literal(boundProp.unit)); strValue = strValue.plus(o.literal(boundProp.unit));
} }
@ -84,8 +84,8 @@ function sanitizedValue(
if (!securityContextExpression) { if (!securityContextExpression) {
throw new Error(`internal error, no SecurityContext given ${boundProp.name}`); throw new Error(`internal error, no SecurityContext given ${boundProp.name}`);
} }
let ctx = view.prop('viewUtils').prop('sanitizer'); const ctx = view.prop('viewUtils').prop('sanitizer');
let args = [securityContextExpression, renderValue]; const args = [securityContextExpression, renderValue];
return ctx.callMethod('sanitize', args); return ctx.callMethod('sanitize', args);
} }

View File

@ -96,7 +96,7 @@ export class CssBlockDefinitionRuleAst extends CssBlockRuleAst {
location: ParseSourceSpan, public strValue: string, type: BlockType, location: ParseSourceSpan, public strValue: string, type: BlockType,
public query: CssAtRulePredicateAst, block: CssBlockAst) { public query: CssAtRulePredicateAst, block: CssBlockAst) {
super(location, type, block); super(location, type, block);
var firstCssToken: CssToken = query.tokens[0]; const firstCssToken: CssToken = query.tokens[0];
this.name = new CssToken( this.name = new CssToken(
firstCssToken.index, firstCssToken.column, firstCssToken.line, CssTokenType.Identifier, firstCssToken.index, firstCssToken.column, firstCssToken.line, CssTokenType.Identifier,
this.strValue); this.strValue);
@ -238,9 +238,9 @@ export class CssUnknownTokenListAst extends CssRuleAst {
} }
export function mergeTokens(tokens: CssToken[], separator: string = ''): CssToken { export function mergeTokens(tokens: CssToken[], separator: string = ''): CssToken {
var mainToken = tokens[0]; const mainToken = tokens[0];
var str = mainToken.strValue; let str = mainToken.strValue;
for (var i = 1; i < tokens.length; i++) { for (let i = 1; i < tokens.length; i++) {
str += separator + tokens[i].strValue; str += separator + tokens[i].strValue;
} }

View File

@ -54,18 +54,18 @@ export function generateErrorMessage(
export function findProblemCode( export function findProblemCode(
input: string, errorValue: string, index: number, column: number): string { input: string, errorValue: string, index: number, column: number): string {
var endOfProblemLine = index; let endOfProblemLine = index;
var current = charCode(input, index); let current = charCode(input, index);
while (current > 0 && !isNewline(current)) { while (current > 0 && !isNewline(current)) {
current = charCode(input, ++endOfProblemLine); current = charCode(input, ++endOfProblemLine);
} }
var choppedString = input.substring(0, endOfProblemLine); const choppedString = input.substring(0, endOfProblemLine);
var pointerPadding = ''; let pointerPadding = '';
for (var i = 0; i < column; i++) { for (let i = 0; i < column; i++) {
pointerPadding += ' '; pointerPadding += ' ';
} }
var pointerString = ''; let pointerString = '';
for (var i = 0; i < errorValue.length; i++) { for (let i = 0; i < errorValue.length; i++) {
pointerString += '^'; pointerString += '^';
} }
return choppedString + '\n' + pointerPadding + pointerString + '\n'; return choppedString + '\n' + pointerPadding + pointerString + '\n';
@ -185,16 +185,16 @@ export class CssScanner {
} }
consume(type: CssTokenType, value: string = null): LexedCssResult { consume(type: CssTokenType, value: string = null): LexedCssResult {
var mode = this._currentMode; const mode = this._currentMode;
this.setMode(_trackWhitespace(mode) ? CssLexerMode.ALL_TRACK_WS : CssLexerMode.ALL); this.setMode(_trackWhitespace(mode) ? CssLexerMode.ALL_TRACK_WS : CssLexerMode.ALL);
var previousIndex = this.index; const previousIndex = this.index;
var previousLine = this.line; const previousLine = this.line;
var previousColumn = this.column; const previousColumn = this.column;
var next: CssToken; let next: CssToken;
var output = this.scan(); const output = this.scan();
if (isPresent(output)) { if (isPresent(output)) {
// just incase the inner scan method returned an error // just incase the inner scan method returned an error
if (isPresent(output.error)) { if (isPresent(output.error)) {
@ -209,7 +209,7 @@ export class CssScanner {
next = new CssToken(this.index, this.column, this.line, CssTokenType.EOF, 'end of file'); next = new CssToken(this.index, this.column, this.line, CssTokenType.EOF, 'end of file');
} }
var isMatchingType: boolean = false; let isMatchingType: boolean = false;
if (type == CssTokenType.IdentifierOrNumber) { if (type == CssTokenType.IdentifierOrNumber) {
// TODO (matsko): implement array traversal for lookup here // TODO (matsko): implement array traversal for lookup here
isMatchingType = next.type == CssTokenType.Number || next.type == CssTokenType.Identifier; isMatchingType = next.type == CssTokenType.Number || next.type == CssTokenType.Identifier;
@ -221,9 +221,9 @@ export class CssScanner {
// mode so that the parser can recover... // mode so that the parser can recover...
this.setMode(mode); this.setMode(mode);
var error: CssScannerError = null; let error: CssScannerError = null;
if (!isMatchingType || (isPresent(value) && value != next.strValue)) { if (!isMatchingType || (isPresent(value) && value != next.strValue)) {
var errorMessage = let errorMessage =
CssTokenType[next.type] + ' does not match expected ' + CssTokenType[type] + ' value'; CssTokenType[next.type] + ' does not match expected ' + CssTokenType[type] + ' value';
if (isPresent(value)) { if (isPresent(value)) {
@ -241,15 +241,15 @@ export class CssScanner {
scan(): LexedCssResult { scan(): LexedCssResult {
var trackWS = _trackWhitespace(this._currentMode); const trackWS = _trackWhitespace(this._currentMode);
if (this.index == 0 && !trackWS) { // first scan if (this.index == 0 && !trackWS) { // first scan
this.consumeWhitespace(); this.consumeWhitespace();
} }
var token = this._scan(); const token = this._scan();
if (token == null) return null; if (token == null) return null;
var error = this._currentError; const error = this._currentError;
this._currentError = null; this._currentError = null;
if (!trackWS) { if (!trackWS) {
@ -260,14 +260,14 @@ export class CssScanner {
/** @internal */ /** @internal */
_scan(): CssToken { _scan(): CssToken {
var peek = this.peek; let peek = this.peek;
var peekPeek = this.peekPeek; let peekPeek = this.peekPeek;
if (peek == chars.$EOF) return null; if (peek == chars.$EOF) return null;
if (isCommentStart(peek, peekPeek)) { if (isCommentStart(peek, peekPeek)) {
// even if comments are not tracked we still lex the // even if comments are not tracked we still lex the
// comment so we can move the pointer forward // comment so we can move the pointer forward
var commentToken = this.scanComment(); const commentToken = this.scanComment();
if (this._trackComments) { if (this._trackComments) {
return commentToken; return commentToken;
} }
@ -290,9 +290,9 @@ export class CssScanner {
return this.scanCssValueFunction(); return this.scanCssValueFunction();
} }
var isModifier = peek == chars.$PLUS || peek == chars.$MINUS; const isModifier = peek == chars.$PLUS || peek == chars.$MINUS;
var digitA = isModifier ? false : chars.isDigit(peek); const digitA = isModifier ? false : chars.isDigit(peek);
var digitB = chars.isDigit(peekPeek); const digitB = chars.isDigit(peekPeek);
if (digitA || (isModifier && (peekPeek == chars.$PERIOD || digitB)) || if (digitA || (isModifier && (peekPeek == chars.$PERIOD || digitB)) ||
(peek == chars.$PERIOD && digitB)) { (peek == chars.$PERIOD && digitB)) {
return this.scanNumber(); return this.scanNumber();
@ -319,9 +319,9 @@ export class CssScanner {
return null; return null;
} }
var start = this.index; const start = this.index;
var startingColumn = this.column; const startingColumn = this.column;
var startingLine = this.line; const startingLine = this.line;
this.advance(); // / this.advance(); // /
this.advance(); // * this.advance(); // *
@ -336,18 +336,18 @@ export class CssScanner {
this.advance(); // * this.advance(); // *
this.advance(); // / this.advance(); // /
var str = this.input.substring(start, this.index); const str = this.input.substring(start, this.index);
return new CssToken(start, startingColumn, startingLine, CssTokenType.Comment, str); return new CssToken(start, startingColumn, startingLine, CssTokenType.Comment, str);
} }
scanWhitespace(): CssToken { scanWhitespace(): CssToken {
var start = this.index; const start = this.index;
var startingColumn = this.column; const startingColumn = this.column;
var startingLine = this.line; const startingLine = this.line;
while (chars.isWhitespace(this.peek) && this.peek != chars.$EOF) { while (chars.isWhitespace(this.peek) && this.peek != chars.$EOF) {
this.advance(); this.advance();
} }
var str = this.input.substring(start, this.index); const str = this.input.substring(start, this.index);
return new CssToken(start, startingColumn, startingLine, CssTokenType.Whitespace, str); return new CssToken(start, startingColumn, startingLine, CssTokenType.Whitespace, str);
} }
@ -357,11 +357,11 @@ export class CssScanner {
return null; return null;
} }
var target = this.peek; const target = this.peek;
var start = this.index; const start = this.index;
var startingColumn = this.column; const startingColumn = this.column;
var startingLine = this.line; const startingLine = this.line;
var previous = target; let previous = target;
this.advance(); this.advance();
while (!isCharMatch(target, previous, this.peek)) { while (!isCharMatch(target, previous, this.peek)) {
@ -377,17 +377,17 @@ export class CssScanner {
} }
this.advance(); this.advance();
var str = this.input.substring(start, this.index); const str = this.input.substring(start, this.index);
return new CssToken(start, startingColumn, startingLine, CssTokenType.String, str); return new CssToken(start, startingColumn, startingLine, CssTokenType.String, str);
} }
scanNumber(): CssToken { scanNumber(): CssToken {
var start = this.index; const start = this.index;
var startingColumn = this.column; const startingColumn = this.column;
if (this.peek == chars.$PLUS || this.peek == chars.$MINUS) { if (this.peek == chars.$PLUS || this.peek == chars.$MINUS) {
this.advance(); this.advance();
} }
var periodUsed = false; let periodUsed = false;
while (chars.isDigit(this.peek) || this.peek == chars.$PERIOD) { while (chars.isDigit(this.peek) || this.peek == chars.$PERIOD) {
if (this.peek == chars.$PERIOD) { if (this.peek == chars.$PERIOD) {
if (periodUsed) { if (periodUsed) {
@ -397,7 +397,7 @@ export class CssScanner {
} }
this.advance(); this.advance();
} }
var strValue = this.input.substring(start, this.index); const strValue = this.input.substring(start, this.index);
return new CssToken(start, startingColumn, this.line, CssTokenType.Number, strValue); return new CssToken(start, startingColumn, this.line, CssTokenType.Number, strValue);
} }
@ -407,19 +407,19 @@ export class CssScanner {
return null; return null;
} }
var start = this.index; const start = this.index;
var startingColumn = this.column; const startingColumn = this.column;
while (isIdentifierPart(this.peek)) { while (isIdentifierPart(this.peek)) {
this.advance(); this.advance();
} }
var strValue = this.input.substring(start, this.index); const strValue = this.input.substring(start, this.index);
return new CssToken(start, startingColumn, this.line, CssTokenType.Identifier, strValue); return new CssToken(start, startingColumn, this.line, CssTokenType.Identifier, strValue);
} }
scanCssValueFunction(): CssToken { scanCssValueFunction(): CssToken {
var start = this.index; const start = this.index;
var startingColumn = this.column; const startingColumn = this.column;
var parenBalance = 1; let parenBalance = 1;
while (this.peek != chars.$EOF && parenBalance > 0) { while (this.peek != chars.$EOF && parenBalance > 0) {
this.advance(); this.advance();
if (this.peek == chars.$LPAREN) { if (this.peek == chars.$LPAREN) {
@ -428,20 +428,20 @@ export class CssScanner {
parenBalance--; parenBalance--;
} }
} }
var strValue = this.input.substring(start, this.index); const strValue = this.input.substring(start, this.index);
return new CssToken(start, startingColumn, this.line, CssTokenType.Identifier, strValue); return new CssToken(start, startingColumn, this.line, CssTokenType.Identifier, strValue);
} }
scanCharacter(): CssToken { scanCharacter(): CssToken {
var start = this.index; const start = this.index;
var startingColumn = this.column; const startingColumn = this.column;
if (this.assertCondition( if (this.assertCondition(
isValidCssCharacter(this.peek, this._currentMode), isValidCssCharacter(this.peek, this._currentMode),
charStr(this.peek) + ' is not a valid CSS character')) { charStr(this.peek) + ' is not a valid CSS character')) {
return null; return null;
} }
var c = this.input.substring(start, start + 1); const c = this.input.substring(start, start + 1);
this.advance(); this.advance();
return new CssToken(start, startingColumn, this.line, CssTokenType.Character, c); return new CssToken(start, startingColumn, this.line, CssTokenType.Character, c);
@ -452,12 +452,12 @@ export class CssScanner {
return null; return null;
} }
var start = this.index; const start = this.index;
var startingColumn = this.column; const startingColumn = this.column;
this.advance(); this.advance();
if (isIdentifierStart(this.peek, this.peekPeek)) { if (isIdentifierStart(this.peek, this.peekPeek)) {
var ident = this.scanIdentifier(); const ident = this.scanIdentifier();
var strValue = '@' + ident.strValue; const strValue = '@' + ident.strValue;
return new CssToken(start, startingColumn, this.line, CssTokenType.AtKeyword, strValue); return new CssToken(start, startingColumn, this.line, CssTokenType.AtKeyword, strValue);
} else { } else {
return this.scanCharacter(); return this.scanCharacter();
@ -473,12 +473,12 @@ export class CssScanner {
} }
error(message: string, errorTokenValue: string = null, doNotAdvance: boolean = false): CssToken { error(message: string, errorTokenValue: string = null, doNotAdvance: boolean = false): CssToken {
var index: number = this.index; const index: number = this.index;
var column: number = this.column; const column: number = this.column;
var line: number = this.line; const line: number = this.line;
errorTokenValue = errorTokenValue || String.fromCharCode(this.peek); errorTokenValue = errorTokenValue || String.fromCharCode(this.peek);
var invalidToken = new CssToken(index, column, line, CssTokenType.Invalid, errorTokenValue); const invalidToken = new CssToken(index, column, line, CssTokenType.Invalid, errorTokenValue);
var errorMessage = const errorMessage =
generateErrorMessage(this.input, message, errorTokenValue, index, line, column); generateErrorMessage(this.input, message, errorTokenValue, index, line, column);
if (!doNotAdvance) { if (!doNotAdvance) {
this.advance(); this.advance();
@ -501,7 +501,7 @@ function isCommentEnd(code: number, next: number): boolean {
} }
function isStringStart(code: number, next: number): boolean { function isStringStart(code: number, next: number): boolean {
var target = code; let target = code;
if (target == chars.$BACKSLASH) { if (target == chars.$BACKSLASH) {
target = next; target = next;
} }
@ -509,7 +509,7 @@ function isStringStart(code: number, next: number): boolean {
} }
function isIdentifierStart(code: number, next: number): boolean { function isIdentifierStart(code: number, next: number): boolean {
var target = code; let target = code;
if (target == chars.$MINUS) { if (target == chars.$MINUS) {
target = next; target = next;
} }

View File

@ -93,16 +93,16 @@ export class CssParser {
* @param url the name of the CSS file containing the CSS source code * @param url the name of the CSS file containing the CSS source code
*/ */
parse(css: string, url: string): ParsedCssResult { parse(css: string, url: string): ParsedCssResult {
var lexer = new CssLexer(); const lexer = new CssLexer();
this._file = new ParseSourceFile(css, url); this._file = new ParseSourceFile(css, url);
this._scanner = lexer.scan(css, false); this._scanner = lexer.scan(css, false);
var ast = this._parseStyleSheet(EOF_DELIM_FLAG); const ast = this._parseStyleSheet(EOF_DELIM_FLAG);
var errors = this._errors; const errors = this._errors;
this._errors = []; this._errors = [];
var result = new ParsedCssResult(errors, ast); const result = new ParsedCssResult(errors, ast);
this._file = null; this._file = null;
this._scanner = null; this._scanner = null;
return result; return result;
@ -110,15 +110,15 @@ export class CssParser {
/** @internal */ /** @internal */
_parseStyleSheet(delimiters: number): CssStyleSheetAst { _parseStyleSheet(delimiters: number): CssStyleSheetAst {
var results: CssRuleAst[] = []; const results: CssRuleAst[] = [];
this._scanner.consumeEmptyStatements(); this._scanner.consumeEmptyStatements();
while (this._scanner.peek != chars.$EOF) { while (this._scanner.peek != chars.$EOF) {
this._scanner.setMode(CssLexerMode.BLOCK); this._scanner.setMode(CssLexerMode.BLOCK);
results.push(this._parseRule(delimiters)); results.push(this._parseRule(delimiters));
} }
var span: ParseSourceSpan = null; let span: ParseSourceSpan = null;
if (results.length > 0) { if (results.length > 0) {
var firstRule = results[0]; const firstRule = results[0];
// we collect the last token like so incase there was an // we collect the last token like so incase there was an
// EOF token that was emitted sometime during the lexing // EOF token that was emitted sometime during the lexing
span = this._generateSourceSpan(firstRule, this._lastToken); span = this._generateSourceSpan(firstRule, this._lastToken);
@ -136,11 +136,11 @@ export class CssParser {
/** @internal */ /** @internal */
_generateSourceSpan(start: CssToken|CssAst, end: CssToken|CssAst = null): ParseSourceSpan { _generateSourceSpan(start: CssToken|CssAst, end: CssToken|CssAst = null): ParseSourceSpan {
var startLoc: ParseLocation; let startLoc: ParseLocation;
if (start instanceof CssAst) { if (start instanceof CssAst) {
startLoc = start.location.start; startLoc = start.location.start;
} else { } else {
var token = start; let token = start;
if (!isPresent(token)) { if (!isPresent(token)) {
// the data here is invalid, however, if and when this does // the data here is invalid, however, if and when this does
// occur, any other errors associated with this will be collected // occur, any other errors associated with this will be collected
@ -153,9 +153,9 @@ export class CssParser {
end = this._lastToken; end = this._lastToken;
} }
var endLine: number; let endLine: number;
var endColumn: number; let endColumn: number;
var endIndex: number; let endIndex: number;
if (end instanceof CssAst) { if (end instanceof CssAst) {
endLine = end.location.end.line; endLine = end.location.end.line;
endColumn = end.location.end.col; endColumn = end.location.end.col;
@ -166,7 +166,7 @@ export class CssParser {
endIndex = end.index; endIndex = end.index;
} }
var endLoc = new ParseLocation(this._file, endIndex, endLine, endColumn); const endLoc = new ParseLocation(this._file, endIndex, endLine, endColumn);
return new ParseSourceSpan(startLoc, endLoc); return new ParseSourceSpan(startLoc, endLoc);
} }
@ -224,21 +224,21 @@ export class CssParser {
const start = this._getScannerIndex(); const start = this._getScannerIndex();
this._scanner.setMode(CssLexerMode.BLOCK); this._scanner.setMode(CssLexerMode.BLOCK);
var token = this._scan(); const token = this._scan();
var startToken = token; const startToken = token;
this._assertCondition( this._assertCondition(
token.type == CssTokenType.AtKeyword, token.type == CssTokenType.AtKeyword,
`The CSS Rule ${token.strValue} is not a valid [@] rule.`, token); `The CSS Rule ${token.strValue} is not a valid [@] rule.`, token);
var block: CssBlockAst; let block: CssBlockAst;
var type = this._resolveBlockType(token); const type = this._resolveBlockType(token);
var span: ParseSourceSpan; let span: ParseSourceSpan;
var tokens: CssToken[]; let tokens: CssToken[];
var endToken: CssToken; let endToken: CssToken;
var end: number; let end: number;
var strValue: string; let strValue: string;
var query: CssAtRulePredicateAst; let query: CssAtRulePredicateAst;
switch (type) { switch (type) {
case BlockType.Charset: case BlockType.Charset:
case BlockType.Namespace: case BlockType.Namespace:
@ -324,23 +324,23 @@ export class CssParser {
/** @internal */ /** @internal */
_parseSelectorRule(delimiters: number): CssRuleAst { _parseSelectorRule(delimiters: number): CssRuleAst {
const start = this._getScannerIndex(); const start = this._getScannerIndex();
var selectors = this._parseSelectors(delimiters); const selectors = this._parseSelectors(delimiters);
var block = this._parseStyleBlock(delimiters); const block = this._parseStyleBlock(delimiters);
var ruleAst: CssRuleAst; let ruleAst: CssRuleAst;
var span: ParseSourceSpan; let span: ParseSourceSpan;
var startSelector = selectors[0]; const startSelector = selectors[0];
if (isPresent(block)) { if (isPresent(block)) {
span = this._generateSourceSpan(startSelector, block); span = this._generateSourceSpan(startSelector, block);
ruleAst = new CssSelectorRuleAst(span, selectors, block); ruleAst = new CssSelectorRuleAst(span, selectors, block);
} else { } else {
var name = this._extractSourceContent(start, this._getScannerIndex() - 1); const name = this._extractSourceContent(start, this._getScannerIndex() - 1);
var innerTokens: CssToken[] = []; const innerTokens: CssToken[] = [];
selectors.forEach((selector: CssSelectorAst) => { selectors.forEach((selector: CssSelectorAst) => {
selector.selectorParts.forEach((part: CssSimpleSelectorAst) => { selector.selectorParts.forEach((part: CssSimpleSelectorAst) => {
part.tokens.forEach((token: CssToken) => { innerTokens.push(token); }); part.tokens.forEach((token: CssToken) => { innerTokens.push(token); });
}); });
}); });
var endToken = innerTokens[innerTokens.length - 1]; const endToken = innerTokens[innerTokens.length - 1];
span = this._generateSourceSpan(startSelector, endToken); span = this._generateSourceSpan(startSelector, endToken);
ruleAst = new CssUnknownTokenListAst(span, name, innerTokens); ruleAst = new CssUnknownTokenListAst(span, name, innerTokens);
} }
@ -353,8 +353,8 @@ export class CssParser {
_parseSelectors(delimiters: number): CssSelectorAst[] { _parseSelectors(delimiters: number): CssSelectorAst[] {
delimiters |= LBRACE_DELIM_FLAG | SEMICOLON_DELIM_FLAG; delimiters |= LBRACE_DELIM_FLAG | SEMICOLON_DELIM_FLAG;
var selectors: CssSelectorAst[] = []; const selectors: CssSelectorAst[] = [];
var isParsingSelectors = true; let isParsingSelectors = true;
while (isParsingSelectors) { while (isParsingSelectors) {
selectors.push(this._parseSelector(delimiters)); selectors.push(this._parseSelector(delimiters));
@ -374,9 +374,9 @@ export class CssParser {
/** @internal */ /** @internal */
_scan(): CssToken { _scan(): CssToken {
var output = this._scanner.scan(); const output = this._scanner.scan();
var token = output.token; const token = output.token;
var error = output.error; const error = output.error;
if (isPresent(error)) { if (isPresent(error)) {
this._error(error.rawMessage, token); this._error(error.rawMessage, token);
} }
@ -389,9 +389,9 @@ export class CssParser {
/** @internal */ /** @internal */
_consume(type: CssTokenType, value: string = null): CssToken { _consume(type: CssTokenType, value: string = null): CssToken {
var output = this._scanner.consume(type, value); const output = this._scanner.consume(type, value);
var token = output.token; const token = output.token;
var error = output.error; const error = output.error;
if (isPresent(error)) { if (isPresent(error)) {
this._error(error.rawMessage, token); this._error(error.rawMessage, token);
} }
@ -404,23 +404,23 @@ export class CssParser {
delimiters |= RBRACE_DELIM_FLAG; delimiters |= RBRACE_DELIM_FLAG;
this._scanner.setMode(CssLexerMode.KEYFRAME_BLOCK); this._scanner.setMode(CssLexerMode.KEYFRAME_BLOCK);
var startToken = this._consume(CssTokenType.Character, '{'); const startToken = this._consume(CssTokenType.Character, '{');
var definitions: CssKeyframeDefinitionAst[] = []; const definitions: CssKeyframeDefinitionAst[] = [];
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) { while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
definitions.push(this._parseKeyframeDefinition(delimiters)); definitions.push(this._parseKeyframeDefinition(delimiters));
} }
var endToken = this._consume(CssTokenType.Character, '}'); const endToken = this._consume(CssTokenType.Character, '}');
var span = this._generateSourceSpan(startToken, endToken); const span = this._generateSourceSpan(startToken, endToken);
return new CssBlockAst(span, definitions); return new CssBlockAst(span, definitions);
} }
/** @internal */ /** @internal */
_parseKeyframeDefinition(delimiters: number): CssKeyframeDefinitionAst { _parseKeyframeDefinition(delimiters: number): CssKeyframeDefinitionAst {
const start = this._getScannerIndex(); const start = this._getScannerIndex();
var stepTokens: CssToken[] = []; const stepTokens: CssToken[] = [];
delimiters |= LBRACE_DELIM_FLAG; delimiters |= LBRACE_DELIM_FLAG;
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) { while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
stepTokens.push(this._parseKeyframeLabel(delimiters | COMMA_DELIM_FLAG)); stepTokens.push(this._parseKeyframeLabel(delimiters | COMMA_DELIM_FLAG));
@ -428,9 +428,9 @@ export class CssParser {
this._consume(CssTokenType.Character, ','); this._consume(CssTokenType.Character, ',');
} }
} }
var stylesBlock = this._parseStyleBlock(delimiters | RBRACE_DELIM_FLAG); const stylesBlock = this._parseStyleBlock(delimiters | RBRACE_DELIM_FLAG);
var span = this._generateSourceSpan(stepTokens[0], stylesBlock); const span = this._generateSourceSpan(stepTokens[0], stylesBlock);
var ast = new CssKeyframeDefinitionAst(span, stepTokens, stylesBlock); const ast = new CssKeyframeDefinitionAst(span, stepTokens, stylesBlock);
this._scanner.setMode(CssLexerMode.BLOCK); this._scanner.setMode(CssLexerMode.BLOCK);
return ast; return ast;
@ -449,34 +449,34 @@ export class CssParser {
delimiters &= ~COMMA_DELIM_FLAG; delimiters &= ~COMMA_DELIM_FLAG;
// we keep the original value since we may use it to recurse when :not, :host are used // we keep the original value since we may use it to recurse when :not, :host are used
var startingDelims = delimiters; const startingDelims = delimiters;
var startToken = this._consume(CssTokenType.Character, ':'); const startToken = this._consume(CssTokenType.Character, ':');
var tokens = [startToken]; const tokens = [startToken];
if (this._scanner.peek == chars.$COLON) { // ::something if (this._scanner.peek == chars.$COLON) { // ::something
tokens.push(this._consume(CssTokenType.Character, ':')); tokens.push(this._consume(CssTokenType.Character, ':'));
} }
var innerSelectors: CssSelectorAst[] = []; const innerSelectors: CssSelectorAst[] = [];
this._scanner.setMode(CssLexerMode.PSEUDO_SELECTOR); this._scanner.setMode(CssLexerMode.PSEUDO_SELECTOR);
// host, host-context, lang, not, nth-child are all identifiers // host, host-context, lang, not, nth-child are all identifiers
var pseudoSelectorToken = this._consume(CssTokenType.Identifier); const pseudoSelectorToken = this._consume(CssTokenType.Identifier);
var pseudoSelectorName = pseudoSelectorToken.strValue; const pseudoSelectorName = pseudoSelectorToken.strValue;
tokens.push(pseudoSelectorToken); tokens.push(pseudoSelectorToken);
// host(), lang(), nth-child(), etc... // host(), lang(), nth-child(), etc...
if (this._scanner.peek == chars.$LPAREN) { if (this._scanner.peek == chars.$LPAREN) {
this._scanner.setMode(CssLexerMode.PSEUDO_SELECTOR_WITH_ARGUMENTS); this._scanner.setMode(CssLexerMode.PSEUDO_SELECTOR_WITH_ARGUMENTS);
var openParenToken = this._consume(CssTokenType.Character, '('); const openParenToken = this._consume(CssTokenType.Character, '(');
tokens.push(openParenToken); tokens.push(openParenToken);
// :host(innerSelector(s)), :not(selector), etc... // :host(innerSelector(s)), :not(selector), etc...
if (_pseudoSelectorSupportsInnerSelectors(pseudoSelectorName)) { if (_pseudoSelectorSupportsInnerSelectors(pseudoSelectorName)) {
var innerDelims = startingDelims | LPAREN_DELIM_FLAG | RPAREN_DELIM_FLAG; let innerDelims = startingDelims | LPAREN_DELIM_FLAG | RPAREN_DELIM_FLAG;
if (pseudoSelectorName == 'not') { if (pseudoSelectorName == 'not') {
// the inner selector inside of :not(...) can only be one // the inner selector inside of :not(...) can only be one
// CSS selector (no commas allowed) ... This is according // CSS selector (no commas allowed) ... This is according
@ -491,23 +491,23 @@ export class CssParser {
} else { } else {
// this branch is for things like "en-us, 2k + 1, etc..." // this branch is for things like "en-us, 2k + 1, etc..."
// which all end up in pseudoSelectors like :lang, :nth-child, etc.. // which all end up in pseudoSelectors like :lang, :nth-child, etc..
var innerValueDelims = delimiters | LBRACE_DELIM_FLAG | COLON_DELIM_FLAG | const innerValueDelims = delimiters | LBRACE_DELIM_FLAG | COLON_DELIM_FLAG |
RPAREN_DELIM_FLAG | LPAREN_DELIM_FLAG; RPAREN_DELIM_FLAG | LPAREN_DELIM_FLAG;
while (!characterContainsDelimiter(this._scanner.peek, innerValueDelims)) { while (!characterContainsDelimiter(this._scanner.peek, innerValueDelims)) {
var token = this._scan(); const token = this._scan();
tokens.push(token); tokens.push(token);
} }
} }
var closeParenToken = this._consume(CssTokenType.Character, ')'); const closeParenToken = this._consume(CssTokenType.Character, ')');
tokens.push(closeParenToken); tokens.push(closeParenToken);
} }
const end = this._getScannerIndex() - 1; const end = this._getScannerIndex() - 1;
var strValue = this._extractSourceContent(start, end); const strValue = this._extractSourceContent(start, end);
var endToken = tokens[tokens.length - 1]; const endToken = tokens[tokens.length - 1];
var span = this._generateSourceSpan(startToken, endToken); const span = this._generateSourceSpan(startToken, endToken);
return new CssPseudoSelectorAst(span, strValue, pseudoSelectorName, tokens, innerSelectors); return new CssPseudoSelectorAst(span, strValue, pseudoSelectorName, tokens, innerSelectors);
} }
@ -518,21 +518,21 @@ export class CssParser {
delimiters |= COMMA_DELIM_FLAG; delimiters |= COMMA_DELIM_FLAG;
this._scanner.setMode(CssLexerMode.SELECTOR); this._scanner.setMode(CssLexerMode.SELECTOR);
var selectorCssTokens: CssToken[] = []; const selectorCssTokens: CssToken[] = [];
var pseudoSelectors: CssPseudoSelectorAst[] = []; const pseudoSelectors: CssPseudoSelectorAst[] = [];
var previousToken: CssToken; let previousToken: CssToken;
var selectorPartDelimiters = delimiters | SPACE_DELIM_FLAG; const selectorPartDelimiters = delimiters | SPACE_DELIM_FLAG;
var loopOverSelector = !characterContainsDelimiter(this._scanner.peek, selectorPartDelimiters); let loopOverSelector = !characterContainsDelimiter(this._scanner.peek, selectorPartDelimiters);
var hasAttributeError = false; let hasAttributeError = false;
while (loopOverSelector) { while (loopOverSelector) {
var peek = this._scanner.peek; const peek = this._scanner.peek;
switch (peek) { switch (peek) {
case chars.$COLON: case chars.$COLON:
var innerPseudo = this._parsePseudoSelector(delimiters); let innerPseudo = this._parsePseudoSelector(delimiters);
pseudoSelectors.push(innerPseudo); pseudoSelectors.push(innerPseudo);
this._scanner.setMode(CssLexerMode.SELECTOR); this._scanner.setMode(CssLexerMode.SELECTOR);
break; break;
@ -561,7 +561,7 @@ export class CssParser {
continue; continue;
} }
var token = this._scan(); let token = this._scan();
previousToken = token; previousToken = token;
selectorCssTokens.push(token); selectorCssTokens.push(token);
break; break;
@ -578,18 +578,18 @@ export class CssParser {
previousToken); previousToken);
} }
var end = this._getScannerIndex() - 1; let end = this._getScannerIndex() - 1;
// this happens if the selector is not directly followed by // this happens if the selector is not directly followed by
// a comma or curly brace without a space in between // a comma or curly brace without a space in between
let operator: CssToken = null;
let operatorScanCount = 0;
let lastOperatorToken: CssToken = null;
if (!characterContainsDelimiter(this._scanner.peek, delimiters)) { if (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
var operator: CssToken = null;
var operatorScanCount = 0;
var lastOperatorToken: CssToken = null;
while (operator == null && !characterContainsDelimiter(this._scanner.peek, delimiters) && while (operator == null && !characterContainsDelimiter(this._scanner.peek, delimiters) &&
isSelectorOperatorCharacter(this._scanner.peek)) { isSelectorOperatorCharacter(this._scanner.peek)) {
var token = this._scan(); let token = this._scan();
var tokenOperator = token.strValue; const tokenOperator = token.strValue;
operatorScanCount++; operatorScanCount++;
lastOperatorToken = token; lastOperatorToken = token;
if (tokenOperator != SPACE_OPERATOR) { if (tokenOperator != SPACE_OPERATOR) {
@ -607,7 +607,7 @@ export class CssParser {
lastOperatorToken.index, lastOperatorToken.column, lastOperatorToken.line, lastOperatorToken.index, lastOperatorToken.column, lastOperatorToken.line,
CssTokenType.Identifier, DEEP_OPERATOR_STR); CssTokenType.Identifier, DEEP_OPERATOR_STR);
} else { } else {
let text = SLASH_CHARACTER + deepToken.strValue + deepSlash.strValue; const text = SLASH_CHARACTER + deepToken.strValue + deepSlash.strValue;
this._error( this._error(
generateErrorMessage( generateErrorMessage(
this._getSourceContent(), `${text} is an invalid CSS operator`, text, index, this._getSourceContent(), `${text} is an invalid CSS operator`, text, index,
@ -643,7 +643,7 @@ export class CssParser {
this._scanner.consumeWhitespace(); this._scanner.consumeWhitespace();
var strValue = this._extractSourceContent(start, end); const strValue = this._extractSourceContent(start, end);
// if we do come across one or more spaces inside of // if we do come across one or more spaces inside of
// the operators loop then an empty space is still a // the operators loop then an empty space is still a
@ -654,8 +654,8 @@ export class CssParser {
// please note that `endToken` is reassigned multiple times below // please note that `endToken` is reassigned multiple times below
// so please do not optimize the if statements into if/elseif // so please do not optimize the if statements into if/elseif
var startTokenOrAst: CssToken|CssAst = null; let startTokenOrAst: CssToken|CssAst = null;
var endTokenOrAst: CssToken|CssAst = null; let endTokenOrAst: CssToken|CssAst = null;
if (selectorCssTokens.length > 0) { if (selectorCssTokens.length > 0) {
startTokenOrAst = startTokenOrAst || selectorCssTokens[0]; startTokenOrAst = startTokenOrAst || selectorCssTokens[0];
endTokenOrAst = selectorCssTokens[selectorCssTokens.length - 1]; endTokenOrAst = selectorCssTokens[selectorCssTokens.length - 1];
@ -669,7 +669,7 @@ export class CssParser {
endTokenOrAst = operator; endTokenOrAst = operator;
} }
var span = this._generateSourceSpan(startTokenOrAst, endTokenOrAst); const span = this._generateSourceSpan(startTokenOrAst, endTokenOrAst);
return new CssSimpleSelectorAst(span, selectorCssTokens, strValue, pseudoSelectors, operator); return new CssSimpleSelectorAst(span, selectorCssTokens, strValue, pseudoSelectors, operator);
} }
@ -678,15 +678,15 @@ export class CssParser {
delimiters |= COMMA_DELIM_FLAG; delimiters |= COMMA_DELIM_FLAG;
this._scanner.setMode(CssLexerMode.SELECTOR); this._scanner.setMode(CssLexerMode.SELECTOR);
var simpleSelectors: CssSimpleSelectorAst[] = []; const simpleSelectors: CssSimpleSelectorAst[] = [];
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) { while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
simpleSelectors.push(this._parseSimpleSelector(delimiters)); simpleSelectors.push(this._parseSimpleSelector(delimiters));
this._scanner.consumeWhitespace(); this._scanner.consumeWhitespace();
} }
var firstSelector = simpleSelectors[0]; const firstSelector = simpleSelectors[0];
var lastSelector = simpleSelectors[simpleSelectors.length - 1]; const lastSelector = simpleSelectors[simpleSelectors.length - 1];
var span = this._generateSourceSpan(firstSelector, lastSelector); const span = this._generateSourceSpan(firstSelector, lastSelector);
return new CssSelectorAst(span, simpleSelectors); return new CssSelectorAst(span, simpleSelectors);
} }
@ -697,11 +697,11 @@ export class CssParser {
this._scanner.setMode(CssLexerMode.STYLE_VALUE); this._scanner.setMode(CssLexerMode.STYLE_VALUE);
const start = this._getScannerIndex(); const start = this._getScannerIndex();
var tokens: CssToken[] = []; const tokens: CssToken[] = [];
var wsStr = ''; let wsStr = '';
var previous: CssToken; let previous: CssToken;
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) { while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
var token: CssToken; let token: CssToken;
if (isPresent(previous) && previous.type == CssTokenType.Identifier && if (isPresent(previous) && previous.type == CssTokenType.Identifier &&
this._scanner.peek == chars.$LPAREN) { this._scanner.peek == chars.$LPAREN) {
token = this._consume(CssTokenType.Character, '('); token = this._consume(CssTokenType.Character, '(');
@ -731,7 +731,7 @@ export class CssParser {
const end = this._getScannerIndex() - 1; const end = this._getScannerIndex() - 1;
this._scanner.consumeWhitespace(); this._scanner.consumeWhitespace();
var code = this._scanner.peek; const code = this._scanner.peek;
if (code == chars.$SEMICOLON) { if (code == chars.$SEMICOLON) {
this._consume(CssTokenType.Character, ';'); this._consume(CssTokenType.Character, ';');
} else if (code != chars.$RBRACE) { } else if (code != chars.$RBRACE) {
@ -742,18 +742,18 @@ export class CssParser {
previous); previous);
} }
var strValue = this._extractSourceContent(start, end); const strValue = this._extractSourceContent(start, end);
var startToken = tokens[0]; const startToken = tokens[0];
var endToken = tokens[tokens.length - 1]; const endToken = tokens[tokens.length - 1];
var span = this._generateSourceSpan(startToken, endToken); const span = this._generateSourceSpan(startToken, endToken);
return new CssStyleValueAst(span, tokens, strValue); return new CssStyleValueAst(span, tokens, strValue);
} }
/** @internal */ /** @internal */
_collectUntilDelim(delimiters: number, assertType: CssTokenType = null): CssToken[] { _collectUntilDelim(delimiters: number, assertType: CssTokenType = null): CssToken[] {
var tokens: CssToken[] = []; const tokens: CssToken[] = [];
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) { while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
var val = isPresent(assertType) ? this._consume(assertType) : this._scan(); const val = isPresent(assertType) ? this._consume(assertType) : this._scan();
tokens.push(val); tokens.push(val);
} }
return tokens; return tokens;
@ -765,20 +765,20 @@ export class CssParser {
this._scanner.setMode(CssLexerMode.BLOCK); this._scanner.setMode(CssLexerMode.BLOCK);
var startToken = this._consume(CssTokenType.Character, '{'); const startToken = this._consume(CssTokenType.Character, '{');
this._scanner.consumeEmptyStatements(); this._scanner.consumeEmptyStatements();
var results: CssRuleAst[] = []; const results: CssRuleAst[] = [];
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) { while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
results.push(this._parseRule(delimiters)); results.push(this._parseRule(delimiters));
} }
var endToken = this._consume(CssTokenType.Character, '}'); const endToken = this._consume(CssTokenType.Character, '}');
this._scanner.setMode(CssLexerMode.BLOCK); this._scanner.setMode(CssLexerMode.BLOCK);
this._scanner.consumeEmptyStatements(); this._scanner.consumeEmptyStatements();
var span = this._generateSourceSpan(startToken, endToken); const span = this._generateSourceSpan(startToken, endToken);
return new CssBlockAst(span, results); return new CssBlockAst(span, results);
} }
@ -788,12 +788,12 @@ export class CssParser {
this._scanner.setMode(CssLexerMode.STYLE_BLOCK); this._scanner.setMode(CssLexerMode.STYLE_BLOCK);
var startToken = this._consume(CssTokenType.Character, '{'); const startToken = this._consume(CssTokenType.Character, '{');
if (startToken.numValue != chars.$LBRACE) { if (startToken.numValue != chars.$LBRACE) {
return null; return null;
} }
var definitions: CssDefinitionAst[] = []; const definitions: CssDefinitionAst[] = [];
this._scanner.consumeEmptyStatements(); this._scanner.consumeEmptyStatements();
while (!characterContainsDelimiter(this._scanner.peek, delimiters)) { while (!characterContainsDelimiter(this._scanner.peek, delimiters)) {
@ -801,12 +801,12 @@ export class CssParser {
this._scanner.consumeEmptyStatements(); this._scanner.consumeEmptyStatements();
} }
var endToken = this._consume(CssTokenType.Character, '}'); const endToken = this._consume(CssTokenType.Character, '}');
this._scanner.setMode(CssLexerMode.STYLE_BLOCK); this._scanner.setMode(CssLexerMode.STYLE_BLOCK);
this._scanner.consumeEmptyStatements(); this._scanner.consumeEmptyStatements();
var span = this._generateSourceSpan(startToken, endToken); const span = this._generateSourceSpan(startToken, endToken);
return new CssStylesBlockAst(span, definitions); return new CssStylesBlockAst(span, definitions);
} }
@ -814,10 +814,10 @@ export class CssParser {
_parseDefinition(delimiters: number): CssDefinitionAst { _parseDefinition(delimiters: number): CssDefinitionAst {
this._scanner.setMode(CssLexerMode.STYLE_BLOCK); this._scanner.setMode(CssLexerMode.STYLE_BLOCK);
var prop = this._consume(CssTokenType.Identifier); let prop = this._consume(CssTokenType.Identifier);
var parseValue: boolean = false; let parseValue: boolean = false;
var value: CssStyleValueAst = null; let value: CssStyleValueAst = null;
var endToken: CssToken|CssStyleValueAst = prop; let endToken: CssToken|CssStyleValueAst = prop;
// the colon value separates the prop from the style. // the colon value separates the prop from the style.
// there are a few cases as to what could happen if it // there are a few cases as to what could happen if it
@ -830,13 +830,13 @@ export class CssParser {
break; break;
default: default:
var propStr = [prop.strValue]; let propStr = [prop.strValue];
if (this._scanner.peek != chars.$COLON) { if (this._scanner.peek != chars.$COLON) {
// this will throw the error // this will throw the error
var nextValue = this._consume(CssTokenType.Character, ':'); const nextValue = this._consume(CssTokenType.Character, ':');
propStr.push(nextValue.strValue); propStr.push(nextValue.strValue);
var remainingTokens = this._collectUntilDelim( const remainingTokens = this._collectUntilDelim(
delimiters | COLON_DELIM_FLAG | SEMICOLON_DELIM_FLAG, CssTokenType.Identifier); delimiters | COLON_DELIM_FLAG | SEMICOLON_DELIM_FLAG, CssTokenType.Identifier);
if (remainingTokens.length > 0) { if (remainingTokens.length > 0) {
remainingTokens.forEach((token) => { propStr.push(token.strValue); }); remainingTokens.forEach((token) => { propStr.push(token.strValue); });
@ -865,7 +865,7 @@ export class CssParser {
prop); prop);
} }
var span = this._generateSourceSpan(prop, endToken); const span = this._generateSourceSpan(prop, endToken);
return new CssDefinitionAst(span, prop, value); return new CssDefinitionAst(span, prop, value);
} }
@ -880,8 +880,8 @@ export class CssParser {
/** @internal */ /** @internal */
_error(message: string, problemToken: CssToken) { _error(message: string, problemToken: CssToken) {
var length = problemToken.strValue.length; const length = problemToken.strValue.length;
var error = CssParseError.create( const error = CssParseError.create(
this._file, 0, problemToken.line, problemToken.column, length, message); this._file, 0, problemToken.line, problemToken.column, length, message);
this._errors.push(error); this._errors.push(error);
} }
@ -891,9 +891,9 @@ export class CssParseError extends ParseError {
static create( static create(
file: ParseSourceFile, offset: number, line: number, col: number, length: number, file: ParseSourceFile, offset: number, line: number, col: number, length: number,
errMsg: string): CssParseError { errMsg: string): CssParseError {
var start = new ParseLocation(file, offset, line, col); const start = new ParseLocation(file, offset, line, col);
var end = new ParseLocation(file, offset, line, col + length); const end = new ParseLocation(file, offset, line, col + length);
var span = new ParseSourceSpan(start, end); const span = new ParseSourceSpan(start, end);
return new CssParseError(span, 'CSS Parse Error: ' + errMsg); return new CssParseError(span, 'CSS Parse Error: ' + errMsg);
} }

View File

@ -52,7 +52,7 @@ export class DirectiveNormalizer {
} }
private _fetch(url: string): Promise<string> { private _fetch(url: string): Promise<string> {
var result = this._resourceLoaderCache.get(url); let result = this._resourceLoaderCache.get(url);
if (!result) { if (!result) {
result = this._resourceLoader.get(url); result = this._resourceLoader.get(url);
this._resourceLoaderCache.set(url, result); this._resourceLoaderCache.set(url, result);
@ -91,7 +91,7 @@ export class DirectiveNormalizer {
normalizeTemplateAsync(prenomData: PrenormalizedTemplateMetadata): normalizeTemplateAsync(prenomData: PrenormalizedTemplateMetadata):
Promise<CompileTemplateMetadata> { Promise<CompileTemplateMetadata> {
let templateUrl = this._urlResolver.resolve(prenomData.moduleUrl, prenomData.templateUrl); const templateUrl = this._urlResolver.resolve(prenomData.moduleUrl, prenomData.templateUrl);
return this._fetch(templateUrl) return this._fetch(templateUrl)
.then((value) => this.normalizeLoadedTemplate(prenomData, value, templateUrl)); .then((value) => this.normalizeLoadedTemplate(prenomData, value, templateUrl));
} }
@ -164,7 +164,7 @@ export class DirectiveNormalizer {
return Promise return Promise
.all(styleUrls.filter((styleUrl) => !loadedStylesheets.has(styleUrl)) .all(styleUrls.filter((styleUrl) => !loadedStylesheets.has(styleUrl))
.map(styleUrl => this._fetch(styleUrl).then((loadedStyle) => { .map(styleUrl => this._fetch(styleUrl).then((loadedStyle) => {
var stylesheet = this.normalizeStylesheet( const stylesheet = this.normalizeStylesheet(
new CompileStylesheetMetadata({styles: [loadedStyle], moduleUrl: styleUrl})); new CompileStylesheetMetadata({styles: [loadedStyle], moduleUrl: styleUrl}));
loadedStylesheets.set(styleUrl, stylesheet); loadedStylesheets.set(styleUrl, stylesheet);
return this._loadMissingExternalStylesheets( return this._loadMissingExternalStylesheets(
@ -174,11 +174,11 @@ export class DirectiveNormalizer {
} }
normalizeStylesheet(stylesheet: CompileStylesheetMetadata): CompileStylesheetMetadata { normalizeStylesheet(stylesheet: CompileStylesheetMetadata): CompileStylesheetMetadata {
var allStyleUrls = stylesheet.styleUrls.filter(isStyleUrlResolvable) const allStyleUrls = stylesheet.styleUrls.filter(isStyleUrlResolvable)
.map(url => this._urlResolver.resolve(stylesheet.moduleUrl, url)); .map(url => this._urlResolver.resolve(stylesheet.moduleUrl, url));
var allStyles = stylesheet.styles.map(style => { const allStyles = stylesheet.styles.map(style => {
var styleWithImports = extractStyleUrls(this._urlResolver, stylesheet.moduleUrl, style); const styleWithImports = extractStyleUrls(this._urlResolver, stylesheet.moduleUrl, style);
allStyleUrls.push(...styleWithImports.styleUrls); allStyleUrls.push(...styleWithImports.styleUrls);
return styleWithImports.style; return styleWithImports.style;
}); });
@ -195,7 +195,7 @@ class TemplatePreparseVisitor implements html.Visitor {
ngNonBindableStackCount: number = 0; ngNonBindableStackCount: number = 0;
visitElement(ast: html.Element, context: any): any { visitElement(ast: html.Element, context: any): any {
var preparsedElement = preparseElement(ast); const preparsedElement = preparseElement(ast);
switch (preparsedElement.type) { switch (preparsedElement.type) {
case PreparsedElementType.NG_CONTENT: case PreparsedElementType.NG_CONTENT:
if (this.ngNonBindableStackCount === 0) { if (this.ngNonBindableStackCount === 0) {
@ -203,7 +203,7 @@ class TemplatePreparseVisitor implements html.Visitor {
} }
break; break;
case PreparsedElementType.STYLE: case PreparsedElementType.STYLE:
var textContent = ''; let textContent = '';
ast.children.forEach(child => { ast.children.forEach(child => {
if (child instanceof html.Text) { if (child instanceof html.Text) {
textContent += child.value; textContent += child.value;

View File

@ -121,7 +121,7 @@ export class DirectiveResolver {
mergedInputs.unshift(...directive.inputs); mergedInputs.unshift(...directive.inputs);
} }
let mergedOutputs: string[] = outputs; const mergedOutputs: string[] = outputs;
if (directive.outputs) { if (directive.outputs) {
const outputNames: string[] = const outputNames: string[] =

View File

@ -207,7 +207,7 @@ function addNgDoCheckMethod(builder: DirectiveWrapperBuilder) {
function addCheckInputMethod(input: string, builder: DirectiveWrapperBuilder) { function addCheckInputMethod(input: string, builder: DirectiveWrapperBuilder) {
const field = createCheckBindingField(builder); const field = createCheckBindingField(builder);
var onChangeStatements: o.Statement[] = [ const onChangeStatements: o.Statement[] = [
o.THIS_EXPR.prop(CHANGED_FIELD_NAME).set(o.literal(true)).toStmt(), o.THIS_EXPR.prop(CHANGED_FIELD_NAME).set(o.literal(true)).toStmt(),
o.THIS_EXPR.prop(CONTEXT_FIELD_NAME).prop(input).set(CURR_VALUE_VAR).toStmt(), o.THIS_EXPR.prop(CONTEXT_FIELD_NAME).prop(input).set(CURR_VALUE_VAR).toStmt(),
]; ];
@ -219,7 +219,7 @@ function addCheckInputMethod(input: string, builder: DirectiveWrapperBuilder) {
.toStmt()); .toStmt());
} }
var methodBody: o.Statement[] = createCheckBindingStmt( const methodBody: o.Statement[] = createCheckBindingStmt(
{currValExpr: CURR_VALUE_VAR, forceUpdate: FORCE_UPDATE_VAR, stmts: []}, field.expression, {currValExpr: CURR_VALUE_VAR, forceUpdate: FORCE_UPDATE_VAR, stmts: []}, field.expression,
THROW_ON_CHANGE_VAR, onChangeStatements); THROW_ON_CHANGE_VAR, onChangeStatements);
builder.methods.push(new o.ClassMethod( builder.methods.push(new o.ClassMethod(
@ -430,7 +430,7 @@ export class DirectiveWrapperExpressions {
dirMeta: CompileDirectiveSummary, hostProps: BoundElementPropertyAst[], usedEvents: string[], dirMeta: CompileDirectiveSummary, hostProps: BoundElementPropertyAst[], usedEvents: string[],
dirWrapper: o.Expression, view: o.Expression, eventListener: o.Expression): o.Statement[] { dirWrapper: o.Expression, view: o.Expression, eventListener: o.Expression): o.Statement[] {
let needsSubscribe = false; let needsSubscribe = false;
let eventFlags: o.Expression[] = []; const eventFlags: o.Expression[] = [];
Object.keys(dirMeta.outputs).forEach((propName) => { Object.keys(dirMeta.outputs).forEach((propName) => {
const eventName = dirMeta.outputs[propName]; const eventName = dirMeta.outputs[propName];
const eventUsed = usedEvents.indexOf(eventName) > -1; const eventUsed = usedEvents.indexOf(eventName) > -1;

View File

@ -376,8 +376,8 @@ export class AstTransformer implements AstVisitor {
} }
visitAll(asts: any[]): any[] { visitAll(asts: any[]): any[] {
var res = new Array(asts.length); const res = new Array(asts.length);
for (var i = 0; i < asts.length; ++i) { for (let i = 0; i < asts.length; ++i) {
res[i] = asts[i].visit(this); res[i] = asts[i].visit(this);
} }
return res; return res;

View File

@ -137,7 +137,8 @@ class _Scanner {
} }
scanToken(): Token { scanToken(): Token {
var input = this.input, length = this.length, peek = this.peek, index = this.index; const input = this.input, length = this.length;
let peek = this.peek, index = this.index;
// Skip whitespace. // Skip whitespace.
while (peek <= chars.$SPACE) { while (peek <= chars.$SPACE) {
@ -160,7 +161,7 @@ class _Scanner {
if (isIdentifierStart(peek)) return this.scanIdentifier(); if (isIdentifierStart(peek)) return this.scanIdentifier();
if (chars.isDigit(peek)) return this.scanNumber(index); if (chars.isDigit(peek)) return this.scanNumber(index);
var start: number = index; const start: number = index;
switch (peek) { switch (peek) {
case chars.$PERIOD: case chars.$PERIOD:
this.advance(); this.advance();
@ -235,7 +236,7 @@ class _Scanner {
start: number, one: string, twoCode: number, two: string, threeCode?: number, start: number, one: string, twoCode: number, two: string, threeCode?: number,
three?: string): Token { three?: string): Token {
this.advance(); this.advance();
var str: string = one; let str: string = one;
if (this.peek == twoCode) { if (this.peek == twoCode) {
this.advance(); this.advance();
str += two; str += two;
@ -248,16 +249,16 @@ class _Scanner {
} }
scanIdentifier(): Token { scanIdentifier(): Token {
var start: number = this.index; const start: number = this.index;
this.advance(); this.advance();
while (isIdentifierPart(this.peek)) this.advance(); while (isIdentifierPart(this.peek)) this.advance();
var str: string = this.input.substring(start, this.index); const str: string = this.input.substring(start, this.index);
return KEYWORDS.indexOf(str) > -1 ? newKeywordToken(start, str) : return KEYWORDS.indexOf(str) > -1 ? newKeywordToken(start, str) :
newIdentifierToken(start, str); newIdentifierToken(start, str);
} }
scanNumber(start: number): Token { scanNumber(start: number): Token {
var simple: boolean = (this.index === start); let simple: boolean = (this.index === start);
this.advance(); // Skip initial digit. this.advance(); // Skip initial digit.
while (true) { while (true) {
if (chars.isDigit(this.peek)) { if (chars.isDigit(this.peek)) {
@ -286,7 +287,7 @@ class _Scanner {
let buffer: string = ''; let buffer: string = '';
let marker: number = this.index; let marker: number = this.index;
let input: string = this.input; const input: string = this.input;
while (this.peek != quote) { while (this.peek != quote) {
if (this.peek == chars.$BACKSLASH) { if (this.peek == chars.$BACKSLASH) {
@ -337,7 +338,7 @@ function isIdentifierStart(code: number): boolean {
export function isIdentifier(input: string): boolean { export function isIdentifier(input: string): boolean {
if (input.length == 0) return false; if (input.length == 0) return false;
var scanner = new _Scanner(input); const scanner = new _Scanner(input);
if (!isIdentifierStart(scanner.peek)) return false; if (!isIdentifierStart(scanner.peek)) return false;
scanner.advance(); scanner.advance();
while (scanner.peek !== chars.$EOF) { while (scanner.peek !== chars.$EOF) {

View File

@ -53,7 +53,7 @@ export class Parser {
parseBinding( parseBinding(
input: string, location: any, input: string, location: any,
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG): ASTWithSource { interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG): ASTWithSource {
var ast = this._parseBindingAst(input, location, interpolationConfig); const ast = this._parseBindingAst(input, location, interpolationConfig);
return new ASTWithSource(ast, input, location, this.errors); return new ASTWithSource(ast, input, location, this.errors);
} }
@ -77,7 +77,7 @@ export class Parser {
input: string, location: string, interpolationConfig: InterpolationConfig): AST { input: string, location: string, interpolationConfig: InterpolationConfig): AST {
// Quotes expressions use 3rd-party expression language. We don't want to use // Quotes expressions use 3rd-party expression language. We don't want to use
// our lexer or parser for that, so we check for that ahead of time. // our lexer or parser for that, so we check for that ahead of time.
var quote = this._parseQuote(input, location); const quote = this._parseQuote(input, location);
if (isPresent(quote)) { if (isPresent(quote)) {
return quote; return quote;
@ -94,11 +94,11 @@ export class Parser {
private _parseQuote(input: string, location: any): AST { private _parseQuote(input: string, location: any): AST {
if (isBlank(input)) return null; if (isBlank(input)) return null;
var prefixSeparatorIndex = input.indexOf(':'); const prefixSeparatorIndex = input.indexOf(':');
if (prefixSeparatorIndex == -1) return null; if (prefixSeparatorIndex == -1) return null;
var prefix = input.substring(0, prefixSeparatorIndex).trim(); const prefix = input.substring(0, prefixSeparatorIndex).trim();
if (!isIdentifier(prefix)) return null; if (!isIdentifier(prefix)) return null;
var uninterpretedExpression = input.substring(prefixSeparatorIndex + 1); const uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);
return new Quote(new ParseSpan(0, input.length), prefix, uninterpretedExpression, location); return new Quote(new ParseSpan(0, input.length), prefix, uninterpretedExpression, location);
} }
@ -120,10 +120,10 @@ export class Parser {
parseInterpolation( parseInterpolation(
input: string, location: any, input: string, location: any,
interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG): ASTWithSource { interpolationConfig: InterpolationConfig = DEFAULT_INTERPOLATION_CONFIG): ASTWithSource {
let split = this.splitInterpolation(input, location, interpolationConfig); const split = this.splitInterpolation(input, location, interpolationConfig);
if (split == null) return null; if (split == null) return null;
let expressions: AST[] = []; const expressions: AST[] = [];
for (let i = 0; i < split.expressions.length; ++i) { for (let i = 0; i < split.expressions.length; ++i) {
const expressionText = split.expressions[i]; const expressionText = split.expressions[i];
@ -155,7 +155,7 @@ export class Parser {
const offsets: number[] = []; const offsets: number[] = [];
let offset = 0; let offset = 0;
for (let i = 0; i < parts.length; i++) { for (let i = 0; i < parts.length; i++) {
var part: string = parts[i]; const part: string = parts[i];
if (i % 2 === 0) { if (i % 2 === 0) {
// fixed string // fixed string
strings.push(part); strings.push(part);
@ -189,7 +189,7 @@ export class Parser {
} }
private _commentStart(input: string): number { private _commentStart(input: string): number {
var outerQuote: number = null; let outerQuote: number = null;
for (let i = 0; i < input.length - 1; i++) { for (let i = 0; i < input.length - 1; i++) {
const char = input.charCodeAt(i); const char = input.charCodeAt(i);
const nextChar = input.charCodeAt(i + 1); const nextChar = input.charCodeAt(i + 1);
@ -207,8 +207,8 @@ export class Parser {
private _checkNoInterpolation( private _checkNoInterpolation(
input: string, location: any, interpolationConfig: InterpolationConfig): void { input: string, location: any, interpolationConfig: InterpolationConfig): void {
var regexp = _createInterpolateRegExp(interpolationConfig); const regexp = _createInterpolateRegExp(interpolationConfig);
var parts = input.split(regexp); const parts = input.split(regexp);
if (parts.length > 1) { if (parts.length > 1) {
this._reportError( this._reportError(
`Got interpolation (${interpolationConfig.start}${interpolationConfig.end}) where expression was expected`, `Got interpolation (${interpolationConfig.start}${interpolationConfig.end}) where expression was expected`,
@ -220,8 +220,8 @@ export class Parser {
private _findInterpolationErrorColumn( private _findInterpolationErrorColumn(
parts: string[], partInErrIdx: number, interpolationConfig: InterpolationConfig): number { parts: string[], partInErrIdx: number, interpolationConfig: InterpolationConfig): number {
var errLocation = ''; let errLocation = '';
for (var j = 0; j < partInErrIdx; j++) { for (let j = 0; j < partInErrIdx; j++) {
errLocation += j % 2 === 0 ? errLocation += j % 2 === 0 ?
parts[j] : parts[j] :
`${interpolationConfig.start}${parts[j]}${interpolationConfig.end}`; `${interpolationConfig.start}${parts[j]}${interpolationConfig.end}`;
@ -244,7 +244,7 @@ export class _ParseAST {
private offset: number) {} private offset: number) {}
peek(offset: number): Token { peek(offset: number): Token {
var i = this.index + offset; const i = this.index + offset;
return i < this.tokens.length ? this.tokens[i] : EOF; return i < this.tokens.length ? this.tokens[i] : EOF;
} }
@ -290,7 +290,7 @@ export class _ParseAST {
} }
expectIdentifierOrKeyword(): string { expectIdentifierOrKeyword(): string {
var n = this.next; const n = this.next;
if (!n.isIdentifier() && !n.isKeyword()) { if (!n.isIdentifier() && !n.isKeyword()) {
this.error(`Unexpected token ${n}, expected identifier or keyword`); this.error(`Unexpected token ${n}, expected identifier or keyword`);
return ''; return '';
@ -300,7 +300,7 @@ export class _ParseAST {
} }
expectIdentifierOrKeywordOrString(): string { expectIdentifierOrKeywordOrString(): string {
var n = this.next; const n = this.next;
if (!n.isIdentifier() && !n.isKeyword() && !n.isString()) { if (!n.isIdentifier() && !n.isKeyword() && !n.isString()) {
this.error(`Unexpected token ${n}, expected identifier, keyword, or string`); this.error(`Unexpected token ${n}, expected identifier, keyword, or string`);
return ''; return '';
@ -310,10 +310,10 @@ export class _ParseAST {
} }
parseChain(): AST { parseChain(): AST {
var exprs: AST[] = []; const exprs: AST[] = [];
const start = this.inputIndex; const start = this.inputIndex;
while (this.index < this.tokens.length) { while (this.index < this.tokens.length) {
var expr = this.parsePipe(); const expr = this.parsePipe();
exprs.push(expr); exprs.push(expr);
if (this.optionalCharacter(chars.$SEMICOLON)) { if (this.optionalCharacter(chars.$SEMICOLON)) {
@ -332,15 +332,15 @@ export class _ParseAST {
} }
parsePipe(): AST { parsePipe(): AST {
var result = this.parseExpression(); let result = this.parseExpression();
if (this.optionalOperator('|')) { if (this.optionalOperator('|')) {
if (this.parseAction) { if (this.parseAction) {
this.error('Cannot have a pipe in an action expression'); this.error('Cannot have a pipe in an action expression');
} }
do { do {
var name = this.expectIdentifierOrKeyword(); const name = this.expectIdentifierOrKeyword();
var args: AST[] = []; const args: AST[] = [];
while (this.optionalCharacter(chars.$COLON)) { while (this.optionalCharacter(chars.$COLON)) {
args.push(this.parseExpression()); args.push(this.parseExpression());
} }
@ -361,8 +361,8 @@ export class _ParseAST {
const yes = this.parsePipe(); const yes = this.parsePipe();
let no: AST; let no: AST;
if (!this.optionalCharacter(chars.$COLON)) { if (!this.optionalCharacter(chars.$COLON)) {
var end = this.inputIndex; const end = this.inputIndex;
var expression = this.input.substring(start, end); const expression = this.input.substring(start, end);
this.error(`Conditional expression ${expression} requires all 3 expressions`); this.error(`Conditional expression ${expression} requires all 3 expressions`);
no = new EmptyExpr(this.span(start)); no = new EmptyExpr(this.span(start));
} else { } else {
@ -398,7 +398,7 @@ export class _ParseAST {
// '==','!=','===','!==' // '==','!=','===','!=='
let result = this.parseRelational(); let result = this.parseRelational();
while (this.next.type == TokenType.Operator) { while (this.next.type == TokenType.Operator) {
let operator = this.next.strValue; const operator = this.next.strValue;
switch (operator) { switch (operator) {
case '==': case '==':
case '===': case '===':
@ -418,7 +418,7 @@ export class _ParseAST {
// '<', '>', '<=', '>=' // '<', '>', '<=', '>='
let result = this.parseAdditive(); let result = this.parseAdditive();
while (this.next.type == TokenType.Operator) { while (this.next.type == TokenType.Operator) {
let operator = this.next.strValue; const operator = this.next.strValue;
switch (operator) { switch (operator) {
case '<': case '<':
case '>': case '>':
@ -591,7 +591,7 @@ export class _ParseAST {
} }
parseExpressionList(terminator: number): AST[] { parseExpressionList(terminator: number): AST[] {
let result: AST[] = []; const result: AST[] = [];
if (!this.next.isCharacter(terminator)) { if (!this.next.isCharacter(terminator)) {
do { do {
result.push(this.parsePipe()); result.push(this.parsePipe());
@ -601,14 +601,14 @@ export class _ParseAST {
} }
parseLiteralMap(): LiteralMap { parseLiteralMap(): LiteralMap {
let keys: string[] = []; const keys: string[] = [];
let values: AST[] = []; const values: AST[] = [];
const start = this.inputIndex; const start = this.inputIndex;
this.expectCharacter(chars.$LBRACE); this.expectCharacter(chars.$LBRACE);
if (!this.optionalCharacter(chars.$RBRACE)) { if (!this.optionalCharacter(chars.$RBRACE)) {
this.rbracesExpected++; this.rbracesExpected++;
do { do {
var key = this.expectIdentifierOrKeywordOrString(); const key = this.expectIdentifierOrKeywordOrString();
keys.push(key); keys.push(key);
this.expectCharacter(chars.$COLON); this.expectCharacter(chars.$COLON);
values.push(this.parsePipe()); values.push(this.parsePipe());
@ -628,7 +628,7 @@ export class _ParseAST {
const args = this.parseCallArguments(); const args = this.parseCallArguments();
this.expectCharacter(chars.$RPAREN); this.expectCharacter(chars.$RPAREN);
this.rparensExpected--; this.rparensExpected--;
let span = this.span(start); const span = this.span(start);
return isSafe ? new SafeMethodCall(span, receiver, id, args) : return isSafe ? new SafeMethodCall(span, receiver, id, args) :
new MethodCall(span, receiver, id, args); new MethodCall(span, receiver, id, args);
@ -647,7 +647,7 @@ export class _ParseAST {
return new EmptyExpr(this.span(start)); return new EmptyExpr(this.span(start));
} }
let value = this.parseConditional(); const value = this.parseConditional();
return new PropertyWrite(this.span(start), receiver, id, value); return new PropertyWrite(this.span(start), receiver, id, value);
} else { } else {
return new PropertyRead(this.span(start), receiver, id); return new PropertyRead(this.span(start), receiver, id);
@ -658,7 +658,7 @@ export class _ParseAST {
parseCallArguments(): BindingPipe[] { parseCallArguments(): BindingPipe[] {
if (this.next.isCharacter(chars.$RPAREN)) return []; if (this.next.isCharacter(chars.$RPAREN)) return [];
var positionals: AST[] = []; const positionals: AST[] = [];
do { do {
positionals.push(this.parsePipe()); positionals.push(this.parsePipe());
} while (this.optionalCharacter(chars.$COMMA)); } while (this.optionalCharacter(chars.$COMMA));
@ -683,16 +683,16 @@ export class _ParseAST {
} }
parseTemplateBindings(): TemplateBindingParseResult { parseTemplateBindings(): TemplateBindingParseResult {
let bindings: TemplateBinding[] = []; const bindings: TemplateBinding[] = [];
let prefix: string = null; let prefix: string = null;
let warnings: string[] = []; const warnings: string[] = [];
while (this.index < this.tokens.length) { while (this.index < this.tokens.length) {
const start = this.inputIndex; const start = this.inputIndex;
const keyIsVar: boolean = this.peekKeywordLet(); const keyIsVar: boolean = this.peekKeywordLet();
if (keyIsVar) { if (keyIsVar) {
this.advance(); this.advance();
} }
var key = this.expectTemplateBindingKey(); let key = this.expectTemplateBindingKey();
if (!keyIsVar) { if (!keyIsVar) {
if (prefix == null) { if (prefix == null) {
prefix = key; prefix = key;
@ -701,8 +701,8 @@ export class _ParseAST {
} }
} }
this.optionalCharacter(chars.$COLON); this.optionalCharacter(chars.$COLON);
var name: string = null; let name: string = null;
var expression: ASTWithSource = null; let expression: ASTWithSource = null;
if (keyIsVar) { if (keyIsVar) {
if (this.optionalOperator('=')) { if (this.optionalOperator('=')) {
name = this.expectTemplateBindingKey(); name = this.expectTemplateBindingKey();
@ -765,7 +765,7 @@ export class _ParseAST {
class SimpleExpressionChecker implements AstVisitor { class SimpleExpressionChecker implements AstVisitor {
static check(ast: AST): string[] { static check(ast: AST): string[] {
var s = new SimpleExpressionChecker(); const s = new SimpleExpressionChecker();
ast.visit(s); ast.visit(s);
return s.errors; return s.errors;
} }

View File

@ -27,7 +27,8 @@ class _SerializerVisitor implements i18n.Visitor {
} }
visitIcu(icu: i18n.Icu, context: any): any { visitIcu(icu: i18n.Icu, context: any): any {
let strCases = Object.keys(icu.cases).map((k: string) => `${k} {${icu.cases[k].visit(this)}}`); const strCases =
Object.keys(icu.cases).map((k: string) => `${k} {${icu.cases[k].visit(this)}}`);
return `{${icu.expression}, ${icu.type}, ${strCases.join(', ')}}`; return `{${icu.expression}, ${icu.type}, ${strCases.join(', ')}}`;
} }

View File

@ -19,7 +19,7 @@ export interface Serializer {
// Generate a map of placeholder to content indexed by message ids // Generate a map of placeholder to content indexed by message ids
export function extractPlaceholders(messageBundle: MessageBundle) { export function extractPlaceholders(messageBundle: MessageBundle) {
const messageMap = messageBundle.getMessageMap(); const messageMap = messageBundle.getMessageMap();
let placeholders: {[id: string]: {[name: string]: string}} = {}; const placeholders: {[id: string]: {[name: string]: string}} = {};
Object.keys(messageMap).forEach(msgId => { Object.keys(messageMap).forEach(msgId => {
placeholders[msgId] = messageMap[msgId].placeholders; placeholders[msgId] = messageMap[msgId].placeholders;
@ -31,7 +31,7 @@ export function extractPlaceholders(messageBundle: MessageBundle) {
// Generate a map of placeholder to message ids indexed by message ids // Generate a map of placeholder to message ids indexed by message ids
export function extractPlaceholderToIds(messageBundle: MessageBundle) { export function extractPlaceholderToIds(messageBundle: MessageBundle) {
const messageMap = messageBundle.getMessageMap(); const messageMap = messageBundle.getMessageMap();
let placeholderToIds: {[id: string]: {[name: string]: string}} = {}; const placeholderToIds: {[id: string]: {[name: string]: string}} = {};
Object.keys(messageMap).forEach(msgId => { Object.keys(messageMap).forEach(msgId => {
placeholderToIds[msgId] = messageMap[msgId].placeholderToMsgIds; placeholderToIds[msgId] = messageMap[msgId].placeholderToMsgIds;

View File

@ -41,7 +41,7 @@ export class Xliff implements Serializer {
Object.keys(messageMap).forEach((id) => { Object.keys(messageMap).forEach((id) => {
const message = messageMap[id]; const message = messageMap[id];
let transUnit = new xml.Tag(_UNIT_TAG, {id: id, datatype: 'html'}); const transUnit = new xml.Tag(_UNIT_TAG, {id: id, datatype: 'html'});
transUnit.children.push( transUnit.children.push(
new xml.CR(8), new xml.Tag(_SOURCE_TAG, {}, visitor.serialize(message.nodes)), new xml.CR(8), new xml.Tag(_SOURCE_TAG, {}, visitor.serialize(message.nodes)),
new xml.CR(8), new xml.Tag(_TARGET_TAG)); new xml.CR(8), new xml.Tag(_TARGET_TAG));
@ -93,7 +93,7 @@ export class Xliff implements Serializer {
// Convert the string messages to html ast // Convert the string messages to html ast
// TODO(vicb): map error message back to the original message in xtb // TODO(vicb): map error message back to the original message in xtb
let messageMap: {[id: string]: ml.Node[]} = {}; const messageMap: {[id: string]: ml.Node[]} = {};
const parseErrors: ParseError[] = []; const parseErrors: ParseError[] = [];
Object.keys(messages).forEach((id) => { Object.keys(messages).forEach((id) => {

View File

@ -42,11 +42,11 @@ const _DOCTYPE = `<!ELEMENT messagebundle (msg)*>
export class Xmb implements Serializer { export class Xmb implements Serializer {
write(messageMap: {[k: string]: i18n.Message}): string { write(messageMap: {[k: string]: i18n.Message}): string {
const visitor = new _Visitor(); const visitor = new _Visitor();
let rootNode = new xml.Tag(_MESSAGES_TAG); const rootNode = new xml.Tag(_MESSAGES_TAG);
Object.keys(messageMap).forEach((id) => { Object.keys(messageMap).forEach((id) => {
const message = messageMap[id]; const message = messageMap[id];
let attrs: {[k: string]: string} = {id}; const attrs: {[k: string]: string} = {id};
if (message.description) { if (message.description) {
attrs['desc'] = message.description; attrs['desc'] = message.description;

View File

@ -43,7 +43,7 @@ export class Xtb implements Serializer {
// Convert the string messages to html ast // Convert the string messages to html ast
// TODO(vicb): map error message back to the original message in xtb // TODO(vicb): map error message back to the original message in xtb
let messageMap: {[id: string]: ml.Node[]} = {}; const messageMap: {[id: string]: ml.Node[]} = {};
const parseErrors: ParseError[] = []; const parseErrors: ParseError[] = [];
Object.keys(messages).forEach((id) => { Object.keys(messages).forEach((id) => {

View File

@ -11,11 +11,11 @@ import {ANALYZE_FOR_ENTRY_COMPONENTS, AnimationTransitionEvent, ChangeDetectionS
import {CompileIdentifierMetadata, CompileTokenMetadata} from './compile_metadata'; import {CompileIdentifierMetadata, CompileTokenMetadata} from './compile_metadata';
import {AnimationGroupPlayer, AnimationKeyframe, AnimationSequencePlayer, AnimationStyles, AnimationTransition, AppView, ChangeDetectorStatus, CodegenComponentFactoryResolver, ComponentRef_, DebugAppView, DebugContext, NgModuleInjector, NoOpAnimationPlayer, StaticNodeDebugInfo, TemplateRef_, UNINITIALIZED, ValueUnwrapper, ViewContainer, ViewType, balanceAnimationKeyframes, clearStyles, collectAndResolveStyles, devModeEqual, prepareFinalAnimationStyles, reflector, registerModuleFactory, renderStyles, view_utils} from './private_import_core'; import {AnimationGroupPlayer, AnimationKeyframe, AnimationSequencePlayer, AnimationStyles, AnimationTransition, AppView, ChangeDetectorStatus, CodegenComponentFactoryResolver, ComponentRef_, DebugAppView, DebugContext, NgModuleInjector, NoOpAnimationPlayer, StaticNodeDebugInfo, TemplateRef_, UNINITIALIZED, ValueUnwrapper, ViewContainer, ViewType, balanceAnimationKeyframes, clearStyles, collectAndResolveStyles, devModeEqual, prepareFinalAnimationStyles, reflector, registerModuleFactory, renderStyles, view_utils} from './private_import_core';
var APP_VIEW_MODULE_URL = assetUrl('core', 'linker/view'); const APP_VIEW_MODULE_URL = assetUrl('core', 'linker/view');
var VIEW_UTILS_MODULE_URL = assetUrl('core', 'linker/view_utils'); const VIEW_UTILS_MODULE_URL = assetUrl('core', 'linker/view_utils');
var CD_MODULE_URL = assetUrl('core', 'change_detection/change_detection'); const CD_MODULE_URL = assetUrl('core', 'change_detection/change_detection');
var ANIMATION_STYLE_UTIL_ASSET_URL = assetUrl('core', 'animation/animation_style_util'); const ANIMATION_STYLE_UTIL_ASSET_URL = assetUrl('core', 'animation/animation_style_util');
export interface IdentifierSpec { export interface IdentifierSpec {
name: string; name: string;

View File

@ -603,9 +603,9 @@ export class CompileMetadataResolver {
private _getDependenciesMetadata(typeOrFunc: Type<any>|Function, dependencies: any[]): private _getDependenciesMetadata(typeOrFunc: Type<any>|Function, dependencies: any[]):
cpl.CompileDiDependencyMetadata[] { cpl.CompileDiDependencyMetadata[] {
let hasUnknownDeps = false; let hasUnknownDeps = false;
let params = dependencies || this._reflector.parameters(typeOrFunc) || []; const params = dependencies || this._reflector.parameters(typeOrFunc) || [];
let dependenciesMetadata: cpl.CompileDiDependencyMetadata[] = params.map((param) => { const dependenciesMetadata: cpl.CompileDiDependencyMetadata[] = params.map((param) => {
let isAttribute = false; let isAttribute = false;
let isHost = false; let isHost = false;
let isSelf = false; let isSelf = false;
@ -651,7 +651,7 @@ export class CompileMetadataResolver {
}); });
if (hasUnknownDeps) { if (hasUnknownDeps) {
let depsTokens = const depsTokens =
dependenciesMetadata.map((dep) => dep ? stringify(dep.token) : '?').join(', '); dependenciesMetadata.map((dep) => dep ? stringify(dep.token) : '?').join(', ');
throw new Error( throw new Error(
`Can't resolve all parameters for ${stringify(typeOrFunc)}: (${depsTokens}).`); `Can't resolve all parameters for ${stringify(typeOrFunc)}: (${depsTokens}).`);
@ -690,7 +690,7 @@ export class CompileMetadataResolver {
if (Array.isArray(provider)) { if (Array.isArray(provider)) {
compileProvider = this._getProvidersMetadata(provider, targetEntryComponents, debugInfo); compileProvider = this._getProvidersMetadata(provider, targetEntryComponents, debugInfo);
} else if (provider instanceof cpl.ProviderMeta) { } else if (provider instanceof cpl.ProviderMeta) {
let tokenMeta = this._getTokenMetadata(provider.token); const tokenMeta = this._getTokenMetadata(provider.token);
if (tokenMeta.reference === if (tokenMeta.reference ===
resolveIdentifierToken(Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS).reference) { resolveIdentifierToken(Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS).reference) {
targetEntryComponents.push(...this._getEntryComponentsFromProvider(provider)); targetEntryComponents.push(...this._getEntryComponentsFromProvider(provider));
@ -792,7 +792,7 @@ export class CompileMetadataResolver {
private _getQueryMetadata(q: Query, propertyName: string, typeOrFunc: Type<any>|Function): private _getQueryMetadata(q: Query, propertyName: string, typeOrFunc: Type<any>|Function):
cpl.CompileQueryMetadata { cpl.CompileQueryMetadata {
var selectors: cpl.CompileTokenMetadata[]; let selectors: cpl.CompileTokenMetadata[];
if (typeof q.selector === 'string') { if (typeof q.selector === 'string') {
selectors = selectors =
this._queryVarBindings(q.selector).map(varName => this._getTokenMetadata(varName)); this._queryVarBindings(q.selector).map(varName => this._getTokenMetadata(varName));

View File

@ -67,9 +67,9 @@ export interface Visitor {
} }
export function visitAll(visitor: Visitor, nodes: Node[], context: any = null): any[] { export function visitAll(visitor: Visitor, nodes: Node[], context: any = null): any[] {
let result: any[] = []; const result: any[] = [];
let visit = visitor.visit ? const visit = visitor.visit ?
(ast: Node) => visitor.visit(ast, context) || ast.visit(visitor, context) : (ast: Node) => visitor.visit(ast, context) || ast.visit(visitor, context) :
(ast: Node) => ast.visit(visitor, context); (ast: Node) => ast.visit(visitor, context);
nodes.forEach(ast => { nodes.forEach(ast => {

View File

@ -102,7 +102,7 @@ function _expandPluralForm(ast: html.Expansion, errors: ParseError[]): html.Elem
} }
function _expandDefaultForm(ast: html.Expansion, errors: ParseError[]): html.Element { function _expandDefaultForm(ast: html.Expansion, errors: ParseError[]): html.Element {
let children = ast.cases.map(c => { const children = ast.cases.map(c => {
const expansionResult = expandNodes(c.expression); const expansionResult = expandNodes(c.expression);
errors.push(...expansionResult.errors); errors.push(...expansionResult.errors);

View File

@ -321,23 +321,23 @@ class _Tokenizer {
const start = this._getLocation(); const start = this._getLocation();
this._advance(); this._advance();
if (this._attemptCharCode(chars.$HASH)) { if (this._attemptCharCode(chars.$HASH)) {
let isHex = this._attemptCharCode(chars.$x) || this._attemptCharCode(chars.$X); const isHex = this._attemptCharCode(chars.$x) || this._attemptCharCode(chars.$X);
let numberStart = this._getLocation().offset; const numberStart = this._getLocation().offset;
this._attemptCharCodeUntilFn(isDigitEntityEnd); this._attemptCharCodeUntilFn(isDigitEntityEnd);
if (this._peek != chars.$SEMICOLON) { if (this._peek != chars.$SEMICOLON) {
throw this._createError(_unexpectedCharacterErrorMsg(this._peek), this._getSpan()); throw this._createError(_unexpectedCharacterErrorMsg(this._peek), this._getSpan());
} }
this._advance(); this._advance();
let strNum = this._input.substring(numberStart, this._index - 1); const strNum = this._input.substring(numberStart, this._index - 1);
try { try {
let charCode = parseInt(strNum, isHex ? 16 : 10); const charCode = parseInt(strNum, isHex ? 16 : 10);
return String.fromCharCode(charCode); return String.fromCharCode(charCode);
} catch (e) { } catch (e) {
let entity = this._input.substring(start.offset + 1, this._index - 1); const entity = this._input.substring(start.offset + 1, this._index - 1);
throw this._createError(_unknownEntityErrorMsg(entity), this._getSpan(start)); throw this._createError(_unknownEntityErrorMsg(entity), this._getSpan(start));
} }
} else { } else {
let startPosition = this._savePosition(); const startPosition = this._savePosition();
this._attemptCharCodeUntilFn(isNamedEntityEnd); this._attemptCharCodeUntilFn(isNamedEntityEnd);
if (this._peek != chars.$SEMICOLON) { if (this._peek != chars.$SEMICOLON) {
this._restorePosition(startPosition); this._restorePosition(startPosition);
@ -420,7 +420,7 @@ class _Tokenizer {
} }
private _consumeTagOpen(start: ParseLocation) { private _consumeTagOpen(start: ParseLocation) {
let savedPos = this._savePosition(); const savedPos = this._savePosition();
let tagName: string; let tagName: string;
let lowercaseTagName: string; let lowercaseTagName: string;
try { try {
@ -490,18 +490,18 @@ class _Tokenizer {
private _consumeAttributeValue() { private _consumeAttributeValue() {
this._beginToken(TokenType.ATTR_VALUE); this._beginToken(TokenType.ATTR_VALUE);
var value: string; let value: string;
if (this._peek === chars.$SQ || this._peek === chars.$DQ) { if (this._peek === chars.$SQ || this._peek === chars.$DQ) {
var quoteChar = this._peek; const quoteChar = this._peek;
this._advance(); this._advance();
var parts: string[] = []; const parts: string[] = [];
while (this._peek !== quoteChar) { while (this._peek !== quoteChar) {
parts.push(this._readChar(true)); parts.push(this._readChar(true));
} }
value = parts.join(''); value = parts.join('');
this._advance(); this._advance();
} else { } else {
var valueStart = this._index; const valueStart = this._index;
this._requireCharCodeUntilFn(isNameEnd, 1); this._requireCharCodeUntilFn(isNameEnd, 1);
value = this._input.substring(valueStart, this._index); value = this._input.substring(valueStart, this._index);
} }
@ -519,7 +519,7 @@ class _Tokenizer {
private _consumeTagClose(start: ParseLocation) { private _consumeTagClose(start: ParseLocation) {
this._beginToken(TokenType.TAG_CLOSE, start); this._beginToken(TokenType.TAG_CLOSE, start);
this._attemptCharCodeUntilFn(isNotWhitespace); this._attemptCharCodeUntilFn(isNotWhitespace);
let prefixAndName = this._consumePrefixAndName(); const prefixAndName = this._consumePrefixAndName();
this._attemptCharCodeUntilFn(isNotWhitespace); this._attemptCharCodeUntilFn(isNotWhitespace);
this._requireCharCode(chars.$GT); this._requireCharCode(chars.$GT);
this._endToken(prefixAndName); this._endToken(prefixAndName);
@ -539,7 +539,7 @@ class _Tokenizer {
this._attemptCharCodeUntilFn(isNotWhitespace); this._attemptCharCodeUntilFn(isNotWhitespace);
this._beginToken(TokenType.RAW_TEXT, this._getLocation()); this._beginToken(TokenType.RAW_TEXT, this._getLocation());
let type = this._readUntil(chars.$COMMA); const type = this._readUntil(chars.$COMMA);
this._endToken([type], this._getLocation()); this._endToken([type], this._getLocation());
this._requireCharCode(chars.$COMMA); this._requireCharCode(chars.$COMMA);
this._attemptCharCodeUntilFn(isNotWhitespace); this._attemptCharCodeUntilFn(isNotWhitespace);
@ -623,7 +623,7 @@ class _Tokenizer {
} }
private _readUntil(char: number): string { private _readUntil(char: number): string {
let start = this._index; const start = this._index;
this._attemptUntilChar(char); this._attemptUntilChar(char);
return this._input.substring(start, this._index); return this._input.substring(start, this._index);
} }
@ -633,7 +633,7 @@ class _Tokenizer {
this._index = position[1]; this._index = position[1];
this._column = position[2]; this._column = position[2];
this._line = position[3]; this._line = position[3];
let nbTokens = position[4]; const nbTokens = position[4];
if (nbTokens < this.tokens.length) { if (nbTokens < this.tokens.length) {
// remove any extra tokens // remove any extra tokens
this.tokens = this.tokens.slice(0, nbTokens); this.tokens = this.tokens.slice(0, nbTokens);
@ -696,10 +696,10 @@ function toUpperCaseCharCode(code: number): number {
} }
function mergeTextTokens(srcTokens: Token[]): Token[] { function mergeTextTokens(srcTokens: Token[]): Token[] {
let dstTokens: Token[] = []; const dstTokens: Token[] = [];
let lastDstToken: Token; let lastDstToken: Token;
for (let i = 0; i < srcTokens.length; i++) { for (let i = 0; i < srcTokens.length; i++) {
let token = srcTokens[i]; const token = srcTokens[i];
if (lastDstToken && lastDstToken.type == TokenType.TEXT && token.type == TokenType.TEXT) { if (lastDstToken && lastDstToken.type == TokenType.TEXT && token.type == TokenType.TEXT) {
lastDstToken.parts[0] += token.parts[0]; lastDstToken.parts[0] += token.parts[0];
lastDstToken.sourceSpan.end = token.sourceSpan.end; lastDstToken.sourceSpan.end = token.sourceSpan.end;

View File

@ -121,7 +121,7 @@ class _TreeBuilder {
// read = // read =
while (this._peek.type === lex.TokenType.EXPANSION_CASE_VALUE) { while (this._peek.type === lex.TokenType.EXPANSION_CASE_VALUE) {
let expCase = this._parseExpansionCase(); const expCase = this._parseExpansionCase();
if (!expCase) return; // error if (!expCase) return; // error
cases.push(expCase); cases.push(expCase);
} }

View File

@ -35,32 +35,32 @@ export class NgModuleCompileResult {
export class NgModuleCompiler { export class NgModuleCompiler {
compile(ngModuleMeta: CompileNgModuleMetadata, extraProviders: CompileProviderMetadata[]): compile(ngModuleMeta: CompileNgModuleMetadata, extraProviders: CompileProviderMetadata[]):
NgModuleCompileResult { NgModuleCompileResult {
var sourceFileName = isPresent(ngModuleMeta.type.moduleUrl) ? const sourceFileName = isPresent(ngModuleMeta.type.moduleUrl) ?
`in NgModule ${ngModuleMeta.type.name} in ${ngModuleMeta.type.moduleUrl}` : `in NgModule ${ngModuleMeta.type.name} in ${ngModuleMeta.type.moduleUrl}` :
`in NgModule ${ngModuleMeta.type.name}`; `in NgModule ${ngModuleMeta.type.name}`;
var sourceFile = new ParseSourceFile('', sourceFileName); const sourceFile = new ParseSourceFile('', sourceFileName);
var sourceSpan = new ParseSourceSpan( const sourceSpan = new ParseSourceSpan(
new ParseLocation(sourceFile, null, null, null), new ParseLocation(sourceFile, null, null, null),
new ParseLocation(sourceFile, null, null, null)); new ParseLocation(sourceFile, null, null, null));
var deps: ComponentFactoryDependency[] = []; const deps: ComponentFactoryDependency[] = [];
var bootstrapComponentFactories: CompileIdentifierMetadata[] = []; const bootstrapComponentFactories: CompileIdentifierMetadata[] = [];
var entryComponentFactories = const entryComponentFactories =
ngModuleMeta.transitiveModule.entryComponents.map((entryComponent) => { ngModuleMeta.transitiveModule.entryComponents.map((entryComponent) => {
var id = new CompileIdentifierMetadata({name: entryComponent.name}); const id = new CompileIdentifierMetadata({name: entryComponent.name});
if (ngModuleMeta.bootstrapComponents.indexOf(entryComponent) > -1) { if (ngModuleMeta.bootstrapComponents.indexOf(entryComponent) > -1) {
bootstrapComponentFactories.push(id); bootstrapComponentFactories.push(id);
} }
deps.push(new ComponentFactoryDependency(entryComponent, id)); deps.push(new ComponentFactoryDependency(entryComponent, id));
return id; return id;
}); });
var builder = new _InjectorBuilder( const builder = new _InjectorBuilder(
ngModuleMeta, entryComponentFactories, bootstrapComponentFactories, sourceSpan); ngModuleMeta, entryComponentFactories, bootstrapComponentFactories, sourceSpan);
var providerParser = new NgModuleProviderAnalyzer(ngModuleMeta, extraProviders, sourceSpan); const providerParser = new NgModuleProviderAnalyzer(ngModuleMeta, extraProviders, sourceSpan);
providerParser.parse().forEach((provider) => builder.addProvider(provider)); providerParser.parse().forEach((provider) => builder.addProvider(provider));
var injectorClass = builder.build(); const injectorClass = builder.build();
var ngModuleFactoryVar = `${ngModuleMeta.type.name}NgFactory`; const ngModuleFactoryVar = `${ngModuleMeta.type.name}NgFactory`;
var ngModuleFactoryStmt = const ngModuleFactoryStmt =
o.variable(ngModuleFactoryVar) o.variable(ngModuleFactoryVar)
.set(o.importExpr(resolveIdentifier(Identifiers.NgModuleFactory)) .set(o.importExpr(resolveIdentifier(Identifiers.NgModuleFactory))
.instantiate( .instantiate(
@ -70,9 +70,9 @@ export class NgModuleCompiler {
[o.importType(ngModuleMeta.type)], [o.TypeModifier.Const]))) [o.importType(ngModuleMeta.type)], [o.TypeModifier.Const])))
.toDeclStmt(null, [o.StmtModifier.Final]); .toDeclStmt(null, [o.StmtModifier.Final]);
let stmts: o.Statement[] = [injectorClass, ngModuleFactoryStmt]; const stmts: o.Statement[] = [injectorClass, ngModuleFactoryStmt];
if (ngModuleMeta.id) { if (ngModuleMeta.id) {
let registerFactoryStmt = const registerFactoryStmt =
o.importExpr(resolveIdentifier(Identifiers.RegisterModuleFactoryFn)) o.importExpr(resolveIdentifier(Identifiers.RegisterModuleFactoryFn))
.callFn([o.literal(ngModuleMeta.id), o.variable(ngModuleFactoryVar)]) .callFn([o.literal(ngModuleMeta.id), o.variable(ngModuleFactoryVar)])
.toStmt(); .toStmt();
@ -100,10 +100,10 @@ class _InjectorBuilder implements ClassBuilder {
private _sourceSpan: ParseSourceSpan) {} private _sourceSpan: ParseSourceSpan) {}
addProvider(resolvedProvider: ProviderAst) { addProvider(resolvedProvider: ProviderAst) {
var providerValueExpressions = const providerValueExpressions =
resolvedProvider.providers.map((provider) => this._getProviderValue(provider)); resolvedProvider.providers.map((provider) => this._getProviderValue(provider));
var propName = `_${resolvedProvider.token.name}_${this._instances.size}`; const propName = `_${resolvedProvider.token.name}_${this._instances.size}`;
var instance = this._createProviderProperty( const instance = this._createProviderProperty(
propName, resolvedProvider, providerValueExpressions, resolvedProvider.multiProvider, propName, resolvedProvider, providerValueExpressions, resolvedProvider.multiProvider,
resolvedProvider.eager); resolvedProvider.eager);
if (resolvedProvider.lifecycleHooks.indexOf(LifecycleHooks.OnDestroy) !== -1) { if (resolvedProvider.lifecycleHooks.indexOf(LifecycleHooks.OnDestroy) !== -1) {
@ -114,18 +114,17 @@ class _InjectorBuilder implements ClassBuilder {
} }
build(): o.ClassStmt { build(): o.ClassStmt {
let getMethodStmts: o.Statement[] = this._tokens.map((token) => { const getMethodStmts: o.Statement[] = this._tokens.map((token) => {
var providerExpr = this._instances.get(token.reference); const providerExpr = this._instances.get(token.reference);
return new o.IfStmt( return new o.IfStmt(
InjectMethodVars.token.identical(createDiTokenExpression(token)), InjectMethodVars.token.identical(createDiTokenExpression(token)),
[new o.ReturnStatement(providerExpr)]); [new o.ReturnStatement(providerExpr)]);
}); });
var methods = [ const methods = [
new o.ClassMethod( new o.ClassMethod(
'createInternal', [], this._createStmts.concat( 'createInternal', [], this._createStmts.concat(new o.ReturnStatement(
new o.ReturnStatement(this._instances.get(this._ngModuleMeta.type.reference)) this._instances.get(this._ngModuleMeta.type.reference))),
), o.importType(this._ngModuleMeta.type) o.importType(this._ngModuleMeta.type)),
),
new o.ClassMethod( new o.ClassMethod(
'getInternal', 'getInternal',
[ [
@ -134,19 +133,17 @@ class _InjectorBuilder implements ClassBuilder {
], ],
getMethodStmts.concat([new o.ReturnStatement(InjectMethodVars.notFoundResult)]), getMethodStmts.concat([new o.ReturnStatement(InjectMethodVars.notFoundResult)]),
o.DYNAMIC_TYPE), o.DYNAMIC_TYPE),
new o.ClassMethod( new o.ClassMethod('destroyInternal', [], this._destroyStmts),
'destroyInternal', [], this._destroyStmts
),
]; ];
var parentArgs = [ const parentArgs = [
o.variable(InjectorProps.parent.name), o.variable(InjectorProps.parent.name),
o.literalArr( o.literalArr(
this._entryComponentFactories.map((componentFactory) => o.importExpr(componentFactory))), this._entryComponentFactories.map((componentFactory) => o.importExpr(componentFactory))),
o.literalArr(this._bootstrapComponentFactories.map( o.literalArr(this._bootstrapComponentFactories.map(
(componentFactory) => o.importExpr(componentFactory))) (componentFactory) => o.importExpr(componentFactory)))
]; ];
var injClassName = `${this._ngModuleMeta.type.name}Injector`; const injClassName = `${this._ngModuleMeta.type.name}Injector`;
return createClassStmt({ return createClassStmt({
name: injClassName, name: injClassName,
ctorParams: [new o.FnParam( ctorParams: [new o.FnParam(
@ -159,16 +156,16 @@ class _InjectorBuilder implements ClassBuilder {
} }
private _getProviderValue(provider: CompileProviderMetadata): o.Expression { private _getProviderValue(provider: CompileProviderMetadata): o.Expression {
var result: o.Expression; let result: o.Expression;
if (isPresent(provider.useExisting)) { if (isPresent(provider.useExisting)) {
result = this._getDependency(new CompileDiDependencyMetadata({token: provider.useExisting})); result = this._getDependency(new CompileDiDependencyMetadata({token: provider.useExisting}));
} else if (isPresent(provider.useFactory)) { } else if (isPresent(provider.useFactory)) {
var deps = provider.deps || provider.useFactory.diDeps; const deps = provider.deps || provider.useFactory.diDeps;
var depsExpr = deps.map((dep) => this._getDependency(dep)); const depsExpr = deps.map((dep) => this._getDependency(dep));
result = o.importExpr(provider.useFactory).callFn(depsExpr); result = o.importExpr(provider.useFactory).callFn(depsExpr);
} else if (isPresent(provider.useClass)) { } else if (isPresent(provider.useClass)) {
var deps = provider.deps || provider.useClass.diDeps; const deps = provider.deps || provider.useClass.diDeps;
var depsExpr = deps.map((dep) => this._getDependency(dep)); const depsExpr = deps.map((dep) => this._getDependency(dep));
result = result =
o.importExpr(provider.useClass).instantiate(depsExpr, o.importType(provider.useClass)); o.importExpr(provider.useClass).instantiate(depsExpr, o.importType(provider.useClass));
} else { } else {
@ -181,8 +178,8 @@ class _InjectorBuilder implements ClassBuilder {
private _createProviderProperty( private _createProviderProperty(
propName: string, provider: ProviderAst, providerValueExpressions: o.Expression[], propName: string, provider: ProviderAst, providerValueExpressions: o.Expression[],
isMulti: boolean, isEager: boolean): o.Expression { isMulti: boolean, isEager: boolean): o.Expression {
var resolvedProviderValueExpr: o.Expression; let resolvedProviderValueExpr: o.Expression;
var type: o.Type; let type: o.Type;
if (isMulti) { if (isMulti) {
resolvedProviderValueExpr = o.literalArr(providerValueExpressions); resolvedProviderValueExpr = o.literalArr(providerValueExpressions);
type = new o.ArrayType(o.DYNAMIC_TYPE); type = new o.ArrayType(o.DYNAMIC_TYPE);
@ -197,10 +194,10 @@ class _InjectorBuilder implements ClassBuilder {
this.fields.push(new o.ClassField(propName, type)); this.fields.push(new o.ClassField(propName, type));
this._createStmts.push(o.THIS_EXPR.prop(propName).set(resolvedProviderValueExpr).toStmt()); this._createStmts.push(o.THIS_EXPR.prop(propName).set(resolvedProviderValueExpr).toStmt());
} else { } else {
var internalField = `_${propName}`; const internalField = `_${propName}`;
this.fields.push(new o.ClassField(internalField, type)); this.fields.push(new o.ClassField(internalField, type));
// Note: Equals is important for JS so that it also checks the undefined case! // Note: Equals is important for JS so that it also checks the undefined case!
var getterStmts = [ const getterStmts = [
new o.IfStmt( new o.IfStmt(
o.THIS_EXPR.prop(internalField).isBlank(), o.THIS_EXPR.prop(internalField).isBlank(),
[o.THIS_EXPR.prop(internalField).set(resolvedProviderValueExpr).toStmt()]), [o.THIS_EXPR.prop(internalField).set(resolvedProviderValueExpr).toStmt()]),
@ -212,7 +209,7 @@ class _InjectorBuilder implements ClassBuilder {
} }
private _getDependency(dep: CompileDiDependencyMetadata): o.Expression { private _getDependency(dep: CompileDiDependencyMetadata): o.Expression {
var result: o.Expression = null; let result: o.Expression = null;
if (dep.isValue) { if (dep.isValue) {
result = o.literal(dep.value); result = o.literal(dep.value);
} }
@ -228,7 +225,7 @@ class _InjectorBuilder implements ClassBuilder {
} }
} }
if (!result) { if (!result) {
var args = [createDiTokenExpression(dep.token)]; const args = [createDiTokenExpression(dep.token)];
if (dep.isOptional) { if (dep.isOptional) {
args.push(o.NULL_EXPR); args.push(o.NULL_EXPR);
} }

View File

@ -78,7 +78,7 @@ export class EmitterVisitorContext {
} }
toSource(): any { toSource(): any {
var lines = this._lines; let lines = this._lines;
if (lines[lines.length - 1].parts.length === 0) { if (lines[lines.length - 1].parts.length === 0) {
lines = lines.slice(0, lines.length - 1); lines = lines.slice(0, lines.length - 1);
} }
@ -118,7 +118,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
ctx.print(`if (`); ctx.print(`if (`);
stmt.condition.visitExpression(this, ctx); stmt.condition.visitExpression(this, ctx);
ctx.print(`) {`); ctx.print(`) {`);
var hasElseCase = isPresent(stmt.falseCase) && stmt.falseCase.length > 0; const hasElseCase = isPresent(stmt.falseCase) && stmt.falseCase.length > 0;
if (stmt.trueCase.length <= 1 && !hasElseCase) { if (stmt.trueCase.length <= 1 && !hasElseCase) {
ctx.print(` `); ctx.print(` `);
this.visitAllStatements(stmt.trueCase, ctx); this.visitAllStatements(stmt.trueCase, ctx);
@ -149,13 +149,13 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
return null; return null;
} }
visitCommentStmt(stmt: o.CommentStmt, ctx: EmitterVisitorContext): any { visitCommentStmt(stmt: o.CommentStmt, ctx: EmitterVisitorContext): any {
var lines = stmt.comment.split('\n'); const lines = stmt.comment.split('\n');
lines.forEach((line) => { ctx.println(`// ${line}`); }); lines.forEach((line) => { ctx.println(`// ${line}`); });
return null; return null;
} }
abstract visitDeclareVarStmt(stmt: o.DeclareVarStmt, ctx: EmitterVisitorContext): any; abstract visitDeclareVarStmt(stmt: o.DeclareVarStmt, ctx: EmitterVisitorContext): any;
visitWriteVarExpr(expr: o.WriteVarExpr, ctx: EmitterVisitorContext): any { visitWriteVarExpr(expr: o.WriteVarExpr, ctx: EmitterVisitorContext): any {
var lineWasEmpty = ctx.lineIsEmpty(); const lineWasEmpty = ctx.lineIsEmpty();
if (!lineWasEmpty) { if (!lineWasEmpty) {
ctx.print('('); ctx.print('(');
} }
@ -167,7 +167,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
return null; return null;
} }
visitWriteKeyExpr(expr: o.WriteKeyExpr, ctx: EmitterVisitorContext): any { visitWriteKeyExpr(expr: o.WriteKeyExpr, ctx: EmitterVisitorContext): any {
var lineWasEmpty = ctx.lineIsEmpty(); const lineWasEmpty = ctx.lineIsEmpty();
if (!lineWasEmpty) { if (!lineWasEmpty) {
ctx.print('('); ctx.print('(');
} }
@ -182,7 +182,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
return null; return null;
} }
visitWritePropExpr(expr: o.WritePropExpr, ctx: EmitterVisitorContext): any { visitWritePropExpr(expr: o.WritePropExpr, ctx: EmitterVisitorContext): any {
var lineWasEmpty = ctx.lineIsEmpty(); const lineWasEmpty = ctx.lineIsEmpty();
if (!lineWasEmpty) { if (!lineWasEmpty) {
ctx.print('('); ctx.print('(');
} }
@ -196,7 +196,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
} }
visitInvokeMethodExpr(expr: o.InvokeMethodExpr, ctx: EmitterVisitorContext): any { visitInvokeMethodExpr(expr: o.InvokeMethodExpr, ctx: EmitterVisitorContext): any {
expr.receiver.visitExpression(this, ctx); expr.receiver.visitExpression(this, ctx);
var name = expr.name; let name = expr.name;
if (isPresent(expr.builtin)) { if (isPresent(expr.builtin)) {
name = this.getBuiltinMethodName(expr.builtin); name = this.getBuiltinMethodName(expr.builtin);
if (isBlank(name)) { if (isBlank(name)) {
@ -220,7 +220,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
return null; return null;
} }
visitReadVarExpr(ast: o.ReadVarExpr, ctx: EmitterVisitorContext): any { visitReadVarExpr(ast: o.ReadVarExpr, ctx: EmitterVisitorContext): any {
var varName = ast.name; let varName = ast.name;
if (isPresent(ast.builtin)) { if (isPresent(ast.builtin)) {
switch (ast.builtin) { switch (ast.builtin) {
case o.BuiltinVar.Super: case o.BuiltinVar.Super:
@ -282,7 +282,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
abstract visitDeclareFunctionStmt(stmt: o.DeclareFunctionStmt, context: any): any; abstract visitDeclareFunctionStmt(stmt: o.DeclareFunctionStmt, context: any): any;
visitBinaryOperatorExpr(ast: o.BinaryOperatorExpr, ctx: EmitterVisitorContext): any { visitBinaryOperatorExpr(ast: o.BinaryOperatorExpr, ctx: EmitterVisitorContext): any {
var opStr: string; let opStr: string;
switch (ast.operator) { switch (ast.operator) {
case o.BinaryOperator.Equals: case o.BinaryOperator.Equals:
opStr = '=='; opStr = '==';
@ -354,7 +354,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
return null; return null;
} }
visitLiteralArrayExpr(ast: o.LiteralArrayExpr, ctx: EmitterVisitorContext): any { visitLiteralArrayExpr(ast: o.LiteralArrayExpr, ctx: EmitterVisitorContext): any {
var useNewLine = ast.entries.length > 1; const useNewLine = ast.entries.length > 1;
ctx.print(`[`, useNewLine); ctx.print(`[`, useNewLine);
ctx.incIndent(); ctx.incIndent();
this.visitAllExpressions(ast.entries, ctx, ',', useNewLine); this.visitAllExpressions(ast.entries, ctx, ',', useNewLine);
@ -363,7 +363,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
return null; return null;
} }
visitLiteralMapExpr(ast: o.LiteralMapExpr, ctx: EmitterVisitorContext): any { visitLiteralMapExpr(ast: o.LiteralMapExpr, ctx: EmitterVisitorContext): any {
var useNewLine = ast.entries.length > 1; const useNewLine = ast.entries.length > 1;
ctx.print(`{`, useNewLine); ctx.print(`{`, useNewLine);
ctx.incIndent(); ctx.incIndent();
this.visitAllObjects(entry => { this.visitAllObjects(entry => {
@ -385,7 +385,7 @@ export abstract class AbstractEmitterVisitor implements o.StatementVisitor, o.Ex
visitAllObjects<T>( visitAllObjects<T>(
handler: (t: T) => void, expressions: T[], ctx: EmitterVisitorContext, separator: string, handler: (t: T) => void, expressions: T[], ctx: EmitterVisitorContext, separator: string,
newLine: boolean = false): void { newLine: boolean = false): void {
for (var i = 0; i < expressions.length; i++) { for (let i = 0; i < expressions.length; i++) {
if (i > 0) { if (i > 0) {
ctx.print(separator, newLine); ctx.print(separator, newLine);
} }
@ -406,7 +406,7 @@ export function escapeIdentifier(
if (isBlank(input)) { if (isBlank(input)) {
return null; return null;
} }
var body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, (...match: string[]) => { const body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, (...match: string[]) => {
if (match[0] == '$') { if (match[0] == '$') {
return escapeDollar ? '\\$' : '$'; return escapeDollar ? '\\$' : '$';
} else if (match[0] == '\n') { } else if (match[0] == '\n') {
@ -417,13 +417,13 @@ export function escapeIdentifier(
return `\\${match[0]}`; return `\\${match[0]}`;
} }
}); });
let requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body); const requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body);
return requiresQuotes ? `'${body}'` : body; return requiresQuotes ? `'${body}'` : body;
} }
function _createIndent(count: number): string { function _createIndent(count: number): string {
var res = ''; let res = '';
for (var i = 0; i < count; i++) { for (let i = 0; i < count; i++) {
res += ' '; res += ' ';
} }
return res; return res;

View File

@ -92,7 +92,7 @@ export abstract class AbstractJsEmitterVisitor extends AbstractEmitterVisitor {
return null; return null;
} }
visitInvokeFunctionExpr(expr: o.InvokeFunctionExpr, ctx: EmitterVisitorContext): string { visitInvokeFunctionExpr(expr: o.InvokeFunctionExpr, ctx: EmitterVisitorContext): string {
var fnExpr = expr.fn; const fnExpr = expr.fn;
if (fnExpr instanceof o.ReadVarExpr && fnExpr.builtin === o.BuiltinVar.Super) { if (fnExpr instanceof o.ReadVarExpr && fnExpr.builtin === o.BuiltinVar.Super) {
ctx.currentClass.parent.visitExpression(this, ctx); ctx.currentClass.parent.visitExpression(this, ctx);
ctx.print(`.call(this`); ctx.print(`.call(this`);
@ -133,7 +133,7 @@ export abstract class AbstractJsEmitterVisitor extends AbstractEmitterVisitor {
ctx.decIndent(); ctx.decIndent();
ctx.println(`} catch (${CATCH_ERROR_VAR.name}) {`); ctx.println(`} catch (${CATCH_ERROR_VAR.name}) {`);
ctx.incIndent(); ctx.incIndent();
var catchStmts = const catchStmts =
[<o.Statement>CATCH_STACK_VAR.set(CATCH_ERROR_VAR.prop('stack')).toDeclStmt(null, [ [<o.Statement>CATCH_STACK_VAR.set(CATCH_ERROR_VAR.prop('stack')).toDeclStmt(null, [
o.StmtModifier.Final o.StmtModifier.Final
])].concat(stmt.catchStmts); ])].concat(stmt.catchStmts);
@ -148,7 +148,7 @@ export abstract class AbstractJsEmitterVisitor extends AbstractEmitterVisitor {
} }
getBuiltinMethodName(method: o.BuiltinMethod): string { getBuiltinMethodName(method: o.BuiltinMethod): string {
var name: string; let name: string;
switch (method) { switch (method) {
case o.BuiltinMethod.ConcatArray: case o.BuiltinMethod.ConcatArray:
name = 'concat'; name = 'concat';

View File

@ -17,10 +17,10 @@ import {ImportGenerator} from './path_util';
export class JavaScriptEmitter implements OutputEmitter { export class JavaScriptEmitter implements OutputEmitter {
constructor(private _importGenerator: ImportGenerator) {} constructor(private _importGenerator: ImportGenerator) {}
emitStatements(moduleUrl: string, stmts: o.Statement[], exportedVars: string[]): string { emitStatements(moduleUrl: string, stmts: o.Statement[], exportedVars: string[]): string {
var converter = new JsEmitterVisitor(moduleUrl); const converter = new JsEmitterVisitor(moduleUrl);
var ctx = EmitterVisitorContext.createRoot(exportedVars); const ctx = EmitterVisitorContext.createRoot(exportedVars);
converter.visitAllStatements(stmts, ctx); converter.visitAllStatements(stmts, ctx);
var srcParts: string[] = []; const srcParts: string[] = [];
converter.importsWithPrefixes.forEach((prefix, importedModuleUrl) => { converter.importsWithPrefixes.forEach((prefix, importedModuleUrl) => {
// Note: can't write the real word for import as it screws up system.js auto detection... // Note: can't write the real word for import as it screws up system.js auto detection...
srcParts.push( srcParts.push(
@ -42,7 +42,7 @@ class JsEmitterVisitor extends AbstractJsEmitterVisitor {
throw new Error(`Internal error: unknown identifier ${ast.value}`); throw new Error(`Internal error: unknown identifier ${ast.value}`);
} }
if (isPresent(ast.value.moduleUrl) && ast.value.moduleUrl != this._moduleUrl) { if (isPresent(ast.value.moduleUrl) && ast.value.moduleUrl != this._moduleUrl) {
var prefix = this.importsWithPrefixes.get(ast.value.moduleUrl); let prefix = this.importsWithPrefixes.get(ast.value.moduleUrl);
if (isBlank(prefix)) { if (isBlank(prefix)) {
prefix = `import${this.importsWithPrefixes.size}`; prefix = `import${this.importsWithPrefixes.size}`;
this.importsWithPrefixes.set(ast.value.moduleUrl, prefix); this.importsWithPrefixes.set(ast.value.moduleUrl, prefix);

View File

@ -626,7 +626,7 @@ export class ExpressionTransformer implements StatementVisitor, ExpressionVisito
expr.value.visitExpression(this, context)); expr.value.visitExpression(this, context));
} }
visitInvokeMethodExpr(ast: InvokeMethodExpr, context: any): any { visitInvokeMethodExpr(ast: InvokeMethodExpr, context: any): any {
var method = ast.builtin || ast.name; const method = ast.builtin || ast.name;
return new InvokeMethodExpr( return new InvokeMethodExpr(
ast.receiver.visitExpression(this, context), method, ast.receiver.visitExpression(this, context), method,
this.visitAllExpressions(ast.args, context), ast.type); this.visitAllExpressions(ast.args, context), ast.type);
@ -841,7 +841,7 @@ export class RecursiveExpressionVisitor implements StatementVisitor, ExpressionV
export function replaceVarInExpression( export function replaceVarInExpression(
varName: string, newValue: Expression, expression: Expression): Expression { varName: string, newValue: Expression, expression: Expression): Expression {
var transformer = new _ReplaceVariableTransformer(varName, newValue); const transformer = new _ReplaceVariableTransformer(varName, newValue);
return expression.visitExpression(transformer, null); return expression.visitExpression(transformer, null);
} }
@ -853,7 +853,7 @@ class _ReplaceVariableTransformer extends ExpressionTransformer {
} }
export function findReadVarNames(stmts: Statement[]): Set<string> { export function findReadVarNames(stmts: Statement[]): Set<string> {
var finder = new _VariableFinder(); const finder = new _VariableFinder();
finder.visitAllStatements(stmts, null); finder.visitAllStatements(stmts, null);
return finder.varNames; return finder.varNames;
} }

View File

@ -13,21 +13,21 @@ import * as o from './output_ast';
import {debugOutputAstAsTypeScript} from './ts_emitter'; import {debugOutputAstAsTypeScript} from './ts_emitter';
export function interpretStatements(statements: o.Statement[], resultVar: string): any { export function interpretStatements(statements: o.Statement[], resultVar: string): any {
var stmtsWithReturn = statements.concat([new o.ReturnStatement(o.variable(resultVar))]); const stmtsWithReturn = statements.concat([new o.ReturnStatement(o.variable(resultVar))]);
var ctx = new _ExecutionContext(null, null, null, new Map<string, any>()); const ctx = new _ExecutionContext(null, null, null, new Map<string, any>());
var visitor = new StatementInterpreter(); const visitor = new StatementInterpreter();
var result = visitor.visitAllStatements(stmtsWithReturn, ctx); const result = visitor.visitAllStatements(stmtsWithReturn, ctx);
return isPresent(result) ? result.value : null; return isPresent(result) ? result.value : null;
} }
function _executeFunctionStatements( function _executeFunctionStatements(
varNames: string[], varValues: any[], statements: o.Statement[], ctx: _ExecutionContext, varNames: string[], varValues: any[], statements: o.Statement[], ctx: _ExecutionContext,
visitor: StatementInterpreter): any { visitor: StatementInterpreter): any {
var childCtx = ctx.createChildWihtLocalVars(); const childCtx = ctx.createChildWihtLocalVars();
for (var i = 0; i < varNames.length; i++) { for (let i = 0; i < varNames.length; i++) {
childCtx.vars.set(varNames[i], varValues[i]); childCtx.vars.set(varNames[i], varValues[i]);
} }
var result = visitor.visitAllStatements(statements, childCtx); const result = visitor.visitAllStatements(statements, childCtx);
return isPresent(result) ? result.value : null; return isPresent(result) ? result.value : null;
} }
@ -47,14 +47,14 @@ class ReturnValue {
function createDynamicClass( function createDynamicClass(
_classStmt: o.ClassStmt, _ctx: _ExecutionContext, _visitor: StatementInterpreter): Function { _classStmt: o.ClassStmt, _ctx: _ExecutionContext, _visitor: StatementInterpreter): Function {
let propertyDescriptors: {[key: string]: any} = {}; const propertyDescriptors: {[key: string]: any} = {};
_classStmt.getters.forEach((getter: o.ClassGetter) => { _classStmt.getters.forEach((getter: o.ClassGetter) => {
// Note: use `function` instead of arrow function to capture `this` // Note: use `function` instead of arrow function to capture `this`
propertyDescriptors[getter.name] = { propertyDescriptors[getter.name] = {
configurable: false, configurable: false,
get: function() { get: function() {
let instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars); const instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
return _executeFunctionStatements([], [], getter.body, instanceCtx, _visitor); return _executeFunctionStatements([], [], getter.body, instanceCtx, _visitor);
} }
}; };
@ -66,21 +66,21 @@ function createDynamicClass(
writable: false, writable: false,
configurable: false, configurable: false,
value: function(...args: any[]) { value: function(...args: any[]) {
let instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars); const instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
return _executeFunctionStatements(paramNames, args, method.body, instanceCtx, _visitor); return _executeFunctionStatements(paramNames, args, method.body, instanceCtx, _visitor);
} }
}; };
}); });
var ctorParamNames = _classStmt.constructorMethod.params.map(param => param.name); const ctorParamNames = _classStmt.constructorMethod.params.map(param => param.name);
// Note: use `function` instead of arrow function to capture `this` // Note: use `function` instead of arrow function to capture `this`
var ctor = function(...args: any[]) { const ctor = function(...args: any[]) {
let instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars); const instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
_classStmt.fields.forEach((field) => { this[field.name] = undefined; }); _classStmt.fields.forEach((field) => { this[field.name] = undefined; });
_executeFunctionStatements( _executeFunctionStatements(
ctorParamNames, args, _classStmt.constructorMethod.body, instanceCtx, _visitor); ctorParamNames, args, _classStmt.constructorMethod.body, instanceCtx, _visitor);
}; };
var superClass = _classStmt.parent ? _classStmt.parent.visitExpression(_visitor, _ctx) : Object; const superClass = _classStmt.parent ? _classStmt.parent.visitExpression(_visitor, _ctx) : Object;
ctor.prototype = Object.create(superClass.prototype, propertyDescriptors); ctor.prototype = Object.create(superClass.prototype, propertyDescriptors);
return ctor; return ctor;
} }
@ -93,8 +93,8 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
return null; return null;
} }
visitWriteVarExpr(expr: o.WriteVarExpr, ctx: _ExecutionContext): any { visitWriteVarExpr(expr: o.WriteVarExpr, ctx: _ExecutionContext): any {
var value = expr.value.visitExpression(this, ctx); const value = expr.value.visitExpression(this, ctx);
var currCtx = ctx; let currCtx = ctx;
while (currCtx != null) { while (currCtx != null) {
if (currCtx.vars.has(expr.name)) { if (currCtx.vars.has(expr.name)) {
currCtx.vars.set(expr.name, value); currCtx.vars.set(expr.name, value);
@ -105,7 +105,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
throw new Error(`Not declared variable ${expr.name}`); throw new Error(`Not declared variable ${expr.name}`);
} }
visitReadVarExpr(ast: o.ReadVarExpr, ctx: _ExecutionContext): any { visitReadVarExpr(ast: o.ReadVarExpr, ctx: _ExecutionContext): any {
var varName = ast.name; let varName = ast.name;
if (isPresent(ast.builtin)) { if (isPresent(ast.builtin)) {
switch (ast.builtin) { switch (ast.builtin) {
case o.BuiltinVar.Super: case o.BuiltinVar.Super:
@ -122,7 +122,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
throw new Error(`Unknown builtin variable ${ast.builtin}`); throw new Error(`Unknown builtin variable ${ast.builtin}`);
} }
} }
var currCtx = ctx; let currCtx = ctx;
while (currCtx != null) { while (currCtx != null) {
if (currCtx.vars.has(varName)) { if (currCtx.vars.has(varName)) {
return currCtx.vars.get(varName); return currCtx.vars.get(varName);
@ -132,23 +132,23 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
throw new Error(`Not declared variable ${varName}`); throw new Error(`Not declared variable ${varName}`);
} }
visitWriteKeyExpr(expr: o.WriteKeyExpr, ctx: _ExecutionContext): any { visitWriteKeyExpr(expr: o.WriteKeyExpr, ctx: _ExecutionContext): any {
var receiver = expr.receiver.visitExpression(this, ctx); const receiver = expr.receiver.visitExpression(this, ctx);
var index = expr.index.visitExpression(this, ctx); const index = expr.index.visitExpression(this, ctx);
var value = expr.value.visitExpression(this, ctx); const value = expr.value.visitExpression(this, ctx);
receiver[index] = value; receiver[index] = value;
return value; return value;
} }
visitWritePropExpr(expr: o.WritePropExpr, ctx: _ExecutionContext): any { visitWritePropExpr(expr: o.WritePropExpr, ctx: _ExecutionContext): any {
var receiver = expr.receiver.visitExpression(this, ctx); const receiver = expr.receiver.visitExpression(this, ctx);
var value = expr.value.visitExpression(this, ctx); const value = expr.value.visitExpression(this, ctx);
receiver[expr.name] = value; receiver[expr.name] = value;
return value; return value;
} }
visitInvokeMethodExpr(expr: o.InvokeMethodExpr, ctx: _ExecutionContext): any { visitInvokeMethodExpr(expr: o.InvokeMethodExpr, ctx: _ExecutionContext): any {
var receiver = expr.receiver.visitExpression(this, ctx); const receiver = expr.receiver.visitExpression(this, ctx);
var args = this.visitAllExpressions(expr.args, ctx); const args = this.visitAllExpressions(expr.args, ctx);
var result: any; let result: any;
if (isPresent(expr.builtin)) { if (isPresent(expr.builtin)) {
switch (expr.builtin) { switch (expr.builtin) {
case o.BuiltinMethod.ConcatArray: case o.BuiltinMethod.ConcatArray:
@ -169,13 +169,13 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
return result; return result;
} }
visitInvokeFunctionExpr(stmt: o.InvokeFunctionExpr, ctx: _ExecutionContext): any { visitInvokeFunctionExpr(stmt: o.InvokeFunctionExpr, ctx: _ExecutionContext): any {
var args = this.visitAllExpressions(stmt.args, ctx); const args = this.visitAllExpressions(stmt.args, ctx);
var fnExpr = stmt.fn; const fnExpr = stmt.fn;
if (fnExpr instanceof o.ReadVarExpr && fnExpr.builtin === o.BuiltinVar.Super) { if (fnExpr instanceof o.ReadVarExpr && fnExpr.builtin === o.BuiltinVar.Super) {
ctx.instance.constructor.prototype.constructor.apply(ctx.instance, args); ctx.instance.constructor.prototype.constructor.apply(ctx.instance, args);
return null; return null;
} else { } else {
var fn = stmt.fn.visitExpression(this, ctx); const fn = stmt.fn.visitExpression(this, ctx);
return fn.apply(null, args); return fn.apply(null, args);
} }
} }
@ -183,7 +183,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
return new ReturnValue(stmt.value.visitExpression(this, ctx)); return new ReturnValue(stmt.value.visitExpression(this, ctx));
} }
visitDeclareClassStmt(stmt: o.ClassStmt, ctx: _ExecutionContext): any { visitDeclareClassStmt(stmt: o.ClassStmt, ctx: _ExecutionContext): any {
var clazz = createDynamicClass(stmt, ctx, this); const clazz = createDynamicClass(stmt, ctx, this);
ctx.vars.set(stmt.name, clazz); ctx.vars.set(stmt.name, clazz);
return null; return null;
} }
@ -191,7 +191,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
return stmt.expr.visitExpression(this, ctx); return stmt.expr.visitExpression(this, ctx);
} }
visitIfStmt(stmt: o.IfStmt, ctx: _ExecutionContext): any { visitIfStmt(stmt: o.IfStmt, ctx: _ExecutionContext): any {
var condition = stmt.condition.visitExpression(this, ctx); const condition = stmt.condition.visitExpression(this, ctx);
if (condition) { if (condition) {
return this.visitAllStatements(stmt.trueCase, ctx); return this.visitAllStatements(stmt.trueCase, ctx);
} else if (isPresent(stmt.falseCase)) { } else if (isPresent(stmt.falseCase)) {
@ -203,7 +203,7 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
try { try {
return this.visitAllStatements(stmt.bodyStmts, ctx); return this.visitAllStatements(stmt.bodyStmts, ctx);
} catch (e) { } catch (e) {
var childCtx = ctx.createChildWihtLocalVars(); const childCtx = ctx.createChildWihtLocalVars();
childCtx.vars.set(CATCH_ERROR_VAR, e); childCtx.vars.set(CATCH_ERROR_VAR, e);
childCtx.vars.set(CATCH_STACK_VAR, e.stack); childCtx.vars.set(CATCH_STACK_VAR, e.stack);
return this.visitAllStatements(stmt.catchStmts, childCtx); return this.visitAllStatements(stmt.catchStmts, childCtx);
@ -214,8 +214,8 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
} }
visitCommentStmt(stmt: o.CommentStmt, context?: any): any { return null; } visitCommentStmt(stmt: o.CommentStmt, context?: any): any { return null; }
visitInstantiateExpr(ast: o.InstantiateExpr, ctx: _ExecutionContext): any { visitInstantiateExpr(ast: o.InstantiateExpr, ctx: _ExecutionContext): any {
var args = this.visitAllExpressions(ast.args, ctx); const args = this.visitAllExpressions(ast.args, ctx);
var clazz = ast.classExpr.visitExpression(this, ctx); const clazz = ast.classExpr.visitExpression(this, ctx);
return new clazz(...args); return new clazz(...args);
} }
visitLiteralExpr(ast: o.LiteralExpr, ctx: _ExecutionContext): any { return ast.value; } visitLiteralExpr(ast: o.LiteralExpr, ctx: _ExecutionContext): any { return ast.value; }
@ -237,17 +237,17 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
return ast.value.visitExpression(this, ctx); return ast.value.visitExpression(this, ctx);
} }
visitFunctionExpr(ast: o.FunctionExpr, ctx: _ExecutionContext): any { visitFunctionExpr(ast: o.FunctionExpr, ctx: _ExecutionContext): any {
var paramNames = ast.params.map((param) => param.name); const paramNames = ast.params.map((param) => param.name);
return _declareFn(paramNames, ast.statements, ctx, this); return _declareFn(paramNames, ast.statements, ctx, this);
} }
visitDeclareFunctionStmt(stmt: o.DeclareFunctionStmt, ctx: _ExecutionContext): any { visitDeclareFunctionStmt(stmt: o.DeclareFunctionStmt, ctx: _ExecutionContext): any {
var paramNames = stmt.params.map((param) => param.name); const paramNames = stmt.params.map((param) => param.name);
ctx.vars.set(stmt.name, _declareFn(paramNames, stmt.statements, ctx, this)); ctx.vars.set(stmt.name, _declareFn(paramNames, stmt.statements, ctx, this));
return null; return null;
} }
visitBinaryOperatorExpr(ast: o.BinaryOperatorExpr, ctx: _ExecutionContext): any { visitBinaryOperatorExpr(ast: o.BinaryOperatorExpr, ctx: _ExecutionContext): any {
var lhs = () => ast.lhs.visitExpression(this, ctx); const lhs = () => ast.lhs.visitExpression(this, ctx);
var rhs = () => ast.rhs.visitExpression(this, ctx); const rhs = () => ast.rhs.visitExpression(this, ctx);
switch (ast.operator) { switch (ast.operator) {
case o.BinaryOperator.Equals: case o.BinaryOperator.Equals:
@ -285,21 +285,21 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
} }
} }
visitReadPropExpr(ast: o.ReadPropExpr, ctx: _ExecutionContext): any { visitReadPropExpr(ast: o.ReadPropExpr, ctx: _ExecutionContext): any {
var result: any; let result: any;
var receiver = ast.receiver.visitExpression(this, ctx); const receiver = ast.receiver.visitExpression(this, ctx);
result = receiver[ast.name]; result = receiver[ast.name];
return result; return result;
} }
visitReadKeyExpr(ast: o.ReadKeyExpr, ctx: _ExecutionContext): any { visitReadKeyExpr(ast: o.ReadKeyExpr, ctx: _ExecutionContext): any {
var receiver = ast.receiver.visitExpression(this, ctx); const receiver = ast.receiver.visitExpression(this, ctx);
var prop = ast.index.visitExpression(this, ctx); const prop = ast.index.visitExpression(this, ctx);
return receiver[prop]; return receiver[prop];
} }
visitLiteralArrayExpr(ast: o.LiteralArrayExpr, ctx: _ExecutionContext): any { visitLiteralArrayExpr(ast: o.LiteralArrayExpr, ctx: _ExecutionContext): any {
return this.visitAllExpressions(ast.entries, ctx); return this.visitAllExpressions(ast.entries, ctx);
} }
visitLiteralMapExpr(ast: o.LiteralMapExpr, ctx: _ExecutionContext): any { visitLiteralMapExpr(ast: o.LiteralMapExpr, ctx: _ExecutionContext): any {
var result = {}; const result = {};
ast.entries.forEach( ast.entries.forEach(
(entry) => (result as any)[<string>entry[0]] = (entry) => (result as any)[<string>entry[0]] =
(<o.Expression>entry[1]).visitExpression(this, ctx)); (<o.Expression>entry[1]).visitExpression(this, ctx));
@ -311,9 +311,9 @@ class StatementInterpreter implements o.StatementVisitor, o.ExpressionVisitor {
} }
visitAllStatements(statements: o.Statement[], ctx: _ExecutionContext): ReturnValue { visitAllStatements(statements: o.Statement[], ctx: _ExecutionContext): ReturnValue {
for (var i = 0; i < statements.length; i++) { for (let i = 0; i < statements.length; i++) {
var stmt = statements[i]; const stmt = statements[i];
var val = stmt.visitStatement(this, ctx); const val = stmt.visitStatement(this, ctx);
if (val instanceof ReturnValue) { if (val instanceof ReturnValue) {
return val; return val;
} }
@ -328,5 +328,5 @@ function _declareFn(
return (...args: any[]) => _executeFunctionStatements(varNames, args, statements, ctx, visitor); return (...args: any[]) => _executeFunctionStatements(varNames, args, statements, ctx, visitor);
} }
var CATCH_ERROR_VAR = 'error'; const CATCH_ERROR_VAR = 'error';
var CATCH_STACK_VAR = 'stack'; const CATCH_STACK_VAR = 'stack';

View File

@ -28,8 +28,8 @@ function evalExpression(
export function jitStatements( export function jitStatements(
sourceUrl: string, statements: o.Statement[], resultVar: string): any { sourceUrl: string, statements: o.Statement[], resultVar: string): any {
var converter = new JitEmitterVisitor(); const converter = new JitEmitterVisitor();
var ctx = EmitterVisitorContext.createRoot([resultVar]); const ctx = EmitterVisitorContext.createRoot([resultVar]);
converter.visitAllStatements(statements, ctx); converter.visitAllStatements(statements, ctx);
return evalExpression(sourceUrl, resultVar, ctx.toSource(), converter.getArgs()); return evalExpression(sourceUrl, resultVar, ctx.toSource(), converter.getArgs());
} }
@ -39,20 +39,20 @@ class JitEmitterVisitor extends AbstractJsEmitterVisitor {
private _evalArgValues: any[] = []; private _evalArgValues: any[] = [];
getArgs(): {[key: string]: any} { getArgs(): {[key: string]: any} {
var result: {[key: string]: any} = {}; const result: {[key: string]: any} = {};
for (var i = 0; i < this._evalArgNames.length; i++) { for (let i = 0; i < this._evalArgNames.length; i++) {
result[this._evalArgNames[i]] = this._evalArgValues[i]; result[this._evalArgNames[i]] = this._evalArgValues[i];
} }
return result; return result;
} }
visitExternalExpr(ast: o.ExternalExpr, ctx: EmitterVisitorContext): any { visitExternalExpr(ast: o.ExternalExpr, ctx: EmitterVisitorContext): any {
var value = ast.value.reference; const value = ast.value.reference;
var id = this._evalArgValues.indexOf(value); let id = this._evalArgValues.indexOf(value);
if (id === -1) { if (id === -1) {
id = this._evalArgValues.length; id = this._evalArgValues.length;
this._evalArgValues.push(value); this._evalArgValues.push(value);
var name = isPresent(ast.value.name) ? sanitizeIdentifier(ast.value.name) : 'val'; const name = isPresent(ast.value.name) ? sanitizeIdentifier(ast.value.name) : 'val';
this._evalArgNames.push(sanitizeIdentifier(`jit_${name}${id}`)); this._evalArgNames.push(sanitizeIdentifier(`jit_${name}${id}`));
} }
ctx.print(this._evalArgNames[id]); ctx.print(this._evalArgNames[id]);

Some files were not shown because too many files have changed in this diff Show More