{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
* - `minIntegerDigits` is the minimum number of integer digits to use. Defaults to `1`.
* - `minFractionDigits` is the minimum number of digits after fraction. Defaults to `0`.
* - `maxFractionDigits` is the maximum number of digits after fraction. Defaults to `3`.
*
* For more information on the acceptable range for each of these numbers and other
* details see your native internationalization library.
*
* WARNING: this pipe uses the Internationalization API which is not yet available in all browsers
* and may require a polyfill. See [Browser Support](guide/browser-support) for details.
*
* ### Example
*
* {@example common/pipes/ts/number_pipe.ts region='DeprecatedNumberPipe'}
*
*
*/
var DeprecatedDecimalPipe = /** @class */ (function () {
function DeprecatedDecimalPipe(_locale) {
this._locale = _locale;
}
DeprecatedDecimalPipe.prototype.transform = function (value, digits) {
return formatNumber$1(DeprecatedDecimalPipe, this._locale, value, NumberFormatStyle.Decimal, digits);
};
DeprecatedDecimalPipe.decorators = [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"], args: [{ name: 'number' },] }
];
/** @nocollapse */
DeprecatedDecimalPipe.ctorParameters = function () { return [
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"], args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"],] }] }
]; };
return DeprecatedDecimalPipe;
}());
/**
* @ngModule CommonModule
*
* @description
*
* Formats a number as percentage according to locale rules.
*
* - `digitInfo` See {@link DecimalPipe} for detailed description.
*
* WARNING: this pipe uses the Internationalization API which is not yet available in all browsers
* and may require a polyfill. See [Browser Support](guide/browser-support) for details.
*
* ### Example
*
* {@example common/pipes/ts/percent_pipe.ts region='DeprecatedPercentPipe'}
*
*
*/
var DeprecatedPercentPipe = /** @class */ (function () {
function DeprecatedPercentPipe(_locale) {
this._locale = _locale;
}
DeprecatedPercentPipe.prototype.transform = function (value, digits) {
return formatNumber$1(DeprecatedPercentPipe, this._locale, value, NumberFormatStyle.Percent, digits);
};
DeprecatedPercentPipe.decorators = [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"], args: [{ name: 'percent' },] }
];
/** @nocollapse */
DeprecatedPercentPipe.ctorParameters = function () { return [
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"], args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"],] }] }
]; };
return DeprecatedPercentPipe;
}());
/**
* @ngModule CommonModule
* @description
*
* Formats a number as currency using locale rules.
*
* Use `currency` to format a number as currency.
*
* - `currencyCode` is the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code, such
* as `USD` for the US dollar and `EUR` for the euro.
* - `symbolDisplay` is a boolean indicating whether to use the currency symbol or code.
* - `true`: use symbol (e.g. `$`).
* - `false`(default): use code (e.g. `USD`).
* - `digitInfo` See {@link DecimalPipe} for detailed description.
*
* WARNING: this pipe uses the Internationalization API which is not yet available in all browsers
* and may require a polyfill. See [Browser Support](guide/browser-support) for details.
*
* ### Example
*
* {@example common/pipes/ts/currency_pipe.ts region='DeprecatedCurrencyPipe'}
*
*
*/
var DeprecatedCurrencyPipe = /** @class */ (function () {
function DeprecatedCurrencyPipe(_locale) {
this._locale = _locale;
}
DeprecatedCurrencyPipe.prototype.transform = function (value, currencyCode, symbolDisplay, digits) {
if (currencyCode === void 0) { currencyCode = 'USD'; }
if (symbolDisplay === void 0) { symbolDisplay = false; }
return formatNumber$1(DeprecatedCurrencyPipe, this._locale, value, NumberFormatStyle.Currency, digits, currencyCode, symbolDisplay);
};
DeprecatedCurrencyPipe.decorators = [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"], args: [{ name: 'currency' },] }
];
/** @nocollapse */
DeprecatedCurrencyPipe.ctorParameters = function () { return [
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"], args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"],] }] }
]; };
return DeprecatedCurrencyPipe;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A collection of deprecated i18n pipes that require intl api
*
* @deprecated from v5
*/
var COMMON_DEPRECATED_I18N_PIPES = [DeprecatedDecimalPipe, DeprecatedPercentPipe, DeprecatedCurrencyPipe, DeprecatedDatePipe];
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var ObservableStrategy = /** @class */ (function () {
function ObservableStrategy() {
}
ObservableStrategy.prototype.createSubscription = function (async, updateLatestValue) {
return async.subscribe({ next: updateLatestValue, error: function (e) { throw e; } });
};
ObservableStrategy.prototype.dispose = function (subscription) { subscription.unsubscribe(); };
ObservableStrategy.prototype.onDestroy = function (subscription) { subscription.unsubscribe(); };
return ObservableStrategy;
}());
var PromiseStrategy = /** @class */ (function () {
function PromiseStrategy() {
}
PromiseStrategy.prototype.createSubscription = function (async, updateLatestValue) {
return async.then(updateLatestValue, function (e) { throw e; });
};
PromiseStrategy.prototype.dispose = function (subscription) { };
PromiseStrategy.prototype.onDestroy = function (subscription) { };
return PromiseStrategy;
}());
var _promiseStrategy = new PromiseStrategy();
var _observableStrategy = new ObservableStrategy();
/**
* @ngModule CommonModule
* @description
*
* Unwraps a value from an asynchronous primitive.
*
* The `async` pipe subscribes to an `Observable` or `Promise` and returns the latest value it has
* emitted. When a new value is emitted, the `async` pipe marks the component to be checked for
* changes. When the component gets destroyed, the `async` pipe unsubscribes automatically to avoid
* potential memory leaks.
*
*
* ## Examples
*
* This example binds a `Promise` to the view. Clicking the `Resolve` button resolves the
* promise.
*
* {@example common/pipes/ts/async_pipe.ts region='AsyncPipePromise'}
*
* It's also possible to use `async` with Observables. The example below binds the `time` Observable
* to the view. The Observable continuously updates the view with the current time.
*
* {@example common/pipes/ts/async_pipe.ts region='AsyncPipeObservable'}
*
*
*/
var AsyncPipe = /** @class */ (function () {
function AsyncPipe(_ref) {
this._ref = _ref;
this._latestValue = null;
this._latestReturnedValue = null;
this._subscription = null;
this._obj = null;
this._strategy = null;
}
AsyncPipe.prototype.ngOnDestroy = function () {
if (this._subscription) {
this._dispose();
}
};
AsyncPipe.prototype.transform = function (obj) {
if (!this._obj) {
if (obj) {
this._subscribe(obj);
}
this._latestReturnedValue = this._latestValue;
return this._latestValue;
}
if (obj !== this._obj) {
this._dispose();
return this.transform(obj);
}
if (this._latestValue === this._latestReturnedValue) {
return this._latestReturnedValue;
}
this._latestReturnedValue = this._latestValue;
return _angular_core__WEBPACK_IMPORTED_MODULE_0__["WrappedValue"].wrap(this._latestValue);
};
AsyncPipe.prototype._subscribe = function (obj) {
var _this = this;
this._obj = obj;
this._strategy = this._selectStrategy(obj);
this._subscription = this._strategy.createSubscription(obj, function (value) { return _this._updateLatestValue(obj, value); });
};
AsyncPipe.prototype._selectStrategy = function (obj) {
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵisPromise"])(obj)) {
return _promiseStrategy;
}
if (Object(_angular_core__WEBPACK_IMPORTED_MODULE_0__["ɵisObservable"])(obj)) {
return _observableStrategy;
}
throw invalidPipeArgumentError(AsyncPipe, obj);
};
AsyncPipe.prototype._dispose = function () {
this._strategy.dispose(this._subscription);
this._latestValue = null;
this._latestReturnedValue = null;
this._subscription = null;
this._obj = null;
};
AsyncPipe.prototype._updateLatestValue = function (async, value) {
if (async === this._obj) {
this._latestValue = value;
this._ref.markForCheck();
}
};
AsyncPipe.decorators = [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"], args: [{ name: 'async', pure: false },] }
];
/** @nocollapse */
AsyncPipe.ctorParameters = function () { return [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["ChangeDetectorRef"] }
]; };
return AsyncPipe;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Transforms text to lowercase.
*
* {@example common/pipes/ts/lowerupper_pipe.ts region='LowerUpperPipe' }
*
*
*/
var LowerCasePipe = /** @class */ (function () {
function LowerCasePipe() {
}
LowerCasePipe.prototype.transform = function (value) {
if (!value)
return value;
if (typeof value !== 'string') {
throw invalidPipeArgumentError(LowerCasePipe, value);
}
return value.toLowerCase();
};
LowerCasePipe.decorators = [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"], args: [{ name: 'lowercase' },] }
];
return LowerCasePipe;
}());
//
// Regex below matches any Unicode word and compatible with ES5. In ES2018 the same result
// can be achieved by using /\p{L}\S*/gu and also known as Unicode Property Escapes
// (http://2ality.com/2017/07/regexp-unicode-property-escapes.html). Since there is no
// transpilation of this functionality down to ES5 without external tool, the only solution is
// to use already transpiled form. Example can be found here -
// https://mothereff.in/regexpu#input=var+regex+%3D+/%5Cp%7BL%7D/u%3B&unicodePropertyEscape=1
//
var unicodeWordMatch = /(?:[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u09FC\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C80\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D54-\u0D56\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16F1-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1C80-\u1C88\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2183\u2184\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005\u3006\u3031-\u3035\u303B\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312E\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FEA\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6E5\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AE\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF2D-\uDF40\uDF42-\uDF49\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF]|\uD801[\uDC00-\uDC9D\uDCB0-\uDCD3\uDCD8-\uDCFB\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC00-\uDC34\uDC47-\uDC4A\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDE00\uDE0B-\uDE32\uDE3A\uDE50\uDE5C-\uDE83\uDE86-\uDE89\uDEC0-\uDEF8]|\uD807[\uDC00-\uDC08\uDC0A-\uDC2E\uDC40\uDC72-\uDC8F\uDD00-\uDD06\uDD08\uDD09\uDD0B-\uDD30\uDD46]|\uD808[\uDC00-\uDF99]|\uD809[\uDC80-\uDD43]|[\uD80C\uD81C-\uD820\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872\uD874-\uD879][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F\uDFE0\uDFE1]|\uD821[\uDC00-\uDFEC]|\uD822[\uDC00-\uDEF2]|\uD82C[\uDC00-\uDD1E\uDD70-\uDEFB]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4\uDD00-\uDD43]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1\uDEB0-\uDFFF]|\uD87A[\uDC00-\uDFE0]|\uD87E[\uDC00-\uDE1D])\S*/g;
/**
* Transforms text to titlecase.
*
* The pipe splits up a text into words, capitalizes the first letter of each word and transforms
* the rest of the word into lowercase. In this case, whitespace characters (such as "space", "\t",
* "\n", etc) are used as word separators.
*
* ## Example
* {@example common/pipes/ts/titlecase_pipe.ts region='TitleCasePipe'}
*
*
*/
var TitleCasePipe = /** @class */ (function () {
function TitleCasePipe() {
}
TitleCasePipe.prototype.transform = function (value) {
if (!value)
return value;
if (typeof value !== 'string') {
throw invalidPipeArgumentError(TitleCasePipe, value);
}
return value.replace(unicodeWordMatch, (function (txt) { return txt[0].toUpperCase() + txt.substr(1).toLowerCase(); }));
};
TitleCasePipe.decorators = [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"], args: [{ name: 'titlecase' },] }
];
return TitleCasePipe;
}());
/**
* Transforms text to uppercase.
*
*
*/
var UpperCasePipe = /** @class */ (function () {
function UpperCasePipe() {
}
UpperCasePipe.prototype.transform = function (value) {
if (!value)
return value;
if (typeof value !== 'string') {
throw invalidPipeArgumentError(UpperCasePipe, value);
}
return value.toUpperCase();
};
UpperCasePipe.decorators = [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"], args: [{ name: 'uppercase' },] }
];
return UpperCasePipe;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// clang-format off
/**
* @ngModule CommonModule
* @description
*
* Uses the function {@link formatDate} to format a date according to locale rules.
*
* The following tabled describes the formatting options.
*
* | Field Type | Format | Description | Example Value |
* |--------------------|-------------|---------------------------------------------------------------|------------------------------------------------------------|
* | Era | G, GG & GGG | Abbreviated | AD |
* | | GGGG | Wide | Anno Domini |
* | | GGGGG | Narrow | A |
* | Year | y | Numeric: minimum digits | 2, 20, 201, 2017, 20173 |
* | | yy | Numeric: 2 digits + zero padded | 02, 20, 01, 17, 73 |
* | | yyy | Numeric: 3 digits + zero padded | 002, 020, 201, 2017, 20173 |
* | | yyyy | Numeric: 4 digits or more + zero padded | 0002, 0020, 0201, 2017, 20173 |
* | Month | M | Numeric: 1 digit | 9, 12 |
* | | MM | Numeric: 2 digits + zero padded | 09, 12 |
* | | MMM | Abbreviated | Sep |
* | | MMMM | Wide | September |
* | | MMMMM | Narrow | S |
* | Month standalone | L | Numeric: 1 digit | 9, 12 |
* | | LL | Numeric: 2 digits + zero padded | 09, 12 |
* | | LLL | Abbreviated | Sep |
* | | LLLL | Wide | September |
* | | LLLLL | Narrow | S |
* | Week of year | w | Numeric: minimum digits | 1... 53 |
* | | ww | Numeric: 2 digits + zero padded | 01... 53 |
* | Week of month | W | Numeric: 1 digit | 1... 5 |
* | Day of month | d | Numeric: minimum digits | 1 |
* | | dd | Numeric: 2 digits + zero padded | 01 |
* | Week day | E, EE & EEE | Abbreviated | Tue |
* | | EEEE | Wide | Tuesday |
* | | EEEEE | Narrow | T |
* | | EEEEEE | Short | Tu |
* | Period | a, aa & aaa | Abbreviated | am/pm or AM/PM |
* | | aaaa | Wide (fallback to `a` when missing) | ante meridiem/post meridiem |
* | | aaaaa | Narrow | a/p |
* | Period* | B, BB & BBB | Abbreviated | mid. |
* | | BBBB | Wide | am, pm, midnight, noon, morning, afternoon, evening, night |
* | | BBBBB | Narrow | md |
* | Period standalone* | b, bb & bbb | Abbreviated | mid. |
* | | bbbb | Wide | am, pm, midnight, noon, morning, afternoon, evening, night |
* | | bbbbb | Narrow | md |
* | Hour 1-12 | h | Numeric: minimum digits | 1, 12 |
* | | hh | Numeric: 2 digits + zero padded | 01, 12 |
* | Hour 0-23 | H | Numeric: minimum digits | 0, 23 |
* | | HH | Numeric: 2 digits + zero padded | 00, 23 |
* | Minute | m | Numeric: minimum digits | 8, 59 |
* | | mm | Numeric: 2 digits + zero padded | 08, 59 |
* | Second | s | Numeric: minimum digits | 0... 59 |
* | | ss | Numeric: 2 digits + zero padded | 00... 59 |
* | Fractional seconds | S | Numeric: 1 digit | 0... 9 |
* | | SS | Numeric: 2 digits + zero padded | 00... 99 |
* | | SSS | Numeric: 3 digits + zero padded (= milliseconds) | 000... 999 |
* | Zone | z, zz & zzz | Short specific non location format (fallback to O) | GMT-8 |
* | | zzzz | Long specific non location format (fallback to OOOO) | GMT-08:00 |
* | | Z, ZZ & ZZZ | ISO8601 basic format | -0800 |
* | | ZZZZ | Long localized GMT format | GMT-8:00 |
* | | ZZZZZ | ISO8601 extended format + Z indicator for offset 0 (= XXXXX) | -08:00 |
* | | O, OO & OOO | Short localized GMT format | GMT-8 |
* | | OOOO | Long localized GMT format | GMT-08:00 |
*
*
* When the expression is a ISO string without time (e.g. 2016-09-19) the time zone offset is not
* applied and the formatted text will have the same day, month and year of the expression.
*
* WARNINGS:
* - this pipe has only access to en-US locale data by default. If you want to localize the dates
* in another language, you will have to import data for other locales.
* See the ["I18n guide"](guide/i18n#i18n-pipes) to know how to import additional locale
* data.
* - Fields suffixed with * are only available in the extra dataset.
* See the ["I18n guide"](guide/i18n#i18n-pipes) to know how to import extra locale
* data.
* - this pipe is marked as pure hence it will not be re-evaluated when the input is mutated.
* Instead users should treat the date as an immutable object and change the reference when the
* pipe needs to re-run (this is to avoid reformatting the date on every change detection run
* which would be an expensive operation).
*
* ### Examples
*
* Assuming `dateObj` is (year: 2015, month: 6, day: 15, hour: 21, minute: 43, second: 11)
* in the _local_ time and locale is 'en-US':
*
* {@example common/pipes/ts/date_pipe.ts region='DatePipe'}
*
*
*/
// clang-format on
var DatePipe = /** @class */ (function () {
function DatePipe(locale) {
this.locale = locale;
}
/**
* @param value a date object or a number (milliseconds since UTC epoch) or an ISO string
* (https://www.w3.org/TR/NOTE-datetime).
* @param format indicates which date/time components to include. The format can be predefined as
* shown below (all examples are given for `en-US`) or custom as shown in the table.
* - `'short'`: equivalent to `'M/d/yy, h:mm a'` (e.g. `6/15/15, 9:03 AM`).
* - `'medium'`: equivalent to `'MMM d, y, h:mm:ss a'` (e.g. `Jun 15, 2015, 9:03:01 AM`).
* - `'long'`: equivalent to `'MMMM d, y, h:mm:ss a z'` (e.g. `June 15, 2015 at 9:03:01 AM
* GMT+1`).
* - `'full'`: equivalent to `'EEEE, MMMM d, y, h:mm:ss a zzzz'` (e.g. `Monday, June 15, 2015 at
* 9:03:01 AM GMT+01:00`).
* - `'shortDate'`: equivalent to `'M/d/yy'` (e.g. `6/15/15`).
* - `'mediumDate'`: equivalent to `'MMM d, y'` (e.g. `Jun 15, 2015`).
* - `'longDate'`: equivalent to `'MMMM d, y'` (e.g. `June 15, 2015`).
* - `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` (e.g. `Monday, June 15, 2015`).
* - `'shortTime'`: equivalent to `'h:mm a'` (e.g. `9:03 AM`).
* - `'mediumTime'`: equivalent to `'h:mm:ss a'` (e.g. `9:03:01 AM`).
* - `'longTime'`: equivalent to `'h:mm:ss a z'` (e.g. `9:03:01 AM GMT+1`).
* - `'fullTime'`: equivalent to `'h:mm:ss a zzzz'` (e.g. `9:03:01 AM GMT+01:00`).
* @param timezone to be used for formatting the time. It understands UTC/GMT and the continental
* US time zone
* abbreviations, but for general use, use a time zone offset (e.g. `'+0430'`).
* @param locale a `string` defining the locale to use (uses the current {@link LOCALE_ID} by
* default).
*/
DatePipe.prototype.transform = function (value, format, timezone, locale) {
if (format === void 0) { format = 'mediumDate'; }
if (value == null || value === '' || value !== value)
return null;
try {
return formatDate(value, format, locale || this.locale, timezone);
}
catch (error) {
throw invalidPipeArgumentError(DatePipe, error.message);
}
};
DatePipe.decorators = [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"], args: [{ name: 'date', pure: true },] }
];
/** @nocollapse */
DatePipe.ctorParameters = function () { return [
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"], args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"],] }] }
]; };
return DatePipe;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var _INTERPOLATION_REGEXP = /#/g;
/**
* @ngModule CommonModule
* @description
*
* Maps a value to a string that pluralizes the value according to locale rules.
*
* ## Example
*
* {@example common/pipes/ts/i18n_pipe.ts region='I18nPluralPipeComponent'}
*
* @experimental
*/
var I18nPluralPipe = /** @class */ (function () {
function I18nPluralPipe(_localization) {
this._localization = _localization;
}
/**
* @param value the number to be formatted
* @param pluralMap an object that mimics the ICU format, see
* http://userguide.icu-project.org/formatparse/messages.
* @param locale a `string` defining the locale to use (uses the current {@link LOCALE_ID} by
* default).
*/
I18nPluralPipe.prototype.transform = function (value, pluralMap, locale) {
if (value == null)
return '';
if (typeof pluralMap !== 'object' || pluralMap === null) {
throw invalidPipeArgumentError(I18nPluralPipe, pluralMap);
}
var key = getPluralCategory(value, Object.keys(pluralMap), this._localization, locale);
return pluralMap[key].replace(_INTERPOLATION_REGEXP, value.toString());
};
I18nPluralPipe.decorators = [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"], args: [{ name: 'i18nPlural', pure: true },] }
];
/** @nocollapse */
I18nPluralPipe.ctorParameters = function () { return [
{ type: NgLocalization }
]; };
return I18nPluralPipe;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @ngModule CommonModule
* @description
*
* Generic selector that displays the string that matches the current value.
*
* If none of the keys of the `mapping` match the `value`, then the content
* of the `other` key is returned when present, otherwise an empty string is returned.
*
* ## Example
*
* {@example common/pipes/ts/i18n_pipe.ts region='I18nSelectPipeComponent'}
*
* @experimental
*/
var I18nSelectPipe = /** @class */ (function () {
function I18nSelectPipe() {
}
/**
* @param value a string to be internationalized.
* @param mapping an object that indicates the text that should be displayed
* for different values of the provided `value`.
*/
I18nSelectPipe.prototype.transform = function (value, mapping) {
if (value == null)
return '';
if (typeof mapping !== 'object' || typeof value !== 'string') {
throw invalidPipeArgumentError(I18nSelectPipe, mapping);
}
if (mapping.hasOwnProperty(value)) {
return mapping[value];
}
if (mapping.hasOwnProperty('other')) {
return mapping['other'];
}
return '';
};
I18nSelectPipe.decorators = [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"], args: [{ name: 'i18nSelect', pure: true },] }
];
return I18nSelectPipe;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @ngModule CommonModule
* @description
*
* Converts value into string using `JSON.stringify`. Useful for debugging.
*
* ### Example
* {@example common/pipes/ts/json_pipe.ts region='JsonPipe'}
*
*
*/
var JsonPipe = /** @class */ (function () {
function JsonPipe() {
}
JsonPipe.prototype.transform = function (value) { return JSON.stringify(value, null, 2); };
JsonPipe.decorators = [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"], args: [{ name: 'json', pure: false },] }
];
return JsonPipe;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @ngModule CommonModule
* @description
*
* Uses the function {@link formatNumber} to format a number according to locale rules.
*
* Formats a number as text. Group sizing and separator and other locale-specific
* configurations are based on the locale.
*
* ### Example
*
* {@example common/pipes/ts/number_pipe.ts region='NumberPipe'}
*
*
*/
var DecimalPipe = /** @class */ (function () {
function DecimalPipe(_locale) {
this._locale = _locale;
}
/**
* @param value a number to be formatted.
* @param digitsInfo a `string` which has a following format: {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
.
* - `minIntegerDigits` is the minimum number of integer digits to use. Defaults to `1`.
* - `minFractionDigits` is the minimum number of digits after the decimal point. Defaults to
* `0`.
* - `maxFractionDigits` is the maximum number of digits after the decimal point. Defaults to
* `3`.
* @param locale a `string` defining the locale to use (uses the current {@link LOCALE_ID} by
* default).
*/
DecimalPipe.prototype.transform = function (value, digitsInfo, locale) {
if (isEmpty(value))
return null;
locale = locale || this._locale;
try {
var num = strToNumber(value);
return formatNumber(num, locale, digitsInfo);
}
catch (error) {
throw invalidPipeArgumentError(DecimalPipe, error.message);
}
};
DecimalPipe.decorators = [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"], args: [{ name: 'number' },] }
];
/** @nocollapse */
DecimalPipe.ctorParameters = function () { return [
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"], args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"],] }] }
]; };
return DecimalPipe;
}());
/**
* @ngModule CommonModule
* @description
*
* Uses the function {@link formatPercent} to format a number as a percentage according
* to locale rules.
*
* ### Example
*
* {@example common/pipes/ts/percent_pipe.ts region='PercentPipe'}
*
*
*/
var PercentPipe = /** @class */ (function () {
function PercentPipe(_locale) {
this._locale = _locale;
}
/**
*
* @param value a number to be formatted as a percentage.
* @param digitsInfo see {@link DecimalPipe} for more details.
* @param locale a `string` defining the locale to use (uses the current {@link LOCALE_ID} by
* default).
*/
PercentPipe.prototype.transform = function (value, digitsInfo, locale) {
if (isEmpty(value))
return null;
locale = locale || this._locale;
try {
var num = strToNumber(value);
return formatPercent(num, locale, digitsInfo);
}
catch (error) {
throw invalidPipeArgumentError(PercentPipe, error.message);
}
};
PercentPipe.decorators = [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"], args: [{ name: 'percent' },] }
];
/** @nocollapse */
PercentPipe.ctorParameters = function () { return [
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"], args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"],] }] }
]; };
return PercentPipe;
}());
/**
* @ngModule CommonModule
* @description
*
* Uses the functions {@link getCurrencySymbol} and {@link formatCurrency} to format a
* number as currency using locale rules.
*
* ### Example
*
* {@example common/pipes/ts/currency_pipe.ts region='CurrencyPipe'}
*
*
*/
var CurrencyPipe = /** @class */ (function () {
function CurrencyPipe(_locale) {
this._locale = _locale;
}
/**
*
* @param value a number to be formatted as currency.
* @param currencyCodeis the [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code,
* such as `USD` for the US dollar and `EUR` for the euro.
* @param display indicates whether to show the currency symbol, the code or a custom value:
* - `code`: use code (e.g. `USD`).
* - `symbol`(default): use symbol (e.g. `$`).
* - `symbol-narrow`: some countries have two symbols for their currency, one regular and one
* narrow (e.g. the canadian dollar CAD has the symbol `CA$` and the symbol-narrow `$`).
* - `string`: use this value instead of a code or a symbol.
* - boolean (deprecated from v5): `true` for symbol and false for `code`.
* If there is no narrow symbol for the chosen currency, the regular symbol will be used.
* @param digitsInfo see {@link DecimalPipe} for more details.
* @param locale a `string` defining the locale to use (uses the current {@link LOCALE_ID} by
* default).
*/
CurrencyPipe.prototype.transform = function (value, currencyCode, display, digitsInfo, locale) {
if (display === void 0) { display = 'symbol'; }
if (isEmpty(value))
return null;
locale = locale || this._locale;
if (typeof display === 'boolean') {
if (console && console.warn) {
console.warn("Warning: the currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are \"code\", \"symbol\" or \"symbol-narrow\".");
}
display = display ? 'symbol' : 'code';
}
var currency = currencyCode || 'USD';
if (display !== 'code') {
if (display === 'symbol' || display === 'symbol-narrow') {
currency = getCurrencySymbol(currency, display === 'symbol' ? 'wide' : 'narrow', locale);
}
else {
currency = display;
}
}
try {
var num = strToNumber(value);
return formatCurrency(num, locale, currency, currencyCode, digitsInfo);
}
catch (error) {
throw invalidPipeArgumentError(CurrencyPipe, error.message);
}
};
CurrencyPipe.decorators = [
{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Pipe"], args: [{ name: 'currency' },] }
];
/** @nocollapse */
CurrencyPipe.ctorParameters = function () { return [
{ type: String, decorators: [{ type: _angular_core__WEBPACK_IMPORTED_MODULE_0__["Inject"], args: [_angular_core__WEBPACK_IMPORTED_MODULE_0__["LOCALE_ID"],] }] }
]; };
return CurrencyPipe;
}());
function isEmpty(value) {
return value == null || value === '' || value !== value;
}
/**
* Transforms a string into a number (if needed)
*/
function strToNumber(value) {
// Convert strings to numbers
if (typeof value === 'string' && !isNaN(Number(value) - parseFloat(value))) {
return Number(value);
}
if (typeof value !== 'number') {
throw new Error(value + " is not a number");
}
return value;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @ngModule CommonModule
* @description
*
* Creates a new `Array` or `String` containing a subset (slice) of the elements.
*
* All behavior is based on the expected behavior of the JavaScript API `Array.prototype.slice()`
* and `String.prototype.slice()`.
*
* When operating on an `Array`, the returned `Array` is always a copy even when all
* the elements are being returned.
*
* When operating on a blank value, the pipe returns the blank value.
*
* ### List Example
*
* This `ngFor` example:
*
* {@example common/pipes/ts/slice_pipe.ts region='SlicePipe_list'}
*
* produces the following:
*
* {ICU message}
` would produce two messages: * - one for the content with meaning and description,
* - another one for the ICU message.
*
* In this case the last message is discarded as it contains less information (the AST is
* otherwise identical).
*
* Note that we should still keep messages extracted from attributes inside the section (ie in the
* ICU message here)
*/
_Visitor.prototype._closeTranslatableSection = function (node, directChildren) {
if (!this._isInTranslatableSection) {
this._reportError(node, 'Unexpected section end');
return;
}
var startIndex = this._msgCountAtSectionStart;
var significantChildren = directChildren.reduce(function (count, node) { return count + (node instanceof Comment ? 0 : 1); }, 0);
if (significantChildren == 1) {
for (var i = this._messages.length - 1; i >= startIndex; i--) {
var ast = this._messages[i].nodes;
if (!(ast.length == 1 && ast[0] instanceof Text$1)) {
this._messages.splice(i, 1);
break;
}
}
}
this._msgCountAtSectionStart = undefined;
};
_Visitor.prototype._reportError = function (node, msg) {
this._errors.push(new I18nError(node.sourceSpan, msg));
};
return _Visitor;
}());
function _isOpeningComment(n) {
return !!(n instanceof Comment && n.value && n.value.startsWith('i18n'));
}
function _isClosingComment(n) {
return !!(n instanceof Comment && n.value && n.value === '/i18n');
}
function _getI18nAttr(p) {
return p.attrs.find(function (attr) { return attr.name === _I18N_ATTR; }) || null;
}
function _parseMessageMeta(i18n) {
if (!i18n)
return { meaning: '', description: '', id: '' };
var idIndex = i18n.indexOf(ID_SEPARATOR);
var descIndex = i18n.indexOf(MEANING_SEPARATOR);
var _a = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__read"])((idIndex > -1) ? [i18n.slice(0, idIndex), i18n.slice(idIndex + 2)] : [i18n, ''], 2), meaningAndDesc = _a[0], id = _a[1];
var _b = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__read"])((descIndex > -1) ?
[meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] :
['', meaningAndDesc], 2), meaning = _b[0], description = _b[1];
return { meaning: meaning, description: description, id: id };
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var XmlTagDefinition = /** @class */ (function () {
function XmlTagDefinition() {
this.closedByParent = false;
this.contentType = TagContentType.PARSABLE_DATA;
this.isVoid = false;
this.ignoreFirstLf = false;
this.canSelfClose = true;
}
XmlTagDefinition.prototype.requireExtraParent = function (currentParent) { return false; };
XmlTagDefinition.prototype.isClosedByChild = function (name) { return false; };
return XmlTagDefinition;
}());
var _TAG_DEFINITION = new XmlTagDefinition();
function getXmlTagDefinition(tagName) {
return _TAG_DEFINITION;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var XmlParser = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(XmlParser, _super);
function XmlParser() {
return _super.call(this, getXmlTagDefinition) || this;
}
XmlParser.prototype.parse = function (source, url, parseExpansionForms) {
if (parseExpansionForms === void 0) { parseExpansionForms = false; }
return _super.prototype.parse.call(this, source, url, parseExpansionForms);
};
return XmlParser;
}(Parser$1));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var Serializer = /** @class */ (function () {
function Serializer() {
}
// Creates a name mapper, see `PlaceholderMapper`
// Returning `null` means that no name mapping is used.
Serializer.prototype.createNameMapper = function (message) { return null; };
return Serializer;
}());
/**
* A simple mapper that take a function to transform an internal name to a public name
*/
var SimplePlaceholderMapper = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(SimplePlaceholderMapper, _super);
// create a mapping from the message
function SimplePlaceholderMapper(message, mapName) {
var _this = _super.call(this) || this;
_this.mapName = mapName;
_this.internalToPublic = {};
_this.publicToNextId = {};
_this.publicToInternal = {};
message.nodes.forEach(function (node) { return node.visit(_this); });
return _this;
}
SimplePlaceholderMapper.prototype.toPublicName = function (internalName) {
return this.internalToPublic.hasOwnProperty(internalName) ?
this.internalToPublic[internalName] :
null;
};
SimplePlaceholderMapper.prototype.toInternalName = function (publicName) {
return this.publicToInternal.hasOwnProperty(publicName) ? this.publicToInternal[publicName] :
null;
};
SimplePlaceholderMapper.prototype.visitText = function (text, context) { return null; };
SimplePlaceholderMapper.prototype.visitTagPlaceholder = function (ph, context) {
this.visitPlaceholderName(ph.startName);
_super.prototype.visitTagPlaceholder.call(this, ph, context);
this.visitPlaceholderName(ph.closeName);
};
SimplePlaceholderMapper.prototype.visitPlaceholder = function (ph, context) { this.visitPlaceholderName(ph.name); };
SimplePlaceholderMapper.prototype.visitIcuPlaceholder = function (ph, context) {
this.visitPlaceholderName(ph.name);
};
// XMB placeholders could only contains A-Z, 0-9 and _
SimplePlaceholderMapper.prototype.visitPlaceholderName = function (internalName) {
if (!internalName || this.internalToPublic.hasOwnProperty(internalName)) {
return;
}
var publicName = this.mapName(internalName);
if (this.publicToInternal.hasOwnProperty(publicName)) {
// Create a new XMB when it has already been used
var nextId = this.publicToNextId[publicName];
this.publicToNextId[publicName] = nextId + 1;
publicName = publicName + "_" + nextId;
}
else {
this.publicToNextId[publicName] = 1;
}
this.internalToPublic[internalName] = publicName;
this.publicToInternal[publicName] = internalName;
};
return SimplePlaceholderMapper;
}(RecurseVisitor));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var _Visitor$1 = /** @class */ (function () {
function _Visitor() {
}
_Visitor.prototype.visitTag = function (tag) {
var _this = this;
var strAttrs = this._serializeAttributes(tag.attrs);
if (tag.children.length == 0) {
return "<" + tag.name + strAttrs + "/>";
}
var strChildren = tag.children.map(function (node) { return node.visit(_this); });
return "<" + tag.name + strAttrs + ">" + strChildren.join('') + "" + tag.name + ">";
};
_Visitor.prototype.visitText = function (text) { return text.value; };
_Visitor.prototype.visitDeclaration = function (decl) {
return "";
};
_Visitor.prototype._serializeAttributes = function (attrs) {
var strAttrs = Object.keys(attrs).map(function (name) { return name + "=\"" + attrs[name] + "\""; }).join(' ');
return strAttrs.length > 0 ? ' ' + strAttrs : '';
};
_Visitor.prototype.visitDoctype = function (doctype) {
return "";
};
return _Visitor;
}());
var _visitor = new _Visitor$1();
function serialize(nodes) {
return nodes.map(function (node) { return node.visit(_visitor); }).join('');
}
var Declaration = /** @class */ (function () {
function Declaration(unescapedAttrs) {
var _this = this;
this.attrs = {};
Object.keys(unescapedAttrs).forEach(function (k) {
_this.attrs[k] = escapeXml(unescapedAttrs[k]);
});
}
Declaration.prototype.visit = function (visitor) { return visitor.visitDeclaration(this); };
return Declaration;
}());
var Doctype = /** @class */ (function () {
function Doctype(rootTag, dtd) {
this.rootTag = rootTag;
this.dtd = dtd;
}
Doctype.prototype.visit = function (visitor) { return visitor.visitDoctype(this); };
return Doctype;
}());
var Tag = /** @class */ (function () {
function Tag(name, unescapedAttrs, children) {
if (unescapedAttrs === void 0) { unescapedAttrs = {}; }
if (children === void 0) { children = []; }
var _this = this;
this.name = name;
this.children = children;
this.attrs = {};
Object.keys(unescapedAttrs).forEach(function (k) {
_this.attrs[k] = escapeXml(unescapedAttrs[k]);
});
}
Tag.prototype.visit = function (visitor) { return visitor.visitTag(this); };
return Tag;
}());
var Text$2 = /** @class */ (function () {
function Text(unescapedValue) {
this.value = escapeXml(unescapedValue);
}
Text.prototype.visit = function (visitor) { return visitor.visitText(this); };
return Text;
}());
var CR = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(CR, _super);
function CR(ws) {
if (ws === void 0) { ws = 0; }
return _super.call(this, "\n" + new Array(ws + 1).join(' ')) || this;
}
return CR;
}(Text$2));
var _ESCAPED_CHARS = [
[/&/g, '&'],
[/"/g, '"'],
[/'/g, '''],
[//g, '>'],
];
// Escape `_ESCAPED_CHARS` characters in the given text with encoded entities
function escapeXml(text) {
return _ESCAPED_CHARS.reduce(function (text, entry) { return text.replace(entry[0], entry[1]); }, text);
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var _VERSION = '1.2';
var _XMLNS = 'urn:oasis:names:tc:xliff:document:1.2';
// TODO(vicb): make this a param (s/_/-/)
var _DEFAULT_SOURCE_LANG = 'en';
var _PLACEHOLDER_TAG = 'x';
var _MARKER_TAG = 'mrk';
var _FILE_TAG = 'file';
var _SOURCE_TAG = 'source';
var _SEGMENT_SOURCE_TAG = 'seg-source';
var _TARGET_TAG = 'target';
var _UNIT_TAG = 'trans-unit';
var _CONTEXT_GROUP_TAG = 'context-group';
var _CONTEXT_TAG = 'context';
// http://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html
// http://docs.oasis-open.org/xliff/v1.2/xliff-profile-html/xliff-profile-html-1.2.html
var Xliff = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Xliff, _super);
function Xliff() {
return _super !== null && _super.apply(this, arguments) || this;
}
Xliff.prototype.write = function (messages, locale) {
var visitor = new _WriteVisitor();
var transUnits = [];
messages.forEach(function (message) {
var contextTags = [];
message.sources.forEach(function (source) {
var contextGroupTag = new Tag(_CONTEXT_GROUP_TAG, { purpose: 'location' });
contextGroupTag.children.push(new CR(10), new Tag(_CONTEXT_TAG, { 'context-type': 'sourcefile' }, [new Text$2(source.filePath)]), new CR(10), new Tag(_CONTEXT_TAG, { 'context-type': 'linenumber' }, [new Text$2("" + source.startLine)]), new CR(8));
contextTags.push(new CR(8), contextGroupTag);
});
var transUnit = new Tag(_UNIT_TAG, { id: message.id, datatype: 'html' });
(_a = transUnit.children).push.apply(_a, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])([new CR(8), new Tag(_SOURCE_TAG, {}, visitor.serialize(message.nodes))], contextTags));
if (message.description) {
transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'description' }, [new Text$2(message.description)]));
}
if (message.meaning) {
transUnit.children.push(new CR(8), new Tag('note', { priority: '1', from: 'meaning' }, [new Text$2(message.meaning)]));
}
transUnit.children.push(new CR(6));
transUnits.push(new CR(6), transUnit);
var _a;
});
var body = new Tag('body', {}, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(transUnits, [new CR(4)]));
var file = new Tag('file', {
'source-language': locale || _DEFAULT_SOURCE_LANG,
datatype: 'plaintext',
original: 'ng2.template',
}, [new CR(4), body, new CR(2)]);
var xliff = new Tag('xliff', { version: _VERSION, xmlns: _XMLNS }, [new CR(2), file, new CR()]);
return serialize([
new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR()
]);
};
Xliff.prototype.load = function (content, url) {
// xliff to xml nodes
var xliffParser = new XliffParser();
var _a = xliffParser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
// xml nodes to i18n nodes
var i18nNodesByMsgId = {};
var converter = new XmlToI18n();
Object.keys(msgIdToHtml).forEach(function (msgId) {
var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, e = _a.errors;
errors.push.apply(errors, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(e));
i18nNodesByMsgId[msgId] = i18nNodes;
});
if (errors.length) {
throw new Error("xliff parse errors:\n" + errors.join('\n'));
}
return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
};
Xliff.prototype.digest = function (message) { return digest(message); };
return Xliff;
}(Serializer));
var _WriteVisitor = /** @class */ (function () {
function _WriteVisitor() {
}
_WriteVisitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
_WriteVisitor.prototype.visitContainer = function (container, context) {
var _this = this;
var nodes = [];
container.children.forEach(function (node) { return nodes.push.apply(nodes, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(node.visit(_this))); });
return nodes;
};
_WriteVisitor.prototype.visitIcu = function (icu, context) {
var _this = this;
var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
Object.keys(icu.cases).forEach(function (c) {
nodes.push.apply(nodes, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])([new Text$2(c + " {")], icu.cases[c].visit(_this), [new Text$2("} ")]));
});
nodes.push(new Text$2("}"));
return nodes;
};
_WriteVisitor.prototype.visitTagPlaceholder = function (ph, context) {
var ctype = getCtypeForTag(ph.tag);
if (ph.isVoid) {
// void tags have no children nor closing tags
return [new Tag(_PLACEHOLDER_TAG, { id: ph.startName, ctype: ctype, 'equiv-text': "<" + ph.tag + "/>" })];
}
var startTagPh = new Tag(_PLACEHOLDER_TAG, { id: ph.startName, ctype: ctype, 'equiv-text': "<" + ph.tag + ">" });
var closeTagPh = new Tag(_PLACEHOLDER_TAG, { id: ph.closeName, ctype: ctype, 'equiv-text': "" + ph.tag + ">" });
return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])([startTagPh], this.serialize(ph.children), [closeTagPh]);
};
_WriteVisitor.prototype.visitPlaceholder = function (ph, context) {
return [new Tag(_PLACEHOLDER_TAG, { id: ph.name, 'equiv-text': "{{" + ph.value + "}}" })];
};
_WriteVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
var equivText = "{" + ph.value.expression + ", " + ph.value.type + ", " + Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ') + "}";
return [new Tag(_PLACEHOLDER_TAG, { id: ph.name, 'equiv-text': equivText })];
};
_WriteVisitor.prototype.serialize = function (nodes) {
var _this = this;
return [].concat.apply([], Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(nodes.map(function (node) { return node.visit(_this); })));
};
return _WriteVisitor;
}());
// TODO(vicb): add error management (structure)
// Extract messages as xml nodes from the xliff file
var XliffParser = /** @class */ (function () {
function XliffParser() {
this._locale = null;
}
XliffParser.prototype.parse = function (xliff, url) {
this._unitMlString = null;
this._msgIdToHtml = {};
var xml = new XmlParser().parse(xliff, url, false);
this._errors = xml.errors;
visitAll(this, xml.rootNodes, null);
return {
msgIdToHtml: this._msgIdToHtml,
errors: this._errors,
locale: this._locale,
};
};
XliffParser.prototype.visitElement = function (element, context) {
switch (element.name) {
case _UNIT_TAG:
this._unitMlString = null;
var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
if (!idAttr) {
this._addError(element, "<" + _UNIT_TAG + "> misses the \"id\" attribute");
}
else {
var id = idAttr.value;
if (this._msgIdToHtml.hasOwnProperty(id)) {
this._addError(element, "Duplicated translations for msg " + id);
}
else {
visitAll(this, element.children, null);
if (typeof this._unitMlString === 'string') {
this._msgIdToHtml[id] = this._unitMlString;
}
else {
this._addError(element, "Message " + id + " misses a translation");
}
}
}
break;
// ignore those tags
case _SOURCE_TAG:
case _SEGMENT_SOURCE_TAG:
break;
case _TARGET_TAG:
var innerTextStart = element.startSourceSpan.end.offset;
var innerTextEnd = element.endSourceSpan.start.offset;
var content = element.startSourceSpan.start.file.content;
var innerText = content.slice(innerTextStart, innerTextEnd);
this._unitMlString = innerText;
break;
case _FILE_TAG:
var localeAttr = element.attrs.find(function (attr) { return attr.name === 'target-language'; });
if (localeAttr) {
this._locale = localeAttr.value;
}
visitAll(this, element.children, null);
break;
default:
// TODO(vicb): assert file structure, xliff version
// For now only recurse on unhandled nodes
visitAll(this, element.children, null);
}
};
XliffParser.prototype.visitAttribute = function (attribute, context) { };
XliffParser.prototype.visitText = function (text, context) { };
XliffParser.prototype.visitComment = function (comment, context) { };
XliffParser.prototype.visitExpansion = function (expansion, context) { };
XliffParser.prototype.visitExpansionCase = function (expansionCase, context) { };
XliffParser.prototype._addError = function (node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
};
return XliffParser;
}());
// Convert ml nodes (xliff syntax) to i18n nodes
var XmlToI18n = /** @class */ (function () {
function XmlToI18n() {
}
XmlToI18n.prototype.convert = function (message, url) {
var xmlIcu = new XmlParser().parse(message, url, true);
this._errors = xmlIcu.errors;
var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
[] : [].concat.apply([], Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(visitAll(this, xmlIcu.rootNodes)));
return {
i18nNodes: i18nNodes,
errors: this._errors,
};
};
XmlToI18n.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
XmlToI18n.prototype.visitElement = function (el, context) {
if (el.name === _PLACEHOLDER_TAG) {
var nameAttr = el.attrs.find(function (attr) { return attr.name === 'id'; });
if (nameAttr) {
return new Placeholder('', nameAttr.value, el.sourceSpan);
}
this._addError(el, "<" + _PLACEHOLDER_TAG + "> misses the \"id\" attribute");
return null;
}
if (el.name === _MARKER_TAG) {
return [].concat.apply([], Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(visitAll(this, el.children)));
}
this._addError(el, "Unexpected tag");
return null;
};
XmlToI18n.prototype.visitExpansion = function (icu, context) {
var caseMap = {};
visitAll(this, icu.cases).forEach(function (c) {
caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
});
return new Icu(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
};
XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
return {
value: icuCase.value,
nodes: visitAll(this, icuCase.expression),
};
};
XmlToI18n.prototype.visitComment = function (comment, context) { };
XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
XmlToI18n.prototype._addError = function (node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
};
return XmlToI18n;
}());
function getCtypeForTag(tag) {
switch (tag.toLowerCase()) {
case 'br':
return 'lb';
case 'img':
return 'image';
default:
return "x-" + tag;
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var _VERSION$1 = '2.0';
var _XMLNS$1 = 'urn:oasis:names:tc:xliff:document:2.0';
// TODO(vicb): make this a param (s/_/-/)
var _DEFAULT_SOURCE_LANG$1 = 'en';
var _PLACEHOLDER_TAG$1 = 'ph';
var _PLACEHOLDER_SPANNING_TAG = 'pc';
var _MARKER_TAG$1 = 'mrk';
var _XLIFF_TAG = 'xliff';
var _SOURCE_TAG$1 = 'source';
var _TARGET_TAG$1 = 'target';
var _UNIT_TAG$1 = 'unit';
// http://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html
var Xliff2 = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Xliff2, _super);
function Xliff2() {
return _super !== null && _super.apply(this, arguments) || this;
}
Xliff2.prototype.write = function (messages, locale) {
var visitor = new _WriteVisitor$1();
var units = [];
messages.forEach(function (message) {
var unit = new Tag(_UNIT_TAG$1, { id: message.id });
var notes = new Tag('notes');
if (message.description || message.meaning) {
if (message.description) {
notes.children.push(new CR(8), new Tag('note', { category: 'description' }, [new Text$2(message.description)]));
}
if (message.meaning) {
notes.children.push(new CR(8), new Tag('note', { category: 'meaning' }, [new Text$2(message.meaning)]));
}
}
message.sources.forEach(function (source) {
notes.children.push(new CR(8), new Tag('note', { category: 'location' }, [
new Text$2(source.filePath + ":" + source.startLine + (source.endLine !== source.startLine ? ',' + source.endLine : ''))
]));
});
notes.children.push(new CR(6));
unit.children.push(new CR(6), notes);
var segment = new Tag('segment');
segment.children.push(new CR(8), new Tag(_SOURCE_TAG$1, {}, visitor.serialize(message.nodes)), new CR(6));
unit.children.push(new CR(6), segment, new CR(4));
units.push(new CR(4), unit);
});
var file = new Tag('file', { 'original': 'ng.template', id: 'ngi18n' }, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(units, [new CR(2)]));
var xliff = new Tag(_XLIFF_TAG, { version: _VERSION$1, xmlns: _XMLNS$1, srcLang: locale || _DEFAULT_SOURCE_LANG$1 }, [new CR(2), file, new CR()]);
return serialize([
new Declaration({ version: '1.0', encoding: 'UTF-8' }), new CR(), xliff, new CR()
]);
};
Xliff2.prototype.load = function (content, url) {
// xliff to xml nodes
var xliff2Parser = new Xliff2Parser();
var _a = xliff2Parser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
// xml nodes to i18n nodes
var i18nNodesByMsgId = {};
var converter = new XmlToI18n$1();
Object.keys(msgIdToHtml).forEach(function (msgId) {
var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, e = _a.errors;
errors.push.apply(errors, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(e));
i18nNodesByMsgId[msgId] = i18nNodes;
});
if (errors.length) {
throw new Error("xliff2 parse errors:\n" + errors.join('\n'));
}
return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
};
Xliff2.prototype.digest = function (message) { return decimalDigest(message); };
return Xliff2;
}(Serializer));
var _WriteVisitor$1 = /** @class */ (function () {
function _WriteVisitor() {
}
_WriteVisitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
_WriteVisitor.prototype.visitContainer = function (container, context) {
var _this = this;
var nodes = [];
container.children.forEach(function (node) { return nodes.push.apply(nodes, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(node.visit(_this))); });
return nodes;
};
_WriteVisitor.prototype.visitIcu = function (icu, context) {
var _this = this;
var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
Object.keys(icu.cases).forEach(function (c) {
nodes.push.apply(nodes, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])([new Text$2(c + " {")], icu.cases[c].visit(_this), [new Text$2("} ")]));
});
nodes.push(new Text$2("}"));
return nodes;
};
_WriteVisitor.prototype.visitTagPlaceholder = function (ph, context) {
var _this = this;
var type = getTypeForTag(ph.tag);
if (ph.isVoid) {
var tagPh = new Tag(_PLACEHOLDER_TAG$1, {
id: (this._nextPlaceholderId++).toString(),
equiv: ph.startName,
type: type,
disp: "<" + ph.tag + "/>",
});
return [tagPh];
}
var tagPc = new Tag(_PLACEHOLDER_SPANNING_TAG, {
id: (this._nextPlaceholderId++).toString(),
equivStart: ph.startName,
equivEnd: ph.closeName,
type: type,
dispStart: "<" + ph.tag + ">",
dispEnd: "" + ph.tag + ">",
});
var nodes = [].concat.apply([], Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(ph.children.map(function (node) { return node.visit(_this); })));
if (nodes.length) {
nodes.forEach(function (node) { return tagPc.children.push(node); });
}
else {
tagPc.children.push(new Text$2(''));
}
return [tagPc];
};
_WriteVisitor.prototype.visitPlaceholder = function (ph, context) {
var idStr = (this._nextPlaceholderId++).toString();
return [new Tag(_PLACEHOLDER_TAG$1, {
id: idStr,
equiv: ph.name,
disp: "{{" + ph.value + "}}",
})];
};
_WriteVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
var cases = Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ');
var idStr = (this._nextPlaceholderId++).toString();
return [new Tag(_PLACEHOLDER_TAG$1, { id: idStr, equiv: ph.name, disp: "{" + ph.value.expression + ", " + ph.value.type + ", " + cases + "}" })];
};
_WriteVisitor.prototype.serialize = function (nodes) {
var _this = this;
this._nextPlaceholderId = 0;
return [].concat.apply([], Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(nodes.map(function (node) { return node.visit(_this); })));
};
return _WriteVisitor;
}());
// Extract messages as xml nodes from the xliff file
var Xliff2Parser = /** @class */ (function () {
function Xliff2Parser() {
this._locale = null;
}
Xliff2Parser.prototype.parse = function (xliff, url) {
this._unitMlString = null;
this._msgIdToHtml = {};
var xml = new XmlParser().parse(xliff, url, false);
this._errors = xml.errors;
visitAll(this, xml.rootNodes, null);
return {
msgIdToHtml: this._msgIdToHtml,
errors: this._errors,
locale: this._locale,
};
};
Xliff2Parser.prototype.visitElement = function (element, context) {
switch (element.name) {
case _UNIT_TAG$1:
this._unitMlString = null;
var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
if (!idAttr) {
this._addError(element, "<" + _UNIT_TAG$1 + "> misses the \"id\" attribute");
}
else {
var id = idAttr.value;
if (this._msgIdToHtml.hasOwnProperty(id)) {
this._addError(element, "Duplicated translations for msg " + id);
}
else {
visitAll(this, element.children, null);
if (typeof this._unitMlString === 'string') {
this._msgIdToHtml[id] = this._unitMlString;
}
else {
this._addError(element, "Message " + id + " misses a translation");
}
}
}
break;
case _SOURCE_TAG$1:
// ignore source message
break;
case _TARGET_TAG$1:
var innerTextStart = element.startSourceSpan.end.offset;
var innerTextEnd = element.endSourceSpan.start.offset;
var content = element.startSourceSpan.start.file.content;
var innerText = content.slice(innerTextStart, innerTextEnd);
this._unitMlString = innerText;
break;
case _XLIFF_TAG:
var localeAttr = element.attrs.find(function (attr) { return attr.name === 'trgLang'; });
if (localeAttr) {
this._locale = localeAttr.value;
}
var versionAttr = element.attrs.find(function (attr) { return attr.name === 'version'; });
if (versionAttr) {
var version = versionAttr.value;
if (version !== '2.0') {
this._addError(element, "The XLIFF file version " + version + " is not compatible with XLIFF 2.0 serializer");
}
else {
visitAll(this, element.children, null);
}
}
break;
default:
visitAll(this, element.children, null);
}
};
Xliff2Parser.prototype.visitAttribute = function (attribute, context) { };
Xliff2Parser.prototype.visitText = function (text, context) { };
Xliff2Parser.prototype.visitComment = function (comment, context) { };
Xliff2Parser.prototype.visitExpansion = function (expansion, context) { };
Xliff2Parser.prototype.visitExpansionCase = function (expansionCase, context) { };
Xliff2Parser.prototype._addError = function (node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
};
return Xliff2Parser;
}());
// Convert ml nodes (xliff syntax) to i18n nodes
var XmlToI18n$1 = /** @class */ (function () {
function XmlToI18n() {
}
XmlToI18n.prototype.convert = function (message, url) {
var xmlIcu = new XmlParser().parse(message, url, true);
this._errors = xmlIcu.errors;
var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
[] : [].concat.apply([], Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(visitAll(this, xmlIcu.rootNodes)));
return {
i18nNodes: i18nNodes,
errors: this._errors,
};
};
XmlToI18n.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
XmlToI18n.prototype.visitElement = function (el, context) {
var _this = this;
switch (el.name) {
case _PLACEHOLDER_TAG$1:
var nameAttr = el.attrs.find(function (attr) { return attr.name === 'equiv'; });
if (nameAttr) {
return [new Placeholder('', nameAttr.value, el.sourceSpan)];
}
this._addError(el, "<" + _PLACEHOLDER_TAG$1 + "> misses the \"equiv\" attribute");
break;
case _PLACEHOLDER_SPANNING_TAG:
var startAttr = el.attrs.find(function (attr) { return attr.name === 'equivStart'; });
var endAttr = el.attrs.find(function (attr) { return attr.name === 'equivEnd'; });
if (!startAttr) {
this._addError(el, "<" + _PLACEHOLDER_TAG$1 + "> misses the \"equivStart\" attribute");
}
else if (!endAttr) {
this._addError(el, "<" + _PLACEHOLDER_TAG$1 + "> misses the \"equivEnd\" attribute");
}
else {
var startId = startAttr.value;
var endId = endAttr.value;
var nodes = [];
return nodes.concat.apply(nodes, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])([new Placeholder('', startId, el.sourceSpan)], el.children.map(function (node) { return node.visit(_this, null); }), [new Placeholder('', endId, el.sourceSpan)]));
}
break;
case _MARKER_TAG$1:
return [].concat.apply([], Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(visitAll(this, el.children)));
default:
this._addError(el, "Unexpected tag");
}
return null;
};
XmlToI18n.prototype.visitExpansion = function (icu, context) {
var caseMap = {};
visitAll(this, icu.cases).forEach(function (c) {
caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
});
return new Icu(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
};
XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
return {
value: icuCase.value,
nodes: [].concat.apply([], Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(visitAll(this, icuCase.expression))),
};
};
XmlToI18n.prototype.visitComment = function (comment, context) { };
XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
XmlToI18n.prototype._addError = function (node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
};
return XmlToI18n;
}());
function getTypeForTag(tag) {
switch (tag.toLowerCase()) {
case 'br':
case 'b':
case 'i':
case 'u':
return 'fmt';
case 'img':
return 'image';
case 'a':
return 'link';
default:
return 'other';
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var _MESSAGES_TAG = 'messagebundle';
var _MESSAGE_TAG = 'msg';
var _PLACEHOLDER_TAG$2 = 'ph';
var _EXEMPLE_TAG = 'ex';
var _SOURCE_TAG$2 = 'source';
var _DOCTYPE = "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
var Xmb = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Xmb, _super);
function Xmb() {
return _super !== null && _super.apply(this, arguments) || this;
}
Xmb.prototype.write = function (messages, locale) {
var exampleVisitor = new ExampleVisitor();
var visitor = new _Visitor$2();
var rootNode = new Tag(_MESSAGES_TAG);
messages.forEach(function (message) {
var attrs = { id: message.id };
if (message.description) {
attrs['desc'] = message.description;
}
if (message.meaning) {
attrs['meaning'] = message.meaning;
}
var sourceTags = [];
message.sources.forEach(function (source) {
sourceTags.push(new Tag(_SOURCE_TAG$2, {}, [
new Text$2(source.filePath + ":" + source.startLine + (source.endLine !== source.startLine ? ',' + source.endLine : ''))
]));
});
rootNode.children.push(new CR(2), new Tag(_MESSAGE_TAG, attrs, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(sourceTags, visitor.serialize(message.nodes))));
});
rootNode.children.push(new CR());
return serialize([
new Declaration({ version: '1.0', encoding: 'UTF-8' }),
new CR(),
new Doctype(_MESSAGES_TAG, _DOCTYPE),
new CR(),
exampleVisitor.addDefaultExamples(rootNode),
new CR(),
]);
};
Xmb.prototype.load = function (content, url) {
throw new Error('Unsupported');
};
Xmb.prototype.digest = function (message) { return digest$1(message); };
Xmb.prototype.createNameMapper = function (message) {
return new SimplePlaceholderMapper(message, toPublicName);
};
return Xmb;
}(Serializer));
var _Visitor$2 = /** @class */ (function () {
function _Visitor() {
}
_Visitor.prototype.visitText = function (text, context) { return [new Text$2(text.value)]; };
_Visitor.prototype.visitContainer = function (container, context) {
var _this = this;
var nodes = [];
container.children.forEach(function (node) { return nodes.push.apply(nodes, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(node.visit(_this))); });
return nodes;
};
_Visitor.prototype.visitIcu = function (icu, context) {
var _this = this;
var nodes = [new Text$2("{" + icu.expressionPlaceholder + ", " + icu.type + ", ")];
Object.keys(icu.cases).forEach(function (c) {
nodes.push.apply(nodes, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])([new Text$2(c + " {")], icu.cases[c].visit(_this), [new Text$2("} ")]));
});
nodes.push(new Text$2("}"));
return nodes;
};
_Visitor.prototype.visitTagPlaceholder = function (ph, context) {
var startEx = new Tag(_EXEMPLE_TAG, {}, [new Text$2("<" + ph.tag + ">")]);
var startTagPh = new Tag(_PLACEHOLDER_TAG$2, { name: ph.startName }, [startEx]);
if (ph.isVoid) {
// void tags have no children nor closing tags
return [startTagPh];
}
var closeEx = new Tag(_EXEMPLE_TAG, {}, [new Text$2("" + ph.tag + ">")]);
var closeTagPh = new Tag(_PLACEHOLDER_TAG$2, { name: ph.closeName }, [closeEx]);
return Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])([startTagPh], this.serialize(ph.children), [closeTagPh]);
};
_Visitor.prototype.visitPlaceholder = function (ph, context) {
var exTag = new Tag(_EXEMPLE_TAG, {}, [new Text$2("{{" + ph.value + "}}")]);
return [new Tag(_PLACEHOLDER_TAG$2, { name: ph.name }, [exTag])];
};
_Visitor.prototype.visitIcuPlaceholder = function (ph, context) {
var exTag = new Tag(_EXEMPLE_TAG, {}, [
new Text$2("{" + ph.value.expression + ", " + ph.value.type + ", " + Object.keys(ph.value.cases).map(function (value) { return value + ' {...}'; }).join(' ') + "}")
]);
return [new Tag(_PLACEHOLDER_TAG$2, { name: ph.name }, [exTag])];
};
_Visitor.prototype.serialize = function (nodes) {
var _this = this;
return [].concat.apply([], Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(nodes.map(function (node) { return node.visit(_this); })));
};
return _Visitor;
}());
function digest$1(message) {
return decimalDigest(message);
}
// TC requires at least one non-empty example on placeholders
var ExampleVisitor = /** @class */ (function () {
function ExampleVisitor() {
}
ExampleVisitor.prototype.addDefaultExamples = function (node) {
node.visit(this);
return node;
};
ExampleVisitor.prototype.visitTag = function (tag) {
var _this = this;
if (tag.name === _PLACEHOLDER_TAG$2) {
if (!tag.children || tag.children.length == 0) {
var exText = new Text$2(tag.attrs['name'] || '...');
tag.children = [new Tag(_EXEMPLE_TAG, {}, [exText])];
}
}
else if (tag.children) {
tag.children.forEach(function (node) { return node.visit(_this); });
}
};
ExampleVisitor.prototype.visitText = function (text) { };
ExampleVisitor.prototype.visitDeclaration = function (decl) { };
ExampleVisitor.prototype.visitDoctype = function (doctype) { };
return ExampleVisitor;
}());
// XMB/XTB placeholders can only contain A-Z, 0-9 and _
function toPublicName(internalName) {
return internalName.toUpperCase().replace(/[^A-Z0-9_]/g, '_');
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var _TRANSLATIONS_TAG = 'translationbundle';
var _TRANSLATION_TAG = 'translation';
var _PLACEHOLDER_TAG$3 = 'ph';
var Xtb = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(Xtb, _super);
function Xtb() {
return _super !== null && _super.apply(this, arguments) || this;
}
Xtb.prototype.write = function (messages, locale) { throw new Error('Unsupported'); };
Xtb.prototype.load = function (content, url) {
// xtb to xml nodes
var xtbParser = new XtbParser();
var _a = xtbParser.parse(content, url), locale = _a.locale, msgIdToHtml = _a.msgIdToHtml, errors = _a.errors;
// xml nodes to i18n nodes
var i18nNodesByMsgId = {};
var converter = new XmlToI18n$2();
// Because we should be able to load xtb files that rely on features not supported by angular,
// we need to delay the conversion of html to i18n nodes so that non angular messages are not
// converted
Object.keys(msgIdToHtml).forEach(function (msgId) {
var valueFn = function () {
var _a = converter.convert(msgIdToHtml[msgId], url), i18nNodes = _a.i18nNodes, errors = _a.errors;
if (errors.length) {
throw new Error("xtb parse errors:\n" + errors.join('\n'));
}
return i18nNodes;
};
createLazyProperty(i18nNodesByMsgId, msgId, valueFn);
});
if (errors.length) {
throw new Error("xtb parse errors:\n" + errors.join('\n'));
}
return { locale: locale, i18nNodesByMsgId: i18nNodesByMsgId };
};
Xtb.prototype.digest = function (message) { return digest$1(message); };
Xtb.prototype.createNameMapper = function (message) {
return new SimplePlaceholderMapper(message, toPublicName);
};
return Xtb;
}(Serializer));
function createLazyProperty(messages, id, valueFn) {
Object.defineProperty(messages, id, {
configurable: true,
enumerable: true,
get: function () {
var value = valueFn();
Object.defineProperty(messages, id, { enumerable: true, value: value });
return value;
},
set: function (_) { throw new Error('Could not overwrite an XTB translation'); },
});
}
// Extract messages as xml nodes from the xtb file
var XtbParser = /** @class */ (function () {
function XtbParser() {
this._locale = null;
}
XtbParser.prototype.parse = function (xtb, url) {
this._bundleDepth = 0;
this._msgIdToHtml = {};
// We can not parse the ICU messages at this point as some messages might not originate
// from Angular that could not be lex'd.
var xml = new XmlParser().parse(xtb, url, false);
this._errors = xml.errors;
visitAll(this, xml.rootNodes);
return {
msgIdToHtml: this._msgIdToHtml,
errors: this._errors,
locale: this._locale,
};
};
XtbParser.prototype.visitElement = function (element, context) {
switch (element.name) {
case _TRANSLATIONS_TAG:
this._bundleDepth++;
if (this._bundleDepth > 1) {
this._addError(element, "<" + _TRANSLATIONS_TAG + "> elements can not be nested");
}
var langAttr = element.attrs.find(function (attr) { return attr.name === 'lang'; });
if (langAttr) {
this._locale = langAttr.value;
}
visitAll(this, element.children, null);
this._bundleDepth--;
break;
case _TRANSLATION_TAG:
var idAttr = element.attrs.find(function (attr) { return attr.name === 'id'; });
if (!idAttr) {
this._addError(element, "<" + _TRANSLATION_TAG + "> misses the \"id\" attribute");
}
else {
var id = idAttr.value;
if (this._msgIdToHtml.hasOwnProperty(id)) {
this._addError(element, "Duplicated translations for msg " + id);
}
else {
var innerTextStart = element.startSourceSpan.end.offset;
var innerTextEnd = element.endSourceSpan.start.offset;
var content = element.startSourceSpan.start.file.content;
var innerText = content.slice(innerTextStart, innerTextEnd);
this._msgIdToHtml[id] = innerText;
}
}
break;
default:
this._addError(element, 'Unexpected tag');
}
};
XtbParser.prototype.visitAttribute = function (attribute, context) { };
XtbParser.prototype.visitText = function (text, context) { };
XtbParser.prototype.visitComment = function (comment, context) { };
XtbParser.prototype.visitExpansion = function (expansion, context) { };
XtbParser.prototype.visitExpansionCase = function (expansionCase, context) { };
XtbParser.prototype._addError = function (node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
};
return XtbParser;
}());
// Convert ml nodes (xtb syntax) to i18n nodes
var XmlToI18n$2 = /** @class */ (function () {
function XmlToI18n() {
}
XmlToI18n.prototype.convert = function (message, url) {
var xmlIcu = new XmlParser().parse(message, url, true);
this._errors = xmlIcu.errors;
var i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
[] :
visitAll(this, xmlIcu.rootNodes);
return {
i18nNodes: i18nNodes,
errors: this._errors,
};
};
XmlToI18n.prototype.visitText = function (text, context) { return new Text$1(text.value, text.sourceSpan); };
XmlToI18n.prototype.visitExpansion = function (icu, context) {
var caseMap = {};
visitAll(this, icu.cases).forEach(function (c) {
caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
});
return new Icu(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
};
XmlToI18n.prototype.visitExpansionCase = function (icuCase, context) {
return {
value: icuCase.value,
nodes: visitAll(this, icuCase.expression),
};
};
XmlToI18n.prototype.visitElement = function (el, context) {
if (el.name === _PLACEHOLDER_TAG$3) {
var nameAttr = el.attrs.find(function (attr) { return attr.name === 'name'; });
if (nameAttr) {
return new Placeholder('', nameAttr.value, el.sourceSpan);
}
this._addError(el, "<" + _PLACEHOLDER_TAG$3 + "> misses the \"name\" attribute");
}
else {
this._addError(el, "Unexpected tag");
}
return null;
};
XmlToI18n.prototype.visitComment = function (comment, context) { };
XmlToI18n.prototype.visitAttribute = function (attribute, context) { };
XmlToI18n.prototype._addError = function (node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
};
return XmlToI18n;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var HtmlParser = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(HtmlParser, _super);
function HtmlParser() {
return _super.call(this, getHtmlTagDefinition) || this;
}
HtmlParser.prototype.parse = function (source, url, parseExpansionForms, interpolationConfig) {
if (parseExpansionForms === void 0) { parseExpansionForms = false; }
if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
return _super.prototype.parse.call(this, source, url, parseExpansionForms, interpolationConfig);
};
return HtmlParser;
}(Parser$1));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A container for translated messages
*/
var TranslationBundle = /** @class */ (function () {
function TranslationBundle(_i18nNodesByMsgId, locale, digest, mapperFactory, missingTranslationStrategy, console) {
if (_i18nNodesByMsgId === void 0) { _i18nNodesByMsgId = {}; }
if (missingTranslationStrategy === void 0) { missingTranslationStrategy = MissingTranslationStrategy.Warning; }
this._i18nNodesByMsgId = _i18nNodesByMsgId;
this.digest = digest;
this.mapperFactory = mapperFactory;
this._i18nToHtml = new I18nToHtmlVisitor(_i18nNodesByMsgId, locale, digest, mapperFactory, missingTranslationStrategy, console);
}
// Creates a `TranslationBundle` by parsing the given `content` with the `serializer`.
TranslationBundle.load = function (content, url, serializer, missingTranslationStrategy, console) {
var _a = serializer.load(content, url), locale = _a.locale, i18nNodesByMsgId = _a.i18nNodesByMsgId;
var digestFn = function (m) { return serializer.digest(m); };
var mapperFactory = function (m) { return serializer.createNameMapper(m); };
return new TranslationBundle(i18nNodesByMsgId, locale, digestFn, mapperFactory, missingTranslationStrategy, console);
};
// Returns the translation as HTML nodes from the given source message.
TranslationBundle.prototype.get = function (srcMsg) {
var html = this._i18nToHtml.convert(srcMsg);
if (html.errors.length) {
throw new Error(html.errors.join('\n'));
}
return html.nodes;
};
TranslationBundle.prototype.has = function (srcMsg) { return this.digest(srcMsg) in this._i18nNodesByMsgId; };
return TranslationBundle;
}());
var I18nToHtmlVisitor = /** @class */ (function () {
function I18nToHtmlVisitor(_i18nNodesByMsgId, _locale, _digest, _mapperFactory, _missingTranslationStrategy, _console) {
if (_i18nNodesByMsgId === void 0) { _i18nNodesByMsgId = {}; }
this._i18nNodesByMsgId = _i18nNodesByMsgId;
this._locale = _locale;
this._digest = _digest;
this._mapperFactory = _mapperFactory;
this._missingTranslationStrategy = _missingTranslationStrategy;
this._console = _console;
this._contextStack = [];
this._errors = [];
}
I18nToHtmlVisitor.prototype.convert = function (srcMsg) {
this._contextStack.length = 0;
this._errors.length = 0;
// i18n to text
var text = this._convertToText(srcMsg);
// text to html
var url = srcMsg.nodes[0].sourceSpan.start.file.url;
var html = new HtmlParser().parse(text, url, true);
return {
nodes: html.rootNodes,
errors: Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(this._errors, html.errors),
};
};
I18nToHtmlVisitor.prototype.visitText = function (text, context) {
// `convert()` uses an `HtmlParser` to return `html.Node`s
// we should then make sure that any special characters are escaped
return escapeXml(text.value);
};
I18nToHtmlVisitor.prototype.visitContainer = function (container, context) {
var _this = this;
return container.children.map(function (n) { return n.visit(_this); }).join('');
};
I18nToHtmlVisitor.prototype.visitIcu = function (icu, context) {
var _this = this;
var cases = Object.keys(icu.cases).map(function (k) { return k + " {" + icu.cases[k].visit(_this) + "}"; });
// TODO(vicb): Once all format switch to using expression placeholders
// we should throw when the placeholder is not in the source message
var exp = this._srcMsg.placeholders.hasOwnProperty(icu.expression) ?
this._srcMsg.placeholders[icu.expression] :
icu.expression;
return "{" + exp + ", " + icu.type + ", " + cases.join(' ') + "}";
};
I18nToHtmlVisitor.prototype.visitPlaceholder = function (ph, context) {
var phName = this._mapper(ph.name);
if (this._srcMsg.placeholders.hasOwnProperty(phName)) {
return this._srcMsg.placeholders[phName];
}
if (this._srcMsg.placeholderToMessage.hasOwnProperty(phName)) {
return this._convertToText(this._srcMsg.placeholderToMessage[phName]);
}
this._addError(ph, "Unknown placeholder \"" + ph.name + "\"");
return '';
};
// Loaded message contains only placeholders (vs tag and icu placeholders).
// However when a translation can not be found, we need to serialize the source message
// which can contain tag placeholders
I18nToHtmlVisitor.prototype.visitTagPlaceholder = function (ph, context) {
var _this = this;
var tag = "" + ph.tag;
var attrs = Object.keys(ph.attrs).map(function (name) { return name + "=\"" + ph.attrs[name] + "\""; }).join(' ');
if (ph.isVoid) {
return "<" + tag + " " + attrs + "/>";
}
var children = ph.children.map(function (c) { return c.visit(_this); }).join('');
return "<" + tag + " " + attrs + ">" + children + "" + tag + ">";
};
// Loaded message contains only placeholders (vs tag and icu placeholders).
// However when a translation can not be found, we need to serialize the source message
// which can contain tag placeholders
I18nToHtmlVisitor.prototype.visitIcuPlaceholder = function (ph, context) {
// An ICU placeholder references the source message to be serialized
return this._convertToText(this._srcMsg.placeholderToMessage[ph.name]);
};
/**
* Convert a source message to a translated text string:
* - text nodes are replaced with their translation,
* - placeholders are replaced with their content,
* - ICU nodes are converted to ICU expressions.
*/
I18nToHtmlVisitor.prototype._convertToText = function (srcMsg) {
var _this = this;
var id = this._digest(srcMsg);
var mapper = this._mapperFactory ? this._mapperFactory(srcMsg) : null;
var nodes;
this._contextStack.push({ msg: this._srcMsg, mapper: this._mapper });
this._srcMsg = srcMsg;
if (this._i18nNodesByMsgId.hasOwnProperty(id)) {
// When there is a translation use its nodes as the source
// And create a mapper to convert serialized placeholder names to internal names
nodes = this._i18nNodesByMsgId[id];
this._mapper = function (name) { return mapper ? mapper.toInternalName(name) : name; };
}
else {
// When no translation has been found
// - report an error / a warning / nothing,
// - use the nodes from the original message
// - placeholders are already internal and need no mapper
if (this._missingTranslationStrategy === MissingTranslationStrategy.Error) {
var ctx = this._locale ? " for locale \"" + this._locale + "\"" : '';
this._addError(srcMsg.nodes[0], "Missing translation for message \"" + id + "\"" + ctx);
}
else if (this._console &&
this._missingTranslationStrategy === MissingTranslationStrategy.Warning) {
var ctx = this._locale ? " for locale \"" + this._locale + "\"" : '';
this._console.warn("Missing translation for message \"" + id + "\"" + ctx);
}
nodes = srcMsg.nodes;
this._mapper = function (name) { return name; };
}
var text = nodes.map(function (node) { return node.visit(_this); }).join('');
var context = this._contextStack.pop();
this._srcMsg = context.msg;
this._mapper = context.mapper;
return text;
};
I18nToHtmlVisitor.prototype._addError = function (el, msg) {
this._errors.push(new I18nError(el.sourceSpan, msg));
};
return I18nToHtmlVisitor;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var I18NHtmlParser = /** @class */ (function () {
function I18NHtmlParser(_htmlParser, translations, translationsFormat, missingTranslation, console) {
if (missingTranslation === void 0) { missingTranslation = MissingTranslationStrategy.Warning; }
this._htmlParser = _htmlParser;
if (translations) {
var serializer = createSerializer(translationsFormat);
this._translationBundle =
TranslationBundle.load(translations, 'i18n', serializer, missingTranslation, console);
}
else {
this._translationBundle =
new TranslationBundle({}, null, digest, undefined, missingTranslation, console);
}
}
I18NHtmlParser.prototype.parse = function (source, url, parseExpansionForms, interpolationConfig) {
if (parseExpansionForms === void 0) { parseExpansionForms = false; }
if (interpolationConfig === void 0) { interpolationConfig = DEFAULT_INTERPOLATION_CONFIG; }
var parseResult = this._htmlParser.parse(source, url, parseExpansionForms, interpolationConfig);
if (parseResult.errors.length) {
return new ParseTreeResult(parseResult.rootNodes, parseResult.errors);
}
return mergeTranslations(parseResult.rootNodes, this._translationBundle, interpolationConfig, [], {});
};
return I18NHtmlParser;
}());
function createSerializer(format) {
format = (format || 'xlf').toLowerCase();
switch (format) {
case 'xmb':
return new Xmb();
case 'xtb':
return new Xtb();
case 'xliff2':
case 'xlf2':
return new Xliff2();
case 'xliff':
case 'xlf':
default:
return new Xliff();
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var CORE = '@angular/core';
var Identifiers = /** @class */ (function () {
function Identifiers() {
}
Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS = {
name: 'ANALYZE_FOR_ENTRY_COMPONENTS',
moduleName: CORE,
};
Identifiers.ElementRef = { name: 'ElementRef', moduleName: CORE };
Identifiers.NgModuleRef = { name: 'NgModuleRef', moduleName: CORE };
Identifiers.ViewContainerRef = { name: 'ViewContainerRef', moduleName: CORE };
Identifiers.ChangeDetectorRef = {
name: 'ChangeDetectorRef',
moduleName: CORE,
};
Identifiers.QueryList = { name: 'QueryList', moduleName: CORE };
Identifiers.TemplateRef = { name: 'TemplateRef', moduleName: CORE };
Identifiers.CodegenComponentFactoryResolver = {
name: 'ɵCodegenComponentFactoryResolver',
moduleName: CORE,
};
Identifiers.ComponentFactoryResolver = {
name: 'ComponentFactoryResolver',
moduleName: CORE,
};
Identifiers.ComponentFactory = { name: 'ComponentFactory', moduleName: CORE };
Identifiers.ComponentRef = { name: 'ComponentRef', moduleName: CORE };
Identifiers.NgModuleFactory = { name: 'NgModuleFactory', moduleName: CORE };
Identifiers.createModuleFactory = {
name: 'ɵcmf',
moduleName: CORE,
};
Identifiers.moduleDef = {
name: 'ɵmod',
moduleName: CORE,
};
Identifiers.moduleProviderDef = {
name: 'ɵmpd',
moduleName: CORE,
};
Identifiers.RegisterModuleFactoryFn = {
name: 'ɵregisterModuleFactory',
moduleName: CORE,
};
Identifiers.inject = { name: 'inject', moduleName: CORE };
Identifiers.INJECTOR = { name: 'INJECTOR', moduleName: CORE };
Identifiers.Injector = { name: 'Injector', moduleName: CORE };
Identifiers.defineInjectable = { name: 'defineInjectable', moduleName: CORE };
Identifiers.ViewEncapsulation = {
name: 'ViewEncapsulation',
moduleName: CORE,
};
Identifiers.ChangeDetectionStrategy = {
name: 'ChangeDetectionStrategy',
moduleName: CORE,
};
Identifiers.SecurityContext = {
name: 'SecurityContext',
moduleName: CORE,
};
Identifiers.LOCALE_ID = { name: 'LOCALE_ID', moduleName: CORE };
Identifiers.TRANSLATIONS_FORMAT = {
name: 'TRANSLATIONS_FORMAT',
moduleName: CORE,
};
Identifiers.inlineInterpolate = {
name: 'ɵinlineInterpolate',
moduleName: CORE,
};
Identifiers.interpolate = { name: 'ɵinterpolate', moduleName: CORE };
Identifiers.EMPTY_ARRAY = { name: 'ɵEMPTY_ARRAY', moduleName: CORE };
Identifiers.EMPTY_MAP = { name: 'ɵEMPTY_MAP', moduleName: CORE };
Identifiers.Renderer = { name: 'Renderer', moduleName: CORE };
Identifiers.viewDef = { name: 'ɵvid', moduleName: CORE };
Identifiers.elementDef = { name: 'ɵeld', moduleName: CORE };
Identifiers.anchorDef = { name: 'ɵand', moduleName: CORE };
Identifiers.textDef = { name: 'ɵted', moduleName: CORE };
Identifiers.directiveDef = { name: 'ɵdid', moduleName: CORE };
Identifiers.providerDef = { name: 'ɵprd', moduleName: CORE };
Identifiers.queryDef = { name: 'ɵqud', moduleName: CORE };
Identifiers.pureArrayDef = { name: 'ɵpad', moduleName: CORE };
Identifiers.pureObjectDef = { name: 'ɵpod', moduleName: CORE };
Identifiers.purePipeDef = { name: 'ɵppd', moduleName: CORE };
Identifiers.pipeDef = { name: 'ɵpid', moduleName: CORE };
Identifiers.nodeValue = { name: 'ɵnov', moduleName: CORE };
Identifiers.ngContentDef = { name: 'ɵncd', moduleName: CORE };
Identifiers.unwrapValue = { name: 'ɵunv', moduleName: CORE };
Identifiers.createRendererType2 = { name: 'ɵcrt', moduleName: CORE };
// type only
Identifiers.RendererType2 = {
name: 'RendererType2',
moduleName: CORE,
};
// type only
Identifiers.ViewDefinition = {
name: 'ɵViewDefinition',
moduleName: CORE,
};
Identifiers.createComponentFactory = { name: 'ɵccf', moduleName: CORE };
return Identifiers;
}());
function createTokenForReference(reference) {
return { identifier: { reference: reference } };
}
function createTokenForExternalReference(reflector, reference) {
return createTokenForReference(reflector.resolveExternalReference(reference));
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
//// Types
var TypeModifier;
(function (TypeModifier) {
TypeModifier[TypeModifier["Const"] = 0] = "Const";
})(TypeModifier || (TypeModifier = {}));
var Type$1 = /** @class */ (function () {
function Type(modifiers) {
if (modifiers === void 0) { modifiers = null; }
this.modifiers = modifiers;
if (!modifiers) {
this.modifiers = [];
}
}
Type.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; };
return Type;
}());
var BuiltinTypeName;
(function (BuiltinTypeName) {
BuiltinTypeName[BuiltinTypeName["Dynamic"] = 0] = "Dynamic";
BuiltinTypeName[BuiltinTypeName["Bool"] = 1] = "Bool";
BuiltinTypeName[BuiltinTypeName["String"] = 2] = "String";
BuiltinTypeName[BuiltinTypeName["Int"] = 3] = "Int";
BuiltinTypeName[BuiltinTypeName["Number"] = 4] = "Number";
BuiltinTypeName[BuiltinTypeName["Function"] = 5] = "Function";
BuiltinTypeName[BuiltinTypeName["Inferred"] = 6] = "Inferred";
})(BuiltinTypeName || (BuiltinTypeName = {}));
var BuiltinType = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(BuiltinType, _super);
function BuiltinType(name, modifiers) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, modifiers) || this;
_this.name = name;
return _this;
}
BuiltinType.prototype.visitType = function (visitor, context) {
return visitor.visitBuiltinType(this, context);
};
return BuiltinType;
}(Type$1));
var ExpressionType = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ExpressionType, _super);
function ExpressionType(value, modifiers) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, modifiers) || this;
_this.value = value;
return _this;
}
ExpressionType.prototype.visitType = function (visitor, context) {
return visitor.visitExpressionType(this, context);
};
return ExpressionType;
}(Type$1));
var ArrayType = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ArrayType, _super);
function ArrayType(of, modifiers) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, modifiers) || this;
_this.of = of;
return _this;
}
ArrayType.prototype.visitType = function (visitor, context) {
return visitor.visitArrayType(this, context);
};
return ArrayType;
}(Type$1));
var MapType = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(MapType, _super);
function MapType(valueType, modifiers) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, modifiers) || this;
_this.valueType = valueType || null;
return _this;
}
MapType.prototype.visitType = function (visitor, context) { return visitor.visitMapType(this, context); };
return MapType;
}(Type$1));
var DYNAMIC_TYPE = new BuiltinType(BuiltinTypeName.Dynamic);
var INFERRED_TYPE = new BuiltinType(BuiltinTypeName.Inferred);
var BOOL_TYPE = new BuiltinType(BuiltinTypeName.Bool);
var INT_TYPE = new BuiltinType(BuiltinTypeName.Int);
var NUMBER_TYPE = new BuiltinType(BuiltinTypeName.Number);
var STRING_TYPE = new BuiltinType(BuiltinTypeName.String);
var FUNCTION_TYPE = new BuiltinType(BuiltinTypeName.Function);
///// Expressions
var BinaryOperator;
(function (BinaryOperator) {
BinaryOperator[BinaryOperator["Equals"] = 0] = "Equals";
BinaryOperator[BinaryOperator["NotEquals"] = 1] = "NotEquals";
BinaryOperator[BinaryOperator["Identical"] = 2] = "Identical";
BinaryOperator[BinaryOperator["NotIdentical"] = 3] = "NotIdentical";
BinaryOperator[BinaryOperator["Minus"] = 4] = "Minus";
BinaryOperator[BinaryOperator["Plus"] = 5] = "Plus";
BinaryOperator[BinaryOperator["Divide"] = 6] = "Divide";
BinaryOperator[BinaryOperator["Multiply"] = 7] = "Multiply";
BinaryOperator[BinaryOperator["Modulo"] = 8] = "Modulo";
BinaryOperator[BinaryOperator["And"] = 9] = "And";
BinaryOperator[BinaryOperator["Or"] = 10] = "Or";
BinaryOperator[BinaryOperator["BitwiseAnd"] = 11] = "BitwiseAnd";
BinaryOperator[BinaryOperator["Lower"] = 12] = "Lower";
BinaryOperator[BinaryOperator["LowerEquals"] = 13] = "LowerEquals";
BinaryOperator[BinaryOperator["Bigger"] = 14] = "Bigger";
BinaryOperator[BinaryOperator["BiggerEquals"] = 15] = "BiggerEquals";
})(BinaryOperator || (BinaryOperator = {}));
function nullSafeIsEquivalent(base, other) {
if (base == null || other == null) {
return base == other;
}
return base.isEquivalent(other);
}
function areAllEquivalent(base, other) {
var len = base.length;
if (len !== other.length) {
return false;
}
for (var i = 0; i < len; i++) {
if (!base[i].isEquivalent(other[i])) {
return false;
}
}
return true;
}
var Expression = /** @class */ (function () {
function Expression(type, sourceSpan) {
this.type = type || null;
this.sourceSpan = sourceSpan || null;
}
Expression.prototype.prop = function (name, sourceSpan) {
return new ReadPropExpr(this, name, null, sourceSpan);
};
Expression.prototype.key = function (index, type, sourceSpan) {
return new ReadKeyExpr(this, index, type, sourceSpan);
};
Expression.prototype.callMethod = function (name, params, sourceSpan) {
return new InvokeMethodExpr(this, name, params, null, sourceSpan);
};
Expression.prototype.callFn = function (params, sourceSpan) {
return new InvokeFunctionExpr(this, params, null, sourceSpan);
};
Expression.prototype.instantiate = function (params, type, sourceSpan) {
return new InstantiateExpr(this, params, type, sourceSpan);
};
Expression.prototype.conditional = function (trueCase, falseCase, sourceSpan) {
if (falseCase === void 0) { falseCase = null; }
return new ConditionalExpr(this, trueCase, falseCase, null, sourceSpan);
};
Expression.prototype.equals = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Equals, this, rhs, null, sourceSpan);
};
Expression.prototype.notEquals = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.NotEquals, this, rhs, null, sourceSpan);
};
Expression.prototype.identical = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Identical, this, rhs, null, sourceSpan);
};
Expression.prototype.notIdentical = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.NotIdentical, this, rhs, null, sourceSpan);
};
Expression.prototype.minus = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Minus, this, rhs, null, sourceSpan);
};
Expression.prototype.plus = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Plus, this, rhs, null, sourceSpan);
};
Expression.prototype.divide = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Divide, this, rhs, null, sourceSpan);
};
Expression.prototype.multiply = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Multiply, this, rhs, null, sourceSpan);
};
Expression.prototype.modulo = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Modulo, this, rhs, null, sourceSpan);
};
Expression.prototype.and = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.And, this, rhs, null, sourceSpan);
};
Expression.prototype.bitwiseAnd = function (rhs, sourceSpan, parens) {
if (parens === void 0) { parens = true; }
return new BinaryOperatorExpr(BinaryOperator.BitwiseAnd, this, rhs, null, sourceSpan, parens);
};
Expression.prototype.or = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Or, this, rhs, null, sourceSpan);
};
Expression.prototype.lower = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Lower, this, rhs, null, sourceSpan);
};
Expression.prototype.lowerEquals = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.LowerEquals, this, rhs, null, sourceSpan);
};
Expression.prototype.bigger = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Bigger, this, rhs, null, sourceSpan);
};
Expression.prototype.biggerEquals = function (rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.BiggerEquals, this, rhs, null, sourceSpan);
};
Expression.prototype.isBlank = function (sourceSpan) {
// Note: We use equals by purpose here to compare to null and undefined in JS.
// We use the typed null to allow strictNullChecks to narrow types.
return this.equals(TYPED_NULL_EXPR, sourceSpan);
};
Expression.prototype.cast = function (type, sourceSpan) {
return new CastExpr(this, type, sourceSpan);
};
Expression.prototype.toStmt = function () { return new ExpressionStatement(this, null); };
return Expression;
}());
var BuiltinVar;
(function (BuiltinVar) {
BuiltinVar[BuiltinVar["This"] = 0] = "This";
BuiltinVar[BuiltinVar["Super"] = 1] = "Super";
BuiltinVar[BuiltinVar["CatchError"] = 2] = "CatchError";
BuiltinVar[BuiltinVar["CatchStack"] = 3] = "CatchStack";
})(BuiltinVar || (BuiltinVar = {}));
var ReadVarExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ReadVarExpr, _super);
function ReadVarExpr(name, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
if (typeof name === 'string') {
_this.name = name;
_this.builtin = null;
}
else {
_this.name = null;
_this.builtin = name;
}
return _this;
}
ReadVarExpr.prototype.isEquivalent = function (e) {
return e instanceof ReadVarExpr && this.name === e.name && this.builtin === e.builtin;
};
ReadVarExpr.prototype.isConstant = function () { return false; };
ReadVarExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitReadVarExpr(this, context);
};
ReadVarExpr.prototype.set = function (value) {
if (!this.name) {
throw new Error("Built in variable " + this.builtin + " can not be assigned to.");
}
return new WriteVarExpr(this.name, value, null, this.sourceSpan);
};
return ReadVarExpr;
}(Expression));
var WriteVarExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(WriteVarExpr, _super);
function WriteVarExpr(name, value, type, sourceSpan) {
var _this = _super.call(this, type || value.type, sourceSpan) || this;
_this.name = name;
_this.value = value;
return _this;
}
WriteVarExpr.prototype.isEquivalent = function (e) {
return e instanceof WriteVarExpr && this.name === e.name && this.value.isEquivalent(e.value);
};
WriteVarExpr.prototype.isConstant = function () { return false; };
WriteVarExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitWriteVarExpr(this, context);
};
WriteVarExpr.prototype.toDeclStmt = function (type, modifiers) {
return new DeclareVarStmt(this.name, this.value, type, modifiers, this.sourceSpan);
};
return WriteVarExpr;
}(Expression));
var WriteKeyExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(WriteKeyExpr, _super);
function WriteKeyExpr(receiver, index, value, type, sourceSpan) {
var _this = _super.call(this, type || value.type, sourceSpan) || this;
_this.receiver = receiver;
_this.index = index;
_this.value = value;
return _this;
}
WriteKeyExpr.prototype.isEquivalent = function (e) {
return e instanceof WriteKeyExpr && this.receiver.isEquivalent(e.receiver) &&
this.index.isEquivalent(e.index) && this.value.isEquivalent(e.value);
};
WriteKeyExpr.prototype.isConstant = function () { return false; };
WriteKeyExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitWriteKeyExpr(this, context);
};
return WriteKeyExpr;
}(Expression));
var WritePropExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(WritePropExpr, _super);
function WritePropExpr(receiver, name, value, type, sourceSpan) {
var _this = _super.call(this, type || value.type, sourceSpan) || this;
_this.receiver = receiver;
_this.name = name;
_this.value = value;
return _this;
}
WritePropExpr.prototype.isEquivalent = function (e) {
return e instanceof WritePropExpr && this.receiver.isEquivalent(e.receiver) &&
this.name === e.name && this.value.isEquivalent(e.value);
};
WritePropExpr.prototype.isConstant = function () { return false; };
WritePropExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitWritePropExpr(this, context);
};
return WritePropExpr;
}(Expression));
var BuiltinMethod;
(function (BuiltinMethod) {
BuiltinMethod[BuiltinMethod["ConcatArray"] = 0] = "ConcatArray";
BuiltinMethod[BuiltinMethod["SubscribeObservable"] = 1] = "SubscribeObservable";
BuiltinMethod[BuiltinMethod["Bind"] = 2] = "Bind";
})(BuiltinMethod || (BuiltinMethod = {}));
var InvokeMethodExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(InvokeMethodExpr, _super);
function InvokeMethodExpr(receiver, method, args, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.receiver = receiver;
_this.args = args;
if (typeof method === 'string') {
_this.name = method;
_this.builtin = null;
}
else {
_this.name = null;
_this.builtin = method;
}
return _this;
}
InvokeMethodExpr.prototype.isEquivalent = function (e) {
return e instanceof InvokeMethodExpr && this.receiver.isEquivalent(e.receiver) &&
this.name === e.name && this.builtin === e.builtin && areAllEquivalent(this.args, e.args);
};
InvokeMethodExpr.prototype.isConstant = function () { return false; };
InvokeMethodExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitInvokeMethodExpr(this, context);
};
return InvokeMethodExpr;
}(Expression));
var InvokeFunctionExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(InvokeFunctionExpr, _super);
function InvokeFunctionExpr(fn, args, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.fn = fn;
_this.args = args;
return _this;
}
InvokeFunctionExpr.prototype.isEquivalent = function (e) {
return e instanceof InvokeFunctionExpr && this.fn.isEquivalent(e.fn) &&
areAllEquivalent(this.args, e.args);
};
InvokeFunctionExpr.prototype.isConstant = function () { return false; };
InvokeFunctionExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitInvokeFunctionExpr(this, context);
};
return InvokeFunctionExpr;
}(Expression));
var InstantiateExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(InstantiateExpr, _super);
function InstantiateExpr(classExpr, args, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.classExpr = classExpr;
_this.args = args;
return _this;
}
InstantiateExpr.prototype.isEquivalent = function (e) {
return e instanceof InstantiateExpr && this.classExpr.isEquivalent(e.classExpr) &&
areAllEquivalent(this.args, e.args);
};
InstantiateExpr.prototype.isConstant = function () { return false; };
InstantiateExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitInstantiateExpr(this, context);
};
return InstantiateExpr;
}(Expression));
var LiteralExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(LiteralExpr, _super);
function LiteralExpr(value, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.value = value;
return _this;
}
LiteralExpr.prototype.isEquivalent = function (e) {
return e instanceof LiteralExpr && this.value === e.value;
};
LiteralExpr.prototype.isConstant = function () { return true; };
LiteralExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitLiteralExpr(this, context);
};
return LiteralExpr;
}(Expression));
var ExternalExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ExternalExpr, _super);
function ExternalExpr(value, type, typeParams, sourceSpan) {
if (typeParams === void 0) { typeParams = null; }
var _this = _super.call(this, type, sourceSpan) || this;
_this.value = value;
_this.typeParams = typeParams;
return _this;
}
ExternalExpr.prototype.isEquivalent = function (e) {
return e instanceof ExternalExpr && this.value.name === e.value.name &&
this.value.moduleName === e.value.moduleName && this.value.runtime === e.value.runtime;
};
ExternalExpr.prototype.isConstant = function () { return false; };
ExternalExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitExternalExpr(this, context);
};
return ExternalExpr;
}(Expression));
var ExternalReference = /** @class */ (function () {
function ExternalReference(moduleName, name, runtime) {
this.moduleName = moduleName;
this.name = name;
this.runtime = runtime;
}
return ExternalReference;
}());
var ConditionalExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ConditionalExpr, _super);
function ConditionalExpr(condition, trueCase, falseCase, type, sourceSpan) {
if (falseCase === void 0) { falseCase = null; }
var _this = _super.call(this, type || trueCase.type, sourceSpan) || this;
_this.condition = condition;
_this.falseCase = falseCase;
_this.trueCase = trueCase;
return _this;
}
ConditionalExpr.prototype.isEquivalent = function (e) {
return e instanceof ConditionalExpr && this.condition.isEquivalent(e.condition) &&
this.trueCase.isEquivalent(e.trueCase) && nullSafeIsEquivalent(this.falseCase, e.falseCase);
};
ConditionalExpr.prototype.isConstant = function () { return false; };
ConditionalExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitConditionalExpr(this, context);
};
return ConditionalExpr;
}(Expression));
var NotExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(NotExpr, _super);
function NotExpr(condition, sourceSpan) {
var _this = _super.call(this, BOOL_TYPE, sourceSpan) || this;
_this.condition = condition;
return _this;
}
NotExpr.prototype.isEquivalent = function (e) {
return e instanceof NotExpr && this.condition.isEquivalent(e.condition);
};
NotExpr.prototype.isConstant = function () { return false; };
NotExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitNotExpr(this, context);
};
return NotExpr;
}(Expression));
var AssertNotNull = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(AssertNotNull, _super);
function AssertNotNull(condition, sourceSpan) {
var _this = _super.call(this, condition.type, sourceSpan) || this;
_this.condition = condition;
return _this;
}
AssertNotNull.prototype.isEquivalent = function (e) {
return e instanceof AssertNotNull && this.condition.isEquivalent(e.condition);
};
AssertNotNull.prototype.isConstant = function () { return false; };
AssertNotNull.prototype.visitExpression = function (visitor, context) {
return visitor.visitAssertNotNullExpr(this, context);
};
return AssertNotNull;
}(Expression));
var CastExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(CastExpr, _super);
function CastExpr(value, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.value = value;
return _this;
}
CastExpr.prototype.isEquivalent = function (e) {
return e instanceof CastExpr && this.value.isEquivalent(e.value);
};
CastExpr.prototype.isConstant = function () { return false; };
CastExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitCastExpr(this, context);
};
return CastExpr;
}(Expression));
var FnParam = /** @class */ (function () {
function FnParam(name, type) {
if (type === void 0) { type = null; }
this.name = name;
this.type = type;
}
FnParam.prototype.isEquivalent = function (param) { return this.name === param.name; };
return FnParam;
}());
var FunctionExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(FunctionExpr, _super);
function FunctionExpr(params, statements, type, sourceSpan, name) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.params = params;
_this.statements = statements;
_this.name = name;
return _this;
}
FunctionExpr.prototype.isEquivalent = function (e) {
return e instanceof FunctionExpr && areAllEquivalent(this.params, e.params) &&
areAllEquivalent(this.statements, e.statements);
};
FunctionExpr.prototype.isConstant = function () { return false; };
FunctionExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitFunctionExpr(this, context);
};
FunctionExpr.prototype.toDeclStmt = function (name, modifiers) {
if (modifiers === void 0) { modifiers = null; }
return new DeclareFunctionStmt(name, this.params, this.statements, this.type, modifiers, this.sourceSpan);
};
return FunctionExpr;
}(Expression));
var BinaryOperatorExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(BinaryOperatorExpr, _super);
function BinaryOperatorExpr(operator, lhs, rhs, type, sourceSpan, parens) {
if (parens === void 0) { parens = true; }
var _this = _super.call(this, type || lhs.type, sourceSpan) || this;
_this.operator = operator;
_this.rhs = rhs;
_this.parens = parens;
_this.lhs = lhs;
return _this;
}
BinaryOperatorExpr.prototype.isEquivalent = function (e) {
return e instanceof BinaryOperatorExpr && this.operator === e.operator &&
this.lhs.isEquivalent(e.lhs) && this.rhs.isEquivalent(e.rhs);
};
BinaryOperatorExpr.prototype.isConstant = function () { return false; };
BinaryOperatorExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitBinaryOperatorExpr(this, context);
};
return BinaryOperatorExpr;
}(Expression));
var ReadPropExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ReadPropExpr, _super);
function ReadPropExpr(receiver, name, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.receiver = receiver;
_this.name = name;
return _this;
}
ReadPropExpr.prototype.isEquivalent = function (e) {
return e instanceof ReadPropExpr && this.receiver.isEquivalent(e.receiver) &&
this.name === e.name;
};
ReadPropExpr.prototype.isConstant = function () { return false; };
ReadPropExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitReadPropExpr(this, context);
};
ReadPropExpr.prototype.set = function (value) {
return new WritePropExpr(this.receiver, this.name, value, null, this.sourceSpan);
};
return ReadPropExpr;
}(Expression));
var ReadKeyExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ReadKeyExpr, _super);
function ReadKeyExpr(receiver, index, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.receiver = receiver;
_this.index = index;
return _this;
}
ReadKeyExpr.prototype.isEquivalent = function (e) {
return e instanceof ReadKeyExpr && this.receiver.isEquivalent(e.receiver) &&
this.index.isEquivalent(e.index);
};
ReadKeyExpr.prototype.isConstant = function () { return false; };
ReadKeyExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitReadKeyExpr(this, context);
};
ReadKeyExpr.prototype.set = function (value) {
return new WriteKeyExpr(this.receiver, this.index, value, null, this.sourceSpan);
};
return ReadKeyExpr;
}(Expression));
var LiteralArrayExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(LiteralArrayExpr, _super);
function LiteralArrayExpr(entries, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.entries = entries;
return _this;
}
LiteralArrayExpr.prototype.isConstant = function () { return this.entries.every(function (e) { return e.isConstant(); }); };
LiteralArrayExpr.prototype.isEquivalent = function (e) {
return e instanceof LiteralArrayExpr && areAllEquivalent(this.entries, e.entries);
};
LiteralArrayExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitLiteralArrayExpr(this, context);
};
return LiteralArrayExpr;
}(Expression));
var LiteralMapEntry = /** @class */ (function () {
function LiteralMapEntry(key, value, quoted) {
this.key = key;
this.value = value;
this.quoted = quoted;
}
LiteralMapEntry.prototype.isEquivalent = function (e) {
return this.key === e.key && this.value.isEquivalent(e.value);
};
return LiteralMapEntry;
}());
var LiteralMapExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(LiteralMapExpr, _super);
function LiteralMapExpr(entries, type, sourceSpan) {
var _this = _super.call(this, type, sourceSpan) || this;
_this.entries = entries;
_this.valueType = null;
if (type) {
_this.valueType = type.valueType;
}
return _this;
}
LiteralMapExpr.prototype.isEquivalent = function (e) {
return e instanceof LiteralMapExpr && areAllEquivalent(this.entries, e.entries);
};
LiteralMapExpr.prototype.isConstant = function () { return this.entries.every(function (e) { return e.value.isConstant(); }); };
LiteralMapExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitLiteralMapExpr(this, context);
};
return LiteralMapExpr;
}(Expression));
var CommaExpr = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(CommaExpr, _super);
function CommaExpr(parts, sourceSpan) {
var _this = _super.call(this, parts[parts.length - 1].type, sourceSpan) || this;
_this.parts = parts;
return _this;
}
CommaExpr.prototype.isEquivalent = function (e) {
return e instanceof CommaExpr && areAllEquivalent(this.parts, e.parts);
};
CommaExpr.prototype.isConstant = function () { return false; };
CommaExpr.prototype.visitExpression = function (visitor, context) {
return visitor.visitCommaExpr(this, context);
};
return CommaExpr;
}(Expression));
var THIS_EXPR = new ReadVarExpr(BuiltinVar.This, null, null);
var SUPER_EXPR = new ReadVarExpr(BuiltinVar.Super, null, null);
var CATCH_ERROR_VAR = new ReadVarExpr(BuiltinVar.CatchError, null, null);
var CATCH_STACK_VAR = new ReadVarExpr(BuiltinVar.CatchStack, null, null);
var NULL_EXPR = new LiteralExpr(null, null, null);
var TYPED_NULL_EXPR = new LiteralExpr(null, INFERRED_TYPE, null);
//// Statements
var StmtModifier;
(function (StmtModifier) {
StmtModifier[StmtModifier["Final"] = 0] = "Final";
StmtModifier[StmtModifier["Private"] = 1] = "Private";
StmtModifier[StmtModifier["Exported"] = 2] = "Exported";
StmtModifier[StmtModifier["Static"] = 3] = "Static";
})(StmtModifier || (StmtModifier = {}));
var Statement = /** @class */ (function () {
function Statement(modifiers, sourceSpan) {
this.modifiers = modifiers || [];
this.sourceSpan = sourceSpan || null;
}
Statement.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; };
return Statement;
}());
var DeclareVarStmt = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(DeclareVarStmt, _super);
function DeclareVarStmt(name, value, type, modifiers, sourceSpan) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, modifiers, sourceSpan) || this;
_this.name = name;
_this.value = value;
_this.type = type || (value && value.type) || null;
return _this;
}
DeclareVarStmt.prototype.isEquivalent = function (stmt) {
return stmt instanceof DeclareVarStmt && this.name === stmt.name &&
(this.value ? !!stmt.value && this.value.isEquivalent(stmt.value) : !stmt.value);
};
DeclareVarStmt.prototype.visitStatement = function (visitor, context) {
return visitor.visitDeclareVarStmt(this, context);
};
return DeclareVarStmt;
}(Statement));
var DeclareFunctionStmt = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(DeclareFunctionStmt, _super);
function DeclareFunctionStmt(name, params, statements, type, modifiers, sourceSpan) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, modifiers, sourceSpan) || this;
_this.name = name;
_this.params = params;
_this.statements = statements;
_this.type = type || null;
return _this;
}
DeclareFunctionStmt.prototype.isEquivalent = function (stmt) {
return stmt instanceof DeclareFunctionStmt && areAllEquivalent(this.params, stmt.params) &&
areAllEquivalent(this.statements, stmt.statements);
};
DeclareFunctionStmt.prototype.visitStatement = function (visitor, context) {
return visitor.visitDeclareFunctionStmt(this, context);
};
return DeclareFunctionStmt;
}(Statement));
var ExpressionStatement = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ExpressionStatement, _super);
function ExpressionStatement(expr, sourceSpan) {
var _this = _super.call(this, null, sourceSpan) || this;
_this.expr = expr;
return _this;
}
ExpressionStatement.prototype.isEquivalent = function (stmt) {
return stmt instanceof ExpressionStatement && this.expr.isEquivalent(stmt.expr);
};
ExpressionStatement.prototype.visitStatement = function (visitor, context) {
return visitor.visitExpressionStmt(this, context);
};
return ExpressionStatement;
}(Statement));
var ReturnStatement = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ReturnStatement, _super);
function ReturnStatement(value, sourceSpan) {
var _this = _super.call(this, null, sourceSpan) || this;
_this.value = value;
return _this;
}
ReturnStatement.prototype.isEquivalent = function (stmt) {
return stmt instanceof ReturnStatement && this.value.isEquivalent(stmt.value);
};
ReturnStatement.prototype.visitStatement = function (visitor, context) {
return visitor.visitReturnStmt(this, context);
};
return ReturnStatement;
}(Statement));
var AbstractClassPart = /** @class */ (function () {
function AbstractClassPart(type, modifiers) {
this.modifiers = modifiers;
if (!modifiers) {
this.modifiers = [];
}
this.type = type || null;
}
AbstractClassPart.prototype.hasModifier = function (modifier) { return this.modifiers.indexOf(modifier) !== -1; };
return AbstractClassPart;
}());
var ClassField = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ClassField, _super);
function ClassField(name, type, modifiers, initializer) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, type, modifiers) || this;
_this.name = name;
_this.initializer = initializer;
return _this;
}
ClassField.prototype.isEquivalent = function (f) { return this.name === f.name; };
return ClassField;
}(AbstractClassPart));
var ClassMethod = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ClassMethod, _super);
function ClassMethod(name, params, body, type, modifiers) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, type, modifiers) || this;
_this.name = name;
_this.params = params;
_this.body = body;
return _this;
}
ClassMethod.prototype.isEquivalent = function (m) {
return this.name === m.name && areAllEquivalent(this.body, m.body);
};
return ClassMethod;
}(AbstractClassPart));
var ClassGetter = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ClassGetter, _super);
function ClassGetter(name, body, type, modifiers) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, type, modifiers) || this;
_this.name = name;
_this.body = body;
return _this;
}
ClassGetter.prototype.isEquivalent = function (m) {
return this.name === m.name && areAllEquivalent(this.body, m.body);
};
return ClassGetter;
}(AbstractClassPart));
var ClassStmt = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ClassStmt, _super);
function ClassStmt(name, parent, fields, getters, constructorMethod, methods, modifiers, sourceSpan) {
if (modifiers === void 0) { modifiers = null; }
var _this = _super.call(this, modifiers, sourceSpan) || this;
_this.name = name;
_this.parent = parent;
_this.fields = fields;
_this.getters = getters;
_this.constructorMethod = constructorMethod;
_this.methods = methods;
return _this;
}
ClassStmt.prototype.isEquivalent = function (stmt) {
return stmt instanceof ClassStmt && this.name === stmt.name &&
nullSafeIsEquivalent(this.parent, stmt.parent) &&
areAllEquivalent(this.fields, stmt.fields) &&
areAllEquivalent(this.getters, stmt.getters) &&
this.constructorMethod.isEquivalent(stmt.constructorMethod) &&
areAllEquivalent(this.methods, stmt.methods);
};
ClassStmt.prototype.visitStatement = function (visitor, context) {
return visitor.visitDeclareClassStmt(this, context);
};
return ClassStmt;
}(Statement));
var IfStmt = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(IfStmt, _super);
function IfStmt(condition, trueCase, falseCase, sourceSpan) {
if (falseCase === void 0) { falseCase = []; }
var _this = _super.call(this, null, sourceSpan) || this;
_this.condition = condition;
_this.trueCase = trueCase;
_this.falseCase = falseCase;
return _this;
}
IfStmt.prototype.isEquivalent = function (stmt) {
return stmt instanceof IfStmt && this.condition.isEquivalent(stmt.condition) &&
areAllEquivalent(this.trueCase, stmt.trueCase) &&
areAllEquivalent(this.falseCase, stmt.falseCase);
};
IfStmt.prototype.visitStatement = function (visitor, context) {
return visitor.visitIfStmt(this, context);
};
return IfStmt;
}(Statement));
var CommentStmt = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(CommentStmt, _super);
function CommentStmt(comment, multiline, sourceSpan) {
if (multiline === void 0) { multiline = false; }
var _this = _super.call(this, null, sourceSpan) || this;
_this.comment = comment;
_this.multiline = multiline;
return _this;
}
CommentStmt.prototype.isEquivalent = function (stmt) { return stmt instanceof CommentStmt; };
CommentStmt.prototype.visitStatement = function (visitor, context) {
return visitor.visitCommentStmt(this, context);
};
return CommentStmt;
}(Statement));
var JSDocCommentStmt = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(JSDocCommentStmt, _super);
function JSDocCommentStmt(tags, sourceSpan) {
if (tags === void 0) { tags = []; }
var _this = _super.call(this, null, sourceSpan) || this;
_this.tags = tags;
return _this;
}
JSDocCommentStmt.prototype.isEquivalent = function (stmt) {
return stmt instanceof JSDocCommentStmt && this.toString() === stmt.toString();
};
JSDocCommentStmt.prototype.visitStatement = function (visitor, context) {
return visitor.visitJSDocCommentStmt(this, context);
};
JSDocCommentStmt.prototype.toString = function () { return serializeTags(this.tags); };
return JSDocCommentStmt;
}(Statement));
var TryCatchStmt = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(TryCatchStmt, _super);
function TryCatchStmt(bodyStmts, catchStmts, sourceSpan) {
var _this = _super.call(this, null, sourceSpan) || this;
_this.bodyStmts = bodyStmts;
_this.catchStmts = catchStmts;
return _this;
}
TryCatchStmt.prototype.isEquivalent = function (stmt) {
return stmt instanceof TryCatchStmt && areAllEquivalent(this.bodyStmts, stmt.bodyStmts) &&
areAllEquivalent(this.catchStmts, stmt.catchStmts);
};
TryCatchStmt.prototype.visitStatement = function (visitor, context) {
return visitor.visitTryCatchStmt(this, context);
};
return TryCatchStmt;
}(Statement));
var ThrowStmt = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ThrowStmt, _super);
function ThrowStmt(error, sourceSpan) {
var _this = _super.call(this, null, sourceSpan) || this;
_this.error = error;
return _this;
}
ThrowStmt.prototype.isEquivalent = function (stmt) {
return stmt instanceof TryCatchStmt && this.error.isEquivalent(stmt.error);
};
ThrowStmt.prototype.visitStatement = function (visitor, context) {
return visitor.visitThrowStmt(this, context);
};
return ThrowStmt;
}(Statement));
var AstTransformer$1 = /** @class */ (function () {
function AstTransformer() {
}
AstTransformer.prototype.transformExpr = function (expr, context) { return expr; };
AstTransformer.prototype.transformStmt = function (stmt, context) { return stmt; };
AstTransformer.prototype.visitReadVarExpr = function (ast, context) { return this.transformExpr(ast, context); };
AstTransformer.prototype.visitWriteVarExpr = function (expr, context) {
return this.transformExpr(new WriteVarExpr(expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
};
AstTransformer.prototype.visitWriteKeyExpr = function (expr, context) {
return this.transformExpr(new WriteKeyExpr(expr.receiver.visitExpression(this, context), expr.index.visitExpression(this, context), expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
};
AstTransformer.prototype.visitWritePropExpr = function (expr, context) {
return this.transformExpr(new WritePropExpr(expr.receiver.visitExpression(this, context), expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
};
AstTransformer.prototype.visitInvokeMethodExpr = function (ast, context) {
var method = ast.builtin || ast.name;
return this.transformExpr(new InvokeMethodExpr(ast.receiver.visitExpression(this, context), method, this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
};
AstTransformer.prototype.visitInvokeFunctionExpr = function (ast, context) {
return this.transformExpr(new InvokeFunctionExpr(ast.fn.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
};
AstTransformer.prototype.visitInstantiateExpr = function (ast, context) {
return this.transformExpr(new InstantiateExpr(ast.classExpr.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
};
AstTransformer.prototype.visitLiteralExpr = function (ast, context) { return this.transformExpr(ast, context); };
AstTransformer.prototype.visitExternalExpr = function (ast, context) {
return this.transformExpr(ast, context);
};
AstTransformer.prototype.visitConditionalExpr = function (ast, context) {
return this.transformExpr(new ConditionalExpr(ast.condition.visitExpression(this, context), ast.trueCase.visitExpression(this, context), ast.falseCase.visitExpression(this, context), ast.type, ast.sourceSpan), context);
};
AstTransformer.prototype.visitNotExpr = function (ast, context) {
return this.transformExpr(new NotExpr(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
};
AstTransformer.prototype.visitAssertNotNullExpr = function (ast, context) {
return this.transformExpr(new AssertNotNull(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
};
AstTransformer.prototype.visitCastExpr = function (ast, context) {
return this.transformExpr(new CastExpr(ast.value.visitExpression(this, context), ast.type, ast.sourceSpan), context);
};
AstTransformer.prototype.visitFunctionExpr = function (ast, context) {
return this.transformExpr(new FunctionExpr(ast.params, this.visitAllStatements(ast.statements, context), ast.type, ast.sourceSpan), context);
};
AstTransformer.prototype.visitBinaryOperatorExpr = function (ast, context) {
return this.transformExpr(new BinaryOperatorExpr(ast.operator, ast.lhs.visitExpression(this, context), ast.rhs.visitExpression(this, context), ast.type, ast.sourceSpan), context);
};
AstTransformer.prototype.visitReadPropExpr = function (ast, context) {
return this.transformExpr(new ReadPropExpr(ast.receiver.visitExpression(this, context), ast.name, ast.type, ast.sourceSpan), context);
};
AstTransformer.prototype.visitReadKeyExpr = function (ast, context) {
return this.transformExpr(new ReadKeyExpr(ast.receiver.visitExpression(this, context), ast.index.visitExpression(this, context), ast.type, ast.sourceSpan), context);
};
AstTransformer.prototype.visitLiteralArrayExpr = function (ast, context) {
return this.transformExpr(new LiteralArrayExpr(this.visitAllExpressions(ast.entries, context), ast.type, ast.sourceSpan), context);
};
AstTransformer.prototype.visitLiteralMapExpr = function (ast, context) {
var _this = this;
var entries = ast.entries.map(function (entry) { return new LiteralMapEntry(entry.key, entry.value.visitExpression(_this, context), entry.quoted); });
var mapType = new MapType(ast.valueType, null);
return this.transformExpr(new LiteralMapExpr(entries, mapType, ast.sourceSpan), context);
};
AstTransformer.prototype.visitCommaExpr = function (ast, context) {
return this.transformExpr(new CommaExpr(this.visitAllExpressions(ast.parts, context), ast.sourceSpan), context);
};
AstTransformer.prototype.visitAllExpressions = function (exprs, context) {
var _this = this;
return exprs.map(function (expr) { return expr.visitExpression(_this, context); });
};
AstTransformer.prototype.visitDeclareVarStmt = function (stmt, context) {
var value = stmt.value && stmt.value.visitExpression(this, context);
return this.transformStmt(new DeclareVarStmt(stmt.name, value, stmt.type, stmt.modifiers, stmt.sourceSpan), context);
};
AstTransformer.prototype.visitDeclareFunctionStmt = function (stmt, context) {
return this.transformStmt(new DeclareFunctionStmt(stmt.name, stmt.params, this.visitAllStatements(stmt.statements, context), stmt.type, stmt.modifiers, stmt.sourceSpan), context);
};
AstTransformer.prototype.visitExpressionStmt = function (stmt, context) {
return this.transformStmt(new ExpressionStatement(stmt.expr.visitExpression(this, context), stmt.sourceSpan), context);
};
AstTransformer.prototype.visitReturnStmt = function (stmt, context) {
return this.transformStmt(new ReturnStatement(stmt.value.visitExpression(this, context), stmt.sourceSpan), context);
};
AstTransformer.prototype.visitDeclareClassStmt = function (stmt, context) {
var _this = this;
var parent = stmt.parent.visitExpression(this, context);
var getters = stmt.getters.map(function (getter) { return new ClassGetter(getter.name, _this.visitAllStatements(getter.body, context), getter.type, getter.modifiers); });
var ctorMethod = stmt.constructorMethod &&
new ClassMethod(stmt.constructorMethod.name, stmt.constructorMethod.params, this.visitAllStatements(stmt.constructorMethod.body, context), stmt.constructorMethod.type, stmt.constructorMethod.modifiers);
var methods = stmt.methods.map(function (method) { return new ClassMethod(method.name, method.params, _this.visitAllStatements(method.body, context), method.type, method.modifiers); });
return this.transformStmt(new ClassStmt(stmt.name, parent, stmt.fields, getters, ctorMethod, methods, stmt.modifiers, stmt.sourceSpan), context);
};
AstTransformer.prototype.visitIfStmt = function (stmt, context) {
return this.transformStmt(new IfStmt(stmt.condition.visitExpression(this, context), this.visitAllStatements(stmt.trueCase, context), this.visitAllStatements(stmt.falseCase, context), stmt.sourceSpan), context);
};
AstTransformer.prototype.visitTryCatchStmt = function (stmt, context) {
return this.transformStmt(new TryCatchStmt(this.visitAllStatements(stmt.bodyStmts, context), this.visitAllStatements(stmt.catchStmts, context), stmt.sourceSpan), context);
};
AstTransformer.prototype.visitThrowStmt = function (stmt, context) {
return this.transformStmt(new ThrowStmt(stmt.error.visitExpression(this, context), stmt.sourceSpan), context);
};
AstTransformer.prototype.visitCommentStmt = function (stmt, context) {
return this.transformStmt(stmt, context);
};
AstTransformer.prototype.visitJSDocCommentStmt = function (stmt, context) {
return this.transformStmt(stmt, context);
};
AstTransformer.prototype.visitAllStatements = function (stmts, context) {
var _this = this;
return stmts.map(function (stmt) { return stmt.visitStatement(_this, context); });
};
return AstTransformer;
}());
var RecursiveAstVisitor$1 = /** @class */ (function () {
function RecursiveAstVisitor() {
}
RecursiveAstVisitor.prototype.visitType = function (ast, context) { return ast; };
RecursiveAstVisitor.prototype.visitExpression = function (ast, context) {
if (ast.type) {
ast.type.visitType(this, context);
}
return ast;
};
RecursiveAstVisitor.prototype.visitBuiltinType = function (type, context) { return this.visitType(type, context); };
RecursiveAstVisitor.prototype.visitExpressionType = function (type, context) {
type.value.visitExpression(this, context);
return this.visitType(type, context);
};
RecursiveAstVisitor.prototype.visitArrayType = function (type, context) { return this.visitType(type, context); };
RecursiveAstVisitor.prototype.visitMapType = function (type, context) { return this.visitType(type, context); };
RecursiveAstVisitor.prototype.visitReadVarExpr = function (ast, context) {
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitWriteVarExpr = function (ast, context) {
ast.value.visitExpression(this, context);
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitWriteKeyExpr = function (ast, context) {
ast.receiver.visitExpression(this, context);
ast.index.visitExpression(this, context);
ast.value.visitExpression(this, context);
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitWritePropExpr = function (ast, context) {
ast.receiver.visitExpression(this, context);
ast.value.visitExpression(this, context);
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitInvokeMethodExpr = function (ast, context) {
ast.receiver.visitExpression(this, context);
this.visitAllExpressions(ast.args, context);
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitInvokeFunctionExpr = function (ast, context) {
ast.fn.visitExpression(this, context);
this.visitAllExpressions(ast.args, context);
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitInstantiateExpr = function (ast, context) {
ast.classExpr.visitExpression(this, context);
this.visitAllExpressions(ast.args, context);
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitLiteralExpr = function (ast, context) {
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitExternalExpr = function (ast, context) {
var _this = this;
if (ast.typeParams) {
ast.typeParams.forEach(function (type) { return type.visitType(_this, context); });
}
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitConditionalExpr = function (ast, context) {
ast.condition.visitExpression(this, context);
ast.trueCase.visitExpression(this, context);
ast.falseCase.visitExpression(this, context);
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitNotExpr = function (ast, context) {
ast.condition.visitExpression(this, context);
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitAssertNotNullExpr = function (ast, context) {
ast.condition.visitExpression(this, context);
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitCastExpr = function (ast, context) {
ast.value.visitExpression(this, context);
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitFunctionExpr = function (ast, context) {
this.visitAllStatements(ast.statements, context);
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitBinaryOperatorExpr = function (ast, context) {
ast.lhs.visitExpression(this, context);
ast.rhs.visitExpression(this, context);
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitReadPropExpr = function (ast, context) {
ast.receiver.visitExpression(this, context);
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitReadKeyExpr = function (ast, context) {
ast.receiver.visitExpression(this, context);
ast.index.visitExpression(this, context);
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitLiteralArrayExpr = function (ast, context) {
this.visitAllExpressions(ast.entries, context);
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitLiteralMapExpr = function (ast, context) {
var _this = this;
ast.entries.forEach(function (entry) { return entry.value.visitExpression(_this, context); });
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitCommaExpr = function (ast, context) {
this.visitAllExpressions(ast.parts, context);
return this.visitExpression(ast, context);
};
RecursiveAstVisitor.prototype.visitAllExpressions = function (exprs, context) {
var _this = this;
exprs.forEach(function (expr) { return expr.visitExpression(_this, context); });
};
RecursiveAstVisitor.prototype.visitDeclareVarStmt = function (stmt, context) {
if (stmt.value) {
stmt.value.visitExpression(this, context);
}
if (stmt.type) {
stmt.type.visitType(this, context);
}
return stmt;
};
RecursiveAstVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) {
this.visitAllStatements(stmt.statements, context);
if (stmt.type) {
stmt.type.visitType(this, context);
}
return stmt;
};
RecursiveAstVisitor.prototype.visitExpressionStmt = function (stmt, context) {
stmt.expr.visitExpression(this, context);
return stmt;
};
RecursiveAstVisitor.prototype.visitReturnStmt = function (stmt, context) {
stmt.value.visitExpression(this, context);
return stmt;
};
RecursiveAstVisitor.prototype.visitDeclareClassStmt = function (stmt, context) {
var _this = this;
stmt.parent.visitExpression(this, context);
stmt.getters.forEach(function (getter) { return _this.visitAllStatements(getter.body, context); });
if (stmt.constructorMethod) {
this.visitAllStatements(stmt.constructorMethod.body, context);
}
stmt.methods.forEach(function (method) { return _this.visitAllStatements(method.body, context); });
return stmt;
};
RecursiveAstVisitor.prototype.visitIfStmt = function (stmt, context) {
stmt.condition.visitExpression(this, context);
this.visitAllStatements(stmt.trueCase, context);
this.visitAllStatements(stmt.falseCase, context);
return stmt;
};
RecursiveAstVisitor.prototype.visitTryCatchStmt = function (stmt, context) {
this.visitAllStatements(stmt.bodyStmts, context);
this.visitAllStatements(stmt.catchStmts, context);
return stmt;
};
RecursiveAstVisitor.prototype.visitThrowStmt = function (stmt, context) {
stmt.error.visitExpression(this, context);
return stmt;
};
RecursiveAstVisitor.prototype.visitCommentStmt = function (stmt, context) { return stmt; };
RecursiveAstVisitor.prototype.visitJSDocCommentStmt = function (stmt, context) { return stmt; };
RecursiveAstVisitor.prototype.visitAllStatements = function (stmts, context) {
var _this = this;
stmts.forEach(function (stmt) { return stmt.visitStatement(_this, context); });
};
return RecursiveAstVisitor;
}());
function findReadVarNames(stmts) {
var visitor = new _ReadVarVisitor();
visitor.visitAllStatements(stmts, null);
return visitor.varNames;
}
var _ReadVarVisitor = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(_ReadVarVisitor, _super);
function _ReadVarVisitor() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.varNames = new Set();
return _this;
}
_ReadVarVisitor.prototype.visitDeclareFunctionStmt = function (stmt, context) {
// Don't descend into nested functions
return stmt;
};
_ReadVarVisitor.prototype.visitDeclareClassStmt = function (stmt, context) {
// Don't descend into nested classes
return stmt;
};
_ReadVarVisitor.prototype.visitReadVarExpr = function (ast, context) {
if (ast.name) {
this.varNames.add(ast.name);
}
return null;
};
return _ReadVarVisitor;
}(RecursiveAstVisitor$1));
function collectExternalReferences(stmts) {
var visitor = new _FindExternalReferencesVisitor();
visitor.visitAllStatements(stmts, null);
return visitor.externalReferences;
}
var _FindExternalReferencesVisitor = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(_FindExternalReferencesVisitor, _super);
function _FindExternalReferencesVisitor() {
var _this = _super !== null && _super.apply(this, arguments) || this;
_this.externalReferences = [];
return _this;
}
_FindExternalReferencesVisitor.prototype.visitExternalExpr = function (e, context) {
this.externalReferences.push(e.value);
return _super.prototype.visitExternalExpr.call(this, e, context);
};
return _FindExternalReferencesVisitor;
}(RecursiveAstVisitor$1));
function applySourceSpanToStatementIfNeeded(stmt, sourceSpan) {
if (!sourceSpan) {
return stmt;
}
var transformer = new _ApplySourceSpanTransformer(sourceSpan);
return stmt.visitStatement(transformer, null);
}
function applySourceSpanToExpressionIfNeeded(expr, sourceSpan) {
if (!sourceSpan) {
return expr;
}
var transformer = new _ApplySourceSpanTransformer(sourceSpan);
return expr.visitExpression(transformer, null);
}
var _ApplySourceSpanTransformer = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(_ApplySourceSpanTransformer, _super);
function _ApplySourceSpanTransformer(sourceSpan) {
var _this = _super.call(this) || this;
_this.sourceSpan = sourceSpan;
return _this;
}
_ApplySourceSpanTransformer.prototype._clone = function (obj) {
var clone = Object.create(obj.constructor.prototype);
for (var prop in obj) {
clone[prop] = obj[prop];
}
return clone;
};
_ApplySourceSpanTransformer.prototype.transformExpr = function (expr, context) {
if (!expr.sourceSpan) {
expr = this._clone(expr);
expr.sourceSpan = this.sourceSpan;
}
return expr;
};
_ApplySourceSpanTransformer.prototype.transformStmt = function (stmt, context) {
if (!stmt.sourceSpan) {
stmt = this._clone(stmt);
stmt.sourceSpan = this.sourceSpan;
}
return stmt;
};
return _ApplySourceSpanTransformer;
}(AstTransformer$1));
function variable(name, type, sourceSpan) {
return new ReadVarExpr(name, type, sourceSpan);
}
function importExpr(id, typeParams, sourceSpan) {
if (typeParams === void 0) { typeParams = null; }
return new ExternalExpr(id, null, typeParams, sourceSpan);
}
function importType(id, typeParams, typeModifiers) {
if (typeParams === void 0) { typeParams = null; }
if (typeModifiers === void 0) { typeModifiers = null; }
return id != null ? expressionType(importExpr(id, typeParams, null), typeModifiers) : null;
}
function expressionType(expr, typeModifiers) {
if (typeModifiers === void 0) { typeModifiers = null; }
return new ExpressionType(expr, typeModifiers);
}
function literalArr(values, type, sourceSpan) {
return new LiteralArrayExpr(values, type, sourceSpan);
}
function literalMap(values, type) {
if (type === void 0) { type = null; }
return new LiteralMapExpr(values.map(function (e) { return new LiteralMapEntry(e.key, e.value, e.quoted); }), type, null);
}
function not(expr, sourceSpan) {
return new NotExpr(expr, sourceSpan);
}
function assertNotNull(expr, sourceSpan) {
return new AssertNotNull(expr, sourceSpan);
}
function fn(params, body, type, sourceSpan, name) {
return new FunctionExpr(params, body, type, sourceSpan, name);
}
function ifStmt(condition, thenClause, elseClause) {
return new IfStmt(condition, thenClause, elseClause);
}
function literal(value, type, sourceSpan) {
return new LiteralExpr(value, type, sourceSpan);
}
function isNull(exp) {
return exp instanceof LiteralExpr && exp.value === null;
}
/*
* Serializes a `Tag` into a string.
* Returns a string like " @foo {bar} baz" (note the leading whitespace before `@foo`).
*/
function tagToString(tag) {
var out = '';
if (tag.tagName) {
out += " @" + tag.tagName;
}
if (tag.text) {
if (tag.text.match(/\/\*|\*\//)) {
throw new Error('JSDoc text cannot contain "/*" and "*/"');
}
out += ' ' + tag.text.replace(/@/g, '\\@');
}
return out;
}
function serializeTags(tags) {
if (tags.length === 0)
return '';
var out = '*\n';
try {
for (var tags_1 = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__values"])(tags), tags_1_1 = tags_1.next(); !tags_1_1.done; tags_1_1 = tags_1.next()) {
var tag = tags_1_1.value;
out += ' *';
// If the tagToString is multi-line, insert " * " prefixes on subsequent lines.
out += tagToString(tag).replace(/\n/g, '\n * ');
out += '\n';
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (tags_1_1 && !tags_1_1.done && (_a = tags_1.return)) _a.call(tags_1);
}
finally { if (e_1) throw e_1.error; }
}
out += ' ';
return out;
var e_1, _a;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var QUOTED_KEYS = '$quoted$';
function convertValueToOutputAst(ctx, value, type) {
if (type === void 0) { type = null; }
return visitValue(value, new _ValueOutputAstTransformer(ctx), type);
}
var _ValueOutputAstTransformer = /** @class */ (function () {
function _ValueOutputAstTransformer(ctx) {
this.ctx = ctx;
}
_ValueOutputAstTransformer.prototype.visitArray = function (arr, type) {
var _this = this;
return literalArr(arr.map(function (value) { return visitValue(value, _this, null); }), type);
};
_ValueOutputAstTransformer.prototype.visitStringMap = function (map, type) {
var _this = this;
var entries = [];
var quotedSet = new Set(map && map[QUOTED_KEYS]);
Object.keys(map).forEach(function (key) {
entries.push(new LiteralMapEntry(key, visitValue(map[key], _this, null), quotedSet.has(key)));
});
return new LiteralMapExpr(entries, type);
};
_ValueOutputAstTransformer.prototype.visitPrimitive = function (value, type) { return literal(value, type); };
_ValueOutputAstTransformer.prototype.visitOther = function (value, type) {
if (value instanceof Expression) {
return value;
}
else {
return this.ctx.importExpr(value);
}
};
return _ValueOutputAstTransformer;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function mapEntry(key, value) {
return { key: key, value: value, quoted: false };
}
var InjectableCompiler = /** @class */ (function () {
function InjectableCompiler(reflector, alwaysGenerateDef) {
this.reflector = reflector;
this.alwaysGenerateDef = alwaysGenerateDef;
this.tokenInjector = reflector.resolveExternalReference(Identifiers.Injector);
}
InjectableCompiler.prototype.depsArray = function (deps, ctx) {
var _this = this;
return deps.map(function (dep) {
var token = dep;
var args = [token];
var flags = 0;
if (Array.isArray(dep)) {
for (var i = 0; i < dep.length; i++) {
var v = dep[i];
if (v) {
if (v.ngMetadataName === 'Optional') {
flags |= 8 /* Optional */;
}
else if (v.ngMetadataName === 'SkipSelf') {
flags |= 4 /* SkipSelf */;
}
else if (v.ngMetadataName === 'Self') {
flags |= 2 /* Self */;
}
else if (v.ngMetadataName === 'Inject') {
token = v.token;
}
else {
token = v;
}
}
}
}
var tokenExpr;
if (typeof token === 'string') {
tokenExpr = literal(token);
}
else if (token === _this.tokenInjector) {
tokenExpr = importExpr(Identifiers.INJECTOR);
}
else {
tokenExpr = ctx.importExpr(token);
}
if (flags !== 0 /* Default */) {
args = [tokenExpr, literal(flags)];
}
else {
args = [tokenExpr];
}
return importExpr(Identifiers.inject).callFn(args);
});
};
InjectableCompiler.prototype.factoryFor = function (injectable, ctx) {
var retValue;
if (injectable.useExisting) {
retValue = importExpr(Identifiers.inject).callFn([ctx.importExpr(injectable.useExisting)]);
}
else if (injectable.useFactory) {
var deps = injectable.deps || [];
if (deps.length > 0) {
retValue = ctx.importExpr(injectable.useFactory).callFn(this.depsArray(deps, ctx));
}
else {
return ctx.importExpr(injectable.useFactory);
}
}
else if (injectable.useValue) {
retValue = convertValueToOutputAst(ctx, injectable.useValue);
}
else {
var clazz = injectable.useClass || injectable.symbol;
var depArgs = this.depsArray(this.reflector.parameters(clazz), ctx);
retValue = new InstantiateExpr(ctx.importExpr(clazz), depArgs);
}
return fn([], [new ReturnStatement(retValue)], undefined, undefined, injectable.symbol.name + '_Factory');
};
InjectableCompiler.prototype.injectableDef = function (injectable, ctx) {
var providedIn = NULL_EXPR;
if (injectable.providedIn !== undefined) {
if (injectable.providedIn === null) {
providedIn = NULL_EXPR;
}
else if (typeof injectable.providedIn === 'string') {
providedIn = literal(injectable.providedIn);
}
else {
providedIn = ctx.importExpr(injectable.providedIn);
}
}
var def = [
mapEntry('factory', this.factoryFor(injectable, ctx)),
mapEntry('token', ctx.importExpr(injectable.type.reference)),
mapEntry('providedIn', providedIn),
];
return importExpr(Identifiers.defineInjectable).callFn([literalMap(def)]);
};
InjectableCompiler.prototype.compile = function (injectable, ctx) {
if (this.alwaysGenerateDef || injectable.providedIn !== undefined) {
var className = identifierName(injectable.type);
var clazz = new ClassStmt(className, null, [
new ClassField('ngInjectableDef', INFERRED_TYPE, [StmtModifier.Static], this.injectableDef(injectable, ctx)),
], [], new ClassMethod(null, [], []), []);
ctx.statements.push(clazz);
}
};
return InjectableCompiler;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var STRIP_SRC_FILE_SUFFIXES = /(\.ts|\.d\.ts|\.js|\.jsx|\.tsx)$/;
var GENERATED_FILE = /\.ngfactory\.|\.ngsummary\./;
var JIT_SUMMARY_FILE = /\.ngsummary\./;
var JIT_SUMMARY_NAME = /NgSummary$/;
function ngfactoryFilePath(filePath, forceSourceFile) {
if (forceSourceFile === void 0) { forceSourceFile = false; }
var urlWithSuffix = splitTypescriptSuffix(filePath, forceSourceFile);
return urlWithSuffix[0] + ".ngfactory" + normalizeGenFileSuffix(urlWithSuffix[1]);
}
function stripGeneratedFileSuffix(filePath) {
return filePath.replace(GENERATED_FILE, '.');
}
function isGeneratedFile(filePath) {
return GENERATED_FILE.test(filePath);
}
function splitTypescriptSuffix(path, forceSourceFile) {
if (forceSourceFile === void 0) { forceSourceFile = false; }
if (path.endsWith('.d.ts')) {
return [path.slice(0, -5), forceSourceFile ? '.ts' : '.d.ts'];
}
var lastDot = path.lastIndexOf('.');
if (lastDot !== -1) {
return [path.substring(0, lastDot), path.substring(lastDot)];
}
return [path, ''];
}
function normalizeGenFileSuffix(srcFileSuffix) {
return srcFileSuffix === '.tsx' ? '.ts' : srcFileSuffix;
}
function summaryFileName(fileName) {
var fileNameWithoutSuffix = fileName.replace(STRIP_SRC_FILE_SUFFIXES, '');
return fileNameWithoutSuffix + ".ngsummary.json";
}
function summaryForJitFileName(fileName, forceSourceFile) {
if (forceSourceFile === void 0) { forceSourceFile = false; }
var urlWithSuffix = splitTypescriptSuffix(stripGeneratedFileSuffix(fileName), forceSourceFile);
return urlWithSuffix[0] + ".ngsummary" + urlWithSuffix[1];
}
function stripSummaryForJitFileSuffix(filePath) {
return filePath.replace(JIT_SUMMARY_FILE, '.');
}
function summaryForJitName(symbolName) {
return symbolName + "NgSummary";
}
function stripSummaryForJitNameSuffix(symbolName) {
return symbolName.replace(JIT_SUMMARY_NAME, '');
}
var LOWERED_SYMBOL = /\u0275\d+/;
function isLoweredSymbol(name) {
return LOWERED_SYMBOL.test(name);
}
function createLoweredSymbol(id) {
return "\u0275" + id;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var LifecycleHooks;
(function (LifecycleHooks) {
LifecycleHooks[LifecycleHooks["OnInit"] = 0] = "OnInit";
LifecycleHooks[LifecycleHooks["OnDestroy"] = 1] = "OnDestroy";
LifecycleHooks[LifecycleHooks["DoCheck"] = 2] = "DoCheck";
LifecycleHooks[LifecycleHooks["OnChanges"] = 3] = "OnChanges";
LifecycleHooks[LifecycleHooks["AfterContentInit"] = 4] = "AfterContentInit";
LifecycleHooks[LifecycleHooks["AfterContentChecked"] = 5] = "AfterContentChecked";
LifecycleHooks[LifecycleHooks["AfterViewInit"] = 6] = "AfterViewInit";
LifecycleHooks[LifecycleHooks["AfterViewChecked"] = 7] = "AfterViewChecked";
})(LifecycleHooks || (LifecycleHooks = {}));
var LIFECYCLE_HOOKS_VALUES = [
LifecycleHooks.OnInit, LifecycleHooks.OnDestroy, LifecycleHooks.DoCheck, LifecycleHooks.OnChanges,
LifecycleHooks.AfterContentInit, LifecycleHooks.AfterContentChecked, LifecycleHooks.AfterViewInit,
LifecycleHooks.AfterViewChecked
];
function hasLifecycleHook(reflector, hook, token) {
return reflector.hasLifecycleHook(token, getHookName(hook));
}
function getAllLifecycleHooks(reflector, token) {
return LIFECYCLE_HOOKS_VALUES.filter(function (hook) { return hasLifecycleHook(reflector, hook, token); });
}
function getHookName(hook) {
switch (hook) {
case LifecycleHooks.OnInit:
return 'ngOnInit';
case LifecycleHooks.OnDestroy:
return 'ngOnDestroy';
case LifecycleHooks.DoCheck:
return 'ngDoCheck';
case LifecycleHooks.OnChanges:
return 'ngOnChanges';
case LifecycleHooks.AfterContentInit:
return 'ngAfterContentInit';
case LifecycleHooks.AfterContentChecked:
return 'ngAfterContentChecked';
case LifecycleHooks.AfterViewInit:
return 'ngAfterViewInit';
case LifecycleHooks.AfterViewChecked:
return 'ngAfterViewChecked';
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var _SELECTOR_REGEXP = new RegExp('(\\:not\\()|' + //":not("
'([-\\w]+)|' + // "tag"
'(?:\\.([-\\w]+))|' + // ".class"
// "-" should appear first in the regexp below as FF31 parses "[.-\w]" as a range
'(?:\\[([-.\\w*]+)(?:=([\"\']?)([^\\]\"\']*)\\5)?\\])|' + // "[name]", "[name=value]",
// "[name="value"]",
// "[name='value']"
'(\\))|' + // ")"
'(\\s*,\\s*)', // ","
'g');
/**
* A css selector contains an element name,
* css classes and attribute/value pairs with the purpose
* of selecting subsets out of them.
*/
var CssSelector = /** @class */ (function () {
function CssSelector() {
this.element = null;
this.classNames = [];
/**
* The selectors are encoded in pairs where:
* - even locations are attribute names
* - odd locations are attribute values.
*
* Example:
* Selector: `[key1=value1][key2]` would parse to:
* ```
* ['key1', 'value1', 'key2', '']
* ```
*/
this.attrs = [];
this.notSelectors = [];
}
CssSelector.parse = function (selector) {
var results = [];
var _addResult = function (res, cssSel) {
if (cssSel.notSelectors.length > 0 && !cssSel.element && cssSel.classNames.length == 0 &&
cssSel.attrs.length == 0) {
cssSel.element = '*';
}
res.push(cssSel);
};
var cssSelector = new CssSelector();
var match;
var current = cssSelector;
var inNot = false;
_SELECTOR_REGEXP.lastIndex = 0;
while (match = _SELECTOR_REGEXP.exec(selector)) {
if (match[1]) {
if (inNot) {
throw new Error('Nesting :not is not allowed in a selector');
}
inNot = true;
current = new CssSelector();
cssSelector.notSelectors.push(current);
}
if (match[2]) {
current.setElement(match[2]);
}
if (match[3]) {
current.addClassName(match[3]);
}
if (match[4]) {
current.addAttribute(match[4], match[6]);
}
if (match[7]) {
inNot = false;
current = cssSelector;
}
if (match[8]) {
if (inNot) {
throw new Error('Multiple selectors in :not are not supported');
}
_addResult(results, cssSelector);
cssSelector = current = new CssSelector();
}
}
_addResult(results, cssSelector);
return results;
};
CssSelector.prototype.isElementSelector = function () {
return this.hasElementSelector() && this.classNames.length == 0 && this.attrs.length == 0 &&
this.notSelectors.length === 0;
};
CssSelector.prototype.hasElementSelector = function () { return !!this.element; };
CssSelector.prototype.setElement = function (element) {
if (element === void 0) { element = null; }
this.element = element;
};
/** Gets a template string for an element that matches the selector. */
CssSelector.prototype.getMatchingElementTemplate = function () {
var tagName = this.element || 'div';
var classAttr = this.classNames.length > 0 ? " class=\"" + this.classNames.join(' ') + "\"" : '';
var attrs = '';
for (var i = 0; i < this.attrs.length; i += 2) {
var attrName = this.attrs[i];
var attrValue = this.attrs[i + 1] !== '' ? "=\"" + this.attrs[i + 1] + "\"" : '';
attrs += " " + attrName + attrValue;
}
return getHtmlTagDefinition(tagName).isVoid ? "<" + tagName + classAttr + attrs + "/>" :
"<" + tagName + classAttr + attrs + ">" + tagName + ">";
};
CssSelector.prototype.getAttrs = function () {
var result = [];
if (this.classNames.length > 0) {
result.push('class', this.classNames.join(' '));
}
return result.concat(this.attrs);
};
CssSelector.prototype.addAttribute = function (name, value) {
if (value === void 0) { value = ''; }
this.attrs.push(name, value && value.toLowerCase() || '');
};
CssSelector.prototype.addClassName = function (name) { this.classNames.push(name.toLowerCase()); };
CssSelector.prototype.toString = function () {
var res = this.element || '';
if (this.classNames) {
this.classNames.forEach(function (klass) { return res += "." + klass; });
}
if (this.attrs) {
for (var i = 0; i < this.attrs.length; i += 2) {
var name_1 = this.attrs[i];
var value = this.attrs[i + 1];
res += "[" + name_1 + (value ? '=' + value : '') + "]";
}
}
this.notSelectors.forEach(function (notSelector) { return res += ":not(" + notSelector + ")"; });
return res;
};
return CssSelector;
}());
/**
* Reads a list of CssSelectors and allows to calculate which ones
* are contained in a given CssSelector.
*/
var SelectorMatcher = /** @class */ (function () {
function SelectorMatcher() {
this._elementMap = new Map();
this._elementPartialMap = new Map();
this._classMap = new Map();
this._classPartialMap = new Map();
this._attrValueMap = new Map();
this._attrValuePartialMap = new Map();
this._listContexts = [];
}
SelectorMatcher.createNotMatcher = function (notSelectors) {
var notMatcher = new SelectorMatcher();
notMatcher.addSelectables(notSelectors, null);
return notMatcher;
};
SelectorMatcher.prototype.addSelectables = function (cssSelectors, callbackCtxt) {
var listContext = null;
if (cssSelectors.length > 1) {
listContext = new SelectorListContext(cssSelectors);
this._listContexts.push(listContext);
}
for (var i = 0; i < cssSelectors.length; i++) {
this._addSelectable(cssSelectors[i], callbackCtxt, listContext);
}
};
/**
* Add an object that can be found later on by calling `match`.
* @param cssSelector A css selector
* @param callbackCtxt An opaque object that will be given to the callback of the `match` function
*/
SelectorMatcher.prototype._addSelectable = function (cssSelector, callbackCtxt, listContext) {
var matcher = this;
var element = cssSelector.element;
var classNames = cssSelector.classNames;
var attrs = cssSelector.attrs;
var selectable = new SelectorContext(cssSelector, callbackCtxt, listContext);
if (element) {
var isTerminal = attrs.length === 0 && classNames.length === 0;
if (isTerminal) {
this._addTerminal(matcher._elementMap, element, selectable);
}
else {
matcher = this._addPartial(matcher._elementPartialMap, element);
}
}
if (classNames) {
for (var i = 0; i < classNames.length; i++) {
var isTerminal = attrs.length === 0 && i === classNames.length - 1;
var className = classNames[i];
if (isTerminal) {
this._addTerminal(matcher._classMap, className, selectable);
}
else {
matcher = this._addPartial(matcher._classPartialMap, className);
}
}
}
if (attrs) {
for (var i = 0; i < attrs.length; i += 2) {
var isTerminal = i === attrs.length - 2;
var name_2 = attrs[i];
var value = attrs[i + 1];
if (isTerminal) {
var terminalMap = matcher._attrValueMap;
var terminalValuesMap = terminalMap.get(name_2);
if (!terminalValuesMap) {
terminalValuesMap = new Map();
terminalMap.set(name_2, terminalValuesMap);
}
this._addTerminal(terminalValuesMap, value, selectable);
}
else {
var partialMap = matcher._attrValuePartialMap;
var partialValuesMap = partialMap.get(name_2);
if (!partialValuesMap) {
partialValuesMap = new Map();
partialMap.set(name_2, partialValuesMap);
}
matcher = this._addPartial(partialValuesMap, value);
}
}
}
};
SelectorMatcher.prototype._addTerminal = function (map, name, selectable) {
var terminalList = map.get(name);
if (!terminalList) {
terminalList = [];
map.set(name, terminalList);
}
terminalList.push(selectable);
};
SelectorMatcher.prototype._addPartial = function (map, name) {
var matcher = map.get(name);
if (!matcher) {
matcher = new SelectorMatcher();
map.set(name, matcher);
}
return matcher;
};
/**
* Find the objects that have been added via `addSelectable`
* whose css selector is contained in the given css selector.
* @param cssSelector A css selector
* @param matchedCallback This callback will be called with the object handed into `addSelectable`
* @return boolean true if a match was found
*/
SelectorMatcher.prototype.match = function (cssSelector, matchedCallback) {
var result = false;
var element = cssSelector.element;
var classNames = cssSelector.classNames;
var attrs = cssSelector.attrs;
for (var i = 0; i < this._listContexts.length; i++) {
this._listContexts[i].alreadyMatched = false;
}
result = this._matchTerminal(this._elementMap, element, cssSelector, matchedCallback) || result;
result = this._matchPartial(this._elementPartialMap, element, cssSelector, matchedCallback) ||
result;
if (classNames) {
for (var i = 0; i < classNames.length; i++) {
var className = classNames[i];
result =
this._matchTerminal(this._classMap, className, cssSelector, matchedCallback) || result;
result =
this._matchPartial(this._classPartialMap, className, cssSelector, matchedCallback) ||
result;
}
}
if (attrs) {
for (var i = 0; i < attrs.length; i += 2) {
var name_3 = attrs[i];
var value = attrs[i + 1];
var terminalValuesMap = this._attrValueMap.get(name_3);
if (value) {
result =
this._matchTerminal(terminalValuesMap, '', cssSelector, matchedCallback) || result;
}
result =
this._matchTerminal(terminalValuesMap, value, cssSelector, matchedCallback) || result;
var partialValuesMap = this._attrValuePartialMap.get(name_3);
if (value) {
result = this._matchPartial(partialValuesMap, '', cssSelector, matchedCallback) || result;
}
result =
this._matchPartial(partialValuesMap, value, cssSelector, matchedCallback) || result;
}
}
return result;
};
/** @internal */
SelectorMatcher.prototype._matchTerminal = function (map, name, cssSelector, matchedCallback) {
if (!map || typeof name !== 'string') {
return false;
}
var selectables = map.get(name) || [];
var starSelectables = map.get('*');
if (starSelectables) {
selectables = selectables.concat(starSelectables);
}
if (selectables.length === 0) {
return false;
}
var selectable;
var result = false;
for (var i = 0; i < selectables.length; i++) {
selectable = selectables[i];
result = selectable.finalize(cssSelector, matchedCallback) || result;
}
return result;
};
/** @internal */
SelectorMatcher.prototype._matchPartial = function (map, name, cssSelector, matchedCallback) {
if (!map || typeof name !== 'string') {
return false;
}
var nestedSelector = map.get(name);
if (!nestedSelector) {
return false;
}
// TODO(perf): get rid of recursion and measure again
// TODO(perf): don't pass the whole selector into the recursion,
// but only the not processed parts
return nestedSelector.match(cssSelector, matchedCallback);
};
return SelectorMatcher;
}());
var SelectorListContext = /** @class */ (function () {
function SelectorListContext(selectors) {
this.selectors = selectors;
this.alreadyMatched = false;
}
return SelectorListContext;
}());
// Store context to pass back selector and context when a selector is matched
var SelectorContext = /** @class */ (function () {
function SelectorContext(selector, cbContext, listContext) {
this.selector = selector;
this.cbContext = cbContext;
this.listContext = listContext;
this.notSelectors = selector.notSelectors;
}
SelectorContext.prototype.finalize = function (cssSelector, callback) {
var result = true;
if (this.notSelectors.length > 0 && (!this.listContext || !this.listContext.alreadyMatched)) {
var notMatcher = SelectorMatcher.createNotMatcher(this.notSelectors);
result = !notMatcher.match(cssSelector, null);
}
if (result && callback && (!this.listContext || !this.listContext.alreadyMatched)) {
if (this.listContext) {
this.listContext.alreadyMatched = true;
}
callback(this.selector, this.cbContext);
}
return result;
};
return SelectorContext;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var ERROR_COMPONENT_TYPE = 'ngComponentType';
// Design notes:
// - don't lazily create metadata:
// For some metadata, we need to do async work sometimes,
// so the user has to kick off this loading.
// But we want to report errors even when the async work is
// not required to check that the user would have been able
// to wait correctly.
var CompileMetadataResolver = /** @class */ (function () {
function CompileMetadataResolver(_config, _htmlParser, _ngModuleResolver, _directiveResolver, _pipeResolver, _summaryResolver, _schemaRegistry, _directiveNormalizer, _console, _staticSymbolCache, _reflector, _errorCollector) {
this._config = _config;
this._htmlParser = _htmlParser;
this._ngModuleResolver = _ngModuleResolver;
this._directiveResolver = _directiveResolver;
this._pipeResolver = _pipeResolver;
this._summaryResolver = _summaryResolver;
this._schemaRegistry = _schemaRegistry;
this._directiveNormalizer = _directiveNormalizer;
this._console = _console;
this._staticSymbolCache = _staticSymbolCache;
this._reflector = _reflector;
this._errorCollector = _errorCollector;
this._nonNormalizedDirectiveCache = new Map();
this._directiveCache = new Map();
this._summaryCache = new Map();
this._pipeCache = new Map();
this._ngModuleCache = new Map();
this._ngModuleOfTypes = new Map();
this._shallowModuleCache = new Map();
}
CompileMetadataResolver.prototype.getReflector = function () { return this._reflector; };
CompileMetadataResolver.prototype.clearCacheFor = function (type) {
var dirMeta = this._directiveCache.get(type);
this._directiveCache.delete(type);
this._nonNormalizedDirectiveCache.delete(type);
this._summaryCache.delete(type);
this._pipeCache.delete(type);
this._ngModuleOfTypes.delete(type);
// Clear all of the NgModule as they contain transitive information!
this._ngModuleCache.clear();
if (dirMeta) {
this._directiveNormalizer.clearCacheFor(dirMeta);
}
};
CompileMetadataResolver.prototype.clearCache = function () {
this._directiveCache.clear();
this._nonNormalizedDirectiveCache.clear();
this._summaryCache.clear();
this._pipeCache.clear();
this._ngModuleCache.clear();
this._ngModuleOfTypes.clear();
this._directiveNormalizer.clearCache();
};
CompileMetadataResolver.prototype._createProxyClass = function (baseType, name) {
var delegate = null;
var proxyClass = function () {
if (!delegate) {
throw new Error("Illegal state: Class " + name + " for type " + stringify(baseType) + " is not compiled yet!");
}
return delegate.apply(this, arguments);
};
proxyClass.setDelegate = function (d) {
delegate = d;
proxyClass.prototype = d.prototype;
};
// Make stringify work correctly
proxyClass.overriddenName = name;
return proxyClass;
};
CompileMetadataResolver.prototype.getGeneratedClass = function (dirType, name) {
if (dirType instanceof StaticSymbol) {
return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), name);
}
else {
return this._createProxyClass(dirType, name);
}
};
CompileMetadataResolver.prototype.getComponentViewClass = function (dirType) {
return this.getGeneratedClass(dirType, viewClassName(dirType, 0));
};
CompileMetadataResolver.prototype.getHostComponentViewClass = function (dirType) {
return this.getGeneratedClass(dirType, hostViewClassName(dirType));
};
CompileMetadataResolver.prototype.getHostComponentType = function (dirType) {
var name = identifierName({ reference: dirType }) + "_Host";
if (dirType instanceof StaticSymbol) {
return this._staticSymbolCache.get(dirType.filePath, name);
}
else {
var HostClass = function HostClass() { };
HostClass.overriddenName = name;
return HostClass;
}
};
CompileMetadataResolver.prototype.getRendererType = function (dirType) {
if (dirType instanceof StaticSymbol) {
return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), rendererTypeName(dirType));
}
else {
// returning an object as proxy,
// that we fill later during runtime compilation.
return {};
}
};
CompileMetadataResolver.prototype.getComponentFactory = function (selector, dirType, inputs, outputs) {
if (dirType instanceof StaticSymbol) {
return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), componentFactoryName(dirType));
}
else {
var hostView = this.getHostComponentViewClass(dirType);
// Note: ngContentSelectors will be filled later once the template is
// loaded.
var createComponentFactory = this._reflector.resolveExternalReference(Identifiers.createComponentFactory);
return createComponentFactory(selector, dirType, hostView, inputs, outputs, []);
}
};
CompileMetadataResolver.prototype.initComponentFactory = function (factory, ngContentSelectors) {
if (!(factory instanceof StaticSymbol)) {
(_a = factory.ngContentSelectors).push.apply(_a, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(ngContentSelectors));
}
var _a;
};
CompileMetadataResolver.prototype._loadSummary = function (type, kind) {
var typeSummary = this._summaryCache.get(type);
if (!typeSummary) {
var summary = this._summaryResolver.resolveSummary(type);
typeSummary = summary ? summary.type : null;
this._summaryCache.set(type, typeSummary || null);
}
return typeSummary && typeSummary.summaryKind === kind ? typeSummary : null;
};
CompileMetadataResolver.prototype.getHostComponentMetadata = function (compMeta, hostViewType) {
var hostType = this.getHostComponentType(compMeta.type.reference);
if (!hostViewType) {
hostViewType = this.getHostComponentViewClass(hostType);
}
// Note: ! is ok here as this method should only be called with normalized directive
// metadata, which always fills in the selector.
var template = CssSelector.parse(compMeta.selector)[0].getMatchingElementTemplate();
var templateUrl = '';
var htmlAst = this._htmlParser.parse(template, templateUrl);
return CompileDirectiveMetadata.create({
isHost: true,
type: { reference: hostType, diDeps: [], lifecycleHooks: [] },
template: new CompileTemplateMetadata({
encapsulation: ViewEncapsulation.None,
template: template,
templateUrl: templateUrl,
htmlAst: htmlAst,
styles: [],
styleUrls: [],
ngContentSelectors: [],
animations: [],
isInline: true,
externalStylesheets: [],
interpolation: null,
preserveWhitespaces: false,
}),
exportAs: null,
changeDetection: ChangeDetectionStrategy.Default,
inputs: [],
outputs: [],
host: {},
isComponent: true,
selector: '*',
providers: [],
viewProviders: [],
queries: [],
guards: {},
viewQueries: [],
componentViewType: hostViewType,
rendererType: { id: '__Host__', encapsulation: ViewEncapsulation.None, styles: [], data: {} },
entryComponents: [],
componentFactory: null
});
};
CompileMetadataResolver.prototype.loadDirectiveMetadata = function (ngModuleType, directiveType, isSync) {
var _this = this;
if (this._directiveCache.has(directiveType)) {
return null;
}
directiveType = resolveForwardRef(directiveType);
var _a = this.getNonNormalizedDirectiveMetadata(directiveType), annotation = _a.annotation, metadata = _a.metadata;
var createDirectiveMetadata = function (templateMetadata) {
var normalizedDirMeta = new CompileDirectiveMetadata({
isHost: false,
type: metadata.type,
isComponent: metadata.isComponent,
selector: metadata.selector,
exportAs: metadata.exportAs,
changeDetection: metadata.changeDetection,
inputs: metadata.inputs,
outputs: metadata.outputs,
hostListeners: metadata.hostListeners,
hostProperties: metadata.hostProperties,
hostAttributes: metadata.hostAttributes,
providers: metadata.providers,
viewProviders: metadata.viewProviders,
queries: metadata.queries,
guards: metadata.guards,
viewQueries: metadata.viewQueries,
entryComponents: metadata.entryComponents,
componentViewType: metadata.componentViewType,
rendererType: metadata.rendererType,
componentFactory: metadata.componentFactory,
template: templateMetadata
});
if (templateMetadata) {
_this.initComponentFactory(metadata.componentFactory, templateMetadata.ngContentSelectors);
}
_this._directiveCache.set(directiveType, normalizedDirMeta);
_this._summaryCache.set(directiveType, normalizedDirMeta.toSummary());
return null;
};
if (metadata.isComponent) {
var template = metadata.template;
var templateMeta = this._directiveNormalizer.normalizeTemplate({
ngModuleType: ngModuleType,
componentType: directiveType,
moduleUrl: this._reflector.componentModuleUrl(directiveType, annotation),
encapsulation: template.encapsulation,
template: template.template,
templateUrl: template.templateUrl,
styles: template.styles,
styleUrls: template.styleUrls,
animations: template.animations,
interpolation: template.interpolation,
preserveWhitespaces: template.preserveWhitespaces
});
if (isPromise(templateMeta) && isSync) {
this._reportError(componentStillLoadingError(directiveType), directiveType);
return null;
}
return SyncAsync.then(templateMeta, createDirectiveMetadata);
}
else {
// directive
createDirectiveMetadata(null);
return null;
}
};
CompileMetadataResolver.prototype.getNonNormalizedDirectiveMetadata = function (directiveType) {
var _this = this;
directiveType = resolveForwardRef(directiveType);
if (!directiveType) {
return null;
}
var cacheEntry = this._nonNormalizedDirectiveCache.get(directiveType);
if (cacheEntry) {
return cacheEntry;
}
var dirMeta = this._directiveResolver.resolve(directiveType, false);
if (!dirMeta) {
return null;
}
var nonNormalizedTemplateMetadata = undefined;
if (createComponent.isTypeOf(dirMeta)) {
// component
var compMeta = dirMeta;
assertArrayOfStrings('styles', compMeta.styles);
assertArrayOfStrings('styleUrls', compMeta.styleUrls);
assertInterpolationSymbols('interpolation', compMeta.interpolation);
var animations = compMeta.animations;
nonNormalizedTemplateMetadata = new CompileTemplateMetadata({
encapsulation: noUndefined(compMeta.encapsulation),
template: noUndefined(compMeta.template),
templateUrl: noUndefined(compMeta.templateUrl),
htmlAst: null,
styles: compMeta.styles || [],
styleUrls: compMeta.styleUrls || [],
animations: animations || [],
interpolation: noUndefined(compMeta.interpolation),
isInline: !!compMeta.template,
externalStylesheets: [],
ngContentSelectors: [],
preserveWhitespaces: noUndefined(dirMeta.preserveWhitespaces),
});
}
var changeDetectionStrategy = null;
var viewProviders = [];
var entryComponentMetadata = [];
var selector = dirMeta.selector;
if (createComponent.isTypeOf(dirMeta)) {
// Component
var compMeta = dirMeta;
changeDetectionStrategy = compMeta.changeDetection;
if (compMeta.viewProviders) {
viewProviders = this._getProvidersMetadata(compMeta.viewProviders, entryComponentMetadata, "viewProviders for \"" + stringifyType(directiveType) + "\"", [], directiveType);
}
if (compMeta.entryComponents) {
entryComponentMetadata = flattenAndDedupeArray(compMeta.entryComponents)
.map(function (type) { return _this._getEntryComponentMetadata(type); })
.concat(entryComponentMetadata);
}
if (!selector) {
selector = this._schemaRegistry.getDefaultComponentElementName();
}
}
else {
// Directive
if (!selector) {
this._reportError(syntaxError("Directive " + stringifyType(directiveType) + " has no selector, please add it!"), directiveType);
selector = 'error';
}
}
var providers = [];
if (dirMeta.providers != null) {
providers = this._getProvidersMetadata(dirMeta.providers, entryComponentMetadata, "providers for \"" + stringifyType(directiveType) + "\"", [], directiveType);
}
var queries = [];
var viewQueries = [];
if (dirMeta.queries != null) {
queries = this._getQueriesMetadata(dirMeta.queries, false, directiveType);
viewQueries = this._getQueriesMetadata(dirMeta.queries, true, directiveType);
}
var metadata = CompileDirectiveMetadata.create({
isHost: false,
selector: selector,
exportAs: noUndefined(dirMeta.exportAs),
isComponent: !!nonNormalizedTemplateMetadata,
type: this._getTypeMetadata(directiveType),
template: nonNormalizedTemplateMetadata,
changeDetection: changeDetectionStrategy,
inputs: dirMeta.inputs || [],
outputs: dirMeta.outputs || [],
host: dirMeta.host || {},
providers: providers || [],
viewProviders: viewProviders || [],
queries: queries || [],
guards: dirMeta.guards || {},
viewQueries: viewQueries || [],
entryComponents: entryComponentMetadata,
componentViewType: nonNormalizedTemplateMetadata ? this.getComponentViewClass(directiveType) :
null,
rendererType: nonNormalizedTemplateMetadata ? this.getRendererType(directiveType) : null,
componentFactory: null
});
if (nonNormalizedTemplateMetadata) {
metadata.componentFactory =
this.getComponentFactory(selector, directiveType, metadata.inputs, metadata.outputs);
}
cacheEntry = { metadata: metadata, annotation: dirMeta };
this._nonNormalizedDirectiveCache.set(directiveType, cacheEntry);
return cacheEntry;
};
/**
* Gets the metadata for the given directive.
* This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
*/
CompileMetadataResolver.prototype.getDirectiveMetadata = function (directiveType) {
var dirMeta = this._directiveCache.get(directiveType);
if (!dirMeta) {
this._reportError(syntaxError("Illegal state: getDirectiveMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Directive " + stringifyType(directiveType) + "."), directiveType);
}
return dirMeta;
};
CompileMetadataResolver.prototype.getDirectiveSummary = function (dirType) {
var dirSummary = this._loadSummary(dirType, CompileSummaryKind.Directive);
if (!dirSummary) {
this._reportError(syntaxError("Illegal state: Could not load the summary for directive " + stringifyType(dirType) + "."), dirType);
}
return dirSummary;
};
CompileMetadataResolver.prototype.isDirective = function (type) {
return !!this._loadSummary(type, CompileSummaryKind.Directive) ||
this._directiveResolver.isDirective(type);
};
CompileMetadataResolver.prototype.isPipe = function (type) {
return !!this._loadSummary(type, CompileSummaryKind.Pipe) ||
this._pipeResolver.isPipe(type);
};
CompileMetadataResolver.prototype.isNgModule = function (type) {
return !!this._loadSummary(type, CompileSummaryKind.NgModule) ||
this._ngModuleResolver.isNgModule(type);
};
CompileMetadataResolver.prototype.getNgModuleSummary = function (moduleType, alreadyCollecting) {
if (alreadyCollecting === void 0) { alreadyCollecting = null; }
var moduleSummary = this._loadSummary(moduleType, CompileSummaryKind.NgModule);
if (!moduleSummary) {
var moduleMeta = this.getNgModuleMetadata(moduleType, false, alreadyCollecting);
moduleSummary = moduleMeta ? moduleMeta.toSummary() : null;
if (moduleSummary) {
this._summaryCache.set(moduleType, moduleSummary);
}
}
return moduleSummary;
};
/**
* Loads the declared directives and pipes of an NgModule.
*/
CompileMetadataResolver.prototype.loadNgModuleDirectiveAndPipeMetadata = function (moduleType, isSync, throwIfNotFound) {
var _this = this;
if (throwIfNotFound === void 0) { throwIfNotFound = true; }
var ngModule = this.getNgModuleMetadata(moduleType, throwIfNotFound);
var loading = [];
if (ngModule) {
ngModule.declaredDirectives.forEach(function (id) {
var promise = _this.loadDirectiveMetadata(moduleType, id.reference, isSync);
if (promise) {
loading.push(promise);
}
});
ngModule.declaredPipes.forEach(function (id) { return _this._loadPipeMetadata(id.reference); });
}
return Promise.all(loading);
};
CompileMetadataResolver.prototype.getShallowModuleMetadata = function (moduleType) {
var compileMeta = this._shallowModuleCache.get(moduleType);
if (compileMeta) {
return compileMeta;
}
var ngModuleMeta = findLast(this._reflector.shallowAnnotations(moduleType), createNgModule.isTypeOf);
compileMeta = {
type: this._getTypeMetadata(moduleType),
rawExports: ngModuleMeta.exports,
rawImports: ngModuleMeta.imports,
rawProviders: ngModuleMeta.providers,
};
this._shallowModuleCache.set(moduleType, compileMeta);
return compileMeta;
};
CompileMetadataResolver.prototype.getNgModuleMetadata = function (moduleType, throwIfNotFound, alreadyCollecting) {
var _this = this;
if (throwIfNotFound === void 0) { throwIfNotFound = true; }
if (alreadyCollecting === void 0) { alreadyCollecting = null; }
moduleType = resolveForwardRef(moduleType);
var compileMeta = this._ngModuleCache.get(moduleType);
if (compileMeta) {
return compileMeta;
}
var meta = this._ngModuleResolver.resolve(moduleType, throwIfNotFound);
if (!meta) {
return null;
}
var declaredDirectives = [];
var exportedNonModuleIdentifiers = [];
var declaredPipes = [];
var importedModules = [];
var exportedModules = [];
var providers = [];
var entryComponents = [];
var bootstrapComponents = [];
var schemas = [];
if (meta.imports) {
flattenAndDedupeArray(meta.imports).forEach(function (importedType) {
var importedModuleType = undefined;
if (isValidType(importedType)) {
importedModuleType = importedType;
}
else if (importedType && importedType.ngModule) {
var moduleWithProviders = importedType;
importedModuleType = moduleWithProviders.ngModule;
if (moduleWithProviders.providers) {
providers.push.apply(providers, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(_this._getProvidersMetadata(moduleWithProviders.providers, entryComponents, "provider for the NgModule '" + stringifyType(importedModuleType) + "'", [], importedType)));
}
}
if (importedModuleType) {
if (_this._checkSelfImport(moduleType, importedModuleType))
return;
if (!alreadyCollecting)
alreadyCollecting = new Set();
if (alreadyCollecting.has(importedModuleType)) {
_this._reportError(syntaxError(_this._getTypeDescriptor(importedModuleType) + " '" + stringifyType(importedType) + "' is imported recursively by the module '" + stringifyType(moduleType) + "'."), moduleType);
return;
}
alreadyCollecting.add(importedModuleType);
var importedModuleSummary = _this.getNgModuleSummary(importedModuleType, alreadyCollecting);
alreadyCollecting.delete(importedModuleType);
if (!importedModuleSummary) {
_this._reportError(syntaxError("Unexpected " + _this._getTypeDescriptor(importedType) + " '" + stringifyType(importedType) + "' imported by the module '" + stringifyType(moduleType) + "'. Please add a @NgModule annotation."), moduleType);
return;
}
importedModules.push(importedModuleSummary);
}
else {
_this._reportError(syntaxError("Unexpected value '" + stringifyType(importedType) + "' imported by the module '" + stringifyType(moduleType) + "'"), moduleType);
return;
}
});
}
if (meta.exports) {
flattenAndDedupeArray(meta.exports).forEach(function (exportedType) {
if (!isValidType(exportedType)) {
_this._reportError(syntaxError("Unexpected value '" + stringifyType(exportedType) + "' exported by the module '" + stringifyType(moduleType) + "'"), moduleType);
return;
}
if (!alreadyCollecting)
alreadyCollecting = new Set();
if (alreadyCollecting.has(exportedType)) {
_this._reportError(syntaxError(_this._getTypeDescriptor(exportedType) + " '" + stringify(exportedType) + "' is exported recursively by the module '" + stringifyType(moduleType) + "'"), moduleType);
return;
}
alreadyCollecting.add(exportedType);
var exportedModuleSummary = _this.getNgModuleSummary(exportedType, alreadyCollecting);
alreadyCollecting.delete(exportedType);
if (exportedModuleSummary) {
exportedModules.push(exportedModuleSummary);
}
else {
exportedNonModuleIdentifiers.push(_this._getIdentifierMetadata(exportedType));
}
});
}
// Note: This will be modified later, so we rely on
// getting a new instance every time!
var transitiveModule = this._getTransitiveNgModuleMetadata(importedModules, exportedModules);
if (meta.declarations) {
flattenAndDedupeArray(meta.declarations).forEach(function (declaredType) {
if (!isValidType(declaredType)) {
_this._reportError(syntaxError("Unexpected value '" + stringifyType(declaredType) + "' declared by the module '" + stringifyType(moduleType) + "'"), moduleType);
return;
}
var declaredIdentifier = _this._getIdentifierMetadata(declaredType);
if (_this.isDirective(declaredType)) {
transitiveModule.addDirective(declaredIdentifier);
declaredDirectives.push(declaredIdentifier);
_this._addTypeToModule(declaredType, moduleType);
}
else if (_this.isPipe(declaredType)) {
transitiveModule.addPipe(declaredIdentifier);
transitiveModule.pipes.push(declaredIdentifier);
declaredPipes.push(declaredIdentifier);
_this._addTypeToModule(declaredType, moduleType);
}
else {
_this._reportError(syntaxError("Unexpected " + _this._getTypeDescriptor(declaredType) + " '" + stringifyType(declaredType) + "' declared by the module '" + stringifyType(moduleType) + "'. Please add a @Pipe/@Directive/@Component annotation."), moduleType);
return;
}
});
}
var exportedDirectives = [];
var exportedPipes = [];
exportedNonModuleIdentifiers.forEach(function (exportedId) {
if (transitiveModule.directivesSet.has(exportedId.reference)) {
exportedDirectives.push(exportedId);
transitiveModule.addExportedDirective(exportedId);
}
else if (transitiveModule.pipesSet.has(exportedId.reference)) {
exportedPipes.push(exportedId);
transitiveModule.addExportedPipe(exportedId);
}
else {
_this._reportError(syntaxError("Can't export " + _this._getTypeDescriptor(exportedId.reference) + " " + stringifyType(exportedId.reference) + " from " + stringifyType(moduleType) + " as it was neither declared nor imported!"), moduleType);
return;
}
});
// The providers of the module have to go last
// so that they overwrite any other provider we already added.
if (meta.providers) {
providers.push.apply(providers, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(this._getProvidersMetadata(meta.providers, entryComponents, "provider for the NgModule '" + stringifyType(moduleType) + "'", [], moduleType)));
}
if (meta.entryComponents) {
entryComponents.push.apply(entryComponents, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(flattenAndDedupeArray(meta.entryComponents)
.map(function (type) { return _this._getEntryComponentMetadata(type); })));
}
if (meta.bootstrap) {
flattenAndDedupeArray(meta.bootstrap).forEach(function (type) {
if (!isValidType(type)) {
_this._reportError(syntaxError("Unexpected value '" + stringifyType(type) + "' used in the bootstrap property of module '" + stringifyType(moduleType) + "'"), moduleType);
return;
}
bootstrapComponents.push(_this._getIdentifierMetadata(type));
});
}
entryComponents.push.apply(entryComponents, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(bootstrapComponents.map(function (type) { return _this._getEntryComponentMetadata(type.reference); })));
if (meta.schemas) {
schemas.push.apply(schemas, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(flattenAndDedupeArray(meta.schemas)));
}
compileMeta = new CompileNgModuleMetadata({
type: this._getTypeMetadata(moduleType),
providers: providers,
entryComponents: entryComponents,
bootstrapComponents: bootstrapComponents,
schemas: schemas,
declaredDirectives: declaredDirectives,
exportedDirectives: exportedDirectives,
declaredPipes: declaredPipes,
exportedPipes: exportedPipes,
importedModules: importedModules,
exportedModules: exportedModules,
transitiveModule: transitiveModule,
id: meta.id || null,
});
entryComponents.forEach(function (id) { return transitiveModule.addEntryComponent(id); });
providers.forEach(function (provider) { return transitiveModule.addProvider(provider, compileMeta.type); });
transitiveModule.addModule(compileMeta.type);
this._ngModuleCache.set(moduleType, compileMeta);
return compileMeta;
};
CompileMetadataResolver.prototype._checkSelfImport = function (moduleType, importedModuleType) {
if (moduleType === importedModuleType) {
this._reportError(syntaxError("'" + stringifyType(moduleType) + "' module can't import itself"), moduleType);
return true;
}
return false;
};
CompileMetadataResolver.prototype._getTypeDescriptor = function (type) {
if (isValidType(type)) {
if (this.isDirective(type)) {
return 'directive';
}
if (this.isPipe(type)) {
return 'pipe';
}
if (this.isNgModule(type)) {
return 'module';
}
}
if (type.provide) {
return 'provider';
}
return 'value';
};
CompileMetadataResolver.prototype._addTypeToModule = function (type, moduleType) {
var oldModule = this._ngModuleOfTypes.get(type);
if (oldModule && oldModule !== moduleType) {
this._reportError(syntaxError("Type " + stringifyType(type) + " is part of the declarations of 2 modules: " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + "! " +
("Please consider moving " + stringifyType(type) + " to a higher module that imports " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + ". ") +
("You can also create a new NgModule that exports and includes " + stringifyType(type) + " then import that NgModule in " + stringifyType(oldModule) + " and " + stringifyType(moduleType) + ".")), moduleType);
return;
}
this._ngModuleOfTypes.set(type, moduleType);
};
CompileMetadataResolver.prototype._getTransitiveNgModuleMetadata = function (importedModules, exportedModules) {
// collect `providers` / `entryComponents` from all imported and all exported modules
var result = new TransitiveCompileNgModuleMetadata();
var modulesByToken = new Map();
importedModules.concat(exportedModules).forEach(function (modSummary) {
modSummary.modules.forEach(function (mod) { return result.addModule(mod); });
modSummary.entryComponents.forEach(function (comp) { return result.addEntryComponent(comp); });
var addedTokens = new Set();
modSummary.providers.forEach(function (entry) {
var tokenRef = tokenReference(entry.provider.token);
var prevModules = modulesByToken.get(tokenRef);
if (!prevModules) {
prevModules = new Set();
modulesByToken.set(tokenRef, prevModules);
}
var moduleRef = entry.module.reference;
// Note: the providers of one module may still contain multiple providers
// per token (e.g. for multi providers), and we need to preserve these.
if (addedTokens.has(tokenRef) || !prevModules.has(moduleRef)) {
prevModules.add(moduleRef);
addedTokens.add(tokenRef);
result.addProvider(entry.provider, entry.module);
}
});
});
exportedModules.forEach(function (modSummary) {
modSummary.exportedDirectives.forEach(function (id) { return result.addExportedDirective(id); });
modSummary.exportedPipes.forEach(function (id) { return result.addExportedPipe(id); });
});
importedModules.forEach(function (modSummary) {
modSummary.exportedDirectives.forEach(function (id) { return result.addDirective(id); });
modSummary.exportedPipes.forEach(function (id) { return result.addPipe(id); });
});
return result;
};
CompileMetadataResolver.prototype._getIdentifierMetadata = function (type) {
type = resolveForwardRef(type);
return { reference: type };
};
CompileMetadataResolver.prototype.isInjectable = function (type) {
var annotations = this._reflector.tryAnnotations(type);
return annotations.some(function (ann) { return createInjectable.isTypeOf(ann); });
};
CompileMetadataResolver.prototype.getInjectableSummary = function (type) {
return {
summaryKind: CompileSummaryKind.Injectable,
type: this._getTypeMetadata(type, null, false)
};
};
CompileMetadataResolver.prototype.getInjectableMetadata = function (type, dependencies, throwOnUnknownDeps) {
if (dependencies === void 0) { dependencies = null; }
if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
var typeSummary = this._loadSummary(type, CompileSummaryKind.Injectable);
var typeMetadata = typeSummary ?
typeSummary.type :
this._getTypeMetadata(type, dependencies, throwOnUnknownDeps);
var annotations = this._reflector.annotations(type).filter(function (ann) { return createInjectable.isTypeOf(ann); });
if (annotations.length === 0) {
return null;
}
var meta = annotations[annotations.length - 1];
return {
symbol: type,
type: typeMetadata,
providedIn: meta.providedIn,
useValue: meta.useValue,
useClass: meta.useClass,
useExisting: meta.useExisting,
useFactory: meta.useFactory,
deps: meta.deps,
};
};
CompileMetadataResolver.prototype._getTypeMetadata = function (type, dependencies, throwOnUnknownDeps) {
if (dependencies === void 0) { dependencies = null; }
if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
var identifier = this._getIdentifierMetadata(type);
return {
reference: identifier.reference,
diDeps: this._getDependenciesMetadata(identifier.reference, dependencies, throwOnUnknownDeps),
lifecycleHooks: getAllLifecycleHooks(this._reflector, identifier.reference),
};
};
CompileMetadataResolver.prototype._getFactoryMetadata = function (factory, dependencies) {
if (dependencies === void 0) { dependencies = null; }
factory = resolveForwardRef(factory);
return { reference: factory, diDeps: this._getDependenciesMetadata(factory, dependencies) };
};
/**
* Gets the metadata for the given pipe.
* This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
*/
CompileMetadataResolver.prototype.getPipeMetadata = function (pipeType) {
var pipeMeta = this._pipeCache.get(pipeType);
if (!pipeMeta) {
this._reportError(syntaxError("Illegal state: getPipeMetadata can only be called after loadNgModuleDirectiveAndPipeMetadata for a module that declares it. Pipe " + stringifyType(pipeType) + "."), pipeType);
}
return pipeMeta || null;
};
CompileMetadataResolver.prototype.getPipeSummary = function (pipeType) {
var pipeSummary = this._loadSummary(pipeType, CompileSummaryKind.Pipe);
if (!pipeSummary) {
this._reportError(syntaxError("Illegal state: Could not load the summary for pipe " + stringifyType(pipeType) + "."), pipeType);
}
return pipeSummary;
};
CompileMetadataResolver.prototype.getOrLoadPipeMetadata = function (pipeType) {
var pipeMeta = this._pipeCache.get(pipeType);
if (!pipeMeta) {
pipeMeta = this._loadPipeMetadata(pipeType);
}
return pipeMeta;
};
CompileMetadataResolver.prototype._loadPipeMetadata = function (pipeType) {
pipeType = resolveForwardRef(pipeType);
var pipeAnnotation = this._pipeResolver.resolve(pipeType);
var pipeMeta = new CompilePipeMetadata({
type: this._getTypeMetadata(pipeType),
name: pipeAnnotation.name,
pure: !!pipeAnnotation.pure
});
this._pipeCache.set(pipeType, pipeMeta);
this._summaryCache.set(pipeType, pipeMeta.toSummary());
return pipeMeta;
};
CompileMetadataResolver.prototype._getDependenciesMetadata = function (typeOrFunc, dependencies, throwOnUnknownDeps) {
var _this = this;
if (throwOnUnknownDeps === void 0) { throwOnUnknownDeps = true; }
var hasUnknownDeps = false;
var params = dependencies || this._reflector.parameters(typeOrFunc) || [];
var dependenciesMetadata = params.map(function (param) {
var isAttribute = false;
var isHost = false;
var isSelf = false;
var isSkipSelf = false;
var isOptional = false;
var token = null;
if (Array.isArray(param)) {
param.forEach(function (paramEntry) {
if (createHost.isTypeOf(paramEntry)) {
isHost = true;
}
else if (createSelf.isTypeOf(paramEntry)) {
isSelf = true;
}
else if (createSkipSelf.isTypeOf(paramEntry)) {
isSkipSelf = true;
}
else if (createOptional.isTypeOf(paramEntry)) {
isOptional = true;
}
else if (createAttribute.isTypeOf(paramEntry)) {
isAttribute = true;
token = paramEntry.attributeName;
}
else if (createInject.isTypeOf(paramEntry)) {
token = paramEntry.token;
}
else if (createInjectionToken.isTypeOf(paramEntry) || paramEntry instanceof StaticSymbol) {
token = paramEntry;
}
else if (isValidType(paramEntry) && token == null) {
token = paramEntry;
}
});
}
else {
token = param;
}
if (token == null) {
hasUnknownDeps = true;
return null;
}
return {
isAttribute: isAttribute,
isHost: isHost,
isSelf: isSelf,
isSkipSelf: isSkipSelf,
isOptional: isOptional,
token: _this._getTokenMetadata(token)
};
});
if (hasUnknownDeps) {
var depsTokens = dependenciesMetadata.map(function (dep) { return dep ? stringifyType(dep.token) : '?'; }).join(', ');
var message = "Can't resolve all parameters for " + stringifyType(typeOrFunc) + ": (" + depsTokens + ").";
if (throwOnUnknownDeps || this._config.strictInjectionParameters) {
this._reportError(syntaxError(message), typeOrFunc);
}
else {
this._console.warn("Warning: " + message + " This will become an error in Angular v6.x");
}
}
return dependenciesMetadata;
};
CompileMetadataResolver.prototype._getTokenMetadata = function (token) {
token = resolveForwardRef(token);
var compileToken;
if (typeof token === 'string') {
compileToken = { value: token };
}
else {
compileToken = { identifier: { reference: token } };
}
return compileToken;
};
CompileMetadataResolver.prototype._getProvidersMetadata = function (providers, targetEntryComponents, debugInfo, compileProviders, type) {
var _this = this;
if (compileProviders === void 0) { compileProviders = []; }
providers.forEach(function (provider, providerIdx) {
if (Array.isArray(provider)) {
_this._getProvidersMetadata(provider, targetEntryComponents, debugInfo, compileProviders);
}
else {
provider = resolveForwardRef(provider);
var providerMeta = undefined;
if (provider && typeof provider === 'object' && provider.hasOwnProperty('provide')) {
_this._validateProvider(provider);
providerMeta = new ProviderMeta(provider.provide, provider);
}
else if (isValidType(provider)) {
providerMeta = new ProviderMeta(provider, { useClass: provider });
}
else if (provider === void 0) {
_this._reportError(syntaxError("Encountered undefined provider! Usually this means you have a circular dependencies. This might be caused by using 'barrel' index.ts files."));
return;
}
else {
var providersInfo = providers.reduce(function (soFar, seenProvider, seenProviderIdx) {
if (seenProviderIdx < providerIdx) {
soFar.push("" + stringifyType(seenProvider));
}
else if (seenProviderIdx == providerIdx) {
soFar.push("?" + stringifyType(seenProvider) + "?");
}
else if (seenProviderIdx == providerIdx + 1) {
soFar.push('...');
}
return soFar;
}, [])
.join(', ');
_this._reportError(syntaxError("Invalid " + (debugInfo ? debugInfo : 'provider') + " - only instances of Provider and Type are allowed, got: [" + providersInfo + "]"), type);
return;
}
if (providerMeta.token ===
_this._reflector.resolveExternalReference(Identifiers.ANALYZE_FOR_ENTRY_COMPONENTS)) {
targetEntryComponents.push.apply(targetEntryComponents, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(_this._getEntryComponentsFromProvider(providerMeta, type)));
}
else {
compileProviders.push(_this.getProviderMetadata(providerMeta));
}
}
});
return compileProviders;
};
CompileMetadataResolver.prototype._validateProvider = function (provider) {
if (provider.hasOwnProperty('useClass') && provider.useClass == null) {
this._reportError(syntaxError("Invalid provider for " + stringifyType(provider.provide) + ". useClass cannot be " + provider.useClass + ".\n Usually it happens when:\n 1. There's a circular dependency (might be caused by using index.ts (barrel) files).\n 2. Class was used before it was declared. Use forwardRef in this case."));
}
};
CompileMetadataResolver.prototype._getEntryComponentsFromProvider = function (provider, type) {
var _this = this;
var components = [];
var collectedIdentifiers = [];
if (provider.useFactory || provider.useExisting || provider.useClass) {
this._reportError(syntaxError("The ANALYZE_FOR_ENTRY_COMPONENTS token only supports useValue!"), type);
return [];
}
if (!provider.multi) {
this._reportError(syntaxError("The ANALYZE_FOR_ENTRY_COMPONENTS token only supports 'multi = true'!"), type);
return [];
}
extractIdentifiers(provider.useValue, collectedIdentifiers);
collectedIdentifiers.forEach(function (identifier) {
var entry = _this._getEntryComponentMetadata(identifier.reference, false);
if (entry) {
components.push(entry);
}
});
return components;
};
CompileMetadataResolver.prototype._getEntryComponentMetadata = function (dirType, throwIfNotFound) {
if (throwIfNotFound === void 0) { throwIfNotFound = true; }
var dirMeta = this.getNonNormalizedDirectiveMetadata(dirType);
if (dirMeta && dirMeta.metadata.isComponent) {
return { componentType: dirType, componentFactory: dirMeta.metadata.componentFactory };
}
var dirSummary = this._loadSummary(dirType, CompileSummaryKind.Directive);
if (dirSummary && dirSummary.isComponent) {
return { componentType: dirType, componentFactory: dirSummary.componentFactory };
}
if (throwIfNotFound) {
throw syntaxError(dirType.name + " cannot be used as an entry component.");
}
return null;
};
CompileMetadataResolver.prototype._getInjectableTypeMetadata = function (type, dependencies) {
if (dependencies === void 0) { dependencies = null; }
var typeSummary = this._loadSummary(type, CompileSummaryKind.Injectable);
if (typeSummary) {
return typeSummary.type;
}
return this._getTypeMetadata(type, dependencies);
};
CompileMetadataResolver.prototype.getProviderMetadata = function (provider) {
var compileDeps = undefined;
var compileTypeMetadata = null;
var compileFactoryMetadata = null;
var token = this._getTokenMetadata(provider.token);
if (provider.useClass) {
compileTypeMetadata =
this._getInjectableTypeMetadata(provider.useClass, provider.dependencies);
compileDeps = compileTypeMetadata.diDeps;
if (provider.token === provider.useClass) {
// use the compileTypeMetadata as it contains information about lifecycleHooks...
token = { identifier: compileTypeMetadata };
}
}
else if (provider.useFactory) {
compileFactoryMetadata = this._getFactoryMetadata(provider.useFactory, provider.dependencies);
compileDeps = compileFactoryMetadata.diDeps;
}
return {
token: token,
useClass: compileTypeMetadata,
useValue: provider.useValue,
useFactory: compileFactoryMetadata,
useExisting: provider.useExisting ? this._getTokenMetadata(provider.useExisting) : undefined,
deps: compileDeps,
multi: provider.multi
};
};
CompileMetadataResolver.prototype._getQueriesMetadata = function (queries, isViewQuery, directiveType) {
var _this = this;
var res = [];
Object.keys(queries).forEach(function (propertyName) {
var query = queries[propertyName];
if (query.isViewQuery === isViewQuery) {
res.push(_this._getQueryMetadata(query, propertyName, directiveType));
}
});
return res;
};
CompileMetadataResolver.prototype._queryVarBindings = function (selector) { return selector.split(/\s*,\s*/); };
CompileMetadataResolver.prototype._getQueryMetadata = function (q, propertyName, typeOrFunc) {
var _this = this;
var selectors;
if (typeof q.selector === 'string') {
selectors =
this._queryVarBindings(q.selector).map(function (varName) { return _this._getTokenMetadata(varName); });
}
else {
if (!q.selector) {
this._reportError(syntaxError("Can't construct a query for the property \"" + propertyName + "\" of \"" + stringifyType(typeOrFunc) + "\" since the query selector wasn't defined."), typeOrFunc);
selectors = [];
}
else {
selectors = [this._getTokenMetadata(q.selector)];
}
}
return {
selectors: selectors,
first: q.first,
descendants: q.descendants, propertyName: propertyName,
read: q.read ? this._getTokenMetadata(q.read) : null
};
};
CompileMetadataResolver.prototype._reportError = function (error$$1, type, otherType) {
if (this._errorCollector) {
this._errorCollector(error$$1, type);
if (otherType) {
this._errorCollector(error$$1, otherType);
}
}
else {
throw error$$1;
}
};
return CompileMetadataResolver;
}());
function flattenArray(tree, out) {
if (out === void 0) { out = []; }
if (tree) {
for (var i = 0; i < tree.length; i++) {
var item = resolveForwardRef(tree[i]);
if (Array.isArray(item)) {
flattenArray(item, out);
}
else {
out.push(item);
}
}
}
return out;
}
function dedupeArray(array) {
if (array) {
return Array.from(new Set(array));
}
return [];
}
function flattenAndDedupeArray(tree) {
return dedupeArray(flattenArray(tree));
}
function isValidType(value) {
return (value instanceof StaticSymbol) || (value instanceof Type);
}
function extractIdentifiers(value, targetIdentifiers) {
visitValue(value, new _CompileValueConverter(), targetIdentifiers);
}
var _CompileValueConverter = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(_CompileValueConverter, _super);
function _CompileValueConverter() {
return _super !== null && _super.apply(this, arguments) || this;
}
_CompileValueConverter.prototype.visitOther = function (value, targetIdentifiers) {
targetIdentifiers.push({ reference: value });
};
return _CompileValueConverter;
}(ValueTransformer));
function stringifyType(type) {
if (type instanceof StaticSymbol) {
return type.name + " in " + type.filePath;
}
else {
return stringify(type);
}
}
/**
* Indicates that a component is still being loaded in a synchronous compile.
*/
function componentStillLoadingError(compType) {
var error$$1 = Error("Can't compile synchronously as " + stringify(compType) + " is still being loaded!");
error$$1[ERROR_COMPONENT_TYPE] = compType;
return error$$1;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var ProviderError = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(ProviderError, _super);
function ProviderError(message, span) {
return _super.call(this, span, message) || this;
}
return ProviderError;
}(ParseError));
var ProviderViewContext = /** @class */ (function () {
function ProviderViewContext(reflector, component) {
var _this = this;
this.reflector = reflector;
this.component = component;
this.errors = [];
this.viewQueries = _getViewQueries(component);
this.viewProviders = new Map();
component.viewProviders.forEach(function (provider) {
if (_this.viewProviders.get(tokenReference(provider.token)) == null) {
_this.viewProviders.set(tokenReference(provider.token), true);
}
});
}
return ProviderViewContext;
}());
var ProviderElementContext = /** @class */ (function () {
function ProviderElementContext(viewContext, _parent, _isViewRoot, _directiveAsts, attrs, refs, isTemplate, contentQueryStartId, _sourceSpan) {
var _this = this;
this.viewContext = viewContext;
this._parent = _parent;
this._isViewRoot = _isViewRoot;
this._directiveAsts = _directiveAsts;
this._sourceSpan = _sourceSpan;
this._transformedProviders = new Map();
this._seenProviders = new Map();
this._queriedTokens = new Map();
this.transformedHasViewContainer = false;
this._attrs = {};
attrs.forEach(function (attrAst) { return _this._attrs[attrAst.name] = attrAst.value; });
var directivesMeta = _directiveAsts.map(function (directiveAst) { return directiveAst.directive; });
this._allProviders =
_resolveProvidersFromDirectives(directivesMeta, _sourceSpan, viewContext.errors);
this._contentQueries = _getContentQueries(contentQueryStartId, directivesMeta);
Array.from(this._allProviders.values()).forEach(function (provider) {
_this._addQueryReadsTo(provider.token, provider.token, _this._queriedTokens);
});
if (isTemplate) {
var templateRefId = createTokenForExternalReference(this.viewContext.reflector, Identifiers.TemplateRef);
this._addQueryReadsTo(templateRefId, templateRefId, this._queriedTokens);
}
refs.forEach(function (refAst) {
var defaultQueryValue = refAst.value ||
createTokenForExternalReference(_this.viewContext.reflector, Identifiers.ElementRef);
_this._addQueryReadsTo({ value: refAst.name }, defaultQueryValue, _this._queriedTokens);
});
if (this._queriedTokens.get(this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef))) {
this.transformedHasViewContainer = true;
}
// create the providers that we know are eager first
Array.from(this._allProviders.values()).forEach(function (provider) {
var eager = provider.eager || _this._queriedTokens.get(tokenReference(provider.token));
if (eager) {
_this._getOrCreateLocalProvider(provider.providerType, provider.token, true);
}
});
}
ProviderElementContext.prototype.afterElement = function () {
var _this = this;
// collect lazy providers
Array.from(this._allProviders.values()).forEach(function (provider) {
_this._getOrCreateLocalProvider(provider.providerType, provider.token, false);
});
};
Object.defineProperty(ProviderElementContext.prototype, "transformProviders", {
get: function () {
// Note: Maps keep their insertion order.
var lazyProviders = [];
var eagerProviders = [];
this._transformedProviders.forEach(function (provider) {
if (provider.eager) {
eagerProviders.push(provider);
}
else {
lazyProviders.push(provider);
}
});
return lazyProviders.concat(eagerProviders);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ProviderElementContext.prototype, "transformedDirectiveAsts", {
get: function () {
var sortedProviderTypes = this.transformProviders.map(function (provider) { return provider.token.identifier; });
var sortedDirectives = this._directiveAsts.slice();
sortedDirectives.sort(function (dir1, dir2) { return sortedProviderTypes.indexOf(dir1.directive.type) -
sortedProviderTypes.indexOf(dir2.directive.type); });
return sortedDirectives;
},
enumerable: true,
configurable: true
});
Object.defineProperty(ProviderElementContext.prototype, "queryMatches", {
get: function () {
var allMatches = [];
this._queriedTokens.forEach(function (matches) { allMatches.push.apply(allMatches, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(matches)); });
return allMatches;
},
enumerable: true,
configurable: true
});
ProviderElementContext.prototype._addQueryReadsTo = function (token, defaultValue, queryReadTokens) {
this._getQueriesFor(token).forEach(function (query) {
var queryValue = query.meta.read || defaultValue;
var tokenRef = tokenReference(queryValue);
var queryMatches = queryReadTokens.get(tokenRef);
if (!queryMatches) {
queryMatches = [];
queryReadTokens.set(tokenRef, queryMatches);
}
queryMatches.push({ queryId: query.queryId, value: queryValue });
});
};
ProviderElementContext.prototype._getQueriesFor = function (token) {
var result = [];
var currentEl = this;
var distance = 0;
var queries;
while (currentEl !== null) {
queries = currentEl._contentQueries.get(tokenReference(token));
if (queries) {
result.push.apply(result, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(queries.filter(function (query) { return query.meta.descendants || distance <= 1; })));
}
if (currentEl._directiveAsts.length > 0) {
distance++;
}
currentEl = currentEl._parent;
}
queries = this.viewContext.viewQueries.get(tokenReference(token));
if (queries) {
result.push.apply(result, Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(queries));
}
return result;
};
ProviderElementContext.prototype._getOrCreateLocalProvider = function (requestingProviderType, token, eager) {
var _this = this;
var resolvedProvider = this._allProviders.get(tokenReference(token));
if (!resolvedProvider || ((requestingProviderType === ProviderAstType.Directive ||
requestingProviderType === ProviderAstType.PublicService) &&
resolvedProvider.providerType === ProviderAstType.PrivateService) ||
((requestingProviderType === ProviderAstType.PrivateService ||
requestingProviderType === ProviderAstType.PublicService) &&
resolvedProvider.providerType === ProviderAstType.Builtin)) {
return null;
}
var transformedProviderAst = this._transformedProviders.get(tokenReference(token));
if (transformedProviderAst) {
return transformedProviderAst;
}
if (this._seenProviders.get(tokenReference(token)) != null) {
this.viewContext.errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), this._sourceSpan));
return null;
}
this._seenProviders.set(tokenReference(token), true);
var transformedProviders = resolvedProvider.providers.map(function (provider) {
var transformedUseValue = provider.useValue;
var transformedUseExisting = provider.useExisting;
var transformedDeps = undefined;
if (provider.useExisting != null) {
var existingDiDep = _this._getDependency(resolvedProvider.providerType, { token: provider.useExisting }, eager);
if (existingDiDep.token != null) {
transformedUseExisting = existingDiDep.token;
}
else {
transformedUseExisting = null;
transformedUseValue = existingDiDep.value;
}
}
else if (provider.useFactory) {
var deps = provider.deps || provider.useFactory.diDeps;
transformedDeps =
deps.map(function (dep) { return _this._getDependency(resolvedProvider.providerType, dep, eager); });
}
else if (provider.useClass) {
var deps = provider.deps || provider.useClass.diDeps;
transformedDeps =
deps.map(function (dep) { return _this._getDependency(resolvedProvider.providerType, dep, eager); });
}
return _transformProvider(provider, {
useExisting: transformedUseExisting,
useValue: transformedUseValue,
deps: transformedDeps
});
});
transformedProviderAst =
_transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders });
this._transformedProviders.set(tokenReference(token), transformedProviderAst);
return transformedProviderAst;
};
ProviderElementContext.prototype._getLocalDependency = function (requestingProviderType, dep, eager) {
if (eager === void 0) { eager = false; }
if (dep.isAttribute) {
var attrValue = this._attrs[dep.token.value];
return { isValue: true, value: attrValue == null ? null : attrValue };
}
if (dep.token != null) {
// access builtints
if ((requestingProviderType === ProviderAstType.Directive ||
requestingProviderType === ProviderAstType.Component)) {
if (tokenReference(dep.token) ===
this.viewContext.reflector.resolveExternalReference(Identifiers.Renderer) ||
tokenReference(dep.token) ===
this.viewContext.reflector.resolveExternalReference(Identifiers.ElementRef) ||
tokenReference(dep.token) ===
this.viewContext.reflector.resolveExternalReference(Identifiers.ChangeDetectorRef) ||
tokenReference(dep.token) ===
this.viewContext.reflector.resolveExternalReference(Identifiers.TemplateRef)) {
return dep;
}
if (tokenReference(dep.token) ===
this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef)) {
this.transformedHasViewContainer = true;
}
}
// access the injector
if (tokenReference(dep.token) ===
this.viewContext.reflector.resolveExternalReference(Identifiers.Injector)) {
return dep;
}
// access providers
if (this._getOrCreateLocalProvider(requestingProviderType, dep.token, eager) != null) {
return dep;
}
}
return null;
};
ProviderElementContext.prototype._getDependency = function (requestingProviderType, dep, eager) {
if (eager === void 0) { eager = false; }
var currElement = this;
var currEager = eager;
var result = null;
if (!dep.isSkipSelf) {
result = this._getLocalDependency(requestingProviderType, dep, eager);
}
if (dep.isSelf) {
if (!result && dep.isOptional) {
result = { isValue: true, value: null };
}
}
else {
// check parent elements
while (!result && currElement._parent) {
var prevElement = currElement;
currElement = currElement._parent;
if (prevElement._isViewRoot) {
currEager = false;
}
result = currElement._getLocalDependency(ProviderAstType.PublicService, dep, currEager);
}
// check @Host restriction
if (!result) {
if (!dep.isHost || this.viewContext.component.isHost ||
this.viewContext.component.type.reference === tokenReference(dep.token) ||
this.viewContext.viewProviders.get(tokenReference(dep.token)) != null) {
result = dep;
}
else {
result = dep.isOptional ? { isValue: true, value: null } : null;
}
}
}
if (!result) {
this.viewContext.errors.push(new ProviderError("No provider for " + tokenName(dep.token), this._sourceSpan));
}
return result;
};
return ProviderElementContext;
}());
var NgModuleProviderAnalyzer = /** @class */ (function () {
function NgModuleProviderAnalyzer(reflector, ngModule, extraProviders, sourceSpan) {
var _this = this;
this.reflector = reflector;
this._transformedProviders = new Map();
this._seenProviders = new Map();
this._errors = [];
this._allProviders = new Map();
ngModule.transitiveModule.modules.forEach(function (ngModuleType) {
var ngModuleProvider = { token: { identifier: ngModuleType }, useClass: ngModuleType };
_resolveProviders([ngModuleProvider], ProviderAstType.PublicService, true, sourceSpan, _this._errors, _this._allProviders, /* isModule */ true);
});
_resolveProviders(ngModule.transitiveModule.providers.map(function (entry) { return entry.provider; }).concat(extraProviders), ProviderAstType.PublicService, false, sourceSpan, this._errors, this._allProviders,
/* isModule */ false);
}
NgModuleProviderAnalyzer.prototype.parse = function () {
var _this = this;
Array.from(this._allProviders.values()).forEach(function (provider) {
_this._getOrCreateLocalProvider(provider.token, provider.eager);
});
if (this._errors.length > 0) {
var errorString = this._errors.join('\n');
throw new Error("Provider parse errors:\n" + errorString);
}
// Note: Maps keep their insertion order.
var lazyProviders = [];
var eagerProviders = [];
this._transformedProviders.forEach(function (provider) {
if (provider.eager) {
eagerProviders.push(provider);
}
else {
lazyProviders.push(provider);
}
});
return lazyProviders.concat(eagerProviders);
};
NgModuleProviderAnalyzer.prototype._getOrCreateLocalProvider = function (token, eager) {
var _this = this;
var resolvedProvider = this._allProviders.get(tokenReference(token));
if (!resolvedProvider) {
return null;
}
var transformedProviderAst = this._transformedProviders.get(tokenReference(token));
if (transformedProviderAst) {
return transformedProviderAst;
}
if (this._seenProviders.get(tokenReference(token)) != null) {
this._errors.push(new ProviderError("Cannot instantiate cyclic dependency! " + tokenName(token), resolvedProvider.sourceSpan));
return null;
}
this._seenProviders.set(tokenReference(token), true);
var transformedProviders = resolvedProvider.providers.map(function (provider) {
var transformedUseValue = provider.useValue;
var transformedUseExisting = provider.useExisting;
var transformedDeps = undefined;
if (provider.useExisting != null) {
var existingDiDep = _this._getDependency({ token: provider.useExisting }, eager, resolvedProvider.sourceSpan);
if (existingDiDep.token != null) {
transformedUseExisting = existingDiDep.token;
}
else {
transformedUseExisting = null;
transformedUseValue = existingDiDep.value;
}
}
else if (provider.useFactory) {
var deps = provider.deps || provider.useFactory.diDeps;
transformedDeps =
deps.map(function (dep) { return _this._getDependency(dep, eager, resolvedProvider.sourceSpan); });
}
else if (provider.useClass) {
var deps = provider.deps || provider.useClass.diDeps;
transformedDeps =
deps.map(function (dep) { return _this._getDependency(dep, eager, resolvedProvider.sourceSpan); });
}
return _transformProvider(provider, {
useExisting: transformedUseExisting,
useValue: transformedUseValue,
deps: transformedDeps
});
});
transformedProviderAst =
_transformProviderAst(resolvedProvider, { eager: eager, providers: transformedProviders });
this._transformedProviders.set(tokenReference(token), transformedProviderAst);
return transformedProviderAst;
};
NgModuleProviderAnalyzer.prototype._getDependency = function (dep, eager, requestorSourceSpan) {
if (eager === void 0) { eager = false; }
if (!dep.isSkipSelf && dep.token != null) {
// access the injector
if (tokenReference(dep.token) ===
this.reflector.resolveExternalReference(Identifiers.Injector) ||
tokenReference(dep.token) ===
this.reflector.resolveExternalReference(Identifiers.ComponentFactoryResolver)) {
// access providers
}
else if (this._getOrCreateLocalProvider(dep.token, eager) != null) {
}
}
return dep;
};
return NgModuleProviderAnalyzer;
}());
function _transformProvider(provider, _a) {
var useExisting = _a.useExisting, useValue = _a.useValue, deps = _a.deps;
return {
token: provider.token,
useClass: provider.useClass,
useExisting: useExisting,
useFactory: provider.useFactory,
useValue: useValue,
deps: deps,
multi: provider.multi
};
}
function _transformProviderAst(provider, _a) {
var eager = _a.eager, providers = _a.providers;
return new ProviderAst(provider.token, provider.multiProvider, provider.eager || eager, providers, provider.providerType, provider.lifecycleHooks, provider.sourceSpan, provider.isModule);
}
function _resolveProvidersFromDirectives(directives, sourceSpan, targetErrors) {
var providersByToken = new Map();
directives.forEach(function (directive) {
var dirProvider = { token: { identifier: directive.type }, useClass: directive.type };
_resolveProviders([dirProvider], directive.isComponent ? ProviderAstType.Component : ProviderAstType.Directive, true, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
});
// Note: directives need to be able to overwrite providers of a component!
var directivesWithComponentFirst = directives.filter(function (dir) { return dir.isComponent; }).concat(directives.filter(function (dir) { return !dir.isComponent; }));
directivesWithComponentFirst.forEach(function (directive) {
_resolveProviders(directive.providers, ProviderAstType.PublicService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
_resolveProviders(directive.viewProviders, ProviderAstType.PrivateService, false, sourceSpan, targetErrors, providersByToken, /* isModule */ false);
});
return providersByToken;
}
function _resolveProviders(providers, providerType, eager, sourceSpan, targetErrors, targetProvidersByToken, isModule) {
providers.forEach(function (provider) {
var resolvedProvider = targetProvidersByToken.get(tokenReference(provider.token));
if (resolvedProvider != null && !!resolvedProvider.multiProvider !== !!provider.multi) {
targetErrors.push(new ProviderError("Mixing multi and non multi provider is not possible for token " + tokenName(resolvedProvider.token), sourceSpan));
}
if (!resolvedProvider) {
var lifecycleHooks = provider.token.identifier &&
provider.token.identifier.lifecycleHooks ?
provider.token.identifier.lifecycleHooks :
[];
var isUseValue = !(provider.useClass || provider.useExisting || provider.useFactory);
resolvedProvider = new ProviderAst(provider.token, !!provider.multi, eager || isUseValue, [provider], providerType, lifecycleHooks, sourceSpan, isModule);
targetProvidersByToken.set(tokenReference(provider.token), resolvedProvider);
}
else {
if (!provider.multi) {
resolvedProvider.providers.length = 0;
}
resolvedProvider.providers.push(provider);
}
});
}
function _getViewQueries(component) {
// Note: queries start with id 1 so we can use the number in a Bloom filter!
var viewQueryId = 1;
var viewQueries = new Map();
if (component.viewQueries) {
component.viewQueries.forEach(function (query) { return _addQueryToTokenMap(viewQueries, { meta: query, queryId: viewQueryId++ }); });
}
return viewQueries;
}
function _getContentQueries(contentQueryStartId, directives) {
var contentQueryId = contentQueryStartId;
var contentQueries = new Map();
directives.forEach(function (directive, directiveIndex) {
if (directive.queries) {
directive.queries.forEach(function (query) { return _addQueryToTokenMap(contentQueries, { meta: query, queryId: contentQueryId++ }); });
}
});
return contentQueries;
}
function _addQueryToTokenMap(map, query) {
query.meta.selectors.forEach(function (token) {
var entry = map.get(tokenReference(token));
if (!entry) {
entry = [];
map.set(tokenReference(token), entry);
}
entry.push(query);
});
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function providerDef(ctx, providerAst) {
var flags = 0;
if (!providerAst.eager) {
flags |= 4096 /* LazyProvider */;
}
if (providerAst.providerType === ProviderAstType.PrivateService) {
flags |= 8192 /* PrivateProvider */;
}
if (providerAst.isModule) {
flags |= 1073741824 /* TypeModuleProvider */;
}
providerAst.lifecycleHooks.forEach(function (lifecycleHook) {
// for regular providers, we only support ngOnDestroy
if (lifecycleHook === LifecycleHooks.OnDestroy ||
providerAst.providerType === ProviderAstType.Directive ||
providerAst.providerType === ProviderAstType.Component) {
flags |= lifecycleHookToNodeFlag(lifecycleHook);
}
});
var _a = providerAst.multiProvider ?
multiProviderDef(ctx, flags, providerAst.providers) :
singleProviderDef(ctx, flags, providerAst.providerType, providerAst.providers[0]), providerExpr = _a.providerExpr, providerFlags = _a.flags, depsExpr = _a.depsExpr;
return {
providerExpr: providerExpr,
flags: providerFlags, depsExpr: depsExpr,
tokenExpr: tokenExpr(ctx, providerAst.token),
};
}
function multiProviderDef(ctx, flags, providers) {
var allDepDefs = [];
var allParams = [];
var exprs = providers.map(function (provider, providerIndex) {
var expr;
if (provider.useClass) {
var depExprs = convertDeps(providerIndex, provider.deps || provider.useClass.diDeps);
expr = ctx.importExpr(provider.useClass.reference).instantiate(depExprs);
}
else if (provider.useFactory) {
var depExprs = convertDeps(providerIndex, provider.deps || provider.useFactory.diDeps);
expr = ctx.importExpr(provider.useFactory.reference).callFn(depExprs);
}
else if (provider.useExisting) {
var depExprs = convertDeps(providerIndex, [{ token: provider.useExisting }]);
expr = depExprs[0];
}
else {
expr = convertValueToOutputAst(ctx, provider.useValue);
}
return expr;
});
var providerExpr = fn(allParams, [new ReturnStatement(literalArr(exprs))], INFERRED_TYPE);
return {
providerExpr: providerExpr,
flags: flags | 1024 /* TypeFactoryProvider */,
depsExpr: literalArr(allDepDefs)
};
function convertDeps(providerIndex, deps) {
return deps.map(function (dep, depIndex) {
var paramName = "p" + providerIndex + "_" + depIndex;
allParams.push(new FnParam(paramName, DYNAMIC_TYPE));
allDepDefs.push(depDef(ctx, dep));
return variable(paramName);
});
}
}
function singleProviderDef(ctx, flags, providerType, providerMeta) {
var providerExpr;
var deps;
if (providerType === ProviderAstType.Directive || providerType === ProviderAstType.Component) {
providerExpr = ctx.importExpr(providerMeta.useClass.reference);
flags |= 16384 /* TypeDirective */;
deps = providerMeta.deps || providerMeta.useClass.diDeps;
}
else {
if (providerMeta.useClass) {
providerExpr = ctx.importExpr(providerMeta.useClass.reference);
flags |= 512 /* TypeClassProvider */;
deps = providerMeta.deps || providerMeta.useClass.diDeps;
}
else if (providerMeta.useFactory) {
providerExpr = ctx.importExpr(providerMeta.useFactory.reference);
flags |= 1024 /* TypeFactoryProvider */;
deps = providerMeta.deps || providerMeta.useFactory.diDeps;
}
else if (providerMeta.useExisting) {
providerExpr = NULL_EXPR;
flags |= 2048 /* TypeUseExistingProvider */;
deps = [{ token: providerMeta.useExisting }];
}
else {
providerExpr = convertValueToOutputAst(ctx, providerMeta.useValue);
flags |= 256 /* TypeValueProvider */;
deps = [];
}
}
var depsExpr = literalArr(deps.map(function (dep) { return depDef(ctx, dep); }));
return { providerExpr: providerExpr, flags: flags, depsExpr: depsExpr };
}
function tokenExpr(ctx, tokenMeta) {
return tokenMeta.identifier ? ctx.importExpr(tokenMeta.identifier.reference) :
literal(tokenMeta.value);
}
function depDef(ctx, dep) {
// Note: the following fields have already been normalized out by provider_analyzer:
// - isAttribute, isHost
var expr = dep.isValue ? convertValueToOutputAst(ctx, dep.value) : tokenExpr(ctx, dep.token);
var flags = 0;
if (dep.isSkipSelf) {
flags |= 1 /* SkipSelf */;
}
if (dep.isOptional) {
flags |= 2 /* Optional */;
}
if (dep.isSelf) {
flags |= 4 /* Self */;
}
if (dep.isValue) {
flags |= 8 /* Value */;
}
return flags === 0 /* None */ ? expr : literalArr([literal(flags), expr]);
}
function lifecycleHookToNodeFlag(lifecycleHook) {
var nodeFlag = 0;
switch (lifecycleHook) {
case LifecycleHooks.AfterContentChecked:
nodeFlag = 2097152 /* AfterContentChecked */;
break;
case LifecycleHooks.AfterContentInit:
nodeFlag = 1048576 /* AfterContentInit */;
break;
case LifecycleHooks.AfterViewChecked:
nodeFlag = 8388608 /* AfterViewChecked */;
break;
case LifecycleHooks.AfterViewInit:
nodeFlag = 4194304 /* AfterViewInit */;
break;
case LifecycleHooks.DoCheck:
nodeFlag = 262144 /* DoCheck */;
break;
case LifecycleHooks.OnChanges:
nodeFlag = 524288 /* OnChanges */;
break;
case LifecycleHooks.OnDestroy:
nodeFlag = 131072 /* OnDestroy */;
break;
case LifecycleHooks.OnInit:
nodeFlag = 65536 /* OnInit */;
break;
}
return nodeFlag;
}
function componentFactoryResolverProviderDef(reflector, ctx, flags, entryComponents) {
var entryComponentFactories = entryComponents.map(function (entryComponent) { return ctx.importExpr(entryComponent.componentFactory); });
var token = createTokenForExternalReference(reflector, Identifiers.ComponentFactoryResolver);
var classMeta = {
diDeps: [
{ isValue: true, value: literalArr(entryComponentFactories) },
{ token: token, isSkipSelf: true, isOptional: true },
{ token: createTokenForExternalReference(reflector, Identifiers.NgModuleRef) },
],
lifecycleHooks: [],
reference: reflector.resolveExternalReference(Identifiers.CodegenComponentFactoryResolver)
};
var _a = singleProviderDef(ctx, flags, ProviderAstType.PrivateService, {
token: token,
multi: false,
useClass: classMeta,
}), providerExpr = _a.providerExpr, providerFlags = _a.flags, depsExpr = _a.depsExpr;
return { providerExpr: providerExpr, flags: providerFlags, depsExpr: depsExpr, tokenExpr: tokenExpr(ctx, token) };
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var NgModuleCompileResult = /** @class */ (function () {
function NgModuleCompileResult(ngModuleFactoryVar) {
this.ngModuleFactoryVar = ngModuleFactoryVar;
}
return NgModuleCompileResult;
}());
var LOG_VAR = variable('_l');
var NgModuleCompiler = /** @class */ (function () {
function NgModuleCompiler(reflector) {
this.reflector = reflector;
}
NgModuleCompiler.prototype.compile = function (ctx, ngModuleMeta, extraProviders) {
var sourceSpan = typeSourceSpan('NgModule', ngModuleMeta.type);
var entryComponentFactories = ngModuleMeta.transitiveModule.entryComponents;
var bootstrapComponents = ngModuleMeta.bootstrapComponents;
var providerParser = new NgModuleProviderAnalyzer(this.reflector, ngModuleMeta, extraProviders, sourceSpan);
var providerDefs = [componentFactoryResolverProviderDef(this.reflector, ctx, 0 /* None */, entryComponentFactories)]
.concat(providerParser.parse().map(function (provider) { return providerDef(ctx, provider); }))
.map(function (_a) {
var providerExpr = _a.providerExpr, depsExpr = _a.depsExpr, flags = _a.flags, tokenExpr = _a.tokenExpr;
return importExpr(Identifiers.moduleProviderDef).callFn([
literal(flags), tokenExpr, providerExpr, depsExpr
]);
});
var ngModuleDef = importExpr(Identifiers.moduleDef).callFn([literalArr(providerDefs)]);
var ngModuleDefFactory = fn([new FnParam(LOG_VAR.name)], [new ReturnStatement(ngModuleDef)], INFERRED_TYPE);
var ngModuleFactoryVar = identifierName(ngModuleMeta.type) + "NgFactory";
this._createNgModuleFactory(ctx, ngModuleMeta.type.reference, importExpr(Identifiers.createModuleFactory).callFn([
ctx.importExpr(ngModuleMeta.type.reference),
literalArr(bootstrapComponents.map(function (id) { return ctx.importExpr(id.reference); })),
ngModuleDefFactory
]));
if (ngModuleMeta.id) {
var id = typeof ngModuleMeta.id === 'string' ? literal(ngModuleMeta.id) :
ctx.importExpr(ngModuleMeta.id);
var registerFactoryStmt = importExpr(Identifiers.RegisterModuleFactoryFn)
.callFn([id, variable(ngModuleFactoryVar)])
.toStmt();
ctx.statements.push(registerFactoryStmt);
}
return new NgModuleCompileResult(ngModuleFactoryVar);
};
NgModuleCompiler.prototype.createStub = function (ctx, ngModuleReference) {
this._createNgModuleFactory(ctx, ngModuleReference, NULL_EXPR);
};
NgModuleCompiler.prototype._createNgModuleFactory = function (ctx, reference, value) {
var ngModuleFactoryVar = identifierName({ reference: reference }) + "NgFactory";
var ngModuleFactoryStmt = variable(ngModuleFactoryVar)
.set(value)
.toDeclStmt(importType(Identifiers.NgModuleFactory, [expressionType(ctx.importExpr(reference))], [TypeModifier.Const]), [StmtModifier.Final, StmtModifier.Exported]);
ctx.statements.push(ngModuleFactoryStmt);
};
return NgModuleCompiler;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Resolves types to {@link NgModule}.
*/
var NgModuleResolver = /** @class */ (function () {
function NgModuleResolver(_reflector) {
this._reflector = _reflector;
}
NgModuleResolver.prototype.isNgModule = function (type) { return this._reflector.annotations(type).some(createNgModule.isTypeOf); };
NgModuleResolver.prototype.resolve = function (type, throwIfNotFound) {
if (throwIfNotFound === void 0) { throwIfNotFound = true; }
var ngModuleMeta = findLast(this._reflector.annotations(type), createNgModule.isTypeOf);
if (ngModuleMeta) {
return ngModuleMeta;
}
else {
if (throwIfNotFound) {
throw new Error("No NgModule metadata found for '" + stringify(type) + "'.");
}
return null;
}
};
return NgModuleResolver;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
var VERSION$1 = 3;
var JS_B64_PREFIX = '# sourceMappingURL=data:application/json;base64,';
var SourceMapGenerator = /** @class */ (function () {
function SourceMapGenerator(file) {
if (file === void 0) { file = null; }
this.file = file;
this.sourcesContent = new Map();
this.lines = [];
this.lastCol0 = 0;
this.hasMappings = false;
}
// The content is `null` when the content is expected to be loaded using the URL
SourceMapGenerator.prototype.addSource = function (url, content) {
if (content === void 0) { content = null; }
if (!this.sourcesContent.has(url)) {
this.sourcesContent.set(url, content);
}
return this;
};
SourceMapGenerator.prototype.addLine = function () {
this.lines.push([]);
this.lastCol0 = 0;
return this;
};
SourceMapGenerator.prototype.addMapping = function (col0, sourceUrl, sourceLine0, sourceCol0) {
if (!this.currentLine) {
throw new Error("A line must be added before mappings can be added");
}
if (sourceUrl != null && !this.sourcesContent.has(sourceUrl)) {
throw new Error("Unknown source file \"" + sourceUrl + "\"");
}
if (col0 == null) {
throw new Error("The column in the generated code must be provided");
}
if (col0 < this.lastCol0) {
throw new Error("Mapping should be added in output order");
}
if (sourceUrl && (sourceLine0 == null || sourceCol0 == null)) {
throw new Error("The source location must be provided when a source url is provided");
}
this.hasMappings = true;
this.lastCol0 = col0;
this.currentLine.push({ col0: col0, sourceUrl: sourceUrl, sourceLine0: sourceLine0, sourceCol0: sourceCol0 });
return this;
};
Object.defineProperty(SourceMapGenerator.prototype, "currentLine", {
get: function () { return this.lines.slice(-1)[0]; },
enumerable: true,
configurable: true
});
SourceMapGenerator.prototype.toJSON = function () {
var _this = this;
if (!this.hasMappings) {
return null;
}
var sourcesIndex = new Map();
var sources = [];
var sourcesContent = [];
Array.from(this.sourcesContent.keys()).forEach(function (url, i) {
sourcesIndex.set(url, i);
sources.push(url);
sourcesContent.push(_this.sourcesContent.get(url) || null);
});
var mappings = '';
var lastCol0 = 0;
var lastSourceIndex = 0;
var lastSourceLine0 = 0;
var lastSourceCol0 = 0;
this.lines.forEach(function (segments) {
lastCol0 = 0;
mappings += segments
.map(function (segment) {
// zero-based starting column of the line in the generated code
var segAsStr = toBase64VLQ(segment.col0 - lastCol0);
lastCol0 = segment.col0;
if (segment.sourceUrl != null) {
// zero-based index into the “sources” list
segAsStr +=
toBase64VLQ(sourcesIndex.get(segment.sourceUrl) - lastSourceIndex);
lastSourceIndex = sourcesIndex.get(segment.sourceUrl);
// the zero-based starting line in the original source
segAsStr += toBase64VLQ(segment.sourceLine0 - lastSourceLine0);
lastSourceLine0 = segment.sourceLine0;
// the zero-based starting column in the original source
segAsStr += toBase64VLQ(segment.sourceCol0 - lastSourceCol0);
lastSourceCol0 = segment.sourceCol0;
}
return segAsStr;
})
.join(',');
mappings += ';';
});
mappings = mappings.slice(0, -1);
return {
'file': this.file || '',
'version': VERSION$1,
'sourceRoot': '',
'sources': sources,
'sourcesContent': sourcesContent,
'mappings': mappings,
};
};
SourceMapGenerator.prototype.toJsComment = function () {
return this.hasMappings ? '//' + JS_B64_PREFIX + toBase64String(JSON.stringify(this, null, 0)) :
'';
};
return SourceMapGenerator;
}());
function toBase64String(value) {
var b64 = '';
value = utf8Encode(value);
for (var i = 0; i < value.length;) {
var i1 = value.charCodeAt(i++);
var i2 = value.charCodeAt(i++);
var i3 = value.charCodeAt(i++);
b64 += toBase64Digit(i1 >> 2);
b64 += toBase64Digit(((i1 & 3) << 4) | (isNaN(i2) ? 0 : i2 >> 4));
b64 += isNaN(i2) ? '=' : toBase64Digit(((i2 & 15) << 2) | (i3 >> 6));
b64 += isNaN(i2) || isNaN(i3) ? '=' : toBase64Digit(i3 & 63);
}
return b64;
}
function toBase64VLQ(value) {
value = value < 0 ? ((-value) << 1) + 1 : value << 1;
var out = '';
do {
var digit = value & 31;
value = value >> 5;
if (value > 0) {
digit = digit | 32;
}
out += toBase64Digit(digit);
} while (value > 0);
return out;
}
var B64_DIGITS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function toBase64Digit(value) {
if (value < 0 || value >= 64) {
throw new Error("Can only encode value in the range [0, 63]");
}
return B64_DIGITS[value];
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var _SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g;
var _LEGAL_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i;
var _INDENT_WITH = ' ';
var CATCH_ERROR_VAR$1 = variable('error', null, null);
var CATCH_STACK_VAR$1 = variable('stack', null, null);
var _EmittedLine = /** @class */ (function () {
function _EmittedLine(indent) {
this.indent = indent;
this.partsLength = 0;
this.parts = [];
this.srcSpans = [];
}
return _EmittedLine;
}());
var EmitterVisitorContext = /** @class */ (function () {
function EmitterVisitorContext(_indent) {
this._indent = _indent;
this._classes = [];
this._preambleLineCount = 0;
this._lines = [new _EmittedLine(_indent)];
}
EmitterVisitorContext.createRoot = function () { return new EmitterVisitorContext(0); };
Object.defineProperty(EmitterVisitorContext.prototype, "_currentLine", {
get: function () { return this._lines[this._lines.length - 1]; },
enumerable: true,
configurable: true
});
EmitterVisitorContext.prototype.println = function (from, lastPart) {
if (lastPart === void 0) { lastPart = ''; }
this.print(from || null, lastPart, true);
};
EmitterVisitorContext.prototype.lineIsEmpty = function () { return this._currentLine.parts.length === 0; };
EmitterVisitorContext.prototype.lineLength = function () {
return this._currentLine.indent * _INDENT_WITH.length + this._currentLine.partsLength;
};
EmitterVisitorContext.prototype.print = function (from, part, newLine) {
if (newLine === void 0) { newLine = false; }
if (part.length > 0) {
this._currentLine.parts.push(part);
this._currentLine.partsLength += part.length;
this._currentLine.srcSpans.push(from && from.sourceSpan || null);
}
if (newLine) {
this._lines.push(new _EmittedLine(this._indent));
}
};
EmitterVisitorContext.prototype.removeEmptyLastLine = function () {
if (this.lineIsEmpty()) {
this._lines.pop();
}
};
EmitterVisitorContext.prototype.incIndent = function () {
this._indent++;
if (this.lineIsEmpty()) {
this._currentLine.indent = this._indent;
}
};
EmitterVisitorContext.prototype.decIndent = function () {
this._indent--;
if (this.lineIsEmpty()) {
this._currentLine.indent = this._indent;
}
};
EmitterVisitorContext.prototype.pushClass = function (clazz) { this._classes.push(clazz); };
EmitterVisitorContext.prototype.popClass = function () { return this._classes.pop(); };
Object.defineProperty(EmitterVisitorContext.prototype, "currentClass", {
get: function () {
return this._classes.length > 0 ? this._classes[this._classes.length - 1] : null;
},
enumerable: true,
configurable: true
});
EmitterVisitorContext.prototype.toSource = function () {
return this.sourceLines
.map(function (l) { return l.parts.length > 0 ? _createIndent(l.indent) + l.parts.join('') : ''; })
.join('\n');
};
EmitterVisitorContext.prototype.toSourceMapGenerator = function (genFilePath, startsAtLine) {
if (startsAtLine === void 0) { startsAtLine = 0; }
var map = new SourceMapGenerator(genFilePath);
var firstOffsetMapped = false;
var mapFirstOffsetIfNeeded = function () {
if (!firstOffsetMapped) {
// Add a single space so that tools won't try to load the file from disk.
// Note: We are using virtual urls like `ng:///`, so we have to
// provide a content here.
map.addSource(genFilePath, ' ').addMapping(0, genFilePath, 0, 0);
firstOffsetMapped = true;
}
};
for (var i = 0; i < startsAtLine; i++) {
map.addLine();
mapFirstOffsetIfNeeded();
}
this.sourceLines.forEach(function (line, lineIdx) {
map.addLine();
var spans = line.srcSpans;
var parts = line.parts;
var col0 = line.indent * _INDENT_WITH.length;
var spanIdx = 0;
// skip leading parts without source spans
while (spanIdx < spans.length && !spans[spanIdx]) {
col0 += parts[spanIdx].length;
spanIdx++;
}
if (spanIdx < spans.length && lineIdx === 0 && col0 === 0) {
firstOffsetMapped = true;
}
else {
mapFirstOffsetIfNeeded();
}
while (spanIdx < spans.length) {
var span = spans[spanIdx];
var source = span.start.file;
var sourceLine = span.start.line;
var sourceCol = span.start.col;
map.addSource(source.url, source.content)
.addMapping(col0, source.url, sourceLine, sourceCol);
col0 += parts[spanIdx].length;
spanIdx++;
// assign parts without span or the same span to the previous segment
while (spanIdx < spans.length && (span === spans[spanIdx] || !spans[spanIdx])) {
col0 += parts[spanIdx].length;
spanIdx++;
}
}
});
return map;
};
EmitterVisitorContext.prototype.setPreambleLineCount = function (count) { return this._preambleLineCount = count; };
EmitterVisitorContext.prototype.spanOf = function (line, column) {
var emittedLine = this._lines[line - this._preambleLineCount];
if (emittedLine) {
var columnsLeft = column - _createIndent(emittedLine.indent).length;
for (var partIndex = 0; partIndex < emittedLine.parts.length; partIndex++) {
var part = emittedLine.parts[partIndex];
if (part.length > columnsLeft) {
return emittedLine.srcSpans[partIndex];
}
columnsLeft -= part.length;
}
}
return null;
};
Object.defineProperty(EmitterVisitorContext.prototype, "sourceLines", {
get: function () {
if (this._lines.length && this._lines[this._lines.length - 1].parts.length === 0) {
return this._lines.slice(0, -1);
}
return this._lines;
},
enumerable: true,
configurable: true
});
return EmitterVisitorContext;
}());
var AbstractEmitterVisitor = /** @class */ (function () {
function AbstractEmitterVisitor(_escapeDollarInStrings) {
this._escapeDollarInStrings = _escapeDollarInStrings;
}
AbstractEmitterVisitor.prototype.visitExpressionStmt = function (stmt, ctx) {
stmt.expr.visitExpression(this, ctx);
ctx.println(stmt, ';');
return null;
};
AbstractEmitterVisitor.prototype.visitReturnStmt = function (stmt, ctx) {
ctx.print(stmt, "return ");
stmt.value.visitExpression(this, ctx);
ctx.println(stmt, ';');
return null;
};
AbstractEmitterVisitor.prototype.visitIfStmt = function (stmt, ctx) {
ctx.print(stmt, "if (");
stmt.condition.visitExpression(this, ctx);
ctx.print(stmt, ") {");
var hasElseCase = stmt.falseCase != null && stmt.falseCase.length > 0;
if (stmt.trueCase.length <= 1 && !hasElseCase) {
ctx.print(stmt, " ");
this.visitAllStatements(stmt.trueCase, ctx);
ctx.removeEmptyLastLine();
ctx.print(stmt, " ");
}
else {
ctx.println();
ctx.incIndent();
this.visitAllStatements(stmt.trueCase, ctx);
ctx.decIndent();
if (hasElseCase) {
ctx.println(stmt, "} else {");
ctx.incIndent();
this.visitAllStatements(stmt.falseCase, ctx);
ctx.decIndent();
}
}
ctx.println(stmt, "}");
return null;
};
AbstractEmitterVisitor.prototype.visitThrowStmt = function (stmt, ctx) {
ctx.print(stmt, "throw ");
stmt.error.visitExpression(this, ctx);
ctx.println(stmt, ";");
return null;
};
AbstractEmitterVisitor.prototype.visitCommentStmt = function (stmt, ctx) {
if (stmt.multiline) {
ctx.println(stmt, "/* " + stmt.comment + " */");
}
else {
stmt.comment.split('\n').forEach(function (line) { ctx.println(stmt, "// " + line); });
}
return null;
};
AbstractEmitterVisitor.prototype.visitJSDocCommentStmt = function (stmt, ctx) {
ctx.println(stmt, "/*" + stmt.toString() + "*/");
return null;
};
AbstractEmitterVisitor.prototype.visitWriteVarExpr = function (expr, ctx) {
var lineWasEmpty = ctx.lineIsEmpty();
if (!lineWasEmpty) {
ctx.print(expr, '(');
}
ctx.print(expr, expr.name + " = ");
expr.value.visitExpression(this, ctx);
if (!lineWasEmpty) {
ctx.print(expr, ')');
}
return null;
};
AbstractEmitterVisitor.prototype.visitWriteKeyExpr = function (expr, ctx) {
var lineWasEmpty = ctx.lineIsEmpty();
if (!lineWasEmpty) {
ctx.print(expr, '(');
}
expr.receiver.visitExpression(this, ctx);
ctx.print(expr, "[");
expr.index.visitExpression(this, ctx);
ctx.print(expr, "] = ");
expr.value.visitExpression(this, ctx);
if (!lineWasEmpty) {
ctx.print(expr, ')');
}
return null;
};
AbstractEmitterVisitor.prototype.visitWritePropExpr = function (expr, ctx) {
var lineWasEmpty = ctx.lineIsEmpty();
if (!lineWasEmpty) {
ctx.print(expr, '(');
}
expr.receiver.visitExpression(this, ctx);
ctx.print(expr, "." + expr.name + " = ");
expr.value.visitExpression(this, ctx);
if (!lineWasEmpty) {
ctx.print(expr, ')');
}
return null;
};
AbstractEmitterVisitor.prototype.visitInvokeMethodExpr = function (expr, ctx) {
expr.receiver.visitExpression(this, ctx);
var name = expr.name;
if (expr.builtin != null) {
name = this.getBuiltinMethodName(expr.builtin);
if (name == null) {
// some builtins just mean to skip the call.
return null;
}
}
ctx.print(expr, "." + name + "(");
this.visitAllExpressions(expr.args, ctx, ",");
ctx.print(expr, ")");
return null;
};
AbstractEmitterVisitor.prototype.visitInvokeFunctionExpr = function (expr, ctx) {
expr.fn.visitExpression(this, ctx);
ctx.print(expr, "(");
this.visitAllExpressions(expr.args, ctx, ',');
ctx.print(expr, ")");
return null;
};
AbstractEmitterVisitor.prototype.visitReadVarExpr = function (ast, ctx) {
var varName = ast.name;
if (ast.builtin != null) {
switch (ast.builtin) {
case BuiltinVar.Super:
varName = 'super';
break;
case BuiltinVar.This:
varName = 'this';
break;
case BuiltinVar.CatchError:
varName = CATCH_ERROR_VAR$1.name;
break;
case BuiltinVar.CatchStack:
varName = CATCH_STACK_VAR$1.name;
break;
default:
throw new Error("Unknown builtin variable " + ast.builtin);
}
}
ctx.print(ast, varName);
return null;
};
AbstractEmitterVisitor.prototype.visitInstantiateExpr = function (ast, ctx) {
ctx.print(ast, "new ");
ast.classExpr.visitExpression(this, ctx);
ctx.print(ast, "(");
this.visitAllExpressions(ast.args, ctx, ',');
ctx.print(ast, ")");
return null;
};
AbstractEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) {
var value = ast.value;
if (typeof value === 'string') {
ctx.print(ast, escapeIdentifier(value, this._escapeDollarInStrings));
}
else {
ctx.print(ast, "" + value);
}
return null;
};
AbstractEmitterVisitor.prototype.visitConditionalExpr = function (ast, ctx) {
ctx.print(ast, "(");
ast.condition.visitExpression(this, ctx);
ctx.print(ast, '? ');
ast.trueCase.visitExpression(this, ctx);
ctx.print(ast, ': ');
ast.falseCase.visitExpression(this, ctx);
ctx.print(ast, ")");
return null;
};
AbstractEmitterVisitor.prototype.visitNotExpr = function (ast, ctx) {
ctx.print(ast, '!');
ast.condition.visitExpression(this, ctx);
return null;
};
AbstractEmitterVisitor.prototype.visitAssertNotNullExpr = function (ast, ctx) {
ast.condition.visitExpression(this, ctx);
return null;
};
AbstractEmitterVisitor.prototype.visitBinaryOperatorExpr = function (ast, ctx) {
var opStr;
switch (ast.operator) {
case BinaryOperator.Equals:
opStr = '==';
break;
case BinaryOperator.Identical:
opStr = '===';
break;
case BinaryOperator.NotEquals:
opStr = '!=';
break;
case BinaryOperator.NotIdentical:
opStr = '!==';
break;
case BinaryOperator.And:
opStr = '&&';
break;
case BinaryOperator.BitwiseAnd:
opStr = '&';
break;
case BinaryOperator.Or:
opStr = '||';
break;
case BinaryOperator.Plus:
opStr = '+';
break;
case BinaryOperator.Minus:
opStr = '-';
break;
case BinaryOperator.Divide:
opStr = '/';
break;
case BinaryOperator.Multiply:
opStr = '*';
break;
case BinaryOperator.Modulo:
opStr = '%';
break;
case BinaryOperator.Lower:
opStr = '<';
break;
case BinaryOperator.LowerEquals:
opStr = '<=';
break;
case BinaryOperator.Bigger:
opStr = '>';
break;
case BinaryOperator.BiggerEquals:
opStr = '>=';
break;
default:
throw new Error("Unknown operator " + ast.operator);
}
if (ast.parens)
ctx.print(ast, "(");
ast.lhs.visitExpression(this, ctx);
ctx.print(ast, " " + opStr + " ");
ast.rhs.visitExpression(this, ctx);
if (ast.parens)
ctx.print(ast, ")");
return null;
};
AbstractEmitterVisitor.prototype.visitReadPropExpr = function (ast, ctx) {
ast.receiver.visitExpression(this, ctx);
ctx.print(ast, ".");
ctx.print(ast, ast.name);
return null;
};
AbstractEmitterVisitor.prototype.visitReadKeyExpr = function (ast, ctx) {
ast.receiver.visitExpression(this, ctx);
ctx.print(ast, "[");
ast.index.visitExpression(this, ctx);
ctx.print(ast, "]");
return null;
};
AbstractEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) {
ctx.print(ast, "[");
this.visitAllExpressions(ast.entries, ctx, ',');
ctx.print(ast, "]");
return null;
};
AbstractEmitterVisitor.prototype.visitLiteralMapExpr = function (ast, ctx) {
var _this = this;
ctx.print(ast, "{");
this.visitAllObjects(function (entry) {
ctx.print(ast, escapeIdentifier(entry.key, _this._escapeDollarInStrings, entry.quoted) + ":");
entry.value.visitExpression(_this, ctx);
}, ast.entries, ctx, ',');
ctx.print(ast, "}");
return null;
};
AbstractEmitterVisitor.prototype.visitCommaExpr = function (ast, ctx) {
ctx.print(ast, '(');
this.visitAllExpressions(ast.parts, ctx, ',');
ctx.print(ast, ')');
return null;
};
AbstractEmitterVisitor.prototype.visitAllExpressions = function (expressions, ctx, separator) {
var _this = this;
this.visitAllObjects(function (expr) { return expr.visitExpression(_this, ctx); }, expressions, ctx, separator);
};
AbstractEmitterVisitor.prototype.visitAllObjects = function (handler, expressions, ctx, separator) {
var incrementedIndent = false;
for (var i = 0; i < expressions.length; i++) {
if (i > 0) {
if (ctx.lineLength() > 80) {
ctx.print(null, separator, true);
if (!incrementedIndent) {
// continuation are marked with double indent.
ctx.incIndent();
ctx.incIndent();
incrementedIndent = true;
}
}
else {
ctx.print(null, separator, false);
}
}
handler(expressions[i]);
}
if (incrementedIndent) {
// continuation are marked with double indent.
ctx.decIndent();
ctx.decIndent();
}
};
AbstractEmitterVisitor.prototype.visitAllStatements = function (statements, ctx) {
var _this = this;
statements.forEach(function (stmt) { return stmt.visitStatement(_this, ctx); });
};
return AbstractEmitterVisitor;
}());
function escapeIdentifier(input, escapeDollar, alwaysQuote) {
if (alwaysQuote === void 0) { alwaysQuote = true; }
if (input == null) {
return null;
}
var body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, function () {
var match = [];
for (var _i = 0; _i < arguments.length; _i++) {
match[_i] = arguments[_i];
}
if (match[0] == '$') {
return escapeDollar ? '\\$' : '$';
}
else if (match[0] == '\n') {
return '\\n';
}
else if (match[0] == '\r') {
return '\\r';
}
else {
return "\\" + match[0];
}
});
var requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body);
return requiresQuotes ? "'" + body + "'" : body;
}
function _createIndent(count) {
var res = '';
for (var i = 0; i < count; i++) {
res += _INDENT_WITH;
}
return res;
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function debugOutputAstAsTypeScript(ast) {
var converter = new _TsEmitterVisitor();
var ctx = EmitterVisitorContext.createRoot();
var asts = Array.isArray(ast) ? ast : [ast];
asts.forEach(function (ast) {
if (ast instanceof Statement) {
ast.visitStatement(converter, ctx);
}
else if (ast instanceof Expression) {
ast.visitExpression(converter, ctx);
}
else if (ast instanceof Type$1) {
ast.visitType(converter, ctx);
}
else {
throw new Error("Don't know how to print debug info for " + ast);
}
});
return ctx.toSource();
}
var TypeScriptEmitter = /** @class */ (function () {
function TypeScriptEmitter() {
}
TypeScriptEmitter.prototype.emitStatementsAndContext = function (genFilePath, stmts, preamble, emitSourceMaps, referenceFilter, importFilter) {
if (preamble === void 0) { preamble = ''; }
if (emitSourceMaps === void 0) { emitSourceMaps = true; }
var converter = new _TsEmitterVisitor(referenceFilter, importFilter);
var ctx = EmitterVisitorContext.createRoot();
converter.visitAllStatements(stmts, ctx);
var preambleLines = preamble ? preamble.split('\n') : [];
converter.reexports.forEach(function (reexports, exportedModuleName) {
var reexportsCode = reexports.map(function (reexport) { return reexport.name + " as " + reexport.as; }).join(',');
preambleLines.push("export {" + reexportsCode + "} from '" + exportedModuleName + "';");
});
converter.importsWithPrefixes.forEach(function (prefix, importedModuleName) {
// Note: can't write the real word for import as it screws up system.js auto detection...
preambleLines.push("imp" +
("ort * as " + prefix + " from '" + importedModuleName + "';"));
});
var sm = emitSourceMaps ?
ctx.toSourceMapGenerator(genFilePath, preambleLines.length).toJsComment() :
'';
var lines = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__spread"])(preambleLines, [ctx.toSource(), sm]);
if (sm) {
// always add a newline at the end, as some tools have bugs without it.
lines.push('');
}
ctx.setPreambleLineCount(preambleLines.length);
return { sourceText: lines.join('\n'), context: ctx };
};
TypeScriptEmitter.prototype.emitStatements = function (genFilePath, stmts, preamble) {
if (preamble === void 0) { preamble = ''; }
return this.emitStatementsAndContext(genFilePath, stmts, preamble).sourceText;
};
return TypeScriptEmitter;
}());
var _TsEmitterVisitor = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(_TsEmitterVisitor, _super);
function _TsEmitterVisitor(referenceFilter, importFilter) {
var _this = _super.call(this, false) || this;
_this.referenceFilter = referenceFilter;
_this.importFilter = importFilter;
_this.typeExpression = 0;
_this.importsWithPrefixes = new Map();
_this.reexports = new Map();
return _this;
}
_TsEmitterVisitor.prototype.visitType = function (t, ctx, defaultType) {
if (defaultType === void 0) { defaultType = 'any'; }
if (t) {
this.typeExpression++;
t.visitType(this, ctx);
this.typeExpression--;
}
else {
ctx.print(null, defaultType);
}
};
_TsEmitterVisitor.prototype.visitLiteralExpr = function (ast, ctx) {
var value = ast.value;
if (value == null && ast.type != INFERRED_TYPE) {
ctx.print(ast, "(" + value + " as any)");
return null;
}
return _super.prototype.visitLiteralExpr.call(this, ast, ctx);
};
// Temporary workaround to support strictNullCheck enabled consumers of ngc emit.
// In SNC mode, [] have the type never[], so we cast here to any[].
// TODO: narrow the cast to a more explicit type, or use a pattern that does not
// start with [].concat. see https://github.com/angular/angular/pull/11846
_TsEmitterVisitor.prototype.visitLiteralArrayExpr = function (ast, ctx) {
if (ast.entries.length === 0) {
ctx.print(ast, '(');
}
var result = _super.prototype.visitLiteralArrayExpr.call(this, ast, ctx);
if (ast.entries.length === 0) {
ctx.print(ast, ' as any[])');
}
return result;
};
_TsEmitterVisitor.prototype.visitExternalExpr = function (ast, ctx) {
this._visitIdentifier(ast.value, ast.typeParams, ctx);
return null;
};
_TsEmitterVisitor.prototype.visitAssertNotNullExpr = function (ast, ctx) {
var result = _super.prototype.visitAssertNotNullExpr.call(this, ast, ctx);
ctx.print(ast, '!');
return result;
};
_TsEmitterVisitor.prototype.visitDeclareVarStmt = function (stmt, ctx) {
if (stmt.hasModifier(StmtModifier.Exported) && stmt.value instanceof ExternalExpr &&
!stmt.type) {
// check for a reexport
var _a = stmt.value.value, name_1 = _a.name, moduleName = _a.moduleName;
if (moduleName) {
var reexports = this.reexports.get(moduleName);
if (!reexports) {
reexports = [];
this.reexports.set(moduleName, reexports);
}
reexports.push({ name: name_1, as: stmt.name });
return null;
}
}
if (stmt.hasModifier(StmtModifier.Exported)) {
ctx.print(stmt, "export ");
}
if (stmt.hasModifier(StmtModifier.Final)) {
ctx.print(stmt, "const");
}
else {
ctx.print(stmt, "var");
}
ctx.print(stmt, " " + stmt.name);
this._printColonType(stmt.type, ctx);
if (stmt.value) {
ctx.print(stmt, " = ");
stmt.value.visitExpression(this, ctx);
}
ctx.println(stmt, ";");
return null;
};
_TsEmitterVisitor.prototype.visitCastExpr = function (ast, ctx) {
ctx.print(ast, "(<");
ast.type.visitType(this, ctx);
ctx.print(ast, ">");
ast.value.visitExpression(this, ctx);
ctx.print(ast, ")");
return null;
};
_TsEmitterVisitor.prototype.visitInstantiateExpr = function (ast, ctx) {
ctx.print(ast, "new ");
this.typeExpression++;
ast.classExpr.visitExpression(this, ctx);
this.typeExpression--;
ctx.print(ast, "(");
this.visitAllExpressions(ast.args, ctx, ',');
ctx.print(ast, ")");
return null;
};
_TsEmitterVisitor.prototype.visitDeclareClassStmt = function (stmt, ctx) {
var _this = this;
ctx.pushClass(stmt);
if (stmt.hasModifier(StmtModifier.Exported)) {
ctx.print(stmt, "export ");
}
ctx.print(stmt, "class " + stmt.name);
if (stmt.parent != null) {
ctx.print(stmt, " extends ");
this.typeExpression++;
stmt.parent.visitExpression(this, ctx);
this.typeExpression--;
}
ctx.println(stmt, " {");
ctx.incIndent();
stmt.fields.forEach(function (field) { return _this._visitClassField(field, ctx); });
if (stmt.constructorMethod != null) {
this._visitClassConstructor(stmt, ctx);
}
stmt.getters.forEach(function (getter) { return _this._visitClassGetter(getter, ctx); });
stmt.methods.forEach(function (method) { return _this._visitClassMethod(method, ctx); });
ctx.decIndent();
ctx.println(stmt, "}");
ctx.popClass();
return null;
};
_TsEmitterVisitor.prototype._visitClassField = function (field, ctx) {
if (field.hasModifier(StmtModifier.Private)) {
// comment out as a workaround for #10967
ctx.print(null, "/*private*/ ");
}
if (field.hasModifier(StmtModifier.Static)) {
ctx.print(null, 'static ');
}
ctx.print(null, field.name);
this._printColonType(field.type, ctx);
if (field.initializer) {
ctx.print(null, ' = ');
field.initializer.visitExpression(this, ctx);
}
ctx.println(null, ";");
};
_TsEmitterVisitor.prototype._visitClassGetter = function (getter, ctx) {
if (getter.hasModifier(StmtModifier.Private)) {
ctx.print(null, "private ");
}
ctx.print(null, "get " + getter.name + "()");
this._printColonType(getter.type, ctx);
ctx.println(null, " {");
ctx.incIndent();
this.visitAllStatements(getter.body, ctx);
ctx.decIndent();
ctx.println(null, "}");
};
_TsEmitterVisitor.prototype._visitClassConstructor = function (stmt, ctx) {
ctx.print(stmt, "constructor(");
this._visitParams(stmt.constructorMethod.params, ctx);
ctx.println(stmt, ") {");
ctx.incIndent();
this.visitAllStatements(stmt.constructorMethod.body, ctx);
ctx.decIndent();
ctx.println(stmt, "}");
};
_TsEmitterVisitor.prototype._visitClassMethod = function (method, ctx) {
if (method.hasModifier(StmtModifier.Private)) {
ctx.print(null, "private ");
}
ctx.print(null, method.name + "(");
this._visitParams(method.params, ctx);
ctx.print(null, ")");
this._printColonType(method.type, ctx, 'void');
ctx.println(null, " {");
ctx.incIndent();
this.visitAllStatements(method.body, ctx);
ctx.decIndent();
ctx.println(null, "}");
};
_TsEmitterVisitor.prototype.visitFunctionExpr = function (ast, ctx) {
if (ast.name) {
ctx.print(ast, 'function ');
ctx.print(ast, ast.name);
}
ctx.print(ast, "(");
this._visitParams(ast.params, ctx);
ctx.print(ast, ")");
this._printColonType(ast.type, ctx, 'void');
if (!ast.name) {
ctx.print(ast, " => ");
}
ctx.println(ast, '{');
ctx.incIndent();
this.visitAllStatements(ast.statements, ctx);
ctx.decIndent();
ctx.print(ast, "}");
return null;
};
_TsEmitterVisitor.prototype.visitDeclareFunctionStmt = function (stmt, ctx) {
if (stmt.hasModifier(StmtModifier.Exported)) {
ctx.print(stmt, "export ");
}
ctx.print(stmt, "function " + stmt.name + "(");
this._visitParams(stmt.params, ctx);
ctx.print(stmt, ")");
this._printColonType(stmt.type, ctx, 'void');
ctx.println(stmt, " {");
ctx.incIndent();
this.visitAllStatements(stmt.statements, ctx);
ctx.decIndent();
ctx.println(stmt, "}");
return null;
};
_TsEmitterVisitor.prototype.visitTryCatchStmt = function (stmt, ctx) {
ctx.println(stmt, "try {");
ctx.incIndent();
this.visitAllStatements(stmt.bodyStmts, ctx);
ctx.decIndent();
ctx.println(stmt, "} catch (" + CATCH_ERROR_VAR$1.name + ") {");
ctx.incIndent();
var catchStmts = [CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack', null)).toDeclStmt(null, [
StmtModifier.Final
])].concat(stmt.catchStmts);
this.visitAllStatements(catchStmts, ctx);
ctx.decIndent();
ctx.println(stmt, "}");
return null;
};
_TsEmitterVisitor.prototype.visitBuiltinType = function (type, ctx) {
var typeStr;
switch (type.name) {
case BuiltinTypeName.Bool:
typeStr = 'boolean';
break;
case BuiltinTypeName.Dynamic:
typeStr = 'any';
break;
case BuiltinTypeName.Function:
typeStr = 'Function';
break;
case BuiltinTypeName.Number:
typeStr = 'number';
break;
case BuiltinTypeName.Int:
typeStr = 'number';
break;
case BuiltinTypeName.String:
typeStr = 'string';
break;
default:
throw new Error("Unsupported builtin type " + type.name);
}
ctx.print(null, typeStr);
return null;
};
_TsEmitterVisitor.prototype.visitExpressionType = function (ast, ctx) {
ast.value.visitExpression(this, ctx);
return null;
};
_TsEmitterVisitor.prototype.visitArrayType = function (type, ctx) {
this.visitType(type.of, ctx);
ctx.print(null, "[]");
return null;
};
_TsEmitterVisitor.prototype.visitMapType = function (type, ctx) {
ctx.print(null, "{[key: string]:");
this.visitType(type.valueType, ctx);
ctx.print(null, "}");
return null;
};
_TsEmitterVisitor.prototype.getBuiltinMethodName = function (method) {
var name;
switch (method) {
case BuiltinMethod.ConcatArray:
name = 'concat';
break;
case BuiltinMethod.SubscribeObservable:
name = 'subscribe';
break;
case BuiltinMethod.Bind:
name = 'bind';
break;
default:
throw new Error("Unknown builtin method: " + method);
}
return name;
};
_TsEmitterVisitor.prototype._visitParams = function (params, ctx) {
var _this = this;
this.visitAllObjects(function (param) {
ctx.print(null, param.name);
_this._printColonType(param.type, ctx);
}, params, ctx, ',');
};
_TsEmitterVisitor.prototype._visitIdentifier = function (value, typeParams, ctx) {
var _this = this;
var name = value.name, moduleName = value.moduleName;
if (this.referenceFilter && this.referenceFilter(value)) {
ctx.print(null, '(null as any)');
return;
}
if (moduleName && (!this.importFilter || !this.importFilter(value))) {
var prefix = this.importsWithPrefixes.get(moduleName);
if (prefix == null) {
prefix = "i" + this.importsWithPrefixes.size;
this.importsWithPrefixes.set(moduleName, prefix);
}
ctx.print(null, prefix + ".");
}
ctx.print(null, name);
if (this.typeExpression > 0) {
// If we are in a type expression that refers to a generic type then supply
// the required type parameters. If there were not enough type parameters
// supplied, supply any as the type. Outside a type expression the reference
// should not supply type parameters and be treated as a simple value reference
// to the constructor function itself.
var suppliedParameters = typeParams || [];
if (suppliedParameters.length > 0) {
ctx.print(null, "<");
this.visitAllObjects(function (type) { return type.visitType(_this, ctx); }, typeParams, ctx, ',');
ctx.print(null, ">");
}
}
};
_TsEmitterVisitor.prototype._printColonType = function (type, ctx, defaultType) {
if (type !== INFERRED_TYPE) {
ctx.print(null, ':');
this.visitType(type, ctx, defaultType);
}
};
return _TsEmitterVisitor;
}(AbstractEmitterVisitor));
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Resolve a `Type` for {@link Pipe}.
*
* This interface can be overridden by the application developer to create custom behavior.
*
* See {@link Compiler}
*/
var PipeResolver = /** @class */ (function () {
function PipeResolver(_reflector) {
this._reflector = _reflector;
}
PipeResolver.prototype.isPipe = function (type) {
var typeMetadata = this._reflector.annotations(resolveForwardRef(type));
return typeMetadata && typeMetadata.some(createPipe.isTypeOf);
};
/**
* Return {@link Pipe} for a given `Type`.
*/
PipeResolver.prototype.resolve = function (type, throwIfNotFound) {
if (throwIfNotFound === void 0) { throwIfNotFound = true; }
var metas = this._reflector.annotations(resolveForwardRef(type));
if (metas) {
var annotation = findLast(metas, createPipe.isTypeOf);
if (annotation) {
return annotation;
}
}
if (throwIfNotFound) {
throw new Error("No Pipe decorator found on " + stringify(type));
}
return null;
};
return PipeResolver;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// =================================================================================================
// =================================================================================================
// =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P ===========
// =================================================================================================
// =================================================================================================
//
// DO NOT EDIT THIS LIST OF SECURITY SENSITIVE PROPERTIES WITHOUT A SECURITY REVIEW!
// Reach out to mprobst for details.
//
// =================================================================================================
/** Map from tagName|propertyName SecurityContext. Properties applying to all tags use '*'. */
var SECURITY_SCHEMA = {};
function registerContext(ctx, specs) {
try {
for (var specs_1 = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__values"])(specs), specs_1_1 = specs_1.next(); !specs_1_1.done; specs_1_1 = specs_1.next()) {
var spec = specs_1_1.value;
SECURITY_SCHEMA[spec.toLowerCase()] = ctx;
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (specs_1_1 && !specs_1_1.done && (_a = specs_1.return)) _a.call(specs_1);
}
finally { if (e_1) throw e_1.error; }
}
var e_1, _a;
}
// Case is insignificant below, all element and attribute names are lower-cased for lookup.
registerContext(SecurityContext.HTML, [
'iframe|srcdoc',
'*|innerHTML',
'*|outerHTML',
]);
registerContext(SecurityContext.STYLE, ['*|style']);
// NB: no SCRIPT contexts here, they are never allowed due to the parser stripping them.
registerContext(SecurityContext.URL, [
'*|formAction', 'area|href', 'area|ping', 'audio|src', 'a|href',
'a|ping', 'blockquote|cite', 'body|background', 'del|cite', 'form|action',
'img|src', 'img|srcset', 'input|src', 'ins|cite', 'q|cite',
'source|src', 'source|srcset', 'track|src', 'video|poster', 'video|src',
]);
registerContext(SecurityContext.RESOURCE_URL, [
'applet|code',
'applet|codebase',
'base|href',
'embed|src',
'frame|src',
'head|profile',
'html|manifest',
'iframe|src',
'link|href',
'media|src',
'object|codebase',
'object|data',
'script|src',
]);
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var ElementSchemaRegistry = /** @class */ (function () {
function ElementSchemaRegistry() {
}
return ElementSchemaRegistry;
}());
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var BOOLEAN = 'boolean';
var NUMBER = 'number';
var STRING = 'string';
var OBJECT = 'object';
/**
* This array represents the DOM schema. It encodes inheritance, properties, and events.
*
* ## Overview
*
* Each line represents one kind of element. The `element_inheritance` and properties are joined
* using `element_inheritance|properties` syntax.
*
* ## Element Inheritance
*
* The `element_inheritance` can be further subdivided as `element1,element2,...^parentElement`.
* Here the individual elements are separated by `,` (commas). Every element in the list
* has identical properties.
*
* An `element` may inherit additional properties from `parentElement` If no `^parentElement` is
* specified then `""` (blank) element is assumed.
*
* NOTE: The blank element inherits from root `[Element]` element, the super element of all
* elements.
*
* NOTE an element prefix such as `:svg:` has no special meaning to the schema.
*
* ## Properties
*
* Each element has a set of properties separated by `,` (commas). Each property can be prefixed
* by a special character designating its type:
*
* - (no prefix): property is a string.
* - `*`: property represents an event.
* - `!`: property is a boolean.
* - `#`: property is a number.
* - `%`: property is an object.
*
* ## Query
*
* The class creates an internal squas representation which allows to easily answer the query of
* if a given property exist on a given element.
*
* NOTE: We don't yet support querying for types or events.
* NOTE: This schema is auto extracted from `schema_extractor.ts` located in the test folder,
* see dom_element_schema_registry_spec.ts
*/
// =================================================================================================
// =================================================================================================
// =========== S T O P - S T O P - S T O P - S T O P - S T O P - S T O P ===========
// =================================================================================================
// =================================================================================================
//
// DO NOT EDIT THIS DOM SCHEMA WITHOUT A SECURITY REVIEW!
//
// Newly added properties must be security reviewed and assigned an appropriate SecurityContext in
// dom_security_schema.ts. Reach out to mprobst & rjamet for details.
//
// =================================================================================================
var SCHEMA = [
'[Element]|textContent,%classList,className,id,innerHTML,*beforecopy,*beforecut,*beforepaste,*copy,*cut,*paste,*search,*selectstart,*webkitfullscreenchange,*webkitfullscreenerror,*wheel,outerHTML,#scrollLeft,#scrollTop,slot' +
/* added manually to avoid breaking changes */
',*message,*mozfullscreenchange,*mozfullscreenerror,*mozpointerlockchange,*mozpointerlockerror,*webglcontextcreationerror,*webglcontextlost,*webglcontextrestored',
'[HTMLElement]^[Element]|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*auxclick,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,outerText,!spellcheck,%style,#tabIndex,title,!translate',
'abbr,address,article,aside,b,bdi,bdo,cite,code,dd,dfn,dt,em,figcaption,figure,footer,header,i,kbd,main,mark,nav,noscript,rb,rp,rt,rtc,ruby,s,samp,section,small,strong,sub,sup,u,var,wbr^[HTMLElement]|accessKey,contentEditable,dir,!draggable,!hidden,innerText,lang,*abort,*auxclick,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,outerText,!spellcheck,%style,#tabIndex,title,!translate',
'media^[HTMLElement]|!autoplay,!controls,%controlsList,%crossOrigin,#currentTime,!defaultMuted,#defaultPlaybackRate,!disableRemotePlayback,!loop,!muted,*encrypted,*waitingforkey,#playbackRate,preload,src,%srcObject,#volume',
':svg:^[HTMLElement]|*abort,*auxclick,*blur,*cancel,*canplay,*canplaythrough,*change,*click,*close,*contextmenu,*cuechange,*dblclick,*drag,*dragend,*dragenter,*dragleave,*dragover,*dragstart,*drop,*durationchange,*emptied,*ended,*error,*focus,*gotpointercapture,*input,*invalid,*keydown,*keypress,*keyup,*load,*loadeddata,*loadedmetadata,*loadstart,*lostpointercapture,*mousedown,*mouseenter,*mouseleave,*mousemove,*mouseout,*mouseover,*mouseup,*mousewheel,*pause,*play,*playing,*pointercancel,*pointerdown,*pointerenter,*pointerleave,*pointermove,*pointerout,*pointerover,*pointerup,*progress,*ratechange,*reset,*resize,*scroll,*seeked,*seeking,*select,*show,*stalled,*submit,*suspend,*timeupdate,*toggle,*volumechange,*waiting,%style,#tabIndex',
':svg:graphics^:svg:|',
':svg:animation^:svg:|*begin,*end,*repeat',
':svg:geometry^:svg:|',
':svg:componentTransferFunction^:svg:|',
':svg:gradient^:svg:|',
':svg:textContent^:svg:graphics|',
':svg:textPositioning^:svg:textContent|',
'a^[HTMLElement]|charset,coords,download,hash,host,hostname,href,hreflang,name,password,pathname,ping,port,protocol,referrerPolicy,rel,rev,search,shape,target,text,type,username',
'area^[HTMLElement]|alt,coords,download,hash,host,hostname,href,!noHref,password,pathname,ping,port,protocol,referrerPolicy,rel,search,shape,target,username',
'audio^media|',
'br^[HTMLElement]|clear',
'base^[HTMLElement]|href,target',
'body^[HTMLElement]|aLink,background,bgColor,link,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,text,vLink',
'button^[HTMLElement]|!autofocus,!disabled,formAction,formEnctype,formMethod,!formNoValidate,formTarget,name,type,value',
'canvas^[HTMLElement]|#height,#width',
'content^[HTMLElement]|select',
'dl^[HTMLElement]|!compact',
'datalist^[HTMLElement]|',
'details^[HTMLElement]|!open',
'dialog^[HTMLElement]|!open,returnValue',
'dir^[HTMLElement]|!compact',
'div^[HTMLElement]|align',
'embed^[HTMLElement]|align,height,name,src,type,width',
'fieldset^[HTMLElement]|!disabled,name',
'font^[HTMLElement]|color,face,size',
'form^[HTMLElement]|acceptCharset,action,autocomplete,encoding,enctype,method,name,!noValidate,target',
'frame^[HTMLElement]|frameBorder,longDesc,marginHeight,marginWidth,name,!noResize,scrolling,src',
'frameset^[HTMLElement]|cols,*beforeunload,*blur,*error,*focus,*hashchange,*languagechange,*load,*message,*offline,*online,*pagehide,*pageshow,*popstate,*rejectionhandled,*resize,*scroll,*storage,*unhandledrejection,*unload,rows',
'hr^[HTMLElement]|align,color,!noShade,size,width',
'head^[HTMLElement]|',
'h1,h2,h3,h4,h5,h6^[HTMLElement]|align',
'html^[HTMLElement]|version',
'iframe^[HTMLElement]|align,!allowFullscreen,frameBorder,height,longDesc,marginHeight,marginWidth,name,referrerPolicy,%sandbox,scrolling,src,srcdoc,width',
'img^[HTMLElement]|align,alt,border,%crossOrigin,#height,#hspace,!isMap,longDesc,lowsrc,name,referrerPolicy,sizes,src,srcset,useMap,#vspace,#width',
'input^[HTMLElement]|accept,align,alt,autocapitalize,autocomplete,!autofocus,!checked,!defaultChecked,defaultValue,dirName,!disabled,%files,formAction,formEnctype,formMethod,!formNoValidate,formTarget,#height,!incremental,!indeterminate,max,#maxLength,min,#minLength,!multiple,name,pattern,placeholder,!readOnly,!required,selectionDirection,#selectionEnd,#selectionStart,#size,src,step,type,useMap,value,%valueAsDate,#valueAsNumber,#width',
'li^[HTMLElement]|type,#value',
'label^[HTMLElement]|htmlFor',
'legend^[HTMLElement]|align',
'link^[HTMLElement]|as,charset,%crossOrigin,!disabled,href,hreflang,integrity,media,referrerPolicy,rel,%relList,rev,%sizes,target,type',
'map^[HTMLElement]|name',
'marquee^[HTMLElement]|behavior,bgColor,direction,height,#hspace,#loop,#scrollAmount,#scrollDelay,!trueSpeed,#vspace,width',
'menu^[HTMLElement]|!compact',
'meta^[HTMLElement]|content,httpEquiv,name,scheme',
'meter^[HTMLElement]|#high,#low,#max,#min,#optimum,#value',
'ins,del^[HTMLElement]|cite,dateTime',
'ol^[HTMLElement]|!compact,!reversed,#start,type',
'object^[HTMLElement]|align,archive,border,code,codeBase,codeType,data,!declare,height,#hspace,name,standby,type,useMap,#vspace,width',
'optgroup^[HTMLElement]|!disabled,label',
'option^[HTMLElement]|!defaultSelected,!disabled,label,!selected,text,value',
'output^[HTMLElement]|defaultValue,%htmlFor,name,value',
'p^[HTMLElement]|align',
'param^[HTMLElement]|name,type,value,valueType',
'picture^[HTMLElement]|',
'pre^[HTMLElement]|#width',
'progress^[HTMLElement]|#max,#value',
'q,blockquote,cite^[HTMLElement]|',
'script^[HTMLElement]|!async,charset,%crossOrigin,!defer,event,htmlFor,integrity,src,text,type',
'select^[HTMLElement]|!autofocus,!disabled,#length,!multiple,name,!required,#selectedIndex,#size,value',
'shadow^[HTMLElement]|',
'slot^[HTMLElement]|name',
'source^[HTMLElement]|media,sizes,src,srcset,type',
'span^[HTMLElement]|',
'style^[HTMLElement]|!disabled,media,type',
'caption^[HTMLElement]|align',
'th,td^[HTMLElement]|abbr,align,axis,bgColor,ch,chOff,#colSpan,headers,height,!noWrap,#rowSpan,scope,vAlign,width',
'col,colgroup^[HTMLElement]|align,ch,chOff,#span,vAlign,width',
'table^[HTMLElement]|align,bgColor,border,%caption,cellPadding,cellSpacing,frame,rules,summary,%tFoot,%tHead,width',
'tr^[HTMLElement]|align,bgColor,ch,chOff,vAlign',
'tfoot,thead,tbody^[HTMLElement]|align,ch,chOff,vAlign',
'template^[HTMLElement]|',
'textarea^[HTMLElement]|autocapitalize,!autofocus,#cols,defaultValue,dirName,!disabled,#maxLength,#minLength,name,placeholder,!readOnly,!required,#rows,selectionDirection,#selectionEnd,#selectionStart,value,wrap',
'title^[HTMLElement]|text',
'track^[HTMLElement]|!default,kind,label,src,srclang',
'ul^[HTMLElement]|!compact,type',
'unknown^[HTMLElement]|',
'video^media|#height,poster,#width',
':svg:a^:svg:graphics|',
':svg:animate^:svg:animation|',
':svg:animateMotion^:svg:animation|',
':svg:animateTransform^:svg:animation|',
':svg:circle^:svg:geometry|',
':svg:clipPath^:svg:graphics|',
':svg:defs^:svg:graphics|',
':svg:desc^:svg:|',
':svg:discard^:svg:|',
':svg:ellipse^:svg:geometry|',
':svg:feBlend^:svg:|',
':svg:feColorMatrix^:svg:|',
':svg:feComponentTransfer^:svg:|',
':svg:feComposite^:svg:|',
':svg:feConvolveMatrix^:svg:|',
':svg:feDiffuseLighting^:svg:|',
':svg:feDisplacementMap^:svg:|',
':svg:feDistantLight^:svg:|',
':svg:feDropShadow^:svg:|',
':svg:feFlood^:svg:|',
':svg:feFuncA^:svg:componentTransferFunction|',
':svg:feFuncB^:svg:componentTransferFunction|',
':svg:feFuncG^:svg:componentTransferFunction|',
':svg:feFuncR^:svg:componentTransferFunction|',
':svg:feGaussianBlur^:svg:|',
':svg:feImage^:svg:|',
':svg:feMerge^:svg:|',
':svg:feMergeNode^:svg:|',
':svg:feMorphology^:svg:|',
':svg:feOffset^:svg:|',
':svg:fePointLight^:svg:|',
':svg:feSpecularLighting^:svg:|',
':svg:feSpotLight^:svg:|',
':svg:feTile^:svg:|',
':svg:feTurbulence^:svg:|',
':svg:filter^:svg:|',
':svg:foreignObject^:svg:graphics|',
':svg:g^:svg:graphics|',
':svg:image^:svg:graphics|',
':svg:line^:svg:geometry|',
':svg:linearGradient^:svg:gradient|',
':svg:mpath^:svg:|',
':svg:marker^:svg:|',
':svg:mask^:svg:|',
':svg:metadata^:svg:|',
':svg:path^:svg:geometry|',
':svg:pattern^:svg:|',
':svg:polygon^:svg:geometry|',
':svg:polyline^:svg:geometry|',
':svg:radialGradient^:svg:gradient|',
':svg:rect^:svg:geometry|',
':svg:svg^:svg:graphics|#currentScale,#zoomAndPan',
':svg:script^:svg:|type',
':svg:set^:svg:animation|',
':svg:stop^:svg:|',
':svg:style^:svg:|!disabled,media,title,type',
':svg:switch^:svg:graphics|',
':svg:symbol^:svg:|',
':svg:tspan^:svg:textPositioning|',
':svg:text^:svg:textPositioning|',
':svg:textPath^:svg:textContent|',
':svg:title^:svg:|',
':svg:use^:svg:graphics|',
':svg:view^:svg:|#zoomAndPan',
'data^[HTMLElement]|value',
'keygen^[HTMLElement]|!autofocus,challenge,!disabled,form,keytype,name',
'menuitem^[HTMLElement]|type,label,icon,!disabled,!checked,radiogroup,!default',
'summary^[HTMLElement]|',
'time^[HTMLElement]|dateTime',
':svg:cursor^:svg:|',
];
var _ATTR_TO_PROP = {
'class': 'className',
'for': 'htmlFor',
'formaction': 'formAction',
'innerHtml': 'innerHTML',
'readonly': 'readOnly',
'tabindex': 'tabIndex',
};
var DomElementSchemaRegistry = /** @class */ (function (_super) {
Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__extends"])(DomElementSchemaRegistry, _super);
function DomElementSchemaRegistry() {
var _this = _super.call(this) || this;
_this._schema = {};
SCHEMA.forEach(function (encodedType) {
var type = {};
var _a = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__read"])(encodedType.split('|'), 2), strType = _a[0], strProperties = _a[1];
var properties = strProperties.split(',');
var _b = Object(tslib__WEBPACK_IMPORTED_MODULE_0__["__read"])(strType.split('^'), 2), typeNames = _b[0], superName = _b[1];
typeNames.split(',').forEach(function (tag) { return _this._schema[tag.toLowerCase()] = type; });
var superType = superName && _this._schema[superName.toLowerCase()];
if (superType) {
Object.keys(superType).forEach(function (prop) { type[prop] = superType[prop]; });
}
properties.forEach(function (property) {
if (property.length > 0) {
switch (property[0]) {
case '*':
// We don't yet support events.
// If ever allowing to bind to events, GO THROUGH A SECURITY REVIEW, allowing events
// will
// almost certainly introduce bad XSS vulnerabilities.
// type[property.substring(1)] = EVENT;
break;
case '!':
type[property.substring(1)] = BOOLEAN;
break;
case '#':
type[property.substring(1)] = NUMBER;
break;
case '%':
type[property.substring(1)] = OBJECT;
break;
default:
type[property] = STRING;
}
}
});
});
return _this;
}
DomElementSchemaRegistry.prototype.hasProperty = function (tagName, propName, schemaMetas) {
if (schemaMetas.some(function (schema) { return schema.name === NO_ERRORS_SCHEMA.name; })) {
return true;
}
if (tagName.indexOf('-') > -1) {
if (isNgContainer(tagName) || isNgContent(tagName)) {
return false;
}
if (schemaMetas.some(function (schema) { return schema.name === CUSTOM_ELEMENTS_SCHEMA.name; })) {
// Can't tell now as we don't know which properties a custom element will get
// once it is instantiated
return true;
}
}
var elementProperties = this._schema[tagName.toLowerCase()] || this._schema['unknown'];
return !!elementProperties[propName];
};
DomElementSchemaRegistry.prototype.hasElement = function (tagName, schemaMetas) {
if (schemaMetas.some(function (schema) { return schema.name === NO_ERRORS_SCHEMA.name; })) {
return true;
}
if (tagName.indexOf('-') > -1) {
if (isNgContainer(tagName) || isNgContent(tagName)) {
return true;
}
if (schemaMetas.some(function (schema) { return schema.name === CUSTOM_ELEMENTS_SCHEMA.name; })) {
// Allow any custom elements
return true;
}
}
return !!this._schema[tagName.toLowerCase()];
};
/**
* securityContext returns the security context for the given property on the given DOM tag.
*
* Tag and property name are statically known and cannot change at runtime, i.e. it is not
* possible to bind a value into a changing attribute or tag name.
*
* The filtering is white list based. All attributes in the schema above are assumed to have the
* 'NONE' security context, i.e. that they are safe inert string values. Only specific well known
* attack vectors are assigned their appropriate context.
*/
DomElementSchemaRegistry.prototype.securityContext = function (tagName, propName, isAttribute) {
if (isAttribute) {
// NB: For security purposes, use the mapped property name, not the attribute name.
propName = this.getMappedPropName(propName);
}
// Make sure comparisons are case insensitive, so that case differences between attribute and
// property names do not have a security impact.
tagName = tagName.toLowerCase();
propName = propName.toLowerCase();
var ctx = SECURITY_SCHEMA[tagName + '|' + propName];
if (ctx) {
return ctx;
}
ctx = SECURITY_SCHEMA['*|' + propName];
return ctx ? ctx : SecurityContext.NONE;
};
DomElementSchemaRegistry.prototype.getMappedPropName = function (propName) { return _ATTR_TO_PROP[propName] || propName; };
DomElementSchemaRegistry.prototype.getDefaultComponentElementName = function () { return 'ng-component'; };
DomElementSchemaRegistry.prototype.validateProperty = function (name) {
if (name.toLowerCase().startsWith('on')) {
var msg = "Binding to event property '" + name + "' is disallowed for security reasons, " +
("please use (" + name.slice(2) + ")=...") +
("\nIf '" + name + "' is a directive input, make sure the directive is imported by the") +
" current module.";
return { error: true, msg: msg };
}
else {
return { error: false };
}
};
DomElementSchemaRegistry.prototype.validateAttribute = function (name) {
if (name.toLowerCase().startsWith('on')) {
var msg = "Binding to event attribute '" + name + "' is disallowed for security reasons, " +
("please use (" + name.slice(2) + ")=...");
return { error: true, msg: msg };
}
else {
return { error: false };
}
};
DomElementSchemaRegistry.prototype.allKnownElementNames = function () { return Object.keys(this._schema); };
DomElementSchemaRegistry.prototype.normalizeAnimationStyleProperty = function (propName) {
return dashCaseToCamelCase(propName);
};
DomElementSchemaRegistry.prototype.normalizeAnimationStyleValue = function (camelCaseProp, userProvidedProp, val) {
var unit = '';
var strVal = val.toString().trim();
var errorMsg = null;
if (_isPixelDimensionStyle(camelCaseProp) && val !== 0 && val !== '0') {
if (typeof val === 'number') {
unit = 'px';
}
else {
var valAndSuffixMatch = val.match(/^[+-]?[\d\.]+([a-z]*)$/);
if (valAndSuffixMatch && valAndSuffixMatch[1].length == 0) {
errorMsg = "Please provide a CSS unit value for " + userProvidedProp + ":" + val;
}
}
}
return { error: errorMsg, value: strVal + unit };
};
return DomElementSchemaRegistry;
}(ElementSchemaRegistry));
function _isPixelDimensionStyle(prop) {
switch (prop) {
case 'width':
case 'height':
case 'minWidth':
case 'minHeight':
case 'maxWidth':
case 'maxHeight':
case 'left':
case 'top':
case 'bottom':
case 'right':
case 'fontSize':
case 'outlineWidth':
case 'outlineOffset':
case 'paddingTop':
case 'paddingLeft':
case 'paddingBottom':
case 'paddingRight':
case 'marginTop':
case 'marginLeft':
case 'marginBottom':
case 'marginRight':
case 'borderRadius':
case 'borderWidth':
case 'borderTopWidth':
case 'borderLeftWidth':
case 'borderRightWidth':
case 'borderBottomWidth':
case 'textIndent':
return true;
default:
return false;
}
}
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* This file is a port of shadowCSS from webcomponents.js to TypeScript.
*
* Please make sure to keep to edits in sync with the source file.
*
* Source:
* https://github.com/webcomponents/webcomponentsjs/blob/4efecd7e0e/src/ShadowCSS/ShadowCSS.js
*
* The original file level comment is reproduced below
*/
/*
This is a limited shim for ShadowDOM css styling.
https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/shadow/index.html#styles
The intention here is to support only the styling features which can be
relatively simply implemented. The goal is to allow users to avoid the
most obvious pitfalls and do so without compromising performance significantly.
For ShadowDOM styling that's not covered here, a set of best practices
can be provided that should allow users to accomplish more complex styling.
The following is a list of specific ShadowDOM styling features and a brief
discussion of the approach used to shim.
Shimmed features:
* :host, :host-context: ShadowDOM allows styling of the shadowRoot's host
element using the :host rule. To shim this feature, the :host styles are
reformatted and prefixed with a given scope name and promoted to a
document level stylesheet.
For example, given a scope name of .foo, a rule like this:
:host {
background: red;
}
}
becomes:
.foo {
background: red;
}
* encapsulation: Styles defined within ShadowDOM, apply only to
dom inside the ShadowDOM. Polymer uses one of two techniques to implement
this feature.
By default, rules are prefixed with the host element tag name
as a descendant selector. This ensures styling does not leak out of the 'top'
of the element's ShadowDOM. For example,
div {
font-weight: bold;
}
becomes:
x-foo div {
font-weight: bold;
}
becomes:
Alternatively, if WebComponents.ShadowCSS.strictStyling is set to true then
selectors are scoped by adding an attribute selector suffix to each
simple selector that contains the host element tag name. Each element
in the element's ShadowDOM template is also given the scope attribute.
Thus, these rules match only elements that have the scope attribute.
For example, given a scope name of x-foo, a rule like this:
div {
font-weight: bold;
}
becomes:
div[x-foo] {
font-weight: bold;
}
Note that elements that are dynamically added to a scope must have the scope
selector added to them manually.
* upper/lower bound encapsulation: Styles which are defined outside a
shadowRoot should not cross the ShadowDOM boundary and should not apply
inside a shadowRoot.
This styling behavior is not emulated. Some possible ways to do this that
were rejected due to complexity and/or performance concerns include: (1) reset
every possible property for every possible selector for a given scope name;
(2) re-implement css in javascript.
As an alternative, users should make sure to use selectors
specific to the scope in which they are working.
* ::distributed: This behavior is not emulated. It's often not necessary
to style the contents of a specific insertion point and instead, descendants
of the host element can be styled selectively. Users can also create an
extra node around an insertion point and style that node's contents
via descendent selectors. For example, with a shadowRoot like this: