blob: 1b85f28da3da1c5bff8307ea90c8a301e0cf1d01 [file] [log] [blame]
/**
* @license Angular v11.2.14
* (c) 2010-2021 Google LLC. https://angular.io/
* License: MIT
*/
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var TagContentType;
(function (TagContentType) {
TagContentType[TagContentType["RAW_TEXT"] = 0] = "RAW_TEXT";
TagContentType[TagContentType["ESCAPABLE_RAW_TEXT"] = 1] = "ESCAPABLE_RAW_TEXT";
TagContentType[TagContentType["PARSABLE_DATA"] = 2] = "PARSABLE_DATA";
})(TagContentType || (TagContentType = {}));
function splitNsName(elementName) {
if (elementName[0] != ':') {
return [null, elementName];
}
const colonIndex = elementName.indexOf(':', 1);
if (colonIndex == -1) {
throw new Error(`Unsupported format "${elementName}" expecting ":namespace:name"`);
}
return [elementName.slice(1, colonIndex), elementName.slice(colonIndex + 1)];
}
// `<ng-container>` tags work the same regardless the namespace
function isNgContainer(tagName) {
return splitNsName(tagName)[1] === 'ng-container';
}
// `<ng-content>` tags work the same regardless the namespace
function isNgContent(tagName) {
return splitNsName(tagName)[1] === 'ng-content';
}
// `<ng-template>` tags work the same regardless the namespace
function isNgTemplate(tagName) {
return splitNsName(tagName)[1] === 'ng-template';
}
function getNsPrefix(fullName) {
return fullName === null ? null : splitNsName(fullName)[0];
}
function mergeNsAndName(prefix, localName) {
return prefix ? `:${prefix}:${localName}` : localName;
}
// see https://www.w3.org/TR/html51/syntax.html#named-character-references
// see https://html.spec.whatwg.org/multipage/entities.json
// This list is not exhaustive to keep the compiler footprint low.
// The `&#123;` / `&#x1ab;` syntax should be used when the named character reference does not
// exist.
const NAMED_ENTITIES = {
'Aacute': '\u00C1',
'aacute': '\u00E1',
'Acirc': '\u00C2',
'acirc': '\u00E2',
'acute': '\u00B4',
'AElig': '\u00C6',
'aelig': '\u00E6',
'Agrave': '\u00C0',
'agrave': '\u00E0',
'alefsym': '\u2135',
'Alpha': '\u0391',
'alpha': '\u03B1',
'amp': '&',
'and': '\u2227',
'ang': '\u2220',
'apos': '\u0027',
'Aring': '\u00C5',
'aring': '\u00E5',
'asymp': '\u2248',
'Atilde': '\u00C3',
'atilde': '\u00E3',
'Auml': '\u00C4',
'auml': '\u00E4',
'bdquo': '\u201E',
'Beta': '\u0392',
'beta': '\u03B2',
'brvbar': '\u00A6',
'bull': '\u2022',
'cap': '\u2229',
'Ccedil': '\u00C7',
'ccedil': '\u00E7',
'cedil': '\u00B8',
'cent': '\u00A2',
'Chi': '\u03A7',
'chi': '\u03C7',
'circ': '\u02C6',
'clubs': '\u2663',
'cong': '\u2245',
'copy': '\u00A9',
'crarr': '\u21B5',
'cup': '\u222A',
'curren': '\u00A4',
'dagger': '\u2020',
'Dagger': '\u2021',
'darr': '\u2193',
'dArr': '\u21D3',
'deg': '\u00B0',
'Delta': '\u0394',
'delta': '\u03B4',
'diams': '\u2666',
'divide': '\u00F7',
'Eacute': '\u00C9',
'eacute': '\u00E9',
'Ecirc': '\u00CA',
'ecirc': '\u00EA',
'Egrave': '\u00C8',
'egrave': '\u00E8',
'empty': '\u2205',
'emsp': '\u2003',
'ensp': '\u2002',
'Epsilon': '\u0395',
'epsilon': '\u03B5',
'equiv': '\u2261',
'Eta': '\u0397',
'eta': '\u03B7',
'ETH': '\u00D0',
'eth': '\u00F0',
'Euml': '\u00CB',
'euml': '\u00EB',
'euro': '\u20AC',
'exist': '\u2203',
'fnof': '\u0192',
'forall': '\u2200',
'frac12': '\u00BD',
'frac14': '\u00BC',
'frac34': '\u00BE',
'frasl': '\u2044',
'Gamma': '\u0393',
'gamma': '\u03B3',
'ge': '\u2265',
'gt': '>',
'harr': '\u2194',
'hArr': '\u21D4',
'hearts': '\u2665',
'hellip': '\u2026',
'Iacute': '\u00CD',
'iacute': '\u00ED',
'Icirc': '\u00CE',
'icirc': '\u00EE',
'iexcl': '\u00A1',
'Igrave': '\u00CC',
'igrave': '\u00EC',
'image': '\u2111',
'infin': '\u221E',
'int': '\u222B',
'Iota': '\u0399',
'iota': '\u03B9',
'iquest': '\u00BF',
'isin': '\u2208',
'Iuml': '\u00CF',
'iuml': '\u00EF',
'Kappa': '\u039A',
'kappa': '\u03BA',
'Lambda': '\u039B',
'lambda': '\u03BB',
'lang': '\u27E8',
'laquo': '\u00AB',
'larr': '\u2190',
'lArr': '\u21D0',
'lceil': '\u2308',
'ldquo': '\u201C',
'le': '\u2264',
'lfloor': '\u230A',
'lowast': '\u2217',
'loz': '\u25CA',
'lrm': '\u200E',
'lsaquo': '\u2039',
'lsquo': '\u2018',
'lt': '<',
'macr': '\u00AF',
'mdash': '\u2014',
'micro': '\u00B5',
'middot': '\u00B7',
'minus': '\u2212',
'Mu': '\u039C',
'mu': '\u03BC',
'nabla': '\u2207',
'nbsp': '\u00A0',
'ndash': '\u2013',
'ne': '\u2260',
'ni': '\u220B',
'not': '\u00AC',
'notin': '\u2209',
'nsub': '\u2284',
'Ntilde': '\u00D1',
'ntilde': '\u00F1',
'Nu': '\u039D',
'nu': '\u03BD',
'Oacute': '\u00D3',
'oacute': '\u00F3',
'Ocirc': '\u00D4',
'ocirc': '\u00F4',
'OElig': '\u0152',
'oelig': '\u0153',
'Ograve': '\u00D2',
'ograve': '\u00F2',
'oline': '\u203E',
'Omega': '\u03A9',
'omega': '\u03C9',
'Omicron': '\u039F',
'omicron': '\u03BF',
'oplus': '\u2295',
'or': '\u2228',
'ordf': '\u00AA',
'ordm': '\u00BA',
'Oslash': '\u00D8',
'oslash': '\u00F8',
'Otilde': '\u00D5',
'otilde': '\u00F5',
'otimes': '\u2297',
'Ouml': '\u00D6',
'ouml': '\u00F6',
'para': '\u00B6',
'permil': '\u2030',
'perp': '\u22A5',
'Phi': '\u03A6',
'phi': '\u03C6',
'Pi': '\u03A0',
'pi': '\u03C0',
'piv': '\u03D6',
'plusmn': '\u00B1',
'pound': '\u00A3',
'prime': '\u2032',
'Prime': '\u2033',
'prod': '\u220F',
'prop': '\u221D',
'Psi': '\u03A8',
'psi': '\u03C8',
'quot': '\u0022',
'radic': '\u221A',
'rang': '\u27E9',
'raquo': '\u00BB',
'rarr': '\u2192',
'rArr': '\u21D2',
'rceil': '\u2309',
'rdquo': '\u201D',
'real': '\u211C',
'reg': '\u00AE',
'rfloor': '\u230B',
'Rho': '\u03A1',
'rho': '\u03C1',
'rlm': '\u200F',
'rsaquo': '\u203A',
'rsquo': '\u2019',
'sbquo': '\u201A',
'Scaron': '\u0160',
'scaron': '\u0161',
'sdot': '\u22C5',
'sect': '\u00A7',
'shy': '\u00AD',
'Sigma': '\u03A3',
'sigma': '\u03C3',
'sigmaf': '\u03C2',
'sim': '\u223C',
'spades': '\u2660',
'sub': '\u2282',
'sube': '\u2286',
'sum': '\u2211',
'sup': '\u2283',
'sup1': '\u00B9',
'sup2': '\u00B2',
'sup3': '\u00B3',
'supe': '\u2287',
'szlig': '\u00DF',
'Tau': '\u03A4',
'tau': '\u03C4',
'there4': '\u2234',
'Theta': '\u0398',
'theta': '\u03B8',
'thetasym': '\u03D1',
'thinsp': '\u2009',
'THORN': '\u00DE',
'thorn': '\u00FE',
'tilde': '\u02DC',
'times': '\u00D7',
'trade': '\u2122',
'Uacute': '\u00DA',
'uacute': '\u00FA',
'uarr': '\u2191',
'uArr': '\u21D1',
'Ucirc': '\u00DB',
'ucirc': '\u00FB',
'Ugrave': '\u00D9',
'ugrave': '\u00F9',
'uml': '\u00A8',
'upsih': '\u03D2',
'Upsilon': '\u03A5',
'upsilon': '\u03C5',
'Uuml': '\u00DC',
'uuml': '\u00FC',
'weierp': '\u2118',
'Xi': '\u039E',
'xi': '\u03BE',
'Yacute': '\u00DD',
'yacute': '\u00FD',
'yen': '\u00A5',
'yuml': '\u00FF',
'Yuml': '\u0178',
'Zeta': '\u0396',
'zeta': '\u03B6',
'zwj': '\u200D',
'zwnj': '\u200C',
};
// The &ngsp; pseudo-entity is denoting a space. see:
// https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart
const NGSP_UNICODE = '\uE500';
NAMED_ENTITIES['ngsp'] = NGSP_UNICODE;
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class HtmlTagDefinition {
constructor({ closedByChildren, implicitNamespacePrefix, contentType = TagContentType.PARSABLE_DATA, closedByParent = false, isVoid = false, ignoreFirstLf = false, preventNamespaceInheritance = false } = {}) {
this.closedByChildren = {};
this.closedByParent = false;
this.canSelfClose = false;
if (closedByChildren && closedByChildren.length > 0) {
closedByChildren.forEach(tagName => this.closedByChildren[tagName] = true);
}
this.isVoid = isVoid;
this.closedByParent = closedByParent || isVoid;
this.implicitNamespacePrefix = implicitNamespacePrefix || null;
this.contentType = contentType;
this.ignoreFirstLf = ignoreFirstLf;
this.preventNamespaceInheritance = preventNamespaceInheritance;
}
isClosedByChild(name) {
return this.isVoid || name.toLowerCase() in this.closedByChildren;
}
getContentType(prefix) {
if (typeof this.contentType === 'object') {
const overrideType = prefix == null ? undefined : this.contentType[prefix];
return overrideType !== null && overrideType !== void 0 ? overrideType : this.contentType.default;
}
return this.contentType;
}
}
let _DEFAULT_TAG_DEFINITION;
// see https://www.w3.org/TR/html51/syntax.html#optional-tags
// This implementation does not fully conform to the HTML5 spec.
let TAG_DEFINITIONS;
function getHtmlTagDefinition(tagName) {
var _a, _b;
if (!TAG_DEFINITIONS) {
_DEFAULT_TAG_DEFINITION = new HtmlTagDefinition();
TAG_DEFINITIONS = {
'base': new HtmlTagDefinition({ isVoid: true }),
'meta': new HtmlTagDefinition({ isVoid: true }),
'area': new HtmlTagDefinition({ isVoid: true }),
'embed': new HtmlTagDefinition({ isVoid: true }),
'link': new HtmlTagDefinition({ isVoid: true }),
'img': new HtmlTagDefinition({ isVoid: true }),
'input': new HtmlTagDefinition({ isVoid: true }),
'param': new HtmlTagDefinition({ isVoid: true }),
'hr': new HtmlTagDefinition({ isVoid: true }),
'br': new HtmlTagDefinition({ isVoid: true }),
'source': new HtmlTagDefinition({ isVoid: true }),
'track': new HtmlTagDefinition({ isVoid: true }),
'wbr': new HtmlTagDefinition({ isVoid: true }),
'p': new HtmlTagDefinition({
closedByChildren: [
'address', 'article', 'aside', 'blockquote', 'div', 'dl', 'fieldset',
'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5',
'h6', 'header', 'hgroup', 'hr', 'main', 'nav', 'ol',
'p', 'pre', 'section', 'table', 'ul'
],
closedByParent: true
}),
'thead': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'] }),
'tbody': new HtmlTagDefinition({ closedByChildren: ['tbody', 'tfoot'], closedByParent: true }),
'tfoot': new HtmlTagDefinition({ closedByChildren: ['tbody'], closedByParent: true }),
'tr': new HtmlTagDefinition({ closedByChildren: ['tr'], closedByParent: true }),
'td': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
'th': new HtmlTagDefinition({ closedByChildren: ['td', 'th'], closedByParent: true }),
'col': new HtmlTagDefinition({ isVoid: true }),
'svg': new HtmlTagDefinition({ implicitNamespacePrefix: 'svg' }),
'foreignObject': new HtmlTagDefinition({
// Usually the implicit namespace here would be redundant since it will be inherited from
// the parent `svg`, but we have to do it for `foreignObject`, because the way the parser
// works is that the parent node of an end tag is its own start tag which means that
// the `preventNamespaceInheritance` on `foreignObject` would have it default to the
// implicit namespace which is `html`, unless specified otherwise.
implicitNamespacePrefix: 'svg',
// We want to prevent children of foreignObject from inheriting its namespace, because
// the point of the element is to allow nodes from other namespaces to be inserted.
preventNamespaceInheritance: true,
}),
'math': new HtmlTagDefinition({ implicitNamespacePrefix: 'math' }),
'li': new HtmlTagDefinition({ closedByChildren: ['li'], closedByParent: true }),
'dt': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'] }),
'dd': new HtmlTagDefinition({ closedByChildren: ['dt', 'dd'], closedByParent: true }),
'rb': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
'rt': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
'rtc': new HtmlTagDefinition({ closedByChildren: ['rb', 'rtc', 'rp'], closedByParent: true }),
'rp': new HtmlTagDefinition({ closedByChildren: ['rb', 'rt', 'rtc', 'rp'], closedByParent: true }),
'optgroup': new HtmlTagDefinition({ closedByChildren: ['optgroup'], closedByParent: true }),
'option': new HtmlTagDefinition({ closedByChildren: ['option', 'optgroup'], closedByParent: true }),
'pre': new HtmlTagDefinition({ ignoreFirstLf: true }),
'listing': new HtmlTagDefinition({ ignoreFirstLf: true }),
'style': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }),
'script': new HtmlTagDefinition({ contentType: TagContentType.RAW_TEXT }),
'title': new HtmlTagDefinition({
// The browser supports two separate `title` tags which have to use
// a different content type: `HTMLTitleElement` and `SVGTitleElement`
contentType: { default: TagContentType.ESCAPABLE_RAW_TEXT, svg: TagContentType.PARSABLE_DATA }
}),
'textarea': new HtmlTagDefinition({ contentType: TagContentType.ESCAPABLE_RAW_TEXT, ignoreFirstLf: true }),
};
}
// We have to make both a case-sensitive and a case-insesitive lookup, because
// HTML tag names are case insensitive, whereas some SVG tags are case sensitive.
return (_b = (_a = TAG_DEFINITIONS[tagName]) !== null && _a !== void 0 ? _a : TAG_DEFINITIONS[tagName.toLowerCase()]) !== null && _b !== void 0 ? _b : _DEFAULT_TAG_DEFINITION;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const _SELECTOR_REGEXP = new RegExp('(\\:not\\()|' + // 1: ":not("
'(([\\.\\#]?)[-\\w]+)|' + // 2: "tag"; 3: "."/"#";
// "-" should appear first in the regexp below as FF31 parses "[.-\w]" as a range
// 4: attribute; 5: attribute_string; 6: attribute_value
'(?:\\[([-.\\w*]+)(?:=([\"\']?)([^\\]\"\']*)\\5)?\\])|' + // "[name]", "[name=value]",
// "[name="value"]",
// "[name='value']"
'(\\))|' + // 7: ")"
'(\\s*,\\s*)', // 8: ","
'g');
/**
* A css selector contains an element name,
* css classes and attribute/value pairs with the purpose
* of selecting subsets out of them.
*/
class CssSelector {
constructor() {
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 = [];
}
static parse(selector) {
const results = [];
const _addResult = (res, cssSel) => {
if (cssSel.notSelectors.length > 0 && !cssSel.element && cssSel.classNames.length == 0 &&
cssSel.attrs.length == 0) {
cssSel.element = '*';
}
res.push(cssSel);
};
let cssSelector = new CssSelector();
let match;
let current = cssSelector;
let inNot = false;
_SELECTOR_REGEXP.lastIndex = 0;
while (match = _SELECTOR_REGEXP.exec(selector)) {
if (match[1 /* NOT */]) {
if (inNot) {
throw new Error('Nesting :not in a selector is not allowed');
}
inNot = true;
current = new CssSelector();
cssSelector.notSelectors.push(current);
}
const tag = match[2 /* TAG */];
if (tag) {
const prefix = match[3 /* PREFIX */];
if (prefix === '#') {
// #hash
current.addAttribute('id', tag.substr(1));
}
else if (prefix === '.') {
// Class
current.addClassName(tag.substr(1));
}
else {
// Element
current.setElement(tag);
}
}
const attribute = match[4 /* ATTRIBUTE */];
if (attribute) {
current.addAttribute(attribute, match[6 /* ATTRIBUTE_VALUE */]);
}
if (match[7 /* NOT_END */]) {
inNot = false;
current = cssSelector;
}
if (match[8 /* SEPARATOR */]) {
if (inNot) {
throw new Error('Multiple selectors in :not are not supported');
}
_addResult(results, cssSelector);
cssSelector = current = new CssSelector();
}
}
_addResult(results, cssSelector);
return results;
}
isElementSelector() {
return this.hasElementSelector() && this.classNames.length == 0 && this.attrs.length == 0 &&
this.notSelectors.length === 0;
}
hasElementSelector() {
return !!this.element;
}
setElement(element = null) {
this.element = element;
}
/** Gets a template string for an element that matches the selector. */
getMatchingElementTemplate() {
const tagName = this.element || 'div';
const classAttr = this.classNames.length > 0 ? ` class="${this.classNames.join(' ')}"` : '';
let attrs = '';
for (let i = 0; i < this.attrs.length; i += 2) {
const attrName = this.attrs[i];
const attrValue = this.attrs[i + 1] !== '' ? `="${this.attrs[i + 1]}"` : '';
attrs += ` ${attrName}${attrValue}`;
}
return getHtmlTagDefinition(tagName).isVoid ? `<${tagName}${classAttr}${attrs}/>` :
`<${tagName}${classAttr}${attrs}></${tagName}>`;
}
getAttrs() {
const result = [];
if (this.classNames.length > 0) {
result.push('class', this.classNames.join(' '));
}
return result.concat(this.attrs);
}
addAttribute(name, value = '') {
this.attrs.push(name, value && value.toLowerCase() || '');
}
addClassName(name) {
this.classNames.push(name.toLowerCase());
}
toString() {
let res = this.element || '';
if (this.classNames) {
this.classNames.forEach(klass => res += `.${klass}`);
}
if (this.attrs) {
for (let i = 0; i < this.attrs.length; i += 2) {
const name = this.attrs[i];
const value = this.attrs[i + 1];
res += `[${name}${value ? '=' + value : ''}]`;
}
}
this.notSelectors.forEach(notSelector => res += `:not(${notSelector})`);
return res;
}
}
/**
* Reads a list of CssSelectors and allows to calculate which ones
* are contained in a given CssSelector.
*/
class SelectorMatcher {
constructor() {
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 = [];
}
static createNotMatcher(notSelectors) {
const notMatcher = new SelectorMatcher();
notMatcher.addSelectables(notSelectors, null);
return notMatcher;
}
addSelectables(cssSelectors, callbackCtxt) {
let listContext = null;
if (cssSelectors.length > 1) {
listContext = new SelectorListContext(cssSelectors);
this._listContexts.push(listContext);
}
for (let 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
*/
_addSelectable(cssSelector, callbackCtxt, listContext) {
let matcher = this;
const element = cssSelector.element;
const classNames = cssSelector.classNames;
const attrs = cssSelector.attrs;
const selectable = new SelectorContext(cssSelector, callbackCtxt, listContext);
if (element) {
const 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 (let i = 0; i < classNames.length; i++) {
const isTerminal = attrs.length === 0 && i === classNames.length - 1;
const className = classNames[i];
if (isTerminal) {
this._addTerminal(matcher._classMap, className, selectable);
}
else {
matcher = this._addPartial(matcher._classPartialMap, className);
}
}
}
if (attrs) {
for (let i = 0; i < attrs.length; i += 2) {
const isTerminal = i === attrs.length - 2;
const name = attrs[i];
const value = attrs[i + 1];
if (isTerminal) {
const terminalMap = matcher._attrValueMap;
let terminalValuesMap = terminalMap.get(name);
if (!terminalValuesMap) {
terminalValuesMap = new Map();
terminalMap.set(name, terminalValuesMap);
}
this._addTerminal(terminalValuesMap, value, selectable);
}
else {
const partialMap = matcher._attrValuePartialMap;
let partialValuesMap = partialMap.get(name);
if (!partialValuesMap) {
partialValuesMap = new Map();
partialMap.set(name, partialValuesMap);
}
matcher = this._addPartial(partialValuesMap, value);
}
}
}
}
_addTerminal(map, name, selectable) {
let terminalList = map.get(name);
if (!terminalList) {
terminalList = [];
map.set(name, terminalList);
}
terminalList.push(selectable);
}
_addPartial(map, name) {
let 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
*/
match(cssSelector, matchedCallback) {
let result = false;
const element = cssSelector.element;
const classNames = cssSelector.classNames;
const attrs = cssSelector.attrs;
for (let 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 (let i = 0; i < classNames.length; i++) {
const className = classNames[i];
result =
this._matchTerminal(this._classMap, className, cssSelector, matchedCallback) || result;
result =
this._matchPartial(this._classPartialMap, className, cssSelector, matchedCallback) ||
result;
}
}
if (attrs) {
for (let i = 0; i < attrs.length; i += 2) {
const name = attrs[i];
const value = attrs[i + 1];
const terminalValuesMap = this._attrValueMap.get(name);
if (value) {
result =
this._matchTerminal(terminalValuesMap, '', cssSelector, matchedCallback) || result;
}
result =
this._matchTerminal(terminalValuesMap, value, cssSelector, matchedCallback) || result;
const partialValuesMap = this._attrValuePartialMap.get(name);
if (value) {
result = this._matchPartial(partialValuesMap, '', cssSelector, matchedCallback) || result;
}
result =
this._matchPartial(partialValuesMap, value, cssSelector, matchedCallback) || result;
}
}
return result;
}
/** @internal */
_matchTerminal(map, name, cssSelector, matchedCallback) {
if (!map || typeof name !== 'string') {
return false;
}
let selectables = map.get(name) || [];
const starSelectables = map.get('*');
if (starSelectables) {
selectables = selectables.concat(starSelectables);
}
if (selectables.length === 0) {
return false;
}
let selectable;
let result = false;
for (let i = 0; i < selectables.length; i++) {
selectable = selectables[i];
result = selectable.finalize(cssSelector, matchedCallback) || result;
}
return result;
}
/** @internal */
_matchPartial(map, name, cssSelector, matchedCallback) {
if (!map || typeof name !== 'string') {
return false;
}
const 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);
}
}
class SelectorListContext {
constructor(selectors) {
this.selectors = selectors;
this.alreadyMatched = false;
}
}
// Store context to pass back selector and context when a selector is matched
class SelectorContext {
constructor(selector, cbContext, listContext) {
this.selector = selector;
this.cbContext = cbContext;
this.listContext = listContext;
this.notSelectors = selector.notSelectors;
}
finalize(cssSelector, callback) {
let result = true;
if (this.notSelectors.length > 0 && (!this.listContext || !this.listContext.alreadyMatched)) {
const 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;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const createInject = makeMetadataFactory('Inject', (token) => ({ token }));
const createInjectionToken = makeMetadataFactory('InjectionToken', (desc) => ({ _desc: desc, ɵprov: undefined }));
const createAttribute = makeMetadataFactory('Attribute', (attributeName) => ({ attributeName }));
// Stores the default value of `emitDistinctChangesOnly` when the `emitDistinctChangesOnly` is not
// explicitly set. This value will be changed to `true` in v12.
// TODO(misko): switch the default in v12 to `true`. See: packages/core/src/metadata/di.ts
const emitDistinctChangesOnlyDefaultValue = false;
const createContentChildren = makeMetadataFactory('ContentChildren', (selector, data = {}) => (Object.assign({ selector, first: false, isViewQuery: false, descendants: false, emitDistinctChangesOnly: emitDistinctChangesOnlyDefaultValue }, data)));
const createContentChild = makeMetadataFactory('ContentChild', (selector, data = {}) => (Object.assign({ selector, first: true, isViewQuery: false, descendants: true }, data)));
const createViewChildren = makeMetadataFactory('ViewChildren', (selector, data = {}) => (Object.assign({ selector, first: false, isViewQuery: true, descendants: true, emitDistinctChangesOnly: emitDistinctChangesOnlyDefaultValue }, data)));
const createViewChild = makeMetadataFactory('ViewChild', (selector, data) => (Object.assign({ selector, first: true, isViewQuery: true, descendants: true }, data)));
const createDirective = makeMetadataFactory('Directive', (dir = {}) => dir);
var ViewEncapsulation;
(function (ViewEncapsulation) {
ViewEncapsulation[ViewEncapsulation["Emulated"] = 0] = "Emulated";
// Historically the 1 value was for `Native` encapsulation which has been removed as of v11.
ViewEncapsulation[ViewEncapsulation["None"] = 2] = "None";
ViewEncapsulation[ViewEncapsulation["ShadowDom"] = 3] = "ShadowDom";
})(ViewEncapsulation || (ViewEncapsulation = {}));
var ChangeDetectionStrategy;
(function (ChangeDetectionStrategy) {
ChangeDetectionStrategy[ChangeDetectionStrategy["OnPush"] = 0] = "OnPush";
ChangeDetectionStrategy[ChangeDetectionStrategy["Default"] = 1] = "Default";
})(ChangeDetectionStrategy || (ChangeDetectionStrategy = {}));
const createComponent = makeMetadataFactory('Component', (c = {}) => (Object.assign({ changeDetection: ChangeDetectionStrategy.Default }, c)));
const createPipe = makeMetadataFactory('Pipe', (p) => (Object.assign({ pure: true }, p)));
const createInput = makeMetadataFactory('Input', (bindingPropertyName) => ({ bindingPropertyName }));
const createOutput = makeMetadataFactory('Output', (bindingPropertyName) => ({ bindingPropertyName }));
const createHostBinding = makeMetadataFactory('HostBinding', (hostPropertyName) => ({ hostPropertyName }));
const createHostListener = makeMetadataFactory('HostListener', (eventName, args) => ({ eventName, args }));
const createNgModule = makeMetadataFactory('NgModule', (ngModule) => ngModule);
const createInjectable = makeMetadataFactory('Injectable', (injectable = {}) => injectable);
const CUSTOM_ELEMENTS_SCHEMA = {
name: 'custom-elements'
};
const NO_ERRORS_SCHEMA = {
name: 'no-errors-schema'
};
const createOptional = makeMetadataFactory('Optional');
const createSelf = makeMetadataFactory('Self');
const createSkipSelf = makeMetadataFactory('SkipSelf');
const createHost = makeMetadataFactory('Host');
const Type = Function;
var SecurityContext;
(function (SecurityContext) {
SecurityContext[SecurityContext["NONE"] = 0] = "NONE";
SecurityContext[SecurityContext["HTML"] = 1] = "HTML";
SecurityContext[SecurityContext["STYLE"] = 2] = "STYLE";
SecurityContext[SecurityContext["SCRIPT"] = 3] = "SCRIPT";
SecurityContext[SecurityContext["URL"] = 4] = "URL";
SecurityContext[SecurityContext["RESOURCE_URL"] = 5] = "RESOURCE_URL";
})(SecurityContext || (SecurityContext = {}));
var MissingTranslationStrategy;
(function (MissingTranslationStrategy) {
MissingTranslationStrategy[MissingTranslationStrategy["Error"] = 0] = "Error";
MissingTranslationStrategy[MissingTranslationStrategy["Warning"] = 1] = "Warning";
MissingTranslationStrategy[MissingTranslationStrategy["Ignore"] = 2] = "Ignore";
})(MissingTranslationStrategy || (MissingTranslationStrategy = {}));
function makeMetadataFactory(name, props) {
// This must be declared as a function, not a fat arrow, so that ES2015 devmode produces code
// that works with the static_reflector.ts in the ViewEngine compiler.
// In particular, `_registerDecoratorOrConstructor` assumes that the value returned here can be
// new'ed.
function factory(...args) {
const values = props ? props(...args) : {};
return Object.assign({ ngMetadataName: name }, values);
}
factory.isTypeOf = (obj) => obj && obj.ngMetadataName === name;
factory.ngMetadataName = name;
return factory;
}
function parserSelectorToSimpleSelector(selector) {
const classes = selector.classNames && selector.classNames.length ?
[8 /* CLASS */, ...selector.classNames] :
[];
const elementName = selector.element && selector.element !== '*' ? selector.element : '';
return [elementName, ...selector.attrs, ...classes];
}
function parserSelectorToNegativeSelector(selector) {
const classes = selector.classNames && selector.classNames.length ?
[8 /* CLASS */, ...selector.classNames] :
[];
if (selector.element) {
return [
1 /* NOT */ | 4 /* ELEMENT */, selector.element, ...selector.attrs, ...classes
];
}
else if (selector.attrs.length) {
return [1 /* NOT */ | 2 /* ATTRIBUTE */, ...selector.attrs, ...classes];
}
else {
return selector.classNames && selector.classNames.length ?
[1 /* NOT */ | 8 /* CLASS */, ...selector.classNames] :
[];
}
}
function parserSelectorToR3Selector(selector) {
const positive = parserSelectorToSimpleSelector(selector);
const negative = selector.notSelectors && selector.notSelectors.length ?
selector.notSelectors.map(notSelector => parserSelectorToNegativeSelector(notSelector)) :
[];
return positive.concat(...negative);
}
function parseSelectorToR3Selector(selector) {
return selector ? CssSelector.parse(selector).map(parserSelectorToR3Selector) : [];
}
var core = /*#__PURE__*/Object.freeze({
__proto__: null,
createInject: createInject,
createInjectionToken: createInjectionToken,
createAttribute: createAttribute,
emitDistinctChangesOnlyDefaultValue: emitDistinctChangesOnlyDefaultValue,
createContentChildren: createContentChildren,
createContentChild: createContentChild,
createViewChildren: createViewChildren,
createViewChild: createViewChild,
createDirective: createDirective,
get ViewEncapsulation () { return ViewEncapsulation; },
get ChangeDetectionStrategy () { return ChangeDetectionStrategy; },
createComponent: createComponent,
createPipe: createPipe,
createInput: createInput,
createOutput: createOutput,
createHostBinding: createHostBinding,
createHostListener: createHostListener,
createNgModule: createNgModule,
createInjectable: createInjectable,
CUSTOM_ELEMENTS_SCHEMA: CUSTOM_ELEMENTS_SCHEMA,
NO_ERRORS_SCHEMA: NO_ERRORS_SCHEMA,
createOptional: createOptional,
createSelf: createSelf,
createSkipSelf: createSkipSelf,
createHost: createHost,
Type: Type,
get SecurityContext () { return SecurityContext; },
get MissingTranslationStrategy () { return MissingTranslationStrategy; },
parseSelectorToR3Selector: parseSelectorToR3Selector
});
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
//// Types
var TypeModifier;
(function (TypeModifier) {
TypeModifier[TypeModifier["Const"] = 0] = "Const";
})(TypeModifier || (TypeModifier = {}));
class Type$1 {
constructor(modifiers = []) {
this.modifiers = modifiers;
}
hasModifier(modifier) {
return this.modifiers.indexOf(modifier) !== -1;
}
}
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["None"] = 7] = "None";
})(BuiltinTypeName || (BuiltinTypeName = {}));
class BuiltinType extends Type$1 {
constructor(name, modifiers) {
super(modifiers);
this.name = name;
}
visitType(visitor, context) {
return visitor.visitBuiltinType(this, context);
}
}
class ExpressionType extends Type$1 {
constructor(value, modifiers, typeParams = null) {
super(modifiers);
this.value = value;
this.typeParams = typeParams;
}
visitType(visitor, context) {
return visitor.visitExpressionType(this, context);
}
}
class ArrayType extends Type$1 {
constructor(of, modifiers) {
super(modifiers);
this.of = of;
}
visitType(visitor, context) {
return visitor.visitArrayType(this, context);
}
}
class MapType extends Type$1 {
constructor(valueType, modifiers) {
super(modifiers);
this.valueType = valueType || null;
}
visitType(visitor, context) {
return visitor.visitMapType(this, context);
}
}
const DYNAMIC_TYPE = new BuiltinType(BuiltinTypeName.Dynamic);
const INFERRED_TYPE = new BuiltinType(BuiltinTypeName.Inferred);
const BOOL_TYPE = new BuiltinType(BuiltinTypeName.Bool);
const INT_TYPE = new BuiltinType(BuiltinTypeName.Int);
const NUMBER_TYPE = new BuiltinType(BuiltinTypeName.Number);
const STRING_TYPE = new BuiltinType(BuiltinTypeName.String);
const FUNCTION_TYPE = new BuiltinType(BuiltinTypeName.Function);
const NONE_TYPE = new BuiltinType(BuiltinTypeName.None);
///// Expressions
var UnaryOperator;
(function (UnaryOperator) {
UnaryOperator[UnaryOperator["Minus"] = 0] = "Minus";
UnaryOperator[UnaryOperator["Plus"] = 1] = "Plus";
})(UnaryOperator || (UnaryOperator = {}));
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 areAllEquivalentPredicate(base, other, equivalentPredicate) {
const len = base.length;
if (len !== other.length) {
return false;
}
for (let i = 0; i < len; i++) {
if (!equivalentPredicate(base[i], other[i])) {
return false;
}
}
return true;
}
function areAllEquivalent(base, other) {
return areAllEquivalentPredicate(base, other, (baseElement, otherElement) => baseElement.isEquivalent(otherElement));
}
class Expression {
constructor(type, sourceSpan) {
this.type = type || null;
this.sourceSpan = sourceSpan || null;
}
prop(name, sourceSpan) {
return new ReadPropExpr(this, name, null, sourceSpan);
}
key(index, type, sourceSpan) {
return new ReadKeyExpr(this, index, type, sourceSpan);
}
callMethod(name, params, sourceSpan) {
return new InvokeMethodExpr(this, name, params, null, sourceSpan);
}
callFn(params, sourceSpan, pure) {
return new InvokeFunctionExpr(this, params, null, sourceSpan, pure);
}
instantiate(params, type, sourceSpan) {
return new InstantiateExpr(this, params, type, sourceSpan);
}
conditional(trueCase, falseCase = null, sourceSpan) {
return new ConditionalExpr(this, trueCase, falseCase, null, sourceSpan);
}
equals(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Equals, this, rhs, null, sourceSpan);
}
notEquals(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.NotEquals, this, rhs, null, sourceSpan);
}
identical(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Identical, this, rhs, null, sourceSpan);
}
notIdentical(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.NotIdentical, this, rhs, null, sourceSpan);
}
minus(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Minus, this, rhs, null, sourceSpan);
}
plus(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Plus, this, rhs, null, sourceSpan);
}
divide(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Divide, this, rhs, null, sourceSpan);
}
multiply(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Multiply, this, rhs, null, sourceSpan);
}
modulo(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Modulo, this, rhs, null, sourceSpan);
}
and(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.And, this, rhs, null, sourceSpan);
}
bitwiseAnd(rhs, sourceSpan, parens = true) {
return new BinaryOperatorExpr(BinaryOperator.BitwiseAnd, this, rhs, null, sourceSpan, parens);
}
or(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Or, this, rhs, null, sourceSpan);
}
lower(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Lower, this, rhs, null, sourceSpan);
}
lowerEquals(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.LowerEquals, this, rhs, null, sourceSpan);
}
bigger(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.Bigger, this, rhs, null, sourceSpan);
}
biggerEquals(rhs, sourceSpan) {
return new BinaryOperatorExpr(BinaryOperator.BiggerEquals, this, rhs, null, sourceSpan);
}
isBlank(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);
}
cast(type, sourceSpan) {
return new CastExpr(this, type, sourceSpan);
}
toStmt() {
return new ExpressionStatement(this, null);
}
}
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 = {}));
class ReadVarExpr extends Expression {
constructor(name, type, sourceSpan) {
super(type, sourceSpan);
if (typeof name === 'string') {
this.name = name;
this.builtin = null;
}
else {
this.name = null;
this.builtin = name;
}
}
isEquivalent(e) {
return e instanceof ReadVarExpr && this.name === e.name && this.builtin === e.builtin;
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitReadVarExpr(this, context);
}
set(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);
}
}
class TypeofExpr extends Expression {
constructor(expr, type, sourceSpan) {
super(type, sourceSpan);
this.expr = expr;
}
visitExpression(visitor, context) {
return visitor.visitTypeofExpr(this, context);
}
isEquivalent(e) {
return e instanceof TypeofExpr && e.expr.isEquivalent(this.expr);
}
isConstant() {
return this.expr.isConstant();
}
}
class WrappedNodeExpr extends Expression {
constructor(node, type, sourceSpan) {
super(type, sourceSpan);
this.node = node;
}
isEquivalent(e) {
return e instanceof WrappedNodeExpr && this.node === e.node;
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitWrappedNodeExpr(this, context);
}
}
class WriteVarExpr extends Expression {
constructor(name, value, type, sourceSpan) {
super(type || value.type, sourceSpan);
this.name = name;
this.value = value;
}
isEquivalent(e) {
return e instanceof WriteVarExpr && this.name === e.name && this.value.isEquivalent(e.value);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitWriteVarExpr(this, context);
}
toDeclStmt(type, modifiers) {
return new DeclareVarStmt(this.name, this.value, type, modifiers, this.sourceSpan);
}
toConstDecl() {
return this.toDeclStmt(INFERRED_TYPE, [StmtModifier.Final]);
}
}
class WriteKeyExpr extends Expression {
constructor(receiver, index, value, type, sourceSpan) {
super(type || value.type, sourceSpan);
this.receiver = receiver;
this.index = index;
this.value = value;
}
isEquivalent(e) {
return e instanceof WriteKeyExpr && this.receiver.isEquivalent(e.receiver) &&
this.index.isEquivalent(e.index) && this.value.isEquivalent(e.value);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitWriteKeyExpr(this, context);
}
}
class WritePropExpr extends Expression {
constructor(receiver, name, value, type, sourceSpan) {
super(type || value.type, sourceSpan);
this.receiver = receiver;
this.name = name;
this.value = value;
}
isEquivalent(e) {
return e instanceof WritePropExpr && this.receiver.isEquivalent(e.receiver) &&
this.name === e.name && this.value.isEquivalent(e.value);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitWritePropExpr(this, context);
}
}
var BuiltinMethod;
(function (BuiltinMethod) {
BuiltinMethod[BuiltinMethod["ConcatArray"] = 0] = "ConcatArray";
BuiltinMethod[BuiltinMethod["SubscribeObservable"] = 1] = "SubscribeObservable";
BuiltinMethod[BuiltinMethod["Bind"] = 2] = "Bind";
})(BuiltinMethod || (BuiltinMethod = {}));
class InvokeMethodExpr extends Expression {
constructor(receiver, method, args, type, sourceSpan) {
super(type, sourceSpan);
this.receiver = receiver;
this.args = args;
if (typeof method === 'string') {
this.name = method;
this.builtin = null;
}
else {
this.name = null;
this.builtin = method;
}
}
isEquivalent(e) {
return e instanceof InvokeMethodExpr && this.receiver.isEquivalent(e.receiver) &&
this.name === e.name && this.builtin === e.builtin && areAllEquivalent(this.args, e.args);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitInvokeMethodExpr(this, context);
}
}
class InvokeFunctionExpr extends Expression {
constructor(fn, args, type, sourceSpan, pure = false) {
super(type, sourceSpan);
this.fn = fn;
this.args = args;
this.pure = pure;
}
isEquivalent(e) {
return e instanceof InvokeFunctionExpr && this.fn.isEquivalent(e.fn) &&
areAllEquivalent(this.args, e.args) && this.pure === e.pure;
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitInvokeFunctionExpr(this, context);
}
}
class TaggedTemplateExpr extends Expression {
constructor(tag, template, type, sourceSpan) {
super(type, sourceSpan);
this.tag = tag;
this.template = template;
}
isEquivalent(e) {
return e instanceof TaggedTemplateExpr && this.tag.isEquivalent(e.tag) &&
areAllEquivalentPredicate(this.template.elements, e.template.elements, (a, b) => a.text === b.text) &&
areAllEquivalent(this.template.expressions, e.template.expressions);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitTaggedTemplateExpr(this, context);
}
}
class InstantiateExpr extends Expression {
constructor(classExpr, args, type, sourceSpan) {
super(type, sourceSpan);
this.classExpr = classExpr;
this.args = args;
}
isEquivalent(e) {
return e instanceof InstantiateExpr && this.classExpr.isEquivalent(e.classExpr) &&
areAllEquivalent(this.args, e.args);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitInstantiateExpr(this, context);
}
}
class LiteralExpr extends Expression {
constructor(value, type, sourceSpan) {
super(type, sourceSpan);
this.value = value;
}
isEquivalent(e) {
return e instanceof LiteralExpr && this.value === e.value;
}
isConstant() {
return true;
}
visitExpression(visitor, context) {
return visitor.visitLiteralExpr(this, context);
}
}
class TemplateLiteral {
constructor(elements, expressions) {
this.elements = elements;
this.expressions = expressions;
}
}
class TemplateLiteralElement {
constructor(text, sourceSpan, rawText) {
var _a;
this.text = text;
this.sourceSpan = sourceSpan;
// If `rawText` is not provided, try to extract the raw string from its
// associated `sourceSpan`. If that is also not available, "fake" the raw
// string instead by escaping the following control sequences:
// - "\" would otherwise indicate that the next character is a control character.
// - "`" and "${" are template string control sequences that would otherwise prematurely
// indicate the end of the template literal element.
this.rawText = (_a = rawText !== null && rawText !== void 0 ? rawText : sourceSpan === null || sourceSpan === void 0 ? void 0 : sourceSpan.toString()) !== null && _a !== void 0 ? _a : escapeForTemplateLiteral(escapeSlashes(text));
}
}
class MessagePiece {
constructor(text, sourceSpan) {
this.text = text;
this.sourceSpan = sourceSpan;
}
}
class LiteralPiece extends MessagePiece {
}
class PlaceholderPiece extends MessagePiece {
}
class LocalizedString extends Expression {
constructor(metaBlock, messageParts, placeHolderNames, expressions, sourceSpan) {
super(STRING_TYPE, sourceSpan);
this.metaBlock = metaBlock;
this.messageParts = messageParts;
this.placeHolderNames = placeHolderNames;
this.expressions = expressions;
}
isEquivalent(e) {
// return e instanceof LocalizedString && this.message === e.message;
return false;
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitLocalizedString(this, context);
}
/**
* Serialize the given `meta` and `messagePart` into "cooked" and "raw" strings that can be used
* in a `$localize` tagged string. The format of the metadata is the same as that parsed by
* `parseI18nMeta()`.
*
* @param meta The metadata to serialize
* @param messagePart The first part of the tagged string
*/
serializeI18nHead() {
const MEANING_SEPARATOR = '|';
const ID_SEPARATOR = '@@';
const LEGACY_ID_INDICATOR = '␟';
let metaBlock = this.metaBlock.description || '';
if (this.metaBlock.meaning) {
metaBlock = `${this.metaBlock.meaning}${MEANING_SEPARATOR}${metaBlock}`;
}
if (this.metaBlock.customId) {
metaBlock = `${metaBlock}${ID_SEPARATOR}${this.metaBlock.customId}`;
}
if (this.metaBlock.legacyIds) {
this.metaBlock.legacyIds.forEach(legacyId => {
metaBlock = `${metaBlock}${LEGACY_ID_INDICATOR}${legacyId}`;
});
}
return createCookedRawString(metaBlock, this.messageParts[0].text, this.getMessagePartSourceSpan(0));
}
getMessagePartSourceSpan(i) {
var _a, _b;
return (_b = (_a = this.messageParts[i]) === null || _a === void 0 ? void 0 : _a.sourceSpan) !== null && _b !== void 0 ? _b : this.sourceSpan;
}
getPlaceholderSourceSpan(i) {
var _a, _b, _c, _d;
return (_d = (_b = (_a = this.placeHolderNames[i]) === null || _a === void 0 ? void 0 : _a.sourceSpan) !== null && _b !== void 0 ? _b : (_c = this.expressions[i]) === null || _c === void 0 ? void 0 : _c.sourceSpan) !== null && _d !== void 0 ? _d : this.sourceSpan;
}
/**
* Serialize the given `placeholderName` and `messagePart` into "cooked" and "raw" strings that
* can be used in a `$localize` tagged string.
*
* @param placeholderName The placeholder name to serialize
* @param messagePart The following message string after this placeholder
*/
serializeI18nTemplatePart(partIndex) {
const placeholderName = this.placeHolderNames[partIndex - 1].text;
const messagePart = this.messageParts[partIndex];
return createCookedRawString(placeholderName, messagePart.text, this.getMessagePartSourceSpan(partIndex));
}
}
const escapeSlashes = (str) => str.replace(/\\/g, '\\\\');
const escapeStartingColon = (str) => str.replace(/^:/, '\\:');
const escapeColons = (str) => str.replace(/:/g, '\\:');
const escapeForTemplateLiteral = (str) => str.replace(/`/g, '\\`').replace(/\${/g, '$\\{');
/**
* Creates a `{cooked, raw}` object from the `metaBlock` and `messagePart`.
*
* The `raw` text must have various character sequences escaped:
* * "\" would otherwise indicate that the next character is a control character.
* * "`" and "${" are template string control sequences that would otherwise prematurely indicate
* the end of a message part.
* * ":" inside a metablock would prematurely indicate the end of the metablock.
* * ":" at the start of a messagePart with no metablock would erroneously indicate the start of a
* metablock.
*
* @param metaBlock Any metadata that should be prepended to the string
* @param messagePart The message part of the string
*/
function createCookedRawString(metaBlock, messagePart, range) {
if (metaBlock === '') {
return {
cooked: messagePart,
raw: escapeForTemplateLiteral(escapeStartingColon(escapeSlashes(messagePart))),
range,
};
}
else {
return {
cooked: `:${metaBlock}:${messagePart}`,
raw: escapeForTemplateLiteral(`:${escapeColons(escapeSlashes(metaBlock))}:${escapeSlashes(messagePart)}`),
range,
};
}
}
class ExternalExpr extends Expression {
constructor(value, type, typeParams = null, sourceSpan) {
super(type, sourceSpan);
this.value = value;
this.typeParams = typeParams;
}
isEquivalent(e) {
return e instanceof ExternalExpr && this.value.name === e.value.name &&
this.value.moduleName === e.value.moduleName && this.value.runtime === e.value.runtime;
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitExternalExpr(this, context);
}
}
class ExternalReference {
constructor(moduleName, name, runtime) {
this.moduleName = moduleName;
this.name = name;
this.runtime = runtime;
}
}
class ConditionalExpr extends Expression {
constructor(condition, trueCase, falseCase = null, type, sourceSpan) {
super(type || trueCase.type, sourceSpan);
this.condition = condition;
this.falseCase = falseCase;
this.trueCase = trueCase;
}
isEquivalent(e) {
return e instanceof ConditionalExpr && this.condition.isEquivalent(e.condition) &&
this.trueCase.isEquivalent(e.trueCase) && nullSafeIsEquivalent(this.falseCase, e.falseCase);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitConditionalExpr(this, context);
}
}
class NotExpr extends Expression {
constructor(condition, sourceSpan) {
super(BOOL_TYPE, sourceSpan);
this.condition = condition;
}
isEquivalent(e) {
return e instanceof NotExpr && this.condition.isEquivalent(e.condition);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitNotExpr(this, context);
}
}
class AssertNotNull extends Expression {
constructor(condition, sourceSpan) {
super(condition.type, sourceSpan);
this.condition = condition;
}
isEquivalent(e) {
return e instanceof AssertNotNull && this.condition.isEquivalent(e.condition);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitAssertNotNullExpr(this, context);
}
}
class CastExpr extends Expression {
constructor(value, type, sourceSpan) {
super(type, sourceSpan);
this.value = value;
}
isEquivalent(e) {
return e instanceof CastExpr && this.value.isEquivalent(e.value);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitCastExpr(this, context);
}
}
class FnParam {
constructor(name, type = null) {
this.name = name;
this.type = type;
}
isEquivalent(param) {
return this.name === param.name;
}
}
class FunctionExpr extends Expression {
constructor(params, statements, type, sourceSpan, name) {
super(type, sourceSpan);
this.params = params;
this.statements = statements;
this.name = name;
}
isEquivalent(e) {
return e instanceof FunctionExpr && areAllEquivalent(this.params, e.params) &&
areAllEquivalent(this.statements, e.statements);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitFunctionExpr(this, context);
}
toDeclStmt(name, modifiers) {
return new DeclareFunctionStmt(name, this.params, this.statements, this.type, modifiers, this.sourceSpan);
}
}
class UnaryOperatorExpr extends Expression {
constructor(operator, expr, type, sourceSpan, parens = true) {
super(type || NUMBER_TYPE, sourceSpan);
this.operator = operator;
this.expr = expr;
this.parens = parens;
}
isEquivalent(e) {
return e instanceof UnaryOperatorExpr && this.operator === e.operator &&
this.expr.isEquivalent(e.expr);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitUnaryOperatorExpr(this, context);
}
}
class BinaryOperatorExpr extends Expression {
constructor(operator, lhs, rhs, type, sourceSpan, parens = true) {
super(type || lhs.type, sourceSpan);
this.operator = operator;
this.rhs = rhs;
this.parens = parens;
this.lhs = lhs;
}
isEquivalent(e) {
return e instanceof BinaryOperatorExpr && this.operator === e.operator &&
this.lhs.isEquivalent(e.lhs) && this.rhs.isEquivalent(e.rhs);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitBinaryOperatorExpr(this, context);
}
}
class ReadPropExpr extends Expression {
constructor(receiver, name, type, sourceSpan) {
super(type, sourceSpan);
this.receiver = receiver;
this.name = name;
}
isEquivalent(e) {
return e instanceof ReadPropExpr && this.receiver.isEquivalent(e.receiver) &&
this.name === e.name;
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitReadPropExpr(this, context);
}
set(value) {
return new WritePropExpr(this.receiver, this.name, value, null, this.sourceSpan);
}
}
class ReadKeyExpr extends Expression {
constructor(receiver, index, type, sourceSpan) {
super(type, sourceSpan);
this.receiver = receiver;
this.index = index;
}
isEquivalent(e) {
return e instanceof ReadKeyExpr && this.receiver.isEquivalent(e.receiver) &&
this.index.isEquivalent(e.index);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitReadKeyExpr(this, context);
}
set(value) {
return new WriteKeyExpr(this.receiver, this.index, value, null, this.sourceSpan);
}
}
class LiteralArrayExpr extends Expression {
constructor(entries, type, sourceSpan) {
super(type, sourceSpan);
this.entries = entries;
}
isConstant() {
return this.entries.every(e => e.isConstant());
}
isEquivalent(e) {
return e instanceof LiteralArrayExpr && areAllEquivalent(this.entries, e.entries);
}
visitExpression(visitor, context) {
return visitor.visitLiteralArrayExpr(this, context);
}
}
class LiteralMapEntry {
constructor(key, value, quoted) {
this.key = key;
this.value = value;
this.quoted = quoted;
}
isEquivalent(e) {
return this.key === e.key && this.value.isEquivalent(e.value);
}
}
class LiteralMapExpr extends Expression {
constructor(entries, type, sourceSpan) {
super(type, sourceSpan);
this.entries = entries;
this.valueType = null;
if (type) {
this.valueType = type.valueType;
}
}
isEquivalent(e) {
return e instanceof LiteralMapExpr && areAllEquivalent(this.entries, e.entries);
}
isConstant() {
return this.entries.every(e => e.value.isConstant());
}
visitExpression(visitor, context) {
return visitor.visitLiteralMapExpr(this, context);
}
}
class CommaExpr extends Expression {
constructor(parts, sourceSpan) {
super(parts[parts.length - 1].type, sourceSpan);
this.parts = parts;
}
isEquivalent(e) {
return e instanceof CommaExpr && areAllEquivalent(this.parts, e.parts);
}
isConstant() {
return false;
}
visitExpression(visitor, context) {
return visitor.visitCommaExpr(this, context);
}
}
const THIS_EXPR = new ReadVarExpr(BuiltinVar.This, null, null);
const SUPER_EXPR = new ReadVarExpr(BuiltinVar.Super, null, null);
const CATCH_ERROR_VAR = new ReadVarExpr(BuiltinVar.CatchError, null, null);
const CATCH_STACK_VAR = new ReadVarExpr(BuiltinVar.CatchStack, null, null);
const NULL_EXPR = new LiteralExpr(null, null, null);
const 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 = {}));
class LeadingComment {
constructor(text, multiline, trailingNewline) {
this.text = text;
this.multiline = multiline;
this.trailingNewline = trailingNewline;
}
toString() {
return this.multiline ? ` ${this.text} ` : this.text;
}
}
class JSDocComment extends LeadingComment {
constructor(tags) {
super('', /* multiline */ true, /* trailingNewline */ true);
this.tags = tags;
}
toString() {
return serializeTags(this.tags);
}
}
class Statement {
constructor(modifiers = [], sourceSpan = null, leadingComments) {
this.modifiers = modifiers;
this.sourceSpan = sourceSpan;
this.leadingComments = leadingComments;
}
hasModifier(modifier) {
return this.modifiers.indexOf(modifier) !== -1;
}
addLeadingComment(leadingComment) {
var _a;
this.leadingComments = (_a = this.leadingComments) !== null && _a !== void 0 ? _a : [];
this.leadingComments.push(leadingComment);
}
}
class DeclareVarStmt extends Statement {
constructor(name, value, type, modifiers, sourceSpan, leadingComments) {
super(modifiers, sourceSpan, leadingComments);
this.name = name;
this.value = value;
this.type = type || (value && value.type) || null;
}
isEquivalent(stmt) {
return stmt instanceof DeclareVarStmt && this.name === stmt.name &&
(this.value ? !!stmt.value && this.value.isEquivalent(stmt.value) : !stmt.value);
}
visitStatement(visitor, context) {
return visitor.visitDeclareVarStmt(this, context);
}
}
class DeclareFunctionStmt extends Statement {
constructor(name, params, statements, type, modifiers, sourceSpan, leadingComments) {
super(modifiers, sourceSpan, leadingComments);
this.name = name;
this.params = params;
this.statements = statements;
this.type = type || null;
}
isEquivalent(stmt) {
return stmt instanceof DeclareFunctionStmt && areAllEquivalent(this.params, stmt.params) &&
areAllEquivalent(this.statements, stmt.statements);
}
visitStatement(visitor, context) {
return visitor.visitDeclareFunctionStmt(this, context);
}
}
class ExpressionStatement extends Statement {
constructor(expr, sourceSpan, leadingComments) {
super([], sourceSpan, leadingComments);
this.expr = expr;
}
isEquivalent(stmt) {
return stmt instanceof ExpressionStatement && this.expr.isEquivalent(stmt.expr);
}
visitStatement(visitor, context) {
return visitor.visitExpressionStmt(this, context);
}
}
class ReturnStatement extends Statement {
constructor(value, sourceSpan = null, leadingComments) {
super([], sourceSpan, leadingComments);
this.value = value;
}
isEquivalent(stmt) {
return stmt instanceof ReturnStatement && this.value.isEquivalent(stmt.value);
}
visitStatement(visitor, context) {
return visitor.visitReturnStmt(this, context);
}
}
class AbstractClassPart {
constructor(type = null, modifiers = []) {
this.type = type;
this.modifiers = modifiers;
}
hasModifier(modifier) {
return this.modifiers.indexOf(modifier) !== -1;
}
}
class ClassField extends AbstractClassPart {
constructor(name, type, modifiers, initializer) {
super(type, modifiers);
this.name = name;
this.initializer = initializer;
}
isEquivalent(f) {
return this.name === f.name;
}
}
class ClassMethod extends AbstractClassPart {
constructor(name, params, body, type, modifiers) {
super(type, modifiers);
this.name = name;
this.params = params;
this.body = body;
}
isEquivalent(m) {
return this.name === m.name && areAllEquivalent(this.body, m.body);
}
}
class ClassGetter extends AbstractClassPart {
constructor(name, body, type, modifiers) {
super(type, modifiers);
this.name = name;
this.body = body;
}
isEquivalent(m) {
return this.name === m.name && areAllEquivalent(this.body, m.body);
}
}
class ClassStmt extends Statement {
constructor(name, parent, fields, getters, constructorMethod, methods, modifiers, sourceSpan, leadingComments) {
super(modifiers, sourceSpan, leadingComments);
this.name = name;
this.parent = parent;
this.fields = fields;
this.getters = getters;
this.constructorMethod = constructorMethod;
this.methods = methods;
}
isEquivalent(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);
}
visitStatement(visitor, context) {
return visitor.visitDeclareClassStmt(this, context);
}
}
class IfStmt extends Statement {
constructor(condition, trueCase, falseCase = [], sourceSpan, leadingComments) {
super([], sourceSpan, leadingComments);
this.condition = condition;
this.trueCase = trueCase;
this.falseCase = falseCase;
}
isEquivalent(stmt) {
return stmt instanceof IfStmt && this.condition.isEquivalent(stmt.condition) &&
areAllEquivalent(this.trueCase, stmt.trueCase) &&
areAllEquivalent(this.falseCase, stmt.falseCase);
}
visitStatement(visitor, context) {
return visitor.visitIfStmt(this, context);
}
}
class TryCatchStmt extends Statement {
constructor(bodyStmts, catchStmts, sourceSpan = null, leadingComments) {
super([], sourceSpan, leadingComments);
this.bodyStmts = bodyStmts;
this.catchStmts = catchStmts;
}
isEquivalent(stmt) {
return stmt instanceof TryCatchStmt && areAllEquivalent(this.bodyStmts, stmt.bodyStmts) &&
areAllEquivalent(this.catchStmts, stmt.catchStmts);
}
visitStatement(visitor, context) {
return visitor.visitTryCatchStmt(this, context);
}
}
class ThrowStmt extends Statement {
constructor(error, sourceSpan = null, leadingComments) {
super([], sourceSpan, leadingComments);
this.error = error;
}
isEquivalent(stmt) {
return stmt instanceof TryCatchStmt && this.error.isEquivalent(stmt.error);
}
visitStatement(visitor, context) {
return visitor.visitThrowStmt(this, context);
}
}
class AstTransformer {
transformExpr(expr, context) {
return expr;
}
transformStmt(stmt, context) {
return stmt;
}
visitReadVarExpr(ast, context) {
return this.transformExpr(ast, context);
}
visitWrappedNodeExpr(ast, context) {
return this.transformExpr(ast, context);
}
visitTypeofExpr(expr, context) {
return this.transformExpr(new TypeofExpr(expr.expr.visitExpression(this, context), expr.type, expr.sourceSpan), context);
}
visitWriteVarExpr(expr, context) {
return this.transformExpr(new WriteVarExpr(expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
}
visitWriteKeyExpr(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);
}
visitWritePropExpr(expr, context) {
return this.transformExpr(new WritePropExpr(expr.receiver.visitExpression(this, context), expr.name, expr.value.visitExpression(this, context), expr.type, expr.sourceSpan), context);
}
visitInvokeMethodExpr(ast, context) {
const 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);
}
visitInvokeFunctionExpr(ast, context) {
return this.transformExpr(new InvokeFunctionExpr(ast.fn.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
}
visitTaggedTemplateExpr(ast, context) {
return this.transformExpr(new TaggedTemplateExpr(ast.tag.visitExpression(this, context), new TemplateLiteral(ast.template.elements, ast.template.expressions.map((e) => e.visitExpression(this, context))), ast.type, ast.sourceSpan), context);
}
visitInstantiateExpr(ast, context) {
return this.transformExpr(new InstantiateExpr(ast.classExpr.visitExpression(this, context), this.visitAllExpressions(ast.args, context), ast.type, ast.sourceSpan), context);
}
visitLiteralExpr(ast, context) {
return this.transformExpr(ast, context);
}
visitLocalizedString(ast, context) {
return this.transformExpr(new LocalizedString(ast.metaBlock, ast.messageParts, ast.placeHolderNames, this.visitAllExpressions(ast.expressions, context), ast.sourceSpan), context);
}
visitExternalExpr(ast, context) {
return this.transformExpr(ast, context);
}
visitConditionalExpr(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);
}
visitNotExpr(ast, context) {
return this.transformExpr(new NotExpr(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
}
visitAssertNotNullExpr(ast, context) {
return this.transformExpr(new AssertNotNull(ast.condition.visitExpression(this, context), ast.sourceSpan), context);
}
visitCastExpr(ast, context) {
return this.transformExpr(new CastExpr(ast.value.visitExpression(this, context), ast.type, ast.sourceSpan), context);
}
visitFunctionExpr(ast, context) {
return this.transformExpr(new FunctionExpr(ast.params, this.visitAllStatements(ast.statements, context), ast.type, ast.sourceSpan), context);
}
visitUnaryOperatorExpr(ast, context) {
return this.transformExpr(new UnaryOperatorExpr(ast.operator, ast.expr.visitExpression(this, context), ast.type, ast.sourceSpan), context);
}
visitBinaryOperatorExpr(ast, context) {
return this.transformExpr(new BinaryOperatorExpr(ast.operator, ast.lhs.visitExpression(this, context), ast.rhs.visitExpression(this, context), ast.type, ast.sourceSpan), context);
}
visitReadPropExpr(ast, context) {
return this.transformExpr(new ReadPropExpr(ast.receiver.visitExpression(this, context), ast.name, ast.type, ast.sourceSpan), context);
}
visitReadKeyExpr(ast, context) {
return this.transformExpr(new ReadKeyExpr(ast.receiver.visitExpression(this, context), ast.index.visitExpression(this, context), ast.type, ast.sourceSpan), context);
}
visitLiteralArrayExpr(ast, context) {
return this.transformExpr(new LiteralArrayExpr(this.visitAllExpressions(ast.entries, context), ast.type, ast.sourceSpan), context);
}
visitLiteralMapExpr(ast, context) {
const entries = ast.entries.map((entry) => new LiteralMapEntry(entry.key, entry.value.visitExpression(this, context), entry.quoted));
const mapType = new MapType(ast.valueType);
return this.transformExpr(new LiteralMapExpr(entries, mapType, ast.sourceSpan), context);
}
visitCommaExpr(ast, context) {
return this.transformExpr(new CommaExpr(this.visitAllExpressions(ast.parts, context), ast.sourceSpan), context);
}
visitAllExpressions(exprs, context) {
return exprs.map(expr => expr.visitExpression(this, context));
}
visitDeclareVarStmt(stmt, context) {
const value = stmt.value && stmt.value.visitExpression(this, context);
return this.transformStmt(new DeclareVarStmt(stmt.name, value, stmt.type, stmt.modifiers, stmt.sourceSpan, stmt.leadingComments), context);
}
visitDeclareFunctionStmt(stmt, context) {
return this.transformStmt(new DeclareFunctionStmt(stmt.name, stmt.params, this.visitAllStatements(stmt.statements, context), stmt.type, stmt.modifiers, stmt.sourceSpan, stmt.leadingComments), context);
}
visitExpressionStmt(stmt, context) {
return this.transformStmt(new ExpressionStatement(stmt.expr.visitExpression(this, context), stmt.sourceSpan, stmt.leadingComments), context);
}
visitReturnStmt(stmt, context) {
return this.transformStmt(new ReturnStatement(stmt.value.visitExpression(this, context), stmt.sourceSpan, stmt.leadingComments), context);
}
visitDeclareClassStmt(stmt, context) {
const parent = stmt.parent.visitExpression(this, context);
const getters = stmt.getters.map(getter => new ClassGetter(getter.name, this.visitAllStatements(getter.body, context), getter.type, getter.modifiers));
const ctorMethod = stmt.constructorMethod &&
new ClassMethod(stmt.constructorMethod.name, stmt.constructorMethod.params, this.visitAllStatements(stmt.constructorMethod.body, context), stmt.constructorMethod.type, stmt.constructorMethod.modifiers);
const methods = stmt.methods.map(method => 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);
}
visitIfStmt(stmt, context) {
return this.transformStmt(new IfStmt(stmt.condition.visitExpression(this, context), this.visitAllStatements(stmt.trueCase, context), this.visitAllStatements(stmt.falseCase, context), stmt.sourceSpan, stmt.leadingComments), context);
}
visitTryCatchStmt(stmt, context) {
return this.transformStmt(new TryCatchStmt(this.visitAllStatements(stmt.bodyStmts, context), this.visitAllStatements(stmt.catchStmts, context), stmt.sourceSpan, stmt.leadingComments), context);
}
visitThrowStmt(stmt, context) {
return this.transformStmt(new ThrowStmt(stmt.error.visitExpression(this, context), stmt.sourceSpan, stmt.leadingComments), context);
}
visitAllStatements(stmts, context) {
return stmts.map(stmt => stmt.visitStatement(this, context));
}
}
class RecursiveAstVisitor {
visitType(ast, context) {
return ast;
}
visitExpression(ast, context) {
if (ast.type) {
ast.type.visitType(this, context);
}
return ast;
}
visitBuiltinType(type, context) {
return this.visitType(type, context);
}
visitExpressionType(type, context) {
type.value.visitExpression(this, context);
if (type.typeParams !== null) {
type.typeParams.forEach(param => this.visitType(param, context));
}
return this.visitType(type, context);
}
visitArrayType(type, context) {
return this.visitType(type, context);
}
visitMapType(type, context) {
return this.visitType(type, context);
}
visitWrappedNodeExpr(ast, context) {
return ast;
}
visitTypeofExpr(ast, context) {
return this.visitExpression(ast, context);
}
visitReadVarExpr(ast, context) {
return this.visitExpression(ast, context);
}
visitWriteVarExpr(ast, context) {
ast.value.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitWriteKeyExpr(ast, context) {
ast.receiver.visitExpression(this, context);
ast.index.visitExpression(this, context);
ast.value.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitWritePropExpr(ast, context) {
ast.receiver.visitExpression(this, context);
ast.value.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitInvokeMethodExpr(ast, context) {
ast.receiver.visitExpression(this, context);
this.visitAllExpressions(ast.args, context);
return this.visitExpression(ast, context);
}
visitInvokeFunctionExpr(ast, context) {
ast.fn.visitExpression(this, context);
this.visitAllExpressions(ast.args, context);
return this.visitExpression(ast, context);
}
visitTaggedTemplateExpr(ast, context) {
ast.tag.visitExpression(this, context);
this.visitAllExpressions(ast.template.expressions, context);
return this.visitExpression(ast, context);
}
visitInstantiateExpr(ast, context) {
ast.classExpr.visitExpression(this, context);
this.visitAllExpressions(ast.args, context);
return this.visitExpression(ast, context);
}
visitLiteralExpr(ast, context) {
return this.visitExpression(ast, context);
}
visitLocalizedString(ast, context) {
return this.visitExpression(ast, context);
}
visitExternalExpr(ast, context) {
if (ast.typeParams) {
ast.typeParams.forEach(type => type.visitType(this, context));
}
return this.visitExpression(ast, context);
}
visitConditionalExpr(ast, context) {
ast.condition.visitExpression(this, context);
ast.trueCase.visitExpression(this, context);
ast.falseCase.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitNotExpr(ast, context) {
ast.condition.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitAssertNotNullExpr(ast, context) {
ast.condition.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitCastExpr(ast, context) {
ast.value.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitFunctionExpr(ast, context) {
this.visitAllStatements(ast.statements, context);
return this.visitExpression(ast, context);
}
visitUnaryOperatorExpr(ast, context) {
ast.expr.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitBinaryOperatorExpr(ast, context) {
ast.lhs.visitExpression(this, context);
ast.rhs.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitReadPropExpr(ast, context) {
ast.receiver.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitReadKeyExpr(ast, context) {
ast.receiver.visitExpression(this, context);
ast.index.visitExpression(this, context);
return this.visitExpression(ast, context);
}
visitLiteralArrayExpr(ast, context) {
this.visitAllExpressions(ast.entries, context);
return this.visitExpression(ast, context);
}
visitLiteralMapExpr(ast, context) {
ast.entries.forEach((entry) => entry.value.visitExpression(this, context));
return this.visitExpression(ast, context);
}
visitCommaExpr(ast, context) {
this.visitAllExpressions(ast.parts, context);
return this.visitExpression(ast, context);
}
visitAllExpressions(exprs, context) {
exprs.forEach(expr => expr.visitExpression(this, context));
}
visitDeclareVarStmt(stmt, context) {
if (stmt.value) {
stmt.value.visitExpression(this, context);
}
if (stmt.type) {
stmt.type.visitType(this, context);
}
return stmt;
}
visitDeclareFunctionStmt(stmt, context) {
this.visitAllStatements(stmt.statements, context);
if (stmt.type) {
stmt.type.visitType(this, context);
}
return stmt;
}
visitExpressionStmt(stmt, context) {
stmt.expr.visitExpression(this, context);
return stmt;
}
visitReturnStmt(stmt, context) {
stmt.value.visitExpression(this, context);
return stmt;
}
visitDeclareClassStmt(stmt, context) {
stmt.parent.visitExpression(this, context);
stmt.getters.forEach(getter => this.visitAllStatements(getter.body, context));
if (stmt.constructorMethod) {
this.visitAllStatements(stmt.constructorMethod.body, context);
}
stmt.methods.forEach(method => this.visitAllStatements(method.body, context));
return stmt;
}
visitIfStmt(stmt, context) {
stmt.condition.visitExpression(this, context);
this.visitAllStatements(stmt.trueCase, context);
this.visitAllStatements(stmt.falseCase, context);
return stmt;
}
visitTryCatchStmt(stmt, context) {
this.visitAllStatements(stmt.bodyStmts, context);
this.visitAllStatements(stmt.catchStmts, context);
return stmt;
}
visitThrowStmt(stmt, context) {
stmt.error.visitExpression(this, context);
return stmt;
}
visitAllStatements(stmts, context) {
stmts.forEach(stmt => stmt.visitStatement(this, context));
}
}
function findReadVarNames(stmts) {
const visitor = new _ReadVarVisitor();
visitor.visitAllStatements(stmts, null);
return visitor.varNames;
}
class _ReadVarVisitor extends RecursiveAstVisitor {
constructor() {
super(...arguments);
this.varNames = new Set();
}
visitDeclareFunctionStmt(stmt, context) {
// Don't descend into nested functions
return stmt;
}
visitDeclareClassStmt(stmt, context) {
// Don't descend into nested classes
return stmt;
}
visitReadVarExpr(ast, context) {
if (ast.name) {
this.varNames.add(ast.name);
}
return null;
}
}
function collectExternalReferences(stmts) {
const visitor = new _FindExternalReferencesVisitor();
visitor.visitAllStatements(stmts, null);
return visitor.externalReferences;
}
class _FindExternalReferencesVisitor extends RecursiveAstVisitor {
constructor() {
super(...arguments);
this.externalReferences = [];
}
visitExternalExpr(e, context) {
this.externalReferences.push(e.value);
return super.visitExternalExpr(e, context);
}
}
function applySourceSpanToStatementIfNeeded(stmt, sourceSpan) {
if (!sourceSpan) {
return stmt;
}
const transformer = new _ApplySourceSpanTransformer(sourceSpan);
return stmt.visitStatement(transformer, null);
}
function applySourceSpanToExpressionIfNeeded(expr, sourceSpan) {
if (!sourceSpan) {
return expr;
}
const transformer = new _ApplySourceSpanTransformer(sourceSpan);
return expr.visitExpression(transformer, null);
}
class _ApplySourceSpanTransformer extends AstTransformer {
constructor(sourceSpan) {
super();
this.sourceSpan = sourceSpan;
}
_clone(obj) {
const clone = Object.create(obj.constructor.prototype);
for (let prop of Object.keys(obj)) {
clone[prop] = obj[prop];
}
return clone;
}
transformExpr(expr, context) {
if (!expr.sourceSpan) {
expr = this._clone(expr);
expr.sourceSpan = this.sourceSpan;
}
return expr;
}
transformStmt(stmt, context) {
if (!stmt.sourceSpan) {
stmt = this._clone(stmt);
stmt.sourceSpan = this.sourceSpan;
}
return stmt;
}
}
function leadingComment(text, multiline = false, trailingNewline = true) {
return new LeadingComment(text, multiline, trailingNewline);
}
function jsDocComment(tags = []) {
return new JSDocComment(tags);
}
function variable(name, type, sourceSpan) {
return new ReadVarExpr(name, type, sourceSpan);
}
function importExpr(id, typeParams = null, sourceSpan) {
return new ExternalExpr(id, null, typeParams, sourceSpan);
}
function importType(id, typeParams, typeModifiers) {
return id != null ? expressionType(importExpr(id, typeParams, null), typeModifiers) : null;
}
function expressionType(expr, typeModifiers, typeParams) {
return new ExpressionType(expr, typeModifiers, typeParams);
}
function typeofExpr(expr) {
return new TypeofExpr(expr);
}
function literalArr(values, type, sourceSpan) {
return new LiteralArrayExpr(values, type, sourceSpan);
}
function literalMap(values, type = null) {
return new LiteralMapExpr(values.map(e => new LiteralMapEntry(e.key, e.value, e.quoted)), type, null);
}
function unary(operator, expr, type, sourceSpan) {
return new UnaryOperatorExpr(operator, expr, type, sourceSpan);
}
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, sourceSpan, leadingComments) {
return new IfStmt(condition, thenClause, elseClause, sourceSpan, leadingComments);
}
function taggedTemplate(tag, template, type, sourceSpan) {
return new TaggedTemplateExpr(tag, template, type, sourceSpan);
}
function literal(value, type, sourceSpan) {
return new LiteralExpr(value, type, sourceSpan);
}
function localizedString(metaBlock, messageParts, placeholderNames, expressions, sourceSpan) {
return new LocalizedString(metaBlock, messageParts, placeholderNames, expressions, 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) {
let 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 '';
if (tags.length === 1 && tags[0].tagName && !tags[0].text) {
// The JSDOC comment is a single simple tag: e.g `/** @tagname */`.
return `*${tagToString(tags[0])} `;
}
let out = '*\n';
for (const tag of tags) {
out += ' *';
// If the tagToString is multi-line, insert " * " prefixes on lines.
out += tagToString(tag).replace(/\n/g, '\n * ');
out += '\n';
}
out += ' ';
return out;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const CONSTANT_PREFIX = '_c';
/**
* `ConstantPool` tries to reuse literal factories when two or more literals are identical.
* We determine whether literals are identical by creating a key out of their AST using the
* `KeyVisitor`. This constant is used to replace dynamic expressions which can't be safely
* converted into a key. E.g. given an expression `{foo: bar()}`, since we don't know what
* the result of `bar` will be, we create a key that looks like `{foo: <unknown>}`. Note
* that we use a variable, rather than something like `null` in order to avoid collisions.
*/
const UNKNOWN_VALUE_KEY = variable('<unknown>');
/**
* Context to use when producing a key.
*
* This ensures we see the constant not the reference variable when producing
* a key.
*/
const KEY_CONTEXT = {};
/**
* Generally all primitive values are excluded from the `ConstantPool`, but there is an exclusion
* for strings that reach a certain length threshold. This constant defines the length threshold for
* strings.
*/
const POOL_INCLUSION_LENGTH_THRESHOLD_FOR_STRINGS = 50;
/**
* A node that is a place-holder that allows the node to be replaced when the actual
* node is known.
*
* This allows the constant pool to change an expression from a direct reference to
* a constant to a shared constant. It returns a fix-up node that is later allowed to
* change the referenced expression.
*/
class FixupExpression extends Expression {
constructor(resolved) {
super(resolved.type);
this.resolved = resolved;
this.original = resolved;
}
visitExpression(visitor, context) {
if (context === KEY_CONTEXT) {
// When producing a key we want to traverse the constant not the
// variable used to refer to it.
return this.original.visitExpression(visitor, context);
}
else {
return this.resolved.visitExpression(visitor, context);
}
}
isEquivalent(e) {
return e instanceof FixupExpression && this.resolved.isEquivalent(e.resolved);
}
isConstant() {
return true;
}
fixup(expression) {
this.resolved = expression;
this.shared = true;
}
}
/**
* A constant pool allows a code emitter to share constant in an output context.
*
* The constant pool also supports sharing access to ivy definitions references.
*/
class ConstantPool {
constructor(isClosureCompilerEnabled = false) {
this.isClosureCompilerEnabled = isClosureCompilerEnabled;
this.statements = [];
this.literals = new Map();
this.literalFactories = new Map();
this.injectorDefinitions = new Map();
this.directiveDefinitions = new Map();
this.componentDefinitions = new Map();
this.pipeDefinitions = new Map();
this.nextNameIndex = 0;
}
getConstLiteral(literal, forceShared) {
if ((literal instanceof LiteralExpr && !isLongStringLiteral(literal)) ||
literal instanceof FixupExpression) {
// Do no put simple literals into the constant pool or try to produce a constant for a
// reference to a constant.
return literal;
}
const key = this.keyOf(literal);
let fixup = this.literals.get(key);
let newValue = false;
if (!fixup) {
fixup = new FixupExpression(literal);
this.literals.set(key, fixup);
newValue = true;
}
if ((!newValue && !fixup.shared) || (newValue && forceShared)) {
// Replace the expression with a variable
const name = this.freshName();
let definition;
let usage;
if (this.isClosureCompilerEnabled && isLongStringLiteral(literal)) {
// For string literals, Closure will **always** inline the string at
// **all** usages, duplicating it each time. For large strings, this
// unnecessarily bloats bundle size. To work around this restriction, we
// wrap the string in a function, and call that function for each usage.
// This tricks Closure into using inline logic for functions instead of
// string literals. Function calls are only inlined if the body is small
// enough to be worth it. By doing this, very large strings will be
// shared across multiple usages, rather than duplicating the string at
// each usage site.
//
// const myStr = function() { return "very very very long string"; };
// const usage1 = myStr();
// const usage2 = myStr();
definition = variable(name).set(new FunctionExpr([], // Params.
[
// Statements.
new ReturnStatement(literal),
]));
usage = variable(name).callFn([]);
}
else {
// Just declare and use the variable directly, without a function call
// indirection. This saves a few bytes and avoids an unncessary call.
definition = variable(name).set(literal);
usage = variable(name);
}
this.statements.push(definition.toDeclStmt(INFERRED_TYPE, [StmtModifier.Final]));
fixup.fixup(usage);
}
return fixup;
}
getDefinition(type, kind, ctx, forceShared = false) {
const definitions = this.definitionsOf(kind);
let fixup = definitions.get(type);
let newValue = false;
if (!fixup) {
const property = this.propertyNameOf(kind);
fixup = new FixupExpression(ctx.importExpr(type).prop(property));
definitions.set(type, fixup);
newValue = true;
}
if ((!newValue && !fixup.shared) || (newValue && forceShared)) {
const name = this.freshName();
this.statements.push(variable(name).set(fixup.resolved).toDeclStmt(INFERRED_TYPE, [StmtModifier.Final]));
fixup.fixup(variable(name));
}
return fixup;
}
getLiteralFactory(literal) {
// Create a pure function that builds an array of a mix of constant and variable expressions
if (literal instanceof LiteralArrayExpr) {
const argumentsForKey = literal.entries.map(e => e.isConstant() ? e : UNKNOWN_VALUE_KEY);
const key = this.keyOf(literalArr(argumentsForKey));
return this._getLiteralFactory(key, literal.entries, entries => literalArr(entries));
}
else {
const expressionForKey = literalMap(literal.entries.map(e => ({
key: e.key,
value: e.value.isConstant() ? e.value : UNKNOWN_VALUE_KEY,
quoted: e.quoted
})));
const key = this.keyOf(expressionForKey);
return this._getLiteralFactory(key, literal.entries.map(e => e.value), entries => literalMap(entries.map((value, index) => ({
key: literal.entries[index].key,
value,
quoted: literal.entries[index].quoted
}))));
}
}
_getLiteralFactory(key, values, resultMap) {
let literalFactory = this.literalFactories.get(key);
const literalFactoryArguments = values.filter((e => !e.isConstant()));
if (!literalFactory) {
const resultExpressions = values.map((e, index) => e.isConstant() ? this.getConstLiteral(e, true) : variable(`a${index}`));
const parameters = resultExpressions.filter(isVariable).map(e => new FnParam(e.name, DYNAMIC_TYPE));
const pureFunctionDeclaration = fn(parameters, [new ReturnStatement(resultMap(resultExpressions))], INFERRED_TYPE);
const name = this.freshName();
this.statements.push(variable(name).set(pureFunctionDeclaration).toDeclStmt(INFERRED_TYPE, [
StmtModifier.Final
]));
literalFactory = variable(name);
this.literalFactories.set(key, literalFactory);
}
return { literalFactory, literalFactoryArguments };
}
/**
* Produce a unique name.
*
* The name might be unique among different prefixes if any of the prefixes end in
* a digit so the prefix should be a constant string (not based on user input) and
* must not end in a digit.
*/
uniqueName(prefix) {
return `${prefix}${this.nextNameIndex++}`;
}
definitionsOf(kind) {
switch (kind) {
case 2 /* Component */:
return this.componentDefinitions;
case 1 /* Directive */:
return this.directiveDefinitions;
case 0 /* Injector */:
return this.injectorDefinitions;
case 3 /* Pipe */:
return this.pipeDefinitions;
}
}
propertyNameOf(kind) {
switch (kind) {
case 2 /* Component */:
return 'ɵcmp';
case 1 /* Directive */:
return 'ɵdir';
case 0 /* Injector */:
return 'ɵinj';
case 3 /* Pipe */:
return 'ɵpipe';
}
}
freshName() {
return this.uniqueName(CONSTANT_PREFIX);
}
keyOf(expression) {
return expression.visitExpression(new KeyVisitor(), KEY_CONTEXT);
}
}
/**
* Visitor used to determine if 2 expressions are equivalent and can be shared in the
* `ConstantPool`.
*
* When the id (string) generated by the visitor is equal, expressions are considered equivalent.
*/
class KeyVisitor {
constructor() {
this.visitWrappedNodeExpr = invalid;
this.visitWriteVarExpr = invalid;
this.visitWriteKeyExpr = invalid;
this.visitWritePropExpr = invalid;
this.visitInvokeMethodExpr = invalid;
this.visitInvokeFunctionExpr = invalid;
this.visitTaggedTemplateExpr = invalid;
this.visitInstantiateExpr = invalid;
this.visitConditionalExpr = invalid;
this.visitNotExpr = invalid;
this.visitAssertNotNullExpr = invalid;
this.visitCastExpr = invalid;
this.visitFunctionExpr = invalid;
this.visitUnaryOperatorExpr = invalid;
this.visitBinaryOperatorExpr = invalid;
this.visitReadPropExpr = invalid;
this.visitReadKeyExpr = invalid;
this.visitCommaExpr = invalid;
this.visitLocalizedString = invalid;
}
visitLiteralExpr(ast) {
return `${typeof ast.value === 'string' ? '"' + ast.value + '"' : ast.value}`;
}
visitLiteralArrayExpr(ast, context) {
return `[${ast.entries.map(entry => entry.visitExpression(this, context)).join(',')}]`;
}
visitLiteralMapExpr(ast, context) {
const mapKey = (entry) => {
const quote = entry.quoted ? '"' : '';
return `${quote}${entry.key}${quote}`;
};
const mapEntry = (entry) => `${mapKey(entry)}:${entry.value.visitExpression(this, context)}`;
return `{${ast.entries.map(mapEntry).join(',')}`;
}
visitExternalExpr(ast) {
return ast.value.moduleName ? `EX:${ast.value.moduleName}:${ast.value.name}` :
`EX:${ast.value.runtime.name}`;
}
visitReadVarExpr(node) {
return `VAR:${node.name}`;
}
visitTypeofExpr(node, context) {
return `TYPEOF:${node.expr.visitExpression(this, context)}`;
}
}
function invalid(arg) {
throw new Error(`Invalid state: Visitor ${this.constructor.name} doesn't handle ${arg.constructor.name}`);
}
function isVariable(e) {
return e instanceof ReadVarExpr;
}
function isLongStringLiteral(expr) {
return expr instanceof LiteralExpr && typeof expr.value === 'string' &&
expr.value.length >= POOL_INCLUSION_LENGTH_THRESHOLD_FOR_STRINGS;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const CORE = '@angular/core';
class 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.Renderer2 = { name: 'Renderer2', 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.directiveInject = { name: 'ɵɵdirectiveInject', moduleName: CORE };
Identifiers.INJECTOR = { name: 'INJECTOR', moduleName: CORE };
Identifiers.Injector = { name: 'Injector', moduleName: CORE };
Identifiers.ɵɵdefineInjectable = { name: 'ɵɵdefineInjectable', moduleName: CORE };
Identifiers.InjectableDef = { name: 'ɵɵInjectableDef', 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 };
Identifiers.setClassMetadata = { name: 'ɵsetClassMetadata', moduleName: CORE };
function createTokenForReference(reference) {
return { identifier: { reference: reference } };
}
function createTokenForExternalReference(reflector, reference) {
return createTokenForReference(reflector.resolveExternalReference(reference));
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A token representing the a reference to a static type.
*
* This token is unique for a filePath and name and can be used as a hash table key.
*/
class StaticSymbol {
constructor(filePath, name, members) {
this.filePath = filePath;
this.name = name;
this.members = members;
}
assertNoMembers() {
if (this.members.length) {
throw new Error(`Illegal state: symbol without members expected, but got ${JSON.stringify(this)}.`);
}
}
}
/**
* A cache of static symbol used by the StaticReflector to return the same symbol for the
* same symbol values.
*/
class StaticSymbolCache {
constructor() {
this.cache = new Map();
}
get(declarationFile, name, members) {
members = members || [];
const memberSuffix = members.length ? `.${members.join('.')}` : '';
const key = `"${declarationFile}".${name}${memberSuffix}`;
let result = this.cache.get(key);
if (!result) {
result = new StaticSymbol(declarationFile, name, members);
this.cache.set(key, result);
}
return result;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const DASH_CASE_REGEXP = /-+([a-z0-9])/g;
function dashCaseToCamelCase(input) {
return input.replace(DASH_CASE_REGEXP, (...m) => m[1].toUpperCase());
}
function splitAtColon(input, defaultValues) {
return _splitAt(input, ':', defaultValues);
}
function splitAtPeriod(input, defaultValues) {
return _splitAt(input, '.', defaultValues);
}
function _splitAt(input, character, defaultValues) {
const characterIndex = input.indexOf(character);
if (characterIndex == -1)
return defaultValues;
return [input.slice(0, characterIndex).trim(), input.slice(characterIndex + 1).trim()];
}
function visitValue(value, visitor, context) {
if (Array.isArray(value)) {
return visitor.visitArray(value, context);
}
if (isStrictStringMap(value)) {
return visitor.visitStringMap(value, context);
}
if (value == null || typeof value == 'string' || typeof value == 'number' ||
typeof value == 'boolean') {
return visitor.visitPrimitive(value, context);
}
return visitor.visitOther(value, context);
}
function isDefined(val) {
return val !== null && val !== undefined;
}
function noUndefined(val) {
return val === undefined ? null : val;
}
class ValueTransformer {
visitArray(arr, context) {
return arr.map(value => visitValue(value, this, context));
}
visitStringMap(map, context) {
const result = {};
Object.keys(map).forEach(key => {
result[key] = visitValue(map[key], this, context);
});
return result;
}
visitPrimitive(value, context) {
return value;
}
visitOther(value, context) {
return value;
}
}
const SyncAsync = {
assertSync: (value) => {
if (isPromise(value)) {
throw new Error(`Illegal state: value cannot be a promise`);
}
return value;
},
then: (value, cb) => {
return isPromise(value) ? value.then(cb) : cb(value);
},
all: (syncAsyncValues) => {
return syncAsyncValues.some(isPromise) ? Promise.all(syncAsyncValues) : syncAsyncValues;
}
};
function error(msg) {
throw new Error(`Internal Error: ${msg}`);
}
function syntaxError(msg, parseErrors) {
const error = Error(msg);
error[ERROR_SYNTAX_ERROR] = true;
if (parseErrors)
error[ERROR_PARSE_ERRORS] = parseErrors;
return error;
}
const ERROR_SYNTAX_ERROR = 'ngSyntaxError';
const ERROR_PARSE_ERRORS = 'ngParseErrors';
function isSyntaxError(error) {
return error[ERROR_SYNTAX_ERROR];
}
function getParseErrors(error) {
return error[ERROR_PARSE_ERRORS] || [];
}
// Escape characters that have a special meaning in Regular Expressions
function escapeRegExp(s) {
return s.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
}
const STRING_MAP_PROTO = Object.getPrototypeOf({});
function isStrictStringMap(obj) {
return typeof obj === 'object' && obj !== null && Object.getPrototypeOf(obj) === STRING_MAP_PROTO;
}
function utf8Encode(str) {
let encoded = [];
for (let index = 0; index < str.length; index++) {
let codePoint = str.charCodeAt(index);
// decode surrogate
// see https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
if (codePoint >= 0xd800 && codePoint <= 0xdbff && str.length > (index + 1)) {
const low = str.charCodeAt(index + 1);
if (low >= 0xdc00 && low <= 0xdfff) {
index++;
codePoint = ((codePoint - 0xd800) << 10) + low - 0xdc00 + 0x10000;
}
}
if (codePoint <= 0x7f) {
encoded.push(codePoint);
}
else if (codePoint <= 0x7ff) {
encoded.push(((codePoint >> 6) & 0x1F) | 0xc0, (codePoint & 0x3f) | 0x80);
}
else if (codePoint <= 0xffff) {
encoded.push((codePoint >> 12) | 0xe0, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80);
}
else if (codePoint <= 0x1fffff) {
encoded.push(((codePoint >> 18) & 0x07) | 0xf0, ((codePoint >> 12) & 0x3f) | 0x80, ((codePoint >> 6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80);
}
}
return encoded;
}
function stringify(token) {
if (typeof token === 'string') {
return token;
}
if (Array.isArray(token)) {
return '[' + token.map(stringify).join(', ') + ']';
}
if (token == null) {
return '' + token;
}
if (token.overriddenName) {
return `${token.overriddenName}`;
}
if (token.name) {
return `${token.name}`;
}
if (!token.toString) {
return 'object';
}
// WARNING: do not try to `JSON.stringify(token)` here
// see https://github.com/angular/angular/issues/23440
const res = token.toString();
if (res == null) {
return '' + res;
}
const newLineIndex = res.indexOf('\n');
return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
}
/**
* Lazily retrieves the reference value from a forwardRef.
*/
function resolveForwardRef(type) {
if (typeof type === 'function' && type.hasOwnProperty('__forward_ref__')) {
return type();
}
else {
return type;
}
}
/**
* Determine if the argument is shaped like a Promise
*/
function isPromise(obj) {
// allow any Promise/A+ compliant thenable.
// It's up to the caller to ensure that obj.then conforms to the spec
return !!obj && typeof obj.then === 'function';
}
class Version {
constructor(full) {
this.full = full;
const splits = full.split('.');
this.major = splits[0];
this.minor = splits[1];
this.patch = splits.slice(2).join('.');
}
}
const __window = typeof window !== 'undefined' && window;
const __self = typeof self !== 'undefined' && typeof WorkerGlobalScope !== 'undefined' &&
self instanceof WorkerGlobalScope && self;
const __global = typeof global !== 'undefined' && global;
// Check __global first, because in Node tests both __global and __window may be defined and _global
// should be __global in that case.
const _global = __global || __window || __self;
function newArray(size, value) {
const list = [];
for (let i = 0; i < size; i++) {
list.push(value);
}
return list;
}
/**
* Partitions a given array into 2 arrays, based on a boolean value returned by the condition
* function.
*
* @param arr Input array that should be partitioned
* @param conditionFn Condition function that is called for each item in a given array and returns a
* boolean value.
*/
function partitionArray(arr, conditionFn) {
const truthy = [];
const falsy = [];
for (const item of arr) {
(conditionFn(item) ? truthy : falsy).push(item);
}
return [truthy, falsy];
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// group 0: "[prop] or (event) or @trigger"
// group 1: "prop" from "[prop]"
// group 2: "event" from "(event)"
// group 3: "@trigger" from "@trigger"
const HOST_REG_EXP = /^(?:(?:\[([^\]]+)\])|(?:\(([^\)]+)\)))|(\@[-\w]+)$/;
function sanitizeIdentifier(name) {
return name.replace(/\W/g, '_');
}
let _anonymousTypeIndex = 0;
function identifierName(compileIdentifier) {
if (!compileIdentifier || !compileIdentifier.reference) {
return null;
}
const ref = compileIdentifier.reference;
if (ref instanceof StaticSymbol) {
return ref.name;
}
if (ref['__anonymousType']) {
return ref['__anonymousType'];
}
let identifier = stringify(ref);
if (identifier.indexOf('(') >= 0) {
// case: anonymous functions!
identifier = `anonymous_${_anonymousTypeIndex++}`;
ref['__anonymousType'] = identifier;
}
else {
identifier = sanitizeIdentifier(identifier);
}
return identifier;
}
function identifierModuleUrl(compileIdentifier) {
const ref = compileIdentifier.reference;
if (ref instanceof StaticSymbol) {
return ref.filePath;
}
// Runtime type
return `./${stringify(ref)}`;
}
function viewClassName(compType, embeddedTemplateIndex) {
return `View_${identifierName({ reference: compType })}_${embeddedTemplateIndex}`;
}
function rendererTypeName(compType) {
return `RenderType_${identifierName({ reference: compType })}`;
}
function hostViewClassName(compType) {
return `HostView_${identifierName({ reference: compType })}`;
}
function componentFactoryName(compType) {
return `${identifierName({ reference: compType })}NgFactory`;
}
var CompileSummaryKind;
(function (CompileSummaryKind) {
CompileSummaryKind[CompileSummaryKind["Pipe"] = 0] = "Pipe";
CompileSummaryKind[CompileSummaryKind["Directive"] = 1] = "Directive";
CompileSummaryKind[CompileSummaryKind["NgModule"] = 2] = "NgModule";
CompileSummaryKind[CompileSummaryKind["Injectable"] = 3] = "Injectable";
})(CompileSummaryKind || (CompileSummaryKind = {}));
function tokenName(token) {
return token.value != null ? sanitizeIdentifier(token.value) : identifierName(token.identifier);
}
function tokenReference(token) {
if (token.identifier != null) {
return token.identifier.reference;
}
else {
return token.value;
}
}
/**
* Metadata about a stylesheet
*/
class CompileStylesheetMetadata {
constructor({ moduleUrl, styles, styleUrls } = {}) {
this.moduleUrl = moduleUrl || null;
this.styles = _normalizeArray(styles);
this.styleUrls = _normalizeArray(styleUrls);
}
}
/**
* Metadata regarding compilation of a template.
*/
class CompileTemplateMetadata {
constructor({ encapsulation, template, templateUrl, htmlAst, styles, styleUrls, externalStylesheets, animations, ngContentSelectors, interpolation, isInline, preserveWhitespaces }) {
this.encapsulation = encapsulation;
this.template = template;
this.templateUrl = templateUrl;
this.htmlAst = htmlAst;
this.styles = _normalizeArray(styles);
this.styleUrls = _normalizeArray(styleUrls);
this.externalStylesheets = _normalizeArray(externalStylesheets);
this.animations = animations ? flatten(animations) : [];
this.ngContentSelectors = ngContentSelectors || [];
if (interpolation && interpolation.length != 2) {
throw new Error(`'interpolation' should have a start and an end symbol.`);
}
this.interpolation = interpolation;
this.isInline = isInline;
this.preserveWhitespaces = preserveWhitespaces;
}
toSummary() {
return {
ngContentSelectors: this.ngContentSelectors,
encapsulation: this.encapsulation,
styles: this.styles,
animations: this.animations
};
}
}
/**
* Metadata regarding compilation of a directive.
*/
class CompileDirectiveMetadata {
constructor({ isHost, type, isComponent, selector, exportAs, changeDetection, inputs, outputs, hostListeners, hostProperties, hostAttributes, providers, viewProviders, queries, guards, viewQueries, entryComponents, template, componentViewType, rendererType, componentFactory }) {
this.isHost = !!isHost;
this.type = type;
this.isComponent = isComponent;
this.selector = selector;
this.exportAs = exportAs;
this.changeDetection = changeDetection;
this.inputs = inputs;
this.outputs = outputs;
this.hostListeners = hostListeners;
this.hostProperties = hostProperties;
this.hostAttributes = hostAttributes;
this.providers = _normalizeArray(providers);
this.viewProviders = _normalizeArray(viewProviders);
this.queries = _normalizeArray(queries);
this.guards = guards;
this.viewQueries = _normalizeArray(viewQueries);
this.entryComponents = _normalizeArray(entryComponents);
this.template = template;
this.componentViewType = componentViewType;
this.rendererType = rendererType;
this.componentFactory = componentFactory;
}
static create({ isHost, type, isComponent, selector, exportAs, changeDetection, inputs, outputs, host, providers, viewProviders, queries, guards, viewQueries, entryComponents, template, componentViewType, rendererType, componentFactory }) {
const hostListeners = {};
const hostProperties = {};
const hostAttributes = {};
if (host != null) {
Object.keys(host).forEach(key => {
const value = host[key];
const matches = key.match(HOST_REG_EXP);
if (matches === null) {
hostAttributes[key] = value;
}
else if (matches[1] != null) {
hostProperties[matches[1]] = value;
}
else if (matches[2] != null) {
hostListeners[matches[2]] = value;
}
});
}
const inputsMap = {};
if (inputs != null) {
inputs.forEach((bindConfig) => {
// canonical syntax: `dirProp: elProp`
// if there is no `:`, use dirProp = elProp
const parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
inputsMap[parts[0]] = parts[1];
});
}
const outputsMap = {};
if (outputs != null) {
outputs.forEach((bindConfig) => {
// canonical syntax: `dirProp: elProp`
// if there is no `:`, use dirProp = elProp
const parts = splitAtColon(bindConfig, [bindConfig, bindConfig]);
outputsMap[parts[0]] = parts[1];
});
}
return new CompileDirectiveMetadata({
isHost,
type,
isComponent: !!isComponent,
selector,
exportAs,
changeDetection,
inputs: inputsMap,
outputs: outputsMap,
hostListeners,
hostProperties,
hostAttributes,
providers,
viewProviders,
queries,
guards,
viewQueries,
entryComponents,
template,
componentViewType,
rendererType,
componentFactory,
});
}
toSummary() {
return {
summaryKind: CompileSummaryKind.Directive,
type: this.type,
isComponent: this.isComponent,
selector: this.selector,
exportAs: this.exportAs,
inputs: this.inputs,
outputs: this.outputs,
hostListeners: this.hostListeners,
hostProperties: this.hostProperties,
hostAttributes: this.hostAttributes,
providers: this.providers,
viewProviders: this.viewProviders,
queries: this.queries,
guards: this.guards,
viewQueries: this.viewQueries,
entryComponents: this.entryComponents,
changeDetection: this.changeDetection,
template: this.template && this.template.toSummary(),
componentViewType: this.componentViewType,
rendererType: this.rendererType,
componentFactory: this.componentFactory
};
}
}
class CompilePipeMetadata {
constructor({ type, name, pure }) {
this.type = type;
this.name = name;
this.pure = !!pure;
}
toSummary() {
return {
summaryKind: CompileSummaryKind.Pipe,
type: this.type,
name: this.name,
pure: this.pure
};
}
}
class CompileShallowModuleMetadata {
}
/**
* Metadata regarding compilation of a module.
*/
class CompileNgModuleMetadata {
constructor({ type, providers, declaredDirectives, exportedDirectives, declaredPipes, exportedPipes, entryComponents, bootstrapComponents, importedModules, exportedModules, schemas, transitiveModule, id }) {
this.type = type || null;
this.declaredDirectives = _normalizeArray(declaredDirectives);
this.exportedDirectives = _normalizeArray(exportedDirectives);
this.declaredPipes = _normalizeArray(declaredPipes);
this.exportedPipes = _normalizeArray(exportedPipes);
this.providers = _normalizeArray(providers);
this.entryComponents = _normalizeArray(entryComponents);
this.bootstrapComponents = _normalizeArray(bootstrapComponents);
this.importedModules = _normalizeArray(importedModules);
this.exportedModules = _normalizeArray(exportedModules);
this.schemas = _normalizeArray(schemas);
this.id = id || null;
this.transitiveModule = transitiveModule || null;
}
toSummary() {
const module = this.transitiveModule;
return {
summaryKind: CompileSummaryKind.NgModule,
type: this.type,
entryComponents: module.entryComponents,
providers: module.providers,
modules: module.modules,
exportedDirectives: module.exportedDirectives,
exportedPipes: module.exportedPipes
};
}
}
class TransitiveCompileNgModuleMetadata {
constructor() {
this.directivesSet = new Set();
this.directives = [];
this.exportedDirectivesSet = new Set();
this.exportedDirectives = [];
this.pipesSet = new Set();
this.pipes = [];
this.exportedPipesSet = new Set();
this.exportedPipes = [];
this.modulesSet = new Set();
this.modules = [];
this.entryComponentsSet = new Set();
this.entryComponents = [];
this.providers = [];
}
addProvider(provider, module) {
this.providers.push({ provider: provider, module: module });
}
addDirective(id) {
if (!this.directivesSet.has(id.reference)) {
this.directivesSet.add(id.reference);
this.directives.push(id);
}
}
addExportedDirective(id) {
if (!this.exportedDirectivesSet.has(id.reference)) {
this.exportedDirectivesSet.add(id.reference);
this.exportedDirectives.push(id);
}
}
addPipe(id) {
if (!this.pipesSet.has(id.reference)) {
this.pipesSet.add(id.reference);
this.pipes.push(id);
}
}
addExportedPipe(id) {
if (!this.exportedPipesSet.has(id.reference)) {
this.exportedPipesSet.add(id.reference);
this.exportedPipes.push(id);
}
}
addModule(id) {
if (!this.modulesSet.has(id.reference)) {
this.modulesSet.add(id.reference);
this.modules.push(id);
}
}
addEntryComponent(ec) {
if (!this.entryComponentsSet.has(ec.componentType)) {
this.entryComponentsSet.add(ec.componentType);
this.entryComponents.push(ec);
}
}
}
function _normalizeArray(obj) {
return obj || [];
}
class ProviderMeta {
constructor(token, { useClass, useValue, useExisting, useFactory, deps, multi }) {
this.token = token;
this.useClass = useClass || null;
this.useValue = useValue;
this.useExisting = useExisting;
this.useFactory = useFactory || null;
this.dependencies = deps || null;
this.multi = !!multi;
}
}
function flatten(list) {
return list.reduce((flat, item) => {
const flatItem = Array.isArray(item) ? flatten(item) : item;
return flat.concat(flatItem);
}, []);
}
function jitSourceUrl(url) {
// Note: We need 3 "/" so that ng shows up as a separate domain
// in the chrome dev tools.
return url.replace(/(\w+:\/\/[\w:-]+)?(\/+)?/, 'ng:///');
}
function templateSourceUrl(ngModuleType, compMeta, templateMeta) {
let url;
if (templateMeta.isInline) {
if (compMeta.type.reference instanceof StaticSymbol) {
// Note: a .ts file might contain multiple components with inline templates,
// so we need to give them unique urls, as these will be used for sourcemaps.
url = `${compMeta.type.reference.filePath}.${compMeta.type.reference.name}.html`;
}
else {
url = `${identifierName(ngModuleType)}/${identifierName(compMeta.type)}.html`;
}
}
else {
url = templateMeta.templateUrl;
}
return compMeta.type.reference instanceof StaticSymbol ? url : jitSourceUrl(url);
}
function sharedStylesheetJitUrl(meta, id) {
const pathParts = meta.moduleUrl.split(/\/\\/g);
const baseName = pathParts[pathParts.length - 1];
return jitSourceUrl(`css/${id}${baseName}.ngstyle.js`);
}
function ngModuleJitUrl(moduleMeta) {
return jitSourceUrl(`${identifierName(moduleMeta.type)}/module.ngfactory.js`);
}
function templateJitUrl(ngModuleType, compMeta) {
return jitSourceUrl(`${identifierName(ngModuleType)}/${identifierName(compMeta.type)}.ngfactory.js`);
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const CORE$1 = '@angular/core';
class Identifiers$1 {
}
/* Methods */
Identifiers$1.NEW_METHOD = 'factory';
Identifiers$1.TRANSFORM_METHOD = 'transform';
Identifiers$1.PATCH_DEPS = 'patchedDeps';
Identifiers$1.core = { name: null, moduleName: CORE$1 };
/* Instructions */
Identifiers$1.namespaceHTML = { name: 'ɵɵnamespaceHTML', moduleName: CORE$1 };
Identifiers$1.namespaceMathML = { name: 'ɵɵnamespaceMathML', moduleName: CORE$1 };
Identifiers$1.namespaceSVG = { name: 'ɵɵnamespaceSVG', moduleName: CORE$1 };
Identifiers$1.element = { name: 'ɵɵelement', moduleName: CORE$1 };
Identifiers$1.elementStart = { name: 'ɵɵelementStart', moduleName: CORE$1 };
Identifiers$1.elementEnd = { name: 'ɵɵelementEnd', moduleName: CORE$1 };
Identifiers$1.advance = { name: 'ɵɵadvance', moduleName: CORE$1 };
Identifiers$1.syntheticHostProperty = { name: 'ɵɵsyntheticHostProperty', moduleName: CORE$1 };
Identifiers$1.syntheticHostListener = { name: 'ɵɵsyntheticHostListener', moduleName: CORE$1 };
Identifiers$1.attribute = { name: 'ɵɵattribute', moduleName: CORE$1 };
Identifiers$1.attributeInterpolate1 = { name: 'ɵɵattributeInterpolate1', moduleName: CORE$1 };
Identifiers$1.attributeInterpolate2 = { name: 'ɵɵattributeInterpolate2', moduleName: CORE$1 };
Identifiers$1.attributeInterpolate3 = { name: 'ɵɵattributeInterpolate3', moduleName: CORE$1 };
Identifiers$1.attributeInterpolate4 = { name: 'ɵɵattributeInterpolate4', moduleName: CORE$1 };
Identifiers$1.attributeInterpolate5 = { name: 'ɵɵattributeInterpolate5', moduleName: CORE$1 };
Identifiers$1.attributeInterpolate6 = { name: 'ɵɵattributeInterpolate6', moduleName: CORE$1 };
Identifiers$1.attributeInterpolate7 = { name: 'ɵɵattributeInterpolate7', moduleName: CORE$1 };
Identifiers$1.attributeInterpolate8 = { name: 'ɵɵattributeInterpolate8', moduleName: CORE$1 };
Identifiers$1.attributeInterpolateV = { name: 'ɵɵattributeInterpolateV', moduleName: CORE$1 };
Identifiers$1.classProp = { name: 'ɵɵclassProp', moduleName: CORE$1 };
Identifiers$1.elementContainerStart = { name: 'ɵɵelementContainerStart', moduleName: CORE$1 };
Identifiers$1.elementContainerEnd = { name: 'ɵɵelementContainerEnd', moduleName: CORE$1 };
Identifiers$1.elementContainer = { name: 'ɵɵelementContainer', moduleName: CORE$1 };
Identifiers$1.styleMap = { name: 'ɵɵstyleMap', moduleName: CORE$1 };
Identifiers$1.styleMapInterpolate1 = { name: 'ɵɵstyleMapInterpolate1', moduleName: CORE$1 };
Identifiers$1.styleMapInterpolate2 = { name: 'ɵɵstyleMapInterpolate2', moduleName: CORE$1 };
Identifiers$1.styleMapInterpolate3 = { name: 'ɵɵstyleMapInterpolate3', moduleName: CORE$1 };
Identifiers$1.styleMapInterpolate4 = { name: 'ɵɵstyleMapInterpolate4', moduleName: CORE$1 };
Identifiers$1.styleMapInterpolate5 = { name: 'ɵɵstyleMapInterpolate5', moduleName: CORE$1 };
Identifiers$1.styleMapInterpolate6 = { name: 'ɵɵstyleMapInterpolate6', moduleName: CORE$1 };
Identifiers$1.styleMapInterpolate7 = { name: 'ɵɵstyleMapInterpolate7', moduleName: CORE$1 };
Identifiers$1.styleMapInterpolate8 = { name: 'ɵɵstyleMapInterpolate8', moduleName: CORE$1 };
Identifiers$1.styleMapInterpolateV = { name: 'ɵɵstyleMapInterpolateV', moduleName: CORE$1 };
Identifiers$1.classMap = { name: 'ɵɵclassMap', moduleName: CORE$1 };
Identifiers$1.classMapInterpolate1 = { name: 'ɵɵclassMapInterpolate1', moduleName: CORE$1 };
Identifiers$1.classMapInterpolate2 = { name: 'ɵɵclassMapInterpolate2', moduleName: CORE$1 };
Identifiers$1.classMapInterpolate3 = { name: 'ɵɵclassMapInterpolate3', moduleName: CORE$1 };
Identifiers$1.classMapInterpolate4 = { name: 'ɵɵclassMapInterpolate4', moduleName: CORE$1 };
Identifiers$1.classMapInterpolate5 = { name: 'ɵɵclassMapInterpolate5', moduleName: CORE$1 };
Identifiers$1.classMapInterpolate6 = { name: 'ɵɵclassMapInterpolate6', moduleName: CORE$1 };
Identifiers$1.classMapInterpolate7 = { name: 'ɵɵclassMapInterpolate7', moduleName: CORE$1 };
Identifiers$1.classMapInterpolate8 = { name: 'ɵɵclassMapInterpolate8', moduleName: CORE$1 };
Identifiers$1.classMapInterpolateV = { name: 'ɵɵclassMapInterpolateV', moduleName: CORE$1 };
Identifiers$1.styleProp = { name: 'ɵɵstyleProp', moduleName: CORE$1 };
Identifiers$1.stylePropInterpolate1 = { name: 'ɵɵstylePropInterpolate1', moduleName: CORE$1 };
Identifiers$1.stylePropInterpolate2 = { name: 'ɵɵstylePropInterpolate2', moduleName: CORE$1 };
Identifiers$1.stylePropInterpolate3 = { name: 'ɵɵstylePropInterpolate3', moduleName: CORE$1 };
Identifiers$1.stylePropInterpolate4 = { name: 'ɵɵstylePropInterpolate4', moduleName: CORE$1 };
Identifiers$1.stylePropInterpolate5 = { name: 'ɵɵstylePropInterpolate5', moduleName: CORE$1 };
Identifiers$1.stylePropInterpolate6 = { name: 'ɵɵstylePropInterpolate6', moduleName: CORE$1 };
Identifiers$1.stylePropInterpolate7 = { name: 'ɵɵstylePropInterpolate7', moduleName: CORE$1 };
Identifiers$1.stylePropInterpolate8 = { name: 'ɵɵstylePropInterpolate8', moduleName: CORE$1 };
Identifiers$1.stylePropInterpolateV = { name: 'ɵɵstylePropInterpolateV', moduleName: CORE$1 };
Identifiers$1.nextContext = { name: 'ɵɵnextContext', moduleName: CORE$1 };
Identifiers$1.templateCreate = { name: 'ɵɵtemplate', moduleName: CORE$1 };
Identifiers$1.text = { name: 'ɵɵtext', moduleName: CORE$1 };
Identifiers$1.enableBindings = { name: 'ɵɵenableBindings', moduleName: CORE$1 };
Identifiers$1.disableBindings = { name: 'ɵɵdisableBindings', moduleName: CORE$1 };
Identifiers$1.getCurrentView = { name: 'ɵɵgetCurrentView', moduleName: CORE$1 };
Identifiers$1.textInterpolate = { name: 'ɵɵtextInterpolate', moduleName: CORE$1 };
Identifiers$1.textInterpolate1 = { name: 'ɵɵtextInterpolate1', moduleName: CORE$1 };
Identifiers$1.textInterpolate2 = { name: 'ɵɵtextInterpolate2', moduleName: CORE$1 };
Identifiers$1.textInterpolate3 = { name: 'ɵɵtextInterpolate3', moduleName: CORE$1 };
Identifiers$1.textInterpolate4 = { name: 'ɵɵtextInterpolate4', moduleName: CORE$1 };
Identifiers$1.textInterpolate5 = { name: 'ɵɵtextInterpolate5', moduleName: CORE$1 };
Identifiers$1.textInterpolate6 = { name: 'ɵɵtextInterpolate6', moduleName: CORE$1 };
Identifiers$1.textInterpolate7 = { name: 'ɵɵtextInterpolate7', moduleName: CORE$1 };
Identifiers$1.textInterpolate8 = { name: 'ɵɵtextInterpolate8', moduleName: CORE$1 };
Identifiers$1.textInterpolateV = { name: 'ɵɵtextInterpolateV', moduleName: CORE$1 };
Identifiers$1.restoreView = { name: 'ɵɵrestoreView', moduleName: CORE$1 };
Identifiers$1.pureFunction0 = { name: 'ɵɵpureFunction0', moduleName: CORE$1 };
Identifiers$1.pureFunction1 = { name: 'ɵɵpureFunction1', moduleName: CORE$1 };
Identifiers$1.pureFunction2 = { name: 'ɵɵpureFunction2', moduleName: CORE$1 };
Identifiers$1.pureFunction3 = { name: 'ɵɵpureFunction3', moduleName: CORE$1 };
Identifiers$1.pureFunction4 = { name: 'ɵɵpureFunction4', moduleName: CORE$1 };
Identifiers$1.pureFunction5 = { name: 'ɵɵpureFunction5', moduleName: CORE$1 };
Identifiers$1.pureFunction6 = { name: 'ɵɵpureFunction6', moduleName: CORE$1 };
Identifiers$1.pureFunction7 = { name: 'ɵɵpureFunction7', moduleName: CORE$1 };
Identifiers$1.pureFunction8 = { name: 'ɵɵpureFunction8', moduleName: CORE$1 };
Identifiers$1.pureFunctionV = { name: 'ɵɵpureFunctionV', moduleName: CORE$1 };
Identifiers$1.pipeBind1 = { name: 'ɵɵpipeBind1', moduleName: CORE$1 };
Identifiers$1.pipeBind2 = { name: 'ɵɵpipeBind2', moduleName: CORE$1 };
Identifiers$1.pipeBind3 = { name: 'ɵɵpipeBind3', moduleName: CORE$1 };
Identifiers$1.pipeBind4 = { name: 'ɵɵpipeBind4', moduleName: CORE$1 };
Identifiers$1.pipeBindV = { name: 'ɵɵpipeBindV', moduleName: CORE$1 };
Identifiers$1.hostProperty = { name: 'ɵɵhostProperty', moduleName: CORE$1 };
Identifiers$1.property = { name: 'ɵɵproperty', moduleName: CORE$1 };
Identifiers$1.propertyInterpolate = { name: 'ɵɵpropertyInterpolate', moduleName: CORE$1 };
Identifiers$1.propertyInterpolate1 = { name: 'ɵɵpropertyInterpolate1', moduleName: CORE$1 };
Identifiers$1.propertyInterpolate2 = { name: 'ɵɵpropertyInterpolate2', moduleName: CORE$1 };
Identifiers$1.propertyInterpolate3 = { name: 'ɵɵpropertyInterpolate3', moduleName: CORE$1 };
Identifiers$1.propertyInterpolate4 = { name: 'ɵɵpropertyInterpolate4', moduleName: CORE$1 };
Identifiers$1.propertyInterpolate5 = { name: 'ɵɵpropertyInterpolate5', moduleName: CORE$1 };
Identifiers$1.propertyInterpolate6 = { name: 'ɵɵpropertyInterpolate6', moduleName: CORE$1 };
Identifiers$1.propertyInterpolate7 = { name: 'ɵɵpropertyInterpolate7', moduleName: CORE$1 };
Identifiers$1.propertyInterpolate8 = { name: 'ɵɵpropertyInterpolate8', moduleName: CORE$1 };
Identifiers$1.propertyInterpolateV = { name: 'ɵɵpropertyInterpolateV', moduleName: CORE$1 };
Identifiers$1.i18n = { name: 'ɵɵi18n', moduleName: CORE$1 };
Identifiers$1.i18nAttributes = { name: 'ɵɵi18nAttributes', moduleName: CORE$1 };
Identifiers$1.i18nExp = { name: 'ɵɵi18nExp', moduleName: CORE$1 };
Identifiers$1.i18nStart = { name: 'ɵɵi18nStart', moduleName: CORE$1 };
Identifiers$1.i18nEnd = { name: 'ɵɵi18nEnd', moduleName: CORE$1 };
Identifiers$1.i18nApply = { name: 'ɵɵi18nApply', moduleName: CORE$1 };
Identifiers$1.i18nPostprocess = { name: 'ɵɵi18nPostprocess', moduleName: CORE$1 };
Identifiers$1.pipe = { name: 'ɵɵpipe', moduleName: CORE$1 };
Identifiers$1.projection = { name: 'ɵɵprojection', moduleName: CORE$1 };
Identifiers$1.projectionDef = { name: 'ɵɵprojectionDef', moduleName: CORE$1 };
Identifiers$1.reference = { name: 'ɵɵreference', moduleName: CORE$1 };
Identifiers$1.inject = { name: 'ɵɵinject', moduleName: CORE$1 };
Identifiers$1.injectAttribute = { name: 'ɵɵinjectAttribute', moduleName: CORE$1 };
Identifiers$1.injectPipeChangeDetectorRef = { name: 'ɵɵinjectPipeChangeDetectorRef', moduleName: CORE$1 };
Identifiers$1.directiveInject = { name: 'ɵɵdirectiveInject', moduleName: CORE$1 };
Identifiers$1.invalidFactory = { name: 'ɵɵinvalidFactory', moduleName: CORE$1 };
Identifiers$1.invalidFactoryDep = { name: 'ɵɵinvalidFactoryDep', moduleName: CORE$1 };
Identifiers$1.templateRefExtractor = { name: 'ɵɵtemplateRefExtractor', moduleName: CORE$1 };
Identifiers$1.forwardRef = { name: 'forwardRef', moduleName: CORE$1 };
Identifiers$1.resolveForwardRef = { name: 'resolveForwardRef', moduleName: CORE$1 };
Identifiers$1.resolveWindow = { name: 'ɵɵresolveWindow', moduleName: CORE$1 };
Identifiers$1.resolveDocument = { name: 'ɵɵresolveDocument', moduleName: CORE$1 };
Identifiers$1.resolveBody = { name: 'ɵɵresolveBody', moduleName: CORE$1 };
Identifiers$1.defineComponent = { name: 'ɵɵdefineComponent', moduleName: CORE$1 };
Identifiers$1.declareComponent = { name: 'ɵɵngDeclareComponent', moduleName: CORE$1 };
Identifiers$1.setComponentScope = { name: 'ɵɵsetComponentScope', moduleName: CORE$1 };
Identifiers$1.ChangeDetectionStrategy = {
name: 'ChangeDetectionStrategy',
moduleName: CORE$1,
};
Identifiers$1.ViewEncapsulation = {
name: 'ViewEncapsulation',
moduleName: CORE$1,
};
Identifiers$1.ComponentDefWithMeta = {
name: 'ɵɵComponentDefWithMeta',
moduleName: CORE$1,
};
Identifiers$1.FactoryDef = {
name: 'ɵɵFactoryDef',
moduleName: CORE$1,
};
Identifiers$1.defineDirective = { name: 'ɵɵdefineDirective', moduleName: CORE$1 };
Identifiers$1.declareDirective = { name: 'ɵɵngDeclareDirective', moduleName: CORE$1 };
Identifiers$1.DirectiveDefWithMeta = {
name: 'ɵɵDirectiveDefWithMeta',
moduleName: CORE$1,
};
Identifiers$1.InjectorDef = {
name: 'ɵɵInjectorDef',
moduleName: CORE$1,
};
Identifiers$1.defineInjector = {
name: 'ɵɵdefineInjector',
moduleName: CORE$1,
};
Identifiers$1.NgModuleDefWithMeta = {
name: 'ɵɵNgModuleDefWithMeta',
moduleName: CORE$1,
};
Identifiers$1.ModuleWithProviders = {
name: 'ModuleWithProviders',
moduleName: CORE$1,
};
Identifiers$1.defineNgModule = { name: 'ɵɵdefineNgModule', moduleName: CORE$1 };
Identifiers$1.setNgModuleScope = { name: 'ɵɵsetNgModuleScope', moduleName: CORE$1 };
Identifiers$1.PipeDefWithMeta = { name: 'ɵɵPipeDefWithMeta', moduleName: CORE$1 };
Identifiers$1.definePipe = { name: 'ɵɵdefinePipe', moduleName: CORE$1 };
Identifiers$1.declarePipe = { name: 'ɵɵngDeclarePipe', moduleName: CORE$1 };
Identifiers$1.queryRefresh = { name: 'ɵɵqueryRefresh', moduleName: CORE$1 };
Identifiers$1.viewQuery = { name: 'ɵɵviewQuery', moduleName: CORE$1 };
Identifiers$1.loadQuery = { name: 'ɵɵloadQuery', moduleName: CORE$1 };
Identifiers$1.contentQuery = { name: 'ɵɵcontentQuery', moduleName: CORE$1 };
Identifiers$1.NgOnChangesFeature = { name: 'ɵɵNgOnChangesFeature', moduleName: CORE$1 };
Identifiers$1.InheritDefinitionFeature = { name: 'ɵɵInheritDefinitionFeature', moduleName: CORE$1 };
Identifiers$1.CopyDefinitionFeature = { name: 'ɵɵCopyDefinitionFeature', moduleName: CORE$1 };
Identifiers$1.ProvidersFeature = { name: 'ɵɵProvidersFeature', moduleName: CORE$1 };
Identifiers$1.listener = { name: 'ɵɵlistener', moduleName: CORE$1 };
Identifiers$1.getInheritedFactory = {
name: 'ɵɵgetInheritedFactory',
moduleName: CORE$1,
};
// sanitization-related functions
Identifiers$1.sanitizeHtml = { name: 'ɵɵsanitizeHtml', moduleName: CORE$1 };
Identifiers$1.sanitizeStyle = { name: 'ɵɵsanitizeStyle', moduleName: CORE$1 };
Identifiers$1.sanitizeResourceUrl = { name: 'ɵɵsanitizeResourceUrl', moduleName: CORE$1 };
Identifiers$1.sanitizeScript = { name: 'ɵɵsanitizeScript', moduleName: CORE$1 };
Identifiers$1.sanitizeUrl = { name: 'ɵɵsanitizeUrl', moduleName: CORE$1 };
Identifiers$1.sanitizeUrlOrResourceUrl = { name: 'ɵɵsanitizeUrlOrResourceUrl', moduleName: CORE$1 };
Identifiers$1.trustConstantHtml = { name: 'ɵɵtrustConstantHtml', moduleName: CORE$1 };
Identifiers$1.trustConstantResourceUrl = { name: 'ɵɵtrustConstantResourceUrl', moduleName: CORE$1 };
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit
const VERSION = 3;
const JS_B64_PREFIX = '# sourceMappingURL=data:application/json;base64,';
class SourceMapGenerator {
constructor(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
addSource(url, content = null) {
if (!this.sourcesContent.has(url)) {
this.sourcesContent.set(url, content);
}
return this;
}
addLine() {
this.lines.push([]);
this.lastCol0 = 0;
return this;
}
addMapping(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, sourceUrl, sourceLine0, sourceCol0 });
return this;
}
/**
* @internal strip this from published d.ts files due to
* https://github.com/microsoft/TypeScript/issues/36216
*/
get currentLine() {
return this.lines.slice(-1)[0];
}
toJSON() {
if (!this.hasMappings) {
return null;
}
const sourcesIndex = new Map();
const sources = [];
const sourcesContent = [];
Array.from(this.sourcesContent.keys()).forEach((url, i) => {
sourcesIndex.set(url, i);
sources.push(url);
sourcesContent.push(this.sourcesContent.get(url) || null);
});
let mappings = '';
let lastCol0 = 0;
let lastSourceIndex = 0;
let lastSourceLine0 = 0;
let lastSourceCol0 = 0;
this.lines.forEach(segments => {
lastCol0 = 0;
mappings += segments
.map(segment => {
// zero-based starting column of the line in the generated code
let 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,
'sourceRoot': '',
'sources': sources,
'sourcesContent': sourcesContent,
'mappings': mappings,
};
}
toJsComment() {
return this.hasMappings ? '//' + JS_B64_PREFIX + toBase64String(JSON.stringify(this, null, 0)) :
'';
}
}
function toBase64String(value) {
let b64 = '';
const encoded = utf8Encode(value);
for (let i = 0; i < encoded.length;) {
const i1 = encoded[i++];
const i2 = i < encoded.length ? encoded[i++] : null;
const i3 = i < encoded.length ? encoded[i++] : null;
b64 += toBase64Digit(i1 >> 2);
b64 += toBase64Digit(((i1 & 3) << 4) | (i2 === null ? 0 : i2 >> 4));
b64 += i2 === null ? '=' : toBase64Digit(((i2 & 15) << 2) | (i3 === null ? 0 : i3 >> 6));
b64 += i2 === null || i3 === null ? '=' : toBase64Digit(i3 & 63);
}
return b64;
}
function toBase64VLQ(value) {
value = value < 0 ? ((-value) << 1) + 1 : value << 1;
let out = '';
do {
let digit = value & 31;
value = value >> 5;
if (value > 0) {
digit = digit | 32;
}
out += toBase64Digit(digit);
} while (value > 0);
return out;
}
const 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 LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const _SINGLE_QUOTE_ESCAPE_STRING_RE = /'|\\|\n|\r|\$/g;
const _LEGAL_IDENTIFIER_RE = /^[$A-Z_][0-9A-Z_$]*$/i;
const _INDENT_WITH = ' ';
const CATCH_ERROR_VAR$1 = variable('error', null, null);
const CATCH_STACK_VAR$1 = variable('stack', null, null);
class _EmittedLine {
constructor(indent) {
this.indent = indent;
this.partsLength = 0;
this.parts = [];
this.srcSpans = [];
}
}
class EmitterVisitorContext {
constructor(_indent) {
this._indent = _indent;
this._classes = [];
this._preambleLineCount = 0;
this._lines = [new _EmittedLine(_indent)];
}
static createRoot() {
return new EmitterVisitorContext(0);
}
/**
* @internal strip this from published d.ts files due to
* https://github.com/microsoft/TypeScript/issues/36216
*/
get _currentLine() {
return this._lines[this._lines.length - 1];
}
println(from, lastPart = '') {
this.print(from || null, lastPart, true);
}
lineIsEmpty() {
return this._currentLine.parts.length === 0;
}
lineLength() {
return this._currentLine.indent * _INDENT_WITH.length + this._currentLine.partsLength;
}
print(from, part, 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));
}
}
removeEmptyLastLine() {
if (this.lineIsEmpty()) {
this._lines.pop();
}
}
incIndent() {
this._indent++;
if (this.lineIsEmpty()) {
this._currentLine.indent = this._indent;
}
}
decIndent() {
this._indent--;
if (this.lineIsEmpty()) {
this._currentLine.indent = this._indent;
}
}
pushClass(clazz) {
this._classes.push(clazz);
}
popClass() {
return this._classes.pop();
}
get currentClass() {
return this._classes.length > 0 ? this._classes[this._classes.length - 1] : null;
}
toSource() {
return this.sourceLines
.map(l => l.parts.length > 0 ? _createIndent(l.indent) + l.parts.join('') : '')
.join('\n');
}
toSourceMapGenerator(genFilePath, startsAtLine = 0) {
const map = new SourceMapGenerator(genFilePath);
let firstOffsetMapped = false;
const mapFirstOffsetIfNeeded = () => {
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 (let i = 0; i < startsAtLine; i++) {
map.addLine();
mapFirstOffsetIfNeeded();
}
this.sourceLines.forEach((line, lineIdx) => {
map.addLine();
const spans = line.srcSpans;
const parts = line.parts;
let col0 = line.indent * _INDENT_WITH.length;
let 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) {
const span = spans[spanIdx];
const source = span.start.file;
const sourceLine = span.start.line;
const 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;
}
setPreambleLineCount(count) {
return this._preambleLineCount = count;
}
spanOf(line, column) {
const emittedLine = this._lines[line - this._preambleLineCount];
if (emittedLine) {
let columnsLeft = column - _createIndent(emittedLine.indent).length;
for (let partIndex = 0; partIndex < emittedLine.parts.length; partIndex++) {
const part = emittedLine.parts[partIndex];
if (part.length > columnsLeft) {
return emittedLine.srcSpans[partIndex];
}
columnsLeft -= part.length;
}
}
return null;
}
/**
* @internal strip this from published d.ts files due to
* https://github.com/microsoft/TypeScript/issues/36216
*/
get sourceLines() {
if (this._lines.length && this._lines[this._lines.length - 1].parts.length === 0) {
return this._lines.slice(0, -1);
}
return this._lines;
}
}
class AbstractEmitterVisitor {
constructor(_escapeDollarInStrings) {
this._escapeDollarInStrings = _escapeDollarInStrings;
}
printLeadingComments(stmt, ctx) {
if (stmt.leadingComments === undefined) {
return;
}
for (const comment of stmt.leadingComments) {
if (comment instanceof JSDocComment) {
ctx.print(stmt, `/*${comment.toString()}*/`, comment.trailingNewline);
}
else {
if (comment.multiline) {
ctx.print(stmt, `/* ${comment.text} */`, comment.trailingNewline);
}
else {
comment.text.split('\n').forEach((line) => {
ctx.println(stmt, `// ${line}`);
});
}
}
}
}
visitExpressionStmt(stmt, ctx) {
this.printLeadingComments(stmt, ctx);
stmt.expr.visitExpression(this, ctx);
ctx.println(stmt, ';');
return null;
}
visitReturnStmt(stmt, ctx) {
this.printLeadingComments(stmt, ctx);
ctx.print(stmt, `return `);
stmt.value.visitExpression(this, ctx);
ctx.println(stmt, ';');
return null;
}
visitIfStmt(stmt, ctx) {
this.printLeadingComments(stmt, ctx);
ctx.print(stmt, `if (`);
stmt.condition.visitExpression(this, ctx);
ctx.print(stmt, `) {`);
const 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;
}
visitThrowStmt(stmt, ctx) {
this.printLeadingComments(stmt, ctx);
ctx.print(stmt, `throw `);
stmt.error.visitExpression(this, ctx);
ctx.println(stmt, `;`);
return null;
}
visitWriteVarExpr(expr, ctx) {
const 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;
}
visitWriteKeyExpr(expr, ctx) {
const 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;
}
visitWritePropExpr(expr, ctx) {
const 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;
}
visitInvokeMethodExpr(expr, ctx) {
expr.receiver.visitExpression(this, ctx);
let 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;
}
visitInvokeFunctionExpr(expr, ctx) {
expr.fn.visitExpression(this, ctx);
ctx.print(expr, `(`);
this.visitAllExpressions(expr.args, ctx, ',');
ctx.print(expr, `)`);
return null;
}
visitTaggedTemplateExpr(expr, ctx) {
expr.tag.visitExpression(this, ctx);
ctx.print(expr, '`' + expr.template.elements[0].rawText);
for (let i = 1; i < expr.template.elements.length; i++) {
ctx.print(expr, '${');
expr.template.expressions[i - 1].visitExpression(this, ctx);
ctx.print(expr, `}${expr.template.elements[i].rawText}`);
}
ctx.print(expr, '`');
return null;
}
visitWrappedNodeExpr(ast, ctx) {
throw new Error('Abstract emitter cannot visit WrappedNodeExpr.');
}
visitTypeofExpr(expr, ctx) {
ctx.print(expr, 'typeof ');
expr.expr.visitExpression(this, ctx);
}
visitReadVarExpr(ast, ctx) {
let 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;
}
visitInstantiateExpr(ast, ctx) {
ctx.print(ast, `new `);
ast.classExpr.visitExpression(this, ctx);
ctx.print(ast, `(`);
this.visitAllExpressions(ast.args, ctx, ',');
ctx.print(ast, `)`);
return null;
}
visitLiteralExpr(ast, ctx) {
const value = ast.value;
if (typeof value === 'string') {
ctx.print(ast, escapeIdentifier(value, this._escapeDollarInStrings));
}
else {
ctx.print(ast, `${value}`);
}
return null;
}
visitLocalizedString(ast, ctx) {
const head = ast.serializeI18nHead();
ctx.print(ast, '$localize `' + head.raw);
for (let i = 1; i < ast.messageParts.length; i++) {
ctx.print(ast, '${');
ast.expressions[i - 1].visitExpression(this, ctx);
ctx.print(ast, `}${ast.serializeI18nTemplatePart(i).raw}`);
}
ctx.print(ast, '`');
return null;
}
visitConditionalExpr(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;
}
visitNotExpr(ast, ctx) {
ctx.print(ast, '!');
ast.condition.visitExpression(this, ctx);
return null;
}
visitAssertNotNullExpr(ast, ctx) {
ast.condition.visitExpression(this, ctx);
return null;
}
visitUnaryOperatorExpr(ast, ctx) {
let opStr;
switch (ast.operator) {
case UnaryOperator.Plus:
opStr = '+';
break;
case UnaryOperator.Minus:
opStr = '-';
break;
default:
throw new Error(`Unknown operator ${ast.operator}`);
}
if (ast.parens)
ctx.print(ast, `(`);
ctx.print(ast, opStr);
ast.expr.visitExpression(this, ctx);
if (ast.parens)
ctx.print(ast, `)`);
return null;
}
visitBinaryOperatorExpr(ast, ctx) {
let 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;
}
visitReadPropExpr(ast, ctx) {
ast.receiver.visitExpression(this, ctx);
ctx.print(ast, `.`);
ctx.print(ast, ast.name);
return null;
}
visitReadKeyExpr(ast, ctx) {
ast.receiver.visitExpression(this, ctx);
ctx.print(ast, `[`);
ast.index.visitExpression(this, ctx);
ctx.print(ast, `]`);
return null;
}
visitLiteralArrayExpr(ast, ctx) {
ctx.print(ast, `[`);
this.visitAllExpressions(ast.entries, ctx, ',');
ctx.print(ast, `]`);
return null;
}
visitLiteralMapExpr(ast, ctx) {
ctx.print(ast, `{`);
this.visitAllObjects(entry => {
ctx.print(ast, `${escapeIdentifier(entry.key, this._escapeDollarInStrings, entry.quoted)}:`);
entry.value.visitExpression(this, ctx);
}, ast.entries, ctx, ',');
ctx.print(ast, `}`);
return null;
}
visitCommaExpr(ast, ctx) {
ctx.print(ast, '(');
this.visitAllExpressions(ast.parts, ctx, ',');
ctx.print(ast, ')');
return null;
}
visitAllExpressions(expressions, ctx, separator) {
this.visitAllObjects(expr => expr.visitExpression(this, ctx), expressions, ctx, separator);
}
visitAllObjects(handler, expressions, ctx, separator) {
let incrementedIndent = false;
for (let 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();
}
}
visitAllStatements(statements, ctx) {
statements.forEach((stmt) => stmt.visitStatement(this, ctx));
}
}
function escapeIdentifier(input, escapeDollar, alwaysQuote = true) {
if (input == null) {
return null;
}
const body = input.replace(_SINGLE_QUOTE_ESCAPE_STRING_RE, (...match) => {
if (match[0] == '$') {
return escapeDollar ? '\\$' : '$';
}
else if (match[0] == '\n') {
return '\\n';
}
else if (match[0] == '\r') {
return '\\r';
}
else {
return `\\${match[0]}`;
}
});
const requiresQuotes = alwaysQuote || !_LEGAL_IDENTIFIER_RE.test(body);
return requiresQuotes ? `'${body}'` : body;
}
function _createIndent(count) {
let res = '';
for (let i = 0; i < count; i++) {
res += _INDENT_WITH;
}
return res;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Convert an object map with `Expression` values into a `LiteralMapExpr`.
*/
function mapToMapExpression(map) {
const result = Object.keys(map).map(key => ({
key,
// The assertion here is because really TypeScript doesn't allow us to express that if the
// key is present, it will have a value, but this is true in reality.
value: map[key],
quoted: false,
}));
return literalMap(result);
}
/**
* Convert metadata into an `Expression` in the given `OutputContext`.
*
* This operation will handle arrays, references to symbols, or literal `null` or `undefined`.
*/
function convertMetaToOutput(meta, ctx) {
if (Array.isArray(meta)) {
return literalArr(meta.map(entry => convertMetaToOutput(entry, ctx)));
}
if (meta instanceof StaticSymbol) {
return ctx.importExpr(meta);
}
if (meta == null) {
return literal(meta);
}
throw new Error(`Internal error: Unsupported or unknown metadata: ${meta}`);
}
function typeWithParameters(type, numParams) {
if (numParams === 0) {
return expressionType(type);
}
const params = [];
for (let i = 0; i < numParams; i++) {
params.push(DYNAMIC_TYPE);
}
return expressionType(type, undefined, params);
}
const ANIMATE_SYMBOL_PREFIX = '@';
function prepareSyntheticPropertyName(name) {
return `${ANIMATE_SYMBOL_PREFIX}${name}`;
}
function prepareSyntheticListenerName(name, phase) {
return `${ANIMATE_SYMBOL_PREFIX}${name}.${phase}`;
}
function isSyntheticPropertyOrListener(name) {
return name.charAt(0) == ANIMATE_SYMBOL_PREFIX;
}
function getSyntheticPropertyName(name) {
// this will strip out listener phase values...
// @foo.start => @foo
const i = name.indexOf('.');
name = i > 0 ? name.substring(0, i) : name;
if (name.charAt(0) !== ANIMATE_SYMBOL_PREFIX) {
name = ANIMATE_SYMBOL_PREFIX + name;
}
return name;
}
function getSafePropertyAccessString(accessor, name) {
const escapedName = escapeIdentifier(name, false, false);
return escapedName !== name ? `${accessor}[${escapedName}]` : `${accessor}.${name}`;
}
function prepareSyntheticListenerFunctionName(name, phase) {
return `animation_${name}_${phase}`;
}
function jitOnlyGuardedExpression(expr) {
return guardedExpression('ngJitMode', expr);
}
function devOnlyGuardedExpression(expr) {
return guardedExpression('ngDevMode', expr);
}
function guardedExpression(guard, expr) {
const guardExpr = new ExternalExpr({ name: guard, moduleName: null });
const guardNotDefined = new BinaryOperatorExpr(BinaryOperator.Identical, new TypeofExpr(guardExpr), literal('undefined'));
const guardUndefinedOrTrue = new BinaryOperatorExpr(BinaryOperator.Or, guardNotDefined, guardExpr, /* type */ undefined,
/* sourceSpan */ undefined, true);
return new BinaryOperatorExpr(BinaryOperator.And, guardUndefinedOrTrue, expr);
}
function wrapReference(value) {
const wrapped = new WrappedNodeExpr(value);
return { value: wrapped, type: wrapped };
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* This is an R3 `Node`-like wrapper for a raw `html.Comment` node. We do not currently
* require the implementation of a visitor for Comments as they are only collected at
* the top-level of the R3 AST, and only if `Render3ParseOptions['collectCommentNodes']`
* is true.
*/
class Comment {
constructor(value, sourceSpan) {
this.value = value;
this.sourceSpan = sourceSpan;
}
visit(_visitor) {
throw new Error('visit() not implemented for Comment');
}
}
class Text {
constructor(value, sourceSpan) {
this.value = value;
this.sourceSpan = sourceSpan;
}
visit(visitor) {
return visitor.visitText(this);
}
}
class BoundText {
constructor(value, sourceSpan, i18n) {
this.value = value;
this.sourceSpan = sourceSpan;
this.i18n = i18n;
}
visit(visitor) {
return visitor.visitBoundText(this);
}
}
/**
* Represents a text attribute in the template.
*
* `valueSpan` may not be present in cases where there is no value `<div a></div>`.
* `keySpan` may also not be present for synthetic attributes from ICU expansions.
*/
class TextAttribute {
constructor(name, value, sourceSpan, keySpan, valueSpan, i18n) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
this.keySpan = keySpan;
this.valueSpan = valueSpan;
this.i18n = i18n;
}
visit(visitor) {
return visitor.visitTextAttribute(this);
}
}
class BoundAttribute {
constructor(name, type, securityContext, value, unit, sourceSpan, keySpan, valueSpan, i18n) {
this.name = name;
this.type = type;
this.securityContext = securityContext;
this.value = value;
this.unit = unit;
this.sourceSpan = sourceSpan;
this.keySpan = keySpan;
this.valueSpan = valueSpan;
this.i18n = i18n;
}
static fromBoundElementProperty(prop, i18n) {
if (prop.keySpan === undefined) {
throw new Error(`Unexpected state: keySpan must be defined for bound attributes but was not for ${prop.name}: ${prop.sourceSpan}`);
}
return new BoundAttribute(prop.name, prop.type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan, prop.keySpan, prop.valueSpan, i18n);
}
visit(visitor) {
return visitor.visitBoundAttribute(this);
}
}
class BoundEvent {
constructor(name, type, handler, target, phase, sourceSpan, handlerSpan, keySpan) {
this.name = name;
this.type = type;
this.handler = handler;
this.target = target;
this.phase = phase;
this.sourceSpan = sourceSpan;
this.handlerSpan = handlerSpan;
this.keySpan = keySpan;
}
static fromParsedEvent(event) {
const target = event.type === 0 /* Regular */ ? event.targetOrPhase : null;
const phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null;
if (event.keySpan === undefined) {
throw new Error(`Unexpected state: keySpan must be defined for bound event but was not for ${event.name}: ${event.sourceSpan}`);
}
return new BoundEvent(event.name, event.type, event.handler, target, phase, event.sourceSpan, event.handlerSpan, event.keySpan);
}
visit(visitor) {
return visitor.visitBoundEvent(this);
}
}
class Element {
constructor(name, attributes, inputs, outputs, children, references, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
this.name = name;
this.attributes = attributes;
this.inputs = inputs;
this.outputs = outputs;
this.children = children;
this.references = references;
this.sourceSpan = sourceSpan;
this.startSourceSpan = startSourceSpan;
this.endSourceSpan = endSourceSpan;
this.i18n = i18n;
}
visit(visitor) {
return visitor.visitElement(this);
}
}
class Template {
constructor(tagName, attributes, inputs, outputs, templateAttrs, children, references, variables, sourceSpan, startSourceSpan, endSourceSpan, i18n) {
this.tagName = tagName;
this.attributes = attributes;
this.inputs = inputs;
this.outputs = outputs;
this.templateAttrs = templateAttrs;
this.children = children;
this.references = references;
this.variables = variables;
this.sourceSpan = sourceSpan;
this.startSourceSpan = startSourceSpan;
this.endSourceSpan = endSourceSpan;
this.i18n = i18n;
}
visit(visitor) {
return visitor.visitTemplate(this);
}
}
class Content {
constructor(selector, attributes, sourceSpan, i18n) {
this.selector = selector;
this.attributes = attributes;
this.sourceSpan = sourceSpan;
this.i18n = i18n;
this.name = 'ng-content';
}
visit(visitor) {
return visitor.visitContent(this);
}
}
class Variable {
constructor(name, value, sourceSpan, keySpan, valueSpan) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
this.keySpan = keySpan;
this.valueSpan = valueSpan;
}
visit(visitor) {
return visitor.visitVariable(this);
}
}
class Reference {
constructor(name, value, sourceSpan, keySpan, valueSpan) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
this.keySpan = keySpan;
this.valueSpan = valueSpan;
}
visit(visitor) {
return visitor.visitReference(this);
}
}
class Icu {
constructor(vars, placeholders, sourceSpan, i18n) {
this.vars = vars;
this.placeholders = placeholders;
this.sourceSpan = sourceSpan;
this.i18n = i18n;
}
visit(visitor) {
return visitor.visitIcu(this);
}
}
class NullVisitor {
visitElement(element) { }
visitTemplate(template) { }
visitContent(content) { }
visitVariable(variable) { }
visitReference(reference) { }
visitTextAttribute(attribute) { }
visitBoundAttribute(attribute) { }
visitBoundEvent(attribute) { }
visitText(text) { }
visitBoundText(text) { }
visitIcu(icu) { }
}
class RecursiveVisitor {
visitElement(element) {
visitAll(this, element.attributes);
visitAll(this, element.children);
visitAll(this, element.references);
}
visitTemplate(template) {
visitAll(this, template.attributes);
visitAll(this, template.children);
visitAll(this, template.references);
visitAll(this, template.variables);
}
visitContent(content) { }
visitVariable(variable) { }
visitReference(reference) { }
visitTextAttribute(attribute) { }
visitBoundAttribute(attribute) { }
visitBoundEvent(attribute) { }
visitText(text) { }
visitBoundText(text) { }
visitIcu(icu) { }
}
class TransformVisitor {
visitElement(element) {
const newAttributes = transformAll(this, element.attributes);
const newInputs = transformAll(this, element.inputs);
const newOutputs = transformAll(this, element.outputs);
const newChildren = transformAll(this, element.children);
const newReferences = transformAll(this, element.references);
if (newAttributes != element.attributes || newInputs != element.inputs ||
newOutputs != element.outputs || newChildren != element.children ||
newReferences != element.references) {
return new Element(element.name, newAttributes, newInputs, newOutputs, newChildren, newReferences, element.sourceSpan, element.startSourceSpan, element.endSourceSpan);
}
return element;
}
visitTemplate(template) {
const newAttributes = transformAll(this, template.attributes);
const newInputs = transformAll(this, template.inputs);
const newOutputs = transformAll(this, template.outputs);
const newTemplateAttrs = transformAll(this, template.templateAttrs);
const newChildren = transformAll(this, template.children);
const newReferences = transformAll(this, template.references);
const newVariables = transformAll(this, template.variables);
if (newAttributes != template.attributes || newInputs != template.inputs ||
newOutputs != template.outputs || newTemplateAttrs != template.templateAttrs ||
newChildren != template.children || newReferences != template.references ||
newVariables != template.variables) {
return new Template(template.tagName, newAttributes, newInputs, newOutputs, newTemplateAttrs, newChildren, newReferences, newVariables, template.sourceSpan, template.startSourceSpan, template.endSourceSpan);
}
return template;
}
visitContent(content) {
return content;
}
visitVariable(variable) {
return variable;
}
visitReference(reference) {
return reference;
}
visitTextAttribute(attribute) {
return attribute;
}
visitBoundAttribute(attribute) {
return attribute;
}
visitBoundEvent(attribute) {
return attribute;
}
visitText(text) {
return text;
}
visitBoundText(text) {
return text;
}
visitIcu(icu) {
return icu;
}
}
function visitAll(visitor, nodes) {
const result = [];
if (visitor.visit) {
for (const node of nodes) {
const newNode = visitor.visit(node) || node.visit(visitor);
}
}
else {
for (const node of nodes) {
const newNode = node.visit(visitor);
if (newNode) {
result.push(newNode);
}
}
}
return result;
}
function transformAll(visitor, nodes) {
const result = [];
let changed = false;
for (const node of nodes) {
const newNode = node.visit(visitor);
if (newNode) {
result.push(newNode);
}
changed = changed || newNode != node;
}
return changed ? result : nodes;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class Message {
/**
* @param nodes message AST
* @param placeholders maps placeholder names to static content and their source spans
* @param placeholderToMessage maps placeholder names to messages (used for nested ICU messages)
* @param meaning
* @param description
* @param customId
*/
constructor(nodes, placeholders, placeholderToMessage, meaning, description, customId) {
this.nodes = nodes;
this.placeholders = placeholders;
this.placeholderToMessage = placeholderToMessage;
this.meaning = meaning;
this.description = description;
this.customId = customId;
this.id = this.customId;
/** The ids to use if there are no custom id and if `i18nLegacyMessageIdFormat` is not empty */
this.legacyIds = [];
if (nodes.length) {
this.sources = [{
filePath: nodes[0].sourceSpan.start.file.url,
startLine: nodes[0].sourceSpan.start.line + 1,
startCol: nodes[0].sourceSpan.start.col + 1,
endLine: nodes[nodes.length - 1].sourceSpan.end.line + 1,
endCol: nodes[0].sourceSpan.start.col + 1
}];
}
else {
this.sources = [];
}
}
}
class Text$1 {
constructor(value, sourceSpan) {
this.value = value;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitText(this, context);
}
}
// TODO(vicb): do we really need this node (vs an array) ?
class Container {
constructor(children, sourceSpan) {
this.children = children;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitContainer(this, context);
}
}
class Icu$1 {
constructor(expression, type, cases, sourceSpan) {
this.expression = expression;
this.type = type;
this.cases = cases;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitIcu(this, context);
}
}
class TagPlaceholder {
constructor(tag, attrs, startName, closeName, children, isVoid,
// TODO sourceSpan should cover all (we need a startSourceSpan and endSourceSpan)
sourceSpan, startSourceSpan, endSourceSpan) {
this.tag = tag;
this.attrs = attrs;
this.startName = startName;
this.closeName = closeName;
this.children = children;
this.isVoid = isVoid;
this.sourceSpan = sourceSpan;
this.startSourceSpan = startSourceSpan;
this.endSourceSpan = endSourceSpan;
}
visit(visitor, context) {
return visitor.visitTagPlaceholder(this, context);
}
}
class Placeholder {
constructor(value, name, sourceSpan) {
this.value = value;
this.name = name;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitPlaceholder(this, context);
}
}
class IcuPlaceholder {
constructor(value, name, sourceSpan) {
this.value = value;
this.name = name;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitIcuPlaceholder(this, context);
}
}
// Clone the AST
class CloneVisitor {
visitText(text, context) {
return new Text$1(text.value, text.sourceSpan);
}
visitContainer(container, context) {
const children = container.children.map(n => n.visit(this, context));
return new Container(children, container.sourceSpan);
}
visitIcu(icu, context) {
const cases = {};
Object.keys(icu.cases).forEach(key => cases[key] = icu.cases[key].visit(this, context));
const msg = new Icu$1(icu.expression, icu.type, cases, icu.sourceSpan);
msg.expressionPlaceholder = icu.expressionPlaceholder;
return msg;
}
visitTagPlaceholder(ph, context) {
const children = ph.children.map(n => n.visit(this, context));
return new TagPlaceholder(ph.tag, ph.attrs, ph.startName, ph.closeName, children, ph.isVoid, ph.sourceSpan, ph.startSourceSpan, ph.endSourceSpan);
}
visitPlaceholder(ph, context) {
return new Placeholder(ph.value, ph.name, ph.sourceSpan);
}
visitIcuPlaceholder(ph, context) {
return new IcuPlaceholder(ph.value, ph.name, ph.sourceSpan);
}
}
// Visit all the nodes recursively
class RecurseVisitor {
visitText(text, context) { }
visitContainer(container, context) {
container.children.forEach(child => child.visit(this));
}
visitIcu(icu, context) {
Object.keys(icu.cases).forEach(k => {
icu.cases[k].visit(this);
});
}
visitTagPlaceholder(ph, context) {
ph.children.forEach(child => child.visit(this));
}
visitPlaceholder(ph, context) { }
visitIcuPlaceholder(ph, context) { }
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Represents a big integer using a buffer of its individual digits, with the least significant
* digit stored at the beginning of the array (little endian).
*
* For performance reasons, each instance is mutable. The addition operation can be done in-place
* to reduce memory pressure of allocation for the digits array.
*/
class BigInteger {
/**
* Creates a big integer using its individual digits in little endian storage.
*/
constructor(digits) {
this.digits = digits;
}
static zero() {
return new BigInteger([0]);
}
static one() {
return new BigInteger([1]);
}
/**
* Creates a clone of this instance.
*/
clone() {
return new BigInteger(this.digits.slice());
}
/**
* Returns a new big integer with the sum of `this` and `other` as its value. This does not mutate
* `this` but instead returns a new instance, unlike `addToSelf`.
*/
add(other) {
const result = this.clone();
result.addToSelf(other);
return result;
}
/**
* Adds `other` to the instance itself, thereby mutating its value.
*/
addToSelf(other) {
const maxNrOfDigits = Math.max(this.digits.length, other.digits.length);
let carry = 0;
for (let i = 0; i < maxNrOfDigits; i++) {
let digitSum = carry;
if (i < this.digits.length) {
digitSum += this.digits[i];
}
if (i < other.digits.length) {
digitSum += other.digits[i];
}
if (digitSum >= 10) {
this.digits[i] = digitSum - 10;
carry = 1;
}
else {
this.digits[i] = digitSum;
carry = 0;
}
}
// Apply a remaining carry if needed.
if (carry > 0) {
this.digits[maxNrOfDigits] = 1;
}
}
/**
* Builds the decimal string representation of the big integer. As this is stored in
* little endian, the digits are concatenated in reverse order.
*/
toString() {
let res = '';
for (let i = this.digits.length - 1; i >= 0; i--) {
res += this.digits[i];
}
return res;
}
}
/**
* Represents a big integer which is optimized for multiplication operations, as its power-of-twos
* are memoized. See `multiplyBy()` for details on the multiplication algorithm.
*/
class BigIntForMultiplication {
constructor(value) {
this.powerOfTwos = [value];
}
/**
* Returns the big integer itself.
*/
getValue() {
return this.powerOfTwos[0];
}
/**
* Computes the value for `num * b`, where `num` is a JS number and `b` is a big integer. The
* value for `b` is represented by a storage model that is optimized for this computation.
*
* This operation is implemented in N(log2(num)) by continuous halving of the number, where the
* least-significant bit (LSB) is tested in each iteration. If the bit is set, the bit's index is
* used as exponent into the power-of-two multiplication of `b`.
*
* As an example, consider the multiplication num=42, b=1337. In binary 42 is 0b00101010 and the
* algorithm unrolls into the following iterations:
*
* Iteration | num | LSB | b * 2^iter | Add? | product
* -----------|------------|------|------------|------|--------
* 0 | 0b00101010 | 0 | 1337 | No | 0
* 1 | 0b00010101 | 1 | 2674 | Yes | 2674
* 2 | 0b00001010 | 0 | 5348 | No | 2674
* 3 | 0b00000101 | 1 | 10696 | Yes | 13370
* 4 | 0b00000010 | 0 | 21392 | No | 13370
* 5 | 0b00000001 | 1 | 42784 | Yes | 56154
* 6 | 0b00000000 | 0 | 85568 | No | 56154
*
* The computed product of 56154 is indeed the correct result.
*
* The `BigIntForMultiplication` representation for a big integer provides memoized access to the
* power-of-two values to reduce the workload in computing those values.
*/
multiplyBy(num) {
const product = BigInteger.zero();
this.multiplyByAndAddTo(num, product);
return product;
}
/**
* See `multiplyBy()` for details. This function allows for the computed product to be added
* directly to the provided result big integer.
*/
multiplyByAndAddTo(num, result) {
for (let exponent = 0; num !== 0; num = num >>> 1, exponent++) {
if (num & 1) {
const value = this.getMultipliedByPowerOfTwo(exponent);
result.addToSelf(value);
}
}
}
/**
* Computes and memoizes the big integer value for `this.number * 2^exponent`.
*/
getMultipliedByPowerOfTwo(exponent) {
// Compute the powers up until the requested exponent, where each value is computed from its
// predecessor. This is simple as `this.number * 2^(exponent - 1)` only has to be doubled (i.e.
// added to itself) to reach `this.number * 2^exponent`.
for (let i = this.powerOfTwos.length; i <= exponent; i++) {
const previousPower = this.powerOfTwos[i - 1];
this.powerOfTwos[i] = previousPower.add(previousPower);
}
return this.powerOfTwos[exponent];
}
}
/**
* Represents an exponentiation operation for the provided base, of which exponents are computed and
* memoized. The results are represented by a `BigIntForMultiplication` which is tailored for
* multiplication operations by memoizing the power-of-twos. This effectively results in a matrix
* representation that is lazily computed upon request.
*/
class BigIntExponentiation {
constructor(base) {
this.base = base;
this.exponents = [new BigIntForMultiplication(BigInteger.one())];
}
/**
* Compute the value for `this.base^exponent`, resulting in a big integer that is optimized for
* further multiplication operations.
*/
toThePowerOf(exponent) {
// Compute the results up until the requested exponent, where every value is computed from its
// predecessor. This is because `this.base^(exponent - 1)` only has to be multiplied by `base`
// to reach `this.base^exponent`.
for (let i = this.exponents.length; i <= exponent; i++) {
const value = this.exponents[i - 1].multiplyBy(this.base);
this.exponents[i] = new BigIntForMultiplication(value);
}
return this.exponents[exponent];
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Return the message id or compute it using the XLIFF1 digest.
*/
function digest(message) {
return message.id || computeDigest(message);
}
/**
* Compute the message id using the XLIFF1 digest.
*/
function computeDigest(message) {
return sha1(serializeNodes(message.nodes).join('') + `[${message.meaning}]`);
}
/**
* Return the message id or compute it using the XLIFF2/XMB/$localize digest.
*/
function decimalDigest(message) {
return message.id || computeDecimalDigest(message);
}
/**
* Compute the message id using the XLIFF2/XMB/$localize digest.
*/
function computeDecimalDigest(message) {
const visitor = new _SerializerIgnoreIcuExpVisitor();
const parts = message.nodes.map(a => a.visit(visitor, null));
return computeMsgId(parts.join(''), message.meaning);
}
/**
* Serialize the i18n ast to something xml-like in order to generate an UID.
*
* The visitor is also used in the i18n parser tests
*
* @internal
*/
class _SerializerVisitor {
visitText(text, context) {
return text.value;
}
visitContainer(container, context) {
return `[${container.children.map(child => child.visit(this)).join(', ')}]`;
}
visitIcu(icu, context) {
const strCases = Object.keys(icu.cases).map((k) => `${k} {${icu.cases[k].visit(this)}}`);
return `{${icu.expression}, ${icu.type}, ${strCases.join(', ')}}`;
}
visitTagPlaceholder(ph, context) {
return ph.isVoid ?
`<ph tag name="${ph.startName}"/>` :
`<ph tag name="${ph.startName}">${ph.children.map(child => child.visit(this)).join(', ')}</ph name="${ph.closeName}">`;
}
visitPlaceholder(ph, context) {
return ph.value ? `<ph name="${ph.name}">${ph.value}</ph>` : `<ph name="${ph.name}"/>`;
}
visitIcuPlaceholder(ph, context) {
return `<ph icu name="${ph.name}">${ph.value.visit(this)}</ph>`;
}
}
const serializerVisitor = new _SerializerVisitor();
function serializeNodes(nodes) {
return nodes.map(a => a.visit(serializerVisitor, null));
}
/**
* Serialize the i18n ast to something xml-like in order to generate an UID.
*
* Ignore the ICU expressions so that message IDs stays identical if only the expression changes.
*
* @internal
*/
class _SerializerIgnoreIcuExpVisitor extends _SerializerVisitor {
visitIcu(icu, context) {
let strCases = Object.keys(icu.cases).map((k) => `${k} {${icu.cases[k].visit(this)}}`);
// Do not take the expression into account
return `{${icu.type}, ${strCases.join(', ')}}`;
}
}
/**
* Compute the SHA1 of the given string
*
* see https://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf
*
* WARNING: this function has not been designed not tested with security in mind.
* DO NOT USE IT IN A SECURITY SENSITIVE CONTEXT.
*/
function sha1(str) {
const utf8 = utf8Encode(str);
const words32 = bytesToWords32(utf8, Endian.Big);
const len = utf8.length * 8;
const w = newArray(80);
let a = 0x67452301, b = 0xefcdab89, c = 0x98badcfe, d = 0x10325476, e = 0xc3d2e1f0;
words32[len >> 5] |= 0x80 << (24 - len % 32);
words32[((len + 64 >> 9) << 4) + 15] = len;
for (let i = 0; i < words32.length; i += 16) {
const h0 = a, h1 = b, h2 = c, h3 = d, h4 = e;
for (let j = 0; j < 80; j++) {
if (j < 16) {
w[j] = words32[i + j];
}
else {
w[j] = rol32(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
}
const fkVal = fk(j, b, c, d);
const f = fkVal[0];
const k = fkVal[1];
const temp = [rol32(a, 5), f, e, k, w[j]].reduce(add32);
e = d;
d = c;
c = rol32(b, 30);
b = a;
a = temp;
}
a = add32(a, h0);
b = add32(b, h1);
c = add32(c, h2);
d = add32(d, h3);
e = add32(e, h4);
}
return bytesToHexString(words32ToByteString([a, b, c, d, e]));
}
function fk(index, b, c, d) {
if (index < 20) {
return [(b & c) | (~b & d), 0x5a827999];
}
if (index < 40) {
return [b ^ c ^ d, 0x6ed9eba1];
}
if (index < 60) {
return [(b & c) | (b & d) | (c & d), 0x8f1bbcdc];
}
return [b ^ c ^ d, 0xca62c1d6];
}
/**
* Compute the fingerprint of the given string
*
* The output is 64 bit number encoded as a decimal string
*
* based on:
* https://github.com/google/closure-compiler/blob/master/src/com/google/javascript/jscomp/GoogleJsMessageIdGenerator.java
*/
function fingerprint(str) {
const utf8 = utf8Encode(str);
let hi = hash32(utf8, 0);
let lo = hash32(utf8, 102072);
if (hi == 0 && (lo == 0 || lo == 1)) {
hi = hi ^ 0x130f9bef;
lo = lo ^ -0x6b5f56d8;
}
return [hi, lo];
}
function computeMsgId(msg, meaning = '') {
let msgFingerprint = fingerprint(msg);
if (meaning) {
const meaningFingerprint = fingerprint(meaning);
msgFingerprint = add64(rol64(msgFingerprint, 1), meaningFingerprint);
}
const hi = msgFingerprint[0];
const lo = msgFingerprint[1];
return wordsToDecimalString(hi & 0x7fffffff, lo);
}
function hash32(bytes, c) {
let a = 0x9e3779b9, b = 0x9e3779b9;
let i;
const len = bytes.length;
for (i = 0; i + 12 <= len; i += 12) {
a = add32(a, wordAt(bytes, i, Endian.Little));
b = add32(b, wordAt(bytes, i + 4, Endian.Little));
c = add32(c, wordAt(bytes, i + 8, Endian.Little));
const res = mix(a, b, c);
a = res[0], b = res[1], c = res[2];
}
a = add32(a, wordAt(bytes, i, Endian.Little));
b = add32(b, wordAt(bytes, i + 4, Endian.Little));
// the first byte of c is reserved for the length
c = add32(c, len);
c = add32(c, wordAt(bytes, i + 8, Endian.Little) << 8);
return mix(a, b, c)[2];
}
// clang-format off
function mix(a, b, c) {
a = sub32(a, b);
a = sub32(a, c);
a ^= c >>> 13;
b = sub32(b, c);
b = sub32(b, a);
b ^= a << 8;
c = sub32(c, a);
c = sub32(c, b);
c ^= b >>> 13;
a = sub32(a, b);
a = sub32(a, c);
a ^= c >>> 12;
b = sub32(b, c);
b = sub32(b, a);
b ^= a << 16;
c = sub32(c, a);
c = sub32(c, b);
c ^= b >>> 5;
a = sub32(a, b);
a = sub32(a, c);
a ^= c >>> 3;
b = sub32(b, c);
b = sub32(b, a);
b ^= a << 10;
c = sub32(c, a);
c = sub32(c, b);
c ^= b >>> 15;
return [a, b, c];
}
// clang-format on
// Utils
var Endian;
(function (Endian) {
Endian[Endian["Little"] = 0] = "Little";
Endian[Endian["Big"] = 1] = "Big";
})(Endian || (Endian = {}));
function add32(a, b) {
return add32to64(a, b)[1];
}
function add32to64(a, b) {
const low = (a & 0xffff) + (b & 0xffff);
const high = (a >>> 16) + (b >>> 16) + (low >>> 16);
return [high >>> 16, (high << 16) | (low & 0xffff)];
}
function add64(a, b) {
const ah = a[0], al = a[1];
const bh = b[0], bl = b[1];
const result = add32to64(al, bl);
const carry = result[0];
const l = result[1];
const h = add32(add32(ah, bh), carry);
return [h, l];
}
function sub32(a, b) {
const low = (a & 0xffff) - (b & 0xffff);
const high = (a >> 16) - (b >> 16) + (low >> 16);
return (high << 16) | (low & 0xffff);
}
// Rotate a 32b number left `count` position
function rol32(a, count) {
return (a << count) | (a >>> (32 - count));
}
// Rotate a 64b number left `count` position
function rol64(num, count) {
const hi = num[0], lo = num[1];
const h = (hi << count) | (lo >>> (32 - count));
const l = (lo << count) | (hi >>> (32 - count));
return [h, l];
}
function bytesToWords32(bytes, endian) {
const size = (bytes.length + 3) >>> 2;
const words32 = [];
for (let i = 0; i < size; i++) {
words32[i] = wordAt(bytes, i * 4, endian);
}
return words32;
}
function byteAt(bytes, index) {
return index >= bytes.length ? 0 : bytes[index];
}
function wordAt(bytes, index, endian) {
let word = 0;
if (endian === Endian.Big) {
for (let i = 0; i < 4; i++) {
word += byteAt(bytes, index + i) << (24 - 8 * i);
}
}
else {
for (let i = 0; i < 4; i++) {
word += byteAt(bytes, index + i) << 8 * i;
}
}
return word;
}
function words32ToByteString(words32) {
return words32.reduce((bytes, word) => bytes.concat(word32ToByteString(word)), []);
}
function word32ToByteString(word) {
let bytes = [];
for (let i = 0; i < 4; i++) {
bytes.push((word >>> 8 * (3 - i)) & 0xff);
}
return bytes;
}
function bytesToHexString(bytes) {
let hex = '';
for (let i = 0; i < bytes.length; i++) {
const b = byteAt(bytes, i);
hex += (b >>> 4).toString(16) + (b & 0x0f).toString(16);
}
return hex.toLowerCase();
}
/**
* Create a shared exponentiation pool for base-256 computations. This shared pool provides memoized
* power-of-256 results with memoized power-of-two computations for efficient multiplication.
*
* For our purposes, this can be safely stored as a global without memory concerns. The reason is
* that we encode two words, so only need the 0th (for the low word) and 4th (for the high word)
* exponent.
*/
const base256 = new BigIntExponentiation(256);
/**
* Represents two 32-bit words as a single decimal number. This requires a big integer storage
* model as JS numbers are not accurate enough to represent the 64-bit number.
*
* Based on https://www.danvk.org/hex2dec.html
*/
function wordsToDecimalString(hi, lo) {
// Encode the four bytes in lo in the lower digits of the decimal number.
// Note: the multiplication results in lo itself but represented by a big integer using its
// decimal digits.
const decimal = base256.toThePowerOf(0).multiplyBy(lo);
// Encode the four bytes in hi above the four lo bytes. lo is a maximum of (2^8)^4, which is why
// this multiplication factor is applied.
base256.toThePowerOf(4).multiplyByAndAddTo(hi, decimal);
return decimal.toString();
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class Serializer {
// Creates a name mapper, see `PlaceholderMapper`
// Returning `null` means that no name mapping is used.
createNameMapper(message) {
return null;
}
}
/**
* A simple mapper that take a function to transform an internal name to a public name
*/
class SimplePlaceholderMapper extends RecurseVisitor {
// create a mapping from the message
constructor(message, mapName) {
super();
this.mapName = mapName;
this.internalToPublic = {};
this.publicToNextId = {};
this.publicToInternal = {};
message.nodes.forEach(node => node.visit(this));
}
toPublicName(internalName) {
return this.internalToPublic.hasOwnProperty(internalName) ?
this.internalToPublic[internalName] :
null;
}
toInternalName(publicName) {
return this.publicToInternal.hasOwnProperty(publicName) ? this.publicToInternal[publicName] :
null;
}
visitText(text, context) {
return null;
}
visitTagPlaceholder(ph, context) {
this.visitPlaceholderName(ph.startName);
super.visitTagPlaceholder(ph, context);
this.visitPlaceholderName(ph.closeName);
}
visitPlaceholder(ph, context) {
this.visitPlaceholderName(ph.name);
}
visitIcuPlaceholder(ph, context) {
this.visitPlaceholderName(ph.name);
}
// XMB placeholders could only contains A-Z, 0-9 and _
visitPlaceholderName(internalName) {
if (!internalName || this.internalToPublic.hasOwnProperty(internalName)) {
return;
}
let publicName = this.mapName(internalName);
if (this.publicToInternal.hasOwnProperty(publicName)) {
// Create a new XMB when it has already been used
const 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;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class _Visitor {
visitTag(tag) {
const strAttrs = this._serializeAttributes(tag.attrs);
if (tag.children.length == 0) {
return `<${tag.name}${strAttrs}/>`;
}
const strChildren = tag.children.map(node => node.visit(this));
return `<${tag.name}${strAttrs}>${strChildren.join('')}</${tag.name}>`;
}
visitText(text) {
return text.value;
}
visitDeclaration(decl) {
return `<?xml${this._serializeAttributes(decl.attrs)} ?>`;
}
_serializeAttributes(attrs) {
const strAttrs = Object.keys(attrs).map((name) => `${name}="${attrs[name]}"`).join(' ');
return strAttrs.length > 0 ? ' ' + strAttrs : '';
}
visitDoctype(doctype) {
return `<!DOCTYPE ${doctype.rootTag} [\n${doctype.dtd}\n]>`;
}
}
const _visitor = new _Visitor();
function serialize(nodes) {
return nodes.map((node) => node.visit(_visitor)).join('');
}
class Declaration {
constructor(unescapedAttrs) {
this.attrs = {};
Object.keys(unescapedAttrs).forEach((k) => {
this.attrs[k] = escapeXml(unescapedAttrs[k]);
});
}
visit(visitor) {
return visitor.visitDeclaration(this);
}
}
class Doctype {
constructor(rootTag, dtd) {
this.rootTag = rootTag;
this.dtd = dtd;
}
visit(visitor) {
return visitor.visitDoctype(this);
}
}
class Tag {
constructor(name, unescapedAttrs = {}, children = []) {
this.name = name;
this.children = children;
this.attrs = {};
Object.keys(unescapedAttrs).forEach((k) => {
this.attrs[k] = escapeXml(unescapedAttrs[k]);
});
}
visit(visitor) {
return visitor.visitTag(this);
}
}
class Text$2 {
constructor(unescapedValue) {
this.value = escapeXml(unescapedValue);
}
visit(visitor) {
return visitor.visitText(this);
}
}
class CR extends Text$2 {
constructor(ws = 0) {
super(`\n${new Array(ws + 1).join(' ')}`);
}
}
const _ESCAPED_CHARS = [
[/&/g, '&amp;'],
[/"/g, '&quot;'],
[/'/g, '&apos;'],
[/</g, '&lt;'],
[/>/g, '&gt;'],
];
// Escape `_ESCAPED_CHARS` characters in the given text with encoded entities
function escapeXml(text) {
return _ESCAPED_CHARS.reduce((text, entry) => text.replace(entry[0], entry[1]), text);
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const _MESSAGES_TAG = 'messagebundle';
const _MESSAGE_TAG = 'msg';
const _PLACEHOLDER_TAG = 'ph';
const _EXAMPLE_TAG = 'ex';
const _SOURCE_TAG = 'source';
const _DOCTYPE = `<!ELEMENT messagebundle (msg)*>
<!ATTLIST messagebundle class CDATA #IMPLIED>
<!ELEMENT msg (#PCDATA|ph|source)*>
<!ATTLIST msg id CDATA #IMPLIED>
<!ATTLIST msg seq CDATA #IMPLIED>
<!ATTLIST msg name CDATA #IMPLIED>
<!ATTLIST msg desc CDATA #IMPLIED>
<!ATTLIST msg meaning CDATA #IMPLIED>
<!ATTLIST msg obsolete (obsolete) #IMPLIED>
<!ATTLIST msg xml:space (default|preserve) "default">
<!ATTLIST msg is_hidden CDATA #IMPLIED>
<!ELEMENT source (#PCDATA)>
<!ELEMENT ph (#PCDATA|ex)*>
<!ATTLIST ph name CDATA #REQUIRED>
<!ELEMENT ex (#PCDATA)>`;
class Xmb extends Serializer {
write(messages, locale) {
const exampleVisitor = new ExampleVisitor();
const visitor = new _Visitor$1();
let rootNode = new Tag(_MESSAGES_TAG);
messages.forEach(message => {
const attrs = { id: message.id };
if (message.description) {
attrs['desc'] = message.description;
}
if (message.meaning) {
attrs['meaning'] = message.meaning;
}
let sourceTags = [];
message.sources.forEach((source) => {
sourceTags.push(new Tag(_SOURCE_TAG, {}, [new Text$2(`${source.filePath}:${source.startLine}${source.endLine !== source.startLine ? ',' + source.endLine : ''}`)]));
});
rootNode.children.push(new CR(2), new Tag(_MESSAGE_TAG, attrs, [...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(),
]);
}
load(content, url) {
throw new Error('Unsupported');
}
digest(message) {
return digest$1(message);
}
createNameMapper(message) {
return new SimplePlaceholderMapper(message, toPublicName);
}
}
class _Visitor$1 {
visitText(text, context) {
return [new Text$2(text.value)];
}
visitContainer(container, context) {
const nodes = [];
container.children.forEach((node) => nodes.push(...node.visit(this)));
return nodes;
}
visitIcu(icu, context) {
const nodes = [new Text$2(`{${icu.expressionPlaceholder}, ${icu.type}, `)];
Object.keys(icu.cases).forEach((c) => {
nodes.push(new Text$2(`${c} {`), ...icu.cases[c].visit(this), new Text$2(`} `));
});
nodes.push(new Text$2(`}`));
return nodes;
}
visitTagPlaceholder(ph, context) {
const startTagAsText = new Text$2(`<${ph.tag}>`);
const startEx = new Tag(_EXAMPLE_TAG, {}, [startTagAsText]);
// TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
const startTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.startName }, [startEx, startTagAsText]);
if (ph.isVoid) {
// void tags have no children nor closing tags
return [startTagPh];
}
const closeTagAsText = new Text$2(`</${ph.tag}>`);
const closeEx = new Tag(_EXAMPLE_TAG, {}, [closeTagAsText]);
// TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
const closeTagPh = new Tag(_PLACEHOLDER_TAG, { name: ph.closeName }, [closeEx, closeTagAsText]);
return [startTagPh, ...this.serialize(ph.children), closeTagPh];
}
visitPlaceholder(ph, context) {
const interpolationAsText = new Text$2(`{{${ph.value}}}`);
// Example tag needs to be not-empty for TC.
const exTag = new Tag(_EXAMPLE_TAG, {}, [interpolationAsText]);
return [
// TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, interpolationAsText])
];
}
visitIcuPlaceholder(ph, context) {
const icuExpression = ph.value.expression;
const icuType = ph.value.type;
const icuCases = Object.keys(ph.value.cases).map((value) => value + ' {...}').join(' ');
const icuAsText = new Text$2(`{${icuExpression}, ${icuType}, ${icuCases}}`);
const exTag = new Tag(_EXAMPLE_TAG, {}, [icuAsText]);
return [
// TC requires PH to have a non empty EX, and uses the text node to show the "original" value.
new Tag(_PLACEHOLDER_TAG, { name: ph.name }, [exTag, icuAsText])
];
}
serialize(nodes) {
return [].concat(...nodes.map(node => node.visit(this)));
}
}
function digest$1(message) {
return decimalDigest(message);
}
// TC requires at least one non-empty example on placeholders
class ExampleVisitor {
addDefaultExamples(node) {
node.visit(this);
return node;
}
visitTag(tag) {
if (tag.name === _PLACEHOLDER_TAG) {
if (!tag.children || tag.children.length == 0) {
const exText = new Text$2(tag.attrs['name'] || '...');
tag.children = [new Tag(_EXAMPLE_TAG, {}, [exText])];
}
}
else if (tag.children) {
tag.children.forEach(node => node.visit(this));
}
}
visitText(text) { }
visitDeclaration(decl) { }
visitDoctype(doctype) { }
}
// 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 LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/* Closure variables holding messages must be named `MSG_[A-Z0-9]+` */
const CLOSURE_TRANSLATION_VAR_PREFIX = 'MSG_';
/**
* Prefix for non-`goog.getMsg` i18n-related vars.
* Note: the prefix uses lowercase characters intentionally due to a Closure behavior that
* considers variables like `I18N_0` as constants and throws an error when their value changes.
*/
const TRANSLATION_VAR_PREFIX = 'i18n_';
/** Name of the i18n attributes **/
const I18N_ATTR = 'i18n';
const I18N_ATTR_PREFIX = 'i18n-';
/** Prefix of var expressions used in ICUs */
const I18N_ICU_VAR_PREFIX = 'VAR_';
/** Prefix of ICU expressions for post processing */
const I18N_ICU_MAPPING_PREFIX = 'I18N_EXP_';
/** Placeholder wrapper for i18n expressions **/
const I18N_PLACEHOLDER_SYMBOL = '�';
function isI18nAttribute(name) {
return name === I18N_ATTR || name.startsWith(I18N_ATTR_PREFIX);
}
function isI18nRootNode(meta) {
return meta instanceof Message;
}
function isSingleI18nIcu(meta) {
return isI18nRootNode(meta) && meta.nodes.length === 1 && meta.nodes[0] instanceof Icu$1;
}
function hasI18nMeta(node) {
return !!node.i18n;
}
function hasI18nAttrs(element) {
return element.attrs.some((attr) => isI18nAttribute(attr.name));
}
function icuFromI18nMessage(message) {
return message.nodes[0];
}
function wrapI18nPlaceholder(content, contextId = 0) {
const blockId = contextId > 0 ? `:${contextId}` : '';
return `${I18N_PLACEHOLDER_SYMBOL}${content}${blockId}${I18N_PLACEHOLDER_SYMBOL}`;
}
function assembleI18nBoundString(strings, bindingStartIndex = 0, contextId = 0) {
if (!strings.length)
return '';
let acc = '';
const lastIdx = strings.length - 1;
for (let i = 0; i < lastIdx; i++) {
acc += `${strings[i]}${wrapI18nPlaceholder(bindingStartIndex + i, contextId)}`;
}
acc += strings[lastIdx];
return acc;
}
function getSeqNumberGenerator(startsAt = 0) {
let current = startsAt;
return () => current++;
}
function placeholdersToParams(placeholders) {
const params = {};
placeholders.forEach((values, key) => {
params[key] = literal(values.length > 1 ? `[${values.join('|')}]` : values[0]);
});
return params;
}
function updatePlaceholderMap(map, name, ...values) {
const current = map.get(name) || [];
current.push(...values);
map.set(name, current);
}
function assembleBoundTextPlaceholders(meta, bindingStartIndex = 0, contextId = 0) {
const startIdx = bindingStartIndex;
const placeholders = new Map();
const node = meta instanceof Message ? meta.nodes.find(node => node instanceof Container) : meta;
if (node) {
node
.children
.filter((child) => child instanceof Placeholder)
.forEach((child, idx) => {
const content = wrapI18nPlaceholder(startIdx + idx, contextId);
updatePlaceholderMap(placeholders, child.name, content);
});
}
return placeholders;
}
/**
* Format the placeholder names in a map of placeholders to expressions.
*
* The placeholder names are converted from "internal" format (e.g. `START_TAG_DIV_1`) to "external"
* format (e.g. `startTagDiv_1`).
*
* @param params A map of placeholder names to expressions.
* @param useCamelCase whether to camelCase the placeholder name when formatting.
* @returns A new map of formatted placeholder names to expressions.
*/
function i18nFormatPlaceholderNames(params = {}, useCamelCase) {
const _params = {};
if (params && Object.keys(params).length) {
Object.keys(params).forEach(key => _params[formatI18nPlaceholderName(key, useCamelCase)] = params[key]);
}
return _params;
}
/**
* Converts internal placeholder names to public-facing format
* (for example to use in goog.getMsg call).
* Example: `START_TAG_DIV_1` is converted to `startTagDiv_1`.
*
* @param name The placeholder name that should be formatted
* @returns Formatted placeholder name
*/
function formatI18nPlaceholderName(name, useCamelCase = true) {
const publicName = toPublicName(name);
if (!useCamelCase) {
return publicName;
}
const chunks = publicName.split('_');
if (chunks.length === 1) {
// if no "_" found - just lowercase the value
return name.toLowerCase();
}
let postfix;
// eject last element if it's a number
if (/^\d+$/.test(chunks[chunks.length - 1])) {
postfix = chunks.pop();
}
let raw = chunks.shift().toLowerCase();
if (chunks.length) {
raw += chunks.map(c => c.charAt(0).toUpperCase() + c.slice(1).toLowerCase()).join('');
}
return postfix ? `${raw}_${postfix}` : raw;
}
/**
* Generates a prefix for translation const name.
*
* @param extra Additional local prefix that should be injected into translation var name
* @returns Complete translation const prefix
*/
function getTranslationConstPrefix(extra) {
return `${CLOSURE_TRANSLATION_VAR_PREFIX}${extra}`.toUpperCase();
}
/**
* Generate AST to declare a variable. E.g. `var I18N_1;`.
* @param variable the name of the variable to declare.
*/
function declareI18nVariable(variable) {
return new DeclareVarStmt(variable.name, undefined, INFERRED_TYPE, undefined, variable.sourceSpan);
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Checks whether an object key contains potentially unsafe chars, thus the key should be wrapped in
* quotes. Note: we do not wrap all keys into quotes, as it may have impact on minification and may
* bot work in some cases when object keys are mangled by minifier.
*
* TODO(FW-1136): this is a temporary solution, we need to come up with a better way of working with
* inputs that contain potentially unsafe chars.
*/
const UNSAFE_OBJECT_KEY_NAME_REGEXP = /[-.]/;
/** Name of the temporary to use during data binding */
const TEMPORARY_NAME = '_t';
/** Name of the context parameter passed into a template function */
const CONTEXT_NAME = 'ctx';
/** Name of the RenderFlag passed into a template function */
const RENDER_FLAGS = 'rf';
/** The prefix reference variables */
const REFERENCE_PREFIX = '_r';
/** The name of the implicit context reference */
const IMPLICIT_REFERENCE = '$implicit';
/** Non bindable attribute name **/
const NON_BINDABLE_ATTR = 'ngNonBindable';
/**
* Creates an allocator for a temporary variable.
*
* A variable declaration is added to the statements the first time the allocator is invoked.
*/
function temporaryAllocator(statements, name) {
let temp = null;
return () => {
if (!temp) {
statements.push(new DeclareVarStmt(TEMPORARY_NAME, undefined, DYNAMIC_TYPE));
temp = variable(name);
}
return temp;
};
}
function unsupported(feature) {
if (this) {
throw new Error(`Builder ${this.constructor.name} doesn't support ${feature} yet`);
}
throw new Error(`Feature ${feature} is not supported yet`);
}
function invalid$1(arg) {
throw new Error(`Invalid state: Visitor ${this.constructor.name} doesn't handle ${arg.constructor.name}`);
}
function asLiteral(value) {
if (Array.isArray(value)) {
return literalArr(value.map(asLiteral));
}
return literal(value, INFERRED_TYPE);
}
function conditionallyCreateMapObjectLiteral(keys, keepDeclared) {
if (Object.getOwnPropertyNames(keys).length > 0) {
return mapToExpression(keys, keepDeclared);
}
return null;
}
function mapToExpression(map, keepDeclared) {
return literalMap(Object.getOwnPropertyNames(map).map(key => {
// canonical syntax: `dirProp: publicProp`
// if there is no `:`, use dirProp = elProp
const value = map[key];
let declaredName;
let publicName;
let minifiedName;
let needsDeclaredName;
if (Array.isArray(value)) {
[publicName, declaredName] = value;
minifiedName = key;
needsDeclaredName = publicName !== declaredName;
}
else {
[declaredName, publicName] = splitAtColon(key, [key, value]);
minifiedName = declaredName;
// Only include the declared name if extracted from the key, i.e. the key contains a colon.
// Otherwise the declared name should be omitted even if it is different from the public name,
// as it may have already been minified.
needsDeclaredName = publicName !== declaredName && key.includes(':');
}
return {
key: minifiedName,
// put quotes around keys that contain potentially unsafe characters
quoted: UNSAFE_OBJECT_KEY_NAME_REGEXP.test(minifiedName),
value: (keepDeclared && needsDeclaredName) ?
literalArr([asLiteral(publicName), asLiteral(declaredName)]) :
asLiteral(publicName)
};
}));
}
/**
* Remove trailing null nodes as they are implied.
*/
function trimTrailingNulls(parameters) {
while (isNull(parameters[parameters.length - 1])) {
parameters.pop();
}
return parameters;
}
function getQueryPredicate(query, constantPool) {
if (Array.isArray(query.predicate)) {
let predicate = [];
query.predicate.forEach((selector) => {
// Each item in predicates array may contain strings with comma-separated refs
// (for ex. 'ref, ref1, ..., refN'), thus we extract individual refs and store them
// as separate array entities
const selectors = selector.split(',').map(token => literal(token.trim()));
predicate.push(...selectors);
});
return constantPool.getConstLiteral(literalArr(predicate), true);
}
else {
return query.predicate;
}
}
/**
* A representation for an object literal used during codegen of definition objects. The generic
* type `T` allows to reference a documented type of the generated structure, such that the
* property names that are set can be resolved to their documented declaration.
*/
class DefinitionMap {
constructor() {
this.values = [];
}
set(key, value) {
if (value) {
this.values.push({ key: key, value, quoted: false });
}
}
toLiteralMap() {
return literalMap(this.values);
}
}
/**
* Extract a map of properties to values for a given element or template node, which can be used
* by the directive matching machinery.
*
* @param elOrTpl the element or template in question
* @return an object set up for directive matching. For attributes on the element/template, this
* object maps a property name to its (static) value. For any bindings, this map simply maps the
* property name to an empty string.
*/
function getAttrsForDirectiveMatching(elOrTpl) {
const attributesMap = {};
if (elOrTpl instanceof Template && elOrTpl.tagName !== 'ng-template') {
elOrTpl.templateAttrs.forEach(a => attributesMap[a.name] = '');
}
else {
elOrTpl.attributes.forEach(a => {
if (!isI18nAttribute(a.name)) {
attributesMap[a.name] = a.value;
}
});
elOrTpl.inputs.forEach(i => {
attributesMap[i.name] = '';
});
elOrTpl.outputs.forEach(o => {
attributesMap[o.name] = '';
});
}
return attributesMap;
}
/** Returns a call expression to a chained instruction, e.g. `property(params[0])(params[1])`. */
function chainedInstruction(reference, calls, span) {
let expression = importExpr(reference, null, span);
if (calls.length > 0) {
for (let i = 0; i < calls.length; i++) {
expression = expression.callFn(calls[i], span);
}
}
else {
// Add a blank invocation, in case the `calls` array is empty.
expression = expression.callFn([], span);
}
return expression;
}
/**
* Gets the number of arguments expected to be passed to a generated instruction in the case of
* interpolation instructions.
* @param interpolation An interpolation ast
*/
function getInterpolationArgsLength(interpolation) {
const { expressions, strings } = interpolation;
if (expressions.length === 1 && strings.length === 2 && strings[0] === '' && strings[1] === '') {
// If the interpolation has one interpolated value, but the prefix and suffix are both empty
// strings, we only pass one argument, to a special instruction like `propertyInterpolate` or
// `textInterpolate`.
return 1;
}
else {
return expressions.length + strings.length;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var R3FactoryDelegateType;
(function (R3FactoryDelegateType) {
R3FactoryDelegateType[R3FactoryDelegateType["Class"] = 0] = "Class";
R3FactoryDelegateType[R3FactoryDelegateType["Function"] = 1] = "Function";
})(R3FactoryDelegateType || (R3FactoryDelegateType = {}));
var R3FactoryTarget;
(function (R3FactoryTarget) {
R3FactoryTarget[R3FactoryTarget["Directive"] = 0] = "Directive";
R3FactoryTarget[R3FactoryTarget["Component"] = 1] = "Component";
R3FactoryTarget[R3FactoryTarget["Injectable"] = 2] = "Injectable";
R3FactoryTarget[R3FactoryTarget["Pipe"] = 3] = "Pipe";
R3FactoryTarget[R3FactoryTarget["NgModule"] = 4] = "NgModule";
})(R3FactoryTarget || (R3FactoryTarget = {}));
/**
* Resolved type of a dependency.
*
* Occasionally, dependencies will have special significance which is known statically. In that
* case the `R3ResolvedDependencyType` informs the factory generator that a particular dependency
* should be generated specially (usually by calling a special injection function instead of the
* standard one).
*/
var R3ResolvedDependencyType;
(function (R3ResolvedDependencyType) {
/**
* A normal token dependency.
*/
R3ResolvedDependencyType[R3ResolvedDependencyType["Token"] = 0] = "Token";
/**
* The dependency is for an attribute.
*
* The token expression is a string representing the attribute name.
*/
R3ResolvedDependencyType[R3ResolvedDependencyType["Attribute"] = 1] = "Attribute";
/**
* Injecting the `ChangeDetectorRef` token. Needs special handling when injected into a pipe.
*/
R3ResolvedDependencyType[R3ResolvedDependencyType["ChangeDetectorRef"] = 2] = "ChangeDetectorRef";
/**
* An invalid dependency (no token could be determined). An error should be thrown at runtime.
*/
R3ResolvedDependencyType[R3ResolvedDependencyType["Invalid"] = 3] = "Invalid";
})(R3ResolvedDependencyType || (R3ResolvedDependencyType = {}));
/**
* Construct a factory function expression for the given `R3FactoryMetadata`.
*/
function compileFactoryFunction(meta) {
const t = variable('t');
const statements = [];
let ctorDepsType = NONE_TYPE;
// The type to instantiate via constructor invocation. If there is no delegated factory, meaning
// this type is always created by constructor invocation, then this is the type-to-create
// parameter provided by the user (t) if specified, or the current type if not. If there is a
// delegated factory (which is used to create the current type) then this is only the type-to-
// create parameter (t).
const typeForCtor = !isDelegatedMetadata(meta) ?
new BinaryOperatorExpr(BinaryOperator.Or, t, meta.internalType) :
t;
let ctorExpr = null;
if (meta.deps !== null) {
// There is a constructor (either explicitly or implicitly defined).
if (meta.deps !== 'invalid') {
ctorExpr = new InstantiateExpr(typeForCtor, injectDependencies(meta.deps, meta.injectFn, meta.target === R3FactoryTarget.Pipe));
ctorDepsType = createCtorDepsType(meta.deps);
}
}
else {
const baseFactory = variable(`ɵ${meta.name}_BaseFactory`);
const getInheritedFactory = importExpr(Identifiers$1.getInheritedFactory);
const baseFactoryStmt = baseFactory
.set(getInheritedFactory.callFn([meta.internalType], /* sourceSpan */ undefined, /* pure */ true))
.toDeclStmt(INFERRED_TYPE, [StmtModifier.Exported, StmtModifier.Final]);
statements.push(baseFactoryStmt);
// There is no constructor, use the base class' factory to construct typeForCtor.
ctorExpr = baseFactory.callFn([typeForCtor]);
}
const ctorExprFinal = ctorExpr;
const body = [];
let retExpr = null;
function makeConditionalFactory(nonCtorExpr) {
const r = variable('r');
body.push(r.set(NULL_EXPR).toDeclStmt());
let ctorStmt = null;
if (ctorExprFinal !== null) {
ctorStmt = r.set(ctorExprFinal).toStmt();
}
else {
ctorStmt = importExpr(Identifiers$1.invalidFactory).callFn([]).toStmt();
}
body.push(ifStmt(t, [ctorStmt], [r.set(nonCtorExpr).toStmt()]));
return r;
}
if (isDelegatedMetadata(meta)) {
// This type is created with a delegated factory. If a type parameter is not specified, call
// the factory instead.
const delegateArgs = injectDependencies(meta.delegateDeps, meta.injectFn, meta.target === R3FactoryTarget.Pipe);
// Either call `new delegate(...)` or `delegate(...)` depending on meta.delegateType.
const factoryExpr = new (meta.delegateType === R3FactoryDelegateType.Class ?
InstantiateExpr :
InvokeFunctionExpr)(meta.delegate, delegateArgs);
retExpr = makeConditionalFactory(factoryExpr);
}
else if (isExpressionFactoryMetadata(meta)) {
// TODO(alxhub): decide whether to lower the value here or in the caller
retExpr = makeConditionalFactory(meta.expression);
}
else {
retExpr = ctorExpr;
}
if (retExpr !== null) {
body.push(new ReturnStatement(retExpr));
}
else {
body.push(importExpr(Identifiers$1.invalidFactory).callFn([]).toStmt());
}
return {
factory: fn([new FnParam('t', DYNAMIC_TYPE)], body, INFERRED_TYPE, undefined, `${meta.name}_Factory`),
statements,
type: expressionType(importExpr(Identifiers$1.FactoryDef, [typeWithParameters(meta.type.type, meta.typeArgumentCount), ctorDepsType]))
};
}
function injectDependencies(deps, injectFn, isPipe) {
return deps.map((dep, index) => compileInjectDependency(dep, injectFn, isPipe, index));
}
function compileInjectDependency(dep, injectFn, isPipe, index) {
// Interpret the dependency according to its resolved type.
switch (dep.resolved) {
case R3ResolvedDependencyType.Token:
case R3ResolvedDependencyType.ChangeDetectorRef:
// Build up the injection flags according to the metadata.
const flags = 0 /* Default */ | (dep.self ? 2 /* Self */ : 0) |
(dep.skipSelf ? 4 /* SkipSelf */ : 0) | (dep.host ? 1 /* Host */ : 0) |
(dep.optional ? 8 /* Optional */ : 0);
// If this dependency is optional or otherwise has non-default flags, then additional
// parameters describing how to inject the dependency must be passed to the inject function
// that's being used.
let flagsParam = (flags !== 0 /* Default */ || dep.optional) ? literal(flags) : null;
// We have a separate instruction for injecting ChangeDetectorRef into a pipe.
if (isPipe && dep.resolved === R3ResolvedDependencyType.ChangeDetectorRef) {
return importExpr(Identifiers$1.injectPipeChangeDetectorRef).callFn(flagsParam ? [flagsParam] : []);
}
// Build up the arguments to the injectFn call.
const injectArgs = [dep.token];
if (flagsParam) {
injectArgs.push(flagsParam);
}
return importExpr(injectFn).callFn(injectArgs);
case R3ResolvedDependencyType.Attribute:
// In the case of attributes, the attribute name in question is given as the token.
return importExpr(Identifiers$1.injectAttribute).callFn([dep.token]);
case R3ResolvedDependencyType.Invalid:
return importExpr(Identifiers$1.invalidFactoryDep).callFn([literal(index)]);
default:
return unsupported(`Unknown R3ResolvedDependencyType: ${R3ResolvedDependencyType[dep.resolved]}`);
}
}
function createCtorDepsType(deps) {
let hasTypes = false;
const attributeTypes = deps.map(dep => {
const type = createCtorDepType(dep);
if (type !== null) {
hasTypes = true;
return type;
}
else {
return literal(null);
}
});
if (hasTypes) {
return expressionType(literalArr(attributeTypes));
}
else {
return NONE_TYPE;
}
}
function createCtorDepType(dep) {
const entries = [];
if (dep.resolved === R3ResolvedDependencyType.Attribute) {
if (dep.attribute !== null) {
entries.push({ key: 'attribute', value: dep.attribute, quoted: false });
}
}
if (dep.optional) {
entries.push({ key: 'optional', value: literal(true), quoted: false });
}
if (dep.host) {
entries.push({ key: 'host', value: literal(true), quoted: false });
}
if (dep.self) {
entries.push({ key: 'self', value: literal(true), quoted: false });
}
if (dep.skipSelf) {
entries.push({ key: 'skipSelf', value: literal(true), quoted: false });
}
return entries.length > 0 ? literalMap(entries) : null;
}
/**
* A helper function useful for extracting `R3DependencyMetadata` from a Render2
* `CompileTypeMetadata` instance.
*/
function dependenciesFromGlobalMetadata(type, outputCtx, reflector) {
// Use the `CompileReflector` to look up references to some well-known Angular types. These will
// be compared with the token to statically determine whether the token has significance to
// Angular, and set the correct `R3ResolvedDependencyType` as a result.
const injectorRef = reflector.resolveExternalReference(Identifiers.Injector);
// Iterate through the type's DI dependencies and produce `R3DependencyMetadata` for each of them.
const deps = [];
for (let dependency of type.diDeps) {
if (dependency.token) {
const tokenRef = tokenReference(dependency.token);
let resolved = dependency.isAttribute ?
R3ResolvedDependencyType.Attribute :
R3ResolvedDependencyType.Token;
// In the case of most dependencies, the token will be a reference to a type. Sometimes,
// however, it can be a string, in the case of older Angular code or @Attribute injection.
const token = tokenRef instanceof StaticSymbol ? outputCtx.importExpr(tokenRef) : literal(tokenRef);
// Construct the dependency.
deps.push({
token,
attribute: null,
resolved,
host: !!dependency.isHost,
optional: !!dependency.isOptional,
self: !!dependency.isSelf,
skipSelf: !!dependency.isSkipSelf,
});
}
else {
unsupported('dependency without a token');
}
}
return deps;
}
function isDelegatedMetadata(meta) {
return meta.delegateType !== undefined;
}
function isExpressionFactoryMetadata(meta) {
return meta.expression !== undefined;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function compileInjectable(meta) {
let result = null;
const factoryMeta = {
name: meta.name,
type: meta.type,
internalType: meta.internalType,
typeArgumentCount: meta.typeArgumentCount,
deps: [],
injectFn: Identifiers.inject,
target: R3FactoryTarget.Injectable,
};
if (meta.useClass !== undefined) {
// meta.useClass has two modes of operation. Either deps are specified, in which case `new` is
// used to instantiate the class with dependencies injected, or deps are not specified and
// the factory of the class is used to instantiate it.
//
// A special case exists for useClass: Type where Type is the injectable type itself and no
// deps are specified, in which case 'useClass' is effectively ignored.
const useClassOnSelf = meta.useClass.isEquivalent(meta.internalType);
let deps = undefined;
if (meta.userDeps !== undefined) {
deps = meta.userDeps;
}
if (deps !== undefined) {
// factory: () => new meta.useClass(...deps)
result = compileFactoryFunction(Object.assign(Object.assign({}, factoryMeta), { delegate: meta.useClass, delegateDeps: deps, delegateType: R3FactoryDelegateType.Class }));
}
else if (useClassOnSelf) {
result = compileFactoryFunction(factoryMeta);
}
else {
result = delegateToFactory(meta.type.value, meta.useClass);
}
}
else if (meta.useFactory !== undefined) {
if (meta.userDeps !== undefined) {
result = compileFactoryFunction(Object.assign(Object.assign({}, factoryMeta), { delegate: meta.useFactory, delegateDeps: meta.userDeps || [], delegateType: R3FactoryDelegateType.Function }));
}
else {
result = {
statements: [],
factory: fn([], [new ReturnStatement(meta.useFactory.callFn([]))])
};
}
}
else if (meta.useValue !== undefined) {
// Note: it's safe to use `meta.useValue` instead of the `USE_VALUE in meta` check used for
// client code because meta.useValue is an Expression which will be defined even if the actual
// value is undefined.
result = compileFactoryFunction(Object.assign(Object.assign({}, factoryMeta), { expression: meta.useValue }));
}
else if (meta.useExisting !== undefined) {
// useExisting is an `inject` call on the existing token.
result = compileFactoryFunction(Object.assign(Object.assign({}, factoryMeta), { expression: importExpr(Identifiers.inject).callFn([meta.useExisting]) }));
}
else {
result = delegateToFactory(meta.type.value, meta.internalType);
}
const token = meta.internalType;
const injectableProps = { token, factory: result.factory };
// Only generate providedIn property if it has a non-null value
if (meta.providedIn.value !== null) {
injectableProps.providedIn = meta.providedIn;
}
const expression = importExpr(Identifiers.ɵɵdefineInjectable).callFn([mapToMapExpression(injectableProps)]);
const type = new ExpressionType(importExpr(Identifiers.InjectableDef, [typeWithParameters(meta.type.type, meta.typeArgumentCount)]));
return {
expression,
type,
statements: result.statements,
};
}
function delegateToFactory(type, internalType) {
return {
statements: [],
// If types are the same, we can generate `factory: type.ɵfac`
// If types are different, we have to generate a wrapper function to ensure
// the internal type has been resolved (`factory: function(t) { return type.ɵfac(t); }`)
factory: type.node === internalType.node ?
internalType.prop('ɵfac') :
fn([new FnParam('t', DYNAMIC_TYPE)], [new ReturnStatement(internalType.callMethod('ɵfac', [variable('t')]))])
};
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function assertArrayOfStrings(identifier, value) {
if (value == null) {
return;
}
if (!Array.isArray(value)) {
throw new Error(`Expected '${identifier}' to be an array of strings.`);
}
for (let i = 0; i < value.length; i += 1) {
if (typeof value[i] !== 'string') {
throw new Error(`Expected '${identifier}' to be an array of strings.`);
}
}
}
const UNUSABLE_INTERPOLATION_REGEXPS = [
/^\s*$/,
/[<>]/,
/^[{}]$/,
/&(#|[a-z])/i,
/^\/\//,
];
function assertInterpolationSymbols(identifier, value) {
if (value != null && !(Array.isArray(value) && value.length == 2)) {
throw new Error(`Expected '${identifier}' to be an array, [start, end].`);
}
else if (value != null) {
const start = value[0];
const end = value[1];
// Check for unusable interpolation symbols
UNUSABLE_INTERPOLATION_REGEXPS.forEach(regexp => {
if (regexp.test(start) || regexp.test(end)) {
throw new Error(`['${start}', '${end}'] contains unusable interpolation symbol.`);
}
});
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class InterpolationConfig {
constructor(start, end) {
this.start = start;
this.end = end;
}
static fromArray(markers) {
if (!markers) {
return DEFAULT_INTERPOLATION_CONFIG;
}
assertInterpolationSymbols('interpolation', markers);
return new InterpolationConfig(markers[0], markers[1]);
}
}
const DEFAULT_INTERPOLATION_CONFIG = new InterpolationConfig('{{', '}}');
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* In TypeScript, tagged template functions expect a "template object", which is an array of
* "cooked" strings plus a `raw` property that contains an array of "raw" strings. This is
* typically constructed with a function called `__makeTemplateObject(cooked, raw)`, but it may not
* be available in all environments.
*
* This is a JavaScript polyfill that uses __makeTemplateObject when it's available, but otherwise
* creates an inline helper with the same functionality.
*
* In the inline function, if `Object.defineProperty` is available we use that to attach the `raw`
* array.
*/
const makeTemplateObjectPolyfill = '(this&&this.__makeTemplateObject||function(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e})';
class AbstractJsEmitterVisitor extends AbstractEmitterVisitor {
constructor() {
super(false);
}
visitDeclareClassStmt(stmt, ctx) {
ctx.pushClass(stmt);
this._visitClassConstructor(stmt, ctx);
if (stmt.parent != null) {
ctx.print(stmt, `${stmt.name}.prototype = Object.create(`);
stmt.parent.visitExpression(this, ctx);
ctx.println(stmt, `.prototype);`);
}
stmt.getters.forEach((getter) => this._visitClassGetter(stmt, getter, ctx));
stmt.methods.forEach((method) => this._visitClassMethod(stmt, method, ctx));
ctx.popClass();
return null;
}
_visitClassConstructor(stmt, ctx) {
ctx.print(stmt, `function ${stmt.name}(`);
if (stmt.constructorMethod != null) {
this._visitParams(stmt.constructorMethod.params, ctx);
}
ctx.println(stmt, `) {`);
ctx.incIndent();
if (stmt.constructorMethod != null) {
if (stmt.constructorMethod.body.length > 0) {
ctx.println(stmt, `var self = this;`);
this.visitAllStatements(stmt.constructorMethod.body, ctx);
}
}
ctx.decIndent();
ctx.println(stmt, `}`);
}
_visitClassGetter(stmt, getter, ctx) {
ctx.println(stmt, `Object.defineProperty(${stmt.name}.prototype, '${getter.name}', { get: function() {`);
ctx.incIndent();
if (getter.body.length > 0) {
ctx.println(stmt, `var self = this;`);
this.visitAllStatements(getter.body, ctx);
}
ctx.decIndent();
ctx.println(stmt, `}});`);
}
_visitClassMethod(stmt, method, ctx) {
ctx.print(stmt, `${stmt.name}.prototype.${method.name} = function(`);
this._visitParams(method.params, ctx);
ctx.println(stmt, `) {`);
ctx.incIndent();
if (method.body.length > 0) {
ctx.println(stmt, `var self = this;`);
this.visitAllStatements(method.body, ctx);
}
ctx.decIndent();
ctx.println(stmt, `};`);
}
visitWrappedNodeExpr(ast, ctx) {
throw new Error('Cannot emit a WrappedNodeExpr in Javascript.');
}
visitReadVarExpr(ast, ctx) {
if (ast.builtin === BuiltinVar.This) {
ctx.print(ast, 'self');
}
else if (ast.builtin === BuiltinVar.Super) {
throw new Error(`'super' needs to be handled at a parent ast node, not at the variable level!`);
}
else {
super.visitReadVarExpr(ast, ctx);
}
return null;
}
visitDeclareVarStmt(stmt, ctx) {
ctx.print(stmt, `var ${stmt.name}`);
if (stmt.value) {
ctx.print(stmt, ' = ');
stmt.value.visitExpression(this, ctx);
}
ctx.println(stmt, `;`);
return null;
}
visitCastExpr(ast, ctx) {
ast.value.visitExpression(this, ctx);
return null;
}
visitInvokeFunctionExpr(expr, ctx) {
const fnExpr = expr.fn;
if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === BuiltinVar.Super) {
ctx.currentClass.parent.visitExpression(this, ctx);
ctx.print(expr, `.call(this`);
if (expr.args.length > 0) {
ctx.print(expr, `, `);
this.visitAllExpressions(expr.args, ctx, ',');
}
ctx.print(expr, `)`);
}
else {
super.visitInvokeFunctionExpr(expr, ctx);
}
return null;
}
visitTaggedTemplateExpr(ast, ctx) {
// The following convoluted piece of code is effectively the downlevelled equivalent of
// ```
// tag`...`
// ```
// which is effectively like:
// ```
// tag(__makeTemplateObject(cooked, raw), expression1, expression2, ...);
// ```
const elements = ast.template.elements;
ast.tag.visitExpression(this, ctx);
ctx.print(ast, `(${makeTemplateObjectPolyfill}(`);
ctx.print(ast, `[${elements.map(part => escapeIdentifier(part.text, false)).join(', ')}], `);
ctx.print(ast, `[${elements.map(part => escapeIdentifier(part.rawText, false)).join(', ')}])`);
ast.template.expressions.forEach(expression => {
ctx.print(ast, ', ');
expression.visitExpression(this, ctx);
});
ctx.print(ast, ')');
return null;
}
visitFunctionExpr(ast, ctx) {
ctx.print(ast, `function${ast.name ? ' ' + ast.name : ''}(`);
this._visitParams(ast.params, ctx);
ctx.println(ast, `) {`);
ctx.incIndent();
this.visitAllStatements(ast.statements, ctx);
ctx.decIndent();
ctx.print(ast, `}`);
return null;
}
visitDeclareFunctionStmt(stmt, ctx) {
ctx.print(stmt, `function ${stmt.name}(`);
this._visitParams(stmt.params, ctx);
ctx.println(stmt, `) {`);
ctx.incIndent();
this.visitAllStatements(stmt.statements, ctx);
ctx.decIndent();
ctx.println(stmt, `}`);
return null;
}
visitTryCatchStmt(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();
const catchStmts = [CATCH_STACK_VAR$1.set(CATCH_ERROR_VAR$1.prop('stack')).toDeclStmt(null, [
StmtModifier.Final
])].concat(stmt.catchStmts);
this.visitAllStatements(catchStmts, ctx);
ctx.decIndent();
ctx.println(stmt, `}`);
return null;
}
visitLocalizedString(ast, ctx) {
// The following convoluted piece of code is effectively the downlevelled equivalent of
// ```
// $localize `...`
// ```
// which is effectively like:
// ```
// $localize(__makeTemplateObject(cooked, raw), expression1, expression2, ...);
// ```
ctx.print(ast, `$localize(${makeTemplateObjectPolyfill}(`);
const parts = [ast.serializeI18nHead()];
for (let i = 1; i < ast.messageParts.length; i++) {
parts.push(ast.serializeI18nTemplatePart(i));
}
ctx.print(ast, `[${parts.map(part => escapeIdentifier(part.cooked, false)).join(', ')}], `);
ctx.print(ast, `[${parts.map(part => escapeIdentifier(part.raw, false)).join(', ')}])`);
ast.expressions.forEach(expression => {
ctx.print(ast, ', ');
expression.visitExpression(this, ctx);
});
ctx.print(ast, ')');
return null;
}
_visitParams(params, ctx) {
this.visitAllObjects(param => ctx.print(null, param.name), params, ctx, ',');
}
getBuiltinMethodName(method) {
let 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;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* The Trusted Types policy, or null if Trusted Types are not
* enabled/supported, or undefined if the policy has not been created yet.
*/
let policy;
/**
* Returns the Trusted Types policy, or null if Trusted Types are not
* enabled/supported. The first call to this function will create the policy.
*/
function getPolicy() {
if (policy === undefined) {
policy = null;
if (_global.trustedTypes) {
try {
policy =
_global.trustedTypes.createPolicy('angular#unsafe-jit', {
createScript: (s) => s,
});
}
catch (_a) {
// trustedTypes.createPolicy throws if called with a name that is
// already registered, even in report-only mode. Until the API changes,
// catch the error not to break the applications functionally. In such
// cases, the code will fall back to using strings.
}
}
}
return policy;
}
/**
* Unsafely promote a string to a TrustedScript, falling back to strings when
* Trusted Types are not available.
* @security In particular, it must be assured that the provided string will
* never cause an XSS vulnerability if used in a context that will be
* interpreted and executed as a script by a browser, e.g. when calling eval.
*/
function trustedScriptFromString(script) {
var _a;
return ((_a = getPolicy()) === null || _a === void 0 ? void 0 : _a.createScript(script)) || script;
}
/**
* Unsafely call the Function constructor with the given string arguments.
* @security This is a security-sensitive function; any use of this function
* must go through security review. In particular, it must be assured that it
* is only called from the JIT compiler, as use in other code can lead to XSS
* vulnerabilities.
*/
function newTrustedFunctionForJIT(...args) {
if (!_global.trustedTypes) {
// In environments that don't support Trusted Types, fall back to the most
// straightforward implementation:
return new Function(...args);
}
// Chrome currently does not support passing TrustedScript to the Function
// constructor. The following implements the workaround proposed on the page
// below, where the Chromium bug is also referenced:
// https://github.com/w3c/webappsec-trusted-types/wiki/Trusted-Types-for-function-constructor
const fnArgs = args.slice(0, -1).join(',');
const fnBody = args[args.length - 1];
const body = `(function anonymous(${fnArgs}
) { ${fnBody}
})`;
// Using eval directly confuses the compiler and prevents this module from
// being stripped out of JS binaries even if not used. The global['eval']
// indirection fixes that.
const fn = _global['eval'](trustedScriptFromString(body));
if (fn.bind === undefined) {
// Workaround for a browser bug that only exists in Chrome 83, where passing
// a TrustedScript to eval just returns the TrustedScript back without
// evaluating it. In that case, fall back to the most straightforward
// implementation:
return new Function(...args);
}
// To completely mimic the behavior of calling "new Function", two more
// things need to happen:
// 1. Stringifying the resulting function should return its source code
fn.toString = () => body;
// 2. When calling the resulting function, `this` should refer to `global`
return fn.bind(_global);
// When Trusted Types support in Function constructors is widely available,
// the implementation of this function can be simplified to:
// return new Function(...args.map(a => trustedScriptFromString(a)));
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A helper class to manage the evaluation of JIT generated code.
*/
class JitEvaluator {
/**
*
* @param sourceUrl The URL of the generated code.
* @param statements An array of Angular statement AST nodes to be evaluated.
* @param reflector A helper used when converting the statements to executable code.
* @param createSourceMaps If true then create a source-map for the generated code and include it
* inline as a source-map comment.
* @returns A map of all the variables in the generated code.
*/
evaluateStatements(sourceUrl, statements, reflector, createSourceMaps) {
const converter = new JitEmitterVisitor(reflector);
const ctx = EmitterVisitorContext.createRoot();
// Ensure generated code is in strict mode
if (statements.length > 0 && !isUseStrictStatement(statements[0])) {
statements = [
literal('use strict').toStmt(),
...statements,
];
}
converter.visitAllStatements(statements, ctx);
converter.createReturnStmt(ctx);
return this.evaluateCode(sourceUrl, ctx, converter.getArgs(), createSourceMaps);
}
/**
* Evaluate a piece of JIT generated code.
* @param sourceUrl The URL of this generated code.
* @param ctx A context object that contains an AST of the code to be evaluated.
* @param vars A map containing the names and values of variables that the evaluated code might
* reference.
* @param createSourceMap If true then create a source-map for the generated code and include it
* inline as a source-map comment.
* @returns The result of evaluating the code.
*/
evaluateCode(sourceUrl, ctx, vars, createSourceMap) {
let fnBody = `"use strict";${ctx.toSource()}\n//# sourceURL=${sourceUrl}`;
const fnArgNames = [];
const fnArgValues = [];
for (const argName in vars) {
fnArgValues.push(vars[argName]);
fnArgNames.push(argName);
}
if (createSourceMap) {
// using `new Function(...)` generates a header, 1 line of no arguments, 2 lines otherwise
// E.g. ```
// function anonymous(a,b,c
// /**/) { ... }```
// We don't want to hard code this fact, so we auto detect it via an empty function first.
const emptyFn = newTrustedFunctionForJIT(...fnArgNames.concat('return null;')).toString();
const headerLines = emptyFn.slice(0, emptyFn.indexOf('return null;')).split('\n').length - 1;
fnBody += `\n${ctx.toSourceMapGenerator(sourceUrl, headerLines).toJsComment()}`;
}
const fn = newTrustedFunctionForJIT(...fnArgNames.concat(fnBody));
return this.executeFunction(fn, fnArgValues);
}
/**
* Execute a JIT generated function by calling it.
*
* This method can be overridden in tests to capture the functions that are generated
* by this `JitEvaluator` class.
*
* @param fn A function to execute.
* @param args The arguments to pass to the function being executed.
* @returns The return value of the executed function.
*/
executeFunction(fn, args) {
return fn(...args);
}
}
/**
* An Angular AST visitor that converts AST nodes into executable JavaScript code.
*/
class JitEmitterVisitor extends AbstractJsEmitterVisitor {
constructor(reflector) {
super();
this.reflector = reflector;
this._evalArgNames = [];
this._evalArgValues = [];
this._evalExportedVars = [];
}
createReturnStmt(ctx) {
const stmt = new ReturnStatement(new LiteralMapExpr(this._evalExportedVars.map(resultVar => new LiteralMapEntry(resultVar, variable(resultVar), false))));
stmt.visitStatement(this, ctx);
}
getArgs() {
const result = {};
for (let i = 0; i < this._evalArgNames.length; i++) {
result[this._evalArgNames[i]] = this._evalArgValues[i];
}
return result;
}
visitExternalExpr(ast, ctx) {
this._emitReferenceToExternal(ast, this.reflector.resolveExternalReference(ast.value), ctx);
return null;
}
visitWrappedNodeExpr(ast, ctx) {
this._emitReferenceToExternal(ast, ast.node, ctx);
return null;
}
visitDeclareVarStmt(stmt, ctx) {
if (stmt.hasModifier(StmtModifier.Exported)) {
this._evalExportedVars.push(stmt.name);
}
return super.visitDeclareVarStmt(stmt, ctx);
}
visitDeclareFunctionStmt(stmt, ctx) {
if (stmt.hasModifier(StmtModifier.Exported)) {
this._evalExportedVars.push(stmt.name);
}
return super.visitDeclareFunctionStmt(stmt, ctx);
}
visitDeclareClassStmt(stmt, ctx) {
if (stmt.hasModifier(StmtModifier.Exported)) {
this._evalExportedVars.push(stmt.name);
}
return super.visitDeclareClassStmt(stmt, ctx);
}
_emitReferenceToExternal(ast, value, ctx) {
let id = this._evalArgValues.indexOf(value);
if (id === -1) {
id = this._evalArgValues.length;
this._evalArgValues.push(value);
const name = identifierName({ reference: value }) || 'val';
this._evalArgNames.push(`jit_${name}_${id}`);
}
ctx.print(ast, this._evalArgNames[id]);
}
}
function isUseStrictStatement(statement) {
return statement.isEquivalent(literal('use strict').toStmt());
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const $EOF = 0;
const $BSPACE = 8;
const $TAB = 9;
const $LF = 10;
const $VTAB = 11;
const $FF = 12;
const $CR = 13;
const $SPACE = 32;
const $BANG = 33;
const $DQ = 34;
const $HASH = 35;
const $$ = 36;
const $PERCENT = 37;
const $AMPERSAND = 38;
const $SQ = 39;
const $LPAREN = 40;
const $RPAREN = 41;
const $STAR = 42;
const $PLUS = 43;
const $COMMA = 44;
const $MINUS = 45;
const $PERIOD = 46;
const $SLASH = 47;
const $COLON = 58;
const $SEMICOLON = 59;
const $LT = 60;
const $EQ = 61;
const $GT = 62;
const $QUESTION = 63;
const $0 = 48;
const $7 = 55;
const $9 = 57;
const $A = 65;
const $E = 69;
const $F = 70;
const $X = 88;
const $Z = 90;
const $LBRACKET = 91;
const $BACKSLASH = 92;
const $RBRACKET = 93;
const $CARET = 94;
const $_ = 95;
const $a = 97;
const $b = 98;
const $e = 101;
const $f = 102;
const $n = 110;
const $r = 114;
const $t = 116;
const $u = 117;
const $v = 118;
const $x = 120;
const $z = 122;
const $LBRACE = 123;
const $BAR = 124;
const $RBRACE = 125;
const $NBSP = 160;
const $PIPE = 124;
const $TILDA = 126;
const $AT = 64;
const $BT = 96;
function isWhitespace(code) {
return (code >= $TAB && code <= $SPACE) || (code == $NBSP);
}
function isDigit(code) {
return $0 <= code && code <= $9;
}
function isAsciiLetter(code) {
return code >= $a && code <= $z || code >= $A && code <= $Z;
}
function isAsciiHexDigit(code) {
return code >= $a && code <= $f || code >= $A && code <= $F || isDigit(code);
}
function isNewLine(code) {
return code === $LF || code === $CR;
}
function isOctalDigit(code) {
return $0 <= code && code <= $7;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class ParseLocation {
constructor(file, offset, line, col) {
this.file = file;
this.offset = offset;
this.line = line;
this.col = col;
}
toString() {
return this.offset != null ? `${this.file.url}@${this.line}:${this.col}` : this.file.url;
}
moveBy(delta) {
const source = this.file.content;
const len = source.length;
let offset = this.offset;
let line = this.line;
let col = this.col;
while (offset > 0 && delta < 0) {
offset--;
delta++;
const ch = source.charCodeAt(offset);
if (ch == $LF) {
line--;
const priorLine = source.substr(0, offset - 1).lastIndexOf(String.fromCharCode($LF));
col = priorLine > 0 ? offset - priorLine : offset;
}
else {
col--;
}
}
while (offset < len && delta > 0) {
const ch = source.charCodeAt(offset);
offset++;
delta--;
if (ch == $LF) {
line++;
col = 0;
}
else {
col++;
}
}
return new ParseLocation(this.file, offset, line, col);
}
// Return the source around the location
// Up to `maxChars` or `maxLines` on each side of the location
getContext(maxChars, maxLines) {
const content = this.file.content;
let startOffset = this.offset;
if (startOffset != null) {
if (startOffset > content.length - 1) {
startOffset = content.length - 1;
}
let endOffset = startOffset;
let ctxChars = 0;
let ctxLines = 0;
while (ctxChars < maxChars && startOffset > 0) {
startOffset--;
ctxChars++;
if (content[startOffset] == '\n') {
if (++ctxLines == maxLines) {
break;
}
}
}
ctxChars = 0;
ctxLines = 0;
while (ctxChars < maxChars && endOffset < content.length - 1) {
endOffset++;
ctxChars++;
if (content[endOffset] == '\n') {
if (++ctxLines == maxLines) {
break;
}
}
}
return {
before: content.substring(startOffset, this.offset),
after: content.substring(this.offset, endOffset + 1),
};
}
return null;
}
}
class ParseSourceFile {
constructor(content, url) {
this.content = content;
this.url = url;
}
}
class ParseSourceSpan {
/**
* Create an object that holds information about spans of tokens/nodes captured during
* lexing/parsing of text.
*
* @param start
* The location of the start of the span (having skipped leading trivia).
* Skipping leading trivia makes source-spans more "user friendly", since things like HTML
* elements will appear to begin at the start of the opening tag, rather than at the start of any
* leading trivia, which could include newlines.
*
* @param end
* The location of the end of the span.
*
* @param fullStart
* The start of the token without skipping the leading trivia.
* This is used by tooling that splits tokens further, such as extracting Angular interpolations
* from text tokens. Such tooling creates new source-spans relative to the original token's
* source-span. If leading trivia characters have been skipped then the new source-spans may be
* incorrectly offset.
*
* @param details
* Additional information (such as identifier names) that should be associated with the span.
*/
constructor(start, end, fullStart = start, details = null) {
this.start = start;
this.end = end;
this.fullStart = fullStart;
this.details = details;
}
toString() {
return this.start.file.content.substring(this.start.offset, this.end.offset);
}
}
var ParseErrorLevel;
(function (ParseErrorLevel) {
ParseErrorLevel[ParseErrorLevel["WARNING"] = 0] = "WARNING";
ParseErrorLevel[ParseErrorLevel["ERROR"] = 1] = "ERROR";
})(ParseErrorLevel || (ParseErrorLevel = {}));
class ParseError {
constructor(span, msg, level = ParseErrorLevel.ERROR) {
this.span = span;
this.msg = msg;
this.level = level;
}
contextualMessage() {
const ctx = this.span.start.getContext(100, 3);
return ctx ? `${this.msg} ("${ctx.before}[${ParseErrorLevel[this.level]} ->]${ctx.after}")` :
this.msg;
}
toString() {
const details = this.span.details ? `, ${this.span.details}` : '';
return `${this.contextualMessage()}: ${this.span.start}${details}`;
}
}
function typeSourceSpan(kind, type) {
const moduleUrl = identifierModuleUrl(type);
const sourceFileName = moduleUrl != null ? `in ${kind} ${identifierName(type)} in ${moduleUrl}` :
`in ${kind} ${identifierName(type)}`;
const sourceFile = new ParseSourceFile('', sourceFileName);
return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
}
/**
* Generates Source Span object for a given R3 Type for JIT mode.
*
* @param kind Component or Directive.
* @param typeName name of the Component or Directive.
* @param sourceUrl reference to Component or Directive source.
* @returns instance of ParseSourceSpan that represent a given Component or Directive.
*/
function r3JitTypeSourceSpan(kind, typeName, sourceUrl) {
const sourceFileName = `in ${kind} ${typeName} in ${sourceUrl}`;
const sourceFile = new ParseSourceFile('', sourceFileName);
return new ParseSourceSpan(new ParseLocation(sourceFile, -1, -1, -1), new ParseLocation(sourceFile, -1, -1, -1));
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Implementation of `CompileReflector` which resolves references to @angular/core
* symbols at runtime, according to a consumer-provided mapping.
*
* Only supports `resolveExternalReference`, all other methods throw.
*/
class R3JitReflector {
constructor(context) {
this.context = context;
}
resolveExternalReference(ref) {
// This reflector only handles @angular/core imports.
if (ref.moduleName !== '@angular/core') {
throw new Error(`Cannot resolve external reference to ${ref.moduleName}, only references to @angular/core are supported.`);
}
if (!this.context.hasOwnProperty(ref.name)) {
throw new Error(`No value provided for @angular/core symbol '${ref.name}'.`);
}
return this.context[ref.name];
}
parameters(typeOrFunc) {
throw new Error('Not implemented.');
}
annotations(typeOrFunc) {
throw new Error('Not implemented.');
}
shallowAnnotations(typeOrFunc) {
throw new Error('Not implemented.');
}
tryAnnotations(typeOrFunc) {
throw new Error('Not implemented.');
}
propMetadata(typeOrFunc) {
throw new Error('Not implemented.');
}
hasLifecycleHook(type, lcProperty) {
throw new Error('Not implemented.');
}
guards(typeOrFunc) {
throw new Error('Not implemented.');
}
componentModuleUrl(type, cmpMetadata) {
throw new Error('Not implemented.');
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Construct an `R3NgModuleDef` for the given `R3NgModuleMetadata`.
*/
function compileNgModule(meta) {
const { internalType, type: moduleType, bootstrap, declarations, imports, exports, schemas, containsForwardDecls, emitInline, id } = meta;
const additionalStatements = [];
const definitionMap = { type: internalType };
// Only generate the keys in the metadata if the arrays have values.
if (bootstrap.length) {
definitionMap.bootstrap = refsToArray(bootstrap, containsForwardDecls);
}
// If requested to emit scope information inline, pass the declarations, imports and exports to
// the `ɵɵdefineNgModule` call. The JIT compilation uses this.
if (emitInline) {
if (declarations.length) {
definitionMap.declarations = refsToArray(declarations, containsForwardDecls);
}
if (imports.length) {
definitionMap.imports = refsToArray(imports, containsForwardDecls);
}
if (exports.length) {
definitionMap.exports = refsToArray(exports, containsForwardDecls);
}
}
// If not emitting inline, the scope information is not passed into `ɵɵdefineNgModule` as it would
// prevent tree-shaking of the declarations, imports and exports references.
else {
const setNgModuleScopeCall = generateSetNgModuleScopeCall(meta);
if (setNgModuleScopeCall !== null) {
additionalStatements.push(setNgModuleScopeCall);
}
}
if (schemas && schemas.length) {
definitionMap.schemas = literalArr(schemas.map(ref => ref.value));
}
if (id) {
definitionMap.id = id;
}
const expression = importExpr(Identifiers$1.defineNgModule).callFn([mapToMapExpression(definitionMap)]);
const type = new ExpressionType(importExpr(Identifiers$1.NgModuleDefWithMeta, [
new ExpressionType(moduleType.type), tupleTypeOf(declarations), tupleTypeOf(imports),
tupleTypeOf(exports)
]));
return { expression, type, additionalStatements };
}
/**
* Generates a function call to `ɵɵsetNgModuleScope` with all necessary information so that the
* transitive module scope can be computed during runtime in JIT mode. This call is marked pure
* such that the references to declarations, imports and exports may be elided causing these
* symbols to become tree-shakeable.
*/
function generateSetNgModuleScopeCall(meta) {
const { adjacentType: moduleType, declarations, imports, exports, containsForwardDecls } = meta;
const scopeMap = {};
if (declarations.length) {
scopeMap.declarations = refsToArray(declarations, containsForwardDecls);
}
if (imports.length) {
scopeMap.imports = refsToArray(imports, containsForwardDecls);
}
if (exports.length) {
scopeMap.exports = refsToArray(exports, containsForwardDecls);
}
if (Object.keys(scopeMap).length === 0) {
return null;
}
// setNgModuleScope(...)
const fnCall = new InvokeFunctionExpr(
/* fn */ importExpr(Identifiers$1.setNgModuleScope),
/* args */ [moduleType, mapToMapExpression(scopeMap)]);
// (ngJitMode guard) && setNgModuleScope(...)
const guardedCall = jitOnlyGuardedExpression(fnCall);
// function() { (ngJitMode guard) && setNgModuleScope(...); }
const iife = new FunctionExpr(
/* params */ [],
/* statements */ [guardedCall.toStmt()]);
// (function() { (ngJitMode guard) && setNgModuleScope(...); })()
const iifeCall = new InvokeFunctionExpr(
/* fn */ iife,
/* args */ []);
return iifeCall.toStmt();
}
function compileInjector(meta) {
const definitionMap = {};
if (meta.providers !== null) {
definitionMap.providers = meta.providers;
}
if (meta.imports.length > 0) {
definitionMap.imports = literalArr(meta.imports);
}
const expression = importExpr(Identifiers$1.defineInjector).callFn([mapToMapExpression(definitionMap)]);
const type = new ExpressionType(importExpr(Identifiers$1.InjectorDef, [new ExpressionType(meta.type.type)]));
return { expression, type };
}
function tupleTypeOf(exp) {
const types = exp.map(ref => typeofExpr(ref.type));
return exp.length > 0 ? expressionType(literalArr(types)) : NONE_TYPE;
}
function refsToArray(refs, shouldForwardDeclare) {
const values = literalArr(refs.map(ref => ref.value));
return shouldForwardDeclare ? fn([], [new ReturnStatement(values)]) : values;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function compilePipeFromMetadata(metadata) {
const definitionMapValues = [];
// e.g. `name: 'myPipe'`
definitionMapValues.push({ key: 'name', value: literal(metadata.pipeName), quoted: false });
// e.g. `type: MyPipe`
definitionMapValues.push({ key: 'type', value: metadata.type.value, quoted: false });
// e.g. `pure: true`
definitionMapValues.push({ key: 'pure', value: literal(metadata.pure), quoted: false });
const expression = importExpr(Identifiers$1.definePipe).callFn([literalMap(definitionMapValues)]);
const type = createPipeType(metadata);
return { expression, type };
}
function createPipeType(metadata) {
return new ExpressionType(importExpr(Identifiers$1.PipeDefWithMeta, [
typeWithParameters(metadata.type.type, metadata.typeArgumentCount),
new ExpressionType(new LiteralExpr(metadata.pipeName)),
]));
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class ParserError {
constructor(message, input, errLocation, ctxLocation) {
this.input = input;
this.errLocation = errLocation;
this.ctxLocation = ctxLocation;
this.message = `Parser Error: ${message} ${errLocation} [${input}] in ${ctxLocation}`;
}
}
class ParseSpan {
constructor(start, end) {
this.start = start;
this.end = end;
}
toAbsolute(absoluteOffset) {
return new AbsoluteSourceSpan(absoluteOffset + this.start, absoluteOffset + this.end);
}
}
class AST {
constructor(span,
/**
* Absolute location of the expression AST in a source code file.
*/
sourceSpan) {
this.span = span;
this.sourceSpan = sourceSpan;
}
visit(visitor, context = null) {
return null;
}
toString() {
return 'AST';
}
}
class ASTWithName extends AST {
constructor(span, sourceSpan, nameSpan) {
super(span, sourceSpan);
this.nameSpan = nameSpan;
}
}
/**
* Represents a quoted expression of the form:
*
* quote = prefix `:` uninterpretedExpression
* prefix = identifier
* uninterpretedExpression = arbitrary string
*
* A quoted expression is meant to be pre-processed by an AST transformer that
* converts it into another AST that no longer contains quoted expressions.
* It is meant to allow third-party developers to extend Angular template
* expression language. The `uninterpretedExpression` part of the quote is
* therefore not interpreted by the Angular's own expression parser.
*/
class Quote extends AST {
constructor(span, sourceSpan, prefix, uninterpretedExpression, location) {
super(span, sourceSpan);
this.prefix = prefix;
this.uninterpretedExpression = uninterpretedExpression;
this.location = location;
}
visit(visitor, context = null) {
return visitor.visitQuote(this, context);
}
toString() {
return 'Quote';
}
}
class EmptyExpr extends AST {
visit(visitor, context = null) {
// do nothing
}
}
class ImplicitReceiver extends AST {
visit(visitor, context = null) {
return visitor.visitImplicitReceiver(this, context);
}
}
/**
* Receiver when something is accessed through `this` (e.g. `this.foo`). Note that this class
* inherits from `ImplicitReceiver`, because accessing something through `this` is treated the
* same as accessing it implicitly inside of an Angular template (e.g. `[attr.title]="this.title"`
* is the same as `[attr.title]="title"`.). Inheriting allows for the `this` accesses to be treated
* the same as implicit ones, except for a couple of exceptions like `$event` and `$any`.
* TODO: we should find a way for this class not to extend from `ImplicitReceiver` in the future.
*/
class ThisReceiver extends ImplicitReceiver {
visit(visitor, context = null) {
var _a;
return (_a = visitor.visitThisReceiver) === null || _a === void 0 ? void 0 : _a.call(visitor, this, context);
}
}
/**
* Multiple expressions separated by a semicolon.
*/
class Chain extends AST {
constructor(span, sourceSpan, expressions) {
super(span, sourceSpan);
this.expressions = expressions;
}
visit(visitor, context = null) {
return visitor.visitChain(this, context);
}
}
class Conditional extends AST {
constructor(span, sourceSpan, condition, trueExp, falseExp) {
super(span, sourceSpan);
this.condition = condition;
this.trueExp = trueExp;
this.falseExp = falseExp;
}
visit(visitor, context = null) {
return visitor.visitConditional(this, context);
}
}
class PropertyRead extends ASTWithName {
constructor(span, sourceSpan, nameSpan, receiver, name) {
super(span, sourceSpan, nameSpan);
this.receiver = receiver;
this.name = name;
}
visit(visitor, context = null) {
return visitor.visitPropertyRead(this, context);
}
}
class PropertyWrite extends ASTWithName {
constructor(span, sourceSpan, nameSpan, receiver, name, value) {
super(span, sourceSpan, nameSpan);
this.receiver = receiver;
this.name = name;
this.value = value;
}
visit(visitor, context = null) {
return visitor.visitPropertyWrite(this, context);
}
}
class SafePropertyRead extends ASTWithName {
constructor(span, sourceSpan, nameSpan, receiver, name) {
super(span, sourceSpan, nameSpan);
this.receiver = receiver;
this.name = name;
}
visit(visitor, context = null) {
return visitor.visitSafePropertyRead(this, context);
}
}
class KeyedRead extends AST {
constructor(span, sourceSpan, obj, key) {
super(span, sourceSpan);
this.obj = obj;
this.key = key;
}
visit(visitor, context = null) {
return visitor.visitKeyedRead(this, context);
}
}
class KeyedWrite extends AST {
constructor(span, sourceSpan, obj, key, value) {
super(span, sourceSpan);
this.obj = obj;
this.key = key;
this.value = value;
}
visit(visitor, context = null) {
return visitor.visitKeyedWrite(this, context);
}
}
class BindingPipe extends ASTWithName {
constructor(span, sourceSpan, exp, name, args, nameSpan) {
super(span, sourceSpan, nameSpan);
this.exp = exp;
this.name = name;
this.args = args;
}
visit(visitor, context = null) {
return visitor.visitPipe(this, context);
}
}
class LiteralPrimitive extends AST {
constructor(span, sourceSpan, value) {
super(span, sourceSpan);
this.value = value;
}
visit(visitor, context = null) {
return visitor.visitLiteralPrimitive(this, context);
}
}
class LiteralArray extends AST {
constructor(span, sourceSpan, expressions) {
super(span, sourceSpan);
this.expressions = expressions;
}
visit(visitor, context = null) {
return visitor.visitLiteralArray(this, context);
}
}
class LiteralMap extends AST {
constructor(span, sourceSpan, keys, values) {
super(span, sourceSpan);
this.keys = keys;
this.values = values;
}
visit(visitor, context = null) {
return visitor.visitLiteralMap(this, context);
}
}
class Interpolation extends AST {
constructor(span, sourceSpan, strings, expressions) {
super(span, sourceSpan);
this.strings = strings;
this.expressions = expressions;
}
visit(visitor, context = null) {
return visitor.visitInterpolation(this, context);
}
}
class Binary extends AST {
constructor(span, sourceSpan, operation, left, right) {
super(span, sourceSpan);
this.operation = operation;
this.left = left;
this.right = right;
}
visit(visitor, context = null) {
return visitor.visitBinary(this, context);
}
}
/**
* For backwards compatibility reasons, `Unary` inherits from `Binary` and mimics the binary AST
* node that was originally used. This inheritance relation can be deleted in some future major,
* after consumers have been given a chance to fully support Unary.
*/
class Unary extends Binary {
/**
* During the deprecation period this constructor is private, to avoid consumers from creating
* a `Unary` with the fallback properties for `Binary`.
*/
constructor(span, sourceSpan, operator, expr, binaryOp, binaryLeft, binaryRight) {
super(span, sourceSpan, binaryOp, binaryLeft, binaryRight);
this.operator = operator;
this.expr = expr;
}
/**
* Creates a unary minus expression "-x", represented as `Binary` using "0 - x".
*/
static createMinus(span, sourceSpan, expr) {
return new Unary(span, sourceSpan, '-', expr, '-', new LiteralPrimitive(span, sourceSpan, 0), expr);
}
/**
* Creates a unary plus expression "+x", represented as `Binary` using "x - 0".
*/
static createPlus(span, sourceSpan, expr) {
return new Unary(span, sourceSpan, '+', expr, '-', expr, new LiteralPrimitive(span, sourceSpan, 0));
}
visit(visitor, context = null) {
if (visitor.visitUnary !== undefined) {
return visitor.visitUnary(this, context);
}
return visitor.visitBinary(this, context);
}
}
class PrefixNot extends AST {
constructor(span, sourceSpan, expression) {
super(span, sourceSpan);
this.expression = expression;
}
visit(visitor, context = null) {
return visitor.visitPrefixNot(this, context);
}
}
class NonNullAssert extends AST {
constructor(span, sourceSpan, expression) {
super(span, sourceSpan);
this.expression = expression;
}
visit(visitor, context = null) {
return visitor.visitNonNullAssert(this, context);
}
}
class MethodCall extends ASTWithName {
constructor(span, sourceSpan, nameSpan, receiver, name, args) {
super(span, sourceSpan, nameSpan);
this.receiver = receiver;
this.name = name;
this.args = args;
}
visit(visitor, context = null) {
return visitor.visitMethodCall(this, context);
}
}
class SafeMethodCall extends ASTWithName {
constructor(span, sourceSpan, nameSpan, receiver, name, args) {
super(span, sourceSpan, nameSpan);
this.receiver = receiver;
this.name = name;
this.args = args;
}
visit(visitor, context = null) {
return visitor.visitSafeMethodCall(this, context);
}
}
class FunctionCall extends AST {
constructor(span, sourceSpan, target, args) {
super(span, sourceSpan);
this.target = target;
this.args = args;
}
visit(visitor, context = null) {
return visitor.visitFunctionCall(this, context);
}
}
/**
* Records the absolute position of a text span in a source file, where `start` and `end` are the
* starting and ending byte offsets, respectively, of the text span in a source file.
*/
class AbsoluteSourceSpan {
constructor(start, end) {
this.start = start;
this.end = end;
}
}
class ASTWithSource extends AST {
constructor(ast, source, location, absoluteOffset, errors) {
super(new ParseSpan(0, source === null ? 0 : source.length), new AbsoluteSourceSpan(absoluteOffset, source === null ? absoluteOffset : absoluteOffset + source.length));
this.ast = ast;
this.source = source;
this.location = location;
this.errors = errors;
}
visit(visitor, context = null) {
if (visitor.visitASTWithSource) {
return visitor.visitASTWithSource(this, context);
}
return this.ast.visit(visitor, context);
}
toString() {
return `${this.source} in ${this.location}`;
}
}
class VariableBinding {
/**
* @param sourceSpan entire span of the binding.
* @param key name of the LHS along with its span.
* @param value optional value for the RHS along with its span.
*/
constructor(sourceSpan, key, value) {
this.sourceSpan = sourceSpan;
this.key = key;
this.value = value;
}
}
class ExpressionBinding {
/**
* @param sourceSpan entire span of the binding.
* @param key binding name, like ngForOf, ngForTrackBy, ngIf, along with its
* span. Note that the length of the span may not be the same as
* `key.source.length`. For example,
* 1. key.source = ngFor, key.span is for "ngFor"
* 2. key.source = ngForOf, key.span is for "of"
* 3. key.source = ngForTrackBy, key.span is for "trackBy"
* @param value optional expression for the RHS.
*/
constructor(sourceSpan, key, value) {
this.sourceSpan = sourceSpan;
this.key = key;
this.value = value;
}
}
class RecursiveAstVisitor$1 {
visit(ast, context) {
// The default implementation just visits every node.
// Classes that extend RecursiveAstVisitor should override this function
// to selectively visit the specified node.
ast.visit(this, context);
}
visitUnary(ast, context) {
this.visit(ast.expr, context);
}
visitBinary(ast, context) {
this.visit(ast.left, context);
this.visit(ast.right, context);
}
visitChain(ast, context) {
this.visitAll(ast.expressions, context);
}
visitConditional(ast, context) {
this.visit(ast.condition, context);
this.visit(ast.trueExp, context);
this.visit(ast.falseExp, context);
}
visitPipe(ast, context) {
this.visit(ast.exp, context);
this.visitAll(ast.args, context);
}
visitFunctionCall(ast, context) {
if (ast.target) {
this.visit(ast.target, context);
}
this.visitAll(ast.args, context);
}
visitImplicitReceiver(ast, context) { }
visitThisReceiver(ast, context) { }
visitInterpolation(ast, context) {
this.visitAll(ast.expressions, context);
}
visitKeyedRead(ast, context) {
this.visit(ast.obj, context);
this.visit(ast.key, context);
}
visitKeyedWrite(ast, context) {
this.visit(ast.obj, context);
this.visit(ast.key, context);
this.visit(ast.value, context);
}
visitLiteralArray(ast, context) {
this.visitAll(ast.expressions, context);
}
visitLiteralMap(ast, context) {
this.visitAll(ast.values, context);
}
visitLiteralPrimitive(ast, context) { }
visitMethodCall(ast, context) {
this.visit(ast.receiver, context);
this.visitAll(ast.args, context);
}
visitPrefixNot(ast, context) {
this.visit(ast.expression, context);
}
visitNonNullAssert(ast, context) {
this.visit(ast.expression, context);
}
visitPropertyRead(ast, context) {
this.visit(ast.receiver, context);
}
visitPropertyWrite(ast, context) {
this.visit(ast.receiver, context);
this.visit(ast.value, context);
}
visitSafePropertyRead(ast, context) {
this.visit(ast.receiver, context);
}
visitSafeMethodCall(ast, context) {
this.visit(ast.receiver, context);
this.visitAll(ast.args, context);
}
visitQuote(ast, context) { }
// This is not part of the AstVisitor interface, just a helper method
visitAll(asts, context) {
for (const ast of asts) {
this.visit(ast, context);
}
}
}
class AstTransformer$1 {
visitImplicitReceiver(ast, context) {
return ast;
}
visitThisReceiver(ast, context) {
return ast;
}
visitInterpolation(ast, context) {
return new Interpolation(ast.span, ast.sourceSpan, ast.strings, this.visitAll(ast.expressions));
}
visitLiteralPrimitive(ast, context) {
return new LiteralPrimitive(ast.span, ast.sourceSpan, ast.value);
}
visitPropertyRead(ast, context) {
return new PropertyRead(ast.span, ast.sourceSpan, ast.nameSpan, ast.receiver.visit(this), ast.name);
}
visitPropertyWrite(ast, context) {
return new PropertyWrite(ast.span, ast.sourceSpan, ast.nameSpan, ast.receiver.visit(this), ast.name, ast.value.visit(this));
}
visitSafePropertyRead(ast, context) {
return new SafePropertyRead(ast.span, ast.sourceSpan, ast.nameSpan, ast.receiver.visit(this), ast.name);
}
visitMethodCall(ast, context) {
return new MethodCall(ast.span, ast.sourceSpan, ast.nameSpan, ast.receiver.visit(this), ast.name, this.visitAll(ast.args));
}
visitSafeMethodCall(ast, context) {
return new SafeMethodCall(ast.span, ast.sourceSpan, ast.nameSpan, ast.receiver.visit(this), ast.name, this.visitAll(ast.args));
}
visitFunctionCall(ast, context) {
return new FunctionCall(ast.span, ast.sourceSpan, ast.target.visit(this), this.visitAll(ast.args));
}
visitLiteralArray(ast, context) {
return new LiteralArray(ast.span, ast.sourceSpan, this.visitAll(ast.expressions));
}
visitLiteralMap(ast, context) {
return new LiteralMap(ast.span, ast.sourceSpan, ast.keys, this.visitAll(ast.values));
}
visitUnary(ast, context) {
switch (ast.operator) {
case '+':
return Unary.createPlus(ast.span, ast.sourceSpan, ast.expr.visit(this));
case '-':
return Unary.createMinus(ast.span, ast.sourceSpan, ast.expr.visit(this));
default:
throw new Error(`Unknown unary operator ${ast.operator}`);
}
}
visitBinary(ast, context) {
return new Binary(ast.span, ast.sourceSpan, ast.operation, ast.left.visit(this), ast.right.visit(this));
}
visitPrefixNot(ast, context) {
return new PrefixNot(ast.span, ast.sourceSpan, ast.expression.visit(this));
}
visitNonNullAssert(ast, context) {
return new NonNullAssert(ast.span, ast.sourceSpan, ast.expression.visit(this));
}
visitConditional(ast, context) {
return new Conditional(ast.span, ast.sourceSpan, ast.condition.visit(this), ast.trueExp.visit(this), ast.falseExp.visit(this));
}
visitPipe(ast, context) {
return new BindingPipe(ast.span, ast.sourceSpan, ast.exp.visit(this), ast.name, this.visitAll(ast.args), ast.nameSpan);
}
visitKeyedRead(ast, context) {
return new KeyedRead(ast.span, ast.sourceSpan, ast.obj.visit(this), ast.key.visit(this));
}
visitKeyedWrite(ast, context) {
return new KeyedWrite(ast.span, ast.sourceSpan, ast.obj.visit(this), ast.key.visit(this), ast.value.visit(this));
}
visitAll(asts) {
const res = [];
for (let i = 0; i < asts.length; ++i) {
res[i] = asts[i].visit(this);
}
return res;
}
visitChain(ast, context) {
return new Chain(ast.span, ast.sourceSpan, this.visitAll(ast.expressions));
}
visitQuote(ast, context) {
return new Quote(ast.span, ast.sourceSpan, ast.prefix, ast.uninterpretedExpression, ast.location);
}
}
// A transformer that only creates new nodes if the transformer makes a change or
// a change is made a child node.
class AstMemoryEfficientTransformer {
visitImplicitReceiver(ast, context) {
return ast;
}
visitThisReceiver(ast, context) {
return ast;
}
visitInterpolation(ast, context) {
const expressions = this.visitAll(ast.expressions);
if (expressions !== ast.expressions)
return new Interpolation(ast.span, ast.sourceSpan, ast.strings, expressions);
return ast;
}
visitLiteralPrimitive(ast, context) {
return ast;
}
visitPropertyRead(ast, context) {
const receiver = ast.receiver.visit(this);
if (receiver !== ast.receiver) {
return new PropertyRead(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name);
}
return ast;
}
visitPropertyWrite(ast, context) {
const receiver = ast.receiver.visit(this);
const value = ast.value.visit(this);
if (receiver !== ast.receiver || value !== ast.value) {
return new PropertyWrite(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name, value);
}
return ast;
}
visitSafePropertyRead(ast, context) {
const receiver = ast.receiver.visit(this);
if (receiver !== ast.receiver) {
return new SafePropertyRead(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name);
}
return ast;
}
visitMethodCall(ast, context) {
const receiver = ast.receiver.visit(this);
const args = this.visitAll(ast.args);
if (receiver !== ast.receiver || args !== ast.args) {
return new MethodCall(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name, args);
}
return ast;
}
visitSafeMethodCall(ast, context) {
const receiver = ast.receiver.visit(this);
const args = this.visitAll(ast.args);
if (receiver !== ast.receiver || args !== ast.args) {
return new SafeMethodCall(ast.span, ast.sourceSpan, ast.nameSpan, receiver, ast.name, args);
}
return ast;
}
visitFunctionCall(ast, context) {
const target = ast.target && ast.target.visit(this);
const args = this.visitAll(ast.args);
if (target !== ast.target || args !== ast.args) {
return new FunctionCall(ast.span, ast.sourceSpan, target, args);
}
return ast;
}
visitLiteralArray(ast, context) {
const expressions = this.visitAll(ast.expressions);
if (expressions !== ast.expressions) {
return new LiteralArray(ast.span, ast.sourceSpan, expressions);
}
return ast;
}
visitLiteralMap(ast, context) {
const values = this.visitAll(ast.values);
if (values !== ast.values) {
return new LiteralMap(ast.span, ast.sourceSpan, ast.keys, values);
}
return ast;
}
visitUnary(ast, context) {
const expr = ast.expr.visit(this);
if (expr !== ast.expr) {
switch (ast.operator) {
case '+':
return Unary.createPlus(ast.span, ast.sourceSpan, expr);
case '-':
return Unary.createMinus(ast.span, ast.sourceSpan, expr);
default:
throw new Error(`Unknown unary operator ${ast.operator}`);
}
}
return ast;
}
visitBinary(ast, context) {
const left = ast.left.visit(this);
const right = ast.right.visit(this);
if (left !== ast.left || right !== ast.right) {
return new Binary(ast.span, ast.sourceSpan, ast.operation, left, right);
}
return ast;
}
visitPrefixNot(ast, context) {
const expression = ast.expression.visit(this);
if (expression !== ast.expression) {
return new PrefixNot(ast.span, ast.sourceSpan, expression);
}
return ast;
}
visitNonNullAssert(ast, context) {
const expression = ast.expression.visit(this);
if (expression !== ast.expression) {
return new NonNullAssert(ast.span, ast.sourceSpan, expression);
}
return ast;
}
visitConditional(ast, context) {
const condition = ast.condition.visit(this);
const trueExp = ast.trueExp.visit(this);
const falseExp = ast.falseExp.visit(this);
if (condition !== ast.condition || trueExp !== ast.trueExp || falseExp !== ast.falseExp) {
return new Conditional(ast.span, ast.sourceSpan, condition, trueExp, falseExp);
}
return ast;
}
visitPipe(ast, context) {
const exp = ast.exp.visit(this);
const args = this.visitAll(ast.args);
if (exp !== ast.exp || args !== ast.args) {
return new BindingPipe(ast.span, ast.sourceSpan, exp, ast.name, args, ast.nameSpan);
}
return ast;
}
visitKeyedRead(ast, context) {
const obj = ast.obj.visit(this);
const key = ast.key.visit(this);
if (obj !== ast.obj || key !== ast.key) {
return new KeyedRead(ast.span, ast.sourceSpan, obj, key);
}
return ast;
}
visitKeyedWrite(ast, context) {
const obj = ast.obj.visit(this);
const key = ast.key.visit(this);
const value = ast.value.visit(this);
if (obj !== ast.obj || key !== ast.key || value !== ast.value) {
return new KeyedWrite(ast.span, ast.sourceSpan, obj, key, value);
}
return ast;
}
visitAll(asts) {
const res = [];
let modified = false;
for (let i = 0; i < asts.length; ++i) {
const original = asts[i];
const value = original.visit(this);
res[i] = value;
modified = modified || value !== original;
}
return modified ? res : asts;
}
visitChain(ast, context) {
const expressions = this.visitAll(ast.expressions);
if (expressions !== ast.expressions) {
return new Chain(ast.span, ast.sourceSpan, expressions);
}
return ast;
}
visitQuote(ast, context) {
return ast;
}
}
// Bindings
class ParsedProperty {
constructor(name, expression, type,
// TODO(FW-2095): `keySpan` should really be required but allows `undefined` so VE does
// not need to be updated. Make `keySpan` required when VE is removed.
sourceSpan, keySpan, valueSpan) {
this.name = name;
this.expression = expression;
this.type = type;
this.sourceSpan = sourceSpan;
this.keySpan = keySpan;
this.valueSpan = valueSpan;
this.isLiteral = this.type === ParsedPropertyType.LITERAL_ATTR;
this.isAnimation = this.type === ParsedPropertyType.ANIMATION;
}
}
var ParsedPropertyType;
(function (ParsedPropertyType) {
ParsedPropertyType[ParsedPropertyType["DEFAULT"] = 0] = "DEFAULT";
ParsedPropertyType[ParsedPropertyType["LITERAL_ATTR"] = 1] = "LITERAL_ATTR";
ParsedPropertyType[ParsedPropertyType["ANIMATION"] = 2] = "ANIMATION";
})(ParsedPropertyType || (ParsedPropertyType = {}));
class ParsedEvent {
// Regular events have a target
// Animation events have a phase
constructor(name, targetOrPhase, type, handler, sourceSpan,
// TODO(FW-2095): keySpan should be required but was made optional to avoid changing VE
handlerSpan, keySpan) {
this.name = name;
this.targetOrPhase = targetOrPhase;
this.type = type;
this.handler = handler;
this.sourceSpan = sourceSpan;
this.handlerSpan = handlerSpan;
this.keySpan = keySpan;
}
}
/**
* ParsedVariable represents a variable declaration in a microsyntax expression.
*/
class ParsedVariable {
constructor(name, value, sourceSpan, keySpan, valueSpan) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
this.keySpan = keySpan;
this.valueSpan = valueSpan;
}
}
class BoundElementProperty {
constructor(name, type, securityContext, value, unit, sourceSpan, keySpan, valueSpan) {
this.name = name;
this.type = type;
this.securityContext = securityContext;
this.value = value;
this.unit = unit;
this.sourceSpan = sourceSpan;
this.keySpan = keySpan;
this.valueSpan = valueSpan;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class EventHandlerVars {
}
EventHandlerVars.event = variable('$event');
class ConvertActionBindingResult {
constructor(
/**
* Render2 compatible statements,
*/
stmts,
/**
* Variable name used with render2 compatible statements.
*/
allowDefault) {
this.stmts = stmts;
this.allowDefault = allowDefault;
/**
* This is bit of a hack. It converts statements which render2 expects to statements which are
* expected by render3.
*
* Example: `<div click="doSomething($event)">` will generate:
*
* Render3:
* ```
* const pd_b:any = ((<any>ctx.doSomething($event)) !== false);
* return pd_b;
* ```
*
* but render2 expects:
* ```
* return ctx.doSomething($event);
* ```
*/
// TODO(misko): remove this hack once we no longer support ViewEngine.
this.render3Stmts = stmts.map((statement) => {
if (statement instanceof DeclareVarStmt && statement.name == allowDefault.name &&
statement.value instanceof BinaryOperatorExpr) {
const lhs = statement.value.lhs;
return new ReturnStatement(lhs.value);
}
return statement;
});
}
}
/**
* Converts the given expression AST into an executable output AST, assuming the expression is
* used in an action binding (e.g. an event handler).
*/
function convertActionBinding(localResolver, implicitReceiver, action, bindingId, interpolationFunction, baseSourceSpan, implicitReceiverAccesses, globals) {
if (!localResolver) {
localResolver = new DefaultLocalResolver(globals);
}
const actionWithoutBuiltins = convertPropertyBindingBuiltins({
createLiteralArrayConverter: (argCount) => {
// Note: no caching for literal arrays in actions.
return (args) => literalArr(args);
},
createLiteralMapConverter: (keys) => {
// Note: no caching for literal maps in actions.
return (values) => {
const entries = keys.map((k, i) => ({
key: k.key,
value: values[i],
quoted: k.quoted,
}));
return literalMap(entries);
};
},
createPipeConverter: (name) => {
throw new Error(`Illegal State: Actions are not allowed to contain pipes. Pipe: ${name}`);
}
}, action);
const visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction, baseSourceSpan, implicitReceiverAccesses);
const actionStmts = [];
flattenStatements(actionWithoutBuiltins.visit(visitor, _Mode.Statement), actionStmts);
prependTemporaryDecls(visitor.temporaryCount, bindingId, actionStmts);
if (visitor.usesImplicitReceiver) {
localResolver.notifyImplicitReceiverUse();
}
const lastIndex = actionStmts.length - 1;
let preventDefaultVar = null;
if (lastIndex >= 0) {
const lastStatement = actionStmts[lastIndex];
const returnExpr = convertStmtIntoExpression(lastStatement);
if (returnExpr) {
// Note: We need to cast the result of the method call to dynamic,
// as it might be a void method!
preventDefaultVar = createPreventDefaultVar(bindingId);
actionStmts[lastIndex] =
preventDefaultVar.set(returnExpr.cast(DYNAMIC_TYPE).notIdentical(literal(false)))
.toDeclStmt(null, [StmtModifier.Final]);
}
}
return new ConvertActionBindingResult(actionStmts, preventDefaultVar);
}
function convertPropertyBindingBuiltins(converterFactory, ast) {
return convertBuiltins(converterFactory, ast);
}
class ConvertPropertyBindingResult {
constructor(stmts, currValExpr) {
this.stmts = stmts;
this.currValExpr = currValExpr;
}
}
var BindingForm;
(function (BindingForm) {
// The general form of binding expression, supports all expressions.
BindingForm[BindingForm["General"] = 0] = "General";
// Try to generate a simple binding (no temporaries or statements)
// otherwise generate a general binding
BindingForm[BindingForm["TrySimple"] = 1] = "TrySimple";
// Inlines assignment of temporaries into the generated expression. The result may still
// have statements attached for declarations of temporary variables.
// This is the only relevant form for Ivy, the other forms are only used in ViewEngine.
BindingForm[BindingForm["Expression"] = 2] = "Expression";
})(BindingForm || (BindingForm = {}));
/**
* Converts the given expression AST into an executable output AST, assuming the expression
* is used in property binding. The expression has to be preprocessed via
* `convertPropertyBindingBuiltins`.
*/
function convertPropertyBinding(localResolver, implicitReceiver, expressionWithoutBuiltins, bindingId, form, interpolationFunction) {
if (!localResolver) {
localResolver = new DefaultLocalResolver();
}
const visitor = new _AstToIrVisitor(localResolver, implicitReceiver, bindingId, interpolationFunction);
const outputExpr = expressionWithoutBuiltins.visit(visitor, _Mode.Expression);
const stmts = getStatementsFromVisitor(visitor, bindingId);
if (visitor.usesImplicitReceiver) {
localResolver.notifyImplicitReceiverUse();
}
if (visitor.temporaryCount === 0 && form == BindingForm.TrySimple) {
return new ConvertPropertyBindingResult([], outputExpr);
}
else if (form === BindingForm.Expression) {
return new ConvertPropertyBindingResult(stmts, outputExpr);
}
const currValExpr = createCurrValueExpr(bindingId);
stmts.push(currValExpr.set(outputExpr).toDeclStmt(DYNAMIC_TYPE, [StmtModifier.Final]));
return new ConvertPropertyBindingResult(stmts, currValExpr);
}
/**
* Given some expression, such as a binding or interpolation expression, and a context expression to
* look values up on, visit each facet of the given expression resolving values from the context
* expression such that a list of arguments can be derived from the found values that can be used as
* arguments to an external update instruction.
*
* @param localResolver The resolver to use to look up expressions by name appropriately
* @param contextVariableExpression The expression representing the context variable used to create
* the final argument expressions
* @param expressionWithArgumentsToExtract The expression to visit to figure out what values need to
* be resolved and what arguments list to build.
* @param bindingId A name prefix used to create temporary variable names if they're needed for the
* arguments generated
* @returns An array of expressions that can be passed as arguments to instruction expressions like
* `o.importExpr(R3.propertyInterpolate).callFn(result)`
*/
function convertUpdateArguments(localResolver, contextVariableExpression, expressionWithArgumentsToExtract, bindingId) {
const visitor = new _AstToIrVisitor(localResolver, contextVariableExpression, bindingId, undefined);
const outputExpr = expressionWithArgumentsToExtract.visit(visitor, _Mode.Expression);
if (visitor.usesImplicitReceiver) {
localResolver.notifyImplicitReceiverUse();
}
const stmts = getStatementsFromVisitor(visitor, bindingId);
// Removing the first argument, because it was a length for ViewEngine, not Ivy.
let args = outputExpr.args.slice(1);
if (expressionWithArgumentsToExtract instanceof Interpolation) {
// If we're dealing with an interpolation of 1 value with an empty prefix and suffix, reduce the
// args returned to just the value, because we're going to pass it to a special instruction.
const strings = expressionWithArgumentsToExtract.strings;
if (args.length === 3 && strings[0] === '' && strings[1] === '') {
// Single argument interpolate instructions.
args = [args[1]];
}
else if (args.length >= 19) {
// 19 or more arguments must be passed to the `interpolateV`-style instructions, which accept
// an array of arguments
args = [literalArr(args)];
}
}
return { stmts, args };
}
function getStatementsFromVisitor(visitor, bindingId) {
const stmts = [];
for (let i = 0; i < visitor.temporaryCount; i++) {
stmts.push(temporaryDeclaration(bindingId, i));
}
return stmts;
}
function convertBuiltins(converterFactory, ast) {
const visitor = new _BuiltinAstConverter(converterFactory);
return ast.visit(visitor);
}
function temporaryName(bindingId, temporaryNumber) {
return `tmp_${bindingId}_${temporaryNumber}`;
}
function temporaryDeclaration(bindingId, temporaryNumber) {
return new DeclareVarStmt(temporaryName(bindingId, temporaryNumber), NULL_EXPR);
}
function prependTemporaryDecls(temporaryCount, bindingId, statements) {
for (let i = temporaryCount - 1; i >= 0; i--) {
statements.unshift(temporaryDeclaration(bindingId, i));
}
}
var _Mode;
(function (_Mode) {
_Mode[_Mode["Statement"] = 0] = "Statement";
_Mode[_Mode["Expression"] = 1] = "Expression";
})(_Mode || (_Mode = {}));
function ensureStatementMode(mode, ast) {
if (mode !== _Mode.Statement) {
throw new Error(`Expected a statement, but saw ${ast}`);
}
}
function ensureExpressionMode(mode, ast) {
if (mode !== _Mode.Expression) {
throw new Error(`Expected an expression, but saw ${ast}`);
}
}
function convertToStatementIfNeeded(mode, expr) {
if (mode === _Mode.Statement) {
return expr.toStmt();
}
else {
return expr;
}
}
class _BuiltinAstConverter extends AstTransformer$1 {
constructor(_converterFactory) {
super();
this._converterFactory = _converterFactory;
}
visitPipe(ast, context) {
const args = [ast.exp, ...ast.args].map(ast => ast.visit(this, context));
return new BuiltinFunctionCall(ast.span, ast.sourceSpan, args, this._converterFactory.createPipeConverter(ast.name, args.length));
}
visitLiteralArray(ast, context) {
const args = ast.expressions.map(ast => ast.visit(this, context));
return new BuiltinFunctionCall(ast.span, ast.sourceSpan, args, this._converterFactory.createLiteralArrayConverter(ast.expressions.length));
}
visitLiteralMap(ast, context) {
const args = ast.values.map(ast => ast.visit(this, context));
return new BuiltinFunctionCall(ast.span, ast.sourceSpan, args, this._converterFactory.createLiteralMapConverter(ast.keys));
}
}
class _AstToIrVisitor {
constructor(_localResolver, _implicitReceiver, bindingId, interpolationFunction, baseSourceSpan, implicitReceiverAccesses) {
this._localResolver = _localResolver;
this._implicitReceiver = _implicitReceiver;
this.bindingId = bindingId;
this.interpolationFunction = interpolationFunction;
this.baseSourceSpan = baseSourceSpan;
this.implicitReceiverAccesses = implicitReceiverAccesses;
this._nodeMap = new Map();
this._resultMap = new Map();
this._currentTemporary = 0;
this.temporaryCount = 0;
this.usesImplicitReceiver = false;
}
visitUnary(ast, mode) {
let op;
switch (ast.operator) {
case '+':
op = UnaryOperator.Plus;
break;
case '-':
op = UnaryOperator.Minus;
break;
default:
throw new Error(`Unsupported operator ${ast.operator}`);
}
return convertToStatementIfNeeded(mode, new UnaryOperatorExpr(op, this._visit(ast.expr, _Mode.Expression), undefined, this.convertSourceSpan(ast.span)));
}
visitBinary(ast, mode) {
let op;
switch (ast.operation) {
case '+':
op = BinaryOperator.Plus;
break;
case '-':
op = BinaryOperator.Minus;
break;
case '*':
op = BinaryOperator.Multiply;
break;
case '/':
op = BinaryOperator.Divide;
break;
case '%':
op = BinaryOperator.Modulo;
break;
case '&&':
op = BinaryOperator.And;
break;
case '||':
op = BinaryOperator.Or;
break;
case '==':
op = BinaryOperator.Equals;
break;
case '!=':
op = BinaryOperator.NotEquals;
break;
case '===':
op = BinaryOperator.Identical;
break;
case '!==':
op = BinaryOperator.NotIdentical;
break;
case '<':
op = BinaryOperator.Lower;
break;
case '>':
op = BinaryOperator.Bigger;
break;
case '<=':
op = BinaryOperator.LowerEquals;
break;
case '>=':
op = BinaryOperator.BiggerEquals;
break;
default:
throw new Error(`Unsupported operation ${ast.operation}`);
}
return convertToStatementIfNeeded(mode, new BinaryOperatorExpr(op, this._visit(ast.left, _Mode.Expression), this._visit(ast.right, _Mode.Expression), undefined, this.convertSourceSpan(ast.span)));
}
visitChain(ast, mode) {
ensureStatementMode(mode, ast);
return this.visitAll(ast.expressions, mode);
}
visitConditional(ast, mode) {
const value = this._visit(ast.condition, _Mode.Expression);
return convertToStatementIfNeeded(mode, value.conditional(this._visit(ast.trueExp, _Mode.Expression), this._visit(ast.falseExp, _Mode.Expression), this.convertSourceSpan(ast.span)));
}
visitPipe(ast, mode) {
throw new Error(`Illegal state: Pipes should have been converted into functions. Pipe: ${ast.name}`);
}
visitFunctionCall(ast, mode) {
const convertedArgs = this.visitAll(ast.args, _Mode.Expression);
let fnResult;
if (ast instanceof BuiltinFunctionCall) {
fnResult = ast.converter(convertedArgs);
}
else {
fnResult = this._visit(ast.target, _Mode.Expression)
.callFn(convertedArgs, this.convertSourceSpan(ast.span));
}
return convertToStatementIfNeeded(mode, fnResult);
}
visitImplicitReceiver(ast, mode) {
ensureExpressionMode(mode, ast);
this.usesImplicitReceiver = true;
return this._implicitReceiver;
}
visitThisReceiver(ast, mode) {
return this.visitImplicitReceiver(ast, mode);
}
visitInterpolation(ast, mode) {
ensureExpressionMode(mode, ast);
const args = [literal(ast.expressions.length)];
for (let i = 0; i < ast.strings.length - 1; i++) {
args.push(literal(ast.strings[i]));
args.push(this._visit(ast.expressions[i], _Mode.Expression));
}
args.push(literal(ast.strings[ast.strings.length - 1]));
if (this.interpolationFunction) {
return this.interpolationFunction(args);
}
return ast.expressions.length <= 9 ?
importExpr(Identifiers.inlineInterpolate).callFn(args) :
importExpr(Identifiers.interpolate).callFn([
args[0], literalArr(args.slice(1), undefined, this.convertSourceSpan(ast.span))
]);
}
visitKeyedRead(ast, mode) {
const leftMostSafe = this.leftMostSafeNode(ast);
if (leftMostSafe) {
return this.convertSafeAccess(ast, leftMostSafe, mode);
}
else {
return convertToStatementIfNeeded(mode, this._visit(ast.obj, _Mode.Expression).key(this._visit(ast.key, _Mode.Expression)));
}
}
visitKeyedWrite(ast, mode) {
const obj = this._visit(ast.obj, _Mode.Expression);
const key = this._visit(ast.key, _Mode.Expression);
const value = this._visit(ast.value, _Mode.Expression);
return convertToStatementIfNeeded(mode, obj.key(key).set(value));
}
visitLiteralArray(ast, mode) {
throw new Error(`Illegal State: literal arrays should have been converted into functions`);
}
visitLiteralMap(ast, mode) {
throw new Error(`Illegal State: literal maps should have been converted into functions`);
}
visitLiteralPrimitive(ast, mode) {
// For literal values of null, undefined, true, or false allow type interference
// to infer the type.
const type = ast.value === null || ast.value === undefined || ast.value === true || ast.value === true ?
INFERRED_TYPE :
undefined;
return convertToStatementIfNeeded(mode, literal(ast.value, type, this.convertSourceSpan(ast.span)));
}
_getLocal(name, receiver) {
var _a;
if (((_a = this._localResolver.globals) === null || _a === void 0 ? void 0 : _a.has(name)) && receiver instanceof ThisReceiver) {
return null;
}
return this._localResolver.getLocal(name);
}
visitMethodCall(ast, mode) {
if (ast.receiver instanceof ImplicitReceiver &&
!(ast.receiver instanceof ThisReceiver) && ast.name === '$any') {
const args = this.visitAll(ast.args, _Mode.Expression);
if (args.length != 1) {
throw new Error(`Invalid call to $any, expected 1 argument but received ${args.length || 'none'}`);
}
return args[0].cast(DYNAMIC_TYPE, this.convertSourceSpan(ast.span));
}
const leftMostSafe = this.leftMostSafeNode(ast);
if (leftMostSafe) {
return this.convertSafeAccess(ast, leftMostSafe, mode);
}
else {
const args = this.visitAll(ast.args, _Mode.Expression);
const prevUsesImplicitReceiver = this.usesImplicitReceiver;
let result = null;
const receiver = this._visit(ast.receiver, _Mode.Expression);
if (receiver === this._implicitReceiver) {
const varExpr = this._getLocal(ast.name, ast.receiver);
if (varExpr) {
// Restore the previous "usesImplicitReceiver" state since the implicit
// receiver has been replaced with a resolved local expression.
this.usesImplicitReceiver = prevUsesImplicitReceiver;
result = varExpr.callFn(args);
this.addImplicitReceiverAccess(ast.name);
}
}
if (result == null) {
result = receiver.callMethod(ast.name, args, this.convertSourceSpan(ast.span));
}
return convertToStatementIfNeeded(mode, result);
}
}
visitPrefixNot(ast, mode) {
return convertToStatementIfNeeded(mode, not(this._visit(ast.expression, _Mode.Expression)));
}
visitNonNullAssert(ast, mode) {
return convertToStatementIfNeeded(mode, assertNotNull(this._visit(ast.expression, _Mode.Expression)));
}
visitPropertyRead(ast, mode) {
const leftMostSafe = this.leftMostSafeNode(ast);
if (leftMostSafe) {
return this.convertSafeAccess(ast, leftMostSafe, mode);
}
else {
let result = null;
const prevUsesImplicitReceiver = this.usesImplicitReceiver;
const receiver = this._visit(ast.receiver, _Mode.Expression);
if (receiver === this._implicitReceiver) {
result = this._getLocal(ast.name, ast.receiver);
if (result) {
// Restore the previous "usesImplicitReceiver" state since the implicit
// receiver has been replaced with a resolved local expression.
this.usesImplicitReceiver = prevUsesImplicitReceiver;
this.addImplicitReceiverAccess(ast.name);
}
}
if (result == null) {
result = receiver.prop(ast.name);
}
return convertToStatementIfNeeded(mode, result);
}
}
visitPropertyWrite(ast, mode) {
const receiver = this._visit(ast.receiver, _Mode.Expression);
const prevUsesImplicitReceiver = this.usesImplicitReceiver;
let varExpr = null;
if (receiver === this._implicitReceiver) {
const localExpr = this._getLocal(ast.name, ast.receiver);
if (localExpr) {
if (localExpr instanceof ReadPropExpr) {
// If the local variable is a property read expression, it's a reference
// to a 'context.property' value and will be used as the target of the
// write expression.
varExpr = localExpr;
// Restore the previous "usesImplicitReceiver" state since the implicit
// receiver has been replaced with a resolved local expression.
this.usesImplicitReceiver = prevUsesImplicitReceiver;
this.addImplicitReceiverAccess(ast.name);
}
else {
// Otherwise it's an error.
const receiver = ast.name;
const value = (ast.value instanceof PropertyRead) ? ast.value.name : undefined;
throw new Error(`Cannot assign value "${value}" to template variable "${receiver}". Template variables are read-only.`);
}
}
}
// If no local expression could be produced, use the original receiver's
// property as the target.
if (varExpr === null) {
varExpr = receiver.prop(ast.name);
}
return convertToStatementIfNeeded(mode, varExpr.set(this._visit(ast.value, _Mode.Expression)));
}
visitSafePropertyRead(ast, mode) {
return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
}
visitSafeMethodCall(ast, mode) {
return this.convertSafeAccess(ast, this.leftMostSafeNode(ast), mode);
}
visitAll(asts, mode) {
return asts.map(ast => this._visit(ast, mode));
}
visitQuote(ast, mode) {
throw new Error(`Quotes are not supported for evaluation!
Statement: ${ast.uninterpretedExpression} located at ${ast.location}`);
}
_visit(ast, mode) {
const result = this._resultMap.get(ast);
if (result)
return result;
return (this._nodeMap.get(ast) || ast).visit(this, mode);
}
convertSafeAccess(ast, leftMostSafe, mode) {
// If the expression contains a safe access node on the left it needs to be converted to
// an expression that guards the access to the member by checking the receiver for blank. As
// execution proceeds from left to right, the left most part of the expression must be guarded
// first but, because member access is left associative, the right side of the expression is at
// the top of the AST. The desired result requires lifting a copy of the left part of the
// expression up to test it for blank before generating the unguarded version.
// Consider, for example the following expression: a?.b.c?.d.e
// This results in the ast:
// .
// / \
// ?. e
// / \
// . d
// / \
// ?. c
// / \
// a b
// The following tree should be generated:
//
// /---- ? ----\
// / | \
// a /--- ? ---\ null
// / | \
// . . null
// / \ / \
// . c . e
// / \ / \
// a b . d
// / \
// . c
// / \
// a b
//
// Notice that the first guard condition is the left hand of the left most safe access node
// which comes in as leftMostSafe to this routine.
let guardedExpression = this._visit(leftMostSafe.receiver, _Mode.Expression);
let temporary = undefined;
if (this.needsTemporary(leftMostSafe.receiver)) {
// If the expression has method calls or pipes then we need to save the result into a
// temporary variable to avoid calling stateful or impure code more than once.
temporary = this.allocateTemporary();
// Preserve the result in the temporary variable
guardedExpression = temporary.set(guardedExpression);
// Ensure all further references to the guarded expression refer to the temporary instead.
this._resultMap.set(leftMostSafe.receiver, temporary);
}
const condition = guardedExpression.isBlank();
// Convert the ast to an unguarded access to the receiver's member. The map will substitute
// leftMostNode with its unguarded version in the call to `this.visit()`.
if (leftMostSafe instanceof SafeMethodCall) {
this._nodeMap.set(leftMostSafe, new MethodCall(leftMostSafe.span, leftMostSafe.sourceSpan, leftMostSafe.nameSpan, leftMostSafe.receiver, leftMostSafe.name, leftMostSafe.args));
}
else {
this._nodeMap.set(leftMostSafe, new PropertyRead(leftMostSafe.span, leftMostSafe.sourceSpan, leftMostSafe.nameSpan, leftMostSafe.receiver, leftMostSafe.name));
}
// Recursively convert the node now without the guarded member access.
const access = this._visit(ast, _Mode.Expression);
// Remove the mapping. This is not strictly required as the converter only traverses each node
// once but is safer if the conversion is changed to traverse the nodes more than once.
this._nodeMap.delete(leftMostSafe);
// If we allocated a temporary, release it.
if (temporary) {
this.releaseTemporary(temporary);
}
// Produce the conditional
return convertToStatementIfNeeded(mode, condition.conditional(literal(null), access));
}
// Given an expression of the form a?.b.c?.d.e then the left most safe node is
// the (a?.b). The . and ?. are left associative thus can be rewritten as:
// ((((a?.c).b).c)?.d).e. This returns the most deeply nested safe read or
// safe method call as this needs to be transformed initially to:
// a == null ? null : a.c.b.c?.d.e
// then to:
// a == null ? null : a.b.c == null ? null : a.b.c.d.e
leftMostSafeNode(ast) {
const visit = (visitor, ast) => {
return (this._nodeMap.get(ast) || ast).visit(visitor);
};
return ast.visit({
visitUnary(ast) {
return null;
},
visitBinary(ast) {
return null;
},
visitChain(ast) {
return null;
},
visitConditional(ast) {
return null;
},
visitFunctionCall(ast) {
return null;
},
visitImplicitReceiver(ast) {
return null;
},
visitThisReceiver(ast) {
return null;
},
visitInterpolation(ast) {
return null;
},
visitKeyedRead(ast) {
return visit(this, ast.obj);
},
visitKeyedWrite(ast) {
return null;
},
visitLiteralArray(ast) {
return null;
},
visitLiteralMap(ast) {
return null;
},
visitLiteralPrimitive(ast) {
return null;
},
visitMethodCall(ast) {
return visit(this, ast.receiver);
},
visitPipe(ast) {
return null;
},
visitPrefixNot(ast) {
return null;
},
visitNonNullAssert(ast) {
return null;
},
visitPropertyRead(ast) {
return visit(this, ast.receiver);
},
visitPropertyWrite(ast) {
return null;
},
visitQuote(ast) {
return null;
},
visitSafeMethodCall(ast) {
return visit(this, ast.receiver) || ast;
},
visitSafePropertyRead(ast) {
return visit(this, ast.receiver) || ast;
}
});
}
// Returns true of the AST includes a method or a pipe indicating that, if the
// expression is used as the target of a safe property or method access then
// the expression should be stored into a temporary variable.
needsTemporary(ast) {
const visit = (visitor, ast) => {
return ast && (this._nodeMap.get(ast) || ast).visit(visitor);
};
const visitSome = (visitor, ast) => {
return ast.some(ast => visit(visitor, ast));
};
return ast.visit({
visitUnary(ast) {
return visit(this, ast.expr);
},
visitBinary(ast) {
return visit(this, ast.left) || visit(this, ast.right);
},
visitChain(ast) {
return false;
},
visitConditional(ast) {
return visit(this, ast.condition) || visit(this, ast.trueExp) || visit(this, ast.falseExp);
},
visitFunctionCall(ast) {
return true;
},
visitImplicitReceiver(ast) {
return false;
},
visitThisReceiver(ast) {
return false;
},
visitInterpolation(ast) {
return visitSome(this, ast.expressions);
},
visitKeyedRead(ast) {
return false;
},
visitKeyedWrite(ast) {
return false;
},
visitLiteralArray(ast) {
return true;
},
visitLiteralMap(ast) {
return true;
},
visitLiteralPrimitive(ast) {
return false;
},
visitMethodCall(ast) {
return true;
},
visitPipe(ast) {
return true;
},
visitPrefixNot(ast) {
return visit(this, ast.expression);
},
visitNonNullAssert(ast) {
return visit(this, ast.expression);
},
visitPropertyRead(ast) {
return false;
},
visitPropertyWrite(ast) {
return false;
},
visitQuote(ast) {
return false;
},
visitSafeMethodCall(ast) {
return true;
},
visitSafePropertyRead(ast) {
return false;
}
});
}
allocateTemporary() {
const tempNumber = this._currentTemporary++;
this.temporaryCount = Math.max(this._currentTemporary, this.temporaryCount);
return new ReadVarExpr(temporaryName(this.bindingId, tempNumber));
}
releaseTemporary(temporary) {
this._currentTemporary--;
if (temporary.name != temporaryName(this.bindingId, this._currentTemporary)) {
throw new Error(`Temporary ${temporary.name} released out of order`);
}
}
/**
* Creates an absolute `ParseSourceSpan` from the relative `ParseSpan`.
*
* `ParseSpan` objects are relative to the start of the expression.
* This method converts these to full `ParseSourceSpan` objects that
* show where the span is within the overall source file.
*
* @param span the relative span to convert.
* @returns a `ParseSourceSpan` for the given span or null if no
* `baseSourceSpan` was provided to this class.
*/
convertSourceSpan(span) {
if (this.baseSourceSpan) {
const start = this.baseSourceSpan.start.moveBy(span.start);
const end = this.baseSourceSpan.start.moveBy(span.end);
const fullStart = this.baseSourceSpan.fullStart.moveBy(span.start);
return new ParseSourceSpan(start, end, fullStart);
}
else {
return null;
}
}
/** Adds the name of an AST to the list of implicit receiver accesses. */
addImplicitReceiverAccess(name) {
if (this.implicitReceiverAccesses) {
this.implicitReceiverAccesses.add(name);
}
}
}
function flattenStatements(arg, output) {
if (Array.isArray(arg)) {
arg.forEach((entry) => flattenStatements(entry, output));
}
else {
output.push(arg);
}
}
class DefaultLocalResolver {
constructor(globals) {
this.globals = globals;
}
notifyImplicitReceiverUse() { }
getLocal(name) {
if (name === EventHandlerVars.event.name) {
return EventHandlerVars.event;
}
return null;
}
}
function createCurrValueExpr(bindingId) {
return variable(`currVal_${bindingId}`); // fix syntax highlighting: `
}
function createPreventDefaultVar(bindingId) {
return variable(`pd_${bindingId}`);
}
function convertStmtIntoExpression(stmt) {
if (stmt instanceof ExpressionStatement) {
return stmt.expr;
}
else if (stmt instanceof ReturnStatement) {
return stmt.value;
}
return null;
}
class BuiltinFunctionCall extends FunctionCall {
constructor(span, sourceSpan, args, converter) {
super(span, sourceSpan, null, args);
this.args = args;
this.converter = converter;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.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:
<style>
::content(div) {
background: red;
}
</style>
<content></content>
could become:
<style>
/ *@polyfill .content-container div * /
::content(div) {
background: red;
}
</style>
<div class="content-container">
<content></content>
</div>
Note the use of @polyfill in the comment above a ShadowDOM specific style
declaration. This is a directive to the styling shim to use the selector
in comments in lieu of the next selector when running under polyfill.
*/
class ShadowCss {
constructor() {
this.strictStyling = true;
}
/*
* Shim some cssText with the given selector. Returns cssText that can
* be included in the document via WebComponents.ShadowCSS.addCssToDocument(css).
*
* When strictStyling is true:
* - selector is the attribute added to all elements inside the host,
* - hostSelector is the attribute added to the host itself.
*/
shimCssText(cssText, selector, hostSelector = '') {
const commentsWithHash = extractCommentsWithHash(cssText);
cssText = stripComments(cssText);
cssText = this._insertDirectives(cssText);
const scopedCssText = this._scopeCssText(cssText, selector, hostSelector);
return [scopedCssText, ...commentsWithHash].join('\n');
}
_insertDirectives(cssText) {
cssText = this._insertPolyfillDirectivesInCssText(cssText);
return this._insertPolyfillRulesInCssText(cssText);
}
/*
* Process styles to convert native ShadowDOM rules that will trip
* up the css parser; we rely on decorating the stylesheet with inert rules.
*
* For example, we convert this rule:
*
* polyfill-next-selector { content: ':host menu-item'; }
* ::content menu-item {
*
* to this:
*
* scopeName menu-item {
*
**/
_insertPolyfillDirectivesInCssText(cssText) {
// Difference with webcomponents.js: does not handle comments
return cssText.replace(_cssContentNextSelectorRe, function (...m) {
return m[2] + '{';
});
}
/*
* Process styles to add rules which will only apply under the polyfill
*
* For example, we convert this rule:
*
* polyfill-rule {
* content: ':host menu-item';
* ...
* }
*
* to this:
*
* scopeName menu-item {...}
*
**/
_insertPolyfillRulesInCssText(cssText) {
// Difference with webcomponents.js: does not handle comments
return cssText.replace(_cssContentRuleRe, (...m) => {
const rule = m[0].replace(m[1], '').replace(m[2], '');
return m[4] + rule;
});
}
/* Ensure styles are scoped. Pseudo-scoping takes a rule like:
*
* .foo {... }
*
* and converts this to
*
* scopeName .foo { ... }
*/
_scopeCssText(cssText, scopeSelector, hostSelector) {
const unscopedRules = this._extractUnscopedRulesFromCssText(cssText);
// replace :host and :host-context -shadowcsshost and -shadowcsshost respectively
cssText = this._insertPolyfillHostInCssText(cssText);
cssText = this._convertColonHost(cssText);
cssText = this._convertColonHostContext(cssText);
cssText = this._convertShadowDOMSelectors(cssText);
if (scopeSelector) {
cssText = this._scopeSelectors(cssText, scopeSelector, hostSelector);
}
cssText = cssText + '\n' + unscopedRules;
return cssText.trim();
}
/*
* Process styles to add rules which will only apply under the polyfill
* and do not process via CSSOM. (CSSOM is destructive to rules on rare
* occasions, e.g. -webkit-calc on Safari.)
* For example, we convert this rule:
*
* @polyfill-unscoped-rule {
* content: 'menu-item';
* ... }
*
* to this:
*
* menu-item {...}
*
**/
_extractUnscopedRulesFromCssText(cssText) {
// Difference with webcomponents.js: does not handle comments
let r = '';
let m;
_cssContentUnscopedRuleRe.lastIndex = 0;
while ((m = _cssContentUnscopedRuleRe.exec(cssText)) !== null) {
const rule = m[0].replace(m[2], '').replace(m[1], m[4]);
r += rule + '\n\n';
}
return r;
}
/*
* convert a rule like :host(.foo) > .bar { }
*
* to
*
* .foo<scopeName> > .bar
*/
_convertColonHost(cssText) {
return cssText.replace(_cssColonHostRe, (_, hostSelectors, otherSelectors) => {
if (hostSelectors) {
const convertedSelectors = [];
const hostSelectorArray = hostSelectors.split(',').map(p => p.trim());
for (const hostSelector of hostSelectorArray) {
if (!hostSelector)
break;
const convertedSelector = _polyfillHostNoCombinator + hostSelector.replace(_polyfillHost, '') + otherSelectors;
convertedSelectors.push(convertedSelector);
}
return convertedSelectors.join(',');
}
else {
return _polyfillHostNoCombinator + otherSelectors;
}
});
}
/*
* convert a rule like :host-context(.foo) > .bar { }
*
* to
*
* .foo<scopeName> > .bar, .foo <scopeName> > .bar { }
*
* and
*
* :host-context(.foo:host) .bar { ... }
*
* to
*
* .foo<scopeName> .bar { ... }
*/
_convertColonHostContext(cssText) {
return cssText.replace(_cssColonHostContextReGlobal, selectorText => {
// We have captured a selector that contains a `:host-context` rule.
var _a;
// For backward compatibility `:host-context` may contain a comma separated list of selectors.
// Each context selector group will contain a list of host-context selectors that must match
// an ancestor of the host.
// (Normally `contextSelectorGroups` will only contain a single array of context selectors.)
const contextSelectorGroups = [[]];
// There may be more than `:host-context` in this selector so `selectorText` could look like:
// `:host-context(.one):host-context(.two)`.
// Execute `_cssColonHostContextRe` over and over until we have extracted all the
// `:host-context` selectors from this selector.
let match;
while (match = _cssColonHostContextRe.exec(selectorText)) {
// `match` = [':host-context(<selectors>)<rest>', <selectors>, <rest>]
// The `<selectors>` could actually be a comma separated list: `:host-context(.one, .two)`.
const newContextSelectors = ((_a = match[1]) !== null && _a !== void 0 ? _a : '').trim().split(',').map(m => m.trim()).filter(m => m !== '');
// We must duplicate the current selector group for each of these new selectors.
// For example if the current groups are:
// ```
// [
// ['a', 'b', 'c'],
// ['x', 'y', 'z'],
// ]
// ```
// And we have a new set of comma separated selectors: `:host-context(m,n)` then the new
// groups are:
// ```
// [
// ['a', 'b', 'c', 'm'],
// ['x', 'y', 'z', 'm'],
// ['a', 'b', 'c', 'n'],
// ['x', 'y', 'z', 'n'],
// ]
// ```
const contextSelectorGroupsLength = contextSelectorGroups.length;
repeatGroups(contextSelectorGroups, newContextSelectors.length);
for (let i = 0; i < newContextSelectors.length; i++) {
for (let j = 0; j < contextSelectorGroupsLength; j++) {
contextSelectorGroups[j + (i * contextSelectorGroupsLength)].push(newContextSelectors[i]);
}
}
// Update the `selectorText` and see repeat to see if there are more `:host-context`s.
selectorText = match[2];
}
// The context selectors now must be combined with each other to capture all the possible
// selectors that `:host-context` can match. See `combineHostContextSelectors()` for more
// info about how this is done.
return contextSelectorGroups
.map(contextSelectors => combineHostContextSelectors(contextSelectors, selectorText))
.join(', ');
});
}
/*
* Convert combinators like ::shadow and pseudo-elements like ::content
* by replacing with space.
*/
_convertShadowDOMSelectors(cssText) {
return _shadowDOMSelectorsRe.reduce((result, pattern) => result.replace(pattern, ' '), cssText);
}
// change a selector like 'div' to 'name div'
_scopeSelectors(cssText, scopeSelector, hostSelector) {
return processRules(cssText, (rule) => {
let selector = rule.selector;
let content = rule.content;
if (rule.selector[0] != '@') {
selector =
this._scopeSelector(rule.selector, scopeSelector, hostSelector, this.strictStyling);
}
else if (rule.selector.startsWith('@media') || rule.selector.startsWith('@supports') ||
rule.selector.startsWith('@page') || rule.selector.startsWith('@document')) {
content = this._scopeSelectors(rule.content, scopeSelector, hostSelector);
}
else if (rule.selector.startsWith('@font-face')) {
content = this._stripScopingSelectors(rule.content, scopeSelector, hostSelector);
}
return new CssRule(selector, content);
});
}
/**
* Handle a css text that is within a rule that should not contain scope selectors by simply
* removing them! An example of such a rule is `@font-face`.
*
* `@font-face` rules cannot contain nested selectors. Nor can they be nested under a selector.
* Normally this would be a syntax error by the author of the styles. But in some rare cases, such
* as importing styles from a library, and applying `:host ::ng-deep` to the imported styles, we
* can end up with broken css if the imported styles happen to contain @font-face rules.
*
* For example:
*
* ```
* :host ::ng-deep {
* import 'some/lib/containing/font-face';
* }
* ```
*/
_stripScopingSelectors(cssText, scopeSelector, hostSelector) {
return processRules(cssText, rule => {
const selector = rule.selector.replace(_shadowDeepSelectors, ' ')
.replace(_polyfillHostNoCombinatorRe, ' ');
const content = this._scopeSelectors(rule.content, scopeSelector, hostSelector);
return new CssRule(selector, content);
});
}
_scopeSelector(selector, scopeSelector, hostSelector, strict) {
return selector.split(',')
.map(part => part.trim().split(_shadowDeepSelectors))
.map((deepParts) => {
const [shallowPart, ...otherParts] = deepParts;
const applyScope = (shallowPart) => {
if (this._selectorNeedsScoping(shallowPart, scopeSelector)) {
return strict ?
this._applyStrictSelectorScope(shallowPart, scopeSelector, hostSelector) :
this._applySelectorScope(shallowPart, scopeSelector, hostSelector);
}
else {
return shallowPart;
}
};
return [applyScope(shallowPart), ...otherParts].join(' ');
})
.join(', ');
}
_selectorNeedsScoping(selector, scopeSelector) {
const re = this._makeScopeMatcher(scopeSelector);
return !re.test(selector);
}
_makeScopeMatcher(scopeSelector) {
const lre = /\[/g;
const rre = /\]/g;
scopeSelector = scopeSelector.replace(lre, '\\[').replace(rre, '\\]');
return new RegExp('^(' + scopeSelector + ')' + _selectorReSuffix, 'm');
}
_applySelectorScope(selector, scopeSelector, hostSelector) {
// Difference from webcomponents.js: scopeSelector could not be an array
return this._applySimpleSelectorScope(selector, scopeSelector, hostSelector);
}
// scope via name and [is=name]
_applySimpleSelectorScope(selector, scopeSelector, hostSelector) {
// In Android browser, the lastIndex is not reset when the regex is used in String.replace()
_polyfillHostRe.lastIndex = 0;
if (_polyfillHostRe.test(selector)) {
const replaceBy = this.strictStyling ? `[${hostSelector}]` : scopeSelector;
return selector
.replace(_polyfillHostNoCombinatorRe, (hnc, selector) => {
return selector.replace(/([^:]*)(:*)(.*)/, (_, before, colon, after) => {
return before + replaceBy + colon + after;
});
})
.replace(_polyfillHostRe, replaceBy + ' ');
}
return scopeSelector + ' ' + selector;
}
// return a selector with [name] suffix on each simple selector
// e.g. .foo.bar > .zot becomes .foo[name].bar[name] > .zot[name] /** @internal */
_applyStrictSelectorScope(selector, scopeSelector, hostSelector) {
const isRe = /\[is=([^\]]*)\]/g;
scopeSelector = scopeSelector.replace(isRe, (_, ...parts) => parts[0]);
const attrName = '[' + scopeSelector + ']';
const _scopeSelectorPart = (p) => {
let scopedP = p.trim();
if (!scopedP) {
return '';
}
if (p.indexOf(_polyfillHostNoCombinator) > -1) {
scopedP = this._applySimpleSelectorScope(p, scopeSelector, hostSelector);
}
else {
// remove :host since it should be unnecessary
const t = p.replace(_polyfillHostRe, '');
if (t.length > 0) {
const matches = t.match(/([^:]*)(:*)(.*)/);
if (matches) {
scopedP = matches[1] + attrName + matches[2] + matches[3];
}
}
}
return scopedP;
};
const safeContent = new SafeSelector(selector);
selector = safeContent.content();
let scopedSelector = '';
let startIndex = 0;
let res;
const sep = /( |>|\+|~(?!=))\s*/g;
// If a selector appears before :host it should not be shimmed as it
// matches on ancestor elements and not on elements in the host's shadow
// `:host-context(div)` is transformed to
// `-shadowcsshost-no-combinatordiv, div -shadowcsshost-no-combinator`
// the `div` is not part of the component in the 2nd selectors and should not be scoped.
// Historically `component-tag:host` was matching the component so we also want to preserve
// this behavior to avoid breaking legacy apps (it should not match).
// The behavior should be:
// - `tag:host` -> `tag[h]` (this is to avoid breaking legacy apps, should not match anything)
// - `tag :host` -> `tag [h]` (`tag` is not scoped because it's considered part of a
// `:host-context(tag)`)
const hasHost = selector.indexOf(_polyfillHostNoCombinator) > -1;
// Only scope parts after the first `-shadowcsshost-no-combinator` when it is present
let shouldScope = !hasHost;
while ((res = sep.exec(selector)) !== null) {
const separator = res[1];
const part = selector.slice(startIndex, res.index).trim();
shouldScope = shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1;
const scopedPart = shouldScope ? _scopeSelectorPart(part) : part;
scopedSelector += `${scopedPart} ${separator} `;
startIndex = sep.lastIndex;
}
const part = selector.substring(startIndex);
shouldScope = shouldScope || part.indexOf(_polyfillHostNoCombinator) > -1;
scopedSelector += shouldScope ? _scopeSelectorPart(part) : part;
// replace the placeholders with their original values
return safeContent.restore(scopedSelector);
}
_insertPolyfillHostInCssText(selector) {
return selector.replace(_colonHostContextRe, _polyfillHostContext)
.replace(_colonHostRe, _polyfillHost);
}
}
class SafeSelector {
constructor(selector) {
this.placeholders = [];
this.index = 0;
// Replaces attribute selectors with placeholders.
// The WS in [attr="va lue"] would otherwise be interpreted as a selector separator.
selector = this._escapeRegexMatches(selector, /(\[[^\]]*\])/g);
// CSS allows for certain special characters to be used in selectors if they're escaped.
// E.g. `.foo:blue` won't match a class called `foo:blue`, because the colon denotes a
// pseudo-class, but writing `.foo\:blue` will match, because the colon was escaped.
// Replace all escape sequences (`\` followed by a character) with a placeholder so
// that our handling of pseudo-selectors doesn't mess with them.
selector = this._escapeRegexMatches(selector, /(\\.)/g);
// Replaces the expression in `:nth-child(2n + 1)` with a placeholder.
// WS and "+" would otherwise be interpreted as selector separators.
this._content = selector.replace(/(:nth-[-\w]+)(\([^)]+\))/g, (_, pseudo, exp) => {
const replaceBy = `__ph-${this.index}__`;
this.placeholders.push(exp);
this.index++;
return pseudo + replaceBy;
});
}
restore(content) {
return content.replace(/__ph-(\d+)__/g, (_ph, index) => this.placeholders[+index]);
}
content() {
return this._content;
}
/**
* Replaces all of the substrings that match a regex within a
* special string (e.g. `__ph-0__`, `__ph-1__`, etc).
*/
_escapeRegexMatches(content, pattern) {
return content.replace(pattern, (_, keep) => {
const replaceBy = `__ph-${this.index}__`;
this.placeholders.push(keep);
this.index++;
return replaceBy;
});
}
}
const _cssContentNextSelectorRe = /polyfill-next-selector[^}]*content:[\s]*?(['"])(.*?)\1[;\s]*}([^{]*?){/gim;
const _cssContentRuleRe = /(polyfill-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
const _cssContentUnscopedRuleRe = /(polyfill-unscoped-rule)[^}]*(content:[\s]*(['"])(.*?)\3)[;\s]*[^}]*}/gim;
const _polyfillHost = '-shadowcsshost';
// note: :host-context pre-processed to -shadowcsshostcontext.
const _polyfillHostContext = '-shadowcsscontext';
const _parenSuffix = '(?:\\((' +
'(?:\\([^)(]*\\)|[^)(]*)+?' +
')\\))?([^,{]*)';
const _cssColonHostRe = new RegExp(_polyfillHost + _parenSuffix, 'gim');
const _cssColonHostContextReGlobal = new RegExp(_polyfillHostContext + _parenSuffix, 'gim');
const _cssColonHostContextRe = new RegExp(_polyfillHostContext + _parenSuffix, 'im');
const _polyfillHostNoCombinator = _polyfillHost + '-no-combinator';
const _polyfillHostNoCombinatorRe = /-shadowcsshost-no-combinator([^\s]*)/;
const _shadowDOMSelectorsRe = [
/::shadow/g,
/::content/g,
// Deprecated selectors
/\/shadow-deep\//g,
/\/shadow\//g,
];
// The deep combinator is deprecated in the CSS spec
// Support for `>>>`, `deep`, `::ng-deep` is then also deprecated and will be removed in the future.
// see https://github.com/angular/angular/pull/17677
const _shadowDeepSelectors = /(?:>>>)|(?:\/deep\/)|(?:::ng-deep)/g;
const _selectorReSuffix = '([>\\s~+\[.,{:][\\s\\S]*)?$';
const _polyfillHostRe = /-shadowcsshost/gim;
const _colonHostRe = /:host/gim;
const _colonHostContextRe = /:host-context/gim;
const _commentRe = /\/\*\s*[\s\S]*?\*\//g;
function stripComments(input) {
return input.replace(_commentRe, '');
}
const _commentWithHashRe = /\/\*\s*#\s*source(Mapping)?URL=[\s\S]+?\*\//g;
function extractCommentsWithHash(input) {
return input.match(_commentWithHashRe) || [];
}
const BLOCK_PLACEHOLDER = '%BLOCK%';
const QUOTE_PLACEHOLDER = '%QUOTED%';
const _ruleRe = /(\s*)([^;\{\}]+?)(\s*)((?:{%BLOCK%}?\s*;?)|(?:\s*;))/g;
const _quotedRe = /%QUOTED%/g;
const CONTENT_PAIRS = new Map([['{', '}']]);
const QUOTE_PAIRS = new Map([[`"`, `"`], [`'`, `'`]]);
class CssRule {
constructor(selector, content) {
this.selector = selector;
this.content = content;
}
}
function processRules(input, ruleCallback) {
const inputWithEscapedQuotes = escapeBlocks(input, QUOTE_PAIRS, QUOTE_PLACEHOLDER);
const inputWithEscapedBlocks = escapeBlocks(inputWithEscapedQuotes.escapedString, CONTENT_PAIRS, BLOCK_PLACEHOLDER);
let nextBlockIndex = 0;
let nextQuoteIndex = 0;
return inputWithEscapedBlocks.escapedString
.replace(_ruleRe, (...m) => {
const selector = m[2];
let content = '';
let suffix = m[4];
let contentPrefix = '';
if (suffix && suffix.startsWith('{' + BLOCK_PLACEHOLDER)) {
content = inputWithEscapedBlocks.blocks[nextBlockIndex++];
suffix = suffix.substring(BLOCK_PLACEHOLDER.length + 1);
contentPrefix = '{';
}
const rule = ruleCallback(new CssRule(selector, content));
return `${m[1]}${rule.selector}${m[3]}${contentPrefix}${rule.content}${suffix}`;
})
.replace(_quotedRe, () => inputWithEscapedQuotes.blocks[nextQuoteIndex++]);
}
class StringWithEscapedBlocks {
constructor(escapedString, blocks) {
this.escapedString = escapedString;
this.blocks = blocks;
}
}
function escapeBlocks(input, charPairs, placeholder) {
const resultParts = [];
const escapedBlocks = [];
let openCharCount = 0;
let nonBlockStartIndex = 0;
let blockStartIndex = -1;
let openChar;
let closeChar;
for (let i = 0; i < input.length; i++) {
const char = input[i];
if (char === '\\') {
i++;
}
else if (char === closeChar) {
openCharCount--;
if (openCharCount === 0) {
escapedBlocks.push(input.substring(blockStartIndex, i));
resultParts.push(placeholder);
nonBlockStartIndex = i;
blockStartIndex = -1;
openChar = closeChar = undefined;
}
}
else if (char === openChar) {
openCharCount++;
}
else if (openCharCount === 0 && charPairs.has(char)) {
openChar = char;
closeChar = charPairs.get(char);
openCharCount = 1;
blockStartIndex = i + 1;
resultParts.push(input.substring(nonBlockStartIndex, blockStartIndex));
}
}
if (blockStartIndex !== -1) {
escapedBlocks.push(input.substring(blockStartIndex));
resultParts.push(placeholder);
}
else {
resultParts.push(input.substring(nonBlockStartIndex));
}
return new StringWithEscapedBlocks(resultParts.join(''), escapedBlocks);
}
/**
* Combine the `contextSelectors` with the `hostMarker` and the `otherSelectors`
* to create a selector that matches the same as `:host-context()`.
*
* Given a single context selector `A` we need to output selectors that match on the host and as an
* ancestor of the host:
*
* ```
* A <hostMarker>, A<hostMarker> {}
* ```
*
* When there is more than one context selector we also have to create combinations of those
* selectors with each other. For example if there are `A` and `B` selectors the output is:
*
* ```
* AB<hostMarker>, AB <hostMarker>, A B<hostMarker>,
* B A<hostMarker>, A B <hostMarker>, B A <hostMarker> {}
* ```
*
* And so on...
*
* @param hostMarker the string that selects the host element.
* @param contextSelectors an array of context selectors that will be combined.
* @param otherSelectors the rest of the selectors that are not context selectors.
*/
function combineHostContextSelectors(contextSelectors, otherSelectors) {
const hostMarker = _polyfillHostNoCombinator;
_polyfillHostRe.lastIndex = 0; // reset the regex to ensure we get an accurate test
const otherSelectorsHasHost = _polyfillHostRe.test(otherSelectors);
// If there are no context selectors then just output a host marker
if (contextSelectors.length === 0) {
return hostMarker + otherSelectors;
}
const combined = [contextSelectors.pop() || ''];
while (contextSelectors.length > 0) {
const length = combined.length;
const contextSelector = contextSelectors.pop();
for (let i = 0; i < length; i++) {
const previousSelectors = combined[i];
// Add the new selector as a descendant of the previous selectors
combined[length * 2 + i] = previousSelectors + ' ' + contextSelector;
// Add the new selector as an ancestor of the previous selectors
combined[length + i] = contextSelector + ' ' + previousSelectors;
// Add the new selector to act on the same element as the previous selectors
combined[i] = contextSelector + previousSelectors;
}
}
// Finally connect the selector to the `hostMarker`s: either acting directly on the host
// (A<hostMarker>) or as an ancestor (A <hostMarker>).
return combined
.map(s => otherSelectorsHasHost ?
`${s}${otherSelectors}` :
`${s}${hostMarker}${otherSelectors}, ${s} ${hostMarker}${otherSelectors}`)
.join(',');
}
/**
* Mutate the given `groups` array so that there are `multiples` clones of the original array
* stored.
*
* For example `repeatGroups([a, b], 3)` will result in `[a, b, a, b, a, b]` - but importantly the
* newly added groups will be clones of the original.
*
* @param groups An array of groups of strings that will be repeated. This array is mutated
* in-place.
* @param multiples The number of times the current groups should appear.
*/
function repeatGroups(groups, multiples) {
const length = groups.length;
for (let i = 1; i < multiples; i++) {
for (let j = 0; j < length; j++) {
groups[j + (i * length)] = groups[j].slice(0);
}
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const COMPONENT_VARIABLE = '%COMP%';
const HOST_ATTR = `_nghost-${COMPONENT_VARIABLE}`;
const CONTENT_ATTR = `_ngcontent-${COMPONENT_VARIABLE}`;
class StylesCompileDependency {
constructor(name, moduleUrl, setValue) {
this.name = name;
this.moduleUrl = moduleUrl;
this.setValue = setValue;
}
}
class CompiledStylesheet {
constructor(outputCtx, stylesVar, dependencies, isShimmed, meta) {
this.outputCtx = outputCtx;
this.stylesVar = stylesVar;
this.dependencies = dependencies;
this.isShimmed = isShimmed;
this.meta = meta;
}
}
class StyleCompiler {
constructor(_urlResolver) {
this._urlResolver = _urlResolver;
this._shadowCss = new ShadowCss();
}
compileComponent(outputCtx, comp) {
const template = comp.template;
return this._compileStyles(outputCtx, comp, new CompileStylesheetMetadata({
styles: template.styles,
styleUrls: template.styleUrls,
moduleUrl: identifierModuleUrl(comp.type)
}), this.needsStyleShim(comp), true);
}
compileStyles(outputCtx, comp, stylesheet, shim = this.needsStyleShim(comp)) {
return this._compileStyles(outputCtx, comp, stylesheet, shim, false);
}
needsStyleShim(comp) {
return comp.template.encapsulation === ViewEncapsulation.Emulated;
}
_compileStyles(outputCtx, comp, stylesheet, shim, isComponentStylesheet) {
const styleExpressions = stylesheet.styles.map(plainStyle => literal(this._shimIfNeeded(plainStyle, shim)));
const dependencies = [];
stylesheet.styleUrls.forEach((styleUrl) => {
const exprIndex = styleExpressions.length;
// Note: This placeholder will be filled later.
styleExpressions.push(null);
dependencies.push(new StylesCompileDependency(getStylesVarName(null), styleUrl, (value) => styleExpressions[exprIndex] = outputCtx.importExpr(value)));
});
// styles variable contains plain strings and arrays of other styles arrays (recursive),
// so we set its type to dynamic.
const stylesVar = getStylesVarName(isComponentStylesheet ? comp : null);
const stmt = variable(stylesVar)
.set(literalArr(styleExpressions, new ArrayType(DYNAMIC_TYPE, [TypeModifier.Const])))
.toDeclStmt(null, isComponentStylesheet ? [StmtModifier.Final] : [
StmtModifier.Final, StmtModifier.Exported
]);
outputCtx.statements.push(stmt);
return new CompiledStylesheet(outputCtx, stylesVar, dependencies, shim, stylesheet);
}
_shimIfNeeded(style, shim) {
return shim ? this._shadowCss.shimCssText(style, CONTENT_ATTR, HOST_ATTR) : style;
}
}
function getStylesVarName(component) {
let result = `styles`;
if (component) {
result += `_${identifierName(component.type)}`;
}
return result;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A path is an ordered set of elements. Typically a path is to a
* particular offset in a source file. The head of the list is the top
* most node. The tail is the node that contains the offset directly.
*
* For example, the expression `a + b + c` might have an ast that looks
* like:
* +
* / \
* a +
* / \
* b c
*
* The path to the node at offset 9 would be `['+' at 1-10, '+' at 7-10,
* 'c' at 9-10]` and the path the node at offset 1 would be
* `['+' at 1-10, 'a' at 1-2]`.
*/
class AstPath {
constructor(path, position = -1) {
this.path = path;
this.position = position;
}
get empty() {
return !this.path || !this.path.length;
}
get head() {
return this.path[0];
}
get tail() {
return this.path[this.path.length - 1];
}
parentOf(node) {
return node && this.path[this.path.indexOf(node) - 1];
}
childOf(node) {
return this.path[this.path.indexOf(node) + 1];
}
first(ctor) {
for (let i = this.path.length - 1; i >= 0; i--) {
let item = this.path[i];
if (item instanceof ctor)
return item;
}
}
push(node) {
this.path.push(node);
}
pop() {
return this.path.pop();
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class NodeWithI18n {
constructor(sourceSpan, i18n) {
this.sourceSpan = sourceSpan;
this.i18n = i18n;
}
}
class Text$3 extends NodeWithI18n {
constructor(value, sourceSpan, i18n) {
super(sourceSpan, i18n);
this.value = value;
}
visit(visitor, context) {
return visitor.visitText(this, context);
}
}
class Expansion extends NodeWithI18n {
constructor(switchValue, type, cases, sourceSpan, switchValueSourceSpan, i18n) {
super(sourceSpan, i18n);
this.switchValue = switchValue;
this.type = type;
this.cases = cases;
this.switchValueSourceSpan = switchValueSourceSpan;
}
visit(visitor, context) {
return visitor.visitExpansion(this, context);
}
}
class ExpansionCase {
constructor(value, expression, sourceSpan, valueSourceSpan, expSourceSpan) {
this.value = value;
this.expression = expression;
this.sourceSpan = sourceSpan;
this.valueSourceSpan = valueSourceSpan;
this.expSourceSpan = expSourceSpan;
}
visit(visitor, context) {
return visitor.visitExpansionCase(this, context);
}
}
class Attribute extends NodeWithI18n {
constructor(name, value, sourceSpan, keySpan, valueSpan, i18n) {
super(sourceSpan, i18n);
this.name = name;
this.value = value;
this.keySpan = keySpan;
this.valueSpan = valueSpan;
}
visit(visitor, context) {
return visitor.visitAttribute(this, context);
}
}
class Element$1 extends NodeWithI18n {
constructor(name, attrs, children, sourceSpan, startSourceSpan, endSourceSpan = null, i18n) {
super(sourceSpan, i18n);
this.name = name;
this.attrs = attrs;
this.children = children;
this.startSourceSpan = startSourceSpan;
this.endSourceSpan = endSourceSpan;
}
visit(visitor, context) {
return visitor.visitElement(this, context);
}
}
class Comment$1 {
constructor(value, sourceSpan) {
this.value = value;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitComment(this, context);
}
}
function visitAll$1(visitor, nodes, context = null) {
const result = [];
const visit = visitor.visit ?
(ast) => visitor.visit(ast, context) || ast.visit(visitor, context) :
(ast) => ast.visit(visitor, context);
nodes.forEach(ast => {
const astResult = visit(ast);
if (astResult) {
result.push(astResult);
}
});
return result;
}
class RecursiveVisitor$1 {
constructor() { }
visitElement(ast, context) {
this.visitChildren(context, visit => {
visit(ast.attrs);
visit(ast.children);
});
}
visitAttribute(ast, context) { }
visitText(ast, context) { }
visitComment(ast, context) { }
visitExpansion(ast, context) {
return this.visitChildren(context, visit => {
visit(ast.cases);
});
}
visitExpansionCase(ast, context) { }
visitChildren(context, cb) {
let results = [];
let t = this;
function visit(children) {
if (children)
results.push(visitAll$1(t, children, context));
}
cb(visit);
return Array.prototype.concat.apply([], results);
}
}
function spanOf(ast) {
const start = ast.sourceSpan.start.offset;
let end = ast.sourceSpan.end.offset;
if (ast instanceof Element$1) {
if (ast.endSourceSpan) {
end = ast.endSourceSpan.end.offset;
}
else if (ast.children && ast.children.length) {
end = spanOf(ast.children[ast.children.length - 1]).end;
}
}
return { start, end };
}
function findNode(nodes, position) {
const path = [];
const visitor = new class extends RecursiveVisitor$1 {
visit(ast, context) {
const span = spanOf(ast);
if (span.start <= position && position < span.end) {
path.push(ast);
}
else {
// Returning a value here will result in the children being skipped.
return true;
}
}
};
visitAll$1(visitor, nodes);
return new AstPath(path, position);
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var TokenType;
(function (TokenType) {
TokenType[TokenType["TAG_OPEN_START"] = 0] = "TAG_OPEN_START";
TokenType[TokenType["TAG_OPEN_END"] = 1] = "TAG_OPEN_END";
TokenType[TokenType["TAG_OPEN_END_VOID"] = 2] = "TAG_OPEN_END_VOID";
TokenType[TokenType["TAG_CLOSE"] = 3] = "TAG_CLOSE";
TokenType[TokenType["INCOMPLETE_TAG_OPEN"] = 4] = "INCOMPLETE_TAG_OPEN";
TokenType[TokenType["TEXT"] = 5] = "TEXT";
TokenType[TokenType["ESCAPABLE_RAW_TEXT"] = 6] = "ESCAPABLE_RAW_TEXT";
TokenType[TokenType["RAW_TEXT"] = 7] = "RAW_TEXT";
TokenType[TokenType["COMMENT_START"] = 8] = "COMMENT_START";
TokenType[TokenType["COMMENT_END"] = 9] = "COMMENT_END";
TokenType[TokenType["CDATA_START"] = 10] = "CDATA_START";
TokenType[TokenType["CDATA_END"] = 11] = "CDATA_END";
TokenType[TokenType["ATTR_NAME"] = 12] = "ATTR_NAME";
TokenType[TokenType["ATTR_QUOTE"] = 13] = "ATTR_QUOTE";
TokenType[TokenType["ATTR_VALUE"] = 14] = "ATTR_VALUE";
TokenType[TokenType["DOC_TYPE"] = 15] = "DOC_TYPE";
TokenType[TokenType["EXPANSION_FORM_START"] = 16] = "EXPANSION_FORM_START";
TokenType[TokenType["EXPANSION_CASE_VALUE"] = 17] = "EXPANSION_CASE_VALUE";
TokenType[TokenType["EXPANSION_CASE_EXP_START"] = 18] = "EXPANSION_CASE_EXP_START";
TokenType[TokenType["EXPANSION_CASE_EXP_END"] = 19] = "EXPANSION_CASE_EXP_END";
TokenType[TokenType["EXPANSION_FORM_END"] = 20] = "EXPANSION_FORM_END";
TokenType[TokenType["EOF"] = 21] = "EOF";
})(TokenType || (TokenType = {}));
class Token {
constructor(type, parts, sourceSpan) {
this.type = type;
this.parts = parts;
this.sourceSpan = sourceSpan;
}
}
class TokenError extends ParseError {
constructor(errorMsg, tokenType, span) {
super(span, errorMsg);
this.tokenType = tokenType;
}
}
class TokenizeResult {
constructor(tokens, errors, nonNormalizedIcuExpressions) {
this.tokens = tokens;
this.errors = errors;
this.nonNormalizedIcuExpressions = nonNormalizedIcuExpressions;
}
}
function tokenize(source, url, getTagDefinition, options = {}) {
const tokenizer = new _Tokenizer(new ParseSourceFile(source, url), getTagDefinition, options);
tokenizer.tokenize();
return new TokenizeResult(mergeTextTokens(tokenizer.tokens), tokenizer.errors, tokenizer.nonNormalizedIcuExpressions);
}
const _CR_OR_CRLF_REGEXP = /\r\n?/g;
function _unexpectedCharacterErrorMsg(charCode) {
const char = charCode === $EOF ? 'EOF' : String.fromCharCode(charCode);
return `Unexpected character "${char}"`;
}
function _unknownEntityErrorMsg(entitySrc) {
return `Unknown entity "${entitySrc}" - use the "&#<decimal>;" or "&#x<hex>;" syntax`;
}
function _unparsableEntityErrorMsg(type, entityStr) {
return `Unable to parse entity "${entityStr}" - ${type} character reference entities must end with ";"`;
}
var CharacterReferenceType;
(function (CharacterReferenceType) {
CharacterReferenceType["HEX"] = "hexadecimal";
CharacterReferenceType["DEC"] = "decimal";
})(CharacterReferenceType || (CharacterReferenceType = {}));
class _ControlFlowError {
constructor(error) {
this.error = error;
}
}
// See https://www.w3.org/TR/html51/syntax.html#writing-html-documents
class _Tokenizer {
/**
* @param _file The html source file being tokenized.
* @param _getTagDefinition A function that will retrieve a tag definition for a given tag name.
* @param options Configuration of the tokenization.
*/
constructor(_file, _getTagDefinition, options) {
this._getTagDefinition = _getTagDefinition;
this._currentTokenStart = null;
this._currentTokenType = null;
this._expansionCaseStack = [];
this._inInterpolation = false;
this.tokens = [];
this.errors = [];
this.nonNormalizedIcuExpressions = [];
this._tokenizeIcu = options.tokenizeExpansionForms || false;
this._interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
this._leadingTriviaCodePoints =
options.leadingTriviaChars && options.leadingTriviaChars.map(c => c.codePointAt(0) || 0);
const range = options.range || { endPos: _file.content.length, startPos: 0, startLine: 0, startCol: 0 };
this._cursor = options.escapedString ? new EscapedCharacterCursor(_file, range) :
new PlainCharacterCursor(_file, range);
this._preserveLineEndings = options.preserveLineEndings || false;
this._escapedString = options.escapedString || false;
this._i18nNormalizeLineEndingsInICUs = options.i18nNormalizeLineEndingsInICUs || false;
try {
this._cursor.init();
}
catch (e) {
this.handleError(e);
}
}
_processCarriageReturns(content) {
if (this._preserveLineEndings) {
return content;
}
// https://www.w3.org/TR/html51/syntax.html#preprocessing-the-input-stream
// In order to keep the original position in the source, we can not
// pre-process it.
// Instead CRs are processed right before instantiating the tokens.
return content.replace(_CR_OR_CRLF_REGEXP, '\n');
}
tokenize() {
while (this._cursor.peek() !== $EOF) {
const start = this._cursor.clone();
try {
if (this._attemptCharCode($LT)) {
if (this._attemptCharCode($BANG)) {
if (this._attemptCharCode($LBRACKET)) {
this._consumeCdata(start);
}
else if (this._attemptCharCode($MINUS)) {
this._consumeComment(start);
}
else {
this._consumeDocType(start);
}
}
else if (this._attemptCharCode($SLASH)) {
this._consumeTagClose(start);
}
else {
this._consumeTagOpen(start);
}
}
else if (!(this._tokenizeIcu && this._tokenizeExpansionForm())) {
this._consumeText();
}
}
catch (e) {
this.handleError(e);
}
}
this._beginToken(TokenType.EOF);
this._endToken([]);
}
/**
* @returns whether an ICU token has been created
* @internal
*/
_tokenizeExpansionForm() {
if (this.isExpansionFormStart()) {
this._consumeExpansionFormStart();
return true;
}
if (isExpansionCaseStart(this._cursor.peek()) && this._isInExpansionForm()) {
this._consumeExpansionCaseStart();
return true;
}
if (this._cursor.peek() === $RBRACE) {
if (this._isInExpansionCase()) {
this._consumeExpansionCaseEnd();
return true;
}
if (this._isInExpansionForm()) {
this._consumeExpansionFormEnd();
return true;
}
}
return false;
}
_beginToken(type, start = this._cursor.clone()) {
this._currentTokenStart = start;
this._currentTokenType = type;
}
_endToken(parts, end) {
if (this._currentTokenStart === null) {
throw new TokenError('Programming error - attempted to end a token when there was no start to the token', this._currentTokenType, this._cursor.getSpan(end));
}
if (this._currentTokenType === null) {
throw new TokenError('Programming error - attempted to end a token which has no token type', null, this._cursor.getSpan(this._currentTokenStart));
}
const token = new Token(this._currentTokenType, parts, this._cursor.getSpan(this._currentTokenStart, this._leadingTriviaCodePoints));
this.tokens.push(token);
this._currentTokenStart = null;
this._currentTokenType = null;
return token;
}
_createError(msg, span) {
if (this._isInExpansionForm()) {
msg += ` (Do you have an unescaped "{" in your template? Use "{{ '{' }}") to escape it.)`;
}
const error = new TokenError(msg, this._currentTokenType, span);
this._currentTokenStart = null;
this._currentTokenType = null;
return new _ControlFlowError(error);
}
handleError(e) {
if (e instanceof CursorError) {
e = this._createError(e.msg, this._cursor.getSpan(e.cursor));
}
if (e instanceof _ControlFlowError) {
this.errors.push(e.error);
}
else {
throw e;
}
}
_attemptCharCode(charCode) {
if (this._cursor.peek() === charCode) {
this._cursor.advance();
return true;
}
return false;
}
_attemptCharCodeCaseInsensitive(charCode) {
if (compareCharCodeCaseInsensitive(this._cursor.peek(), charCode)) {
this._cursor.advance();
return true;
}
return false;
}
_requireCharCode(charCode) {
const location = this._cursor.clone();
if (!this._attemptCharCode(charCode)) {
throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location));
}
}
_attemptStr(chars) {
const len = chars.length;
if (this._cursor.charsLeft() < len) {
return false;
}
const initialPosition = this._cursor.clone();
for (let i = 0; i < len; i++) {
if (!this._attemptCharCode(chars.charCodeAt(i))) {
// If attempting to parse the string fails, we want to reset the parser
// to where it was before the attempt
this._cursor = initialPosition;
return false;
}
}
return true;
}
_attemptStrCaseInsensitive(chars) {
for (let i = 0; i < chars.length; i++) {
if (!this._attemptCharCodeCaseInsensitive(chars.charCodeAt(i))) {
return false;
}
}
return true;
}
_requireStr(chars) {
const location = this._cursor.clone();
if (!this._attemptStr(chars)) {
throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(location));
}
}
_attemptCharCodeUntilFn(predicate) {
while (!predicate(this._cursor.peek())) {
this._cursor.advance();
}
}
_requireCharCodeUntilFn(predicate, len) {
const start = this._cursor.clone();
this._attemptCharCodeUntilFn(predicate);
if (this._cursor.diff(start) < len) {
throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start));
}
}
_attemptUntilChar(char) {
while (this._cursor.peek() !== char) {
this._cursor.advance();
}
}
_readChar(decodeEntities) {
if (decodeEntities && this._cursor.peek() === $AMPERSAND) {
return this._decodeEntity();
}
else {
// Don't rely upon reading directly from `_input` as the actual char value
// may have been generated from an escape sequence.
const char = String.fromCodePoint(this._cursor.peek());
this._cursor.advance();
return char;
}
}
_decodeEntity() {
const start = this._cursor.clone();
this._cursor.advance();
if (this._attemptCharCode($HASH)) {
const isHex = this._attemptCharCode($x) || this._attemptCharCode($X);
const codeStart = this._cursor.clone();
this._attemptCharCodeUntilFn(isDigitEntityEnd);
if (this._cursor.peek() != $SEMICOLON) {
// Advance cursor to include the peeked character in the string provided to the error
// message.
this._cursor.advance();
const entityType = isHex ? CharacterReferenceType.HEX : CharacterReferenceType.DEC;
throw this._createError(_unparsableEntityErrorMsg(entityType, this._cursor.getChars(start)), this._cursor.getSpan());
}
const strNum = this._cursor.getChars(codeStart);
this._cursor.advance();
try {
const charCode = parseInt(strNum, isHex ? 16 : 10);
return String.fromCharCode(charCode);
}
catch (_a) {
throw this._createError(_unknownEntityErrorMsg(this._cursor.getChars(start)), this._cursor.getSpan());
}
}
else {
const nameStart = this._cursor.clone();
this._attemptCharCodeUntilFn(isNamedEntityEnd);
if (this._cursor.peek() != $SEMICOLON) {
this._cursor = nameStart;
return '&';
}
const name = this._cursor.getChars(nameStart);
this._cursor.advance();
const char = NAMED_ENTITIES[name];
if (!char) {
throw this._createError(_unknownEntityErrorMsg(name), this._cursor.getSpan(start));
}
return char;
}
}
_consumeRawText(decodeEntities, endMarkerPredicate) {
this._beginToken(decodeEntities ? TokenType.ESCAPABLE_RAW_TEXT : TokenType.RAW_TEXT);
const parts = [];
while (true) {
const tagCloseStart = this._cursor.clone();
const foundEndMarker = endMarkerPredicate();
this._cursor = tagCloseStart;
if (foundEndMarker) {
break;
}
parts.push(this._readChar(decodeEntities));
}
return this._endToken([this._processCarriageReturns(parts.join(''))]);
}
_consumeComment(start) {
this._beginToken(TokenType.COMMENT_START, start);
this._requireCharCode($MINUS);
this._endToken([]);
this._consumeRawText(false, () => this._attemptStr('-->'));
this._beginToken(TokenType.COMMENT_END);
this._requireStr('-->');
this._endToken([]);
}
_consumeCdata(start) {
this._beginToken(TokenType.CDATA_START, start);
this._requireStr('CDATA[');
this._endToken([]);
this._consumeRawText(false, () => this._attemptStr(']]>'));
this._beginToken(TokenType.CDATA_END);
this._requireStr(']]>');
this._endToken([]);
}
_consumeDocType(start) {
this._beginToken(TokenType.DOC_TYPE, start);
const contentStart = this._cursor.clone();
this._attemptUntilChar($GT);
const content = this._cursor.getChars(contentStart);
this._cursor.advance();
this._endToken([content]);
}
_consumePrefixAndName() {
const nameOrPrefixStart = this._cursor.clone();
let prefix = '';
while (this._cursor.peek() !== $COLON && !isPrefixEnd(this._cursor.peek())) {
this._cursor.advance();
}
let nameStart;
if (this._cursor.peek() === $COLON) {
prefix = this._cursor.getChars(nameOrPrefixStart);
this._cursor.advance();
nameStart = this._cursor.clone();
}
else {
nameStart = nameOrPrefixStart;
}
this._requireCharCodeUntilFn(isNameEnd, prefix === '' ? 0 : 1);
const name = this._cursor.getChars(nameStart);
return [prefix, name];
}
_consumeTagOpen(start) {
let tagName;
let prefix;
let openTagToken;
try {
if (!isAsciiLetter(this._cursor.peek())) {
throw this._createError(_unexpectedCharacterErrorMsg(this._cursor.peek()), this._cursor.getSpan(start));
}
openTagToken = this._consumeTagOpenStart(start);
prefix = openTagToken.parts[0];
tagName = openTagToken.parts[1];
this._attemptCharCodeUntilFn(isNotWhitespace);
while (this._cursor.peek() !== $SLASH && this._cursor.peek() !== $GT &&
this._cursor.peek() !== $LT && this._cursor.peek() !== $EOF) {
this._consumeAttributeName();
this._attemptCharCodeUntilFn(isNotWhitespace);
if (this._attemptCharCode($EQ)) {
this._attemptCharCodeUntilFn(isNotWhitespace);
this._consumeAttributeValue();
}
this._attemptCharCodeUntilFn(isNotWhitespace);
}
this._consumeTagOpenEnd();
}
catch (e) {
if (e instanceof _ControlFlowError) {
if (openTagToken) {
// We errored before we could close the opening tag, so it is incomplete.
openTagToken.type = TokenType.INCOMPLETE_TAG_OPEN;
}
else {
// When the start tag is invalid, assume we want a "<" as text.
// Back to back text tokens are merged at the end.
this._beginToken(TokenType.TEXT, start);
this._endToken(['<']);
}
return;
}
throw e;
}
const contentTokenType = this._getTagDefinition(tagName).getContentType(prefix);
if (contentTokenType === TagContentType.RAW_TEXT) {
this._consumeRawTextWithTagClose(prefix, tagName, false);
}
else if (contentTokenType === TagContentType.ESCAPABLE_RAW_TEXT) {
this._consumeRawTextWithTagClose(prefix, tagName, true);
}
}
_consumeRawTextWithTagClose(prefix, tagName, decodeEntities) {
this._consumeRawText(decodeEntities, () => {
if (!this._attemptCharCode($LT))
return false;
if (!this._attemptCharCode($SLASH))
return false;
this._attemptCharCodeUntilFn(isNotWhitespace);
if (!this._attemptStrCaseInsensitive(tagName))
return false;
this._attemptCharCodeUntilFn(isNotWhitespace);
return this._attemptCharCode($GT);
});
this._beginToken(TokenType.TAG_CLOSE);
this._requireCharCodeUntilFn(code => code === $GT, 3);
this._cursor.advance(); // Consume the `>`
this._endToken([prefix, tagName]);
}
_consumeTagOpenStart(start) {
this._beginToken(TokenType.TAG_OPEN_START, start);
const parts = this._consumePrefixAndName();
return this._endToken(parts);
}
_consumeAttributeName() {
const attrNameStart = this._cursor.peek();
if (attrNameStart === $SQ || attrNameStart === $DQ) {
throw this._createError(_unexpectedCharacterErrorMsg(attrNameStart), this._cursor.getSpan());
}
this._beginToken(TokenType.ATTR_NAME);
const prefixAndName = this._consumePrefixAndName();
this._endToken(prefixAndName);
}
_consumeAttributeValue() {
let value;
if (this._cursor.peek() === $SQ || this._cursor.peek() === $DQ) {
this._beginToken(TokenType.ATTR_QUOTE);
const quoteChar = this._cursor.peek();
this._cursor.advance();
this._endToken([String.fromCodePoint(quoteChar)]);
this._beginToken(TokenType.ATTR_VALUE);
const parts = [];
while (this._cursor.peek() !== quoteChar) {
parts.push(this._readChar(true));
}
value = parts.join('');
this._endToken([this._processCarriageReturns(value)]);
this._beginToken(TokenType.ATTR_QUOTE);
this._cursor.advance();
this._endToken([String.fromCodePoint(quoteChar)]);
}
else {
this._beginToken(TokenType.ATTR_VALUE);
const valueStart = this._cursor.clone();
this._requireCharCodeUntilFn(isNameEnd, 1);
value = this._cursor.getChars(valueStart);
this._endToken([this._processCarriageReturns(value)]);
}
}
_consumeTagOpenEnd() {
const tokenType = this._attemptCharCode($SLASH) ? TokenType.TAG_OPEN_END_VOID : TokenType.TAG_OPEN_END;
this._beginToken(tokenType);
this._requireCharCode($GT);
this._endToken([]);
}
_consumeTagClose(start) {
this._beginToken(TokenType.TAG_CLOSE, start);
this._attemptCharCodeUntilFn(isNotWhitespace);
const prefixAndName = this._consumePrefixAndName();
this._attemptCharCodeUntilFn(isNotWhitespace);
this._requireCharCode($GT);
this._endToken(prefixAndName);
}
_consumeExpansionFormStart() {
this._beginToken(TokenType.EXPANSION_FORM_START);
this._requireCharCode($LBRACE);
this._endToken([]);
this._expansionCaseStack.push(TokenType.EXPANSION_FORM_START);
this._beginToken(TokenType.RAW_TEXT);
const condition = this._readUntil($COMMA);
const normalizedCondition = this._processCarriageReturns(condition);
if (this._i18nNormalizeLineEndingsInICUs) {
// We explicitly want to normalize line endings for this text.
this._endToken([normalizedCondition]);
}
else {
// We are not normalizing line endings.
const conditionToken = this._endToken([condition]);
if (normalizedCondition !== condition) {
this.nonNormalizedIcuExpressions.push(conditionToken);
}
}
this._requireCharCode($COMMA);
this._attemptCharCodeUntilFn(isNotWhitespace);
this._beginToken(TokenType.RAW_TEXT);
const type = this._readUntil($COMMA);
this._endToken([type]);
this._requireCharCode($COMMA);
this._attemptCharCodeUntilFn(isNotWhitespace);
}
_consumeExpansionCaseStart() {
this._beginToken(TokenType.EXPANSION_CASE_VALUE);
const value = this._readUntil($LBRACE).trim();
this._endToken([value]);
this._attemptCharCodeUntilFn(isNotWhitespace);
this._beginToken(TokenType.EXPANSION_CASE_EXP_START);
this._requireCharCode($LBRACE);
this._endToken([]);
this._attemptCharCodeUntilFn(isNotWhitespace);
this._expansionCaseStack.push(TokenType.EXPANSION_CASE_EXP_START);
}
_consumeExpansionCaseEnd() {
this._beginToken(TokenType.EXPANSION_CASE_EXP_END);
this._requireCharCode($RBRACE);
this._endToken([]);
this._attemptCharCodeUntilFn(isNotWhitespace);
this._expansionCaseStack.pop();
}
_consumeExpansionFormEnd() {
this._beginToken(TokenType.EXPANSION_FORM_END);
this._requireCharCode($RBRACE);
this._endToken([]);
this._expansionCaseStack.pop();
}
_consumeText() {
const start = this._cursor.clone();
this._beginToken(TokenType.TEXT, start);
const parts = [];
do {
if (this._interpolationConfig && this._attemptStr(this._interpolationConfig.start)) {
parts.push(this._interpolationConfig.start);
this._inInterpolation = true;
}
else if (this._interpolationConfig && this._inInterpolation &&
this._attemptStr(this._interpolationConfig.end)) {
parts.push(this._interpolationConfig.end);
this._inInterpolation = false;
}
else {
parts.push(this._readChar(true));
}
} while (!this._isTextEnd());
this._endToken([this._processCarriageReturns(parts.join(''))]);
}
_isTextEnd() {
if (this._cursor.peek() === $LT || this._cursor.peek() === $EOF) {
return true;
}
if (this._tokenizeIcu && !this._inInterpolation) {
if (this.isExpansionFormStart()) {
// start of an expansion form
return true;
}
if (this._cursor.peek() === $RBRACE && this._isInExpansionCase()) {
// end of and expansion case
return true;
}
}
return false;
}
_readUntil(char) {
const start = this._cursor.clone();
this._attemptUntilChar(char);
return this._cursor.getChars(start);
}
_isInExpansionCase() {
return this._expansionCaseStack.length > 0 &&
this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
TokenType.EXPANSION_CASE_EXP_START;
}
_isInExpansionForm() {
return this._expansionCaseStack.length > 0 &&
this._expansionCaseStack[this._expansionCaseStack.length - 1] ===
TokenType.EXPANSION_FORM_START;
}
isExpansionFormStart() {
if (this._cursor.peek() !== $LBRACE) {
return false;
}
if (this._interpolationConfig) {
const start = this._cursor.clone();
const isInterpolation = this._attemptStr(this._interpolationConfig.start);
this._cursor = start;
return !isInterpolation;
}
return true;
}
}
function isNotWhitespace(code) {
return !isWhitespace(code) || code === $EOF;
}
function isNameEnd(code) {
return isWhitespace(code) || code === $GT || code === $LT ||
code === $SLASH || code === $SQ || code === $DQ || code === $EQ ||
code === $EOF;
}
function isPrefixEnd(code) {
return (code < $a || $z < code) && (code < $A || $Z < code) &&
(code < $0 || code > $9);
}
function isDigitEntityEnd(code) {
return code == $SEMICOLON || code == $EOF || !isAsciiHexDigit(code);
}
function isNamedEntityEnd(code) {
return code == $SEMICOLON || code == $EOF || !isAsciiLetter(code);
}
function isExpansionCaseStart(peek) {
return peek !== $RBRACE;
}
function compareCharCodeCaseInsensitive(code1, code2) {
return toUpperCaseCharCode(code1) == toUpperCaseCharCode(code2);
}
function toUpperCaseCharCode(code) {
return code >= $a && code <= $z ? code - $a + $A : code;
}
function mergeTextTokens(srcTokens) {
const dstTokens = [];
let lastDstToken = undefined;
for (let i = 0; i < srcTokens.length; i++) {
const token = srcTokens[i];
if (lastDstToken && lastDstToken.type == TokenType.TEXT && token.type == TokenType.TEXT) {
lastDstToken.parts[0] += token.parts[0];
lastDstToken.sourceSpan.end = token.sourceSpan.end;
}
else {
lastDstToken = token;
dstTokens.push(lastDstToken);
}
}
return dstTokens;
}
class PlainCharacterCursor {
constructor(fileOrCursor, range) {
if (fileOrCursor instanceof PlainCharacterCursor) {
this.file = fileOrCursor.file;
this.input = fileOrCursor.input;
this.end = fileOrCursor.end;
const state = fileOrCursor.state;
// Note: avoid using `{...fileOrCursor.state}` here as that has a severe performance penalty.
// In ES5 bundles the object spread operator is translated into the `__assign` helper, which
// is not optimized by VMs as efficiently as a raw object literal. Since this constructor is
// called in tight loops, this difference matters.
this.state = {
peek: state.peek,
offset: state.offset,
line: state.line,
column: state.column,
};
}
else {
if (!range) {
throw new Error('Programming error: the range argument must be provided with a file argument.');
}
this.file = fileOrCursor;
this.input = fileOrCursor.content;
this.end = range.endPos;
this.state = {
peek: -1,
offset: range.startPos,
line: range.startLine,
column: range.startCol,
};
}
}
clone() {
return new PlainCharacterCursor(this);
}
peek() {
return this.state.peek;
}
charsLeft() {
return this.end - this.state.offset;
}
diff(other) {
return this.state.offset - other.state.offset;
}
advance() {
this.advanceState(this.state);
}
init() {
this.updatePeek(this.state);
}
getSpan(start, leadingTriviaCodePoints) {
start = start || this;
let fullStart = start;
if (leadingTriviaCodePoints) {
while (this.diff(start) > 0 && leadingTriviaCodePoints.indexOf(start.peek()) !== -1) {
if (fullStart === start) {
start = start.clone();
}
start.advance();
}
}
const startLocation = this.locationFromCursor(start);
const endLocation = this.locationFromCursor(this);
const fullStartLocation = fullStart !== start ? this.locationFromCursor(fullStart) : startLocation;
return new ParseSourceSpan(startLocation, endLocation, fullStartLocation);
}
getChars(start) {
return this.input.substring(start.state.offset, this.state.offset);
}
charAt(pos) {
return this.input.charCodeAt(pos);
}
advanceState(state) {
if (state.offset >= this.end) {
this.state = state;
throw new CursorError('Unexpected character "EOF"', this);
}
const currentChar = this.charAt(state.offset);
if (currentChar === $LF) {
state.line++;
state.column = 0;
}
else if (!isNewLine(currentChar)) {
state.column++;
}
state.offset++;
this.updatePeek(state);
}
updatePeek(state) {
state.peek = state.offset >= this.end ? $EOF : this.charAt(state.offset);
}
locationFromCursor(cursor) {
return new ParseLocation(cursor.file, cursor.state.offset, cursor.state.line, cursor.state.column);
}
}
class EscapedCharacterCursor extends PlainCharacterCursor {
constructor(fileOrCursor, range) {
if (fileOrCursor instanceof EscapedCharacterCursor) {
super(fileOrCursor);
this.internalState = Object.assign({}, fileOrCursor.internalState);
}
else {
super(fileOrCursor, range);
this.internalState = this.state;
}
}
advance() {
this.state = this.internalState;
super.advance();
this.processEscapeSequence();
}
init() {
super.init();
this.processEscapeSequence();
}
clone() {
return new EscapedCharacterCursor(this);
}
getChars(start) {
const cursor = start.clone();
let chars = '';
while (cursor.internalState.offset < this.internalState.offset) {
chars += String.fromCodePoint(cursor.peek());
cursor.advance();
}
return chars;
}
/**
* Process the escape sequence that starts at the current position in the text.
*
* This method is called to ensure that `peek` has the unescaped value of escape sequences.
*/
processEscapeSequence() {
const peek = () => this.internalState.peek;
if (peek() === $BACKSLASH) {
// We have hit an escape sequence so we need the internal state to become independent
// of the external state.
this.internalState = Object.assign({}, this.state);
// Move past the backslash
this.advanceState(this.internalState);
// First check for standard control char sequences
if (peek() === $n) {
this.state.peek = $LF;
}
else if (peek() === $r) {
this.state.peek = $CR;
}
else if (peek() === $v) {
this.state.peek = $VTAB;
}
else if (peek() === $t) {
this.state.peek = $TAB;
}
else if (peek() === $b) {
this.state.peek = $BSPACE;
}
else if (peek() === $f) {
this.state.peek = $FF;
}
// Now consider more complex sequences
else if (peek() === $u) {
// Unicode code-point sequence
this.advanceState(this.internalState); // advance past the `u` char
if (peek() === $LBRACE) {
// Variable length Unicode, e.g. `\x{123}`
this.advanceState(this.internalState); // advance past the `{` char
// Advance past the variable number of hex digits until we hit a `}` char
const digitStart = this.clone();
let length = 0;
while (peek() !== $RBRACE) {
this.advanceState(this.internalState);
length++;
}
this.state.peek = this.decodeHexDigits(digitStart, length);
}
else {
// Fixed length Unicode, e.g. `\u1234`
const digitStart = this.clone();
this.advanceState(this.internalState);
this.advanceState(this.internalState);
this.advanceState(this.internalState);
this.state.peek = this.decodeHexDigits(digitStart, 4);
}
}
else if (peek() === $x) {
// Hex char code, e.g. `\x2F`
this.advanceState(this.internalState); // advance past the `x` char
const digitStart = this.clone();
this.advanceState(this.internalState);
this.state.peek = this.decodeHexDigits(digitStart, 2);
}
else if (isOctalDigit(peek())) {
// Octal char code, e.g. `\012`,
let octal = '';
let length = 0;
let previous = this.clone();
while (isOctalDigit(peek()) && length < 3) {
previous = this.clone();
octal += String.fromCodePoint(peek());
this.advanceState(this.internalState);
length++;
}
this.state.peek = parseInt(octal, 8);
// Backup one char
this.internalState = previous.internalState;
}
else if (isNewLine(this.internalState.peek)) {
// Line continuation `\` followed by a new line
this.advanceState(this.internalState); // advance over the newline
this.state = this.internalState;
}
else {
// If none of the `if` blocks were executed then we just have an escaped normal character.
// In that case we just, effectively, skip the backslash from the character.
this.state.peek = this.internalState.peek;
}
}
}
decodeHexDigits(start, length) {
const hex = this.input.substr(start.internalState.offset, length);
const charCode = parseInt(hex, 16);
if (!isNaN(charCode)) {
return charCode;
}
else {
start.state = start.internalState;
throw new CursorError('Invalid hexadecimal escape sequence', start);
}
}
}
class CursorError {
constructor(msg, cursor) {
this.msg = msg;
this.cursor = cursor;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class TreeError extends ParseError {
constructor(elementName, span, msg) {
super(span, msg);
this.elementName = elementName;
}
static create(elementName, span, msg) {
return new TreeError(elementName, span, msg);
}
}
class ParseTreeResult {
constructor(rootNodes, errors) {
this.rootNodes = rootNodes;
this.errors = errors;
}
}
class Parser {
constructor(getTagDefinition) {
this.getTagDefinition = getTagDefinition;
}
parse(source, url, options) {
const tokenizeResult = tokenize(source, url, this.getTagDefinition, options);
const parser = new _TreeBuilder(tokenizeResult.tokens, this.getTagDefinition);
parser.build();
return new ParseTreeResult(parser.rootNodes, tokenizeResult.errors.concat(parser.errors));
}
}
class _TreeBuilder {
constructor(tokens, getTagDefinition) {
this.tokens = tokens;
this.getTagDefinition = getTagDefinition;
this._index = -1;
this._elementStack = [];
this.rootNodes = [];
this.errors = [];
this._advance();
}
build() {
while (this._peek.type !== TokenType.EOF) {
if (this._peek.type === TokenType.TAG_OPEN_START ||
this._peek.type === TokenType.INCOMPLETE_TAG_OPEN) {
this._consumeStartTag(this._advance());
}
else if (this._peek.type === TokenType.TAG_CLOSE) {
this._consumeEndTag(this._advance());
}
else if (this._peek.type === TokenType.CDATA_START) {
this._closeVoidElement();
this._consumeCdata(this._advance());
}
else if (this._peek.type === TokenType.COMMENT_START) {
this._closeVoidElement();
this._consumeComment(this._advance());
}
else if (this._peek.type === TokenType.TEXT || this._peek.type === TokenType.RAW_TEXT ||
this._peek.type === TokenType.ESCAPABLE_RAW_TEXT) {
this._closeVoidElement();
this._consumeText(this._advance());
}
else if (this._peek.type === TokenType.EXPANSION_FORM_START) {
this._consumeExpansion(this._advance());
}
else {
// Skip all other tokens...
this._advance();
}
}
}
_advance() {
const prev = this._peek;
if (this._index < this.tokens.length - 1) {
// Note: there is always an EOF token at the end
this._index++;
}
this._peek = this.tokens[this._index];
return prev;
}
_advanceIf(type) {
if (this._peek.type === type) {
return this._advance();
}
return null;
}
_consumeCdata(_startToken) {
this._consumeText(this._advance());
this._advanceIf(TokenType.CDATA_END);
}
_consumeComment(token) {
const text = this._advanceIf(TokenType.RAW_TEXT);
this._advanceIf(TokenType.COMMENT_END);
const value = text != null ? text.parts[0].trim() : null;
this._addToParent(new Comment$1(value, token.sourceSpan));
}
_consumeExpansion(token) {
const switchValue = this._advance();
const type = this._advance();
const cases = [];
// read =
while (this._peek.type === TokenType.EXPANSION_CASE_VALUE) {
const expCase = this._parseExpansionCase();
if (!expCase)
return; // error
cases.push(expCase);
}
// read the final }
if (this._peek.type !== TokenType.EXPANSION_FORM_END) {
this.errors.push(TreeError.create(null, this._peek.sourceSpan, `Invalid ICU message. Missing '}'.`));
return;
}
const sourceSpan = new ParseSourceSpan(token.sourceSpan.start, this._peek.sourceSpan.end, token.sourceSpan.fullStart);
this._addToParent(new Expansion(switchValue.parts[0], type.parts[0], cases, sourceSpan, switchValue.sourceSpan));
this._advance();
}
_parseExpansionCase() {
const value = this._advance();
// read {
if (this._peek.type !== TokenType.EXPANSION_CASE_EXP_START) {
this.errors.push(TreeError.create(null, this._peek.sourceSpan, `Invalid ICU message. Missing '{'.`));
return null;
}
// read until }
const start = this._advance();
const exp = this._collectExpansionExpTokens(start);
if (!exp)
return null;
const end = this._advance();
exp.push(new Token(TokenType.EOF, [], end.sourceSpan));
// parse everything in between { and }
const expansionCaseParser = new _TreeBuilder(exp, this.getTagDefinition);
expansionCaseParser.build();
if (expansionCaseParser.errors.length > 0) {
this.errors = this.errors.concat(expansionCaseParser.errors);
return null;
}
const sourceSpan = new ParseSourceSpan(value.sourceSpan.start, end.sourceSpan.end, value.sourceSpan.fullStart);
const expSourceSpan = new ParseSourceSpan(start.sourceSpan.start, end.sourceSpan.end, start.sourceSpan.fullStart);
return new ExpansionCase(value.parts[0], expansionCaseParser.rootNodes, sourceSpan, value.sourceSpan, expSourceSpan);
}
_collectExpansionExpTokens(start) {
const exp = [];
const expansionFormStack = [TokenType.EXPANSION_CASE_EXP_START];
while (true) {
if (this._peek.type === TokenType.EXPANSION_FORM_START ||
this._peek.type === TokenType.EXPANSION_CASE_EXP_START) {
expansionFormStack.push(this._peek.type);
}
if (this._peek.type === TokenType.EXPANSION_CASE_EXP_END) {
if (lastOnStack(expansionFormStack, TokenType.EXPANSION_CASE_EXP_START)) {
expansionFormStack.pop();
if (expansionFormStack.length == 0)
return exp;
}
else {
this.errors.push(TreeError.create(null, start.sourceSpan, `Invalid ICU message. Missing '}'.`));
return null;
}
}
if (this._peek.type === TokenType.EXPANSION_FORM_END) {
if (lastOnStack(expansionFormStack, TokenType.EXPANSION_FORM_START)) {
expansionFormStack.pop();
}
else {
this.errors.push(TreeError.create(null, start.sourceSpan, `Invalid ICU message. Missing '}'.`));
return null;
}
}
if (this._peek.type === TokenType.EOF) {
this.errors.push(TreeError.create(null, start.sourceSpan, `Invalid ICU message. Missing '}'.`));
return null;
}
exp.push(this._advance());
}
}
_consumeText(token) {
let text = token.parts[0];
if (text.length > 0 && text[0] == '\n') {
const parent = this._getParentElement();
if (parent != null && parent.children.length == 0 &&
this.getTagDefinition(parent.name).ignoreFirstLf) {
text = text.substring(1);
}
}
if (text.length > 0) {
this._addToParent(new Text$3(text, token.sourceSpan));
}
}
_closeVoidElement() {
const el = this._getParentElement();
if (el && this.getTagDefinition(el.name).isVoid) {
this._elementStack.pop();
}
}
_consumeStartTag(startTagToken) {
const [prefix, name] = startTagToken.parts;
const attrs = [];
while (this._peek.type === TokenType.ATTR_NAME) {
attrs.push(this._consumeAttr(this._advance()));
}
const fullName = this._getElementFullName(prefix, name, this._getParentElement());
let selfClosing = false;
// Note: There could have been a tokenizer error
// so that we don't get a token for the end tag...
if (this._peek.type === TokenType.TAG_OPEN_END_VOID) {
this._advance();
selfClosing = true;
const tagDef = this.getTagDefinition(fullName);
if (!(tagDef.canSelfClose || getNsPrefix(fullName) !== null || tagDef.isVoid)) {
this.errors.push(TreeError.create(fullName, startTagToken.sourceSpan, `Only void and foreign elements can be self closed "${startTagToken.parts[1]}"`));
}
}
else if (this._peek.type === TokenType.TAG_OPEN_END) {
this._advance();
selfClosing = false;
}
const end = this._peek.sourceSpan.fullStart;
const span = new ParseSourceSpan(startTagToken.sourceSpan.start, end, startTagToken.sourceSpan.fullStart);
// Create a separate `startSpan` because `span` will be modified when there is an `end` span.
const startSpan = new ParseSourceSpan(startTagToken.sourceSpan.start, end, startTagToken.sourceSpan.fullStart);
const el = new Element$1(fullName, attrs, [], span, startSpan, undefined);
this._pushElement(el);
if (selfClosing) {
// Elements that are self-closed have their `endSourceSpan` set to the full span, as the
// element start tag also represents the end tag.
this._popElement(fullName, span);
}
else if (startTagToken.type === TokenType.INCOMPLETE_TAG_OPEN) {
// We already know the opening tag is not complete, so it is unlikely it has a corresponding
// close tag. Let's optimistically parse it as a full element and emit an error.
this._popElement(fullName, null);
this.errors.push(TreeError.create(fullName, span, `Opening tag "${fullName}" not terminated.`));
}
}
_pushElement(el) {
const parentEl = this._getParentElement();
if (parentEl && this.getTagDefinition(parentEl.name).isClosedByChild(el.name)) {
this._elementStack.pop();
}
this._addToParent(el);
this._elementStack.push(el);
}
_consumeEndTag(endTagToken) {
const fullName = this._getElementFullName(endTagToken.parts[0], endTagToken.parts[1], this._getParentElement());
if (this.getTagDefinition(fullName).isVoid) {
this.errors.push(TreeError.create(fullName, endTagToken.sourceSpan, `Void elements do not have end tags "${endTagToken.parts[1]}"`));
}
else if (!this._popElement(fullName, endTagToken.sourceSpan)) {
const errMsg = `Unexpected closing tag "${fullName}". It may happen when the tag has already been closed by another tag. For more info see https://www.w3.org/TR/html5/syntax.html#closing-elements-that-have-implied-end-tags`;
this.errors.push(TreeError.create(fullName, endTagToken.sourceSpan, errMsg));
}
}
/**
* Closes the nearest element with the tag name `fullName` in the parse tree.
* `endSourceSpan` is the span of the closing tag, or null if the element does
* not have a closing tag (for example, this happens when an incomplete
* opening tag is recovered).
*/
_popElement(fullName, endSourceSpan) {
for (let stackIndex = this._elementStack.length - 1; stackIndex >= 0; stackIndex--) {
const el = this._elementStack[stackIndex];
if (el.name == fullName) {
// Record the parse span with the element that is being closed. Any elements that are
// removed from the element stack at this point are closed implicitly, so they won't get
// an end source span (as there is no explicit closing element).
el.endSourceSpan = endSourceSpan;
el.sourceSpan.end = endSourceSpan !== null ? endSourceSpan.end : el.sourceSpan.end;
this._elementStack.splice(stackIndex, this._elementStack.length - stackIndex);
return true;
}
if (!this.getTagDefinition(el.name).closedByParent) {
return false;
}
}
return false;
}
_consumeAttr(attrName) {
const fullName = mergeNsAndName(attrName.parts[0], attrName.parts[1]);
let end = attrName.sourceSpan.end;
let value = '';
let valueSpan = undefined;
if (this._peek.type === TokenType.ATTR_QUOTE) {
this._advance();
}
if (this._peek.type === TokenType.ATTR_VALUE) {
const valueToken = this._advance();
value = valueToken.parts[0];
end = valueToken.sourceSpan.end;
valueSpan = valueToken.sourceSpan;
}
if (this._peek.type === TokenType.ATTR_QUOTE) {
const quoteToken = this._advance();
end = quoteToken.sourceSpan.end;
}
const keySpan = new ParseSourceSpan(attrName.sourceSpan.start, attrName.sourceSpan.end);
return new Attribute(fullName, value, new ParseSourceSpan(attrName.sourceSpan.start, end, attrName.sourceSpan.fullStart), keySpan, valueSpan);
}
_getParentElement() {
return this._elementStack.length > 0 ? this._elementStack[this._elementStack.length - 1] : null;
}
_addToParent(node) {
const parent = this._getParentElement();
if (parent != null) {
parent.children.push(node);
}
else {
this.rootNodes.push(node);
}
}
_getElementFullName(prefix, localName, parentElement) {
if (prefix === '') {
prefix = this.getTagDefinition(localName).implicitNamespacePrefix || '';
if (prefix === '' && parentElement != null) {
const parentTagName = splitNsName(parentElement.name)[1];
const parentTagDefinition = this.getTagDefinition(parentTagName);
if (!parentTagDefinition.preventNamespaceInheritance) {
prefix = getNsPrefix(parentElement.name);
}
}
}
return mergeNsAndName(prefix, localName);
}
}
function lastOnStack(stack, element) {
return stack.length > 0 && stack[stack.length - 1] === element;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class HtmlParser extends Parser {
constructor() {
super(getHtmlTagDefinition);
}
parse(source, url, options) {
return super.parse(source, url, options);
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const PRESERVE_WS_ATTR_NAME = 'ngPreserveWhitespaces';
const SKIP_WS_TRIM_TAGS = new Set(['pre', 'template', 'textarea', 'script', 'style']);
// Equivalent to \s with \u00a0 (non-breaking space) excluded.
// Based on https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
const WS_CHARS = ' \f\n\r\t\v\u1680\u180e\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff';
const NO_WS_REGEXP = new RegExp(`[^${WS_CHARS}]`);
const WS_REPLACE_REGEXP = new RegExp(`[${WS_CHARS}]{2,}`, 'g');
function hasPreserveWhitespacesAttr(attrs) {
return attrs.some((attr) => attr.name === PRESERVE_WS_ATTR_NAME);
}
/**
* Angular Dart introduced &ngsp; as a placeholder for non-removable space, see:
* https://github.com/dart-lang/angular/blob/0bb611387d29d65b5af7f9d2515ab571fd3fbee4/_tests/test/compiler/preserve_whitespace_test.dart#L25-L32
* In Angular Dart &ngsp; is converted to the 0xE500 PUA (Private Use Areas) unicode character
* and later on replaced by a space. We are re-implementing the same idea here.
*/
function replaceNgsp(value) {
// lexer is replacing the &ngsp; pseudo-entity with NGSP_UNICODE
return value.replace(new RegExp(NGSP_UNICODE, 'g'), ' ');
}
/**
* This visitor can walk HTML parse tree and remove / trim text nodes using the following rules:
* - consider spaces, tabs and new lines as whitespace characters;
* - drop text nodes consisting of whitespace characters only;
* - for all other text nodes replace consecutive whitespace characters with one space;
* - convert &ngsp; pseudo-entity to a single space;
*
* Removal and trimming of whitespaces have positive performance impact (less code to generate
* while compiling templates, faster view creation). At the same time it can be "destructive"
* in some cases (whitespaces can influence layout). Because of the potential of breaking layout
* this visitor is not activated by default in Angular 5 and people need to explicitly opt-in for
* whitespace removal. The default option for whitespace removal will be revisited in Angular 6
* and might be changed to "on" by default.
*/
class WhitespaceVisitor {
visitElement(element, context) {
if (SKIP_WS_TRIM_TAGS.has(element.name) || hasPreserveWhitespacesAttr(element.attrs)) {
// don't descent into elements where we need to preserve whitespaces
// but still visit all attributes to eliminate one used as a market to preserve WS
return new Element$1(element.name, visitAll$1(this, element.attrs), element.children, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
}
return new Element$1(element.name, element.attrs, visitAllWithSiblings(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
}
visitAttribute(attribute, context) {
return attribute.name !== PRESERVE_WS_ATTR_NAME ? attribute : null;
}
visitText(text, context) {
const isNotBlank = text.value.match(NO_WS_REGEXP);
const hasExpansionSibling = context &&
(context.prev instanceof Expansion || context.next instanceof Expansion);
if (isNotBlank || hasExpansionSibling) {
return new Text$3(replaceNgsp(text.value).replace(WS_REPLACE_REGEXP, ' '), text.sourceSpan, text.i18n);
}
return null;
}
visitComment(comment, context) {
return comment;
}
visitExpansion(expansion, context) {
return expansion;
}
visitExpansionCase(expansionCase, context) {
return expansionCase;
}
}
function removeWhitespaces(htmlAstWithErrors) {
return new ParseTreeResult(visitAll$1(new WhitespaceVisitor(), htmlAstWithErrors.rootNodes), htmlAstWithErrors.errors);
}
function visitAllWithSiblings(visitor, nodes) {
const result = [];
nodes.forEach((ast, i) => {
const context = { prev: nodes[i - 1], next: nodes[i + 1] };
const astResult = ast.visit(visitor, context);
if (astResult) {
result.push(astResult);
}
});
return result;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// http://cldr.unicode.org/index/cldr-spec/plural-rules
const PLURAL_CASES = ['zero', 'one', 'two', 'few', 'many', 'other'];
/**
* Expands special forms into elements.
*
* For example,
*
* ```
* { messages.length, plural,
* =0 {zero}
* =1 {one}
* other {more than one}
* }
* ```
*
* will be expanded into
*
* ```
* <ng-container [ngPlural]="messages.length">
* <ng-template ngPluralCase="=0">zero</ng-template>
* <ng-template ngPluralCase="=1">one</ng-template>
* <ng-template ngPluralCase="other">more than one</ng-template>
* </ng-container>
* ```
*/
function expandNodes(nodes) {
const expander = new _Expander();
return new ExpansionResult(visitAll$1(expander, nodes), expander.isExpanded, expander.errors);
}
class ExpansionResult {
constructor(nodes, expanded, errors) {
this.nodes = nodes;
this.expanded = expanded;
this.errors = errors;
}
}
class ExpansionError extends ParseError {
constructor(span, errorMsg) {
super(span, errorMsg);
}
}
/**
* Expand expansion forms (plural, select) to directives
*
* @internal
*/
class _Expander {
constructor() {
this.isExpanded = false;
this.errors = [];
}
visitElement(element, context) {
return new Element$1(element.name, element.attrs, visitAll$1(this, element.children), element.sourceSpan, element.startSourceSpan, element.endSourceSpan);
}
visitAttribute(attribute, context) {
return attribute;
}
visitText(text, context) {
return text;
}
visitComment(comment, context) {
return comment;
}
visitExpansion(icu, context) {
this.isExpanded = true;
return icu.type == 'plural' ? _expandPluralForm(icu, this.errors) :
_expandDefaultForm(icu, this.errors);
}
visitExpansionCase(icuCase, context) {
throw new Error('Should not be reached');
}
}
// Plural forms are expanded to `NgPlural` and `NgPluralCase`s
function _expandPluralForm(ast, errors) {
const children = ast.cases.map(c => {
if (PLURAL_CASES.indexOf(c.value) == -1 && !c.value.match(/^=\d+$/)) {
errors.push(new ExpansionError(c.valueSourceSpan, `Plural cases should be "=<number>" or one of ${PLURAL_CASES.join(', ')}`));
}
const expansionResult = expandNodes(c.expression);
errors.push(...expansionResult.errors);
return new Element$1(`ng-template`, [new Attribute('ngPluralCase', `${c.value}`, c.valueSourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
});
const switchAttr = new Attribute('[ngPlural]', ast.switchValue, ast.switchValueSourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */);
return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan);
}
// ICU messages (excluding plural form) are expanded to `NgSwitch` and `NgSwitchCase`s
function _expandDefaultForm(ast, errors) {
const children = ast.cases.map(c => {
const expansionResult = expandNodes(c.expression);
errors.push(...expansionResult.errors);
if (c.value === 'other') {
// other is the default case when no values match
return new Element$1(`ng-template`, [new Attribute('ngSwitchDefault', '', c.valueSourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
}
return new Element$1(`ng-template`, [new Attribute('ngSwitchCase', `${c.value}`, c.valueSourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */)], expansionResult.nodes, c.sourceSpan, c.sourceSpan, c.sourceSpan);
});
const switchAttr = new Attribute('[ngSwitch]', ast.switchValue, ast.switchValueSourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */);
return new Element$1('ng-container', [switchAttr], children, ast.sourceSpan, ast.sourceSpan, ast.sourceSpan);
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A segment of text within the template.
*/
class TextAst {
constructor(value, ngContentIndex, sourceSpan) {
this.value = value;
this.ngContentIndex = ngContentIndex;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitText(this, context);
}
}
/**
* A bound expression within the text of a template.
*/
class BoundTextAst {
constructor(value, ngContentIndex, sourceSpan) {
this.value = value;
this.ngContentIndex = ngContentIndex;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitBoundText(this, context);
}
}
/**
* A plain attribute on an element.
*/
class AttrAst {
constructor(name, value, sourceSpan) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitAttr(this, context);
}
}
const BoundPropertyMapping = {
[4 /* Animation */]: 4 /* Animation */,
[1 /* Attribute */]: 1 /* Attribute */,
[2 /* Class */]: 2 /* Class */,
[0 /* Property */]: 0 /* Property */,
[3 /* Style */]: 3 /* Style */,
};
/**
* A binding for an element property (e.g. `[property]="expression"`) or an animation trigger (e.g.
* `[@trigger]="stateExp"`)
*/
class BoundElementPropertyAst {
constructor(name, type, securityContext, value, unit, sourceSpan) {
this.name = name;
this.type = type;
this.securityContext = securityContext;
this.value = value;
this.unit = unit;
this.sourceSpan = sourceSpan;
this.isAnimation = this.type === 4 /* Animation */;
}
static fromBoundProperty(prop) {
const type = BoundPropertyMapping[prop.type];
return new BoundElementPropertyAst(prop.name, type, prop.securityContext, prop.value, prop.unit, prop.sourceSpan);
}
visit(visitor, context) {
return visitor.visitElementProperty(this, context);
}
}
/**
* A binding for an element event (e.g. `(event)="handler()"`) or an animation trigger event (e.g.
* `(@trigger.phase)="callback($event)"`).
*/
class BoundEventAst {
constructor(name, target, phase, handler, sourceSpan, handlerSpan) {
this.name = name;
this.target = target;
this.phase = phase;
this.handler = handler;
this.sourceSpan = sourceSpan;
this.handlerSpan = handlerSpan;
this.fullName = BoundEventAst.calcFullName(this.name, this.target, this.phase);
this.isAnimation = !!this.phase;
}
static calcFullName(name, target, phase) {
if (target) {
return `${target}:${name}`;
}
if (phase) {
return `@${name}.${phase}`;
}
return name;
}
static fromParsedEvent(event) {
const target = event.type === 0 /* Regular */ ? event.targetOrPhase : null;
const phase = event.type === 1 /* Animation */ ? event.targetOrPhase : null;
return new BoundEventAst(event.name, target, phase, event.handler, event.sourceSpan, event.handlerSpan);
}
visit(visitor, context) {
return visitor.visitEvent(this, context);
}
}
/**
* A reference declaration on an element (e.g. `let someName="expression"`).
*/
class ReferenceAst {
constructor(name, value, originalValue, sourceSpan) {
this.name = name;
this.value = value;
this.originalValue = originalValue;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitReference(this, context);
}
}
/**
* A variable declaration on a <ng-template> (e.g. `var-someName="someLocalName"`).
*/
class VariableAst {
constructor(name, value, sourceSpan, valueSpan) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
this.valueSpan = valueSpan;
}
static fromParsedVariable(v) {
return new VariableAst(v.name, v.value, v.sourceSpan, v.valueSpan);
}
visit(visitor, context) {
return visitor.visitVariable(this, context);
}
}
/**
* An element declaration in a template.
*/
class ElementAst {
constructor(name, attrs, inputs, outputs, references, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan, endSourceSpan) {
this.name = name;
this.attrs = attrs;
this.inputs = inputs;
this.outputs = outputs;
this.references = references;
this.directives = directives;
this.providers = providers;
this.hasViewContainer = hasViewContainer;
this.queryMatches = queryMatches;
this.children = children;
this.ngContentIndex = ngContentIndex;
this.sourceSpan = sourceSpan;
this.endSourceSpan = endSourceSpan;
}
visit(visitor, context) {
return visitor.visitElement(this, context);
}
}
/**
* A `<ng-template>` element included in an Angular template.
*/
class EmbeddedTemplateAst {
constructor(attrs, outputs, references, variables, directives, providers, hasViewContainer, queryMatches, children, ngContentIndex, sourceSpan) {
this.attrs = attrs;
this.outputs = outputs;
this.references = references;
this.variables = variables;
this.directives = directives;
this.providers = providers;
this.hasViewContainer = hasViewContainer;
this.queryMatches = queryMatches;
this.children = children;
this.ngContentIndex = ngContentIndex;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitEmbeddedTemplate(this, context);
}
}
/**
* A directive property with a bound value (e.g. `*ngIf="condition").
*/
class BoundDirectivePropertyAst {
constructor(directiveName, templateName, value, sourceSpan) {
this.directiveName = directiveName;
this.templateName = templateName;
this.value = value;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitDirectiveProperty(this, context);
}
}
/**
* A directive declared on an element.
*/
class DirectiveAst {
constructor(directive, inputs, hostProperties, hostEvents, contentQueryStartId, sourceSpan) {
this.directive = directive;
this.inputs = inputs;
this.hostProperties = hostProperties;
this.hostEvents = hostEvents;
this.contentQueryStartId = contentQueryStartId;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitDirective(this, context);
}
}
/**
* A provider declared on an element
*/
class ProviderAst {
constructor(token, multiProvider, eager, providers, providerType, lifecycleHooks, sourceSpan, isModule) {
this.token = token;
this.multiProvider = multiProvider;
this.eager = eager;
this.providers = providers;
this.providerType = providerType;
this.lifecycleHooks = lifecycleHooks;
this.sourceSpan = sourceSpan;
this.isModule = isModule;
}
visit(visitor, context) {
// No visit method in the visitor for now...
return null;
}
}
var ProviderAstType;
(function (ProviderAstType) {
ProviderAstType[ProviderAstType["PublicService"] = 0] = "PublicService";
ProviderAstType[ProviderAstType["PrivateService"] = 1] = "PrivateService";
ProviderAstType[ProviderAstType["Component"] = 2] = "Component";
ProviderAstType[ProviderAstType["Directive"] = 3] = "Directive";
ProviderAstType[ProviderAstType["Builtin"] = 4] = "Builtin";
})(ProviderAstType || (ProviderAstType = {}));
/**
* Position where content is to be projected (instance of `<ng-content>` in a template).
*/
class NgContentAst {
constructor(index, ngContentIndex, sourceSpan) {
this.index = index;
this.ngContentIndex = ngContentIndex;
this.sourceSpan = sourceSpan;
}
visit(visitor, context) {
return visitor.visitNgContent(this, context);
}
}
/**
* A visitor that accepts each node but doesn't do anything. It is intended to be used
* as the base class for a visitor that is only interested in a subset of the node types.
*/
class NullTemplateVisitor {
visitNgContent(ast, context) { }
visitEmbeddedTemplate(ast, context) { }
visitElement(ast, context) { }
visitReference(ast, context) { }
visitVariable(ast, context) { }
visitEvent(ast, context) { }
visitElementProperty(ast, context) { }
visitAttr(ast, context) { }
visitBoundText(ast, context) { }
visitText(ast, context) { }
visitDirective(ast, context) { }
visitDirectiveProperty(ast, context) { }
}
/**
* Base class that can be used to build a visitor that visits each node
* in an template ast recursively.
*/
class RecursiveTemplateAstVisitor extends NullTemplateVisitor {
constructor() {
super();
}
// Nodes with children
visitEmbeddedTemplate(ast, context) {
return this.visitChildren(context, visit => {
visit(ast.attrs);
visit(ast.references);
visit(ast.variables);
visit(ast.directives);
visit(ast.providers);
visit(ast.children);
});
}
visitElement(ast, context) {
return this.visitChildren(context, visit => {
visit(ast.attrs);
visit(ast.inputs);
visit(ast.outputs);
visit(ast.references);
visit(ast.directives);
visit(ast.providers);
visit(ast.children);
});
}
visitDirective(ast, context) {
return this.visitChildren(context, visit => {
visit(ast.inputs);
visit(ast.hostProperties);
visit(ast.hostEvents);
});
}
visitChildren(context, cb) {
let results = [];
let t = this;
function visit(children) {
if (children && children.length)
results.push(templateVisitAll(t, children, context));
}
cb(visit);
return Array.prototype.concat.apply([], results);
}
}
/**
* Visit every node in a list of {@link TemplateAst}s with the given {@link TemplateAstVisitor}.
*/
function templateVisitAll(visitor, asts, context = null) {
const result = [];
const visit = visitor.visit ?
(ast) => visitor.visit(ast, context) || ast.visit(visitor, context) :
(ast) => ast.visit(visitor, context);
asts.forEach(ast => {
const astResult = visit(ast);
if (astResult) {
result.push(astResult);
}
});
return result;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class ProviderError extends ParseError {
constructor(message, span) {
super(span, message);
}
}
class ProviderViewContext {
constructor(reflector, component) {
this.reflector = reflector;
this.component = component;
this.errors = [];
this.viewQueries = _getViewQueries(component);
this.viewProviders = new Map();
component.viewProviders.forEach((provider) => {
if (this.viewProviders.get(tokenReference(provider.token)) == null) {
this.viewProviders.set(tokenReference(provider.token), true);
}
});
}
}
class ProviderElementContext {
constructor(viewContext, _parent, _isViewRoot, _directiveAsts, attrs, refs, isTemplate, contentQueryStartId, _sourceSpan) {
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((attrAst) => this._attrs[attrAst.name] = attrAst.value);
const directivesMeta = _directiveAsts.map(directiveAst => directiveAst.directive);
this._allProviders =
_resolveProvidersFromDirectives(directivesMeta, _sourceSpan, viewContext.errors);
this._contentQueries = _getContentQueries(contentQueryStartId, directivesMeta);
Array.from(this._allProviders.values()).forEach((provider) => {
this._addQueryReadsTo(provider.token, provider.token, this._queriedTokens);
});
if (isTemplate) {
const templateRefId = createTokenForExternalReference(this.viewContext.reflector, Identifiers.TemplateRef);
this._addQueryReadsTo(templateRefId, templateRefId, this._queriedTokens);
}
refs.forEach((refAst) => {
let 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((provider) => {
const eager = provider.eager || this._queriedTokens.get(tokenReference(provider.token));
if (eager) {
this._getOrCreateLocalProvider(provider.providerType, provider.token, true);
}
});
}
afterElement() {
// collect lazy providers
Array.from(this._allProviders.values()).forEach((provider) => {
this._getOrCreateLocalProvider(provider.providerType, provider.token, false);
});
}
get transformProviders() {
// Note: Maps keep their insertion order.
const lazyProviders = [];
const eagerProviders = [];
this._transformedProviders.forEach(provider => {
if (provider.eager) {
eagerProviders.push(provider);
}
else {
lazyProviders.push(provider);
}
});
return lazyProviders.concat(eagerProviders);
}
get transformedDirectiveAsts() {
const sortedProviderTypes = this.transformProviders.map(provider => provider.token.identifier);
const sortedDirectives = this._directiveAsts.slice();
sortedDirectives.sort((dir1, dir2) => sortedProviderTypes.indexOf(dir1.directive.type) -
sortedProviderTypes.indexOf(dir2.directive.type));
return sortedDirectives;
}
get queryMatches() {
const allMatches = [];
this._queriedTokens.forEach((matches) => {
allMatches.push(...matches);
});
return allMatches;
}
_addQueryReadsTo(token, defaultValue, queryReadTokens) {
this._getQueriesFor(token).forEach((query) => {
const queryValue = query.meta.read || defaultValue;
const tokenRef = tokenReference(queryValue);
let queryMatches = queryReadTokens.get(tokenRef);
if (!queryMatches) {
queryMatches = [];
queryReadTokens.set(tokenRef, queryMatches);
}
queryMatches.push({ queryId: query.queryId, value: queryValue });
});
}
_getQueriesFor(token) {
const result = [];
let currentEl = this;
let distance = 0;
let queries;
while (currentEl !== null) {
queries = currentEl._contentQueries.get(tokenReference(token));
if (queries) {
result.push(...queries.filter((query) => 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(...queries);
}
return result;
}
_getOrCreateLocalProvider(requestingProviderType, token, eager) {
const 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;
}
let 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);
const transformedProviders = resolvedProvider.providers.map((provider) => {
let transformedUseValue = provider.useValue;
let transformedUseExisting = provider.useExisting;
let transformedDeps = undefined;
if (provider.useExisting != null) {
const 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) {
const deps = provider.deps || provider.useFactory.diDeps;
transformedDeps =
deps.map((dep) => this._getDependency(resolvedProvider.providerType, dep, eager));
}
else if (provider.useClass) {
const deps = provider.deps || provider.useClass.diDeps;
transformedDeps =
deps.map((dep) => 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;
}
_getLocalDependency(requestingProviderType, dep, eager = false) {
if (dep.isAttribute) {
const 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;
}
_getDependency(requestingProviderType, dep, eager = false) {
let currElement = this;
let currEager = eager;
let 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) {
const 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;
}
}
class NgModuleProviderAnalyzer {
constructor(reflector, ngModule, extraProviders, sourceSpan) {
this.reflector = reflector;
this._transformedProviders = new Map();
this._seenProviders = new Map();
this._errors = [];
this._allProviders = new Map();
ngModule.transitiveModule.modules.forEach((ngModuleType) => {
const ngModuleProvider = { token: { identifier: ngModuleType }, useClass: ngModuleType };
_resolveProviders([ngModuleProvider], ProviderAstType.PublicService, true, sourceSpan, this._errors, this._allProviders, /* isModule */ true);
});
_resolveProviders(ngModule.transitiveModule.providers.map(entry => entry.provider).concat(extraProviders), ProviderAstType.PublicService, false, sourceSpan, this._errors, this._allProviders,
/* isModule */ false);
}
parse() {
Array.from(this._allProviders.values()).forEach((provider) => {
this._getOrCreateLocalProvider(provider.token, provider.eager);
});
if (this._errors.length > 0) {
const errorString = this._errors.join('\n');
throw new Error(`Provider parse errors:\n${errorString}`);
}
// Note: Maps keep their insertion order.
const lazyProviders = [];
const eagerProviders = [];
this._transformedProviders.forEach(provider => {
if (provider.eager) {
eagerProviders.push(provider);
}
else {
lazyProviders.push(provider);
}
});
return lazyProviders.concat(eagerProviders);
}
_getOrCreateLocalProvider(token, eager) {
const resolvedProvider = this._allProviders.get(tokenReference(token));
if (!resolvedProvider) {
return null;
}
let 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);
const transformedProviders = resolvedProvider.providers.map((provider) => {
let transformedUseValue = provider.useValue;
let transformedUseExisting = provider.useExisting;
let transformedDeps = undefined;
if (provider.useExisting != null) {
const 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) {
const deps = provider.deps || provider.useFactory.diDeps;
transformedDeps =
deps.map((dep) => this._getDependency(dep, eager, resolvedProvider.sourceSpan));
}
else if (provider.useClass) {
const deps = provider.deps || provider.useClass.diDeps;
transformedDeps =
deps.map((dep) => 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;
}
_getDependency(dep, eager = false, requestorSourceSpan) {
let foundLocal = 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)) {
foundLocal = true;
// access providers
}
else if (this._getOrCreateLocalProvider(dep.token, eager) != null) {
foundLocal = true;
}
}
return dep;
}
}
function _transformProvider(provider, { useExisting, useValue, deps }) {
return {
token: provider.token,
useClass: provider.useClass,
useExisting: useExisting,
useFactory: provider.useFactory,
useValue: useValue,
deps: deps,
multi: provider.multi
};
}
function _transformProviderAst(provider, { eager, 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) {
const providersByToken = new Map();
directives.forEach((directive) => {
const 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!
const directivesWithComponentFirst = directives.filter(dir => dir.isComponent).concat(directives.filter(dir => !dir.isComponent));
directivesWithComponentFirst.forEach((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((provider) => {
let 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) {
const lifecycleHooks = provider.token.identifier &&
provider.token.identifier.lifecycleHooks ?
provider.token.identifier.lifecycleHooks :
[];
const 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!
let viewQueryId = 1;
const viewQueries = new Map();
if (component.viewQueries) {
component.viewQueries.forEach((query) => _addQueryToTokenMap(viewQueries, { meta: query, queryId: viewQueryId++ }));
}
return viewQueries;
}
function _getContentQueries(contentQueryStartId, directives) {
let contentQueryId = contentQueryStartId;
const contentQueries = new Map();
directives.forEach((directive, directiveIndex) => {
if (directive.queries) {
directive.queries.forEach((query) => _addQueryToTokenMap(contentQueries, { meta: query, queryId: contentQueryId++ }));
}
});
return contentQueries;
}
function _addQueryToTokenMap(map, query) {
query.meta.selectors.forEach((token) => {
let entry = map.get(tokenReference(token));
if (!entry) {
entry = [];
map.set(tokenReference(token), entry);
}
entry.push(query);
});
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class StyleWithImports {
constructor(style, styleUrls) {
this.style = style;
this.styleUrls = styleUrls;
}
}
function isStyleUrlResolvable(url) {
if (url == null || url.length === 0 || url[0] == '/')
return false;
const schemeMatch = url.match(URL_WITH_SCHEMA_REGEXP);
return schemeMatch === null || schemeMatch[1] == 'package' || schemeMatch[1] == 'asset';
}
/**
* Rewrites stylesheets by resolving and removing the @import urls that
* are either relative or don't have a `package:` scheme
*/
function extractStyleUrls(resolver, baseUrl, cssText) {
const foundUrls = [];
const modifiedCssText = cssText.replace(CSS_STRIPPABLE_COMMENT_REGEXP, '')
.replace(CSS_IMPORT_REGEXP, (...m) => {
const url = m[1] || m[2];
if (!isStyleUrlResolvable(url)) {
// Do not attempt to resolve non-package absolute URLs with URI
// scheme
return m[0];
}
foundUrls.push(resolver.resolve(baseUrl, url));
return '';
});
return new StyleWithImports(modifiedCssText, foundUrls);
}
const CSS_IMPORT_REGEXP = /@import\s+(?:url\()?\s*(?:(?:['"]([^'"]*))|([^;\)\s]*))[^;]*;?/g;
const CSS_STRIPPABLE_COMMENT_REGEXP = /\/\*(?!#\s*(?:sourceURL|sourceMappingURL)=)[\s\S]+?\*\//g;
const URL_WITH_SCHEMA_REGEXP = /^([^:/?#]+):/;
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const PROPERTY_PARTS_SEPARATOR = '.';
const ATTRIBUTE_PREFIX = 'attr';
const CLASS_PREFIX = 'class';
const STYLE_PREFIX = 'style';
const TEMPLATE_ATTR_PREFIX = '*';
const ANIMATE_PROP_PREFIX = 'animate-';
/**
* Parses bindings in templates and in the directive host area.
*/
class BindingParser {
constructor(_exprParser, _interpolationConfig, _schemaRegistry, pipes, errors) {
this._exprParser = _exprParser;
this._interpolationConfig = _interpolationConfig;
this._schemaRegistry = _schemaRegistry;
this.errors = errors;
this.pipesByName = null;
this._usedPipes = new Map();
// When the `pipes` parameter is `null`, do not check for used pipes
// This is used in IVY when we might not know the available pipes at compile time
if (pipes) {
const pipesByName = new Map();
pipes.forEach(pipe => pipesByName.set(pipe.name, pipe));
this.pipesByName = pipesByName;
}
}
get interpolationConfig() {
return this._interpolationConfig;
}
getUsedPipes() {
return Array.from(this._usedPipes.values());
}
createBoundHostProperties(dirMeta, sourceSpan) {
if (dirMeta.hostProperties) {
const boundProps = [];
Object.keys(dirMeta.hostProperties).forEach(propName => {
const expression = dirMeta.hostProperties[propName];
if (typeof expression === 'string') {
this.parsePropertyBinding(propName, expression, true, sourceSpan, sourceSpan.start.offset, undefined, [],
// Use the `sourceSpan` for `keySpan`. This isn't really accurate, but neither is the
// sourceSpan, as it represents the sourceSpan of the host itself rather than the
// source of the host binding (which doesn't exist in the template). Regardless,
// neither of these values are used in Ivy but are only here to satisfy the function
// signature. This should likely be refactored in the future so that `sourceSpan`
// isn't being used inaccurately.
boundProps, sourceSpan);
}
else {
this._reportError(`Value of the host property binding "${propName}" needs to be a string representing an expression but got "${expression}" (${typeof expression})`, sourceSpan);
}
});
return boundProps;
}
return null;
}
createDirectiveHostPropertyAsts(dirMeta, elementSelector, sourceSpan) {
const boundProps = this.createBoundHostProperties(dirMeta, sourceSpan);
return boundProps &&
boundProps.map((prop) => this.createBoundElementProperty(elementSelector, prop));
}
createDirectiveHostEventAsts(dirMeta, sourceSpan) {
if (dirMeta.hostListeners) {
const targetEvents = [];
Object.keys(dirMeta.hostListeners).forEach(propName => {
const expression = dirMeta.hostListeners[propName];
if (typeof expression === 'string') {
// Use the `sourceSpan` for `keySpan` and `handlerSpan`. This isn't really accurate, but
// neither is the `sourceSpan`, as it represents the `sourceSpan` of the host itself
// rather than the source of the host binding (which doesn't exist in the template).
// Regardless, neither of these values are used in Ivy but are only here to satisfy the
// function signature. This should likely be refactored in the future so that `sourceSpan`
// isn't being used inaccurately.
this.parseEvent(propName, expression, sourceSpan, sourceSpan, [], targetEvents, sourceSpan);
}
else {
this._reportError(`Value of the host listener "${propName}" needs to be a string representing an expression but got "${expression}" (${typeof expression})`, sourceSpan);
}
});
return targetEvents;
}
return null;
}
parseInterpolation(value, sourceSpan) {
const sourceInfo = sourceSpan.start.toString();
const absoluteOffset = sourceSpan.fullStart.offset;
try {
const ast = this._exprParser.parseInterpolation(value, sourceInfo, absoluteOffset, this._interpolationConfig);
if (ast)
this._reportExpressionParserErrors(ast.errors, sourceSpan);
this._checkPipes(ast, sourceSpan);
return ast;
}
catch (e) {
this._reportError(`${e}`, sourceSpan);
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset);
}
}
/**
* Similar to `parseInterpolation`, but treats the provided string as a single expression
* element that would normally appear within the interpolation prefix and suffix (`{{` and `}}`).
* This is used for parsing the switch expression in ICUs.
*/
parseInterpolationExpression(expression, sourceSpan) {
const sourceInfo = sourceSpan.start.toString();
const absoluteOffset = sourceSpan.start.offset;
try {
const ast = this._exprParser.parseInterpolationExpression(expression, sourceInfo, absoluteOffset);
if (ast)
this._reportExpressionParserErrors(ast.errors, sourceSpan);
this._checkPipes(ast, sourceSpan);
return ast;
}
catch (e) {
this._reportError(`${e}`, sourceSpan);
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset);
}
}
/**
* Parses the bindings in a microsyntax expression, and converts them to
* `ParsedProperty` or `ParsedVariable`.
*
* @param tplKey template binding name
* @param tplValue template binding value
* @param sourceSpan span of template binding relative to entire the template
* @param absoluteValueOffset start of the tplValue relative to the entire template
* @param targetMatchableAttrs potential attributes to match in the template
* @param targetProps target property bindings in the template
* @param targetVars target variables in the template
*/
parseInlineTemplateBinding(tplKey, tplValue, sourceSpan, absoluteValueOffset, targetMatchableAttrs, targetProps, targetVars, isIvyAst) {
const absoluteKeyOffset = sourceSpan.start.offset + TEMPLATE_ATTR_PREFIX.length;
const bindings = this._parseTemplateBindings(tplKey, tplValue, sourceSpan, absoluteKeyOffset, absoluteValueOffset);
for (const binding of bindings) {
// sourceSpan is for the entire HTML attribute. bindingSpan is for a particular
// binding within the microsyntax expression so it's more narrow than sourceSpan.
const bindingSpan = moveParseSourceSpan(sourceSpan, binding.sourceSpan);
const key = binding.key.source;
const keySpan = moveParseSourceSpan(sourceSpan, binding.key.span);
if (binding instanceof VariableBinding) {
const value = binding.value ? binding.value.source : '$implicit';
const valueSpan = binding.value ? moveParseSourceSpan(sourceSpan, binding.value.span) : undefined;
targetVars.push(new ParsedVariable(key, value, bindingSpan, keySpan, valueSpan));
}
else if (binding.value) {
const srcSpan = isIvyAst ? bindingSpan : sourceSpan;
const valueSpan = moveParseSourceSpan(sourceSpan, binding.value.ast.sourceSpan);
this._parsePropertyAst(key, binding.value, srcSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps);
}
else {
targetMatchableAttrs.push([key, '' /* value */]);
// Since this is a literal attribute with no RHS, source span should be
// just the key span.
this.parseLiteralAttr(key, null /* value */, keySpan, absoluteValueOffset, undefined /* valueSpan */, targetMatchableAttrs, targetProps, keySpan);
}
}
}
/**
* Parses the bindings in a microsyntax expression, e.g.
* ```
* <tag *tplKey="let value1 = prop; let value2 = localVar">
* ```
*
* @param tplKey template binding name
* @param tplValue template binding value
* @param sourceSpan span of template binding relative to entire the template
* @param absoluteKeyOffset start of the `tplKey`
* @param absoluteValueOffset start of the `tplValue`
*/
_parseTemplateBindings(tplKey, tplValue, sourceSpan, absoluteKeyOffset, absoluteValueOffset) {
const sourceInfo = sourceSpan.start.toString();
try {
const bindingsResult = this._exprParser.parseTemplateBindings(tplKey, tplValue, sourceInfo, absoluteKeyOffset, absoluteValueOffset);
this._reportExpressionParserErrors(bindingsResult.errors, sourceSpan);
bindingsResult.templateBindings.forEach((binding) => {
if (binding.value instanceof ASTWithSource) {
this._checkPipes(binding.value, sourceSpan);
}
});
bindingsResult.warnings.forEach((warning) => {
this._reportError(warning, sourceSpan, ParseErrorLevel.WARNING);
});
return bindingsResult.templateBindings;
}
catch (e) {
this._reportError(`${e}`, sourceSpan);
return [];
}
}
parseLiteralAttr(name, value, sourceSpan, absoluteOffset, valueSpan, targetMatchableAttrs,
// TODO(atscott): keySpan is only optional here so VE template parser implementation does not
// have to change This should be required when VE is removed.
targetProps, keySpan) {
if (isAnimationLabel(name)) {
name = name.substring(1);
if (keySpan !== undefined) {
keySpan = moveParseSourceSpan(keySpan, new AbsoluteSourceSpan(keySpan.start.offset + 1, keySpan.end.offset));
}
if (value) {
this._reportError(`Assigning animation triggers via @prop="exp" attributes with an expression is invalid.` +
` Use property bindings (e.g. [@prop]="exp") or use an attribute without a value (e.g. @prop) instead.`, sourceSpan, ParseErrorLevel.ERROR);
}
this._parseAnimation(name, value, sourceSpan, absoluteOffset, keySpan, valueSpan, targetMatchableAttrs, targetProps);
}
else {
targetProps.push(new ParsedProperty(name, this._exprParser.wrapLiteralPrimitive(value, '', absoluteOffset), ParsedPropertyType.LITERAL_ATTR, sourceSpan, keySpan, valueSpan));
}
}
parsePropertyBinding(name, expression, isHost, sourceSpan, absoluteOffset, valueSpan,
// TODO(atscott): keySpan is only optional here so VE template parser implementation does not
// have to change This should be required when VE is removed.
targetMatchableAttrs, targetProps, keySpan) {
if (name.length === 0) {
this._reportError(`Property name is missing in binding`, sourceSpan);
}
let isAnimationProp = false;
if (name.startsWith(ANIMATE_PROP_PREFIX)) {
isAnimationProp = true;
name = name.substring(ANIMATE_PROP_PREFIX.length);
if (keySpan !== undefined) {
keySpan = moveParseSourceSpan(keySpan, new AbsoluteSourceSpan(keySpan.start.offset + ANIMATE_PROP_PREFIX.length, keySpan.end.offset));
}
}
else if (isAnimationLabel(name)) {
isAnimationProp = true;
name = name.substring(1);
if (keySpan !== undefined) {
keySpan = moveParseSourceSpan(keySpan, new AbsoluteSourceSpan(keySpan.start.offset + 1, keySpan.end.offset));
}
}
if (isAnimationProp) {
this._parseAnimation(name, expression, sourceSpan, absoluteOffset, keySpan, valueSpan, targetMatchableAttrs, targetProps);
}
else {
this._parsePropertyAst(name, this._parseBinding(expression, isHost, valueSpan || sourceSpan, absoluteOffset), sourceSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps);
}
}
parsePropertyInterpolation(name, value, sourceSpan, valueSpan, targetMatchableAttrs,
// TODO(atscott): keySpan is only optional here so VE template parser implementation does not
// have to change This should be required when VE is removed.
targetProps, keySpan) {
const expr = this.parseInterpolation(value, valueSpan || sourceSpan);
if (expr) {
this._parsePropertyAst(name, expr, sourceSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps);
return true;
}
return false;
}
_parsePropertyAst(name, ast, sourceSpan, keySpan, valueSpan, targetMatchableAttrs, targetProps) {
targetMatchableAttrs.push([name, ast.source]);
targetProps.push(new ParsedProperty(name, ast, ParsedPropertyType.DEFAULT, sourceSpan, keySpan, valueSpan));
}
_parseAnimation(name, expression, sourceSpan, absoluteOffset, keySpan, valueSpan, targetMatchableAttrs, targetProps) {
if (name.length === 0) {
this._reportError('Animation trigger is missing', sourceSpan);
}
// This will occur when a @trigger is not paired with an expression.
// For animations it is valid to not have an expression since */void
// states will be applied by angular when the element is attached/detached
const ast = this._parseBinding(expression || 'undefined', false, valueSpan || sourceSpan, absoluteOffset);
targetMatchableAttrs.push([name, ast.source]);
targetProps.push(new ParsedProperty(name, ast, ParsedPropertyType.ANIMATION, sourceSpan, keySpan, valueSpan));
}
_parseBinding(value, isHostBinding, sourceSpan, absoluteOffset) {
const sourceInfo = (sourceSpan && sourceSpan.start || '(unknown)').toString();
try {
const ast = isHostBinding ?
this._exprParser.parseSimpleBinding(value, sourceInfo, absoluteOffset, this._interpolationConfig) :
this._exprParser.parseBinding(value, sourceInfo, absoluteOffset, this._interpolationConfig);
if (ast)
this._reportExpressionParserErrors(ast.errors, sourceSpan);
this._checkPipes(ast, sourceSpan);
return ast;
}
catch (e) {
this._reportError(`${e}`, sourceSpan);
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset);
}
}
createBoundElementProperty(elementSelector, boundProp, skipValidation = false, mapPropertyName = true) {
if (boundProp.isAnimation) {
return new BoundElementProperty(boundProp.name, 4 /* Animation */, SecurityContext.NONE, boundProp.expression, null, boundProp.sourceSpan, boundProp.keySpan, boundProp.valueSpan);
}
let unit = null;
let bindingType = undefined;
let boundPropertyName = null;
const parts = boundProp.name.split(PROPERTY_PARTS_SEPARATOR);
let securityContexts = undefined;
// Check for special cases (prefix style, attr, class)
if (parts.length > 1) {
if (parts[0] == ATTRIBUTE_PREFIX) {
boundPropertyName = parts.slice(1).join(PROPERTY_PARTS_SEPARATOR);
if (!skipValidation) {
this._validatePropertyOrAttributeName(boundPropertyName, boundProp.sourceSpan, true);
}
securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, boundPropertyName, true);
const nsSeparatorIdx = boundPropertyName.indexOf(':');
if (nsSeparatorIdx > -1) {
const ns = boundPropertyName.substring(0, nsSeparatorIdx);
const name = boundPropertyName.substring(nsSeparatorIdx + 1);
boundPropertyName = mergeNsAndName(ns, name);
}
bindingType = 1 /* Attribute */;
}
else if (parts[0] == CLASS_PREFIX) {
boundPropertyName = parts[1];
bindingType = 2 /* Class */;
securityContexts = [SecurityContext.NONE];
}
else if (parts[0] == STYLE_PREFIX) {
unit = parts.length > 2 ? parts[2] : null;
boundPropertyName = parts[1];
bindingType = 3 /* Style */;
securityContexts = [SecurityContext.STYLE];
}
}
// If not a special case, use the full property name
if (boundPropertyName === null) {
const mappedPropName = this._schemaRegistry.getMappedPropName(boundProp.name);
boundPropertyName = mapPropertyName ? mappedPropName : boundProp.name;
securityContexts = calcPossibleSecurityContexts(this._schemaRegistry, elementSelector, mappedPropName, false);
bindingType = 0 /* Property */;
if (!skipValidation) {
this._validatePropertyOrAttributeName(mappedPropName, boundProp.sourceSpan, false);
}
}
return new BoundElementProperty(boundPropertyName, bindingType, securityContexts[0], boundProp.expression, unit, boundProp.sourceSpan, boundProp.keySpan, boundProp.valueSpan);
}
// TODO: keySpan should be required but was made optional to avoid changing VE parser.
parseEvent(name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents, keySpan) {
if (name.length === 0) {
this._reportError(`Event name is missing in binding`, sourceSpan);
}
if (isAnimationLabel(name)) {
name = name.substr(1);
if (keySpan !== undefined) {
keySpan = moveParseSourceSpan(keySpan, new AbsoluteSourceSpan(keySpan.start.offset + 1, keySpan.end.offset));
}
this._parseAnimationEvent(name, expression, sourceSpan, handlerSpan, targetEvents, keySpan);
}
else {
this._parseRegularEvent(name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents, keySpan);
}
}
calcPossibleSecurityContexts(selector, propName, isAttribute) {
const prop = this._schemaRegistry.getMappedPropName(propName);
return calcPossibleSecurityContexts(this._schemaRegistry, selector, prop, isAttribute);
}
_parseAnimationEvent(name, expression, sourceSpan, handlerSpan, targetEvents, keySpan) {
const matches = splitAtPeriod(name, [name, '']);
const eventName = matches[0];
const phase = matches[1].toLowerCase();
const ast = this._parseAction(expression, handlerSpan);
targetEvents.push(new ParsedEvent(eventName, phase, 1 /* Animation */, ast, sourceSpan, handlerSpan, keySpan));
if (eventName.length === 0) {
this._reportError(`Animation event name is missing in binding`, sourceSpan);
}
if (phase) {
if (phase !== 'start' && phase !== 'done') {
this._reportError(`The provided animation output phase value "${phase}" for "@${eventName}" is not supported (use start or done)`, sourceSpan);
}
}
else {
this._reportError(`The animation trigger output event (@${eventName}) is missing its phase value name (start or done are currently supported)`, sourceSpan);
}
}
_parseRegularEvent(name, expression, sourceSpan, handlerSpan, targetMatchableAttrs, targetEvents, keySpan) {
// long format: 'target: eventName'
const [target, eventName] = splitAtColon(name, [null, name]);
const ast = this._parseAction(expression, handlerSpan);
targetMatchableAttrs.push([name, ast.source]);
targetEvents.push(new ParsedEvent(eventName, target, 0 /* Regular */, ast, sourceSpan, handlerSpan, keySpan));
// Don't detect directives for event names for now,
// so don't add the event name to the matchableAttrs
}
_parseAction(value, sourceSpan) {
const sourceInfo = (sourceSpan && sourceSpan.start || '(unknown').toString();
const absoluteOffset = (sourceSpan && sourceSpan.start) ? sourceSpan.start.offset : 0;
try {
const ast = this._exprParser.parseAction(value, sourceInfo, absoluteOffset, this._interpolationConfig);
if (ast) {
this._reportExpressionParserErrors(ast.errors, sourceSpan);
}
if (!ast || ast.ast instanceof EmptyExpr) {
this._reportError(`Empty expressions are not allowed`, sourceSpan);
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset);
}
this._checkPipes(ast, sourceSpan);
return ast;
}
catch (e) {
this._reportError(`${e}`, sourceSpan);
return this._exprParser.wrapLiteralPrimitive('ERROR', sourceInfo, absoluteOffset);
}
}
_reportError(message, sourceSpan, level = ParseErrorLevel.ERROR) {
this.errors.push(new ParseError(sourceSpan, message, level));
}
_reportExpressionParserErrors(errors, sourceSpan) {
for (const error of errors) {
this._reportError(error.message, sourceSpan);
}
}
// Make sure all the used pipes are known in `this.pipesByName`
_checkPipes(ast, sourceSpan) {
if (ast && this.pipesByName) {
const collector = new PipeCollector();
ast.visit(collector);
collector.pipes.forEach((ast, pipeName) => {
const pipeMeta = this.pipesByName.get(pipeName);
if (!pipeMeta) {
this._reportError(`The pipe '${pipeName}' could not be found`, new ParseSourceSpan(sourceSpan.start.moveBy(ast.span.start), sourceSpan.start.moveBy(ast.span.end)));
}
else {
this._usedPipes.set(pipeName, pipeMeta);
}
});
}
}
/**
* @param propName the name of the property / attribute
* @param sourceSpan
* @param isAttr true when binding to an attribute
*/
_validatePropertyOrAttributeName(propName, sourceSpan, isAttr) {
const report = isAttr ? this._schemaRegistry.validateAttribute(propName) :
this._schemaRegistry.validateProperty(propName);
if (report.error) {
this._reportError(report.msg, sourceSpan, ParseErrorLevel.ERROR);
}
}
}
class PipeCollector extends RecursiveAstVisitor$1 {
constructor() {
super(...arguments);
this.pipes = new Map();
}
visitPipe(ast, context) {
this.pipes.set(ast.name, ast);
ast.exp.visit(this);
this.visitAll(ast.args, context);
return null;
}
}
function isAnimationLabel(name) {
return name[0] == '@';
}
function calcPossibleSecurityContexts(registry, selector, propName, isAttribute) {
const ctxs = [];
CssSelector.parse(selector).forEach((selector) => {
const elementNames = selector.element ? [selector.element] : registry.allKnownElementNames();
const notElementNames = new Set(selector.notSelectors.filter(selector => selector.isElementSelector())
.map((selector) => selector.element));
const possibleElementNames = elementNames.filter(elementName => !notElementNames.has(elementName));
ctxs.push(...possibleElementNames.map(elementName => registry.securityContext(elementName, propName, isAttribute)));
});
return ctxs.length === 0 ? [SecurityContext.NONE] : Array.from(new Set(ctxs)).sort();
}
/**
* Compute a new ParseSourceSpan based off an original `sourceSpan` by using
* absolute offsets from the specified `absoluteSpan`.
*
* @param sourceSpan original source span
* @param absoluteSpan absolute source span to move to
*/
function moveParseSourceSpan(sourceSpan, absoluteSpan) {
// The difference of two absolute offsets provide the relative offset
const startDiff = absoluteSpan.start - sourceSpan.start.offset;
const endDiff = absoluteSpan.end - sourceSpan.end.offset;
return new ParseSourceSpan(sourceSpan.start.moveBy(startDiff), sourceSpan.end.moveBy(endDiff), sourceSpan.fullStart.moveBy(startDiff), sourceSpan.details);
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const NG_CONTENT_SELECT_ATTR = 'select';
const LINK_ELEMENT = 'link';
const LINK_STYLE_REL_ATTR = 'rel';
const LINK_STYLE_HREF_ATTR = 'href';
const LINK_STYLE_REL_VALUE = 'stylesheet';
const STYLE_ELEMENT = 'style';
const SCRIPT_ELEMENT = 'script';
const NG_NON_BINDABLE_ATTR = 'ngNonBindable';
const NG_PROJECT_AS = 'ngProjectAs';
function preparseElement(ast) {
let selectAttr = null;
let hrefAttr = null;
let relAttr = null;
let nonBindable = false;
let projectAs = '';
ast.attrs.forEach(attr => {
const lcAttrName = attr.name.toLowerCase();
if (lcAttrName == NG_CONTENT_SELECT_ATTR) {
selectAttr = attr.value;
}
else if (lcAttrName == LINK_STYLE_HREF_ATTR) {
hrefAttr = attr.value;
}
else if (lcAttrName == LINK_STYLE_REL_ATTR) {
relAttr = attr.value;
}
else if (attr.name == NG_NON_BINDABLE_ATTR) {
nonBindable = true;
}
else if (attr.name == NG_PROJECT_AS) {
if (attr.value.length > 0) {
projectAs = attr.value;
}
}
});
selectAttr = normalizeNgContentSelect(selectAttr);
const nodeName = ast.name.toLowerCase();
let type = PreparsedElementType.OTHER;
if (isNgContent(nodeName)) {
type = PreparsedElementType.NG_CONTENT;
}
else if (nodeName == STYLE_ELEMENT) {
type = PreparsedElementType.STYLE;
}
else if (nodeName == SCRIPT_ELEMENT) {
type = PreparsedElementType.SCRIPT;
}
else if (nodeName == LINK_ELEMENT && relAttr == LINK_STYLE_REL_VALUE) {
type = PreparsedElementType.STYLESHEET;
}
return new PreparsedElement(type, selectAttr, hrefAttr, nonBindable, projectAs);
}
var PreparsedElementType;
(function (PreparsedElementType) {
PreparsedElementType[PreparsedElementType["NG_CONTENT"] = 0] = "NG_CONTENT";
PreparsedElementType[PreparsedElementType["STYLE"] = 1] = "STYLE";
PreparsedElementType[PreparsedElementType["STYLESHEET"] = 2] = "STYLESHEET";
PreparsedElementType[PreparsedElementType["SCRIPT"] = 3] = "SCRIPT";
PreparsedElementType[PreparsedElementType["OTHER"] = 4] = "OTHER";
})(PreparsedElementType || (PreparsedElementType = {}));
class PreparsedElement {
constructor(type, selectAttr, hrefAttr, nonBindable, projectAs) {
this.type = type;
this.selectAttr = selectAttr;
this.hrefAttr = hrefAttr;
this.nonBindable = nonBindable;
this.projectAs = projectAs;
}
}
function normalizeNgContentSelect(selectAttr) {
if (selectAttr === null || selectAttr.length === 0) {
return '*';
}
return selectAttr;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const BIND_NAME_REGEXP = /^(?:(?:(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.*))|\[\(([^\)]+)\)\]|\[([^\]]+)\]|\(([^\)]+)\))$/;
// Group 1 = "bind-"
const KW_BIND_IDX = 1;
// Group 2 = "let-"
const KW_LET_IDX = 2;
// Group 3 = "ref-/#"
const KW_REF_IDX = 3;
// Group 4 = "on-"
const KW_ON_IDX = 4;
// Group 5 = "bindon-"
const KW_BINDON_IDX = 5;
// Group 6 = "@"
const KW_AT_IDX = 6;
// Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
const IDENT_KW_IDX = 7;
// Group 8 = identifier inside [()]
const IDENT_BANANA_BOX_IDX = 8;
// Group 9 = identifier inside []
const IDENT_PROPERTY_IDX = 9;
// Group 10 = identifier inside ()
const IDENT_EVENT_IDX = 10;
const TEMPLATE_ATTR_PREFIX$1 = '*';
const CLASS_ATTR = 'class';
let _TEXT_CSS_SELECTOR;
function TEXT_CSS_SELECTOR() {
if (!_TEXT_CSS_SELECTOR) {
_TEXT_CSS_SELECTOR = CssSelector.parse('*')[0];
}
return _TEXT_CSS_SELECTOR;
}
class TemplateParseError extends ParseError {
constructor(message, span, level) {
super(span, message, level);
}
}
class TemplateParseResult {
constructor(templateAst, usedPipes, errors) {
this.templateAst = templateAst;
this.usedPipes = usedPipes;
this.errors = errors;
}
}
class TemplateParser {
constructor(_config, _reflector, _exprParser, _schemaRegistry, _htmlParser, _console, transforms) {
this._config = _config;
this._reflector = _reflector;
this._exprParser = _exprParser;
this._schemaRegistry = _schemaRegistry;
this._htmlParser = _htmlParser;
this._console = _console;
this.transforms = transforms;
}
get expressionParser() {
return this._exprParser;
}
parse(component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) {
var _a;
const result = this.tryParse(component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces);
const warnings = result.errors.filter(error => error.level === ParseErrorLevel.WARNING);
const errors = result.errors.filter(error => error.level === ParseErrorLevel.ERROR);
if (warnings.length > 0) {
(_a = this._console) === null || _a === void 0 ? void 0 : _a.warn(`Template parse warnings:\n${warnings.join('\n')}`);
}
if (errors.length > 0) {
const errorString = errors.join('\n');
throw syntaxError(`Template parse errors:\n${errorString}`, errors);
}
return { template: result.templateAst, pipes: result.usedPipes };
}
tryParse(component, template, directives, pipes, schemas, templateUrl, preserveWhitespaces) {
let htmlParseResult = typeof template === 'string' ?
this._htmlParser.parse(template, templateUrl, {
tokenizeExpansionForms: true,
interpolationConfig: this.getInterpolationConfig(component)
}) :
template;
if (!preserveWhitespaces) {
htmlParseResult = removeWhitespaces(htmlParseResult);
}
return this.tryParseHtml(this.expandHtml(htmlParseResult), component, directives, pipes, schemas);
}
tryParseHtml(htmlAstWithErrors, component, directives, pipes, schemas) {
let result;
const errors = htmlAstWithErrors.errors;
const usedPipes = [];
if (htmlAstWithErrors.rootNodes.length > 0) {
const uniqDirectives = removeSummaryDuplicates(directives);
const uniqPipes = removeSummaryDuplicates(pipes);
const providerViewContext = new ProviderViewContext(this._reflector, component);
let interpolationConfig = undefined;
if (component.template && component.template.interpolation) {
interpolationConfig = {
start: component.template.interpolation[0],
end: component.template.interpolation[1]
};
}
const bindingParser = new BindingParser(this._exprParser, interpolationConfig, this._schemaRegistry, uniqPipes, errors);
const parseVisitor = new TemplateParseVisitor(this._reflector, this._config, providerViewContext, uniqDirectives, bindingParser, this._schemaRegistry, schemas, errors);
result = visitAll$1(parseVisitor, htmlAstWithErrors.rootNodes, EMPTY_ELEMENT_CONTEXT);
errors.push(...providerViewContext.errors);
usedPipes.push(...bindingParser.getUsedPipes());
}
else {
result = [];
}
this._assertNoReferenceDuplicationOnTemplate(result, errors);
if (errors.length > 0) {
return new TemplateParseResult(result, usedPipes, errors);
}
if (this.transforms) {
this.transforms.forEach((transform) => {
result = templateVisitAll(transform, result);
});
}
return new TemplateParseResult(result, usedPipes, errors);
}
expandHtml(htmlAstWithErrors, forced = false) {
const errors = htmlAstWithErrors.errors;
if (errors.length == 0 || forced) {
// Transform ICU messages to angular directives
const expandedHtmlAst = expandNodes(htmlAstWithErrors.rootNodes);
errors.push(...expandedHtmlAst.errors);
htmlAstWithErrors = new ParseTreeResult(expandedHtmlAst.nodes, errors);
}
return htmlAstWithErrors;
}
getInterpolationConfig(component) {
if (component.template) {
return InterpolationConfig.fromArray(component.template.interpolation);
}
return undefined;
}
/** @internal */
_assertNoReferenceDuplicationOnTemplate(result, errors) {
const existingReferences = [];
result.filter(element => !!element.references)
.forEach(element => element.references.forEach((reference) => {
const name = reference.name;
if (existingReferences.indexOf(name) < 0) {
existingReferences.push(name);
}
else {
const error = new TemplateParseError(`Reference "#${name}" is defined several times`, reference.sourceSpan, ParseErrorLevel.ERROR);
errors.push(error);
}
}));
}
}
class TemplateParseVisitor {
constructor(reflector, config, providerViewContext, directives, _bindingParser, _schemaRegistry, _schemas, _targetErrors) {
this.reflector = reflector;
this.config = config;
this.providerViewContext = providerViewContext;
this._bindingParser = _bindingParser;
this._schemaRegistry = _schemaRegistry;
this._schemas = _schemas;
this._targetErrors = _targetErrors;
this.selectorMatcher = new SelectorMatcher();
this.directivesIndex = new Map();
this.ngContentCount = 0;
// Note: queries start with id 1 so we can use the number in a Bloom filter!
this.contentQueryStartId = providerViewContext.component.viewQueries.length + 1;
directives.forEach((directive, index) => {
const selector = CssSelector.parse(directive.selector);
this.selectorMatcher.addSelectables(selector, directive);
this.directivesIndex.set(directive, index);
});
}
visitExpansion(expansion, context) {
return null;
}
visitExpansionCase(expansionCase, context) {
return null;
}
visitText(text, parent) {
const ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR());
const valueNoNgsp = replaceNgsp(text.value);
const expr = this._bindingParser.parseInterpolation(valueNoNgsp, text.sourceSpan);
return expr ? new BoundTextAst(expr, ngContentIndex, text.sourceSpan) :
new TextAst(valueNoNgsp, ngContentIndex, text.sourceSpan);
}
visitAttribute(attribute, context) {
return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
}
visitComment(comment, context) {
return null;
}
visitElement(element, parent) {
const queryStartIndex = this.contentQueryStartId;
const elName = element.name;
const preparsedElement = preparseElement(element);
if (preparsedElement.type === PreparsedElementType.SCRIPT ||
preparsedElement.type === PreparsedElementType.STYLE) {
// Skipping <script> for security reasons
// Skipping <style> as we already processed them
// in the StyleCompiler
return null;
}
if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
isStyleUrlResolvable(preparsedElement.hrefAttr)) {
// Skipping stylesheets with either relative urls or package scheme as we already processed
// them in the StyleCompiler
return null;
}
const matchableAttrs = [];
const elementOrDirectiveProps = [];
const elementOrDirectiveRefs = [];
const elementVars = [];
const events = [];
const templateElementOrDirectiveProps = [];
const templateMatchableAttrs = [];
const templateElementVars = [];
let hasInlineTemplates = false;
const attrs = [];
const isTemplateElement = isNgTemplate(element.name);
element.attrs.forEach(attr => {
const parsedVariables = [];
const hasBinding = this._parseAttr(isTemplateElement, attr, matchableAttrs, elementOrDirectiveProps, events, elementOrDirectiveRefs, elementVars);
elementVars.push(...parsedVariables.map(v => VariableAst.fromParsedVariable(v)));
let templateValue;
let templateKey;
const normalizedName = this._normalizeAttributeName(attr.name);
if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX$1)) {
templateValue = attr.value;
templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX$1.length);
}
const hasTemplateBinding = templateValue != null;
if (hasTemplateBinding) {
if (hasInlineTemplates) {
this._reportError(`Can't have multiple template bindings on one element. Use only one attribute prefixed with *`, attr.sourceSpan);
}
hasInlineTemplates = true;
const parsedVariables = [];
const absoluteOffset = (attr.valueSpan || attr.sourceSpan).start.offset;
this._bindingParser.parseInlineTemplateBinding(templateKey, templateValue, attr.sourceSpan, absoluteOffset, templateMatchableAttrs, templateElementOrDirectiveProps, parsedVariables, false /* isIvyAst */);
templateElementVars.push(...parsedVariables.map(v => VariableAst.fromParsedVariable(v)));
}
if (!hasBinding && !hasTemplateBinding) {
// don't include the bindings as attributes as well in the AST
attrs.push(this.visitAttribute(attr, null));
matchableAttrs.push([attr.name, attr.value]);
}
});
const elementCssSelector = createElementCssSelector(elName, matchableAttrs);
const { directives: directiveMetas, matchElement } = this._parseDirectives(this.selectorMatcher, elementCssSelector);
const references = [];
const boundDirectivePropNames = new Set();
const directiveAsts = this._createDirectiveAsts(isTemplateElement, element.name, directiveMetas, elementOrDirectiveProps, elementOrDirectiveRefs, element.sourceSpan, references, boundDirectivePropNames);
const elementProps = this._createElementPropertyAsts(element.name, elementOrDirectiveProps, boundDirectivePropNames);
const isViewRoot = parent.isTemplateElement || hasInlineTemplates;
const providerContext = new ProviderElementContext(this.providerViewContext, parent.providerContext, isViewRoot, directiveAsts, attrs, references, isTemplateElement, queryStartIndex, element.sourceSpan);
const children = visitAll$1(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR : this, element.children, ElementContext.create(isTemplateElement, directiveAsts, isTemplateElement ? parent.providerContext : providerContext));
providerContext.afterElement();
// Override the actual selector when the `ngProjectAs` attribute is provided
const projectionSelector = preparsedElement.projectAs != '' ?
CssSelector.parse(preparsedElement.projectAs)[0] :
elementCssSelector;
const ngContentIndex = parent.findNgContentIndex(projectionSelector);
let parsedElement;
if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
// `<ng-content>` element
if (element.children && !element.children.every(_isEmptyTextNode)) {
this._reportError(`<ng-content> element cannot have content.`, element.sourceSpan);
}
parsedElement = new NgContentAst(this.ngContentCount++, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan);
}
else if (isTemplateElement) {
// `<ng-template>` element
this._assertAllEventsPublishedByDirectives(directiveAsts, events);
this._assertNoComponentsNorElementBindingsOnTemplate(directiveAsts, elementProps, element.sourceSpan);
parsedElement = new EmbeddedTemplateAst(attrs, events, references, elementVars, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, providerContext.queryMatches, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan);
}
else {
// element other than `<ng-content>` and `<ng-template>`
this._assertElementExists(matchElement, element);
this._assertOnlyOneComponent(directiveAsts, element.sourceSpan);
const ngContentIndex = hasInlineTemplates ? null : parent.findNgContentIndex(projectionSelector);
parsedElement = new ElementAst(elName, attrs, elementProps, events, references, providerContext.transformedDirectiveAsts, providerContext.transformProviders, providerContext.transformedHasViewContainer, providerContext.queryMatches, children, hasInlineTemplates ? null : ngContentIndex, element.sourceSpan, element.endSourceSpan || null);
}
if (hasInlineTemplates) {
// The element as a *-attribute
const templateQueryStartIndex = this.contentQueryStartId;
const templateSelector = createElementCssSelector('ng-template', templateMatchableAttrs);
const { directives } = this._parseDirectives(this.selectorMatcher, templateSelector);
const templateBoundDirectivePropNames = new Set();
const templateDirectiveAsts = this._createDirectiveAsts(true, elName, directives, templateElementOrDirectiveProps, [], element.sourceSpan, [], templateBoundDirectivePropNames);
const templateElementProps = this._createElementPropertyAsts(elName, templateElementOrDirectiveProps, templateBoundDirectivePropNames);
this._assertNoComponentsNorElementBindingsOnTemplate(templateDirectiveAsts, templateElementProps, element.sourceSpan);
const templateProviderContext = new ProviderElementContext(this.providerViewContext, parent.providerContext, parent.isTemplateElement, templateDirectiveAsts, [], [], true, templateQueryStartIndex, element.sourceSpan);
templateProviderContext.afterElement();
parsedElement = new EmbeddedTemplateAst([], [], [], templateElementVars, templateProviderContext.transformedDirectiveAsts, templateProviderContext.transformProviders, templateProviderContext.transformedHasViewContainer, templateProviderContext.queryMatches, [parsedElement], ngContentIndex, element.sourceSpan);
}
return parsedElement;
}
_parseAttr(isTemplateElement, attr, targetMatchableAttrs, targetProps, targetEvents, targetRefs, targetVars) {
const name = this._normalizeAttributeName(attr.name);
const value = attr.value;
const srcSpan = attr.sourceSpan;
const absoluteOffset = attr.valueSpan ? attr.valueSpan.start.offset : srcSpan.start.offset;
const boundEvents = [];
const bindParts = name.match(BIND_NAME_REGEXP);
let hasBinding = false;
if (bindParts !== null) {
hasBinding = true;
if (bindParts[KW_BIND_IDX] != null) {
this._bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX], value, false, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
}
else if (bindParts[KW_LET_IDX]) {
if (isTemplateElement) {
const identifier = bindParts[IDENT_KW_IDX];
this._parseVariable(identifier, value, srcSpan, targetVars);
}
else {
this._reportError(`"let-" is only supported on ng-template elements.`, srcSpan);
}
}
else if (bindParts[KW_REF_IDX]) {
const identifier = bindParts[IDENT_KW_IDX];
this._parseReference(identifier, value, srcSpan, targetRefs);
}
else if (bindParts[KW_ON_IDX]) {
this._bindingParser.parseEvent(bindParts[IDENT_KW_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
}
else if (bindParts[KW_BINDON_IDX]) {
this._bindingParser.parsePropertyBinding(bindParts[IDENT_KW_IDX], value, false, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
this._parseAssignmentEvent(bindParts[IDENT_KW_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
}
else if (bindParts[KW_AT_IDX]) {
this._bindingParser.parseLiteralAttr(name, value, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
}
else if (bindParts[IDENT_BANANA_BOX_IDX]) {
this._bindingParser.parsePropertyBinding(bindParts[IDENT_BANANA_BOX_IDX], value, false, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
this._parseAssignmentEvent(bindParts[IDENT_BANANA_BOX_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
}
else if (bindParts[IDENT_PROPERTY_IDX]) {
this._bindingParser.parsePropertyBinding(bindParts[IDENT_PROPERTY_IDX], value, false, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
}
else if (bindParts[IDENT_EVENT_IDX]) {
this._bindingParser.parseEvent(bindParts[IDENT_EVENT_IDX], value, srcSpan, attr.valueSpan || srcSpan, targetMatchableAttrs, boundEvents);
}
}
else {
hasBinding = this._bindingParser.parsePropertyInterpolation(name, value, srcSpan, attr.valueSpan, targetMatchableAttrs, targetProps);
}
if (!hasBinding) {
this._bindingParser.parseLiteralAttr(name, value, srcSpan, absoluteOffset, attr.valueSpan, targetMatchableAttrs, targetProps);
}
targetEvents.push(...boundEvents.map(e => BoundEventAst.fromParsedEvent(e)));
return hasBinding;
}
_normalizeAttributeName(attrName) {
return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
}
_parseVariable(identifier, value, sourceSpan, targetVars) {
if (identifier.indexOf('-') > -1) {
this._reportError(`"-" is not allowed in variable names`, sourceSpan);
}
else if (identifier.length === 0) {
this._reportError(`Variable does not have a name`, sourceSpan);
}
targetVars.push(new VariableAst(identifier, value, sourceSpan));
}
_parseReference(identifier, value, sourceSpan, targetRefs) {
if (identifier.indexOf('-') > -1) {
this._reportError(`"-" is not allowed in reference names`, sourceSpan);
}
else if (identifier.length === 0) {
this._reportError(`Reference does not have a name`, sourceSpan);
}
targetRefs.push(new ElementOrDirectiveRef(identifier, value, sourceSpan));
}
_parseAssignmentEvent(name, expression, sourceSpan, valueSpan, targetMatchableAttrs, targetEvents) {
this._bindingParser.parseEvent(`${name}Change`, `${expression}=$event`, sourceSpan, valueSpan, targetMatchableAttrs, targetEvents);
}
_parseDirectives(selectorMatcher, elementCssSelector) {
// Need to sort the directives so that we get consistent results throughout,
// as selectorMatcher uses Maps inside.
// Also deduplicate directives as they might match more than one time!
const directives = newArray(this.directivesIndex.size);
// Whether any directive selector matches on the element name
let matchElement = false;
selectorMatcher.match(elementCssSelector, (selector, directive) => {
directives[this.directivesIndex.get(directive)] = directive;
matchElement = matchElement || selector.hasElementSelector();
});
return {
directives: directives.filter(dir => !!dir),
matchElement,
};
}
_createDirectiveAsts(isTemplateElement, elementName, directives, props, elementOrDirectiveRefs, elementSourceSpan, targetReferences, targetBoundDirectivePropNames) {
const matchedReferences = new Set();
let component = null;
const directiveAsts = directives.map((directive) => {
const sourceSpan = new ParseSourceSpan(elementSourceSpan.start, elementSourceSpan.end, elementSourceSpan.fullStart, `Directive ${identifierName(directive.type)}`);
if (directive.isComponent) {
component = directive;
}
const directiveProperties = [];
const boundProperties = this._bindingParser.createDirectiveHostPropertyAsts(directive, elementName, sourceSpan);
let hostProperties = boundProperties.map(prop => BoundElementPropertyAst.fromBoundProperty(prop));
// Note: We need to check the host properties here as well,
// as we don't know the element name in the DirectiveWrapperCompiler yet.
hostProperties = this._checkPropertiesInSchema(elementName, hostProperties);
const parsedEvents = this._bindingParser.createDirectiveHostEventAsts(directive, sourceSpan);
this._createDirectivePropertyAsts(directive.inputs, props, directiveProperties, targetBoundDirectivePropNames);
elementOrDirectiveRefs.forEach((elOrDirRef) => {
if ((elOrDirRef.value.length === 0 && directive.isComponent) ||
(elOrDirRef.isReferenceToDirective(directive))) {
targetReferences.push(new ReferenceAst(elOrDirRef.name, createTokenForReference(directive.type.reference), elOrDirRef.value, elOrDirRef.sourceSpan));
matchedReferences.add(elOrDirRef.name);
}
});
const hostEvents = parsedEvents.map(e => BoundEventAst.fromParsedEvent(e));
const contentQueryStartId = this.contentQueryStartId;
this.contentQueryStartId += directive.queries.length;
return new DirectiveAst(directive, directiveProperties, hostProperties, hostEvents, contentQueryStartId, sourceSpan);
});
elementOrDirectiveRefs.forEach((elOrDirRef) => {
if (elOrDirRef.value.length > 0) {
if (!matchedReferences.has(elOrDirRef.name)) {
this._reportError(`There is no directive with "exportAs" set to "${elOrDirRef.value}"`, elOrDirRef.sourceSpan);
}
}
else if (!component) {
let refToken = null;
if (isTemplateElement) {
refToken = createTokenForExternalReference(this.reflector, Identifiers.TemplateRef);
}
targetReferences.push(new ReferenceAst(elOrDirRef.name, refToken, elOrDirRef.value, elOrDirRef.sourceSpan));
}
});
return directiveAsts;
}
_createDirectivePropertyAsts(directiveProperties, boundProps, targetBoundDirectiveProps, targetBoundDirectivePropNames) {
if (directiveProperties) {
const boundPropsByName = new Map();
boundProps.forEach(boundProp => {
const prevValue = boundPropsByName.get(boundProp.name);
if (!prevValue || prevValue.isLiteral) {
// give [a]="b" a higher precedence than a="b" on the same element
boundPropsByName.set(boundProp.name, boundProp);
}
});
Object.keys(directiveProperties).forEach(dirProp => {
const elProp = directiveProperties[dirProp];
const boundProp = boundPropsByName.get(elProp);
// Bindings are optional, so this binding only needs to be set up if an expression is given.
if (boundProp) {
targetBoundDirectivePropNames.add(boundProp.name);
if (!isEmptyExpression(boundProp.expression)) {
targetBoundDirectiveProps.push(new BoundDirectivePropertyAst(dirProp, boundProp.name, boundProp.expression, boundProp.sourceSpan));
}
}
});
}
}
_createElementPropertyAsts(elementName, props, boundDirectivePropNames) {
const boundElementProps = [];
props.forEach((prop) => {
if (!prop.isLiteral && !boundDirectivePropNames.has(prop.name)) {
const boundProp = this._bindingParser.createBoundElementProperty(elementName, prop);
boundElementProps.push(BoundElementPropertyAst.fromBoundProperty(boundProp));
}
});
return this._checkPropertiesInSchema(elementName, boundElementProps);
}
_findComponentDirectives(directives) {
return directives.filter(directive => directive.directive.isComponent);
}
_findComponentDirectiveNames(directives) {
return this._findComponentDirectives(directives)
.map(directive => identifierName(directive.directive.type));
}
_assertOnlyOneComponent(directives, sourceSpan) {
const componentTypeNames = this._findComponentDirectiveNames(directives);
if (componentTypeNames.length > 1) {
this._reportError(`More than one component matched on this element.\n` +
`Make sure that only one component's selector can match a given element.\n` +
`Conflicting components: ${componentTypeNames.join(',')}`, sourceSpan);
}
}
/**
* Make sure that non-angular tags conform to the schemas.
*
* Note: An element is considered an angular tag when at least one directive selector matches the
* tag name.
*
* @param matchElement Whether any directive has matched on the tag name
* @param element the html element
*/
_assertElementExists(matchElement, element) {
const elName = element.name.replace(/^:xhtml:/, '');
if (!matchElement && !this._schemaRegistry.hasElement(elName, this._schemas)) {
let errorMsg = `'${elName}' is not a known element:\n`;
errorMsg += `1. If '${elName}' is an Angular component, then verify that it is part of this module.\n`;
if (elName.indexOf('-') > -1) {
errorMsg += `2. If '${elName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.`;
}
else {
errorMsg +=
`2. To allow any element add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`;
}
this._reportError(errorMsg, element.sourceSpan);
}
}
_assertNoComponentsNorElementBindingsOnTemplate(directives, elementProps, sourceSpan) {
const componentTypeNames = this._findComponentDirectiveNames(directives);
if (componentTypeNames.length > 0) {
this._reportError(`Components on an embedded template: ${componentTypeNames.join(',')}`, sourceSpan);
}
elementProps.forEach(prop => {
this._reportError(`Property binding ${prop.name} not used by any directive on an embedded template. Make sure that the property name is spelled correctly and all directives are listed in the "@NgModule.declarations".`, sourceSpan);
});
}
_assertAllEventsPublishedByDirectives(directives, events) {
const allDirectiveEvents = new Set();
directives.forEach(directive => {
Object.keys(directive.directive.outputs).forEach(k => {
const eventName = directive.directive.outputs[k];
allDirectiveEvents.add(eventName);
});
});
events.forEach(event => {
if (event.target != null || !allDirectiveEvents.has(event.name)) {
this._reportError(`Event binding ${event
.fullName} not emitted by any directive on an embedded template. Make sure that the event name is spelled correctly and all directives are listed in the "@NgModule.declarations".`, event.sourceSpan);
}
});
}
_checkPropertiesInSchema(elementName, boundProps) {
// Note: We can't filter out empty expressions before this method,
// as we still want to validate them!
return boundProps.filter((boundProp) => {
if (boundProp.type === 0 /* Property */ &&
!this._schemaRegistry.hasProperty(elementName, boundProp.name, this._schemas)) {
let errorMsg = `Can't bind to '${boundProp.name}' since it isn't a known property of '${elementName}'.`;
if (elementName.startsWith('ng-')) {
errorMsg +=
`\n1. If '${boundProp
.name}' is an Angular directive, then add 'CommonModule' to the '@NgModule.imports' of this component.` +
`\n2. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`;
}
else if (elementName.indexOf('-') > -1) {
errorMsg +=
`\n1. If '${elementName}' is an Angular component and it has '${boundProp.name}' input, then verify that it is part of this module.` +
`\n2. If '${elementName}' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.` +
`\n3. To allow any property add 'NO_ERRORS_SCHEMA' to the '@NgModule.schemas' of this component.`;
}
this._reportError(errorMsg, boundProp.sourceSpan);
}
return !isEmptyExpression(boundProp.value);
});
}
_reportError(message, sourceSpan, level = ParseErrorLevel.ERROR) {
this._targetErrors.push(new ParseError(sourceSpan, message, level));
}
}
class NonBindableVisitor {
visitElement(ast, parent) {
const preparsedElement = preparseElement(ast);
if (preparsedElement.type === PreparsedElementType.SCRIPT ||
preparsedElement.type === PreparsedElementType.STYLE ||
preparsedElement.type === PreparsedElementType.STYLESHEET) {
// Skipping <script> for security reasons
// Skipping <style> and stylesheets as we already processed them
// in the StyleCompiler
return null;
}
const attrNameAndValues = ast.attrs.map((attr) => [attr.name, attr.value]);
const selector = createElementCssSelector(ast.name, attrNameAndValues);
const ngContentIndex = parent.findNgContentIndex(selector);
const children = visitAll$1(this, ast.children, EMPTY_ELEMENT_CONTEXT);
return new ElementAst(ast.name, visitAll$1(this, ast.attrs), [], [], [], [], [], false, [], children, ngContentIndex, ast.sourceSpan, ast.endSourceSpan);
}
visitComment(comment, context) {
return null;
}
visitAttribute(attribute, context) {
return new AttrAst(attribute.name, attribute.value, attribute.sourceSpan);
}
visitText(text, parent) {
const ngContentIndex = parent.findNgContentIndex(TEXT_CSS_SELECTOR());
return new TextAst(text.value, ngContentIndex, text.sourceSpan);
}
visitExpansion(expansion, context) {
return expansion;
}
visitExpansionCase(expansionCase, context) {
return expansionCase;
}
}
/**
* A reference to an element or directive in a template. E.g., the reference in this template:
*
* <div #myMenu="coolMenu">
*
* would be {name: 'myMenu', value: 'coolMenu', sourceSpan: ...}
*/
class ElementOrDirectiveRef {
constructor(name, value, sourceSpan) {
this.name = name;
this.value = value;
this.sourceSpan = sourceSpan;
}
/** Gets whether this is a reference to the given directive. */
isReferenceToDirective(directive) {
return splitExportAs(directive.exportAs).indexOf(this.value) !== -1;
}
}
/** Splits a raw, potentially comma-delimited `exportAs` value into an array of names. */
function splitExportAs(exportAs) {
return exportAs ? exportAs.split(',').map(e => e.trim()) : [];
}
function splitClasses(classAttrValue) {
return classAttrValue.trim().split(/\s+/g);
}
class ElementContext {
constructor(isTemplateElement, _ngContentIndexMatcher, _wildcardNgContentIndex, providerContext) {
this.isTemplateElement = isTemplateElement;
this._ngContentIndexMatcher = _ngContentIndexMatcher;
this._wildcardNgContentIndex = _wildcardNgContentIndex;
this.providerContext = providerContext;
}
static create(isTemplateElement, directives, providerContext) {
const matcher = new SelectorMatcher();
let wildcardNgContentIndex = null;
const component = directives.find(directive => directive.directive.isComponent);
if (component) {
const ngContentSelectors = component.directive.template.ngContentSelectors;
for (let i = 0; i < ngContentSelectors.length; i++) {
const selector = ngContentSelectors[i];
if (selector === '*') {
wildcardNgContentIndex = i;
}
else {
matcher.addSelectables(CssSelector.parse(ngContentSelectors[i]), i);
}
}
}
return new ElementContext(isTemplateElement, matcher, wildcardNgContentIndex, providerContext);
}
findNgContentIndex(selector) {
const ngContentIndices = [];
this._ngContentIndexMatcher.match(selector, (selector, ngContentIndex) => {
ngContentIndices.push(ngContentIndex);
});
ngContentIndices.sort();
if (this._wildcardNgContentIndex != null) {
ngContentIndices.push(this._wildcardNgContentIndex);
}
return ngContentIndices.length > 0 ? ngContentIndices[0] : null;
}
}
function createElementCssSelector(elementName, attributes) {
const cssSelector = new CssSelector();
const elNameNoNs = splitNsName(elementName)[1];
cssSelector.setElement(elNameNoNs);
for (let i = 0; i < attributes.length; i++) {
const attrName = attributes[i][0];
const attrNameNoNs = splitNsName(attrName)[1];
const attrValue = attributes[i][1];
cssSelector.addAttribute(attrNameNoNs, attrValue);
if (attrName.toLowerCase() == CLASS_ATTR) {
const classes = splitClasses(attrValue);
classes.forEach(className => cssSelector.addClassName(className));
}
}
return cssSelector;
}
const EMPTY_ELEMENT_CONTEXT = new ElementContext(true, new SelectorMatcher(), null, null);
const NON_BINDABLE_VISITOR = new NonBindableVisitor();
function _isEmptyTextNode(node) {
return node instanceof Text$3 && node.value.trim().length == 0;
}
function removeSummaryDuplicates(items) {
const map = new Map();
items.forEach((item) => {
if (!map.get(item.type.reference)) {
map.set(item.type.reference, item);
}
});
return Array.from(map.values());
}
function isEmptyExpression(ast) {
if (ast instanceof ASTWithSource) {
ast = ast.ast;
}
return ast instanceof EmptyExpr;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Parses string representation of a style and converts it into object literal.
*
* @param value string representation of style as used in the `style` attribute in HTML.
* Example: `color: red; height: auto`.
* @returns An array of style property name and value pairs, e.g. `['color', 'red', 'height',
* 'auto']`
*/
function parse(value) {
// we use a string array here instead of a string map
// because a string-map is not guaranteed to retain the
// order of the entries whereas a string array can be
// constructed in a [key, value, key, value] format.
const styles = [];
let i = 0;
let parenDepth = 0;
let quote = 0 /* QuoteNone */;
let valueStart = 0;
let propStart = 0;
let currentProp = null;
let valueHasQuotes = false;
while (i < value.length) {
const token = value.charCodeAt(i++);
switch (token) {
case 40 /* OpenParen */:
parenDepth++;
break;
case 41 /* CloseParen */:
parenDepth--;
break;
case 39 /* QuoteSingle */:
// valueStart needs to be there since prop values don't
// have quotes in CSS
valueHasQuotes = valueHasQuotes || valueStart > 0;
if (quote === 0 /* QuoteNone */) {
quote = 39 /* QuoteSingle */;
}
else if (quote === 39 /* QuoteSingle */ && value.charCodeAt(i - 1) !== 92 /* BackSlash */) {
quote = 0 /* QuoteNone */;
}
break;
case 34 /* QuoteDouble */:
// same logic as above
valueHasQuotes = valueHasQuotes || valueStart > 0;
if (quote === 0 /* QuoteNone */) {
quote = 34 /* QuoteDouble */;
}
else if (quote === 34 /* QuoteDouble */ && value.charCodeAt(i - 1) !== 92 /* BackSlash */) {
quote = 0 /* QuoteNone */;
}
break;
case 58 /* Colon */:
if (!currentProp && parenDepth === 0 && quote === 0 /* QuoteNone */) {
currentProp = hyphenate(value.substring(propStart, i - 1).trim());
valueStart = i;
}
break;
case 59 /* Semicolon */:
if (currentProp && valueStart > 0 && parenDepth === 0 && quote === 0 /* QuoteNone */) {
const styleVal = value.substring(valueStart, i - 1).trim();
styles.push(currentProp, valueHasQuotes ? stripUnnecessaryQuotes(styleVal) : styleVal);
propStart = i;
valueStart = 0;
currentProp = null;
valueHasQuotes = false;
}
break;
}
}
if (currentProp && valueStart) {
const styleVal = value.substr(valueStart).trim();
styles.push(currentProp, valueHasQuotes ? stripUnnecessaryQuotes(styleVal) : styleVal);
}
return styles;
}
function stripUnnecessaryQuotes(value) {
const qS = value.charCodeAt(0);
const qE = value.charCodeAt(value.length - 1);
if (qS == qE && (qS == 39 /* QuoteSingle */ || qS == 34 /* QuoteDouble */)) {
const tempValue = value.substring(1, value.length - 1);
// special case to avoid using a multi-quoted string that was just chomped
// (e.g. `font-family: "Verdana", "sans-serif"`)
if (tempValue.indexOf('\'') == -1 && tempValue.indexOf('"') == -1) {
value = tempValue;
}
}
return value;
}
function hyphenate(value) {
return value
.replace(/[a-z][A-Z]/g, v => {
return v.charAt(0) + '-' + v.charAt(1);
})
.toLowerCase();
}
const IMPORTANT_FLAG = '!important';
/**
* Minimum amount of binding slots required in the runtime for style/class bindings.
*
* Styling in Angular uses up two slots in the runtime LView/TData data structures to
* record binding data, property information and metadata.
*
* When a binding is registered it will place the following information in the `LView`:
*
* slot 1) binding value
* slot 2) cached value (all other values collected before it in string form)
*
* When a binding is registered it will place the following information in the `TData`:
*
* slot 1) prop name
* slot 2) binding index that points to the previous style/class binding (and some extra config
* values)
*
* Let's imagine we have a binding that looks like so:
*
* ```
* <div [style.width]="x" [style.height]="y">
* ```
*
* Our `LView` and `TData` data-structures look like so:
*
* ```typescript
* LView = [
* // ...
* x, // value of x
* "width: x",
*
* y, // value of y
* "width: x; height: y",
* // ...
* ];
*
* TData = [
* // ...
* "width", // binding slot 20
* 0,
*
* "height",
* 20,
* // ...
* ];
* ```
*
* */
const MIN_STYLING_BINDING_SLOTS_REQUIRED = 2;
/**
* Produces creation/update instructions for all styling bindings (class and style)
*
* It also produces the creation instruction to register all initial styling values
* (which are all the static class="..." and style="..." attribute values that exist
* on an element within a template).
*
* The builder class below handles producing instructions for the following cases:
*
* - Static style/class attributes (style="..." and class="...")
* - Dynamic style/class map bindings ([style]="map" and [class]="map|string")
* - Dynamic style/class property bindings ([style.prop]="exp" and [class.name]="exp")
*
* Due to the complex relationship of all of these cases, the instructions generated
* for these attributes/properties/bindings must be done so in the correct order. The
* order which these must be generated is as follows:
*
* if (createMode) {
* styling(...)
* }
* if (updateMode) {
* styleMap(...)
* classMap(...)
* styleProp(...)
* classProp(...)
* }
*
* The creation/update methods within the builder class produce these instructions.
*/
class StylingBuilder {
constructor(_directiveExpr) {
this._directiveExpr = _directiveExpr;
/** Whether or not there are any static styling values present */
this._hasInitialValues = false;
/**
* Whether or not there are any styling bindings present
* (i.e. `[style]`, `[class]`, `[style.prop]` or `[class.name]`)
*/
this.hasBindings = false;
this.hasBindingsWithPipes = false;
/** the input for [class] (if it exists) */
this._classMapInput = null;
/** the input for [style] (if it exists) */
this._styleMapInput = null;
/** an array of each [style.prop] input */
this._singleStyleInputs = null;
/** an array of each [class.name] input */
this._singleClassInputs = null;
this._lastStylingInput = null;
this._firstStylingInput = null;
// maps are used instead of hash maps because a Map will
// retain the ordering of the keys
/**
* Represents the location of each style binding in the template
* (e.g. `<div [style.width]="w" [style.height]="h">` implies
* that `width=0` and `height=1`)
*/
this._stylesIndex = new Map();
/**
* Represents the location of each class binding in the template
* (e.g. `<div [class.big]="b" [class.hidden]="h">` implies
* that `big=0` and `hidden=1`)
*/
this._classesIndex = new Map();
this._initialStyleValues = [];
this._initialClassValues = [];
}
/**
* Registers a given input to the styling builder to be later used when producing AOT code.
*
* The code below will only accept the input if it is somehow tied to styling (whether it be
* style/class bindings or static style/class attributes).
*/
registerBoundInput(input) {
// [attr.style] or [attr.class] are skipped in the code below,
// they should not be treated as styling-based bindings since
// they are intended to be written directly to the attr and
// will therefore skip all style/class resolution that is present
// with style="", [style]="" and [style.prop]="", class="",
// [class.prop]="". [class]="" assignments
let binding = null;
let name = input.name;
switch (input.type) {
case 0 /* Property */:
binding = this.registerInputBasedOnName(name, input.value, input.sourceSpan);
break;
case 3 /* Style */:
binding = this.registerStyleInput(name, false, input.value, input.sourceSpan, input.unit);
break;
case 2 /* Class */:
binding = this.registerClassInput(name, false, input.value, input.sourceSpan);
break;
}
return binding ? true : false;
}
registerInputBasedOnName(name, expression, sourceSpan) {
let binding = null;
const prefix = name.substring(0, 6);
const isStyle = name === 'style' || prefix === 'style.' || prefix === 'style!';
const isClass = !isStyle && (name === 'class' || prefix === 'class.' || prefix === 'class!');
if (isStyle || isClass) {
const isMapBased = name.charAt(5) !== '.'; // style.prop or class.prop makes this a no
const property = name.substr(isMapBased ? 5 : 6); // the dot explains why there's a +1
if (isStyle) {
binding = this.registerStyleInput(property, isMapBased, expression, sourceSpan);
}
else {
binding = this.registerClassInput(property, isMapBased, expression, sourceSpan);
}
}
return binding;
}
registerStyleInput(name, isMapBased, value, sourceSpan, suffix) {
if (isEmptyExpression(value)) {
return null;
}
// CSS custom properties are case-sensitive so we shouldn't normalize them.
// See: https://www.w3.org/TR/css-variables-1/#defining-variables
if (!isCssCustomProperty(name)) {
name = hyphenate(name);
}
const { property, hasOverrideFlag, suffix: bindingSuffix } = parseProperty(name);
suffix = typeof suffix === 'string' && suffix.length !== 0 ? suffix : bindingSuffix;
const entry = { name: property, suffix: suffix, value, sourceSpan, hasOverrideFlag };
if (isMapBased) {
this._styleMapInput = entry;
}
else {
(this._singleStyleInputs = this._singleStyleInputs || []).push(entry);
registerIntoMap(this._stylesIndex, property);
}
this._lastStylingInput = entry;
this._firstStylingInput = this._firstStylingInput || entry;
this._checkForPipes(value);
this.hasBindings = true;
return entry;
}
registerClassInput(name, isMapBased, value, sourceSpan) {
if (isEmptyExpression(value)) {
return null;
}
const { property, hasOverrideFlag } = parseProperty(name);
const entry = { name: property, value, sourceSpan, hasOverrideFlag, suffix: null };
if (isMapBased) {
this._classMapInput = entry;
}
else {
(this._singleClassInputs = this._singleClassInputs || []).push(entry);
registerIntoMap(this._classesIndex, property);
}
this._lastStylingInput = entry;
this._firstStylingInput = this._firstStylingInput || entry;
this._checkForPipes(value);
this.hasBindings = true;
return entry;
}
_checkForPipes(value) {
if ((value instanceof ASTWithSource) && (value.ast instanceof BindingPipe)) {
this.hasBindingsWithPipes = true;
}
}
/**
* Registers the element's static style string value to the builder.
*
* @param value the style string (e.g. `width:100px; height:200px;`)
*/
registerStyleAttr(value) {
this._initialStyleValues = parse(value);
this._hasInitialValues = true;
}
/**
* Registers the element's static class string value to the builder.
*
* @param value the className string (e.g. `disabled gold zoom`)
*/
registerClassAttr(value) {
this._initialClassValues = value.trim().split(/\s+/g);
this._hasInitialValues = true;
}
/**
* Appends all styling-related expressions to the provided attrs array.
*
* @param attrs an existing array where each of the styling expressions
* will be inserted into.
*/
populateInitialStylingAttrs(attrs) {
// [CLASS_MARKER, 'foo', 'bar', 'baz' ...]
if (this._initialClassValues.length) {
attrs.push(literal(1 /* Classes */));
for (let i = 0; i < this._initialClassValues.length; i++) {
attrs.push(literal(this._initialClassValues[i]));
}
}
// [STYLE_MARKER, 'width', '200px', 'height', '100px', ...]
if (this._initialStyleValues.length) {
attrs.push(literal(2 /* Styles */));
for (let i = 0; i < this._initialStyleValues.length; i += 2) {
attrs.push(literal(this._initialStyleValues[i]), literal(this._initialStyleValues[i + 1]));
}
}
}
/**
* Builds an instruction with all the expressions and parameters for `elementHostAttrs`.
*
* The instruction generation code below is used for producing the AOT statement code which is
* responsible for registering initial styles (within a directive hostBindings' creation block),
* as well as any of the provided attribute values, to the directive host element.
*/
assignHostAttrs(attrs, definitionMap) {
if (this._directiveExpr && (attrs.length || this._hasInitialValues)) {
this.populateInitialStylingAttrs(attrs);
definitionMap.set('hostAttrs', literalArr(attrs));
}
}
/**
* Builds an instruction with all the expressions and parameters for `classMap`.
*
* The instruction data will contain all expressions for `classMap` to function
* which includes the `[class]` expression params.
*/
buildClassMapInstruction(valueConverter) {
if (this._classMapInput) {
return this._buildMapBasedInstruction(valueConverter, true, this._classMapInput);
}
return null;
}
/**
* Builds an instruction with all the expressions and parameters for `styleMap`.
*
* The instruction data will contain all expressions for `styleMap` to function
* which includes the `[style]` expression params.
*/
buildStyleMapInstruction(valueConverter) {
if (this._styleMapInput) {
return this._buildMapBasedInstruction(valueConverter, false, this._styleMapInput);
}
return null;
}
_buildMapBasedInstruction(valueConverter, isClassBased, stylingInput) {
// each styling binding value is stored in the LView
// map-based bindings allocate two slots: one for the
// previous binding value and another for the previous
// className or style attribute value.
let totalBindingSlotsRequired = MIN_STYLING_BINDING_SLOTS_REQUIRED;
// these values must be outside of the update block so that they can
// be evaluated (the AST visit call) during creation time so that any
// pipes can be picked up in time before the template is built
const mapValue = stylingInput.value.visit(valueConverter);
let reference;
if (mapValue instanceof Interpolation) {
totalBindingSlotsRequired += mapValue.expressions.length;
reference = isClassBased ? getClassMapInterpolationExpression(mapValue) :
getStyleMapInterpolationExpression(mapValue);
}
else {
reference = isClassBased ? Identifiers$1.classMap : Identifiers$1.styleMap;
}
return {
reference,
calls: [{
supportsInterpolation: true,
sourceSpan: stylingInput.sourceSpan,
allocateBindingSlots: totalBindingSlotsRequired,
params: (convertFn) => {
const convertResult = convertFn(mapValue);
const params = Array.isArray(convertResult) ? convertResult : [convertResult];
return params;
}
}]
};
}
_buildSingleInputs(reference, inputs, valueConverter, getInterpolationExpressionFn, isClassBased) {
const instructions = [];
inputs.forEach(input => {
const previousInstruction = instructions[instructions.length - 1];
const value = input.value.visit(valueConverter);
let referenceForCall = reference;
// each styling binding value is stored in the LView
// but there are two values stored for each binding:
// 1) the value itself
// 2) an intermediate value (concatenation of style up to this point).
// We need to store the intermediate value so that we don't allocate
// the strings on each CD.
let totalBindingSlotsRequired = MIN_STYLING_BINDING_SLOTS_REQUIRED;
if (value instanceof Interpolation) {
totalBindingSlotsRequired += value.expressions.length;
if (getInterpolationExpressionFn) {
referenceForCall = getInterpolationExpressionFn(value);
}
}
const call = {
sourceSpan: input.sourceSpan,
allocateBindingSlots: totalBindingSlotsRequired,
supportsInterpolation: !!getInterpolationExpressionFn,
params: (convertFn) => {
// params => stylingProp(propName, value, suffix)
const params = [];
params.push(literal(input.name));
const convertResult = convertFn(value);
if (Array.isArray(convertResult)) {
params.push(...convertResult);
}
else {
params.push(convertResult);
}
// [style.prop] bindings may use suffix values (e.g. px, em, etc...), therefore,
// if that is detected then we need to pass that in as an optional param.
if (!isClassBased && input.suffix !== null) {
params.push(literal(input.suffix));
}
return params;
}
};
// If we ended up generating a call to the same instruction as the previous styling property
// we can chain the calls together safely to save some bytes, otherwise we have to generate
// a separate instruction call. This is primarily a concern with interpolation instructions
// where we may start off with one `reference`, but end up using another based on the
// number of interpolations.
if (previousInstruction && previousInstruction.reference === referenceForCall) {
previousInstruction.calls.push(call);
}
else {
instructions.push({ reference: referenceForCall, calls: [call] });
}
});
return instructions;
}
_buildClassInputs(valueConverter) {
if (this._singleClassInputs) {
return this._buildSingleInputs(Identifiers$1.classProp, this._singleClassInputs, valueConverter, null, true);
}
return [];
}
_buildStyleInputs(valueConverter) {
if (this._singleStyleInputs) {
return this._buildSingleInputs(Identifiers$1.styleProp, this._singleStyleInputs, valueConverter, getStylePropInterpolationExpression, false);
}
return [];
}
/**
* Constructs all instructions which contain the expressions that will be placed
* into the update block of a template function or a directive hostBindings function.
*/
buildUpdateLevelInstructions(valueConverter) {
const instructions = [];
if (this.hasBindings) {
const styleMapInstruction = this.buildStyleMapInstruction(valueConverter);
if (styleMapInstruction) {
instructions.push(styleMapInstruction);
}
const classMapInstruction = this.buildClassMapInstruction(valueConverter);
if (classMapInstruction) {
instructions.push(classMapInstruction);
}
instructions.push(...this._buildStyleInputs(valueConverter));
instructions.push(...this._buildClassInputs(valueConverter));
}
return instructions;
}
}
function registerIntoMap(map, key) {
if (!map.has(key)) {
map.set(key, map.size);
}
}
function parseProperty(name) {
let hasOverrideFlag = false;
const overrideIndex = name.indexOf(IMPORTANT_FLAG);
if (overrideIndex !== -1) {
name = overrideIndex > 0 ? name.substring(0, overrideIndex) : '';
hasOverrideFlag = true;
}
let suffix = null;
let property = name;
const unitIndex = name.lastIndexOf('.');
if (unitIndex > 0) {
suffix = name.substr(unitIndex + 1);
property = name.substring(0, unitIndex);
}
return { property, suffix, hasOverrideFlag };
}
/**
* Gets the instruction to generate for an interpolated class map.
* @param interpolation An Interpolation AST
*/
function getClassMapInterpolationExpression(interpolation) {
switch (getInterpolationArgsLength(interpolation)) {
case 1:
return Identifiers$1.classMap;
case 3:
return Identifiers$1.classMapInterpolate1;
case 5:
return Identifiers$1.classMapInterpolate2;
case 7:
return Identifiers$1.classMapInterpolate3;
case 9:
return Identifiers$1.classMapInterpolate4;
case 11:
return Identifiers$1.classMapInterpolate5;
case 13:
return Identifiers$1.classMapInterpolate6;
case 15:
return Identifiers$1.classMapInterpolate7;
case 17:
return Identifiers$1.classMapInterpolate8;
default:
return Identifiers$1.classMapInterpolateV;
}
}
/**
* Gets the instruction to generate for an interpolated style map.
* @param interpolation An Interpolation AST
*/
function getStyleMapInterpolationExpression(interpolation) {
switch (getInterpolationArgsLength(interpolation)) {
case 1:
return Identifiers$1.styleMap;
case 3:
return Identifiers$1.styleMapInterpolate1;
case 5:
return Identifiers$1.styleMapInterpolate2;
case 7:
return Identifiers$1.styleMapInterpolate3;
case 9:
return Identifiers$1.styleMapInterpolate4;
case 11:
return Identifiers$1.styleMapInterpolate5;
case 13:
return Identifiers$1.styleMapInterpolate6;
case 15:
return Identifiers$1.styleMapInterpolate7;
case 17:
return Identifiers$1.styleMapInterpolate8;
default:
return Identifiers$1.styleMapInterpolateV;
}
}
/**
* Gets the instruction to generate for an interpolated style prop.
* @param interpolation An Interpolation AST
*/
function getStylePropInterpolationExpression(interpolation) {
switch (getInterpolationArgsLength(interpolation)) {
case 1:
return Identifiers$1.styleProp;
case 3:
return Identifiers$1.stylePropInterpolate1;
case 5:
return Identifiers$1.stylePropInterpolate2;
case 7:
return Identifiers$1.stylePropInterpolate3;
case 9:
return Identifiers$1.stylePropInterpolate4;
case 11:
return Identifiers$1.stylePropInterpolate5;
case 13:
return Identifiers$1.stylePropInterpolate6;
case 15:
return Identifiers$1.stylePropInterpolate7;
case 17:
return Identifiers$1.stylePropInterpolate8;
default:
return Identifiers$1.stylePropInterpolateV;
}
}
/**
* Checks whether property name is a custom CSS property.
* See: https://www.w3.org/TR/css-variables-1
*/
function isCssCustomProperty(name) {
return name.startsWith('--');
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var TokenType$1;
(function (TokenType) {
TokenType[TokenType["Character"] = 0] = "Character";
TokenType[TokenType["Identifier"] = 1] = "Identifier";
TokenType[TokenType["Keyword"] = 2] = "Keyword";
TokenType[TokenType["String"] = 3] = "String";
TokenType[TokenType["Operator"] = 4] = "Operator";
TokenType[TokenType["Number"] = 5] = "Number";
TokenType[TokenType["Error"] = 6] = "Error";
})(TokenType$1 || (TokenType$1 = {}));
const KEYWORDS = ['var', 'let', 'as', 'null', 'undefined', 'true', 'false', 'if', 'else', 'this'];
class Lexer {
tokenize(text) {
const scanner = new _Scanner(text);
const tokens = [];
let token = scanner.scanToken();
while (token != null) {
tokens.push(token);
token = scanner.scanToken();
}
return tokens;
}
}
class Token$1 {
constructor(index, end, type, numValue, strValue) {
this.index = index;
this.end = end;
this.type = type;
this.numValue = numValue;
this.strValue = strValue;
}
isCharacter(code) {
return this.type == TokenType$1.Character && this.numValue == code;
}
isNumber() {
return this.type == TokenType$1.Number;
}
isString() {
return this.type == TokenType$1.String;
}
isOperator(operator) {
return this.type == TokenType$1.Operator && this.strValue == operator;
}
isIdentifier() {
return this.type == TokenType$1.Identifier;
}
isKeyword() {
return this.type == TokenType$1.Keyword;
}
isKeywordLet() {
return this.type == TokenType$1.Keyword && this.strValue == 'let';
}
isKeywordAs() {
return this.type == TokenType$1.Keyword && this.strValue == 'as';
}
isKeywordNull() {
return this.type == TokenType$1.Keyword && this.strValue == 'null';
}
isKeywordUndefined() {
return this.type == TokenType$1.Keyword && this.strValue == 'undefined';
}
isKeywordTrue() {
return this.type == TokenType$1.Keyword && this.strValue == 'true';
}
isKeywordFalse() {
return this.type == TokenType$1.Keyword && this.strValue == 'false';
}
isKeywordThis() {
return this.type == TokenType$1.Keyword && this.strValue == 'this';
}
isError() {
return this.type == TokenType$1.Error;
}
toNumber() {
return this.type == TokenType$1.Number ? this.numValue : -1;
}
toString() {
switch (this.type) {
case TokenType$1.Character:
case TokenType$1.Identifier:
case TokenType$1.Keyword:
case TokenType$1.Operator:
case TokenType$1.String:
case TokenType$1.Error:
return this.strValue;
case TokenType$1.Number:
return this.numValue.toString();
default:
return null;
}
}
}
function newCharacterToken(index, end, code) {
return new Token$1(index, end, TokenType$1.Character, code, String.fromCharCode(code));
}
function newIdentifierToken(index, end, text) {
return new Token$1(index, end, TokenType$1.Identifier, 0, text);
}
function newKeywordToken(index, end, text) {
return new Token$1(index, end, TokenType$1.Keyword, 0, text);
}
function newOperatorToken(index, end, text) {
return new Token$1(index, end, TokenType$1.Operator, 0, text);
}
function newStringToken(index, end, text) {
return new Token$1(index, end, TokenType$1.String, 0, text);
}
function newNumberToken(index, end, n) {
return new Token$1(index, end, TokenType$1.Number, n, '');
}
function newErrorToken(index, end, message) {
return new Token$1(index, end, TokenType$1.Error, 0, message);
}
const EOF = new Token$1(-1, -1, TokenType$1.Character, 0, '');
class _Scanner {
constructor(input) {
this.input = input;
this.peek = 0;
this.index = -1;
this.length = input.length;
this.advance();
}
advance() {
this.peek = ++this.index >= this.length ? $EOF : this.input.charCodeAt(this.index);
}
scanToken() {
const input = this.input, length = this.length;
let peek = this.peek, index = this.index;
// Skip whitespace.
while (peek <= $SPACE) {
if (++index >= length) {
peek = $EOF;
break;
}
else {
peek = input.charCodeAt(index);
}
}
this.peek = peek;
this.index = index;
if (index >= length) {
return null;
}
// Handle identifiers and numbers.
if (isIdentifierStart(peek))
return this.scanIdentifier();
if (isDigit(peek))
return this.scanNumber(index);
const start = index;
switch (peek) {
case $PERIOD:
this.advance();
return isDigit(this.peek) ? this.scanNumber(start) :
newCharacterToken(start, this.index, $PERIOD);
case $LPAREN:
case $RPAREN:
case $LBRACE:
case $RBRACE:
case $LBRACKET:
case $RBRACKET:
case $COMMA:
case $COLON:
case $SEMICOLON:
return this.scanCharacter(start, peek);
case $SQ:
case $DQ:
return this.scanString();
case $HASH:
case $PLUS:
case $MINUS:
case $STAR:
case $SLASH:
case $PERCENT:
case $CARET:
return this.scanOperator(start, String.fromCharCode(peek));
case $QUESTION:
return this.scanComplexOperator(start, '?', $PERIOD, '.');
case $LT:
case $GT:
return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, '=');
case $BANG:
case $EQ:
return this.scanComplexOperator(start, String.fromCharCode(peek), $EQ, '=', $EQ, '=');
case $AMPERSAND:
return this.scanComplexOperator(start, '&', $AMPERSAND, '&');
case $BAR:
return this.scanComplexOperator(start, '|', $BAR, '|');
case $NBSP:
while (isWhitespace(this.peek))
this.advance();
return this.scanToken();
}
this.advance();
return this.error(`Unexpected character [${String.fromCharCode(peek)}]`, 0);
}
scanCharacter(start, code) {
this.advance();
return newCharacterToken(start, this.index, code);
}
scanOperator(start, str) {
this.advance();
return newOperatorToken(start, this.index, str);
}
/**
* Tokenize a 2/3 char long operator
*
* @param start start index in the expression
* @param one first symbol (always part of the operator)
* @param twoCode code point for the second symbol
* @param two second symbol (part of the operator when the second code point matches)
* @param threeCode code point for the third symbol
* @param three third symbol (part of the operator when provided and matches source expression)
*/
scanComplexOperator(start, one, twoCode, two, threeCode, three) {
this.advance();
let str = one;
if (this.peek == twoCode) {
this.advance();
str += two;
}
if (threeCode != null && this.peek == threeCode) {
this.advance();
str += three;
}
return newOperatorToken(start, this.index, str);
}
scanIdentifier() {
const start = this.index;
this.advance();
while (isIdentifierPart(this.peek))
this.advance();
const str = this.input.substring(start, this.index);
return KEYWORDS.indexOf(str) > -1 ? newKeywordToken(start, this.index, str) :
newIdentifierToken(start, this.index, str);
}
scanNumber(start) {
let simple = (this.index === start);
this.advance(); // Skip initial digit.
while (true) {
if (isDigit(this.peek)) {
// Do nothing.
}
else if (this.peek == $PERIOD) {
simple = false;
}
else if (isExponentStart(this.peek)) {
this.advance();
if (isExponentSign(this.peek))
this.advance();
if (!isDigit(this.peek))
return this.error('Invalid exponent', -1);
simple = false;
}
else {
break;
}
this.advance();
}
const str = this.input.substring(start, this.index);
const value = simple ? parseIntAutoRadix(str) : parseFloat(str);
return newNumberToken(start, this.index, value);
}
scanString() {
const start = this.index;
const quote = this.peek;
this.advance(); // Skip initial quote.
let buffer = '';
let marker = this.index;
const input = this.input;
while (this.peek != quote) {
if (this.peek == $BACKSLASH) {
buffer += input.substring(marker, this.index);
this.advance();
let unescapedCode;
// Workaround for TS2.1-introduced type strictness
this.peek = this.peek;
if (this.peek == $u) {
// 4 character hex code for unicode character.
const hex = input.substring(this.index + 1, this.index + 5);
if (/^[0-9a-f]+$/i.test(hex)) {
unescapedCode = parseInt(hex, 16);
}
else {
return this.error(`Invalid unicode escape [\\u${hex}]`, 0);
}
for (let i = 0; i < 5; i++) {
this.advance();
}
}
else {
unescapedCode = unescape(this.peek);
this.advance();
}
buffer += String.fromCharCode(unescapedCode);
marker = this.index;
}
else if (this.peek == $EOF) {
return this.error('Unterminated quote', 0);
}
else {
this.advance();
}
}
const last = input.substring(marker, this.index);
this.advance(); // Skip terminating quote.
return newStringToken(start, this.index, buffer + last);
}
error(message, offset) {
const position = this.index + offset;
return newErrorToken(position, this.index, `Lexer Error: ${message} at column ${position} in expression [${this.input}]`);
}
}
function isIdentifierStart(code) {
return ($a <= code && code <= $z) || ($A <= code && code <= $Z) ||
(code == $_) || (code == $$);
}
function isIdentifier(input) {
if (input.length == 0)
return false;
const scanner = new _Scanner(input);
if (!isIdentifierStart(scanner.peek))
return false;
scanner.advance();
while (scanner.peek !== $EOF) {
if (!isIdentifierPart(scanner.peek))
return false;
scanner.advance();
}
return true;
}
function isIdentifierPart(code) {
return isAsciiLetter(code) || isDigit(code) || (code == $_) ||
(code == $$);
}
function isExponentStart(code) {
return code == $e || code == $E;
}
function isExponentSign(code) {
return code == $MINUS || code == $PLUS;
}
function isQuote(code) {
return code === $SQ || code === $DQ || code === $BT;
}
function unescape(code) {
switch (code) {
case $n:
return $LF;
case $f:
return $FF;
case $r:
return $CR;
case $t:
return $TAB;
case $v:
return $VTAB;
default:
return code;
}
}
function parseIntAutoRadix(text) {
const result = parseInt(text);
if (isNaN(result)) {
throw new Error('Invalid integer literal when parsing ' + text);
}
return result;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class SplitInterpolation {
constructor(strings, expressions, offsets) {
this.strings = strings;
this.expressions = expressions;
this.offsets = offsets;
}
}
class TemplateBindingParseResult {
constructor(templateBindings, warnings, errors) {
this.templateBindings = templateBindings;
this.warnings = warnings;
this.errors = errors;
}
}
class Parser$1 {
constructor(_lexer) {
this._lexer = _lexer;
this.errors = [];
this.simpleExpressionChecker = SimpleExpressionChecker;
}
parseAction(input, location, absoluteOffset, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
this._checkNoInterpolation(input, location, interpolationConfig);
const sourceToLex = this._stripComments(input);
const tokens = this._lexer.tokenize(this._stripComments(input));
const ast = new _ParseAST(input, location, absoluteOffset, tokens, sourceToLex.length, true, this.errors, input.length - sourceToLex.length)
.parseChain();
return new ASTWithSource(ast, input, location, absoluteOffset, this.errors);
}
parseBinding(input, location, absoluteOffset, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
const ast = this._parseBindingAst(input, location, absoluteOffset, interpolationConfig);
return new ASTWithSource(ast, input, location, absoluteOffset, this.errors);
}
checkSimpleExpression(ast) {
const checker = new this.simpleExpressionChecker();
ast.visit(checker);
return checker.errors;
}
parseSimpleBinding(input, location, absoluteOffset, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
const ast = this._parseBindingAst(input, location, absoluteOffset, interpolationConfig);
const errors = this.checkSimpleExpression(ast);
if (errors.length > 0) {
this._reportError(`Host binding expression cannot contain ${errors.join(' ')}`, input, location);
}
return new ASTWithSource(ast, input, location, absoluteOffset, this.errors);
}
_reportError(message, input, errLocation, ctxLocation) {
this.errors.push(new ParserError(message, input, errLocation, ctxLocation));
}
_parseBindingAst(input, location, absoluteOffset, interpolationConfig) {
// Quotes expressions use 3rd-party expression language. We don't want to use
// our lexer or parser for that, so we check for that ahead of time.
const quote = this._parseQuote(input, location, absoluteOffset);
if (quote != null) {
return quote;
}
this._checkNoInterpolation(input, location, interpolationConfig);
const sourceToLex = this._stripComments(input);
const tokens = this._lexer.tokenize(sourceToLex);
return new _ParseAST(input, location, absoluteOffset, tokens, sourceToLex.length, false, this.errors, input.length - sourceToLex.length)
.parseChain();
}
_parseQuote(input, location, absoluteOffset) {
if (input == null)
return null;
const prefixSeparatorIndex = input.indexOf(':');
if (prefixSeparatorIndex == -1)
return null;
const prefix = input.substring(0, prefixSeparatorIndex).trim();
if (!isIdentifier(prefix))
return null;
const uninterpretedExpression = input.substring(prefixSeparatorIndex + 1);
const span = new ParseSpan(0, input.length);
return new Quote(span, span.toAbsolute(absoluteOffset), prefix, uninterpretedExpression, location);
}
/**
* Parse microsyntax template expression and return a list of bindings or
* parsing errors in case the given expression is invalid.
*
* For example,
* ```
* <div *ngFor="let item of items">
* ^ ^ absoluteValueOffset for `templateValue`
* absoluteKeyOffset for `templateKey`
* ```
* contains three bindings:
* 1. ngFor -> null
* 2. item -> NgForOfContext.$implicit
* 3. ngForOf -> items
*
* This is apparent from the de-sugared template:
* ```
* <ng-template ngFor let-item [ngForOf]="items">
* ```
*
* @param templateKey name of directive, without the * prefix. For example: ngIf, ngFor
* @param templateValue RHS of the microsyntax attribute
* @param templateUrl template filename if it's external, component filename if it's inline
* @param absoluteKeyOffset start of the `templateKey`
* @param absoluteValueOffset start of the `templateValue`
*/
parseTemplateBindings(templateKey, templateValue, templateUrl, absoluteKeyOffset, absoluteValueOffset) {
const tokens = this._lexer.tokenize(templateValue);
const parser = new _ParseAST(templateValue, templateUrl, absoluteValueOffset, tokens, templateValue.length, false /* parseAction */, this.errors, 0 /* relative offset */);
return parser.parseTemplateBindings({
source: templateKey,
span: new AbsoluteSourceSpan(absoluteKeyOffset, absoluteKeyOffset + templateKey.length),
});
}
parseInterpolation(input, location, absoluteOffset, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
const { strings, expressions, offsets } = this.splitInterpolation(input, location, interpolationConfig);
if (expressions.length === 0)
return null;
const expressionNodes = [];
for (let i = 0; i < expressions.length; ++i) {
const expressionText = expressions[i].text;
const sourceToLex = this._stripComments(expressionText);
const tokens = this._lexer.tokenize(sourceToLex);
const ast = new _ParseAST(input, location, absoluteOffset, tokens, sourceToLex.length, false, this.errors, offsets[i] + (expressionText.length - sourceToLex.length))
.parseChain();
expressionNodes.push(ast);
}
return this.createInterpolationAst(strings.map(s => s.text), expressionNodes, input, location, absoluteOffset);
}
/**
* Similar to `parseInterpolation`, but treats the provided string as a single expression
* element that would normally appear within the interpolation prefix and suffix (`{{` and `}}`).
* This is used for parsing the switch expression in ICUs.
*/
parseInterpolationExpression(expression, location, absoluteOffset) {
const sourceToLex = this._stripComments(expression);
const tokens = this._lexer.tokenize(sourceToLex);
const ast = new _ParseAST(expression, location, absoluteOffset, tokens, sourceToLex.length,
/* parseAction */ false, this.errors, 0)
.parseChain();
const strings = ['', '']; // The prefix and suffix strings are both empty
return this.createInterpolationAst(strings, [ast], expression, location, absoluteOffset);
}
createInterpolationAst(strings, expressions, input, location, absoluteOffset) {
const span = new ParseSpan(0, input.length);
const interpolation = new Interpolation(span, span.toAbsolute(absoluteOffset), strings, expressions);
return new ASTWithSource(interpolation, input, location, absoluteOffset, this.errors);
}
/**
* Splits a string of text into "raw" text segments and expressions present in interpolations in
* the string.
* Returns `null` if there are no interpolations, otherwise a
* `SplitInterpolation` with splits that look like
* <raw text> <expression> <raw text> ... <raw text> <expression> <raw text>
*/
splitInterpolation(input, location, interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
const strings = [];
const expressions = [];
const offsets = [];
let i = 0;
let atInterpolation = false;
let extendLastString = false;
let { start: interpStart, end: interpEnd } = interpolationConfig;
while (i < input.length) {
if (!atInterpolation) {
// parse until starting {{
const start = i;
i = input.indexOf(interpStart, i);
if (i === -1) {
i = input.length;
}
const text = input.substring(start, i);
strings.push({ text, start, end: i });
atInterpolation = true;
}
else {
// parse from starting {{ to ending }} while ignoring content inside quotes.
const fullStart = i;
const exprStart = fullStart + interpStart.length;
const exprEnd = this._getInterpolationEndIndex(input, interpEnd, exprStart);
if (exprEnd === -1) {
// Could not find the end of the interpolation; do not parse an expression.
// Instead we should extend the content on the last raw string.
atInterpolation = false;
extendLastString = true;
break;
}
const fullEnd = exprEnd + interpEnd.length;
const text = input.substring(exprStart, exprEnd);
if (text.trim().length === 0) {
this._reportError('Blank expressions are not allowed in interpolated strings', input, `at column ${i} in`, location);
}
expressions.push({ text, start: fullStart, end: fullEnd });
offsets.push(exprStart);
i = fullEnd;
atInterpolation = false;
}
}
if (!atInterpolation) {
// If we are now at a text section, add the remaining content as a raw string.
if (extendLastString) {
const piece = strings[strings.length - 1];
piece.text += input.substring(i);
piece.end = input.length;
}
else {
strings.push({ text: input.substring(i), start: i, end: input.length });
}
}
return new SplitInterpolation(strings, expressions, offsets);
}
wrapLiteralPrimitive(input, location, absoluteOffset) {
const span = new ParseSpan(0, input == null ? 0 : input.length);
return new ASTWithSource(new LiteralPrimitive(span, span.toAbsolute(absoluteOffset), input), input, location, absoluteOffset, this.errors);
}
_stripComments(input) {
const i = this._commentStart(input);
return i != null ? input.substring(0, i).trim() : input;
}
_commentStart(input) {
let outerQuote = null;
for (let i = 0; i < input.length - 1; i++) {
const char = input.charCodeAt(i);
const nextChar = input.charCodeAt(i + 1);
if (char === $SLASH && nextChar == $SLASH && outerQuote == null)
return i;
if (outerQuote === char) {
outerQuote = null;
}
else if (outerQuote == null && isQuote(char)) {
outerQuote = char;
}
}
return null;
}
_checkNoInterpolation(input, location, { start, end }) {
let startIndex = -1;
let endIndex = -1;
for (const charIndex of this._forEachUnquotedChar(input, 0)) {
if (startIndex === -1) {
if (input.startsWith(start)) {
startIndex = charIndex;
}
}
else {
endIndex = this._getInterpolationEndIndex(input, end, charIndex);
if (endIndex > -1) {
break;
}
}
}
if (startIndex > -1 && endIndex > -1) {
this._reportError(`Got interpolation (${start}${end}) where expression was expected`, input, `at column ${startIndex} in`, location);
}
}
/**
* Finds the index of the end of an interpolation expression
* while ignoring comments and quoted content.
*/
_getInterpolationEndIndex(input, expressionEnd, start) {
for (const charIndex of this._forEachUnquotedChar(input, start)) {
if (input.startsWith(expressionEnd, charIndex)) {
return charIndex;
}
// Nothing else in the expression matters after we've
// hit a comment so look directly for the end token.
if (input.startsWith('//', charIndex)) {
return input.indexOf(expressionEnd, charIndex);
}
}
return -1;
}
/**
* Generator used to iterate over the character indexes of a string that are outside of quotes.
* @param input String to loop through.
* @param start Index within the string at which to start.
*/
*_forEachUnquotedChar(input, start) {
let currentQuote = null;
let escapeCount = 0;
for (let i = start; i < input.length; i++) {
const char = input[i];
// Skip the characters inside quotes. Note that we only care about the outer-most
// quotes matching up and we need to account for escape characters.
if (isQuote(input.charCodeAt(i)) && (currentQuote === null || currentQuote === char) &&
escapeCount % 2 === 0) {
currentQuote = currentQuote === null ? char : null;
}
else if (currentQuote === null) {
yield i;
}
escapeCount = char === '\\' ? escapeCount + 1 : 0;
}
}
}
class IvyParser extends Parser$1 {
constructor() {
super(...arguments);
this.simpleExpressionChecker = IvySimpleExpressionChecker;
}
}
/** Describes a stateful context an expression parser is in. */
var ParseContextFlags;
(function (ParseContextFlags) {
ParseContextFlags[ParseContextFlags["None"] = 0] = "None";
/**
* A Writable context is one in which a value may be written to an lvalue.
* For example, after we see a property access, we may expect a write to the
* property via the "=" operator.
* prop
* ^ possible "=" after
*/
ParseContextFlags[ParseContextFlags["Writable"] = 1] = "Writable";
})(ParseContextFlags || (ParseContextFlags = {}));
class _ParseAST {
constructor(input, location, absoluteOffset, tokens, inputLength, parseAction, errors, offset) {
this.input = input;
this.location = location;
this.absoluteOffset = absoluteOffset;
this.tokens = tokens;
this.inputLength = inputLength;
this.parseAction = parseAction;
this.errors = errors;
this.offset = offset;
this.rparensExpected = 0;
this.rbracketsExpected = 0;
this.rbracesExpected = 0;
this.context = ParseContextFlags.None;
// Cache of expression start and input indeces to the absolute source span they map to, used to
// prevent creating superfluous source spans in `sourceSpan`.
// A serial of the expression start and input index is used for mapping because both are stateful
// and may change for subsequent expressions visited by the parser.
this.sourceSpanCache = new Map();
this.index = 0;
}
peek(offset) {
const i = this.index + offset;
return i < this.tokens.length ? this.tokens[i] : EOF;
}
get next() {
return this.peek(0);
}
/** Whether all the parser input has been processed. */
get atEOF() {
return this.index >= this.tokens.length;
}
/**
* Index of the next token to be processed, or the end of the last token if all have been
* processed.
*/
get inputIndex() {
return this.atEOF ? this.currentEndIndex : this.next.index + this.offset;
}
/**
* End index of the last processed token, or the start of the first token if none have been
* processed.
*/
get currentEndIndex() {
if (this.index > 0) {
const curToken = this.peek(-1);
return curToken.end + this.offset;
}
// No tokens have been processed yet; return the next token's start or the length of the input
// if there is no token.
if (this.tokens.length === 0) {
return this.inputLength + this.offset;
}
return this.next.index + this.offset;
}
/**
* Returns the absolute offset of the start of the current token.
*/
get currentAbsoluteOffset() {
return this.absoluteOffset + this.inputIndex;
}
/**
* Retrieve a `ParseSpan` from `start` to the current position (or to `artificialEndIndex` if
* provided).
*
* @param start Position from which the `ParseSpan` will start.
* @param artificialEndIndex Optional ending index to be used if provided (and if greater than the
* natural ending index)
*/
span(start, artificialEndIndex) {
let endIndex = this.currentEndIndex;
if (artificialEndIndex !== undefined && artificialEndIndex > this.currentEndIndex) {
endIndex = artificialEndIndex;
}
return new ParseSpan(start, endIndex);
}
sourceSpan(start, artificialEndIndex) {
const serial = `${start}@${this.inputIndex}:${artificialEndIndex}`;
if (!this.sourceSpanCache.has(serial)) {
this.sourceSpanCache.set(serial, this.span(start, artificialEndIndex).toAbsolute(this.absoluteOffset));
}
return this.sourceSpanCache.get(serial);
}
advance() {
this.index++;
}
/**
* Executes a callback in the provided context.
*/
withContext(context, cb) {
this.context |= context;
const ret = cb();
this.context ^= context;
return ret;
}
consumeOptionalCharacter(code) {
if (this.next.isCharacter(code)) {
this.advance();
return true;
}
else {
return false;
}
}
peekKeywordLet() {
return this.next.isKeywordLet();
}
peekKeywordAs() {
return this.next.isKeywordAs();
}
/**
* Consumes an expected character, otherwise emits an error about the missing expected character
* and skips over the token stream until reaching a recoverable point.
*
* See `this.error` and `this.skip` for more details.
*/
expectCharacter(code) {
if (this.consumeOptionalCharacter(code))
return;
this.error(`Missing expected ${String.fromCharCode(code)}`);
}
consumeOptionalOperator(op) {
if (this.next.isOperator(op)) {
this.advance();
return true;
}
else {
return false;
}
}
expectOperator(operator) {
if (this.consumeOptionalOperator(operator))
return;
this.error(`Missing expected operator ${operator}`);
}
prettyPrintToken(tok) {
return tok === EOF ? 'end of input' : `token ${tok}`;
}
expectIdentifierOrKeyword() {
const n = this.next;
if (!n.isIdentifier() && !n.isKeyword()) {
this.error(`Unexpected ${this.prettyPrintToken(n)}, expected identifier or keyword`);
return null;
}
this.advance();
return n.toString();
}
expectIdentifierOrKeywordOrString() {
const n = this.next;
if (!n.isIdentifier() && !n.isKeyword() && !n.isString()) {
this.error(`Unexpected ${this.prettyPrintToken(n)}, expected identifier, keyword, or string`);
return '';
}
this.advance();
return n.toString();
}
parseChain() {
const exprs = [];
const start = this.inputIndex;
while (this.index < this.tokens.length) {
const expr = this.parsePipe();
exprs.push(expr);
if (this.consumeOptionalCharacter($SEMICOLON)) {
if (!this.parseAction) {
this.error('Binding expression cannot contain chained expression');
}
while (this.consumeOptionalCharacter($SEMICOLON)) {
} // read all semicolons
}
else if (this.index < this.tokens.length) {
this.error(`Unexpected token '${this.next}'`);
}
}
if (exprs.length == 0) {
// We have no expressions so create an empty expression that spans the entire input length
const artificialStart = this.offset;
const artificialEnd = this.offset + this.inputLength;
return new EmptyExpr(this.span(artificialStart, artificialEnd), this.sourceSpan(artificialStart, artificialEnd));
}
if (exprs.length == 1)
return exprs[0];
return new Chain(this.span(start), this.sourceSpan(start), exprs);
}
parsePipe() {
const start = this.inputIndex;
let result = this.parseExpression();
if (this.consumeOptionalOperator('|')) {
if (this.parseAction) {
this.error('Cannot have a pipe in an action expression');
}
do {
const nameStart = this.inputIndex;
let nameId = this.expectIdentifierOrKeyword();
let nameSpan;
let fullSpanEnd = undefined;
if (nameId !== null) {
nameSpan = this.sourceSpan(nameStart);
}
else {
// No valid identifier was found, so we'll assume an empty pipe name ('').
nameId = '';
// However, there may have been whitespace present between the pipe character and the next
// token in the sequence (or the end of input). We want to track this whitespace so that
// the `BindingPipe` we produce covers not just the pipe character, but any trailing
// whitespace beyond it. Another way of thinking about this is that the zero-length name
// is assumed to be at the end of any whitespace beyond the pipe character.
//
// Therefore, we push the end of the `ParseSpan` for this pipe all the way up to the
// beginning of the next token, or until the end of input if the next token is EOF.
fullSpanEnd = this.next.index !== -1 ? this.next.index : this.inputLength + this.offset;
// The `nameSpan` for an empty pipe name is zero-length at the end of any whitespace
// beyond the pipe character.
nameSpan = new ParseSpan(fullSpanEnd, fullSpanEnd).toAbsolute(this.absoluteOffset);
}
const args = [];
while (this.consumeOptionalCharacter($COLON)) {
args.push(this.parseExpression());
// If there are additional expressions beyond the name, then the artificial end for the
// name is no longer relevant.
}
result = new BindingPipe(this.span(start), this.sourceSpan(start, fullSpanEnd), result, nameId, args, nameSpan);
} while (this.consumeOptionalOperator('|'));
}
return result;
}
parseExpression() {
return this.parseConditional();
}
parseConditional() {
const start = this.inputIndex;
const result = this.parseLogicalOr();
if (this.consumeOptionalOperator('?')) {
const yes = this.parsePipe();
let no;
if (!this.consumeOptionalCharacter($COLON)) {
const end = this.inputIndex;
const expression = this.input.substring(start, end);
this.error(`Conditional expression ${expression} requires all 3 expressions`);
no = new EmptyExpr(this.span(start), this.sourceSpan(start));
}
else {
no = this.parsePipe();
}
return new Conditional(this.span(start), this.sourceSpan(start), result, yes, no);
}
else {
return result;
}
}
parseLogicalOr() {
// '||'
const start = this.inputIndex;
let result = this.parseLogicalAnd();
while (this.consumeOptionalOperator('||')) {
const right = this.parseLogicalAnd();
result = new Binary(this.span(start), this.sourceSpan(start), '||', result, right);
}
return result;
}
parseLogicalAnd() {
// '&&'
const start = this.inputIndex;
let result = this.parseEquality();
while (this.consumeOptionalOperator('&&')) {
const right = this.parseEquality();
result = new Binary(this.span(start), this.sourceSpan(start), '&&', result, right);
}
return result;
}
parseEquality() {
// '==','!=','===','!=='
const start = this.inputIndex;
let result = this.parseRelational();
while (this.next.type == TokenType$1.Operator) {
const operator = this.next.strValue;
switch (operator) {
case '==':
case '===':
case '!=':
case '!==':
this.advance();
const right = this.parseRelational();
result = new Binary(this.span(start), this.sourceSpan(start), operator, result, right);
continue;
}
break;
}
return result;
}
parseRelational() {
// '<', '>', '<=', '>='
const start = this.inputIndex;
let result = this.parseAdditive();
while (this.next.type == TokenType$1.Operator) {
const operator = this.next.strValue;
switch (operator) {
case '<':
case '>':
case '<=':
case '>=':
this.advance();
const right = this.parseAdditive();
result = new Binary(this.span(start), this.sourceSpan(start), operator, result, right);
continue;
}
break;
}
return result;
}
parseAdditive() {
// '+', '-'
const start = this.inputIndex;
let result = this.parseMultiplicative();
while (this.next.type == TokenType$1.Operator) {
const operator = this.next.strValue;
switch (operator) {
case '+':
case '-':
this.advance();
let right = this.parseMultiplicative();
result = new Binary(this.span(start), this.sourceSpan(start), operator, result, right);
continue;
}
break;
}
return result;
}
parseMultiplicative() {
// '*', '%', '/'
const start = this.inputIndex;
let result = this.parsePrefix();
while (this.next.type == TokenType$1.Operator) {
const operator = this.next.strValue;
switch (operator) {
case '*':
case '%':
case '/':
this.advance();
let right = this.parsePrefix();
result = new Binary(this.span(start), this.sourceSpan(start), operator, result, right);
continue;
}
break;
}
return result;
}
parsePrefix() {
if (this.next.type == TokenType$1.Operator) {
const start = this.inputIndex;
const operator = this.next.strValue;
let result;
switch (operator) {
case '+':
this.advance();
result = this.parsePrefix();
return Unary.createPlus(this.span(start), this.sourceSpan(start), result);
case '-':
this.advance();
result = this.parsePrefix();
return Unary.createMinus(this.span(start), this.sourceSpan(start), result);
case '!':
this.advance();
result = this.parsePrefix();
return new PrefixNot(this.span(start), this.sourceSpan(start), result);
}
}
return this.parseCallChain();
}
parseCallChain() {
const start = this.inputIndex;
let result = this.parsePrimary();
while (true) {
if (this.consumeOptionalCharacter($PERIOD)) {
result = this.parseAccessMemberOrMethodCall(result, start, false);
}
else if (this.consumeOptionalOperator('?.')) {
result = this.parseAccessMemberOrMethodCall(result, start, true);
}
else if (this.consumeOptionalCharacter($LBRACKET)) {
this.withContext(ParseContextFlags.Writable, () => {
this.rbracketsExpected++;
const key = this.parsePipe();
if (key instanceof EmptyExpr) {
this.error(`Key access cannot be empty`);
}
this.rbracketsExpected--;
this.expectCharacter($RBRACKET);
if (this.consumeOptionalOperator('=')) {
const value = this.parseConditional();
result = new KeyedWrite(this.span(start), this.sourceSpan(start), result, key, value);
}
else {
result = new KeyedRead(this.span(start), this.sourceSpan(start), result, key);
}
});
}
else if (this.consumeOptionalCharacter($LPAREN)) {
this.rparensExpected++;
const args = this.parseCallArguments();
this.rparensExpected--;
this.expectCharacter($RPAREN);
result = new FunctionCall(this.span(start), this.sourceSpan(start), result, args);
}
else if (this.consumeOptionalOperator('!')) {
result = new NonNullAssert(this.span(start), this.sourceSpan(start), result);
}
else {
return result;
}
}
}
parsePrimary() {
const start = this.inputIndex;
if (this.consumeOptionalCharacter($LPAREN)) {
this.rparensExpected++;
const result = this.parsePipe();
this.rparensExpected--;
this.expectCharacter($RPAREN);
return result;
}
else if (this.next.isKeywordNull()) {
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), null);
}
else if (this.next.isKeywordUndefined()) {
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), void 0);
}
else if (this.next.isKeywordTrue()) {
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), true);
}
else if (this.next.isKeywordFalse()) {
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), false);
}
else if (this.next.isKeywordThis()) {
this.advance();
return new ThisReceiver(this.span(start), this.sourceSpan(start));
}
else if (this.consumeOptionalCharacter($LBRACKET)) {
this.rbracketsExpected++;
const elements = this.parseExpressionList($RBRACKET);
this.rbracketsExpected--;
this.expectCharacter($RBRACKET);
return new LiteralArray(this.span(start), this.sourceSpan(start), elements);
}
else if (this.next.isCharacter($LBRACE)) {
return this.parseLiteralMap();
}
else if (this.next.isIdentifier()) {
return this.parseAccessMemberOrMethodCall(new ImplicitReceiver(this.span(start), this.sourceSpan(start)), start, false);
}
else if (this.next.isNumber()) {
const value = this.next.toNumber();
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), value);
}
else if (this.next.isString()) {
const literalValue = this.next.toString();
this.advance();
return new LiteralPrimitive(this.span(start), this.sourceSpan(start), literalValue);
}
else if (this.index >= this.tokens.length) {
this.error(`Unexpected end of expression: ${this.input}`);
return new EmptyExpr(this.span(start), this.sourceSpan(start));
}
else {
this.error(`Unexpected token ${this.next}`);
return new EmptyExpr(this.span(start), this.sourceSpan(start));
}
}
parseExpressionList(terminator) {
const result = [];
do {
if (!this.next.isCharacter(terminator)) {
result.push(this.parsePipe());
}
else {
break;
}
} while (this.consumeOptionalCharacter($COMMA));
return result;
}
parseLiteralMap() {
const keys = [];
const values = [];
const start = this.inputIndex;
this.expectCharacter($LBRACE);
if (!this.consumeOptionalCharacter($RBRACE)) {
this.rbracesExpected++;
do {
const quoted = this.next.isString();
const key = this.expectIdentifierOrKeywordOrString();
keys.push({ key, quoted });
this.expectCharacter($COLON);
values.push(this.parsePipe());
} while (this.consumeOptionalCharacter($COMMA));
this.rbracesExpected--;
this.expectCharacter($RBRACE);
}
return new LiteralMap(this.span(start), this.sourceSpan(start), keys, values);
}
parseAccessMemberOrMethodCall(receiver, start, isSafe = false) {
const nameStart = this.inputIndex;
const id = this.withContext(ParseContextFlags.Writable, () => {
var _a;
const id = (_a = this.expectIdentifierOrKeyword()) !== null && _a !== void 0 ? _a : '';
if (id.length === 0) {
this.error(`Expected identifier for property access`, receiver.span.end);
}
return id;
});
const nameSpan = this.sourceSpan(nameStart);
if (this.consumeOptionalCharacter($LPAREN)) {
this.rparensExpected++;
const args = this.parseCallArguments();
this.expectCharacter($RPAREN);
this.rparensExpected--;
const span = this.span(start);
const sourceSpan = this.sourceSpan(start);
return isSafe ? new SafeMethodCall(span, sourceSpan, nameSpan, receiver, id, args) :
new MethodCall(span, sourceSpan, nameSpan, receiver, id, args);
}
else {
if (isSafe) {
if (this.consumeOptionalOperator('=')) {
this.error('The \'?.\' operator cannot be used in the assignment');
return new EmptyExpr(this.span(start), this.sourceSpan(start));
}
else {
return new SafePropertyRead(this.span(start), this.sourceSpan(start), nameSpan, receiver, id);
}
}
else {
if (this.consumeOptionalOperator('=')) {
if (!this.parseAction) {
this.error('Bindings cannot contain assignments');
return new EmptyExpr(this.span(start), this.sourceSpan(start));
}
const value = this.parseConditional();
return new PropertyWrite(this.span(start), this.sourceSpan(start), nameSpan, receiver, id, value);
}
else {
return new PropertyRead(this.span(start), this.sourceSpan(start), nameSpan, receiver, id);
}
}
}
}
parseCallArguments() {
if (this.next.isCharacter($RPAREN))
return [];
const positionals = [];
do {
positionals.push(this.parsePipe());
} while (this.consumeOptionalCharacter($COMMA));
return positionals;
}
/**
* Parses an identifier, a keyword, a string with an optional `-` in between,
* and returns the string along with its absolute source span.
*/
expectTemplateBindingKey() {
let result = '';
let operatorFound = false;
const start = this.currentAbsoluteOffset;
do {
result += this.expectIdentifierOrKeywordOrString();
operatorFound = this.consumeOptionalOperator('-');
if (operatorFound) {
result += '-';
}
} while (operatorFound);
return {
source: result,
span: new AbsoluteSourceSpan(start, start + result.length),
};
}
/**
* Parse microsyntax template expression and return a list of bindings or
* parsing errors in case the given expression is invalid.
*
* For example,
* ```
* <div *ngFor="let item of items; index as i; trackBy: func">
* ```
* contains five bindings:
* 1. ngFor -> null
* 2. item -> NgForOfContext.$implicit
* 3. ngForOf -> items
* 4. i -> NgForOfContext.index
* 5. ngForTrackBy -> func
*
* For a full description of the microsyntax grammar, see
* https://gist.github.com/mhevery/d3530294cff2e4a1b3fe15ff75d08855
*
* @param templateKey name of the microsyntax directive, like ngIf, ngFor,
* without the *, along with its absolute span.
*/
parseTemplateBindings(templateKey) {
const bindings = [];
// The first binding is for the template key itself
// In *ngFor="let item of items", key = "ngFor", value = null
// In *ngIf="cond | pipe", key = "ngIf", value = "cond | pipe"
bindings.push(...this.parseDirectiveKeywordBindings(templateKey));
while (this.index < this.tokens.length) {
// If it starts with 'let', then this must be variable declaration
const letBinding = this.parseLetBinding();
if (letBinding) {
bindings.push(letBinding);
}
else {
// Two possible cases here, either `value "as" key` or
// "directive-keyword expression". We don't know which case, but both
// "value" and "directive-keyword" are template binding key, so consume
// the key first.
const key = this.expectTemplateBindingKey();
// Peek at the next token, if it is "as" then this must be variable
// declaration.
const binding = this.parseAsBinding(key);
if (binding) {
bindings.push(binding);
}
else {
// Otherwise the key must be a directive keyword, like "of". Transform
// the key to actual key. Eg. of -> ngForOf, trackBy -> ngForTrackBy
key.source =
templateKey.source + key.source.charAt(0).toUpperCase() + key.source.substring(1);
bindings.push(...this.parseDirectiveKeywordBindings(key));
}
}
this.consumeStatementTerminator();
}
return new TemplateBindingParseResult(bindings, [] /* warnings */, this.errors);
}
/**
* Parse a directive keyword, followed by a mandatory expression.
* For example, "of items", "trackBy: func".
* The bindings are: ngForOf -> items, ngForTrackBy -> func
* There could be an optional "as" binding that follows the expression.
* For example,
* ```
* *ngFor="let item of items | slice:0:1 as collection".
* ^^ ^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^
* keyword bound target optional 'as' binding
* ```
*
* @param key binding key, for example, ngFor, ngIf, ngForOf, along with its
* absolute span.
*/
parseDirectiveKeywordBindings(key) {
const bindings = [];
this.consumeOptionalCharacter($COLON); // trackBy: trackByFunction
const value = this.getDirectiveBoundTarget();
let spanEnd = this.currentAbsoluteOffset;
// The binding could optionally be followed by "as". For example,
// *ngIf="cond | pipe as x". In this case, the key in the "as" binding
// is "x" and the value is the template key itself ("ngIf"). Note that the
// 'key' in the current context now becomes the "value" in the next binding.
const asBinding = this.parseAsBinding(key);
if (!asBinding) {
this.consumeStatementTerminator();
spanEnd = this.currentAbsoluteOffset;
}
const sourceSpan = new AbsoluteSourceSpan(key.span.start, spanEnd);
bindings.push(new ExpressionBinding(sourceSpan, key, value));
if (asBinding) {
bindings.push(asBinding);
}
return bindings;
}
/**
* Return the expression AST for the bound target of a directive keyword
* binding. For example,
* ```
* *ngIf="condition | pipe"
* ^^^^^^^^^^^^^^^^ bound target for "ngIf"
* *ngFor="let item of items"
* ^^^^^ bound target for "ngForOf"
* ```
*/
getDirectiveBoundTarget() {
if (this.next === EOF || this.peekKeywordAs() || this.peekKeywordLet()) {
return null;
}
const ast = this.parsePipe(); // example: "condition | async"
const { start, end } = ast.span;
const value = this.input.substring(start, end);
return new ASTWithSource(ast, value, this.location, this.absoluteOffset + start, this.errors);
}
/**
* Return the binding for a variable declared using `as`. Note that the order
* of the key-value pair in this declaration is reversed. For example,
* ```
* *ngFor="let item of items; index as i"
* ^^^^^ ^
* value key
* ```
*
* @param value name of the value in the declaration, "ngIf" in the example
* above, along with its absolute span.
*/
parseAsBinding(value) {
if (!this.peekKeywordAs()) {
return null;
}
this.advance(); // consume the 'as' keyword
const key = this.expectTemplateBindingKey();
this.consumeStatementTerminator();
const sourceSpan = new AbsoluteSourceSpan(value.span.start, this.currentAbsoluteOffset);
return new VariableBinding(sourceSpan, key, value);
}
/**
* Return the binding for a variable declared using `let`. For example,
* ```
* *ngFor="let item of items; let i=index;"
* ^^^^^^^^ ^^^^^^^^^^^
* ```
* In the first binding, `item` is bound to `NgForOfContext.$implicit`.
* In the second binding, `i` is bound to `NgForOfContext.index`.
*/
parseLetBinding() {
if (!this.peekKeywordLet()) {
return null;
}
const spanStart = this.currentAbsoluteOffset;
this.advance(); // consume the 'let' keyword
const key = this.expectTemplateBindingKey();
let value = null;
if (this.consumeOptionalOperator('=')) {
value = this.expectTemplateBindingKey();
}
this.consumeStatementTerminator();
const sourceSpan = new AbsoluteSourceSpan(spanStart, this.currentAbsoluteOffset);
return new VariableBinding(sourceSpan, key, value);
}
/**
* Consume the optional statement terminator: semicolon or comma.
*/
consumeStatementTerminator() {
this.consumeOptionalCharacter($SEMICOLON) || this.consumeOptionalCharacter($COMMA);
}
/**
* Records an error and skips over the token stream until reaching a recoverable point. See
* `this.skip` for more details on token skipping.
*/
error(message, index = null) {
this.errors.push(new ParserError(message, this.input, this.locationText(index), this.location));
this.skip();
}
locationText(index = null) {
if (index == null)
index = this.index;
return (index < this.tokens.length) ? `at column ${this.tokens[index].index + 1} in` :
`at the end of the expression`;
}
/**
* Error recovery should skip tokens until it encounters a recovery point.
*
* The following are treated as unconditional recovery points:
* - end of input
* - ';' (parseChain() is always the root production, and it expects a ';')
* - '|' (since pipes may be chained and each pipe expression may be treated independently)
*
* The following are conditional recovery points:
* - ')', '}', ']' if one of calling productions is expecting one of these symbols
* - This allows skip() to recover from errors such as '(a.) + 1' allowing more of the AST to
* be retained (it doesn't skip any tokens as the ')' is retained because of the '(' begins
* an '(' <expr> ')' production).
* The recovery points of grouping symbols must be conditional as they must be skipped if
* none of the calling productions are not expecting the closing token else we will never
* make progress in the case of an extraneous group closing symbol (such as a stray ')').
* That is, we skip a closing symbol if we are not in a grouping production.
* - '=' in a `Writable` context
* - In this context, we are able to recover after seeing the `=` operator, which
* signals the presence of an independent rvalue expression following the `=` operator.
*
* If a production expects one of these token it increments the corresponding nesting count,
* and then decrements it just prior to checking if the token is in the input.
*/
skip() {
let n = this.next;
while (this.index < this.tokens.length && !n.isCharacter($SEMICOLON) &&
!n.isOperator('|') && (this.rparensExpected <= 0 || !n.isCharacter($RPAREN)) &&
(this.rbracesExpected <= 0 || !n.isCharacter($RBRACE)) &&
(this.rbracketsExpected <= 0 || !n.isCharacter($RBRACKET)) &&
(!(this.context & ParseContextFlags.Writable) || !n.isOperator('='))) {
if (this.next.isError()) {
this.errors.push(new ParserError(this.next.toString(), this.input, this.locationText(), this.location));
}
this.advance();
n = this.next;
}
}
}
class SimpleExpressionChecker {
constructor() {
this.errors = [];
}
visitImplicitReceiver(ast, context) { }
visitThisReceiver(ast, context) { }
visitInterpolation(ast, context) { }
visitLiteralPrimitive(ast, context) { }
visitPropertyRead(ast, context) { }
visitPropertyWrite(ast, context) { }
visitSafePropertyRead(ast, context) { }
visitMethodCall(ast, context) { }
visitSafeMethodCall(ast, context) { }
visitFunctionCall(ast, context) { }
visitLiteralArray(ast, context) {
this.visitAll(ast.expressions, context);
}
visitLiteralMap(ast, context) {
this.visitAll(ast.values, context);
}
visitUnary(ast, context) { }
visitBinary(ast, context) { }
visitPrefixNot(ast, context) { }
visitNonNullAssert(ast, context) { }
visitConditional(ast, context) { }
visitPipe(ast, context) {
this.errors.push('pipes');
}
visitKeyedRead(ast, context) { }
visitKeyedWrite(ast, context) { }
visitAll(asts, context) {
return asts.map(node => node.visit(this, context));
}
visitChain(ast, context) { }
visitQuote(ast, context) { }
}
/**
* This class implements SimpleExpressionChecker used in View Engine and performs more strict checks
* to make sure host bindings do not contain pipes. In View Engine, having pipes in host bindings is
* not supported as well, but in some cases (like `!(value | async)`) the error is not triggered at
* compile time. In order to preserve View Engine behavior, more strict checks are introduced for
* Ivy mode only.
*/
class IvySimpleExpressionChecker extends RecursiveAstVisitor$1 {
constructor() {
super(...arguments);
this.errors = [];
}
visitPipe() {
this.errors.push('pipes');
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function mapEntry(key, value) {
return { key, value, quoted: false };
}
function mapLiteral(obj, quoted = false) {
return literalMap(Object.keys(obj).map(key => ({
key,
quoted,
value: obj[key],
})));
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.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 to SecurityContext. Properties applying to all tags use '*'. */
let _SECURITY_SCHEMA;
function SECURITY_SCHEMA() {
if (!_SECURITY_SCHEMA) {
_SECURITY_SCHEMA = {};
// 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',
]);
}
return _SECURITY_SCHEMA;
}
function registerContext(ctx, specs) {
for (const spec of specs)
_SECURITY_SCHEMA[spec.toLowerCase()] = ctx;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class ElementSchemaRegistry {
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const BOOLEAN = 'boolean';
const NUMBER = 'number';
const STRING = 'string';
const 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.
//
// =================================================================================================
const 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]|autocomplete,!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,autocomplete,!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:|',
];
const _ATTR_TO_PROP = {
'class': 'className',
'for': 'htmlFor',
'formaction': 'formAction',
'innerHtml': 'innerHTML',
'readonly': 'readOnly',
'tabindex': 'tabIndex',
};
// Invert _ATTR_TO_PROP.
const _PROP_TO_ATTR = Object.keys(_ATTR_TO_PROP).reduce((inverted, attr) => {
inverted[_ATTR_TO_PROP[attr]] = attr;
return inverted;
}, {});
class DomElementSchemaRegistry extends ElementSchemaRegistry {
constructor() {
super();
this._schema = {};
SCHEMA.forEach(encodedType => {
const type = {};
const [strType, strProperties] = encodedType.split('|');
const properties = strProperties.split(',');
const [typeNames, superName] = strType.split('^');
typeNames.split(',').forEach(tag => this._schema[tag.toLowerCase()] = type);
const superType = superName && this._schema[superName.toLowerCase()];
if (superType) {
Object.keys(superType).forEach((prop) => {
type[prop] = superType[prop];
});
}
properties.forEach((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;
}
}
});
});
}
hasProperty(tagName, propName, schemaMetas) {
if (schemaMetas.some((schema) => schema.name === NO_ERRORS_SCHEMA.name)) {
return true;
}
if (tagName.indexOf('-') > -1) {
if (isNgContainer(tagName) || isNgContent(tagName)) {
return false;
}
if (schemaMetas.some((schema) => 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;
}
}
const elementProperties = this._schema[tagName.toLowerCase()] || this._schema['unknown'];
return !!elementProperties[propName];
}
hasElement(tagName, schemaMetas) {
if (schemaMetas.some((schema) => schema.name === NO_ERRORS_SCHEMA.name)) {
return true;
}
if (tagName.indexOf('-') > -1) {
if (isNgContainer(tagName) || isNgContent(tagName)) {
return true;
}
if (schemaMetas.some((schema) => 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 based on a list of allowed tags|attributes. 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.
*/
securityContext(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();
let ctx = SECURITY_SCHEMA()[tagName + '|' + propName];
if (ctx) {
return ctx;
}
ctx = SECURITY_SCHEMA()['*|' + propName];
return ctx ? ctx : SecurityContext.NONE;
}
getMappedPropName(propName) {
return _ATTR_TO_PROP[propName] || propName;
}
getDefaultComponentElementName() {
return 'ng-component';
}
validateProperty(name) {
if (name.toLowerCase().startsWith('on')) {
const 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 };
}
}
validateAttribute(name) {
if (name.toLowerCase().startsWith('on')) {
const 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 };
}
}
allKnownElementNames() {
return Object.keys(this._schema);
}
allKnownAttributesOfElement(tagName) {
const elementProperties = this._schema[tagName.toLowerCase()] || this._schema['unknown'];
// Convert properties to attributes.
return Object.keys(elementProperties).map(prop => { var _a; return (_a = _PROP_TO_ATTR[prop]) !== null && _a !== void 0 ? _a : prop; });
}
normalizeAnimationStyleProperty(propName) {
return dashCaseToCamelCase(propName);
}
normalizeAnimationStyleValue(camelCaseProp, userProvidedProp, val) {
let unit = '';
const strVal = val.toString().trim();
let errorMsg = null;
if (_isPixelDimensionStyle(camelCaseProp) && val !== 0 && val !== '0') {
if (typeof val === 'number') {
unit = 'px';
}
else {
const 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 };
}
}
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 LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Set of tagName|propertyName corresponding to Trusted Types sinks. Properties applying to all
* tags use '*'.
*
* Extracted from, and should be kept in sync with
* https://w3c.github.io/webappsec-trusted-types/dist/spec/#integrations
*/
const TRUSTED_TYPES_SINKS = new Set([
// NOTE: All strings in this set *must* be lowercase!
// TrustedHTML
'iframe|srcdoc',
'*|innerhtml',
'*|outerhtml',
// NB: no TrustedScript here, as the corresponding tags are stripped by the compiler.
// TrustedScriptURL
'embed|src',
'object|codebase',
'object|data',
]);
/**
* isTrustedTypesSink returns true if the given property on the given DOM tag is a Trusted Types
* sink. In that case, use `ElementSchemaRegistry.securityContext` to determine which particular
* Trusted Type is required for values passed to the sink:
* - SecurityContext.HTML corresponds to TrustedHTML
* - SecurityContext.RESOURCE_URL corresponds to TrustedScriptURL
*/
function isTrustedTypesSink(tagName, 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();
return TRUSTED_TYPES_SINKS.has(tagName + '|' + propName) ||
TRUSTED_TYPES_SINKS.has('*|' + propName);
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const BIND_NAME_REGEXP$1 = /^(?:(bind-)|(let-)|(ref-|#)|(on-)|(bindon-)|(@))(.*)$/;
// Group 1 = "bind-"
const KW_BIND_IDX$1 = 1;
// Group 2 = "let-"
const KW_LET_IDX$1 = 2;
// Group 3 = "ref-/#"
const KW_REF_IDX$1 = 3;
// Group 4 = "on-"
const KW_ON_IDX$1 = 4;
// Group 5 = "bindon-"
const KW_BINDON_IDX$1 = 5;
// Group 6 = "@"
const KW_AT_IDX$1 = 6;
// Group 7 = the identifier after "bind-", "let-", "ref-/#", "on-", "bindon-" or "@"
const IDENT_KW_IDX$1 = 7;
const BINDING_DELIMS = {
BANANA_BOX: { start: '[(', end: ')]' },
PROPERTY: { start: '[', end: ']' },
EVENT: { start: '(', end: ')' },
};
const TEMPLATE_ATTR_PREFIX$2 = '*';
function htmlAstToRender3Ast(htmlNodes, bindingParser, options) {
const transformer = new HtmlAstToIvyAst(bindingParser, options);
const ivyNodes = visitAll$1(transformer, htmlNodes);
// Errors might originate in either the binding parser or the html to ivy transformer
const allErrors = bindingParser.errors.concat(transformer.errors);
const result = {
nodes: ivyNodes,
errors: allErrors,
styleUrls: transformer.styleUrls,
styles: transformer.styles,
ngContentSelectors: transformer.ngContentSelectors
};
if (options.collectCommentNodes) {
result.commentNodes = transformer.commentNodes;
}
return result;
}
class HtmlAstToIvyAst {
constructor(bindingParser, options) {
this.bindingParser = bindingParser;
this.options = options;
this.errors = [];
this.styles = [];
this.styleUrls = [];
this.ngContentSelectors = [];
// This array will be populated if `Render3ParseOptions['collectCommentNodes']` is true
this.commentNodes = [];
this.inI18nBlock = false;
}
// HTML visitor
visitElement(element) {
const isI18nRootElement = isI18nRootNode(element.i18n);
if (isI18nRootElement) {
if (this.inI18nBlock) {
this.reportError('Cannot mark an element as translatable inside of a translatable section. Please remove the nested i18n marker.', element.sourceSpan);
}
this.inI18nBlock = true;
}
const preparsedElement = preparseElement(element);
if (preparsedElement.type === PreparsedElementType.SCRIPT) {
return null;
}
else if (preparsedElement.type === PreparsedElementType.STYLE) {
const contents = textContents(element);
if (contents !== null) {
this.styles.push(contents);
}
return null;
}
else if (preparsedElement.type === PreparsedElementType.STYLESHEET &&
isStyleUrlResolvable(preparsedElement.hrefAttr)) {
this.styleUrls.push(preparsedElement.hrefAttr);
return null;
}
// Whether the element is a `<ng-template>`
const isTemplateElement = isNgTemplate(element.name);
const parsedProperties = [];
const boundEvents = [];
const variables = [];
const references = [];
const attributes = [];
const i18nAttrsMeta = {};
const templateParsedProperties = [];
const templateVariables = [];
// Whether the element has any *-attribute
let elementHasInlineTemplate = false;
for (const attribute of element.attrs) {
let hasBinding = false;
const normalizedName = normalizeAttributeName(attribute.name);
// `*attr` defines template bindings
let isTemplateBinding = false;
if (attribute.i18n) {
i18nAttrsMeta[attribute.name] = attribute.i18n;
}
if (normalizedName.startsWith(TEMPLATE_ATTR_PREFIX$2)) {
// *-attributes
if (elementHasInlineTemplate) {
this.reportError(`Can't have multiple template bindings on one element. Use only one attribute prefixed with *`, attribute.sourceSpan);
}
isTemplateBinding = true;
elementHasInlineTemplate = true;
const templateValue = attribute.value;
const templateKey = normalizedName.substring(TEMPLATE_ATTR_PREFIX$2.length);
const parsedVariables = [];
const absoluteValueOffset = attribute.valueSpan ?
attribute.valueSpan.start.offset :
// If there is no value span the attribute does not have a value, like `attr` in
//`<div attr></div>`. In this case, point to one character beyond the last character of
// the attribute name.
attribute.sourceSpan.start.offset + attribute.name.length;
this.bindingParser.parseInlineTemplateBinding(templateKey, templateValue, attribute.sourceSpan, absoluteValueOffset, [], templateParsedProperties, parsedVariables, true /* isIvyAst */);
templateVariables.push(...parsedVariables.map(v => new Variable(v.name, v.value, v.sourceSpan, v.keySpan, v.valueSpan)));
}
else {
// Check for variables, events, property bindings, interpolation
hasBinding = this.parseAttribute(isTemplateElement, attribute, [], parsedProperties, boundEvents, variables, references);
}
if (!hasBinding && !isTemplateBinding) {
// don't include the bindings as attributes as well in the AST
attributes.push(this.visitAttribute(attribute));
}
}
const children = visitAll$1(preparsedElement.nonBindable ? NON_BINDABLE_VISITOR$1 : this, element.children);
let parsedElement;
if (preparsedElement.type === PreparsedElementType.NG_CONTENT) {
// `<ng-content>`
if (element.children &&
!element.children.every((node) => isEmptyTextNode(node) || isCommentNode(node))) {
this.reportError(`<ng-content> element cannot have content.`, element.sourceSpan);
}
const selector = preparsedElement.selectAttr;
const attrs = element.attrs.map(attr => this.visitAttribute(attr));
parsedElement = new Content(selector, attrs, element.sourceSpan, element.i18n);
this.ngContentSelectors.push(selector);
}
else if (isTemplateElement) {
// `<ng-template>`
const attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
parsedElement = new Template(element.name, attributes, attrs.bound, boundEvents, [ /* no template attributes */], children, references, variables, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
}
else {
const attrs = this.extractAttributes(element.name, parsedProperties, i18nAttrsMeta);
parsedElement = new Element(element.name, attributes, attrs.bound, boundEvents, children, references, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, element.i18n);
}
if (elementHasInlineTemplate) {
// If this node is an inline-template (e.g. has *ngFor) then we need to create a template
// node that contains this node.
// Moreover, if the node is an element, then we need to hoist its attributes to the template
// node for matching against content projection selectors.
const attrs = this.extractAttributes('ng-template', templateParsedProperties, i18nAttrsMeta);
const templateAttrs = [];
attrs.literal.forEach(attr => templateAttrs.push(attr));
attrs.bound.forEach(attr => templateAttrs.push(attr));
const hoistedAttrs = parsedElement instanceof Element ?
{
attributes: parsedElement.attributes,
inputs: parsedElement.inputs,
outputs: parsedElement.outputs,
} :
{ attributes: [], inputs: [], outputs: [] };
// For <ng-template>s with structural directives on them, avoid passing i18n information to
// the wrapping template to prevent unnecessary i18n instructions from being generated. The
// necessary i18n meta information will be extracted from child elements.
const i18n = isTemplateElement && isI18nRootElement ? undefined : element.i18n;
// TODO(pk): test for this case
parsedElement = new Template(parsedElement.name, hoistedAttrs.attributes, hoistedAttrs.inputs, hoistedAttrs.outputs, templateAttrs, [parsedElement], [ /* no references */], templateVariables, element.sourceSpan, element.startSourceSpan, element.endSourceSpan, i18n);
}
if (isI18nRootElement) {
this.inI18nBlock = false;
}
return parsedElement;
}
visitAttribute(attribute) {
return new TextAttribute(attribute.name, attribute.value, attribute.sourceSpan, attribute.keySpan, attribute.valueSpan, attribute.i18n);
}
visitText(text) {
return this._visitTextWithInterpolation(text.value, text.sourceSpan, text.i18n);
}
visitExpansion(expansion) {
if (!expansion.i18n) {
// do not generate Icu in case it was created
// outside of i18n block in a template
return null;
}
if (!isI18nRootNode(expansion.i18n)) {
throw new Error(`Invalid type "${expansion.i18n.constructor}" for "i18n" property of ${expansion.sourceSpan.toString()}. Expected a "Message"`);
}
const message = expansion.i18n;
const vars = {};
const placeholders = {};
// extract VARs from ICUs - we process them separately while
// assembling resulting message via goog.getMsg function, since
// we need to pass them to top-level goog.getMsg call
Object.keys(message.placeholders).forEach(key => {
const value = message.placeholders[key];
if (key.startsWith(I18N_ICU_VAR_PREFIX)) {
// Currently when the `plural` or `select` keywords in an ICU contain trailing spaces (e.g.
// `{count, select , ...}`), these spaces are also included into the key names in ICU vars
// (e.g. "VAR_SELECT "). These trailing spaces are not desirable, since they will later be
// converted into `_` symbols while normalizing placeholder names, which might lead to
// mismatches at runtime (i.e. placeholder will not be replaced with the correct value).
const formattedKey = key.trim();
const ast = this.bindingParser.parseInterpolationExpression(value.text, value.sourceSpan);
vars[formattedKey] = new BoundText(ast, value.sourceSpan);
}
else {
placeholders[key] = this._visitTextWithInterpolation(value.text, value.sourceSpan);
}
});
return new Icu(vars, placeholders, expansion.sourceSpan, message);
}
visitExpansionCase(expansionCase) {
return null;
}
visitComment(comment) {
if (this.options.collectCommentNodes) {
this.commentNodes.push(new Comment(comment.value || '', comment.sourceSpan));
}
return null;
}
// convert view engine `ParsedProperty` to a format suitable for IVY
extractAttributes(elementName, properties, i18nPropsMeta) {
const bound = [];
const literal = [];
properties.forEach(prop => {
const i18n = i18nPropsMeta[prop.name];
if (prop.isLiteral) {
literal.push(new TextAttribute(prop.name, prop.expression.source || '', prop.sourceSpan, prop.keySpan, prop.valueSpan, i18n));
}
else {
// Note that validation is skipped and property mapping is disabled
// due to the fact that we need to make sure a given prop is not an
// input of a directive and directive matching happens at runtime.
const bep = this.bindingParser.createBoundElementProperty(elementName, prop, /* skipValidation */ true, /* mapPropertyName */ false);
bound.push(BoundAttribute.fromBoundElementProperty(bep, i18n));
}
});
return { bound, literal };
}
parseAttribute(isTemplateElement, attribute, matchableAttributes, parsedProperties, boundEvents, variables, references) {
const name = normalizeAttributeName(attribute.name);
const value = attribute.value;
const srcSpan = attribute.sourceSpan;
const absoluteOffset = attribute.valueSpan ? attribute.valueSpan.start.offset : srcSpan.start.offset;
function createKeySpan(srcSpan, prefix, identifier) {
// We need to adjust the start location for the keySpan to account for the removed 'data-'
// prefix from `normalizeAttributeName`.
const normalizationAdjustment = attribute.name.length - name.length;
const keySpanStart = srcSpan.start.moveBy(prefix.length + normalizationAdjustment);
const keySpanEnd = keySpanStart.moveBy(identifier.length);
return new ParseSourceSpan(keySpanStart, keySpanEnd, keySpanStart, identifier);
}
const bindParts = name.match(BIND_NAME_REGEXP$1);
if (bindParts) {
if (bindParts[KW_BIND_IDX$1] != null) {
const identifier = bindParts[IDENT_KW_IDX$1];
const keySpan = createKeySpan(srcSpan, bindParts[KW_BIND_IDX$1], identifier);
this.bindingParser.parsePropertyBinding(identifier, value, false, srcSpan, absoluteOffset, attribute.valueSpan, matchableAttributes, parsedProperties, keySpan);
}
else if (bindParts[KW_LET_IDX$1]) {
if (isTemplateElement) {
const identifier = bindParts[IDENT_KW_IDX$1];
const keySpan = createKeySpan(srcSpan, bindParts[KW_LET_IDX$1], identifier);
this.parseVariable(identifier, value, srcSpan, keySpan, attribute.valueSpan, variables);
}
else {
this.reportError(`"let-" is only supported on ng-template elements.`, srcSpan);
}
}
else if (bindParts[KW_REF_IDX$1]) {
const identifier = bindParts[IDENT_KW_IDX$1];
const keySpan = createKeySpan(srcSpan, bindParts[KW_REF_IDX$1], identifier);
this.parseReference(identifier, value, srcSpan, keySpan, attribute.valueSpan, references);
}
else if (bindParts[KW_ON_IDX$1]) {
const events = [];
const identifier = bindParts[IDENT_KW_IDX$1];
const keySpan = createKeySpan(srcSpan, bindParts[KW_ON_IDX$1], identifier);
this.bindingParser.parseEvent(identifier, value, srcSpan, attribute.valueSpan || srcSpan, matchableAttributes, events, keySpan);
addEvents(events, boundEvents);
}
else if (bindParts[KW_BINDON_IDX$1]) {
const identifier = bindParts[IDENT_KW_IDX$1];
const keySpan = createKeySpan(srcSpan, bindParts[KW_BINDON_IDX$1], identifier);
this.bindingParser.parsePropertyBinding(identifier, value, false, srcSpan, absoluteOffset, attribute.valueSpan, matchableAttributes, parsedProperties, keySpan);
this.parseAssignmentEvent(identifier, value, srcSpan, attribute.valueSpan, matchableAttributes, boundEvents, keySpan);
}
else if (bindParts[KW_AT_IDX$1]) {
const keySpan = createKeySpan(srcSpan, '', name);
this.bindingParser.parseLiteralAttr(name, value, srcSpan, absoluteOffset, attribute.valueSpan, matchableAttributes, parsedProperties, keySpan);
}
return true;
}
// We didn't see a kw-prefixed property binding, but we have not yet checked
// for the []/()/[()] syntax.
let delims = null;
if (name.startsWith(BINDING_DELIMS.BANANA_BOX.start)) {
delims = BINDING_DELIMS.BANANA_BOX;
}
else if (name.startsWith(BINDING_DELIMS.PROPERTY.start)) {
delims = BINDING_DELIMS.PROPERTY;
}
else if (name.startsWith(BINDING_DELIMS.EVENT.start)) {
delims = BINDING_DELIMS.EVENT;
}
if (delims !== null &&
// NOTE: older versions of the parser would match a start/end delimited
// binding iff the property name was terminated by the ending delimiter
// and the identifier in the binding was non-empty.
// TODO(ayazhafiz): update this to handle malformed bindings.
name.endsWith(delims.end) && name.length > delims.start.length + delims.end.length) {
const identifier = name.substring(delims.start.length, name.length - delims.end.length);
const keySpan = createKeySpan(srcSpan, delims.start, identifier);
if (delims.start === BINDING_DELIMS.BANANA_BOX.start) {
this.bindingParser.parsePropertyBinding(identifier, value, false, srcSpan, absoluteOffset, attribute.valueSpan, matchableAttributes, parsedProperties, keySpan);
this.parseAssignmentEvent(identifier, value, srcSpan, attribute.valueSpan, matchableAttributes, boundEvents, keySpan);
}
else if (delims.start === BINDING_DELIMS.PROPERTY.start) {
this.bindingParser.parsePropertyBinding(identifier, value, false, srcSpan, absoluteOffset, attribute.valueSpan, matchableAttributes, parsedProperties, keySpan);
}
else {
const events = [];
this.bindingParser.parseEvent(identifier, value, srcSpan, attribute.valueSpan || srcSpan, matchableAttributes, events, keySpan);
addEvents(events, boundEvents);
}
return true;
}
// No explicit binding found.
const keySpan = createKeySpan(srcSpan, '' /* prefix */, name);
const hasBinding = this.bindingParser.parsePropertyInterpolation(name, value, srcSpan, attribute.valueSpan, matchableAttributes, parsedProperties, keySpan);
return hasBinding;
}
_visitTextWithInterpolation(value, sourceSpan, i18n) {
const valueNoNgsp = replaceNgsp(value);
const expr = this.bindingParser.parseInterpolation(valueNoNgsp, sourceSpan);
return expr ? new BoundText(expr, sourceSpan, i18n) : new Text(valueNoNgsp, sourceSpan);
}
parseVariable(identifier, value, sourceSpan, keySpan, valueSpan, variables) {
if (identifier.indexOf('-') > -1) {
this.reportError(`"-" is not allowed in variable names`, sourceSpan);
}
else if (identifier.length === 0) {
this.reportError(`Variable does not have a name`, sourceSpan);
}
variables.push(new Variable(identifier, value, sourceSpan, keySpan, valueSpan));
}
parseReference(identifier, value, sourceSpan, keySpan, valueSpan, references) {
if (identifier.indexOf('-') > -1) {
this.reportError(`"-" is not allowed in reference names`, sourceSpan);
}
else if (identifier.length === 0) {
this.reportError(`Reference does not have a name`, sourceSpan);
}
else if (references.some(reference => reference.name === identifier)) {
this.reportError(`Reference "#${identifier}" is defined more than once`, sourceSpan);
}
references.push(new Reference(identifier, value, sourceSpan, keySpan, valueSpan));
}
parseAssignmentEvent(name, expression, sourceSpan, valueSpan, targetMatchableAttrs, boundEvents, keySpan) {
const events = [];
this.bindingParser.parseEvent(`${name}Change`, `${expression}=$event`, sourceSpan, valueSpan || sourceSpan, targetMatchableAttrs, events, keySpan);
addEvents(events, boundEvents);
}
reportError(message, sourceSpan, level = ParseErrorLevel.ERROR) {
this.errors.push(new ParseError(sourceSpan, message, level));
}
}
class NonBindableVisitor$1 {
visitElement(ast) {
const preparsedElement = preparseElement(ast);
if (preparsedElement.type === PreparsedElementType.SCRIPT ||
preparsedElement.type === PreparsedElementType.STYLE ||
preparsedElement.type === PreparsedElementType.STYLESHEET) {
// Skipping <script> for security reasons
// Skipping <style> and stylesheets as we already processed them
// in the StyleCompiler
return null;
}
const children = visitAll$1(this, ast.children, null);
return new Element(ast.name, visitAll$1(this, ast.attrs),
/* inputs */ [], /* outputs */ [], children, /* references */ [], ast.sourceSpan, ast.startSourceSpan, ast.endSourceSpan);
}
visitComment(comment) {
return null;
}
visitAttribute(attribute) {
return new TextAttribute(attribute.name, attribute.value, attribute.sourceSpan, attribute.keySpan, attribute.valueSpan, attribute.i18n);
}
visitText(text) {
return new Text(text.value, text.sourceSpan);
}
visitExpansion(expansion) {
return null;
}
visitExpansionCase(expansionCase) {
return null;
}
}
const NON_BINDABLE_VISITOR$1 = new NonBindableVisitor$1();
function normalizeAttributeName(attrName) {
return /^data-/i.test(attrName) ? attrName.substring(5) : attrName;
}
function addEvents(events, boundEvents) {
boundEvents.push(...events.map(e => BoundEvent.fromParsedEvent(e)));
}
function isEmptyTextNode(node) {
return node instanceof Text$3 && node.value.trim().length == 0;
}
function isCommentNode(node) {
return node instanceof Comment$1;
}
function textContents(node) {
if (node.children.length !== 1 || !(node.children[0] instanceof Text$3)) {
return null;
}
else {
return node.children[0].value;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
var TagType;
(function (TagType) {
TagType[TagType["ELEMENT"] = 0] = "ELEMENT";
TagType[TagType["TEMPLATE"] = 1] = "TEMPLATE";
})(TagType || (TagType = {}));
/**
* Generates an object that is used as a shared state between parent and all child contexts.
*/
function setupRegistry() {
return { getUniqueId: getSeqNumberGenerator(), icus: new Map() };
}
/**
* I18nContext is a helper class which keeps track of all i18n-related aspects
* (accumulates placeholders, bindings, etc) between i18nStart and i18nEnd instructions.
*
* When we enter a nested template, the top-level context is being passed down
* to the nested component, which uses this context to generate a child instance
* of I18nContext class (to handle nested template) and at the end, reconciles it back
* with the parent context.
*
* @param index Instruction index of i18nStart, which initiates this context
* @param ref Reference to a translation const that represents the content if thus context
* @param level Nestng level defined for child contexts
* @param templateIndex Instruction index of a template which this context belongs to
* @param meta Meta information (id, meaning, description, etc) associated with this context
*/
class I18nContext {
constructor(index, ref, level = 0, templateIndex = null, meta, registry) {
this.index = index;
this.ref = ref;
this.level = level;
this.templateIndex = templateIndex;
this.meta = meta;
this.registry = registry;
this.bindings = new Set();
this.placeholders = new Map();
this.isEmitted = false;
this._unresolvedCtxCount = 0;
this._registry = registry || setupRegistry();
this.id = this._registry.getUniqueId();
}
appendTag(type, node, index, closed) {
if (node.isVoid && closed) {
return; // ignore "close" for void tags
}
const ph = node.isVoid || !closed ? node.startName : node.closeName;
const content = { type, index, ctx: this.id, isVoid: node.isVoid, closed };
updatePlaceholderMap(this.placeholders, ph, content);
}
get icus() {
return this._registry.icus;
}
get isRoot() {
return this.level === 0;
}
get isResolved() {
return this._unresolvedCtxCount === 0;
}
getSerializedPlaceholders() {
const result = new Map();
this.placeholders.forEach((values, key) => result.set(key, values.map(serializePlaceholderValue)));
return result;
}
// public API to accumulate i18n-related content
appendBinding(binding) {
this.bindings.add(binding);
}
appendIcu(name, ref) {
updatePlaceholderMap(this._registry.icus, name, ref);
}
appendBoundText(node) {
const phs = assembleBoundTextPlaceholders(node, this.bindings.size, this.id);
phs.forEach((values, key) => updatePlaceholderMap(this.placeholders, key, ...values));
}
appendTemplate(node, index) {
// add open and close tags at the same time,
// since we process nested templates separately
this.appendTag(TagType.TEMPLATE, node, index, false);
this.appendTag(TagType.TEMPLATE, node, index, true);
this._unresolvedCtxCount++;
}
appendElement(node, index, closed) {
this.appendTag(TagType.ELEMENT, node, index, closed);
}
appendProjection(node, index) {
// Add open and close tags at the same time, since `<ng-content>` has no content,
// so when we come across `<ng-content>` we can register both open and close tags.
// Note: runtime i18n logic doesn't distinguish `<ng-content>` tag placeholders and
// regular element tag placeholders, so we generate element placeholders for both types.
this.appendTag(TagType.ELEMENT, node, index, false);
this.appendTag(TagType.ELEMENT, node, index, true);
}
/**
* Generates an instance of a child context based on the root one,
* when we enter a nested template within I18n section.
*
* @param index Instruction index of corresponding i18nStart, which initiates this context
* @param templateIndex Instruction index of a template which this context belongs to
* @param meta Meta information (id, meaning, description, etc) associated with this context
*
* @returns I18nContext instance
*/
forkChildContext(index, templateIndex, meta) {
return new I18nContext(index, this.ref, this.level + 1, templateIndex, meta, this._registry);
}
/**
* Reconciles child context into parent one once the end of the i18n block is reached (i18nEnd).
*
* @param context Child I18nContext instance to be reconciled with parent context.
*/
reconcileChildContext(context) {
// set the right context id for open and close
// template tags, so we can use it as sub-block ids
['start', 'close'].forEach((op) => {
const key = context.meta[`${op}Name`];
const phs = this.placeholders.get(key) || [];
const tag = phs.find(findTemplateFn(this.id, context.templateIndex));
if (tag) {
tag.ctx = context.id;
}
});
// reconcile placeholders
const childPhs = context.placeholders;
childPhs.forEach((values, key) => {
const phs = this.placeholders.get(key);
if (!phs) {
this.placeholders.set(key, values);
return;
}
// try to find matching template...
const tmplIdx = phs.findIndex(findTemplateFn(context.id, context.templateIndex));
if (tmplIdx >= 0) {
// ... if found - replace it with nested template content
const isCloseTag = key.startsWith('CLOSE');
const isTemplateTag = key.endsWith('NG-TEMPLATE');
if (isTemplateTag) {
// current template's content is placed before or after
// parent template tag, depending on the open/close atrribute
phs.splice(tmplIdx + (isCloseTag ? 0 : 1), 0, ...values);
}
else {
const idx = isCloseTag ? values.length - 1 : 0;
values[idx].tmpl = phs[tmplIdx];
phs.splice(tmplIdx, 1, ...values);
}
}
else {
// ... otherwise just append content to placeholder value
phs.push(...values);
}
this.placeholders.set(key, phs);
});
this._unresolvedCtxCount--;
}
}
//
// Helper methods
//
function wrap(symbol, index, contextId, closed) {
const state = closed ? '/' : '';
return wrapI18nPlaceholder(`${state}${symbol}${index}`, contextId);
}
function wrapTag(symbol, { index, ctx, isVoid }, closed) {
return isVoid ? wrap(symbol, index, ctx) + wrap(symbol, index, ctx, true) :
wrap(symbol, index, ctx, closed);
}
function findTemplateFn(ctx, templateIndex) {
return (token) => typeof token === 'object' && token.type === TagType.TEMPLATE &&
token.index === templateIndex && token.ctx === ctx;
}
function serializePlaceholderValue(value) {
const element = (data, closed) => wrapTag('#', data, closed);
const template = (data, closed) => wrapTag('*', data, closed);
const projection = (data, closed) => wrapTag('!', data, closed);
switch (value.type) {
case TagType.ELEMENT:
// close element tag
if (value.closed) {
return element(value, true) + (value.tmpl ? template(value.tmpl, true) : '');
}
// open element tag that also initiates a template
if (value.tmpl) {
return template(value.tmpl) + element(value) +
(value.isVoid ? template(value.tmpl, true) : '');
}
return element(value);
case TagType.TEMPLATE:
return template(value, value.closed);
default:
return value;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class IcuSerializerVisitor {
visitText(text) {
return text.value;
}
visitContainer(container) {
return container.children.map(child => child.visit(this)).join('');
}
visitIcu(icu) {
const strCases = Object.keys(icu.cases).map((k) => `${k} {${icu.cases[k].visit(this)}}`);
const result = `{${icu.expressionPlaceholder}, ${icu.type}, ${strCases.join(' ')}}`;
return result;
}
visitTagPlaceholder(ph) {
return ph.isVoid ?
this.formatPh(ph.startName) :
`${this.formatPh(ph.startName)}${ph.children.map(child => child.visit(this)).join('')}${this.formatPh(ph.closeName)}`;
}
visitPlaceholder(ph) {
return this.formatPh(ph.name);
}
visitIcuPlaceholder(ph, context) {
return this.formatPh(ph.name);
}
formatPh(value) {
return `{${formatI18nPlaceholderName(value, /* useCamelCase */ false)}}`;
}
}
const serializer = new IcuSerializerVisitor();
function serializeIcuNode(icu) {
return icu.visit(serializer);
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const TAG_TO_PLACEHOLDER_NAMES = {
'A': 'LINK',
'B': 'BOLD_TEXT',
'BR': 'LINE_BREAK',
'EM': 'EMPHASISED_TEXT',
'H1': 'HEADING_LEVEL1',
'H2': 'HEADING_LEVEL2',
'H3': 'HEADING_LEVEL3',
'H4': 'HEADING_LEVEL4',
'H5': 'HEADING_LEVEL5',
'H6': 'HEADING_LEVEL6',
'HR': 'HORIZONTAL_RULE',
'I': 'ITALIC_TEXT',
'LI': 'LIST_ITEM',
'LINK': 'MEDIA_LINK',
'OL': 'ORDERED_LIST',
'P': 'PARAGRAPH',
'Q': 'QUOTATION',
'S': 'STRIKETHROUGH_TEXT',
'SMALL': 'SMALL_TEXT',
'SUB': 'SUBSTRIPT',
'SUP': 'SUPERSCRIPT',
'TBODY': 'TABLE_BODY',
'TD': 'TABLE_CELL',
'TFOOT': 'TABLE_FOOTER',
'TH': 'TABLE_HEADER_CELL',
'THEAD': 'TABLE_HEADER',
'TR': 'TABLE_ROW',
'TT': 'MONOSPACED_TEXT',
'U': 'UNDERLINED_TEXT',
'UL': 'UNORDERED_LIST',
};
/**
* Creates unique names for placeholder with different content.
*
* Returns the same placeholder name when the content is identical.
*/
class PlaceholderRegistry {
constructor() {
// Count the occurrence of the base name top generate a unique name
this._placeHolderNameCounts = {};
// Maps signature to placeholder names
this._signatureToName = {};
}
getStartTagPlaceholderName(tag, attrs, isVoid) {
const signature = this._hashTag(tag, attrs, isVoid);
if (this._signatureToName[signature]) {
return this._signatureToName[signature];
}
const upperTag = tag.toUpperCase();
const baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || `TAG_${upperTag}`;
const name = this._generateUniqueName(isVoid ? baseName : `START_${baseName}`);
this._signatureToName[signature] = name;
return name;
}
getCloseTagPlaceholderName(tag) {
const signature = this._hashClosingTag(tag);
if (this._signatureToName[signature]) {
return this._signatureToName[signature];
}
const upperTag = tag.toUpperCase();
const baseName = TAG_TO_PLACEHOLDER_NAMES[upperTag] || `TAG_${upperTag}`;
const name = this._generateUniqueName(`CLOSE_${baseName}`);
this._signatureToName[signature] = name;
return name;
}
getPlaceholderName(name, content) {
const upperName = name.toUpperCase();
const signature = `PH: ${upperName}=${content}`;
if (this._signatureToName[signature]) {
return this._signatureToName[signature];
}
const uniqueName = this._generateUniqueName(upperName);
this._signatureToName[signature] = uniqueName;
return uniqueName;
}
getUniquePlaceholder(name) {
return this._generateUniqueName(name.toUpperCase());
}
// Generate a hash for a tag - does not take attribute order into account
_hashTag(tag, attrs, isVoid) {
const start = `<${tag}`;
const strAttrs = Object.keys(attrs).sort().map((name) => ` ${name}=${attrs[name]}`).join('');
const end = isVoid ? '/>' : `></${tag}>`;
return start + strAttrs + end;
}
_hashClosingTag(tag) {
return this._hashTag(`/${tag}`, {}, false);
}
_generateUniqueName(base) {
const seen = this._placeHolderNameCounts.hasOwnProperty(base);
if (!seen) {
this._placeHolderNameCounts[base] = 1;
return base;
}
const id = this._placeHolderNameCounts[base];
this._placeHolderNameCounts[base] = id + 1;
return `${base}_${id}`;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const _expParser = new Parser$1(new Lexer());
/**
* Returns a function converting html nodes to an i18n Message given an interpolationConfig
*/
function createI18nMessageFactory(interpolationConfig) {
const visitor = new _I18nVisitor(_expParser, interpolationConfig);
return (nodes, meaning, description, customId, visitNodeFn) => visitor.toI18nMessage(nodes, meaning, description, customId, visitNodeFn);
}
function noopVisitNodeFn(_html, i18n) {
return i18n;
}
class _I18nVisitor {
constructor(_expressionParser, _interpolationConfig) {
this._expressionParser = _expressionParser;
this._interpolationConfig = _interpolationConfig;
}
toI18nMessage(nodes, meaning = '', description = '', customId = '', visitNodeFn) {
const context = {
isIcu: nodes.length == 1 && nodes[0] instanceof Expansion,
icuDepth: 0,
placeholderRegistry: new PlaceholderRegistry(),
placeholderToContent: {},
placeholderToMessage: {},
visitNodeFn: visitNodeFn || noopVisitNodeFn,
};
const i18nodes = visitAll$1(this, nodes, context);
return new Message(i18nodes, context.placeholderToContent, context.placeholderToMessage, meaning, description, customId);
}
visitElement(el, context) {
var _a;
const children = visitAll$1(this, el.children, context);
const attrs = {};
el.attrs.forEach(attr => {
// Do not visit the attributes, translatable ones are top-level ASTs
attrs[attr.name] = attr.value;
});
const isVoid = getHtmlTagDefinition(el.name).isVoid;
const startPhName = context.placeholderRegistry.getStartTagPlaceholderName(el.name, attrs, isVoid);
context.placeholderToContent[startPhName] = {
text: el.startSourceSpan.toString(),
sourceSpan: el.startSourceSpan,
};
let closePhName = '';
if (!isVoid) {
closePhName = context.placeholderRegistry.getCloseTagPlaceholderName(el.name);
context.placeholderToContent[closePhName] = {
text: `</${el.name}>`,
sourceSpan: (_a = el.endSourceSpan) !== null && _a !== void 0 ? _a : el.sourceSpan,
};
}
const node = new TagPlaceholder(el.name, attrs, startPhName, closePhName, children, isVoid, el.sourceSpan, el.startSourceSpan, el.endSourceSpan);
return context.visitNodeFn(el, node);
}
visitAttribute(attribute, context) {
const node = this._visitTextWithInterpolation(attribute.value, attribute.valueSpan || attribute.sourceSpan, context, attribute.i18n);
return context.visitNodeFn(attribute, node);
}
visitText(text, context) {
const node = this._visitTextWithInterpolation(text.value, text.sourceSpan, context, text.i18n);
return context.visitNodeFn(text, node);
}
visitComment(comment, context) {
return null;
}
visitExpansion(icu, context) {
context.icuDepth++;
const i18nIcuCases = {};
const i18nIcu = new Icu$1(icu.switchValue, icu.type, i18nIcuCases, icu.sourceSpan);
icu.cases.forEach((caze) => {
i18nIcuCases[caze.value] = new Container(caze.expression.map((node) => node.visit(this, context)), caze.expSourceSpan);
});
context.icuDepth--;
if (context.isIcu || context.icuDepth > 0) {
// Returns an ICU node when:
// - the message (vs a part of the message) is an ICU message, or
// - the ICU message is nested.
const expPh = context.placeholderRegistry.getUniquePlaceholder(`VAR_${icu.type}`);
i18nIcu.expressionPlaceholder = expPh;
context.placeholderToContent[expPh] = {
text: icu.switchValue,
sourceSpan: icu.switchValueSourceSpan,
};
return context.visitNodeFn(icu, i18nIcu);
}
// Else returns a placeholder
// ICU placeholders should not be replaced with their original content but with the their
// translations.
// TODO(vicb): add a html.Node -> i18n.Message cache to avoid having to re-create the msg
const phName = context.placeholderRegistry.getPlaceholderName('ICU', icu.sourceSpan.toString());
context.placeholderToMessage[phName] = this.toI18nMessage([icu], '', '', '', undefined);
const node = new IcuPlaceholder(i18nIcu, phName, icu.sourceSpan);
return context.visitNodeFn(icu, node);
}
visitExpansionCase(_icuCase, _context) {
throw new Error('Unreachable code');
}
/**
* Split the, potentially interpolated, text up into text and placeholder pieces.
*
* @param text The potentially interpolated string to be split.
* @param sourceSpan The span of the whole of the `text` string.
* @param context The current context of the visitor, used to compute and store placeholders.
* @param previousI18n Any i18n metadata associated with this `text` from a previous pass.
*/
_visitTextWithInterpolation(text, sourceSpan, context, previousI18n) {
const { strings, expressions } = this._expressionParser.splitInterpolation(text, sourceSpan.start.toString(), this._interpolationConfig);
// No expressions, return a single text.
if (expressions.length === 0) {
return new Text$1(text, sourceSpan);
}
// Return a sequence of `Text` and `Placeholder` nodes grouped in a `Container`.
const nodes = [];
for (let i = 0; i < strings.length - 1; i++) {
this._addText(nodes, strings[i], sourceSpan);
this._addPlaceholder(nodes, context, expressions[i], sourceSpan);
}
// The last index contains no expression
this._addText(nodes, strings[strings.length - 1], sourceSpan);
// Whitespace removal may have invalidated the interpolation source-spans.
reusePreviousSourceSpans(nodes, previousI18n);
return new Container(nodes, sourceSpan);
}
/**
* Create a new `Text` node from the `textPiece` and add it to the `nodes` collection.
*
* @param nodes The nodes to which the created `Text` node should be added.
* @param textPiece The text and relative span information for this `Text` node.
* @param interpolationSpan The span of the whole interpolated text.
*/
_addText(nodes, textPiece, interpolationSpan) {
if (textPiece.text.length > 0) {
// No need to add empty strings
const stringSpan = getOffsetSourceSpan(interpolationSpan, textPiece);
nodes.push(new Text$1(textPiece.text, stringSpan));
}
}
/**
* Create a new `Placeholder` node from the `expression` and add it to the `nodes` collection.
*
* @param nodes The nodes to which the created `Text` node should be added.
* @param context The current context of the visitor, used to compute and store placeholders.
* @param expression The expression text and relative span information for this `Placeholder`
* node.
* @param interpolationSpan The span of the whole interpolated text.
*/
_addPlaceholder(nodes, context, expression, interpolationSpan) {
const sourceSpan = getOffsetSourceSpan(interpolationSpan, expression);
const baseName = extractPlaceholderName(expression.text) || 'INTERPOLATION';
const phName = context.placeholderRegistry.getPlaceholderName(baseName, expression.text);
const text = this._interpolationConfig.start + expression.text + this._interpolationConfig.end;
context.placeholderToContent[phName] = { text, sourceSpan };
nodes.push(new Placeholder(expression.text, phName, sourceSpan));
}
}
/**
* Re-use the source-spans from `previousI18n` metadata for the `nodes`.
*
* Whitespace removal can invalidate the source-spans of interpolation nodes, so we
* reuse the source-span stored from a previous pass before the whitespace was removed.
*
* @param nodes The `Text` and `Placeholder` nodes to be processed.
* @param previousI18n Any i18n metadata for these `nodes` stored from a previous pass.
*/
function reusePreviousSourceSpans(nodes, previousI18n) {
if (previousI18n instanceof Message) {
// The `previousI18n` is an i18n `Message`, so we are processing an `Attribute` with i18n
// metadata. The `Message` should consist only of a single `Container` that contains the
// parts (`Text` and `Placeholder`) to process.
assertSingleContainerMessage(previousI18n);
previousI18n = previousI18n.nodes[0];
}
if (previousI18n instanceof Container) {
// The `previousI18n` is a `Container`, which means that this is a second i18n extraction pass
// after whitespace has been removed from the AST ndoes.
assertEquivalentNodes(previousI18n.children, nodes);
// Reuse the source-spans from the first pass.
for (let i = 0; i < nodes.length; i++) {
nodes[i].sourceSpan = previousI18n.children[i].sourceSpan;
}
}
}
/**
* Asserts that the `message` contains exactly one `Container` node.
*/
function assertSingleContainerMessage(message) {
const nodes = message.nodes;
if (nodes.length !== 1 || !(nodes[0] instanceof Container)) {
throw new Error('Unexpected previous i18n message - expected it to consist of only a single `Container` node.');
}
}
/**
* Asserts that the `previousNodes` and `node` collections have the same number of elements and
* corresponding elements have the same node type.
*/
function assertEquivalentNodes(previousNodes, nodes) {
if (previousNodes.length !== nodes.length) {
throw new Error('The number of i18n message children changed between first and second pass.');
}
if (previousNodes.some((node, i) => nodes[i].constructor !== node.constructor)) {
throw new Error('The types of the i18n message children changed between first and second pass.');
}
}
/**
* Create a new `ParseSourceSpan` from the `sourceSpan`, offset by the `start` and `end` values.
*/
function getOffsetSourceSpan(sourceSpan, { start, end }) {
return new ParseSourceSpan(sourceSpan.fullStart.moveBy(start), sourceSpan.fullStart.moveBy(end));
}
const _CUSTOM_PH_EXP = /\/\/[\s\S]*i18n[\s\S]*\([\s\S]*ph[\s\S]*=[\s\S]*("|')([\s\S]*?)\1[\s\S]*\)/g;
function extractPlaceholderName(input) {
return input.split(_CUSTOM_PH_EXP)[2];
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* An i18n error.
*/
class I18nError extends ParseError {
constructor(span, msg) {
super(span, msg);
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const setI18nRefs = (htmlNode, i18nNode) => {
if (htmlNode instanceof NodeWithI18n) {
if (i18nNode instanceof IcuPlaceholder && htmlNode.i18n instanceof Message) {
// This html node represents an ICU but this is a second processing pass, and the legacy id
// was computed in the previous pass and stored in the `i18n` property as a message.
// We are about to wipe out that property so capture the previous message to be reused when
// generating the message for this ICU later. See `_generateI18nMessage()`.
i18nNode.previousMessage = htmlNode.i18n;
}
htmlNode.i18n = i18nNode;
}
return i18nNode;
};
/**
* This visitor walks over HTML parse tree and converts information stored in
* i18n-related attributes ("i18n" and "i18n-*") into i18n meta object that is
* stored with other element's and attribute's information.
*/
class I18nMetaVisitor {
constructor(interpolationConfig = DEFAULT_INTERPOLATION_CONFIG, keepI18nAttrs = false, enableI18nLegacyMessageIdFormat = false) {
this.interpolationConfig = interpolationConfig;
this.keepI18nAttrs = keepI18nAttrs;
this.enableI18nLegacyMessageIdFormat = enableI18nLegacyMessageIdFormat;
// whether visited nodes contain i18n information
this.hasI18nMeta = false;
this._errors = [];
// i18n message generation factory
this._createI18nMessage = createI18nMessageFactory(this.interpolationConfig);
}
_generateI18nMessage(nodes, meta = '', visitNodeFn) {
const { meaning, description, customId } = this._parseMetadata(meta);
const message = this._createI18nMessage(nodes, meaning, description, customId, visitNodeFn);
this._setMessageId(message, meta);
this._setLegacyIds(message, meta);
return message;
}
visitAllWithErrors(nodes) {
const result = nodes.map(node => node.visit(this, null));
return new ParseTreeResult(result, this._errors);
}
visitElement(element) {
if (hasI18nAttrs(element)) {
this.hasI18nMeta = true;
const attrs = [];
const attrsMeta = {};
for (const attr of element.attrs) {
if (attr.name === I18N_ATTR) {
// root 'i18n' node attribute
const i18n = element.i18n || attr.value;
const message = this._generateI18nMessage(element.children, i18n, setI18nRefs);
// do not assign empty i18n meta
if (message.nodes.length) {
element.i18n = message;
}
}
else if (attr.name.startsWith(I18N_ATTR_PREFIX)) {
// 'i18n-*' attributes
const name = attr.name.slice(I18N_ATTR_PREFIX.length);
if (isTrustedTypesSink(element.name, name)) {
this._reportError(attr, `Translating attribute '${name}' is disallowed for security reasons.`);
}
else {
attrsMeta[name] = attr.value;
}
}
else {
// non-i18n attributes
attrs.push(attr);
}
}
// set i18n meta for attributes
if (Object.keys(attrsMeta).length) {
for (const attr of attrs) {
const meta = attrsMeta[attr.name];
// do not create translation for empty attributes
if (meta !== undefined && attr.value) {
attr.i18n = this._generateI18nMessage([attr], attr.i18n || meta);
}
}
}
if (!this.keepI18nAttrs) {
// update element's attributes,
// keeping only non-i18n related ones
element.attrs = attrs;
}
}
visitAll$1(this, element.children, element.i18n);
return element;
}
visitExpansion(expansion, currentMessage) {
let message;
const meta = expansion.i18n;
this.hasI18nMeta = true;
if (meta instanceof IcuPlaceholder) {
// set ICU placeholder name (e.g. "ICU_1"),
// generated while processing root element contents,
// so we can reference it when we output translation
const name = meta.name;
message = this._generateI18nMessage([expansion], meta);
const icu = icuFromI18nMessage(message);
icu.name = name;
}
else {
// ICU is a top level message, try to use metadata from container element if provided via
// `context` argument. Note: context may not be available for standalone ICUs (without
// wrapping element), so fallback to ICU metadata in this case.
message = this._generateI18nMessage([expansion], currentMessage || meta);
}
expansion.i18n = message;
return expansion;
}
visitText(text) {
return text;
}
visitAttribute(attribute) {
return attribute;
}
visitComment(comment) {
return comment;
}
visitExpansionCase(expansionCase) {
return expansionCase;
}
/**
* Parse the general form `meta` passed into extract the explicit metadata needed to create a
* `Message`.
*
* There are three possibilities for the `meta` variable
* 1) a string from an `i18n` template attribute: parse it to extract the metadata values.
* 2) a `Message` from a previous processing pass: reuse the metadata values in the message.
* 4) other: ignore this and just process the message metadata as normal
*
* @param meta the bucket that holds information about the message
* @returns the parsed metadata.
*/
_parseMetadata(meta) {
return typeof meta === 'string' ? parseI18nMeta(meta) :
meta instanceof Message ? meta : {};
}
/**
* Generate (or restore) message id if not specified already.
*/
_setMessageId(message, meta) {
if (!message.id) {
message.id = meta instanceof Message && meta.id || decimalDigest(message);
}
}
/**
* Update the `message` with a `legacyId` if necessary.
*
* @param message the message whose legacy id should be set
* @param meta information about the message being processed
*/
_setLegacyIds(message, meta) {
if (this.enableI18nLegacyMessageIdFormat) {
message.legacyIds = [computeDigest(message), computeDecimalDigest(message)];
}
else if (typeof meta !== 'string') {
// This occurs if we are doing the 2nd pass after whitespace removal (see `parseTemplate()` in
// `packages/compiler/src/render3/view/template.ts`).
// In that case we want to reuse the legacy message generated in the 1st pass (see
// `setI18nRefs()`).
const previousMessage = meta instanceof Message ?
meta :
meta instanceof IcuPlaceholder ? meta.previousMessage : undefined;
message.legacyIds = previousMessage ? previousMessage.legacyIds : [];
}
}
_reportError(node, msg) {
this._errors.push(new I18nError(node.sourceSpan, msg));
}
}
/** I18n separators for metadata **/
const I18N_MEANING_SEPARATOR = '|';
const I18N_ID_SEPARATOR = '@@';
/**
* Parses i18n metas like:
* - "@@id",
* - "description[@@id]",
* - "meaning|description[@@id]"
* and returns an object with parsed output.
*
* @param meta String that represents i18n meta
* @returns Object with id, meaning and description fields
*/
function parseI18nMeta(meta = '') {
let customId;
let meaning;
let description;
meta = meta.trim();
if (meta) {
const idIndex = meta.indexOf(I18N_ID_SEPARATOR);
const descIndex = meta.indexOf(I18N_MEANING_SEPARATOR);
let meaningAndDesc;
[meaningAndDesc, customId] =
(idIndex > -1) ? [meta.slice(0, idIndex), meta.slice(idIndex + 2)] : [meta, ''];
[meaning, description] = (descIndex > -1) ?
[meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] :
['', meaningAndDesc];
}
return { customId, meaning, description };
}
// Converts i18n meta information for a message (id, description, meaning)
// to a JsDoc statement formatted as expected by the Closure compiler.
function i18nMetaToJSDoc(meta) {
const tags = [];
if (meta.description) {
tags.push({ tagName: "desc" /* Desc */, text: meta.description });
}
if (meta.meaning) {
tags.push({ tagName: "meaning" /* Meaning */, text: meta.meaning });
}
return tags.length == 0 ? null : jsDocComment(tags);
}
/** Closure uses `goog.getMsg(message)` to lookup translations */
const GOOG_GET_MSG = 'goog.getMsg';
function createGoogleGetMsgStatements(variable$1, message, closureVar, params) {
const messageString = serializeI18nMessageForGetMsg(message);
const args = [literal(messageString)];
if (Object.keys(params).length) {
args.push(mapLiteral(params, true));
}
// /**
// * @desc description of message
// * @meaning meaning of message
// */
// const MSG_... = goog.getMsg(..);
// I18N_X = MSG_...;
const googGetMsgStmt = closureVar.set(variable(GOOG_GET_MSG).callFn(args)).toConstDecl();
const metaComment = i18nMetaToJSDoc(message);
if (metaComment !== null) {
googGetMsgStmt.addLeadingComment(metaComment);
}
const i18nAssignmentStmt = new ExpressionStatement(variable$1.set(closureVar));
return [googGetMsgStmt, i18nAssignmentStmt];
}
/**
* This visitor walks over i18n tree and generates its string representation, including ICUs and
* placeholders in `{$placeholder}` (for plain messages) or `{PLACEHOLDER}` (inside ICUs) format.
*/
class GetMsgSerializerVisitor {
formatPh(value) {
return `{$${formatI18nPlaceholderName(value)}}`;
}
visitText(text) {
return text.value;
}
visitContainer(container) {
return container.children.map(child => child.visit(this)).join('');
}
visitIcu(icu) {
return serializeIcuNode(icu);
}
visitTagPlaceholder(ph) {
return ph.isVoid ?
this.formatPh(ph.startName) :
`${this.formatPh(ph.startName)}${ph.children.map(child => child.visit(this)).join('')}${this.formatPh(ph.closeName)}`;
}
visitPlaceholder(ph) {
return this.formatPh(ph.name);
}
visitIcuPlaceholder(ph, context) {
return this.formatPh(ph.name);
}
}
const serializerVisitor$1 = new GetMsgSerializerVisitor();
function serializeI18nMessageForGetMsg(message) {
return message.nodes.map(node => node.visit(serializerVisitor$1, null)).join('');
}
function createLocalizeStatements(variable, message, params) {
const { messageParts, placeHolders } = serializeI18nMessageForLocalize(message);
const sourceSpan = getSourceSpan(message);
const expressions = placeHolders.map(ph => params[ph.text]);
const localizedString$1 = localizedString(message, messageParts, placeHolders, expressions, sourceSpan);
const variableInitialization = variable.set(localizedString$1);
return [new ExpressionStatement(variableInitialization)];
}
/**
* This visitor walks over an i18n tree, capturing literal strings and placeholders.
*
* The result can be used for generating the `$localize` tagged template literals.
*/
class LocalizeSerializerVisitor {
visitText(text, context) {
if (context[context.length - 1] instanceof LiteralPiece) {
// Two literal pieces in a row means that there was some comment node in-between.
context[context.length - 1].text += text.value;
}
else {
context.push(new LiteralPiece(text.value, text.sourceSpan));
}
}
visitContainer(container, context) {
container.children.forEach(child => child.visit(this, context));
}
visitIcu(icu, context) {
context.push(new LiteralPiece(serializeIcuNode(icu), icu.sourceSpan));
}
visitTagPlaceholder(ph, context) {
var _a, _b;
context.push(this.createPlaceholderPiece(ph.startName, (_a = ph.startSourceSpan) !== null && _a !== void 0 ? _a : ph.sourceSpan));
if (!ph.isVoid) {
ph.children.forEach(child => child.visit(this, context));
context.push(this.createPlaceholderPiece(ph.closeName, (_b = ph.endSourceSpan) !== null && _b !== void 0 ? _b : ph.sourceSpan));
}
}
visitPlaceholder(ph, context) {
context.push(this.createPlaceholderPiece(ph.name, ph.sourceSpan));
}
visitIcuPlaceholder(ph, context) {
context.push(this.createPlaceholderPiece(ph.name, ph.sourceSpan));
}
createPlaceholderPiece(name, sourceSpan) {
return new PlaceholderPiece(formatI18nPlaceholderName(name, /* useCamelCase */ false), sourceSpan);
}
}
const serializerVisitor$2 = new LocalizeSerializerVisitor();
/**
* Serialize an i18n message into two arrays: messageParts and placeholders.
*
* These arrays will be used to generate `$localize` tagged template literals.
*
* @param message The message to be serialized.
* @returns an object containing the messageParts and placeholders.
*/
function serializeI18nMessageForLocalize(message) {
const pieces = [];
message.nodes.forEach(node => node.visit(serializerVisitor$2, pieces));
return processMessagePieces(pieces);
}
function getSourceSpan(message) {
const startNode = message.nodes[0];
const endNode = message.nodes[message.nodes.length - 1];
return new ParseSourceSpan(startNode.sourceSpan.start, endNode.sourceSpan.end, startNode.sourceSpan.fullStart, startNode.sourceSpan.details);
}
/**
* Convert the list of serialized MessagePieces into two arrays.
*
* One contains the literal string pieces and the other the placeholders that will be replaced by
* expressions when rendering `$localize` tagged template literals.
*
* @param pieces The pieces to process.
* @returns an object containing the messageParts and placeholders.
*/
function processMessagePieces(pieces) {
const messageParts = [];
const placeHolders = [];
if (pieces[0] instanceof PlaceholderPiece) {
// The first piece was a placeholder so we need to add an initial empty message part.
messageParts.push(createEmptyMessagePart(pieces[0].sourceSpan.start));
}
for (let i = 0; i < pieces.length; i++) {
const part = pieces[i];
if (part instanceof LiteralPiece) {
messageParts.push(part);
}
else {
placeHolders.push(part);
if (pieces[i - 1] instanceof PlaceholderPiece) {
// There were two placeholders in a row, so we need to add an empty message part.
messageParts.push(createEmptyMessagePart(pieces[i - 1].sourceSpan.end));
}
}
}
if (pieces[pieces.length - 1] instanceof PlaceholderPiece) {
// The last piece was a placeholder so we need to add a final empty message part.
messageParts.push(createEmptyMessagePart(pieces[pieces.length - 1].sourceSpan.end));
}
return { messageParts, placeHolders };
}
function createEmptyMessagePart(location) {
return new LiteralPiece('', new ParseSourceSpan(location, location));
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// Selector attribute name of `<ng-content>`
const NG_CONTENT_SELECT_ATTR$1 = 'select';
// Attribute name of `ngProjectAs`.
const NG_PROJECT_AS_ATTR_NAME = 'ngProjectAs';
// Global symbols available only inside event bindings.
const EVENT_BINDING_SCOPE_GLOBALS = new Set(['$event']);
// List of supported global targets for event listeners
const GLOBAL_TARGET_RESOLVERS = new Map([['window', Identifiers$1.resolveWindow], ['document', Identifiers$1.resolveDocument], ['body', Identifiers$1.resolveBody]]);
const LEADING_TRIVIA_CHARS = [' ', '\n', '\r', '\t'];
// if (rf & flags) { .. }
function renderFlagCheckIfStmt(flags, statements) {
return ifStmt(variable(RENDER_FLAGS).bitwiseAnd(literal(flags), null, false), statements);
}
function prepareEventListenerParameters(eventAst, handlerName = null, scope = null) {
const { type, name, target, phase, handler } = eventAst;
if (target && !GLOBAL_TARGET_RESOLVERS.has(target)) {
throw new Error(`Unexpected global target '${target}' defined for '${name}' event.
Supported list of global targets: ${Array.from(GLOBAL_TARGET_RESOLVERS.keys())}.`);
}
const eventArgumentName = '$event';
const implicitReceiverAccesses = new Set();
const implicitReceiverExpr = (scope === null || scope.bindingLevel === 0) ?
variable(CONTEXT_NAME) :
scope.getOrCreateSharedContextVar(0);
const bindingExpr = convertActionBinding(scope, implicitReceiverExpr, handler, 'b', () => error('Unexpected interpolation'), eventAst.handlerSpan, implicitReceiverAccesses, EVENT_BINDING_SCOPE_GLOBALS);
const statements = [];
if (scope) {
statements.push(...scope.restoreViewStatement());
statements.push(...scope.variableDeclarations());
}
statements.push(...bindingExpr.render3Stmts);
const eventName = type === 1 /* Animation */ ? prepareSyntheticListenerName(name, phase) : name;
const fnName = handlerName && sanitizeIdentifier(handlerName);
const fnArgs = [];
if (implicitReceiverAccesses.has(eventArgumentName)) {
fnArgs.push(new FnParam(eventArgumentName, DYNAMIC_TYPE));
}
const handlerFn = fn(fnArgs, statements, INFERRED_TYPE, null, fnName);
const params = [literal(eventName), handlerFn];
if (target) {
params.push(literal(false), // `useCapture` flag, defaults to `false`
importExpr(GLOBAL_TARGET_RESOLVERS.get(target)));
}
return params;
}
function createComponentDefConsts() {
return {
prepareStatements: [],
constExpressions: [],
i18nVarRefsCache: new Map(),
};
}
class TemplateDefinitionBuilder {
constructor(constantPool, parentBindingScope, level = 0, contextName, i18nContext, templateIndex, templateName, directiveMatcher, directives, pipeTypeByName, pipes, _namespace, relativeContextFilePath, i18nUseExternalIds, _constants = createComponentDefConsts()) {
this.constantPool = constantPool;
this.level = level;
this.contextName = contextName;
this.i18nContext = i18nContext;
this.templateIndex = templateIndex;
this.templateName = templateName;
this.directiveMatcher = directiveMatcher;
this.directives = directives;
this.pipeTypeByName = pipeTypeByName;
this.pipes = pipes;
this._namespace = _namespace;
this.i18nUseExternalIds = i18nUseExternalIds;
this._constants = _constants;
this._dataIndex = 0;
this._bindingContext = 0;
this._prefixCode = [];
/**
* List of callbacks to generate creation mode instructions. We store them here as we process
* the template so bindings in listeners are resolved only once all nodes have been visited.
* This ensures all local refs and context variables are available for matching.
*/
this._creationCodeFns = [];
/**
* List of callbacks to generate update mode instructions. We store them here as we process
* the template so bindings are resolved only once all nodes have been visited. This ensures
* all local refs and context variables are available for matching.
*/
this._updateCodeFns = [];
/** Index of the currently-selected node. */
this._currentIndex = 0;
/** Temporary variable declarations generated from visiting pipes, literals, etc. */
this._tempVariables = [];
/**
* List of callbacks to build nested templates. Nested templates must not be visited until
* after the parent template has finished visiting all of its nodes. This ensures that all
* local ref bindings in nested templates are able to find local ref values if the refs
* are defined after the template declaration.
*/
this._nestedTemplateFns = [];
this._unsupported = unsupported;
// i18n context local to this template
this.i18n = null;
// Number of slots to reserve for pureFunctions
this._pureFunctionSlots = 0;
// Number of binding slots
this._bindingSlots = 0;
// Projection slots found in the template. Projection slots can distribute projected
// nodes based on a selector, or can just use the wildcard selector to match
// all nodes which aren't matching any selector.
this._ngContentReservedSlots = [];
// Number of non-default selectors found in all parent templates of this template. We need to
// track it to properly adjust projection slot index in the `projection` instruction.
this._ngContentSelectorsOffset = 0;
// Expression that should be used as implicit receiver when converting template
// expressions to output AST.
this._implicitReceiverExpr = null;
// These should be handled in the template or element directly.
this.visitReference = invalid$1;
this.visitVariable = invalid$1;
this.visitTextAttribute = invalid$1;
this.visitBoundAttribute = invalid$1;
this.visitBoundEvent = invalid$1;
this._bindingScope = parentBindingScope.nestedScope(level);
// Turn the relative context file path into an identifier by replacing non-alphanumeric
// characters with underscores.
this.fileBasedI18nSuffix = relativeContextFilePath.replace(/[^A-Za-z0-9]/g, '_') + '_';
this._valueConverter = new ValueConverter(constantPool, () => this.allocateDataSlot(), (numSlots) => this.allocatePureFunctionSlots(numSlots), (name, localName, slot, value) => {
const pipeType = pipeTypeByName.get(name);
if (pipeType) {
this.pipes.add(pipeType);
}
this._bindingScope.set(this.level, localName, value);
this.creationInstruction(null, Identifiers$1.pipe, [literal(slot), literal(name)]);
});
}
buildTemplateFunction(nodes, variables, ngContentSelectorsOffset = 0, i18n) {
this._ngContentSelectorsOffset = ngContentSelectorsOffset;
if (this._namespace !== Identifiers$1.namespaceHTML) {
this.creationInstruction(null, this._namespace);
}
// Create variable bindings
variables.forEach(v => this.registerContextVariables(v));
// Initiate i18n context in case:
// - this template has parent i18n context
// - or the template has i18n meta associated with it,
// but it's not initiated by the Element (e.g. <ng-template i18n>)
const initI18nContext = this.i18nContext ||
(isI18nRootNode(i18n) && !isSingleI18nIcu(i18n) &&
!(isSingleElementTemplate(nodes) && nodes[0].i18n === i18n));
const selfClosingI18nInstruction = hasTextChildrenOnly(nodes);
if (initI18nContext) {
this.i18nStart(null, i18n, selfClosingI18nInstruction);
}
// This is the initial pass through the nodes of this template. In this pass, we
// queue all creation mode and update mode instructions for generation in the second
// pass. It's necessary to separate the passes to ensure local refs are defined before
// resolving bindings. We also count bindings in this pass as we walk bound expressions.
visitAll(this, nodes);
// Add total binding count to pure function count so pure function instructions are
// generated with the correct slot offset when update instructions are processed.
this._pureFunctionSlots += this._bindingSlots;
// Pipes are walked in the first pass (to enqueue `pipe()` creation instructions and
// `pipeBind` update instructions), so we have to update the slot offsets manually
// to account for bindings.
this._valueConverter.updatePipeSlotOffsets(this._bindingSlots);
// Nested templates must be processed before creation instructions so template()
// instructions can be generated with the correct internal const count.
this._nestedTemplateFns.forEach(buildTemplateFn => buildTemplateFn());
// Output the `projectionDef` instruction when some `<ng-content>` tags are present.
// The `projectionDef` instruction is only emitted for the component template and
// is skipped for nested templates (<ng-template> tags).
if (this.level === 0 && this._ngContentReservedSlots.length) {
const parameters = [];
// By default the `projectionDef` instructions creates one slot for the wildcard
// selector if no parameters are passed. Therefore we only want to allocate a new
// array for the projection slots if the default projection slot is not sufficient.
if (this._ngContentReservedSlots.length > 1 || this._ngContentReservedSlots[0] !== '*') {
const r3ReservedSlots = this._ngContentReservedSlots.map(s => s !== '*' ? parseSelectorToR3Selector(s) : s);
parameters.push(this.constantPool.getConstLiteral(asLiteral(r3ReservedSlots), true));
}
// Since we accumulate ngContent selectors while processing template elements,
// we *prepend* `projectionDef` to creation instructions block, to put it before
// any `projection` instructions
this.creationInstruction(null, Identifiers$1.projectionDef, parameters, /* prepend */ true);
}
if (initI18nContext) {
this.i18nEnd(null, selfClosingI18nInstruction);
}
// Generate all the creation mode instructions (e.g. resolve bindings in listeners)
const creationStatements = this._creationCodeFns.map((fn) => fn());
// Generate all the update mode instructions (e.g. resolve property or text bindings)
const updateStatements = this._updateCodeFns.map((fn) => fn());
// Variable declaration must occur after binding resolution so we can generate context
// instructions that build on each other.
// e.g. const b = nextContext().$implicit(); const b = nextContext();
const creationVariables = this._bindingScope.viewSnapshotStatements();
const updateVariables = this._bindingScope.variableDeclarations().concat(this._tempVariables);
const creationBlock = creationStatements.length > 0 ?
[renderFlagCheckIfStmt(1 /* Create */, creationVariables.concat(creationStatements))] :
[];
const updateBlock = updateStatements.length > 0 ?
[renderFlagCheckIfStmt(2 /* Update */, updateVariables.concat(updateStatements))] :
[];
return fn(
// i.e. (rf: RenderFlags, ctx: any)
[new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], [
// Temporary variable declarations for query refresh (i.e. let _t: any;)
...this._prefixCode,
// Creating mode (i.e. if (rf & RenderFlags.Create) { ... })
...creationBlock,
// Binding and refresh mode (i.e. if (rf & RenderFlags.Update) {...})
...updateBlock,
], INFERRED_TYPE, null, this.templateName);
}
// LocalResolver
getLocal(name) {
return this._bindingScope.get(name);
}
// LocalResolver
notifyImplicitReceiverUse() {
this._bindingScope.notifyImplicitReceiverUse();
}
i18nTranslate(message, params = {}, ref, transformFn) {
const _ref = ref || this.i18nGenerateMainBlockVar();
// Closure Compiler requires const names to start with `MSG_` but disallows any other const to
// start with `MSG_`. We define a variable starting with `MSG_` just for the `goog.getMsg` call
const closureVar = this.i18nGenerateClosureVar(message.id);
const statements = getTranslationDeclStmts(message, _ref, closureVar, params, transformFn);
this._constants.prepareStatements.push(...statements);
return _ref;
}
registerContextVariables(variable$1) {
const scopedName = this._bindingScope.freshReferenceName();
const retrievalLevel = this.level;
const lhs = variable(variable$1.name + scopedName);
this._bindingScope.set(retrievalLevel, variable$1.name, lhs, 1 /* CONTEXT */, (scope, relativeLevel) => {
let rhs;
if (scope.bindingLevel === retrievalLevel) {
// e.g. ctx
rhs = variable(CONTEXT_NAME);
}
else {
const sharedCtxVar = scope.getSharedContextName(retrievalLevel);
// e.g. ctx_r0 OR x(2);
rhs = sharedCtxVar ? sharedCtxVar : generateNextContextExpr(relativeLevel);
}
// e.g. const $item$ = x(2).$implicit;
return [lhs.set(rhs.prop(variable$1.value || IMPLICIT_REFERENCE)).toConstDecl()];
});
}
i18nAppendBindings(expressions) {
if (expressions.length > 0) {
expressions.forEach(expression => this.i18n.appendBinding(expression));
}
}
i18nBindProps(props) {
const bound = {};
Object.keys(props).forEach(key => {
const prop = props[key];
if (prop instanceof Text) {
bound[key] = literal(prop.value);
}
else {
const value = prop.value.visit(this._valueConverter);
this.allocateBindingSlots(value);
if (value instanceof Interpolation) {
const { strings, expressions } = value;
const { id, bindings } = this.i18n;
const label = assembleI18nBoundString(strings, bindings.size, id);
this.i18nAppendBindings(expressions);
bound[key] = literal(label);
}
}
});
return bound;
}
// Generates top level vars for i18n blocks (i.e. `i18n_N`).
i18nGenerateMainBlockVar() {
return variable(this.constantPool.uniqueName(TRANSLATION_VAR_PREFIX));
}
// Generates vars with Closure-specific names for i18n blocks (i.e. `MSG_XXX`).
i18nGenerateClosureVar(messageId) {
let name;
const suffix = this.fileBasedI18nSuffix.toUpperCase();
if (this.i18nUseExternalIds) {
const prefix = getTranslationConstPrefix(`EXTERNAL_`);
const uniqueSuffix = this.constantPool.uniqueName(suffix);
name = `${prefix}${sanitizeIdentifier(messageId)}$$${uniqueSuffix}`;
}
else {
const prefix = getTranslationConstPrefix(suffix);
name = this.constantPool.uniqueName(prefix);
}
return variable(name);
}
i18nUpdateRef(context) {
const { icus, meta, isRoot, isResolved, isEmitted } = context;
if (isRoot && isResolved && !isEmitted && !isSingleI18nIcu(meta)) {
context.isEmitted = true;
const placeholders = context.getSerializedPlaceholders();
let icuMapping = {};
let params = placeholders.size ? placeholdersToParams(placeholders) : {};
if (icus.size) {
icus.forEach((refs, key) => {
if (refs.length === 1) {
// if we have one ICU defined for a given
// placeholder - just output its reference
params[key] = refs[0];
}
else {
// ... otherwise we need to activate post-processing
// to replace ICU placeholders with proper values
const placeholder = wrapI18nPlaceholder(`${I18N_ICU_MAPPING_PREFIX}${key}`);
params[key] = literal(placeholder);
icuMapping[key] = literalArr(refs);
}
});
}
// translation requires post processing in 2 cases:
// - if we have placeholders with multiple values (ex. `START_DIV`: [�#1�, �#2�, ...])
// - if we have multiple ICUs that refer to the same placeholder name
const needsPostprocessing = Array.from(placeholders.values()).some((value) => value.length > 1) ||
Object.keys(icuMapping).length;
let transformFn;
if (needsPostprocessing) {
transformFn = (raw) => {
const args = [raw];
if (Object.keys(icuMapping).length) {
args.push(mapLiteral(icuMapping, true));
}
return instruction(null, Identifiers$1.i18nPostprocess, args);
};
}
this.i18nTranslate(meta, params, context.ref, transformFn);
}
}
i18nStart(span = null, meta, selfClosing) {
const index = this.allocateDataSlot();
this.i18n = this.i18nContext ?
this.i18nContext.forkChildContext(index, this.templateIndex, meta) :
new I18nContext(index, this.i18nGenerateMainBlockVar(), 0, this.templateIndex, meta);
// generate i18nStart instruction
const { id, ref } = this.i18n;
const params = [literal(index), this.addToConsts(ref)];
if (id > 0) {
// do not push 3rd argument (sub-block id)
// into i18nStart call for top level i18n context
params.push(literal(id));
}
this.creationInstruction(span, selfClosing ? Identifiers$1.i18n : Identifiers$1.i18nStart, params);
}
i18nEnd(span = null, selfClosing) {
if (!this.i18n) {
throw new Error('i18nEnd is executed with no i18n context present');
}
if (this.i18nContext) {
this.i18nContext.reconcileChildContext(this.i18n);
this.i18nUpdateRef(this.i18nContext);
}
else {
this.i18nUpdateRef(this.i18n);
}
// setup accumulated bindings
const { index, bindings } = this.i18n;
if (bindings.size) {
const chainBindings = [];
bindings.forEach(binding => {
chainBindings.push({ sourceSpan: span, value: () => this.convertPropertyBinding(binding) });
});
// for i18n block, advance to the most recent element index (by taking the current number of
// elements and subtracting one) before invoking `i18nExp` instructions, to make sure the
// necessary lifecycle hooks of components/directives are properly flushed.
this.updateInstructionChainWithAdvance(this.getConstCount() - 1, Identifiers$1.i18nExp, chainBindings);
this.updateInstruction(span, Identifiers$1.i18nApply, [literal(index)]);
}
if (!selfClosing) {
this.creationInstruction(span, Identifiers$1.i18nEnd);
}
this.i18n = null; // reset local i18n context
}
i18nAttributesInstruction(nodeIndex, attrs, sourceSpan) {
let hasBindings = false;
const i18nAttrArgs = [];
const bindings = [];
attrs.forEach(attr => {
const message = attr.i18n;
const converted = attr.value.visit(this._valueConverter);
this.allocateBindingSlots(converted);
if (converted instanceof Interpolation) {
const placeholders = assembleBoundTextPlaceholders(message);
const params = placeholdersToParams(placeholders);
i18nAttrArgs.push(literal(attr.name), this.i18nTranslate(message, params));
converted.expressions.forEach(expression => {
hasBindings = true;
bindings.push({
sourceSpan,
value: () => this.convertPropertyBinding(expression),
});
});
}
});
if (bindings.length > 0) {
this.updateInstructionChainWithAdvance(nodeIndex, Identifiers$1.i18nExp, bindings);
}
if (i18nAttrArgs.length > 0) {
const index = literal(this.allocateDataSlot());
const constIndex = this.addToConsts(literalArr(i18nAttrArgs));
this.creationInstruction(sourceSpan, Identifiers$1.i18nAttributes, [index, constIndex]);
if (hasBindings) {
this.updateInstruction(sourceSpan, Identifiers$1.i18nApply, [index]);
}
}
}
getNamespaceInstruction(namespaceKey) {
switch (namespaceKey) {
case 'math':
return Identifiers$1.namespaceMathML;
case 'svg':
return Identifiers$1.namespaceSVG;
default:
return Identifiers$1.namespaceHTML;
}
}
addNamespaceInstruction(nsInstruction, element) {
this._namespace = nsInstruction;
this.creationInstruction(element.startSourceSpan, nsInstruction);
}
/**
* Adds an update instruction for an interpolated property or attribute, such as
* `prop="{{value}}"` or `attr.title="{{value}}"`
*/
interpolatedUpdateInstruction(instruction, elementIndex, attrName, input, value, params) {
this.updateInstructionWithAdvance(elementIndex, input.sourceSpan, instruction, () => [literal(attrName), ...this.getUpdateInstructionArguments(value), ...params]);
}
visitContent(ngContent) {
const slot = this.allocateDataSlot();
const projectionSlotIdx = this._ngContentSelectorsOffset + this._ngContentReservedSlots.length;
const parameters = [literal(slot)];
this._ngContentReservedSlots.push(ngContent.selector);
const nonContentSelectAttributes = ngContent.attributes.filter(attr => attr.name.toLowerCase() !== NG_CONTENT_SELECT_ATTR$1);
const attributes = this.getAttributeExpressions(ngContent.name, nonContentSelectAttributes, [], []);
if (attributes.length > 0) {
parameters.push(literal(projectionSlotIdx), literalArr(attributes));
}
else if (projectionSlotIdx !== 0) {
parameters.push(literal(projectionSlotIdx));
}
this.creationInstruction(ngContent.sourceSpan, Identifiers$1.projection, parameters);
if (this.i18n) {
this.i18n.appendProjection(ngContent.i18n, slot);
}
}
visitElement(element) {
var _a, _b;
const elementIndex = this.allocateDataSlot();
const stylingBuilder = new StylingBuilder(null);
let isNonBindableMode = false;
const isI18nRootElement = isI18nRootNode(element.i18n) && !isSingleI18nIcu(element.i18n);
const outputAttrs = [];
const [namespaceKey, elementName] = splitNsName(element.name);
const isNgContainer$1 = isNgContainer(element.name);
// Handle styling, i18n, ngNonBindable attributes
for (const attr of element.attributes) {
const { name, value } = attr;
if (name === NON_BINDABLE_ATTR) {
isNonBindableMode = true;
}
else if (name === 'style') {
stylingBuilder.registerStyleAttr(value);
}
else if (name === 'class') {
stylingBuilder.registerClassAttr(value);
}
else {
outputAttrs.push(attr);
}
}
// Match directives on non i18n attributes
this.matchDirectives(element.name, element);
// Regular element or ng-container creation mode
const parameters = [literal(elementIndex)];
if (!isNgContainer$1) {
parameters.push(literal(elementName));
}
// Add the attributes
const allOtherInputs = [];
const boundI18nAttrs = [];
element.inputs.forEach(input => {
const stylingInputWasSet = stylingBuilder.registerBoundInput(input);
if (!stylingInputWasSet) {
if (input.type === 0 /* Property */ && input.i18n) {
boundI18nAttrs.push(input);
}
else {
allOtherInputs.push(input);
}
}
});
// add attributes for directive and projection matching purposes
const attributes = this.getAttributeExpressions(element.name, outputAttrs, allOtherInputs, element.outputs, stylingBuilder, [], boundI18nAttrs);
parameters.push(this.addAttrsToConsts(attributes));
// local refs (ex.: <div #foo #bar="baz">)
const refs = this.prepareRefsArray(element.references);
parameters.push(this.addToConsts(refs));
const wasInNamespace = this._namespace;
const currentNamespace = this.getNamespaceInstruction(namespaceKey);
// If the namespace is changing now, include an instruction to change it
// during element creation.
if (currentNamespace !== wasInNamespace) {
this.addNamespaceInstruction(currentNamespace, element);
}
if (this.i18n) {
this.i18n.appendElement(element.i18n, elementIndex);
}
// Note that we do not append text node instructions and ICUs inside i18n section,
// so we exclude them while calculating whether current element has children
const hasChildren = (!isI18nRootElement && this.i18n) ? !hasTextChildrenOnly(element.children) :
element.children.length > 0;
const createSelfClosingInstruction = !stylingBuilder.hasBindingsWithPipes &&
element.outputs.length === 0 && boundI18nAttrs.length === 0 && !hasChildren;
const createSelfClosingI18nInstruction = !createSelfClosingInstruction && hasTextChildrenOnly(element.children);
if (createSelfClosingInstruction) {
this.creationInstruction(element.sourceSpan, isNgContainer$1 ? Identifiers$1.elementContainer : Identifiers$1.element, trimTrailingNulls(parameters));
}
else {
this.creationInstruction(element.startSourceSpan, isNgContainer$1 ? Identifiers$1.elementContainerStart : Identifiers$1.elementStart, trimTrailingNulls(parameters));
if (isNonBindableMode) {
this.creationInstruction(element.startSourceSpan, Identifiers$1.disableBindings);
}
if (boundI18nAttrs.length > 0) {
this.i18nAttributesInstruction(elementIndex, boundI18nAttrs, (_a = element.startSourceSpan) !== null && _a !== void 0 ? _a : element.sourceSpan);
}
// Generate Listeners (outputs)
if (element.outputs.length > 0) {
const listeners = element.outputs.map((outputAst) => ({
sourceSpan: outputAst.sourceSpan,
params: this.prepareListenerParameter(element.name, outputAst, elementIndex)
}));
this.creationInstructionChain(Identifiers$1.listener, listeners);
}
// Note: it's important to keep i18n/i18nStart instructions after i18nAttributes and
// listeners, to make sure i18nAttributes instruction targets current element at runtime.
if (isI18nRootElement) {
this.i18nStart(element.startSourceSpan, element.i18n, createSelfClosingI18nInstruction);
}
}
// the code here will collect all update-level styling instructions and add them to the
// update block of the template function AOT code. Instructions like `styleProp`,
// `styleMap`, `classMap`, `classProp`
// are all generated and assigned in the code below.
const stylingInstructions = stylingBuilder.buildUpdateLevelInstructions(this._valueConverter);
const limit = stylingInstructions.length - 1;
for (let i = 0; i <= limit; i++) {
const instruction = stylingInstructions[i];
this._bindingSlots += this.processStylingUpdateInstruction(elementIndex, instruction);
}
// the reason why `undefined` is used is because the renderer understands this as a
// special value to symbolize that there is no RHS to this binding
// TODO (matsko): revisit this once FW-959 is approached
const emptyValueBindInstruction = literal(undefined);
const propertyBindings = [];
const attributeBindings = [];
// Generate element input bindings
allOtherInputs.forEach(input => {
const inputType = input.type;
if (inputType === 4 /* Animation */) {
const value = input.value.visit(this._valueConverter);
// animation bindings can be presented in the following formats:
// 1. [@binding]="fooExp"
// 2. [@binding]="{value:fooExp, params:{...}}"
// 3. [@binding]
// 4. @binding
// All formats will be valid for when a synthetic binding is created.
// The reasoning for this is because the renderer should get each
// synthetic binding value in the order of the array that they are
// defined in...
const hasValue = value instanceof LiteralPrimitive ? !!value.value : true;
this.allocateBindingSlots(value);
propertyBindings.push({
name: prepareSyntheticPropertyName(input.name),
sourceSpan: input.sourceSpan,
value: () => hasValue ? this.convertPropertyBinding(value) : emptyValueBindInstruction
});
}
else {
// we must skip attributes with associated i18n context, since these attributes are handled
// separately and corresponding `i18nExp` and `i18nApply` instructions will be generated
if (input.i18n)
return;
const value = input.value.visit(this._valueConverter);
if (value !== undefined) {
const params = [];
const [attrNamespace, attrName] = splitNsName(input.name);
const isAttributeBinding = inputType === 1 /* Attribute */;
const sanitizationRef = resolveSanitizationFn(input.securityContext, isAttributeBinding);
if (sanitizationRef)
params.push(sanitizationRef);
if (attrNamespace) {
const namespaceLiteral = literal(attrNamespace);
if (sanitizationRef) {
params.push(namespaceLiteral);
}
else {
// If there wasn't a sanitization ref, we need to add
// an extra param so that we can pass in the namespace.
params.push(literal(null), namespaceLiteral);
}
}
this.allocateBindingSlots(value);
if (inputType === 0 /* Property */) {
if (value instanceof Interpolation) {
// prop="{{value}}" and friends
this.interpolatedUpdateInstruction(getPropertyInterpolationExpression(value), elementIndex, attrName, input, value, params);
}
else {
// [prop]="value"
// Collect all the properties so that we can chain into a single function at the end.
propertyBindings.push({
name: attrName,
sourceSpan: input.sourceSpan,
value: () => this.convertPropertyBinding(value),
params
});
}
}
else if (inputType === 1 /* Attribute */) {
if (value instanceof Interpolation && getInterpolationArgsLength(value) > 1) {
// attr.name="text{{value}}" and friends
this.interpolatedUpdateInstruction(getAttributeInterpolationExpression(value), elementIndex, attrName, input, value, params);
}
else {
const boundValue = value instanceof Interpolation ? value.expressions[0] : value;
// [attr.name]="value" or attr.name="{{value}}"
// Collect the attribute bindings so that they can be chained at the end.
attributeBindings.push({
name: attrName,
sourceSpan: input.sourceSpan,
value: () => this.convertPropertyBinding(boundValue),
params
});
}
}
else {
// class prop
this.updateInstructionWithAdvance(elementIndex, input.sourceSpan, Identifiers$1.classProp, () => {
return [
literal(elementIndex), literal(attrName), this.convertPropertyBinding(value),
...params
];
});
}
}
}
});
if (propertyBindings.length > 0) {
this.updateInstructionChainWithAdvance(elementIndex, Identifiers$1.property, propertyBindings);
}
if (attributeBindings.length > 0) {
this.updateInstructionChainWithAdvance(elementIndex, Identifiers$1.attribute, attributeBindings);
}
// Traverse element child nodes
visitAll(this, element.children);
if (!isI18nRootElement && this.i18n) {
this.i18n.appendElement(element.i18n, elementIndex, true);
}
if (!createSelfClosingInstruction) {
// Finish element construction mode.
const span = (_b = element.endSourceSpan) !== null && _b !== void 0 ? _b : element.sourceSpan;
if (isI18nRootElement) {
this.i18nEnd(span, createSelfClosingI18nInstruction);
}
if (isNonBindableMode) {
this.creationInstruction(span, Identifiers$1.enableBindings);
}
this.creationInstruction(span, isNgContainer$1 ? Identifiers$1.elementContainerEnd : Identifiers$1.elementEnd);
}
}
visitTemplate(template) {
var _a;
const NG_TEMPLATE_TAG_NAME = 'ng-template';
const templateIndex = this.allocateDataSlot();
if (this.i18n) {
this.i18n.appendTemplate(template.i18n, templateIndex);
}
const tagName = sanitizeIdentifier(template.tagName || '');
const contextName = `${this.contextName}${tagName ? '_' + tagName : ''}_${templateIndex}`;
const templateName = `${contextName}_Template`;
const parameters = [
literal(templateIndex),
variable(templateName),
// We don't care about the tag's namespace here, because we infer
// it based on the parent nodes inside the template instruction.
literal(template.tagName ? splitNsName(template.tagName)[1] : template.tagName),
];
// find directives matching on a given <ng-template> node
this.matchDirectives(NG_TEMPLATE_TAG_NAME, template);
// prepare attributes parameter (including attributes used for directive matching)
const attrsExprs = this.getAttributeExpressions(NG_TEMPLATE_TAG_NAME, template.attributes, template.inputs, template.outputs, undefined /* styles */, template.templateAttrs);
parameters.push(this.addAttrsToConsts(attrsExprs));
// local refs (ex.: <ng-template #foo>)
if (template.references && template.references.length) {
const refs = this.prepareRefsArray(template.references);
parameters.push(this.addToConsts(refs));
parameters.push(importExpr(Identifiers$1.templateRefExtractor));
}
// Create the template function
const templateVisitor = new TemplateDefinitionBuilder(this.constantPool, this._bindingScope, this.level + 1, contextName, this.i18n, templateIndex, templateName, this.directiveMatcher, this.directives, this.pipeTypeByName, this.pipes, this._namespace, this.fileBasedI18nSuffix, this.i18nUseExternalIds, this._constants);
// Nested templates must not be visited until after their parent templates have completed
// processing, so they are queued here until after the initial pass. Otherwise, we wouldn't
// be able to support bindings in nested templates to local refs that occur after the
// template definition. e.g. <div *ngIf="showing">{{ foo }}</div> <div #foo></div>
this._nestedTemplateFns.push(() => {
const templateFunctionExpr = templateVisitor.buildTemplateFunction(template.children, template.variables, this._ngContentReservedSlots.length + this._ngContentSelectorsOffset, template.i18n);
this.constantPool.statements.push(templateFunctionExpr.toDeclStmt(templateName));
if (templateVisitor._ngContentReservedSlots.length) {
this._ngContentReservedSlots.push(...templateVisitor._ngContentReservedSlots);
}
});
// e.g. template(1, MyComp_Template_1)
this.creationInstruction(template.sourceSpan, Identifiers$1.templateCreate, () => {
parameters.splice(2, 0, literal(templateVisitor.getConstCount()), literal(templateVisitor.getVarCount()));
return trimTrailingNulls(parameters);
});
// handle property bindings e.g. ɵɵproperty('ngForOf', ctx.items), et al;
this.templatePropertyBindings(templateIndex, template.templateAttrs);
// Only add normal input/output binding instructions on explicit <ng-template> elements.
if (template.tagName === NG_TEMPLATE_TAG_NAME) {
const [i18nInputs, inputs] = partitionArray(template.inputs, hasI18nMeta);
// Add i18n attributes that may act as inputs to directives. If such attributes are present,
// generate `i18nAttributes` instruction. Note: we generate it only for explicit <ng-template>
// elements, in case of inline templates, corresponding instructions will be generated in the
// nested template function.
if (i18nInputs.length > 0) {
this.i18nAttributesInstruction(templateIndex, i18nInputs, (_a = template.startSourceSpan) !== null && _a !== void 0 ? _a : template.sourceSpan);
}
// Add the input bindings
if (inputs.length > 0) {
this.templatePropertyBindings(templateIndex, inputs);
}
// Generate listeners for directive output
if (template.outputs.length > 0) {
const listeners = template.outputs.map((outputAst) => ({
sourceSpan: outputAst.sourceSpan,
params: this.prepareListenerParameter('ng_template', outputAst, templateIndex)
}));
this.creationInstructionChain(Identifiers$1.listener, listeners);
}
}
}
visitBoundText(text) {
if (this.i18n) {
const value = text.value.visit(this._valueConverter);
this.allocateBindingSlots(value);
if (value instanceof Interpolation) {
this.i18n.appendBoundText(text.i18n);
this.i18nAppendBindings(value.expressions);
}
return;
}
const nodeIndex = this.allocateDataSlot();
this.creationInstruction(text.sourceSpan, Identifiers$1.text, [literal(nodeIndex)]);
const value = text.value.visit(this._valueConverter);
this.allocateBindingSlots(value);
if (value instanceof Interpolation) {
this.updateInstructionWithAdvance(nodeIndex, text.sourceSpan, getTextInterpolationExpression(value), () => this.getUpdateInstructionArguments(value));
}
else {
error('Text nodes should be interpolated and never bound directly.');
}
}
visitText(text) {
// when a text element is located within a translatable
// block, we exclude this text element from instructions set,
// since it will be captured in i18n content and processed at runtime
if (!this.i18n) {
this.creationInstruction(text.sourceSpan, Identifiers$1.text, [literal(this.allocateDataSlot()), literal(text.value)]);
}
}
visitIcu(icu) {
let initWasInvoked = false;
// if an ICU was created outside of i18n block, we still treat
// it as a translatable entity and invoke i18nStart and i18nEnd
// to generate i18n context and the necessary instructions
if (!this.i18n) {
initWasInvoked = true;
this.i18nStart(null, icu.i18n, true);
}
const i18n = this.i18n;
const vars = this.i18nBindProps(icu.vars);
const placeholders = this.i18nBindProps(icu.placeholders);
// output ICU directly and keep ICU reference in context
const message = icu.i18n;
// we always need post-processing function for ICUs, to make sure that:
// - all placeholders in a form of {PLACEHOLDER} are replaced with actual values (note:
// `goog.getMsg` does not process ICUs and uses the `{PLACEHOLDER}` format for placeholders
// inside ICUs)
// - all ICU vars (such as `VAR_SELECT` or `VAR_PLURAL`) are replaced with correct values
const transformFn = (raw) => {
const params = Object.assign(Object.assign({}, vars), placeholders);
const formatted = i18nFormatPlaceholderNames(params, /* useCamelCase */ false);
return instruction(null, Identifiers$1.i18nPostprocess, [raw, mapLiteral(formatted, true)]);
};
// in case the whole i18n message is a single ICU - we do not need to
// create a separate top-level translation, we can use the root ref instead
// and make this ICU a top-level translation
// note: ICU placeholders are replaced with actual values in `i18nPostprocess` function
// separately, so we do not pass placeholders into `i18nTranslate` function.
if (isSingleI18nIcu(i18n.meta)) {
this.i18nTranslate(message, /* placeholders */ {}, i18n.ref, transformFn);
}
else {
// output ICU directly and keep ICU reference in context
const ref = this.i18nTranslate(message, /* placeholders */ {}, /* ref */ undefined, transformFn);
i18n.appendIcu(icuFromI18nMessage(message).name, ref);
}
if (initWasInvoked) {
this.i18nEnd(null, true);
}
return null;
}
allocateDataSlot() {
return this._dataIndex++;
}
getConstCount() {
return this._dataIndex;
}
getVarCount() {
return this._pureFunctionSlots;
}
getConsts() {
return this._constants;
}
getNgContentSelectors() {
return this._ngContentReservedSlots.length ?
this.constantPool.getConstLiteral(asLiteral(this._ngContentReservedSlots), true) :
null;
}
bindingContext() {
return `${this._bindingContext++}`;
}
templatePropertyBindings(templateIndex, attrs) {
const propertyBindings = [];
attrs.forEach(input => {
if (input instanceof BoundAttribute) {
const value = input.value.visit(this._valueConverter);
if (value !== undefined) {
this.allocateBindingSlots(value);
if (value instanceof Interpolation) {
// Params typically contain attribute namespace and value sanitizer, which is applicable
// for regular HTML elements, but not applicable for <ng-template> (since props act as
// inputs to directives), so keep params array empty.
const params = [];
// prop="{{value}}" case
this.interpolatedUpdateInstruction(getPropertyInterpolationExpression(value), templateIndex, input.name, input, value, params);
}
else {
// [prop]="value" case
propertyBindings.push({
name: input.name,
sourceSpan: input.sourceSpan,
value: () => this.convertPropertyBinding(value)
});
}
}
}
});
if (propertyBindings.length > 0) {
this.updateInstructionChainWithAdvance(templateIndex, Identifiers$1.property, propertyBindings);
}
}
// Bindings must only be resolved after all local refs have been visited, so all
// instructions are queued in callbacks that execute once the initial pass has completed.
// Otherwise, we wouldn't be able to support local refs that are defined after their
// bindings. e.g. {{ foo }} <div #foo></div>
instructionFn(fns, span, reference, paramsOrFn, prepend = false) {
fns[prepend ? 'unshift' : 'push'](() => {
const params = Array.isArray(paramsOrFn) ? paramsOrFn : paramsOrFn();
return instruction(span, reference, params).toStmt();
});
}
processStylingUpdateInstruction(elementIndex, instruction) {
let allocateBindingSlots = 0;
if (instruction) {
const calls = [];
instruction.calls.forEach(call => {
allocateBindingSlots += call.allocateBindingSlots;
calls.push({
sourceSpan: call.sourceSpan,
value: () => {
return call.params(value => (call.supportsInterpolation && value instanceof Interpolation) ?
this.getUpdateInstructionArguments(value) :
this.convertPropertyBinding(value));
}
});
});
this.updateInstructionChainWithAdvance(elementIndex, instruction.reference, calls);
}
return allocateBindingSlots;
}
creationInstruction(span, reference, paramsOrFn, prepend) {
this.instructionFn(this._creationCodeFns, span, reference, paramsOrFn || [], prepend);
}
creationInstructionChain(reference, calls) {
const span = calls.length ? calls[0].sourceSpan : null;
this._creationCodeFns.push(() => {
return chainedInstruction(reference, calls.map(call => call.params()), span).toStmt();
});
}
updateInstructionWithAdvance(nodeIndex, span, reference, paramsOrFn) {
this.addAdvanceInstructionIfNecessary(nodeIndex, span);
this.updateInstruction(span, reference, paramsOrFn);
}
updateInstruction(span, reference, paramsOrFn) {
this.instructionFn(this._updateCodeFns, span, reference, paramsOrFn || []);
}
updateInstructionChain(reference, bindings) {
const span = bindings.length ? bindings[0].sourceSpan : null;
this._updateCodeFns.push(() => {
const calls = bindings.map(property => {
const value = property.value();
const fnParams = Array.isArray(value) ? value : [value];
if (property.params) {
fnParams.push(...property.params);
}
if (property.name) {
// We want the property name to always be the first function parameter.
fnParams.unshift(literal(property.name));
}
return fnParams;
});
return chainedInstruction(reference, calls, span).toStmt();
});
}
updateInstructionChainWithAdvance(nodeIndex, reference, bindings) {
this.addAdvanceInstructionIfNecessary(nodeIndex, bindings.length ? bindings[0].sourceSpan : null);
this.updateInstructionChain(reference, bindings);
}
addAdvanceInstructionIfNecessary(nodeIndex, span) {
if (nodeIndex !== this._currentIndex) {
const delta = nodeIndex - this._currentIndex;
if (delta < 1) {
throw new Error('advance instruction can only go forwards');
}
this.instructionFn(this._updateCodeFns, span, Identifiers$1.advance, [literal(delta)]);
this._currentIndex = nodeIndex;
}
}
allocatePureFunctionSlots(numSlots) {
const originalSlots = this._pureFunctionSlots;
this._pureFunctionSlots += numSlots;
return originalSlots;
}
allocateBindingSlots(value) {
this._bindingSlots += value instanceof Interpolation ? value.expressions.length : 1;
}
/**
* Gets an expression that refers to the implicit receiver. The implicit
* receiver is always the root level context.
*/
getImplicitReceiverExpr() {
if (this._implicitReceiverExpr) {
return this._implicitReceiverExpr;
}
return this._implicitReceiverExpr = this.level === 0 ?
variable(CONTEXT_NAME) :
this._bindingScope.getOrCreateSharedContextVar(0);
}
convertPropertyBinding(value) {
const convertedPropertyBinding = convertPropertyBinding(this, this.getImplicitReceiverExpr(), value, this.bindingContext(), BindingForm.Expression, () => error('Unexpected interpolation'));
const valExpr = convertedPropertyBinding.currValExpr;
this._tempVariables.push(...convertedPropertyBinding.stmts);
return valExpr;
}
/**
* Gets a list of argument expressions to pass to an update instruction expression. Also updates
* the temp variables state with temp variables that were identified as needing to be created
* while visiting the arguments.
* @param value The original expression we will be resolving an arguments list from.
*/
getUpdateInstructionArguments(value) {
const { args, stmts } = convertUpdateArguments(this, this.getImplicitReceiverExpr(), value, this.bindingContext());
this._tempVariables.push(...stmts);
return args;
}
matchDirectives(elementName, elOrTpl) {
if (this.directiveMatcher) {
const selector = createCssSelector(elementName, getAttrsForDirectiveMatching(elOrTpl));
this.directiveMatcher.match(selector, (cssSelector, staticType) => {
this.directives.add(staticType);
});
}
}
/**
* Prepares all attribute expression values for the `TAttributes` array.
*
* The purpose of this function is to properly construct an attributes array that
* is passed into the `elementStart` (or just `element`) functions. Because there
* are many different types of attributes, the array needs to be constructed in a
* special way so that `elementStart` can properly evaluate them.
*
* The format looks like this:
*
* ```
* attrs = [prop, value, prop2, value2,
* PROJECT_AS, selector,
* CLASSES, class1, class2,
* STYLES, style1, value1, style2, value2,
* BINDINGS, name1, name2, name3,
* TEMPLATE, name4, name5, name6,
* I18N, name7, name8, ...]
* ```
*
* Note that this function will fully ignore all synthetic (@foo) attribute values
* because those values are intended to always be generated as property instructions.
*/
getAttributeExpressions(elementName, renderAttributes, inputs, outputs, styles, templateAttrs = [], boundI18nAttrs = []) {
const alreadySeen = new Set();
const attrExprs = [];
let ngProjectAsAttr;
for (const attr of renderAttributes) {
if (attr.name === NG_PROJECT_AS_ATTR_NAME) {
ngProjectAsAttr = attr;
}
// Note that static i18n attributes aren't in the i18n array,
// because they're treated in the same way as regular attributes.
if (attr.i18n) {
// When i18n attributes are present on elements with structural directives
// (e.g. `<div *ngIf title="Hello" i18n-title>`), we want to avoid generating
// duplicate i18n translation blocks for `ɵɵtemplate` and `ɵɵelement` instruction
// attributes. So we do a cache lookup to see if suitable i18n translation block
// already exists.
const { i18nVarRefsCache } = this._constants;
let i18nVarRef;
if (i18nVarRefsCache.has(attr.i18n)) {
i18nVarRef = i18nVarRefsCache.get(attr.i18n);
}
else {
i18nVarRef = this.i18nTranslate(attr.i18n);
i18nVarRefsCache.set(attr.i18n, i18nVarRef);
}
attrExprs.push(literal(attr.name), i18nVarRef);
}
else {
attrExprs.push(...getAttributeNameLiterals(attr.name), trustedConstAttribute(elementName, attr));
}
}
// Keep ngProjectAs next to the other name, value pairs so we can verify that we match
// ngProjectAs marker in the attribute name slot.
if (ngProjectAsAttr) {
attrExprs.push(...getNgProjectAsLiteral(ngProjectAsAttr));
}
function addAttrExpr(key, value) {
if (typeof key === 'string') {
if (!alreadySeen.has(key)) {
attrExprs.push(...getAttributeNameLiterals(key));
value !== undefined && attrExprs.push(value);
alreadySeen.add(key);
}
}
else {
attrExprs.push(literal(key));
}
}
// it's important that this occurs before BINDINGS and TEMPLATE because once `elementStart`
// comes across the BINDINGS or TEMPLATE markers then it will continue reading each value as
// as single property value cell by cell.
if (styles) {
styles.populateInitialStylingAttrs(attrExprs);
}
if (inputs.length || outputs.length) {
const attrsLengthBeforeInputs = attrExprs.length;
for (let i = 0; i < inputs.length; i++) {
const input = inputs[i];
// We don't want the animation and attribute bindings in the
// attributes array since they aren't used for directive matching.
if (input.type !== 4 /* Animation */ && input.type !== 1 /* Attribute */) {
addAttrExpr(input.name);
}
}
for (let i = 0; i < outputs.length; i++) {
const output = outputs[i];
if (output.type !== 1 /* Animation */) {
addAttrExpr(output.name);
}
}
// this is a cheap way of adding the marker only after all the input/output
// values have been filtered (by not including the animation ones) and added
// to the expressions. The marker is important because it tells the runtime
// code that this is where attributes without values start...
if (attrExprs.length !== attrsLengthBeforeInputs) {
attrExprs.splice(attrsLengthBeforeInputs, 0, literal(3 /* Bindings */));
}
}
if (templateAttrs.length) {
attrExprs.push(literal(4 /* Template */));
templateAttrs.forEach(attr => addAttrExpr(attr.name));
}
if (boundI18nAttrs.length) {
attrExprs.push(literal(6 /* I18n */));
boundI18nAttrs.forEach(attr => addAttrExpr(attr.name));
}
return attrExprs;
}
addToConsts(expression) {
if (isNull(expression)) {
return TYPED_NULL_EXPR;
}
const consts = this._constants.constExpressions;
// Try to reuse a literal that's already in the array, if possible.
for (let i = 0; i < consts.length; i++) {
if (consts[i].isEquivalent(expression)) {
return literal(i);
}
}
return literal(consts.push(expression) - 1);
}
addAttrsToConsts(attrs) {
return attrs.length > 0 ? this.addToConsts(literalArr(attrs)) : TYPED_NULL_EXPR;
}
prepareRefsArray(references) {
if (!references || references.length === 0) {
return TYPED_NULL_EXPR;
}
const refsParam = flatten(references.map(reference => {
const slot = this.allocateDataSlot();
// Generate the update temporary.
const variableName = this._bindingScope.freshReferenceName();
const retrievalLevel = this.level;
const lhs = variable(variableName);
this._bindingScope.set(retrievalLevel, reference.name, lhs, 0 /* DEFAULT */, (scope, relativeLevel) => {
// e.g. nextContext(2);
const nextContextStmt = relativeLevel > 0 ? [generateNextContextExpr(relativeLevel).toStmt()] : [];
// e.g. const $foo$ = reference(1);
const refExpr = lhs.set(importExpr(Identifiers$1.reference).callFn([literal(slot)]));
return nextContextStmt.concat(refExpr.toConstDecl());
}, true);
return [reference.name, reference.value];
}));
return asLiteral(refsParam);
}
prepareListenerParameter(tagName, outputAst, index) {
return () => {
const eventName = outputAst.name;
const bindingFnName = outputAst.type === 1 /* Animation */ ?
// synthetic @listener.foo values are treated the exact same as are standard listeners
prepareSyntheticListenerFunctionName(eventName, outputAst.phase) :
sanitizeIdentifier(eventName);
const handlerName = `${this.templateName}_${tagName}_${bindingFnName}_${index}_listener`;
const scope = this._bindingScope.nestedScope(this._bindingScope.bindingLevel, EVENT_BINDING_SCOPE_GLOBALS);
return prepareEventListenerParameters(outputAst, handlerName, scope);
};
}
}
class ValueConverter extends AstMemoryEfficientTransformer {
constructor(constantPool, allocateSlot, allocatePureFunctionSlots, definePipe) {
super();
this.constantPool = constantPool;
this.allocateSlot = allocateSlot;
this.allocatePureFunctionSlots = allocatePureFunctionSlots;
this.definePipe = definePipe;
this._pipeBindExprs = [];
}
// AstMemoryEfficientTransformer
visitPipe(pipe, context) {
// Allocate a slot to create the pipe
const slot = this.allocateSlot();
const slotPseudoLocal = `PIPE:${slot}`;
// Allocate one slot for the result plus one slot per pipe argument
const pureFunctionSlot = this.allocatePureFunctionSlots(2 + pipe.args.length);
const target = new PropertyRead(pipe.span, pipe.sourceSpan, pipe.nameSpan, new ImplicitReceiver(pipe.span, pipe.sourceSpan), slotPseudoLocal);
const { identifier, isVarLength } = pipeBindingCallInfo(pipe.args);
this.definePipe(pipe.name, slotPseudoLocal, slot, importExpr(identifier));
const args = [pipe.exp, ...pipe.args];
const convertedArgs = isVarLength ?
this.visitAll([new LiteralArray(pipe.span, pipe.sourceSpan, args)]) :
this.visitAll(args);
const pipeBindExpr = new FunctionCall(pipe.span, pipe.sourceSpan, target, [
new LiteralPrimitive(pipe.span, pipe.sourceSpan, slot),
new LiteralPrimitive(pipe.span, pipe.sourceSpan, pureFunctionSlot),
...convertedArgs,
]);
this._pipeBindExprs.push(pipeBindExpr);
return pipeBindExpr;
}
updatePipeSlotOffsets(bindingSlots) {
this._pipeBindExprs.forEach((pipe) => {
// update the slot offset arg (index 1) to account for binding slots
const slotOffset = pipe.args[1];
slotOffset.value += bindingSlots;
});
}
visitLiteralArray(array, context) {
return new BuiltinFunctionCall(array.span, array.sourceSpan, this.visitAll(array.expressions), values => {
// If the literal has calculated (non-literal) elements transform it into
// calls to literal factories that compose the literal and will cache intermediate
// values.
const literal = literalArr(values);
return getLiteralFactory(this.constantPool, literal, this.allocatePureFunctionSlots);
});
}
visitLiteralMap(map, context) {
return new BuiltinFunctionCall(map.span, map.sourceSpan, this.visitAll(map.values), values => {
// If the literal has calculated (non-literal) elements transform it into
// calls to literal factories that compose the literal and will cache intermediate
// values.
const literal = literalMap(values.map((value, index) => ({ key: map.keys[index].key, value, quoted: map.keys[index].quoted })));
return getLiteralFactory(this.constantPool, literal, this.allocatePureFunctionSlots);
});
}
}
// Pipes always have at least one parameter, the value they operate on
const pipeBindingIdentifiers = [Identifiers$1.pipeBind1, Identifiers$1.pipeBind2, Identifiers$1.pipeBind3, Identifiers$1.pipeBind4];
function pipeBindingCallInfo(args) {
const identifier = pipeBindingIdentifiers[args.length];
return {
identifier: identifier || Identifiers$1.pipeBindV,
isVarLength: !identifier,
};
}
const pureFunctionIdentifiers = [
Identifiers$1.pureFunction0, Identifiers$1.pureFunction1, Identifiers$1.pureFunction2, Identifiers$1.pureFunction3, Identifiers$1.pureFunction4,
Identifiers$1.pureFunction5, Identifiers$1.pureFunction6, Identifiers$1.pureFunction7, Identifiers$1.pureFunction8
];
function pureFunctionCallInfo(args) {
const identifier = pureFunctionIdentifiers[args.length];
return {
identifier: identifier || Identifiers$1.pureFunctionV,
isVarLength: !identifier,
};
}
function instruction(span, reference, params) {
return importExpr(reference, null, span).callFn(params, span);
}
// e.g. x(2);
function generateNextContextExpr(relativeLevelDiff) {
return importExpr(Identifiers$1.nextContext)
.callFn(relativeLevelDiff > 1 ? [literal(relativeLevelDiff)] : []);
}
function getLiteralFactory(constantPool, literal$1, allocateSlots) {
const { literalFactory, literalFactoryArguments } = constantPool.getLiteralFactory(literal$1);
// Allocate 1 slot for the result plus 1 per argument
const startSlot = allocateSlots(1 + literalFactoryArguments.length);
const { identifier, isVarLength } = pureFunctionCallInfo(literalFactoryArguments);
// Literal factories are pure functions that only need to be re-invoked when the parameters
// change.
const args = [literal(startSlot), literalFactory];
if (isVarLength) {
args.push(literalArr(literalFactoryArguments));
}
else {
args.push(...literalFactoryArguments);
}
return importExpr(identifier).callFn(args);
}
/**
* Gets an array of literals that can be added to an expression
* to represent the name and namespace of an attribute. E.g.
* `:xlink:href` turns into `[AttributeMarker.NamespaceURI, 'xlink', 'href']`.
*
* @param name Name of the attribute, including the namespace.
*/
function getAttributeNameLiterals(name) {
const [attributeNamespace, attributeName] = splitNsName(name);
const nameLiteral = literal(attributeName);
if (attributeNamespace) {
return [
literal(0 /* NamespaceURI */), literal(attributeNamespace), nameLiteral
];
}
return [nameLiteral];
}
/** The prefix used to get a shared context in BindingScope's map. */
const SHARED_CONTEXT_KEY = '$$shared_ctx$$';
class BindingScope {
constructor(bindingLevel = 0, parent = null, globals) {
this.bindingLevel = bindingLevel;
this.parent = parent;
this.globals = globals;
/** Keeps a map from local variables to their BindingData. */
this.map = new Map();
this.referenceNameIndex = 0;
this.restoreViewVariable = null;
if (globals !== undefined) {
for (const name of globals) {
this.set(0, name, variable(name));
}
}
}
static createRootScope() {
return new BindingScope();
}
get(name) {
let current = this;
while (current) {
let value = current.map.get(name);
if (value != null) {
if (current !== this) {
// make a local copy and reset the `declare` state
value = {
retrievalLevel: value.retrievalLevel,
lhs: value.lhs,
declareLocalCallback: value.declareLocalCallback,
declare: false,
priority: value.priority,
localRef: value.localRef
};
// Cache the value locally.
this.map.set(name, value);
// Possibly generate a shared context var
this.maybeGenerateSharedContextVar(value);
this.maybeRestoreView(value.retrievalLevel, value.localRef);
}
if (value.declareLocalCallback && !value.declare) {
value.declare = true;
}
return value.lhs;
}
current = current.parent;
}
// If we get to this point, we are looking for a property on the top level component
// - If level === 0, we are on the top and don't need to re-declare `ctx`.
// - If level > 0, we are in an embedded view. We need to retrieve the name of the
// local var we used to store the component context, e.g. const $comp$ = x();
return this.bindingLevel === 0 ? null : this.getComponentProperty(name);
}
/**
* Create a local variable for later reference.
*
* @param retrievalLevel The level from which this value can be retrieved
* @param name Name of the variable.
* @param lhs AST representing the left hand side of the `let lhs = rhs;`.
* @param priority The sorting priority of this var
* @param declareLocalCallback The callback to invoke when declaring this local var
* @param localRef Whether or not this is a local ref
*/
set(retrievalLevel, name, lhs, priority = 0 /* DEFAULT */, declareLocalCallback, localRef) {
if (this.map.has(name)) {
if (localRef) {
// Do not throw an error if it's a local ref and do not update existing value,
// so the first defined ref is always returned.
return this;
}
error(`The name ${name} is already defined in scope to be ${this.map.get(name)}`);
}
this.map.set(name, {
retrievalLevel: retrievalLevel,
lhs: lhs,
declare: false,
declareLocalCallback: declareLocalCallback,
priority: priority,
localRef: localRef || false
});
return this;
}
// Implemented as part of LocalResolver.
getLocal(name) {
return this.get(name);
}
// Implemented as part of LocalResolver.
notifyImplicitReceiverUse() {
if (this.bindingLevel !== 0) {
// Since the implicit receiver is accessed in an embedded view, we need to
// ensure that we declare a shared context variable for the current template
// in the update variables.
this.map.get(SHARED_CONTEXT_KEY + 0).declare = true;
}
}
nestedScope(level, globals) {
const newScope = new BindingScope(level, this, globals);
if (level > 0)
newScope.generateSharedContextVar(0);
return newScope;
}
/**
* Gets or creates a shared context variable and returns its expression. Note that
* this does not mean that the shared variable will be declared. Variables in the
* binding scope will be only declared if they are used.
*/
getOrCreateSharedContextVar(retrievalLevel) {
const bindingKey = SHARED_CONTEXT_KEY + retrievalLevel;
if (!this.map.has(bindingKey)) {
this.generateSharedContextVar(retrievalLevel);
}
// Shared context variables are always generated as "ReadVarExpr".
return this.map.get(bindingKey).lhs;
}
getSharedContextName(retrievalLevel) {
const sharedCtxObj = this.map.get(SHARED_CONTEXT_KEY + retrievalLevel);
// Shared context variables are always generated as "ReadVarExpr".
return sharedCtxObj && sharedCtxObj.declare ? sharedCtxObj.lhs : null;
}
maybeGenerateSharedContextVar(value) {
if (value.priority === 1 /* CONTEXT */ &&
value.retrievalLevel < this.bindingLevel) {
const sharedCtxObj = this.map.get(SHARED_CONTEXT_KEY + value.retrievalLevel);
if (sharedCtxObj) {
sharedCtxObj.declare = true;
}
else {
this.generateSharedContextVar(value.retrievalLevel);
}
}
}
generateSharedContextVar(retrievalLevel) {
const lhs = variable(CONTEXT_NAME + this.freshReferenceName());
this.map.set(SHARED_CONTEXT_KEY + retrievalLevel, {
retrievalLevel: retrievalLevel,
lhs: lhs,
declareLocalCallback: (scope, relativeLevel) => {
// const ctx_r0 = nextContext(2);
return [lhs.set(generateNextContextExpr(relativeLevel)).toConstDecl()];
},
declare: false,
priority: 2 /* SHARED_CONTEXT */,
localRef: false
});
}
getComponentProperty(name) {
const componentValue = this.map.get(SHARED_CONTEXT_KEY + 0);
componentValue.declare = true;
this.maybeRestoreView(0, false);
return componentValue.lhs.prop(name);
}
maybeRestoreView(retrievalLevel, localRefLookup) {
// We want to restore the current view in listener fns if:
// 1 - we are accessing a value in a parent view, which requires walking the view tree rather
// than using the ctx arg. In this case, the retrieval and binding level will be different.
// 2 - we are looking up a local ref, which requires restoring the view where the local
// ref is stored
if (this.isListenerScope() && (retrievalLevel < this.bindingLevel || localRefLookup)) {
if (!this.parent.restoreViewVariable) {
// parent saves variable to generate a shared `const $s$ = getCurrentView();` instruction
this.parent.restoreViewVariable = variable(this.parent.freshReferenceName());
}
this.restoreViewVariable = this.parent.restoreViewVariable;
}
}
restoreViewStatement() {
// restoreView($state$);
return this.restoreViewVariable ?
[instruction(null, Identifiers$1.restoreView, [this.restoreViewVariable]).toStmt()] :
[];
}
viewSnapshotStatements() {
// const $state$ = getCurrentView();
const getCurrentViewInstruction = instruction(null, Identifiers$1.getCurrentView, []);
return this.restoreViewVariable ?
[this.restoreViewVariable.set(getCurrentViewInstruction).toConstDecl()] :
[];
}
isListenerScope() {
return this.parent && this.parent.bindingLevel === this.bindingLevel;
}
variableDeclarations() {
let currentContextLevel = 0;
return Array.from(this.map.values())
.filter(value => value.declare)
.sort((a, b) => b.retrievalLevel - a.retrievalLevel || b.priority - a.priority)
.reduce((stmts, value) => {
const levelDiff = this.bindingLevel - value.retrievalLevel;
const currStmts = value.declareLocalCallback(this, levelDiff - currentContextLevel);
currentContextLevel = levelDiff;
return stmts.concat(currStmts);
}, []);
}
freshReferenceName() {
let current = this;
// Find the top scope as it maintains the global reference count
while (current.parent)
current = current.parent;
const ref = `${REFERENCE_PREFIX}${current.referenceNameIndex++}`;
return ref;
}
}
/**
* Creates a `CssSelector` given a tag name and a map of attributes
*/
function createCssSelector(elementName, attributes) {
const cssSelector = new CssSelector();
const elementNameNoNs = splitNsName(elementName)[1];
cssSelector.setElement(elementNameNoNs);
Object.getOwnPropertyNames(attributes).forEach((name) => {
const nameNoNs = splitNsName(name)[1];
const value = attributes[name];
cssSelector.addAttribute(nameNoNs, value);
if (name.toLowerCase() === 'class') {
const classes = value.trim().split(/\s+/);
classes.forEach(className => cssSelector.addClassName(className));
}
});
return cssSelector;
}
/**
* Creates an array of expressions out of an `ngProjectAs` attributes
* which can be added to the instruction parameters.
*/
function getNgProjectAsLiteral(attribute) {
// Parse the attribute value into a CssSelectorList. Note that we only take the
// first selector, because we don't support multiple selectors in ngProjectAs.
const parsedR3Selector = parseSelectorToR3Selector(attribute.value)[0];
return [literal(5 /* ProjectAs */), asLiteral(parsedR3Selector)];
}
/**
* Gets the instruction to generate for an interpolated property
* @param interpolation An Interpolation AST
*/
function getPropertyInterpolationExpression(interpolation) {
switch (getInterpolationArgsLength(interpolation)) {
case 1:
return Identifiers$1.propertyInterpolate;
case 3:
return Identifiers$1.propertyInterpolate1;
case 5:
return Identifiers$1.propertyInterpolate2;
case 7:
return Identifiers$1.propertyInterpolate3;
case 9:
return Identifiers$1.propertyInterpolate4;
case 11:
return Identifiers$1.propertyInterpolate5;
case 13:
return Identifiers$1.propertyInterpolate6;
case 15:
return Identifiers$1.propertyInterpolate7;
case 17:
return Identifiers$1.propertyInterpolate8;
default:
return Identifiers$1.propertyInterpolateV;
}
}
/**
* Gets the instruction to generate for an interpolated attribute
* @param interpolation An Interpolation AST
*/
function getAttributeInterpolationExpression(interpolation) {
switch (getInterpolationArgsLength(interpolation)) {
case 3:
return Identifiers$1.attributeInterpolate1;
case 5:
return Identifiers$1.attributeInterpolate2;
case 7:
return Identifiers$1.attributeInterpolate3;
case 9:
return Identifiers$1.attributeInterpolate4;
case 11:
return Identifiers$1.attributeInterpolate5;
case 13:
return Identifiers$1.attributeInterpolate6;
case 15:
return Identifiers$1.attributeInterpolate7;
case 17:
return Identifiers$1.attributeInterpolate8;
default:
return Identifiers$1.attributeInterpolateV;
}
}
/**
* Gets the instruction to generate for interpolated text.
* @param interpolation An Interpolation AST
*/
function getTextInterpolationExpression(interpolation) {
switch (getInterpolationArgsLength(interpolation)) {
case 1:
return Identifiers$1.textInterpolate;
case 3:
return Identifiers$1.textInterpolate1;
case 5:
return Identifiers$1.textInterpolate2;
case 7:
return Identifiers$1.textInterpolate3;
case 9:
return Identifiers$1.textInterpolate4;
case 11:
return Identifiers$1.textInterpolate5;
case 13:
return Identifiers$1.textInterpolate6;
case 15:
return Identifiers$1.textInterpolate7;
case 17:
return Identifiers$1.textInterpolate8;
default:
return Identifiers$1.textInterpolateV;
}
}
/**
* Parse a template into render3 `Node`s and additional metadata, with no other dependencies.
*
* @param template text of the template to parse
* @param templateUrl URL to use for source mapping of the parsed template
* @param options options to modify how the template is parsed
*/
function parseTemplate(template, templateUrl, options = {}) {
var _a;
const { interpolationConfig, preserveWhitespaces, enableI18nLegacyMessageIdFormat } = options;
const isInline = (_a = options.isInline) !== null && _a !== void 0 ? _a : false;
const bindingParser = makeBindingParser(interpolationConfig);
const htmlParser = new HtmlParser();
const parseResult = htmlParser.parse(template, templateUrl, Object.assign(Object.assign({ leadingTriviaChars: LEADING_TRIVIA_CHARS }, options), { tokenizeExpansionForms: true }));
if (!options.alwaysAttemptHtmlToR3AstConversion && parseResult.errors &&
parseResult.errors.length > 0) {
const parsedTemplate = {
interpolationConfig,
preserveWhitespaces,
template,
templateUrl,
isInline,
errors: parseResult.errors,
nodes: [],
styleUrls: [],
styles: [],
ngContentSelectors: []
};
if (options.collectCommentNodes) {
parsedTemplate.commentNodes = [];
}
return parsedTemplate;
}
let rootNodes = parseResult.rootNodes;
// process i18n meta information (scan attributes, generate ids)
// before we run whitespace removal process, because existing i18n
// extraction process (ng extract-i18n) relies on a raw content to generate
// message ids
const i18nMetaVisitor = new I18nMetaVisitor(interpolationConfig, /* keepI18nAttrs */ !preserveWhitespaces, enableI18nLegacyMessageIdFormat);
const i18nMetaResult = i18nMetaVisitor.visitAllWithErrors(rootNodes);
if (!options.alwaysAttemptHtmlToR3AstConversion && i18nMetaResult.errors &&
i18nMetaResult.errors.length > 0) {
const parsedTemplate = {
interpolationConfig,
preserveWhitespaces,
template,
templateUrl,
isInline,
errors: i18nMetaResult.errors,
nodes: [],
styleUrls: [],
styles: [],
ngContentSelectors: []
};
if (options.collectCommentNodes) {
parsedTemplate.commentNodes = [];
}
return parsedTemplate;
}
rootNodes = i18nMetaResult.rootNodes;
if (!preserveWhitespaces) {
rootNodes = visitAll$1(new WhitespaceVisitor(), rootNodes);
// run i18n meta visitor again in case whitespaces are removed (because that might affect
// generated i18n message content) and first pass indicated that i18n content is present in a
// template. During this pass i18n IDs generated at the first pass will be preserved, so we can
// mimic existing extraction process (ng extract-i18n)
if (i18nMetaVisitor.hasI18nMeta) {
rootNodes = visitAll$1(new I18nMetaVisitor(interpolationConfig, /* keepI18nAttrs */ false), rootNodes);
}
}
const { nodes, errors, styleUrls, styles, ngContentSelectors, commentNodes } = htmlAstToRender3Ast(rootNodes, bindingParser, { collectCommentNodes: !!options.collectCommentNodes });
errors.push(...parseResult.errors, ...i18nMetaResult.errors);
const parsedTemplate = {
interpolationConfig,
preserveWhitespaces,
errors: errors.length > 0 ? errors : null,
template,
templateUrl,
isInline,
nodes,
styleUrls,
styles,
ngContentSelectors
};
if (options.collectCommentNodes) {
parsedTemplate.commentNodes = commentNodes;
}
return parsedTemplate;
}
const elementRegistry = new DomElementSchemaRegistry();
/**
* Construct a `BindingParser` with a default configuration.
*/
function makeBindingParser(interpolationConfig = DEFAULT_INTERPOLATION_CONFIG) {
return new BindingParser(new IvyParser(new Lexer()), interpolationConfig, elementRegistry, null, []);
}
function resolveSanitizationFn(context, isAttribute) {
switch (context) {
case SecurityContext.HTML:
return importExpr(Identifiers$1.sanitizeHtml);
case SecurityContext.SCRIPT:
return importExpr(Identifiers$1.sanitizeScript);
case SecurityContext.STYLE:
// the compiler does not fill in an instruction for [style.prop?] binding
// values because the style algorithm knows internally what props are subject
// to sanitization (only [attr.style] values are explicitly sanitized)
return isAttribute ? importExpr(Identifiers$1.sanitizeStyle) : null;
case SecurityContext.URL:
return importExpr(Identifiers$1.sanitizeUrl);
case SecurityContext.RESOURCE_URL:
return importExpr(Identifiers$1.sanitizeResourceUrl);
default:
return null;
}
}
function trustedConstAttribute(tagName, attr) {
const value = asLiteral(attr.value);
if (isTrustedTypesSink(tagName, attr.name)) {
switch (elementRegistry.securityContext(tagName, attr.name, /* isAttribute */ true)) {
case SecurityContext.HTML:
return taggedTemplate(importExpr(Identifiers$1.trustConstantHtml), new TemplateLiteral([new TemplateLiteralElement(attr.value)], []), undefined, attr.valueSpan);
// NB: no SecurityContext.SCRIPT here, as the corresponding tags are stripped by the compiler.
case SecurityContext.RESOURCE_URL:
return taggedTemplate(importExpr(Identifiers$1.trustConstantResourceUrl), new TemplateLiteral([new TemplateLiteralElement(attr.value)], []), undefined, attr.valueSpan);
default:
return value;
}
}
else {
return value;
}
}
function isSingleElementTemplate(children) {
return children.length === 1 && children[0] instanceof Element;
}
function isTextNode(node) {
return node instanceof Text || node instanceof BoundText || node instanceof Icu;
}
function hasTextChildrenOnly(children) {
return children.every(isTextNode);
}
/** Name of the global variable that is used to determine if we use Closure translations or not */
const NG_I18N_CLOSURE_MODE = 'ngI18nClosureMode';
/**
* Generate statements that define a given translation message.
*
* ```
* var I18N_1;
* if (typeof ngI18nClosureMode !== undefined && ngI18nClosureMode) {
* var MSG_EXTERNAL_XXX = goog.getMsg(
* "Some message with {$interpolation}!",
* { "interpolation": "\uFFFD0\uFFFD" }
* );
* I18N_1 = MSG_EXTERNAL_XXX;
* }
* else {
* I18N_1 = $localize`Some message with ${'\uFFFD0\uFFFD'}!`;
* }
* ```
*
* @param message The original i18n AST message node
* @param variable The variable that will be assigned the translation, e.g. `I18N_1`.
* @param closureVar The variable for Closure `goog.getMsg` calls, e.g. `MSG_EXTERNAL_XXX`.
* @param params Object mapping placeholder names to their values (e.g.
* `{ "interpolation": "\uFFFD0\uFFFD" }`).
* @param transformFn Optional transformation function that will be applied to the translation (e.g.
* post-processing).
* @returns An array of statements that defined a given translation.
*/
function getTranslationDeclStmts(message, variable, closureVar, params = {}, transformFn) {
const statements = [
declareI18nVariable(variable),
ifStmt(createClosureModeGuard(), createGoogleGetMsgStatements(variable, message, closureVar, i18nFormatPlaceholderNames(params, /* useCamelCase */ true)), createLocalizeStatements(variable, message, i18nFormatPlaceholderNames(params, /* useCamelCase */ false))),
];
if (transformFn) {
statements.push(new ExpressionStatement(variable.set(transformFn(variable))));
}
return statements;
}
/**
* Create the expression that will be used to guard the closure mode block
* It is equivalent to:
*
* ```
* typeof ngI18nClosureMode !== undefined && ngI18nClosureMode
* ```
*/
function createClosureModeGuard() {
return typeofExpr(variable(NG_I18N_CLOSURE_MODE))
.notIdentical(literal('undefined', STRING_TYPE))
.and(variable(NG_I18N_CLOSURE_MODE));
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// This regex matches any binding names that contain the "attr." prefix, e.g. "attr.required"
// If there is a match, the first matching group will contain the attribute name to bind.
const ATTR_REGEX = /attr\.([^\]]+)/;
function baseDirectiveFields(meta, constantPool, bindingParser) {
const definitionMap = new DefinitionMap();
const selectors = parseSelectorToR3Selector(meta.selector);
// e.g. `type: MyDirective`
definitionMap.set('type', meta.internalType);
// e.g. `selectors: [['', 'someDir', '']]`
if (selectors.length > 0) {
definitionMap.set('selectors', asLiteral(selectors));
}
if (meta.queries.length > 0) {
// e.g. `contentQueries: (rf, ctx, dirIndex) => { ... }
definitionMap.set('contentQueries', createContentQueriesFunction(meta.queries, constantPool, meta.name));
}
if (meta.viewQueries.length) {
definitionMap.set('viewQuery', createViewQueriesFunction(meta.viewQueries, constantPool, meta.name));
}
// e.g. `hostBindings: (rf, ctx) => { ... }
definitionMap.set('hostBindings', createHostBindingsFunction(meta.host, meta.typeSourceSpan, bindingParser, constantPool, meta.selector || '', meta.name, definitionMap));
// e.g 'inputs: {a: 'a'}`
definitionMap.set('inputs', conditionallyCreateMapObjectLiteral(meta.inputs, true));
// e.g 'outputs: {a: 'a'}`
definitionMap.set('outputs', conditionallyCreateMapObjectLiteral(meta.outputs));
if (meta.exportAs !== null) {
definitionMap.set('exportAs', literalArr(meta.exportAs.map(e => literal(e))));
}
return definitionMap;
}
/**
* Add features to the definition map.
*/
function addFeatures(definitionMap, meta) {
// e.g. `features: [NgOnChangesFeature]`
const features = [];
const providers = meta.providers;
const viewProviders = meta.viewProviders;
if (providers || viewProviders) {
const args = [providers || new LiteralArrayExpr([])];
if (viewProviders) {
args.push(viewProviders);
}
features.push(importExpr(Identifiers$1.ProvidersFeature).callFn(args));
}
if (meta.usesInheritance) {
features.push(importExpr(Identifiers$1.InheritDefinitionFeature));
}
if (meta.fullInheritance) {
features.push(importExpr(Identifiers$1.CopyDefinitionFeature));
}
if (meta.lifecycle.usesOnChanges) {
features.push(importExpr(Identifiers$1.NgOnChangesFeature));
}
if (features.length) {
definitionMap.set('features', literalArr(features));
}
}
/**
* Compile a directive for the render3 runtime as defined by the `R3DirectiveMetadata`.
*/
function compileDirectiveFromMetadata(meta, constantPool, bindingParser) {
const definitionMap = baseDirectiveFields(meta, constantPool, bindingParser);
addFeatures(definitionMap, meta);
const expression = importExpr(Identifiers$1.defineDirective).callFn([definitionMap.toLiteralMap()]);
const type = createDirectiveType(meta);
return { expression, type };
}
/**
* Compile a component for the render3 runtime as defined by the `R3ComponentMetadata`.
*/
function compileComponentFromMetadata(meta, constantPool, bindingParser) {
const definitionMap = baseDirectiveFields(meta, constantPool, bindingParser);
addFeatures(definitionMap, meta);
const selector = meta.selector && CssSelector.parse(meta.selector);
const firstSelector = selector && selector[0];
// e.g. `attr: ["class", ".my.app"]`
// This is optional an only included if the first selector of a component specifies attributes.
if (firstSelector) {
const selectorAttributes = firstSelector.getAttrs();
if (selectorAttributes.length) {
definitionMap.set('attrs', constantPool.getConstLiteral(literalArr(selectorAttributes.map(value => value != null ? literal(value) : literal(undefined))),
/* forceShared */ true));
}
}
// Generate the CSS matcher that recognize directive
let directiveMatcher = null;
if (meta.directives.length > 0) {
const matcher = new SelectorMatcher();
for (const { selector, type } of meta.directives) {
matcher.addSelectables(CssSelector.parse(selector), type);
}
directiveMatcher = matcher;
}
// e.g. `template: function MyComponent_Template(_ctx, _cm) {...}`
const templateTypeName = meta.name;
const templateName = templateTypeName ? `${templateTypeName}_Template` : null;
const directivesUsed = new Set();
const pipesUsed = new Set();
const changeDetection = meta.changeDetection;
const template = meta.template;
const templateBuilder = new TemplateDefinitionBuilder(constantPool, BindingScope.createRootScope(), 0, templateTypeName, null, null, templateName, directiveMatcher, directivesUsed, meta.pipes, pipesUsed, Identifiers$1.namespaceHTML, meta.relativeContextFilePath, meta.i18nUseExternalIds);
const templateFunctionExpression = templateBuilder.buildTemplateFunction(template.nodes, []);
// We need to provide this so that dynamically generated components know what
// projected content blocks to pass through to the component when it is instantiated.
const ngContentSelectors = templateBuilder.getNgContentSelectors();
if (ngContentSelectors) {
definitionMap.set('ngContentSelectors', ngContentSelectors);
}
// e.g. `decls: 2`
definitionMap.set('decls', literal(templateBuilder.getConstCount()));
// e.g. `vars: 2`
definitionMap.set('vars', literal(templateBuilder.getVarCount()));
// Generate `consts` section of ComponentDef:
// - either as an array:
// `consts: [['one', 'two'], ['three', 'four']]`
// - or as a factory function in case additional statements are present (to support i18n):
// `consts: function() { var i18n_0; if (ngI18nClosureMode) {...} else {...} return [i18n_0]; }`
const { constExpressions, prepareStatements } = templateBuilder.getConsts();
if (constExpressions.length > 0) {
let constsExpr = literalArr(constExpressions);
// Prepare statements are present - turn `consts` into a function.
if (prepareStatements.length > 0) {
constsExpr = fn([], [...prepareStatements, new ReturnStatement(constsExpr)]);
}
definitionMap.set('consts', constsExpr);
}
definitionMap.set('template', templateFunctionExpression);
// e.g. `directives: [MyDirective]`
if (directivesUsed.size) {
const directivesList = literalArr(Array.from(directivesUsed));
const directivesExpr = compileDeclarationList(directivesList, meta.declarationListEmitMode);
definitionMap.set('directives', directivesExpr);
}
// e.g. `pipes: [MyPipe]`
if (pipesUsed.size) {
const pipesList = literalArr(Array.from(pipesUsed));
const pipesExpr = compileDeclarationList(pipesList, meta.declarationListEmitMode);
definitionMap.set('pipes', pipesExpr);
}
if (meta.encapsulation === null) {
meta.encapsulation = ViewEncapsulation.Emulated;
}
// e.g. `styles: [str1, str2]`
if (meta.styles && meta.styles.length) {
const styleValues = meta.encapsulation == ViewEncapsulation.Emulated ?
compileStyles(meta.styles, CONTENT_ATTR, HOST_ATTR) :
meta.styles;
const strings = styleValues.map(str => constantPool.getConstLiteral(literal(str)));
definitionMap.set('styles', literalArr(strings));
}
else if (meta.encapsulation === ViewEncapsulation.Emulated) {
// If there is no style, don't generate css selectors on elements
meta.encapsulation = ViewEncapsulation.None;
}
// Only set view encapsulation if it's not the default value
if (meta.encapsulation !== ViewEncapsulation.Emulated) {
definitionMap.set('encapsulation', literal(meta.encapsulation));
}
// e.g. `animation: [trigger('123', [])]`
if (meta.animations !== null) {
definitionMap.set('data', literalMap([{ key: 'animation', value: meta.animations, quoted: false }]));
}
// Only set the change detection flag if it's defined and it's not the default.
if (changeDetection != null && changeDetection !== ChangeDetectionStrategy.Default) {
definitionMap.set('changeDetection', literal(changeDetection));
}
const expression = importExpr(Identifiers$1.defineComponent).callFn([definitionMap.toLiteralMap()]);
const type = createComponentType(meta);
return { expression, type };
}
/**
* Creates the type specification from the component meta. This type is inserted into .d.ts files
* to be consumed by upstream compilations.
*/
function createComponentType(meta) {
const typeParams = createDirectiveTypeParams(meta);
typeParams.push(stringArrayAsType(meta.template.ngContentSelectors));
return expressionType(importExpr(Identifiers$1.ComponentDefWithMeta, typeParams));
}
/**
* Compiles the array literal of declarations into an expression according to the provided emit
* mode.
*/
function compileDeclarationList(list, mode) {
switch (mode) {
case 0 /* Direct */:
// directives: [MyDir],
return list;
case 1 /* Closure */:
// directives: function () { return [MyDir]; }
return fn([], [new ReturnStatement(list)]);
case 2 /* ClosureResolved */:
// directives: function () { return [MyDir].map(ng.resolveForwardRef); }
const resolvedList = list.callMethod('map', [importExpr(Identifiers$1.resolveForwardRef)]);
return fn([], [new ReturnStatement(resolvedList)]);
}
}
function prepareQueryParams(query, constantPool) {
const parameters = [getQueryPredicate(query, constantPool), literal(toQueryFlags(query))];
if (query.read) {
parameters.push(query.read);
}
return parameters;
}
/**
* Translates query flags into `TQueryFlags` type in packages/core/src/render3/interfaces/query.ts
* @param query
*/
function toQueryFlags(query) {
return (query.descendants ? 1 /* descendants */ : 0 /* none */) |
(query.static ? 2 /* isStatic */ : 0 /* none */) |
(query.emitDistinctChangesOnly ? 4 /* emitDistinctChangesOnly */ : 0 /* none */);
}
function convertAttributesToExpressions(attributes) {
const values = [];
for (let key of Object.getOwnPropertyNames(attributes)) {
const value = attributes[key];
values.push(literal(key), value);
}
return values;
}
// Define and update any content queries
function createContentQueriesFunction(queries, constantPool, name) {
const createStatements = [];
const updateStatements = [];
const tempAllocator = temporaryAllocator(updateStatements, TEMPORARY_NAME);
for (const query of queries) {
// creation, e.g. r3.contentQuery(dirIndex, somePredicate, true, null);
createStatements.push(importExpr(Identifiers$1.contentQuery)
.callFn([variable('dirIndex'), ...prepareQueryParams(query, constantPool)])
.toStmt());
// update, e.g. (r3.queryRefresh(tmp = r3.loadQuery()) && (ctx.someDir = tmp));
const temporary = tempAllocator();
const getQueryList = importExpr(Identifiers$1.loadQuery).callFn([]);
const refresh = importExpr(Identifiers$1.queryRefresh).callFn([temporary.set(getQueryList)]);
const updateDirective = variable(CONTEXT_NAME)
.prop(query.propertyName)
.set(query.first ? temporary.prop('first') : temporary);
updateStatements.push(refresh.and(updateDirective).toStmt());
}
const contentQueriesFnName = name ? `${name}_ContentQueries` : null;
return fn([
new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null),
new FnParam('dirIndex', null)
], [
renderFlagCheckIfStmt(1 /* Create */, createStatements),
renderFlagCheckIfStmt(2 /* Update */, updateStatements)
], INFERRED_TYPE, null, contentQueriesFnName);
}
function stringAsType(str) {
return expressionType(literal(str));
}
function stringMapAsType(map) {
const mapValues = Object.keys(map).map(key => {
const value = Array.isArray(map[key]) ? map[key][0] : map[key];
return {
key,
value: literal(value),
quoted: true,
};
});
return expressionType(literalMap(mapValues));
}
function stringArrayAsType(arr) {
return arr.length > 0 ? expressionType(literalArr(arr.map(value => literal(value)))) :
NONE_TYPE;
}
function createDirectiveTypeParams(meta) {
// On the type side, remove newlines from the selector as it will need to fit into a TypeScript
// string literal, which must be on one line.
const selectorForType = meta.selector !== null ? meta.selector.replace(/\n/g, '') : null;
return [
typeWithParameters(meta.type.type, meta.typeArgumentCount),
selectorForType !== null ? stringAsType(selectorForType) : NONE_TYPE,
meta.exportAs !== null ? stringArrayAsType(meta.exportAs) : NONE_TYPE,
stringMapAsType(meta.inputs),
stringMapAsType(meta.outputs),
stringArrayAsType(meta.queries.map(q => q.propertyName)),
];
}
/**
* Creates the type specification from the directive meta. This type is inserted into .d.ts files
* to be consumed by upstream compilations.
*/
function createDirectiveType(meta) {
const typeParams = createDirectiveTypeParams(meta);
return expressionType(importExpr(Identifiers$1.DirectiveDefWithMeta, typeParams));
}
// Define and update any view queries
function createViewQueriesFunction(viewQueries, constantPool, name) {
const createStatements = [];
const updateStatements = [];
const tempAllocator = temporaryAllocator(updateStatements, TEMPORARY_NAME);
viewQueries.forEach((query) => {
// creation, e.g. r3.viewQuery(somePredicate, true);
const queryDefinition = importExpr(Identifiers$1.viewQuery).callFn(prepareQueryParams(query, constantPool));
createStatements.push(queryDefinition.toStmt());
// update, e.g. (r3.queryRefresh(tmp = r3.loadQuery()) && (ctx.someDir = tmp));
const temporary = tempAllocator();
const getQueryList = importExpr(Identifiers$1.loadQuery).callFn([]);
const refresh = importExpr(Identifiers$1.queryRefresh).callFn([temporary.set(getQueryList)]);
const updateDirective = variable(CONTEXT_NAME)
.prop(query.propertyName)
.set(query.first ? temporary.prop('first') : temporary);
updateStatements.push(refresh.and(updateDirective).toStmt());
});
const viewQueryFnName = name ? `${name}_Query` : null;
return fn([new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], [
renderFlagCheckIfStmt(1 /* Create */, createStatements),
renderFlagCheckIfStmt(2 /* Update */, updateStatements)
], INFERRED_TYPE, null, viewQueryFnName);
}
// Return a host binding function or null if one is not necessary.
function createHostBindingsFunction(hostBindingsMetadata, typeSourceSpan, bindingParser, constantPool, selector, name, definitionMap) {
const bindingContext = variable(CONTEXT_NAME);
const styleBuilder = new StylingBuilder(bindingContext);
const { styleAttr, classAttr } = hostBindingsMetadata.specialAttributes;
if (styleAttr !== undefined) {
styleBuilder.registerStyleAttr(styleAttr);
}
if (classAttr !== undefined) {
styleBuilder.registerClassAttr(classAttr);
}
const createStatements = [];
const updateStatements = [];
const hostBindingSourceSpan = typeSourceSpan;
const directiveSummary = metadataAsSummary(hostBindingsMetadata);
// Calculate host event bindings
const eventBindings = bindingParser.createDirectiveHostEventAsts(directiveSummary, hostBindingSourceSpan);
if (eventBindings && eventBindings.length) {
const listeners = createHostListeners(eventBindings, name);
createStatements.push(...listeners);
}
// Calculate the host property bindings
const bindings = bindingParser.createBoundHostProperties(directiveSummary, hostBindingSourceSpan);
const allOtherBindings = [];
// We need to calculate the total amount of binding slots required by
// all the instructions together before any value conversions happen.
// Value conversions may require additional slots for interpolation and
// bindings with pipes. These calculates happen after this block.
let totalHostVarsCount = 0;
bindings && bindings.forEach((binding) => {
const stylingInputWasSet = styleBuilder.registerInputBasedOnName(binding.name, binding.expression, hostBindingSourceSpan);
if (stylingInputWasSet) {
totalHostVarsCount += MIN_STYLING_BINDING_SLOTS_REQUIRED;
}
else {
allOtherBindings.push(binding);
totalHostVarsCount++;
}
});
let valueConverter;
const getValueConverter = () => {
if (!valueConverter) {
const hostVarsCountFn = (numSlots) => {
const originalVarsCount = totalHostVarsCount;
totalHostVarsCount += numSlots;
return originalVarsCount;
};
valueConverter = new ValueConverter(constantPool, () => error('Unexpected node'), // new nodes are illegal here
hostVarsCountFn, () => error('Unexpected pipe')); // pipes are illegal here
}
return valueConverter;
};
const propertyBindings = [];
const attributeBindings = [];
const syntheticHostBindings = [];
allOtherBindings.forEach((binding) => {
// resolve literal arrays and literal objects
const value = binding.expression.visit(getValueConverter());
const bindingExpr = bindingFn(bindingContext, value);
const { bindingName, instruction, isAttribute } = getBindingNameAndInstruction(binding);
const securityContexts = bindingParser.calcPossibleSecurityContexts(selector, bindingName, isAttribute)
.filter(context => context !== SecurityContext.NONE);
let sanitizerFn = null;
if (securityContexts.length) {
if (securityContexts.length === 2 &&
securityContexts.indexOf(SecurityContext.URL) > -1 &&
securityContexts.indexOf(SecurityContext.RESOURCE_URL) > -1) {
// Special case for some URL attributes (such as "src" and "href") that may be a part
// of different security contexts. In this case we use special santitization function and
// select the actual sanitizer at runtime based on a tag name that is provided while
// invoking sanitization function.
sanitizerFn = importExpr(Identifiers$1.sanitizeUrlOrResourceUrl);
}
else {
sanitizerFn = resolveSanitizationFn(securityContexts[0], isAttribute);
}
}
const instructionParams = [literal(bindingName), bindingExpr.currValExpr];
if (sanitizerFn) {
instructionParams.push(sanitizerFn);
}
updateStatements.push(...bindingExpr.stmts);
if (instruction === Identifiers$1.hostProperty) {
propertyBindings.push(instructionParams);
}
else if (instruction === Identifiers$1.attribute) {
attributeBindings.push(instructionParams);
}
else if (instruction === Identifiers$1.syntheticHostProperty) {
syntheticHostBindings.push(instructionParams);
}
else {
updateStatements.push(importExpr(instruction).callFn(instructionParams).toStmt());
}
});
if (propertyBindings.length > 0) {
updateStatements.push(chainedInstruction(Identifiers$1.hostProperty, propertyBindings).toStmt());
}
if (attributeBindings.length > 0) {
updateStatements.push(chainedInstruction(Identifiers$1.attribute, attributeBindings).toStmt());
}
if (syntheticHostBindings.length > 0) {
updateStatements.push(chainedInstruction(Identifiers$1.syntheticHostProperty, syntheticHostBindings).toStmt());
}
// since we're dealing with directives/components and both have hostBinding
// functions, we need to generate a special hostAttrs instruction that deals
// with both the assignment of styling as well as static attributes to the host
// element. The instruction below will instruct all initial styling (styling
// that is inside of a host binding within a directive/component) to be attached
// to the host element alongside any of the provided host attributes that were
// collected earlier.
const hostAttrs = convertAttributesToExpressions(hostBindingsMetadata.attributes);
styleBuilder.assignHostAttrs(hostAttrs, definitionMap);
if (styleBuilder.hasBindings) {
// finally each binding that was registered in the statement above will need to be added to
// the update block of a component/directive templateFn/hostBindingsFn so that the bindings
// are evaluated and updated for the element.
styleBuilder.buildUpdateLevelInstructions(getValueConverter()).forEach(instruction => {
if (instruction.calls.length > 0) {
const calls = [];
instruction.calls.forEach(call => {
// we subtract a value of `1` here because the binding slot was already allocated
// at the top of this method when all the input bindings were counted.
totalHostVarsCount +=
Math.max(call.allocateBindingSlots - MIN_STYLING_BINDING_SLOTS_REQUIRED, 0);
calls.push(convertStylingCall(call, bindingContext, bindingFn));
});
updateStatements.push(chainedInstruction(instruction.reference, calls).toStmt());
}
});
}
if (totalHostVarsCount) {
definitionMap.set('hostVars', literal(totalHostVarsCount));
}
if (createStatements.length > 0 || updateStatements.length > 0) {
const hostBindingsFnName = name ? `${name}_HostBindings` : null;
const statements = [];
if (createStatements.length > 0) {
statements.push(renderFlagCheckIfStmt(1 /* Create */, createStatements));
}
if (updateStatements.length > 0) {
statements.push(renderFlagCheckIfStmt(2 /* Update */, updateStatements));
}
return fn([new FnParam(RENDER_FLAGS, NUMBER_TYPE), new FnParam(CONTEXT_NAME, null)], statements, INFERRED_TYPE, null, hostBindingsFnName);
}
return null;
}
function bindingFn(implicit, value) {
return convertPropertyBinding(null, implicit, value, 'b', BindingForm.Expression, () => error('Unexpected interpolation'));
}
function convertStylingCall(call, bindingContext, bindingFn) {
return call.params(value => bindingFn(bindingContext, value).currValExpr);
}
function getBindingNameAndInstruction(binding) {
let bindingName = binding.name;
let instruction;
// Check to see if this is an attr binding or a property binding
const attrMatches = bindingName.match(ATTR_REGEX);
if (attrMatches) {
bindingName = attrMatches[1];
instruction = Identifiers$1.attribute;
}
else {
if (binding.isAnimation) {
bindingName = prepareSyntheticPropertyName(bindingName);
// host bindings that have a synthetic property (e.g. @foo) should always be rendered
// in the context of the component and not the parent. Therefore there is a special
// compatibility instruction available for this purpose.
instruction = Identifiers$1.syntheticHostProperty;
}
else {
instruction = Identifiers$1.hostProperty;
}
}
return { bindingName, instruction, isAttribute: !!attrMatches };
}
function createHostListeners(eventBindings, name) {
const listeners = [];
const syntheticListeners = [];
const instructions = [];
eventBindings.forEach(binding => {
let bindingName = binding.name && sanitizeIdentifier(binding.name);
const bindingFnName = binding.type === 1 /* Animation */ ?
prepareSyntheticListenerFunctionName(bindingName, binding.targetOrPhase) :
bindingName;
const handlerName = name && bindingName ? `${name}_${bindingFnName}_HostBindingHandler` : null;
const params = prepareEventListenerParameters(BoundEvent.fromParsedEvent(binding), handlerName);
if (binding.type == 1 /* Animation */) {
syntheticListeners.push(params);
}
else {
listeners.push(params);
}
});
if (syntheticListeners.length > 0) {
instructions.push(chainedInstruction(Identifiers$1.syntheticHostListener, syntheticListeners).toStmt());
}
if (listeners.length > 0) {
instructions.push(chainedInstruction(Identifiers$1.listener, listeners).toStmt());
}
return instructions;
}
function metadataAsSummary(meta) {
// clang-format off
return {
// This is used by the BindingParser, which only deals with listeners and properties. There's no
// need to pass attributes to it.
hostAttributes: {},
hostListeners: meta.listeners,
hostProperties: meta.properties,
};
// clang-format on
}
const HOST_REG_EXP$1 = /^(?:\[([^\]]+)\])|(?:\(([^\)]+)\))$/;
function parseHostBindings(host) {
const attributes = {};
const listeners = {};
const properties = {};
const specialAttributes = {};
for (const key of Object.keys(host)) {
const value = host[key];
const matches = key.match(HOST_REG_EXP$1);
if (matches === null) {
switch (key) {
case 'class':
if (typeof value !== 'string') {
// TODO(alxhub): make this a diagnostic.
throw new Error(`Class binding must be string`);
}
specialAttributes.classAttr = value;
break;
case 'style':
if (typeof value !== 'string') {
// TODO(alxhub): make this a diagnostic.
throw new Error(`Style binding must be string`);
}
specialAttributes.styleAttr = value;
break;
default:
if (typeof value === 'string') {
attributes[key] = literal(value);
}
else {
attributes[key] = value;
}
}
}
else if (matches[1 /* Binding */] != null) {
if (typeof value !== 'string') {
// TODO(alxhub): make this a diagnostic.
throw new Error(`Property binding must be string`);
}
// synthetic properties (the ones that have a `@` as a prefix)
// are still treated the same as regular properties. Therefore
// there is no point in storing them in a separate map.
properties[matches[1 /* Binding */]] = value;
}
else if (matches[2 /* Event */] != null) {
if (typeof value !== 'string') {
// TODO(alxhub): make this a diagnostic.
throw new Error(`Event binding must be string`);
}
listeners[matches[2 /* Event */]] = value;
}
}
return { attributes, listeners, properties, specialAttributes };
}
/**
* Verifies host bindings and returns the list of errors (if any). Empty array indicates that a
* given set of host bindings has no errors.
*
* @param bindings set of host bindings to verify.
* @param sourceSpan source span where host bindings were defined.
* @returns array of errors associated with a given set of host bindings.
*/
function verifyHostBindings(bindings, sourceSpan) {
const summary = metadataAsSummary(bindings);
// TODO: abstract out host bindings verification logic and use it instead of
// creating events and properties ASTs to detect errors (FW-996)
const bindingParser = makeBindingParser();
bindingParser.createDirectiveHostEventAsts(summary, sourceSpan);
bindingParser.createBoundHostProperties(summary, sourceSpan);
return bindingParser.errors;
}
function compileStyles(styles, selector, hostSelector) {
const shadowCss = new ShadowCss();
return styles.map(style => {
return shadowCss.shimCssText(style, selector, hostSelector);
});
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* An interface for retrieving documents by URL that the compiler uses
* to load templates.
*/
class ResourceLoader {
get(url) {
return '';
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class CompilerFacadeImpl {
constructor(jitEvaluator = new JitEvaluator()) {
this.jitEvaluator = jitEvaluator;
this.R3ResolvedDependencyType = R3ResolvedDependencyType;
this.R3FactoryTarget = R3FactoryTarget;
this.ResourceLoader = ResourceLoader;
this.elementSchemaRegistry = new DomElementSchemaRegistry();
}
compilePipe(angularCoreEnv, sourceMapUrl, facade) {
const metadata = {
name: facade.name,
type: wrapReference$1(facade.type),
internalType: new WrappedNodeExpr(facade.type),
typeArgumentCount: facade.typeArgumentCount,
deps: convertR3DependencyMetadataArray(facade.deps),
pipeName: facade.pipeName,
pure: facade.pure,
};
const res = compilePipeFromMetadata(metadata);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
}
compilePipeDeclaration(angularCoreEnv, sourceMapUrl, declaration) {
const meta = convertDeclarePipeFacadeToMetadata(declaration);
const res = compilePipeFromMetadata(meta);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
}
compileInjectable(angularCoreEnv, sourceMapUrl, facade) {
const { expression, statements } = compileInjectable({
name: facade.name,
type: wrapReference$1(facade.type),
internalType: new WrappedNodeExpr(facade.type),
typeArgumentCount: facade.typeArgumentCount,
providedIn: computeProvidedIn(facade.providedIn),
useClass: wrapExpression(facade, USE_CLASS),
useFactory: wrapExpression(facade, USE_FACTORY),
useValue: wrapExpression(facade, USE_VALUE),
useExisting: wrapExpression(facade, USE_EXISTING),
userDeps: convertR3DependencyMetadataArray(facade.userDeps) || undefined,
});
return this.jitExpression(expression, angularCoreEnv, sourceMapUrl, statements);
}
compileInjector(angularCoreEnv, sourceMapUrl, facade) {
const meta = {
name: facade.name,
type: wrapReference$1(facade.type),
internalType: new WrappedNodeExpr(facade.type),
providers: new WrappedNodeExpr(facade.providers),
imports: facade.imports.map(i => new WrappedNodeExpr(i)),
};
const res = compileInjector(meta);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
}
compileNgModule(angularCoreEnv, sourceMapUrl, facade) {
const meta = {
type: wrapReference$1(facade.type),
internalType: new WrappedNodeExpr(facade.type),
adjacentType: new WrappedNodeExpr(facade.type),
bootstrap: facade.bootstrap.map(wrapReference$1),
declarations: facade.declarations.map(wrapReference$1),
imports: facade.imports.map(wrapReference$1),
exports: facade.exports.map(wrapReference$1),
emitInline: true,
containsForwardDecls: false,
schemas: facade.schemas ? facade.schemas.map(wrapReference$1) : null,
id: facade.id ? new WrappedNodeExpr(facade.id) : null,
};
const res = compileNgModule(meta);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, []);
}
compileDirective(angularCoreEnv, sourceMapUrl, facade) {
const meta = convertDirectiveFacadeToMetadata(facade);
return this.compileDirectiveFromMeta(angularCoreEnv, sourceMapUrl, meta);
}
compileDirectiveDeclaration(angularCoreEnv, sourceMapUrl, declaration) {
const typeSourceSpan = this.createParseSourceSpan('Directive', declaration.type.name, sourceMapUrl);
const meta = convertDeclareDirectiveFacadeToMetadata(declaration, typeSourceSpan);
return this.compileDirectiveFromMeta(angularCoreEnv, sourceMapUrl, meta);
}
compileDirectiveFromMeta(angularCoreEnv, sourceMapUrl, meta) {
const constantPool = new ConstantPool();
const bindingParser = makeBindingParser();
const res = compileDirectiveFromMetadata(meta, constantPool, bindingParser);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, constantPool.statements);
}
compileComponent(angularCoreEnv, sourceMapUrl, facade) {
// Parse the template and check for errors.
const { template, interpolation } = parseJitTemplate(facade.template, facade.name, sourceMapUrl, facade.preserveWhitespaces, facade.interpolation);
// Compile the component metadata, including template, into an expression.
const meta = Object.assign(Object.assign(Object.assign({}, facade), convertDirectiveFacadeToMetadata(facade)), { selector: facade.selector || this.elementSchemaRegistry.getDefaultComponentElementName(), template, declarationListEmitMode: 0 /* Direct */, styles: [...facade.styles, ...template.styles], encapsulation: facade.encapsulation, interpolation, changeDetection: facade.changeDetection, animations: facade.animations != null ? new WrappedNodeExpr(facade.animations) : null, viewProviders: facade.viewProviders != null ? new WrappedNodeExpr(facade.viewProviders) :
null, relativeContextFilePath: '', i18nUseExternalIds: true });
const jitExpressionSourceMap = `ng:///${facade.name}.js`;
return this.compileComponentFromMeta(angularCoreEnv, jitExpressionSourceMap, meta);
}
compileComponentDeclaration(angularCoreEnv, sourceMapUrl, declaration) {
const typeSourceSpan = this.createParseSourceSpan('Component', declaration.type.name, sourceMapUrl);
const meta = convertDeclareComponentFacadeToMetadata(declaration, typeSourceSpan, sourceMapUrl);
return this.compileComponentFromMeta(angularCoreEnv, sourceMapUrl, meta);
}
compileComponentFromMeta(angularCoreEnv, sourceMapUrl, meta) {
const constantPool = new ConstantPool();
const bindingParser = makeBindingParser(meta.interpolation);
const res = compileComponentFromMetadata(meta, constantPool, bindingParser);
return this.jitExpression(res.expression, angularCoreEnv, sourceMapUrl, constantPool.statements);
}
compileFactory(angularCoreEnv, sourceMapUrl, meta) {
const factoryRes = compileFactoryFunction({
name: meta.name,
type: wrapReference$1(meta.type),
internalType: new WrappedNodeExpr(meta.type),
typeArgumentCount: meta.typeArgumentCount,
deps: convertR3DependencyMetadataArray(meta.deps),
injectFn: meta.injectFn === 'directiveInject' ? Identifiers.directiveInject :
Identifiers.inject,
target: meta.target,
});
return this.jitExpression(factoryRes.factory, angularCoreEnv, sourceMapUrl, factoryRes.statements);
}
createParseSourceSpan(kind, typeName, sourceUrl) {
return r3JitTypeSourceSpan(kind, typeName, sourceUrl);
}
/**
* JIT compiles an expression and returns the result of executing that expression.
*
* @param def the definition which will be compiled and executed to get the value to patch
* @param context an object map of @angular/core symbol names to symbols which will be available
* in the context of the compiled expression
* @param sourceUrl a URL to use for the source map of the compiled expression
* @param preStatements a collection of statements that should be evaluated before the expression.
*/
jitExpression(def, context, sourceUrl, preStatements) {
// The ConstantPool may contain Statements which declare variables used in the final expression.
// Therefore, its statements need to precede the actual JIT operation. The final statement is a
// declaration of $def which is set to the expression being compiled.
const statements = [
...preStatements,
new DeclareVarStmt('$def', def, undefined, [StmtModifier.Exported]),
];
const res = this.jitEvaluator.evaluateStatements(sourceUrl, statements, new R3JitReflector(context), /* enableSourceMaps */ true);
return res['$def'];
}
}
const USE_CLASS = Object.keys({ useClass: null })[0];
const USE_FACTORY = Object.keys({ useFactory: null })[0];
const USE_VALUE = Object.keys({ useValue: null })[0];
const USE_EXISTING = Object.keys({ useExisting: null })[0];
const wrapReference$1 = function (value) {
const wrapped = new WrappedNodeExpr(value);
return { value: wrapped, type: wrapped };
};
function convertToR3QueryMetadata(facade) {
return Object.assign(Object.assign({}, facade), { predicate: Array.isArray(facade.predicate) ? facade.predicate :
new WrappedNodeExpr(facade.predicate), read: facade.read ? new WrappedNodeExpr(facade.read) : null, static: facade.static, emitDistinctChangesOnly: facade.emitDistinctChangesOnly });
}
function convertQueryDeclarationToMetadata(declaration) {
var _a, _b, _c, _d;
return {
propertyName: declaration.propertyName,
first: (_a = declaration.first) !== null && _a !== void 0 ? _a : false,
predicate: Array.isArray(declaration.predicate) ? declaration.predicate :
new WrappedNodeExpr(declaration.predicate),
descendants: (_b = declaration.descendants) !== null && _b !== void 0 ? _b : false,
read: declaration.read ? new WrappedNodeExpr(declaration.read) : null,
static: (_c = declaration.static) !== null && _c !== void 0 ? _c : false,
emitDistinctChangesOnly: (_d = declaration.emitDistinctChangesOnly) !== null && _d !== void 0 ? _d : true,
};
}
function convertDirectiveFacadeToMetadata(facade) {
const inputsFromMetadata = parseInputOutputs(facade.inputs || []);
const outputsFromMetadata = parseInputOutputs(facade.outputs || []);
const propMetadata = facade.propMetadata;
const inputsFromType = {};
const outputsFromType = {};
for (const field in propMetadata) {
if (propMetadata.hasOwnProperty(field)) {
propMetadata[field].forEach(ann => {
if (isInput(ann)) {
inputsFromType[field] =
ann.bindingPropertyName ? [ann.bindingPropertyName, field] : field;
}
else if (isOutput(ann)) {
outputsFromType[field] = ann.bindingPropertyName || field;
}
});
}
}
return Object.assign(Object.assign({}, facade), { typeSourceSpan: facade.typeSourceSpan, type: wrapReference$1(facade.type), internalType: new WrappedNodeExpr(facade.type), deps: convertR3DependencyMetadataArray(facade.deps), host: extractHostBindings(facade.propMetadata, facade.typeSourceSpan, facade.host), inputs: Object.assign(Object.assign({}, inputsFromMetadata), inputsFromType), outputs: Object.assign(Object.assign({}, outputsFromMetadata), outputsFromType), queries: facade.queries.map(convertToR3QueryMetadata), providers: facade.providers != null ? new WrappedNodeExpr(facade.providers) : null, viewQueries: facade.viewQueries.map(convertToR3QueryMetadata), fullInheritance: false });
}
function convertDeclareDirectiveFacadeToMetadata(declaration, typeSourceSpan) {
var _a, _b, _c, _d, _e, _f, _g, _h;
return {
name: declaration.type.name,
type: wrapReference$1(declaration.type),
typeSourceSpan,
internalType: new WrappedNodeExpr(declaration.type),
selector: (_a = declaration.selector) !== null && _a !== void 0 ? _a : null,
inputs: (_b = declaration.inputs) !== null && _b !== void 0 ? _b : {},
outputs: (_c = declaration.outputs) !== null && _c !== void 0 ? _c : {},
host: convertHostDeclarationToMetadata(declaration.host),
queries: ((_d = declaration.queries) !== null && _d !== void 0 ? _d : []).map(convertQueryDeclarationToMetadata),
viewQueries: ((_e = declaration.viewQueries) !== null && _e !== void 0 ? _e : []).map(convertQueryDeclarationToMetadata),
providers: declaration.providers !== undefined ? new WrappedNodeExpr(declaration.providers) :
null,
exportAs: (_f = declaration.exportAs) !== null && _f !== void 0 ? _f : null,
usesInheritance: (_g = declaration.usesInheritance) !== null && _g !== void 0 ? _g : false,
lifecycle: { usesOnChanges: (_h = declaration.usesOnChanges) !== null && _h !== void 0 ? _h : false },
deps: null,
typeArgumentCount: 0,
fullInheritance: false,
};
}
function convertHostDeclarationToMetadata(host = {}) {
var _a, _b, _c;
return {
attributes: convertOpaqueValuesToExpressions((_a = host.attributes) !== null && _a !== void 0 ? _a : {}),
listeners: (_b = host.listeners) !== null && _b !== void 0 ? _b : {},
properties: (_c = host.properties) !== null && _c !== void 0 ? _c : {},
specialAttributes: {
classAttr: host.classAttribute,
styleAttr: host.styleAttribute,
},
};
}
function convertOpaqueValuesToExpressions(obj) {
const result = {};
for (const key of Object.keys(obj)) {
result[key] = new WrappedNodeExpr(obj[key]);
}
return result;
}
function convertDeclareComponentFacadeToMetadata(declaration, typeSourceSpan, sourceMapUrl) {
var _a, _b, _c, _d, _e;
const { template, interpolation } = parseJitTemplate(declaration.template, declaration.type.name, sourceMapUrl, (_a = declaration.preserveWhitespaces) !== null && _a !== void 0 ? _a : false, declaration.interpolation);
return Object.assign(Object.assign({}, convertDeclareDirectiveFacadeToMetadata(declaration, typeSourceSpan)), { template, styles: (_b = declaration.styles) !== null && _b !== void 0 ? _b : [], directives: ((_c = declaration.directives) !== null && _c !== void 0 ? _c : []).map(convertUsedDirectiveDeclarationToMetadata), pipes: convertUsedPipesToMetadata(declaration.pipes), viewProviders: declaration.viewProviders !== undefined ?
new WrappedNodeExpr(declaration.viewProviders) :
null, animations: declaration.animations !== undefined ? new WrappedNodeExpr(declaration.animations) :
null, changeDetection: (_d = declaration.changeDetection) !== null && _d !== void 0 ? _d : ChangeDetectionStrategy.Default, encapsulation: (_e = declaration.encapsulation) !== null && _e !== void 0 ? _e : ViewEncapsulation.Emulated, interpolation, declarationListEmitMode: 2 /* ClosureResolved */, relativeContextFilePath: '', i18nUseExternalIds: true });
}
function convertUsedDirectiveDeclarationToMetadata(declaration) {
var _a, _b, _c;
return {
selector: declaration.selector,
type: new WrappedNodeExpr(declaration.type),
inputs: (_a = declaration.inputs) !== null && _a !== void 0 ? _a : [],
outputs: (_b = declaration.outputs) !== null && _b !== void 0 ? _b : [],
exportAs: (_c = declaration.exportAs) !== null && _c !== void 0 ? _c : null,
};
}
function convertUsedPipesToMetadata(declaredPipes) {
const pipes = new Map();
if (declaredPipes === undefined) {
return pipes;
}
for (const pipeName of Object.keys(declaredPipes)) {
const pipeType = declaredPipes[pipeName];
pipes.set(pipeName, new WrappedNodeExpr(pipeType));
}
return pipes;
}
function parseJitTemplate(template, typeName, sourceMapUrl, preserveWhitespaces, interpolation) {
const interpolationConfig = interpolation ? InterpolationConfig.fromArray(interpolation) : DEFAULT_INTERPOLATION_CONFIG;
// Parse the template and check for errors.
const parsed = parseTemplate(template, sourceMapUrl, { preserveWhitespaces: preserveWhitespaces, interpolationConfig });
if (parsed.errors !== null) {
const errors = parsed.errors.map(err => err.toString()).join(', ');
throw new Error(`Errors during JIT compilation of template for ${typeName}: ${errors}`);
}
return { template: parsed, interpolation: interpolationConfig };
}
function wrapExpression(obj, property) {
if (obj.hasOwnProperty(property)) {
return new WrappedNodeExpr(obj[property]);
}
else {
return undefined;
}
}
function computeProvidedIn(providedIn) {
if (providedIn == null || typeof providedIn === 'string') {
return new LiteralExpr(providedIn);
}
else {
return new WrappedNodeExpr(providedIn);
}
}
function convertR3DependencyMetadata(facade) {
let tokenExpr;
if (facade.token === null) {
tokenExpr = new LiteralExpr(null);
}
else if (facade.resolved === R3ResolvedDependencyType.Attribute) {
tokenExpr = new LiteralExpr(facade.token);
}
else {
tokenExpr = new WrappedNodeExpr(facade.token);
}
return {
token: tokenExpr,
attribute: null,
resolved: facade.resolved,
host: facade.host,
optional: facade.optional,
self: facade.self,
skipSelf: facade.skipSelf,
};
}
function convertR3DependencyMetadataArray(facades) {
return facades == null ? null : facades.map(convertR3DependencyMetadata);
}
function extractHostBindings(propMetadata, sourceSpan, host) {
// First parse the declarations from the metadata.
const bindings = parseHostBindings(host || {});
// After that check host bindings for errors
const errors = verifyHostBindings(bindings, sourceSpan);
if (errors.length) {
throw new Error(errors.map((error) => error.msg).join('\n'));
}
// Next, loop over the properties of the object, looking for @HostBinding and @HostListener.
for (const field in propMetadata) {
if (propMetadata.hasOwnProperty(field)) {
propMetadata[field].forEach(ann => {
if (isHostBinding(ann)) {
// Since this is a decorator, we know that the value is a class member. Always access it
// through `this` so that further down the line it can't be confused for a literal value
// (e.g. if there's a property called `true`).
bindings.properties[ann.hostPropertyName || field] =
getSafePropertyAccessString('this', field);
}
else if (isHostListener(ann)) {
bindings.listeners[ann.eventName || field] = `${field}(${(ann.args || []).join(',')})`;
}
});
}
}
return bindings;
}
function isHostBinding(value) {
return value.ngMetadataName === 'HostBinding';
}
function isHostListener(value) {
return value.ngMetadataName === 'HostListener';
}
function isInput(value) {
return value.ngMetadataName === 'Input';
}
function isOutput(value) {
return value.ngMetadataName === 'Output';
}
function parseInputOutputs(values) {
return values.reduce((map, value) => {
const [field, property] = value.split(',').map(piece => piece.trim());
map[field] = property || field;
return map;
}, {});
}
function convertDeclarePipeFacadeToMetadata(declaration) {
var _a;
return {
name: declaration.type.name,
type: wrapReference$1(declaration.type),
internalType: new WrappedNodeExpr(declaration.type),
typeArgumentCount: 0,
pipeName: declaration.name,
deps: null,
pure: (_a = declaration.pure) !== null && _a !== void 0 ? _a : true,
};
}
function publishFacade(global) {
const ng = global.ng || (global.ng = {});
ngcompilerFacade = new CompilerFacadeImpl();
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const VERSION$1 = new Version('11.2.14');
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class CompilerConfig {
constructor({ defaultEncapsulation = ViewEncapsulation.Emulated, useJit = true, jitDevMode = false, missingTranslation = null, preserveWhitespaces, strictInjectionParameters } = {}) {
this.defaultEncapsulation = defaultEncapsulation;
this.useJit = !!useJit;
this.jitDevMode = !!jitDevMode;
this.missingTranslation = missingTranslation;
this.preserveWhitespaces = preserveWhitespacesDefault(noUndefined(preserveWhitespaces));
this.strictInjectionParameters = strictInjectionParameters === true;
}
}
function preserveWhitespacesDefault(preserveWhitespacesOption, defaultSetting = false) {
return preserveWhitespacesOption === null ? defaultSetting : preserveWhitespacesOption;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class DirectiveNormalizer {
constructor(_resourceLoader, _urlResolver, _htmlParser, _config) {
this._resourceLoader = _resourceLoader;
this._urlResolver = _urlResolver;
this._htmlParser = _htmlParser;
this._config = _config;
this._resourceLoaderCache = new Map();
}
clearCache() {
this._resourceLoaderCache.clear();
}
clearCacheFor(normalizedDirective) {
if (!normalizedDirective.isComponent) {
return;
}
const template = normalizedDirective.template;
this._resourceLoaderCache.delete(template.templateUrl);
template.externalStylesheets.forEach((stylesheet) => {
this._resourceLoaderCache.delete(stylesheet.moduleUrl);
});
}
_fetch(url) {
let result = this._resourceLoaderCache.get(url);
if (!result) {
result = this._resourceLoader.get(url);
this._resourceLoaderCache.set(url, result);
}
return result;
}
normalizeTemplate(prenormData) {
if (isDefined(prenormData.template)) {
if (isDefined(prenormData.templateUrl)) {
throw syntaxError(`'${stringify(prenormData
.componentType)}' component cannot define both template and templateUrl`);
}
if (typeof prenormData.template !== 'string') {
throw syntaxError(`The template specified for component ${stringify(prenormData.componentType)} is not a string`);
}
}
else if (isDefined(prenormData.templateUrl)) {
if (typeof prenormData.templateUrl !== 'string') {
throw syntaxError(`The templateUrl specified for component ${stringify(prenormData.componentType)} is not a string`);
}
}
else {
throw syntaxError(`No template specified for component ${stringify(prenormData.componentType)}`);
}
if (isDefined(prenormData.preserveWhitespaces) &&
typeof prenormData.preserveWhitespaces !== 'boolean') {
throw syntaxError(`The preserveWhitespaces option for component ${stringify(prenormData.componentType)} must be a boolean`);
}
return SyncAsync.then(this._preParseTemplate(prenormData), (preparsedTemplate) => this._normalizeTemplateMetadata(prenormData, preparsedTemplate));
}
_preParseTemplate(prenomData) {
let template;
let templateUrl;
if (prenomData.template != null) {
template = prenomData.template;
templateUrl = prenomData.moduleUrl;
}
else {
templateUrl = this._urlResolver.resolve(prenomData.moduleUrl, prenomData.templateUrl);
template = this._fetch(templateUrl);
}
return SyncAsync.then(template, (template) => this._preparseLoadedTemplate(prenomData, template, templateUrl));
}
_preparseLoadedTemplate(prenormData, template, templateAbsUrl) {
const isInline = !!prenormData.template;
const interpolationConfig = InterpolationConfig.fromArray(prenormData.interpolation);
const templateUrl = templateSourceUrl({ reference: prenormData.ngModuleType }, { type: { reference: prenormData.componentType } }, { isInline, templateUrl: templateAbsUrl });
const rootNodesAndErrors = this._htmlParser.parse(template, templateUrl, { tokenizeExpansionForms: true, interpolationConfig });
if (rootNodesAndErrors.errors.length > 0) {
const errorString = rootNodesAndErrors.errors.join('\n');
throw syntaxError(`Template parse errors:\n${errorString}`);
}
const templateMetadataStyles = this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: prenormData.styles, moduleUrl: prenormData.moduleUrl }));
const visitor = new TemplatePreparseVisitor();
visitAll$1(visitor, rootNodesAndErrors.rootNodes);
const templateStyles = this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: visitor.styles, styleUrls: visitor.styleUrls, moduleUrl: templateAbsUrl }));
const styles = templateMetadataStyles.styles.concat(templateStyles.styles);
const inlineStyleUrls = templateMetadataStyles.styleUrls.concat(templateStyles.styleUrls);
const styleUrls = this
._normalizeStylesheet(new CompileStylesheetMetadata({ styleUrls: prenormData.styleUrls, moduleUrl: prenormData.moduleUrl }))
.styleUrls;
return {
template,
templateUrl: templateAbsUrl,
isInline,
htmlAst: rootNodesAndErrors,
styles,
inlineStyleUrls,
styleUrls,
ngContentSelectors: visitor.ngContentSelectors,
};
}
_normalizeTemplateMetadata(prenormData, preparsedTemplate) {
return SyncAsync.then(this._loadMissingExternalStylesheets(preparsedTemplate.styleUrls.concat(preparsedTemplate.inlineStyleUrls)), (externalStylesheets) => this._normalizeLoadedTemplateMetadata(prenormData, preparsedTemplate, externalStylesheets));
}
_normalizeLoadedTemplateMetadata(prenormData, preparsedTemplate, stylesheets) {
// Algorithm:
// - produce exactly 1 entry per original styleUrl in
// CompileTemplateMetadata.externalStylesheets with all styles inlined
// - inline all styles that are referenced by the template into CompileTemplateMetadata.styles.
// Reason: be able to determine how many stylesheets there are even without loading
// the template nor the stylesheets, so we can create a stub for TypeScript always synchronously
// (as resource loading may be async)
const styles = [...preparsedTemplate.styles];
this._inlineStyles(preparsedTemplate.inlineStyleUrls, stylesheets, styles);
const styleUrls = preparsedTemplate.styleUrls;
const externalStylesheets = styleUrls.map(styleUrl => {
const stylesheet = stylesheets.get(styleUrl);
const styles = [...stylesheet.styles];
this._inlineStyles(stylesheet.styleUrls, stylesheets, styles);
return new CompileStylesheetMetadata({ moduleUrl: styleUrl, styles: styles });
});
let encapsulation = prenormData.encapsulation;
if (encapsulation == null) {
encapsulation = this._config.defaultEncapsulation;
}
if (encapsulation === ViewEncapsulation.Emulated && styles.length === 0 &&
styleUrls.length === 0) {
encapsulation = ViewEncapsulation.None;
}
return new CompileTemplateMetadata({
encapsulation,
template: preparsedTemplate.template,
templateUrl: preparsedTemplate.templateUrl,
htmlAst: preparsedTemplate.htmlAst,
styles,
styleUrls,
ngContentSelectors: preparsedTemplate.ngContentSelectors,
animations: prenormData.animations,
interpolation: prenormData.interpolation,
isInline: preparsedTemplate.isInline,
externalStylesheets,
preserveWhitespaces: preserveWhitespacesDefault(prenormData.preserveWhitespaces, this._config.preserveWhitespaces),
});
}
_inlineStyles(styleUrls, stylesheets, targetStyles) {
styleUrls.forEach(styleUrl => {
const stylesheet = stylesheets.get(styleUrl);
stylesheet.styles.forEach(style => targetStyles.push(style));
this._inlineStyles(stylesheet.styleUrls, stylesheets, targetStyles);
});
}
_loadMissingExternalStylesheets(styleUrls, loadedStylesheets = new Map()) {
return SyncAsync.then(SyncAsync.all(styleUrls.filter((styleUrl) => !loadedStylesheets.has(styleUrl))
.map(styleUrl => SyncAsync.then(this._fetch(styleUrl), (loadedStyle) => {
const stylesheet = this._normalizeStylesheet(new CompileStylesheetMetadata({ styles: [loadedStyle], moduleUrl: styleUrl }));
loadedStylesheets.set(styleUrl, stylesheet);
return this._loadMissingExternalStylesheets(stylesheet.styleUrls, loadedStylesheets);
}))), (_) => loadedStylesheets);
}
_normalizeStylesheet(stylesheet) {
const moduleUrl = stylesheet.moduleUrl;
const allStyleUrls = stylesheet.styleUrls.filter(isStyleUrlResolvable)
.map(url => this._urlResolver.resolve(moduleUrl, url));
const allStyles = stylesheet.styles.map(style => {
const styleWithImports = extractStyleUrls(this._urlResolver, moduleUrl, style);
allStyleUrls.push(...styleWithImports.styleUrls);
return styleWithImports.style;
});
return new CompileStylesheetMetadata({ styles: allStyles, styleUrls: allStyleUrls, moduleUrl: moduleUrl });
}
}
class TemplatePreparseVisitor {
constructor() {
this.ngContentSelectors = [];
this.styles = [];
this.styleUrls = [];
this.ngNonBindableStackCount = 0;
}
visitElement(ast, context) {
const preparsedElement = preparseElement(ast);
switch (preparsedElement.type) {
case PreparsedElementType.NG_CONTENT:
if (this.ngNonBindableStackCount === 0) {
this.ngContentSelectors.push(preparsedElement.selectAttr);
}
break;
case PreparsedElementType.STYLE:
let textContent = '';
ast.children.forEach(child => {
if (child instanceof Text$3) {
textContent += child.value;
}
});
this.styles.push(textContent);
break;
case PreparsedElementType.STYLESHEET:
this.styleUrls.push(preparsedElement.hrefAttr);
break;
default:
break;
}
if (preparsedElement.nonBindable) {
this.ngNonBindableStackCount++;
}
visitAll$1(this, ast.children);
if (preparsedElement.nonBindable) {
this.ngNonBindableStackCount--;
}
return null;
}
visitExpansion(ast, context) {
visitAll$1(this, ast.cases);
}
visitExpansionCase(ast, context) {
visitAll$1(this, ast.expression);
}
visitComment(ast, context) {
return null;
}
visitAttribute(ast, context) {
return null;
}
visitText(ast, context) {
return null;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const QUERY_METADATA_IDENTIFIERS = [
createViewChild,
createViewChildren,
createContentChild,
createContentChildren,
];
/*
* Resolve a `Type` for {@link Directive}.
*
* This interface can be overridden by the application developer to create custom behavior.
*
* See {@link Compiler}
*/
class DirectiveResolver {
constructor(_reflector) {
this._reflector = _reflector;
}
isDirective(type) {
const typeMetadata = this._reflector.annotations(resolveForwardRef(type));
return typeMetadata && typeMetadata.some(isDirectiveMetadata);
}
resolve(type, throwIfNotFound = true) {
const typeMetadata = this._reflector.annotations(resolveForwardRef(type));
if (typeMetadata) {
const metadata = findLast(typeMetadata, isDirectiveMetadata);
if (metadata) {
const propertyMetadata = this._reflector.propMetadata(type);
const guards = this._reflector.guards(type);
return this._mergeWithPropertyMetadata(metadata, propertyMetadata, guards, type);
}
}
if (throwIfNotFound) {
throw new Error(`No Directive annotation found on ${stringify(type)}`);
}
return null;
}
_mergeWithPropertyMetadata(dm, propertyMetadata, guards, directiveType) {
const inputs = [];
const outputs = [];
const host = {};
const queries = {};
Object.keys(propertyMetadata).forEach((propName) => {
const input = findLast(propertyMetadata[propName], (a) => createInput.isTypeOf(a));
if (input) {
if (input.bindingPropertyName) {
inputs.push(`${propName}: ${input.bindingPropertyName}`);
}
else {
inputs.push(propName);
}
}
const output = findLast(propertyMetadata[propName], (a) => createOutput.isTypeOf(a));
if (output) {
if (output.bindingPropertyName) {
outputs.push(`${propName}: ${output.bindingPropertyName}`);
}
else {
outputs.push(propName);
}
}
const hostBindings = propertyMetadata[propName].filter(a => createHostBinding.isTypeOf(a));
hostBindings.forEach(hostBinding => {
if (hostBinding.hostPropertyName) {
const startWith = hostBinding.hostPropertyName[0];
if (startWith === '(') {
throw new Error(`@HostBinding can not bind to events. Use @HostListener instead.`);
}
else if (startWith === '[') {
throw new Error(`@HostBinding parameter should be a property name, 'class.<name>', or 'attr.<name>'.`);
}
host[`[${hostBinding.hostPropertyName}]`] = propName;
}
else {
host[`[${propName}]`] = propName;
}
});
const hostListeners = propertyMetadata[propName].filter(a => createHostListener.isTypeOf(a));
hostListeners.forEach(hostListener => {
const args = hostListener.args || [];
host[`(${hostListener.eventName})`] = `${propName}(${args.join(',')})`;
});
const query = findLast(propertyMetadata[propName], (a) => QUERY_METADATA_IDENTIFIERS.some(i => i.isTypeOf(a)));
if (query) {
queries[propName] = query;
}
});
return this._merge(dm, inputs, outputs, host, queries, guards, directiveType);
}
_extractPublicName(def) {
return splitAtColon(def, [null, def])[1].trim();
}
_dedupeBindings(bindings) {
const names = new Set();
const publicNames = new Set();
const reversedResult = [];
// go last to first to allow later entries to overwrite previous entries
for (let i = bindings.length - 1; i >= 0; i--) {
const binding = bindings[i];
const name = this._extractPublicName(binding);
publicNames.add(name);
if (!names.has(name)) {
names.add(name);
reversedResult.push(binding);
}
}
return reversedResult.reverse();
}
_merge(directive, inputs, outputs, host, queries, guards, directiveType) {
const mergedInputs = this._dedupeBindings(directive.inputs ? directive.inputs.concat(inputs) : inputs);
const mergedOutputs = this._dedupeBindings(directive.outputs ? directive.outputs.concat(outputs) : outputs);
const mergedHost = directive.host ? Object.assign(Object.assign({}, directive.host), host) : host;
const mergedQueries = directive.queries ? Object.assign(Object.assign({}, directive.queries), queries) : queries;
if (createComponent.isTypeOf(directive)) {
const comp = directive;
return createComponent({
selector: comp.selector,
inputs: mergedInputs,
outputs: mergedOutputs,
host: mergedHost,
exportAs: comp.exportAs,
moduleId: comp.moduleId,
queries: mergedQueries,
changeDetection: comp.changeDetection,
providers: comp.providers,
viewProviders: comp.viewProviders,
entryComponents: comp.entryComponents,
template: comp.template,
templateUrl: comp.templateUrl,
styles: comp.styles,
styleUrls: comp.styleUrls,
encapsulation: comp.encapsulation,
animations: comp.animations,
interpolation: comp.interpolation,
preserveWhitespaces: directive.preserveWhitespaces,
});
}
else {
return createDirective({
selector: directive.selector,
inputs: mergedInputs,
outputs: mergedOutputs,
host: mergedHost,
exportAs: directive.exportAs,
queries: mergedQueries,
providers: directive.providers,
guards
});
}
}
}
function isDirectiveMetadata(type) {
return createDirective.isTypeOf(type) || createComponent.isTypeOf(type);
}
function findLast(arr, condition) {
for (let i = arr.length - 1; i >= 0; i--) {
if (condition(arr[i])) {
return arr[i];
}
}
return null;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const _I18N_ATTR = 'i18n';
const _I18N_ATTR_PREFIX = 'i18n-';
const _I18N_COMMENT_PREFIX_REGEXP = /^i18n:?/;
const MEANING_SEPARATOR = '|';
const ID_SEPARATOR = '@@';
let i18nCommentsWarned = false;
/**
* Extract translatable messages from an html AST
*/
function extractMessages(nodes, interpolationConfig, implicitTags, implicitAttrs) {
const visitor = new _Visitor$2(implicitTags, implicitAttrs);
return visitor.extract(nodes, interpolationConfig);
}
function mergeTranslations(nodes, translations, interpolationConfig, implicitTags, implicitAttrs) {
const visitor = new _Visitor$2(implicitTags, implicitAttrs);
return visitor.merge(nodes, translations, interpolationConfig);
}
class ExtractionResult {
constructor(messages, errors) {
this.messages = messages;
this.errors = errors;
}
}
var _VisitorMode;
(function (_VisitorMode) {
_VisitorMode[_VisitorMode["Extract"] = 0] = "Extract";
_VisitorMode[_VisitorMode["Merge"] = 1] = "Merge";
})(_VisitorMode || (_VisitorMode = {}));
/**
* This Visitor is used:
* 1. to extract all the translatable strings from an html AST (see `extract()`),
* 2. to replace the translatable strings with the actual translations (see `merge()`)
*
* @internal
*/
class _Visitor$2 {
constructor(_implicitTags, _implicitAttrs) {
this._implicitTags = _implicitTags;
this._implicitAttrs = _implicitAttrs;
}
/**
* Extracts the messages from the tree
*/
extract(nodes, interpolationConfig) {
this._init(_VisitorMode.Extract, interpolationConfig);
nodes.forEach(node => node.visit(this, null));
if (this._inI18nBlock) {
this._reportError(nodes[nodes.length - 1], 'Unclosed block');
}
return new ExtractionResult(this._messages, this._errors);
}
/**
* Returns a tree where all translatable nodes are translated
*/
merge(nodes, translations, interpolationConfig) {
this._init(_VisitorMode.Merge, interpolationConfig);
this._translations = translations;
// Construct a single fake root element
const wrapper = new Element$1('wrapper', [], nodes, undefined, undefined, undefined);
const translatedNode = wrapper.visit(this, null);
if (this._inI18nBlock) {
this._reportError(nodes[nodes.length - 1], 'Unclosed block');
}
return new ParseTreeResult(translatedNode.children, this._errors);
}
visitExpansionCase(icuCase, context) {
// Parse cases for translatable html attributes
const expression = visitAll$1(this, icuCase.expression, context);
if (this._mode === _VisitorMode.Merge) {
return new ExpansionCase(icuCase.value, expression, icuCase.sourceSpan, icuCase.valueSourceSpan, icuCase.expSourceSpan);
}
}
visitExpansion(icu, context) {
this._mayBeAddBlockChildren(icu);
const wasInIcu = this._inIcu;
if (!this._inIcu) {
// nested ICU messages should not be extracted but top-level translated as a whole
if (this._isInTranslatableSection) {
this._addMessage([icu]);
}
this._inIcu = true;
}
const cases = visitAll$1(this, icu.cases, context);
if (this._mode === _VisitorMode.Merge) {
icu = new Expansion(icu.switchValue, icu.type, cases, icu.sourceSpan, icu.switchValueSourceSpan);
}
this._inIcu = wasInIcu;
return icu;
}
visitComment(comment, context) {
const isOpening = _isOpeningComment(comment);
if (isOpening && this._isInTranslatableSection) {
this._reportError(comment, 'Could not start a block inside a translatable section');
return;
}
const isClosing = _isClosingComment(comment);
if (isClosing && !this._inI18nBlock) {
this._reportError(comment, 'Trying to close an unopened block');
return;
}
if (!this._inI18nNode && !this._inIcu) {
if (!this._inI18nBlock) {
if (isOpening) {
// deprecated from v5 you should use <ng-container i18n> instead of i18n comments
if (!i18nCommentsWarned && console && console.warn) {
i18nCommentsWarned = true;
const details = comment.sourceSpan.details ? `, ${comment.sourceSpan.details}` : '';
// TODO(ocombe): use a log service once there is a public one available
console.warn(`I18n comments are deprecated, use an <ng-container> element instead (${comment.sourceSpan.start}${details})`);
}
this._inI18nBlock = true;
this._blockStartDepth = this._depth;
this._blockChildren = [];
this._blockMeaningAndDesc =
comment.value.replace(_I18N_COMMENT_PREFIX_REGEXP, '').trim();
this._openTranslatableSection(comment);
}
}
else {
if (isClosing) {
if (this._depth == this._blockStartDepth) {
this._closeTranslatableSection(comment, this._blockChildren);
this._inI18nBlock = false;
const message = this._addMessage(this._blockChildren, this._blockMeaningAndDesc);
// merge attributes in sections
const nodes = this._translateMessage(comment, message);
return visitAll$1(this, nodes);
}
else {
this._reportError(comment, 'I18N blocks should not cross element boundaries');
return;
}
}
}
}
}
visitText(text, context) {
if (this._isInTranslatableSection) {
this._mayBeAddBlockChildren(text);
}
return text;
}
visitElement(el, context) {
this._mayBeAddBlockChildren(el);
this._depth++;
const wasInI18nNode = this._inI18nNode;
const wasInImplicitNode = this._inImplicitNode;
let childNodes = [];
let translatedChildNodes = undefined;
// Extract:
// - top level nodes with the (implicit) "i18n" attribute if not already in a section
// - ICU messages
const i18nAttr = _getI18nAttr(el);
const i18nMeta = i18nAttr ? i18nAttr.value : '';
const isImplicit = this._implicitTags.some(tag => el.name === tag) && !this._inIcu &&
!this._isInTranslatableSection;
const isTopLevelImplicit = !wasInImplicitNode && isImplicit;
this._inImplicitNode = wasInImplicitNode || isImplicit;
if (!this._isInTranslatableSection && !this._inIcu) {
if (i18nAttr || isTopLevelImplicit) {
this._inI18nNode = true;
const message = this._addMessage(el.children, i18nMeta);
translatedChildNodes = this._translateMessage(el, message);
}
if (this._mode == _VisitorMode.Extract) {
const isTranslatable = i18nAttr || isTopLevelImplicit;
if (isTranslatable)
this._openTranslatableSection(el);
visitAll$1(this, el.children);
if (isTranslatable)
this._closeTranslatableSection(el, el.children);
}
}
else {
if (i18nAttr || isTopLevelImplicit) {
this._reportError(el, 'Could not mark an element as translatable inside a translatable section');
}
if (this._mode == _VisitorMode.Extract) {
// Descend into child nodes for extraction
visitAll$1(this, el.children);
}
}
if (this._mode === _VisitorMode.Merge) {
const visitNodes = translatedChildNodes || el.children;
visitNodes.forEach(child => {
const visited = child.visit(this, context);
if (visited && !this._isInTranslatableSection) {
// Do not add the children from translatable sections (= i18n blocks here)
// They will be added later in this loop when the block closes (i.e. on `<!-- /i18n -->`)
childNodes = childNodes.concat(visited);
}
});
}
this._visitAttributesOf(el);
this._depth--;
this._inI18nNode = wasInI18nNode;
this._inImplicitNode = wasInImplicitNode;
if (this._mode === _VisitorMode.Merge) {
const translatedAttrs = this._translateAttributes(el);
return new Element$1(el.name, translatedAttrs, childNodes, el.sourceSpan, el.startSourceSpan, el.endSourceSpan);
}
return null;
}
visitAttribute(attribute, context) {
throw new Error('unreachable code');
}
_init(mode, interpolationConfig) {
this._mode = mode;
this._inI18nBlock = false;
this._inI18nNode = false;
this._depth = 0;
this._inIcu = false;
this._msgCountAtSectionStart = undefined;
this._errors = [];
this._messages = [];
this._inImplicitNode = false;
this._createI18nMessage = createI18nMessageFactory(interpolationConfig);
}
// looks for translatable attributes
_visitAttributesOf(el) {
const explicitAttrNameToValue = {};
const implicitAttrNames = this._implicitAttrs[el.name] || [];
el.attrs.filter(attr => attr.name.startsWith(_I18N_ATTR_PREFIX))
.forEach(attr => explicitAttrNameToValue[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
attr.value);
el.attrs.forEach(attr => {
if (attr.name in explicitAttrNameToValue) {
this._addMessage([attr], explicitAttrNameToValue[attr.name]);
}
else if (implicitAttrNames.some(name => attr.name === name)) {
this._addMessage([attr]);
}
});
}
// add a translatable message
_addMessage(ast, msgMeta) {
if (ast.length == 0 ||
ast.length == 1 && ast[0] instanceof Attribute && !ast[0].value) {
// Do not create empty messages
return null;
}
const { meaning, description, id } = _parseMessageMeta(msgMeta);
const message = this._createI18nMessage(ast, meaning, description, id);
this._messages.push(message);
return message;
}
// Translates the given message given the `TranslationBundle`
// This is used for translating elements / blocks - see `_translateAttributes` for attributes
// no-op when called in extraction mode (returns [])
_translateMessage(el, message) {
if (message && this._mode === _VisitorMode.Merge) {
const nodes = this._translations.get(message);
if (nodes) {
return nodes;
}
this._reportError(el, `Translation unavailable for message id="${this._translations.digest(message)}"`);
}
return [];
}
// translate the attributes of an element and remove i18n specific attributes
_translateAttributes(el) {
const attributes = el.attrs;
const i18nParsedMessageMeta = {};
attributes.forEach(attr => {
if (attr.name.startsWith(_I18N_ATTR_PREFIX)) {
i18nParsedMessageMeta[attr.name.slice(_I18N_ATTR_PREFIX.length)] =
_parseMessageMeta(attr.value);
}
});
const translatedAttributes = [];
attributes.forEach((attr) => {
if (attr.name === _I18N_ATTR || attr.name.startsWith(_I18N_ATTR_PREFIX)) {
// strip i18n specific attributes
return;
}
if (attr.value && attr.value != '' && i18nParsedMessageMeta.hasOwnProperty(attr.name)) {
const { meaning, description, id } = i18nParsedMessageMeta[attr.name];
const message = this._createI18nMessage([attr], meaning, description, id);
const nodes = this._translations.get(message);
if (nodes) {
if (nodes.length == 0) {
translatedAttributes.push(new Attribute(attr.name, '', attr.sourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */));
}
else if (nodes[0] instanceof Text$3) {
const value = nodes[0].value;
translatedAttributes.push(new Attribute(attr.name, value, attr.sourceSpan, undefined /* keySpan */, undefined /* valueSpan */, undefined /* i18n */));
}
else {
this._reportError(el, `Unexpected translation for attribute "${attr.name}" (id="${id || this._translations.digest(message)}")`);
}
}
else {
this._reportError(el, `Translation unavailable for attribute "${attr.name}" (id="${id || this._translations.digest(message)}")`);
}
}
else {
translatedAttributes.push(attr);
}
});
return translatedAttributes;
}
/**
* Add the node as a child of the block when:
* - we are in a block,
* - we are not inside a ICU message (those are handled separately),
* - the node is a "direct child" of the block
*/
_mayBeAddBlockChildren(node) {
if (this._inI18nBlock && !this._inIcu && this._depth == this._blockStartDepth) {
this._blockChildren.push(node);
}
}
/**
* Marks the start of a section, see `_closeTranslatableSection`
*/
_openTranslatableSection(node) {
if (this._isInTranslatableSection) {
this._reportError(node, 'Unexpected section start');
}
else {
this._msgCountAtSectionStart = this._messages.length;
}
}
/**
* A translatable section could be:
* - the content of translatable element,
* - nodes between `<!-- i18n -->` and `<!-- /i18n -->` comments
*/
get _isInTranslatableSection() {
return this._msgCountAtSectionStart !== void 0;
}
/**
* Terminates a section.
*
* If a section has only one significant children (comments not significant) then we should not
* keep the message from this children:
*
* `<p i18n="meaning|description">{ICU message}</p>` would produce two messages:
* - one for the <p> 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)
*/
_closeTranslatableSection(node, directChildren) {
if (!this._isInTranslatableSection) {
this._reportError(node, 'Unexpected section end');
return;
}
const startIndex = this._msgCountAtSectionStart;
const significantChildren = directChildren.reduce((count, node) => count + (node instanceof Comment$1 ? 0 : 1), 0);
if (significantChildren == 1) {
for (let i = this._messages.length - 1; i >= startIndex; i--) {
const ast = this._messages[i].nodes;
if (!(ast.length == 1 && ast[0] instanceof Text$1)) {
this._messages.splice(i, 1);
break;
}
}
}
this._msgCountAtSectionStart = undefined;
}
_reportError(node, msg) {
this._errors.push(new I18nError(node.sourceSpan, msg));
}
}
function _isOpeningComment(n) {
return !!(n instanceof Comment$1 && n.value && n.value.startsWith('i18n'));
}
function _isClosingComment(n) {
return !!(n instanceof Comment$1 && n.value && n.value === '/i18n');
}
function _getI18nAttr(p) {
return p.attrs.find(attr => attr.name === _I18N_ATTR) || null;
}
function _parseMessageMeta(i18n) {
if (!i18n)
return { meaning: '', description: '', id: '' };
const idIndex = i18n.indexOf(ID_SEPARATOR);
const descIndex = i18n.indexOf(MEANING_SEPARATOR);
const [meaningAndDesc, id] = (idIndex > -1) ? [i18n.slice(0, idIndex), i18n.slice(idIndex + 2)] : [i18n, ''];
const [meaning, description] = (descIndex > -1) ?
[meaningAndDesc.slice(0, descIndex), meaningAndDesc.slice(descIndex + 1)] :
['', meaningAndDesc];
return { meaning, description, id: id.trim() };
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class XmlTagDefinition {
constructor() {
this.closedByParent = false;
this.isVoid = false;
this.ignoreFirstLf = false;
this.canSelfClose = true;
this.preventNamespaceInheritance = false;
}
requireExtraParent(currentParent) {
return false;
}
isClosedByChild(name) {
return false;
}
getContentType() {
return TagContentType.PARSABLE_DATA;
}
}
const _TAG_DEFINITION = new XmlTagDefinition();
function getXmlTagDefinition(tagName) {
return _TAG_DEFINITION;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class XmlParser extends Parser {
constructor() {
super(getXmlTagDefinition);
}
parse(source, url, options) {
return super.parse(source, url, options);
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const _VERSION = '1.2';
const _XMLNS = 'urn:oasis:names:tc:xliff:document:1.2';
// TODO(vicb): make this a param (s/_/-/)
const _DEFAULT_SOURCE_LANG = 'en';
const _PLACEHOLDER_TAG$1 = 'x';
const _MARKER_TAG = 'mrk';
const _FILE_TAG = 'file';
const _SOURCE_TAG$1 = 'source';
const _SEGMENT_SOURCE_TAG = 'seg-source';
const _ALT_TRANS_TAG = 'alt-trans';
const _TARGET_TAG = 'target';
const _UNIT_TAG = 'trans-unit';
const _CONTEXT_GROUP_TAG = 'context-group';
const _CONTEXT_TAG = 'context';
// https://docs.oasis-open.org/xliff/v1.2/os/xliff-core.html
// https://docs.oasis-open.org/xliff/v1.2/xliff-profile-html/xliff-profile-html-1.2.html
class Xliff extends Serializer {
write(messages, locale) {
const visitor = new _WriteVisitor();
const transUnits = [];
messages.forEach(message => {
let contextTags = [];
message.sources.forEach((source) => {
let 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);
});
const transUnit = new Tag(_UNIT_TAG, { id: message.id, datatype: 'html' });
transUnit.children.push(new CR(8), new Tag(_SOURCE_TAG$1, {}, 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);
});
const body = new Tag('body', {}, [...transUnits, new CR(4)]);
const file = new Tag('file', {
'source-language': locale || _DEFAULT_SOURCE_LANG,
datatype: 'plaintext',
original: 'ng2.template',
}, [new CR(4), body, new CR(2)]);
const 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()
]);
}
load(content, url) {
// xliff to xml nodes
const xliffParser = new XliffParser();
const { locale, msgIdToHtml, errors } = xliffParser.parse(content, url);
// xml nodes to i18n nodes
const i18nNodesByMsgId = {};
const converter = new XmlToI18n();
Object.keys(msgIdToHtml).forEach(msgId => {
const { i18nNodes, errors: e } = converter.convert(msgIdToHtml[msgId], url);
errors.push(...e);
i18nNodesByMsgId[msgId] = i18nNodes;
});
if (errors.length) {
throw new Error(`xliff parse errors:\n${errors.join('\n')}`);
}
return { locale: locale, i18nNodesByMsgId };
}
digest(message) {
return digest(message);
}
}
class _WriteVisitor {
visitText(text, context) {
return [new Text$2(text.value)];
}
visitContainer(container, context) {
const nodes = [];
container.children.forEach((node) => nodes.push(...node.visit(this)));
return nodes;
}
visitIcu(icu, context) {
const nodes = [new Text$2(`{${icu.expressionPlaceholder}, ${icu.type}, `)];
Object.keys(icu.cases).forEach((c) => {
nodes.push(new Text$2(`${c} {`), ...icu.cases[c].visit(this), new Text$2(`} `));
});
nodes.push(new Text$2(`}`));
return nodes;
}
visitTagPlaceholder(ph, context) {
const ctype = getCtypeForTag(ph.tag);
if (ph.isVoid) {
// void tags have no children nor closing tags
return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.startName, ctype, 'equiv-text': `<${ph.tag}/>` })];
}
const startTagPh = new Tag(_PLACEHOLDER_TAG$1, { id: ph.startName, ctype, 'equiv-text': `<${ph.tag}>` });
const closeTagPh = new Tag(_PLACEHOLDER_TAG$1, { id: ph.closeName, ctype, 'equiv-text': `</${ph.tag}>` });
return [startTagPh, ...this.serialize(ph.children), closeTagPh];
}
visitPlaceholder(ph, context) {
return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.name, 'equiv-text': `{{${ph.value}}}` })];
}
visitIcuPlaceholder(ph, context) {
const equivText = `{${ph.value.expression}, ${ph.value.type}, ${Object.keys(ph.value.cases).map((value) => value + ' {...}').join(' ')}}`;
return [new Tag(_PLACEHOLDER_TAG$1, { id: ph.name, 'equiv-text': equivText })];
}
serialize(nodes) {
return [].concat(...nodes.map(node => node.visit(this)));
}
}
// TODO(vicb): add error management (structure)
// Extract messages as xml nodes from the xliff file
class XliffParser {
constructor() {
this._locale = null;
}
parse(xliff, url) {
this._unitMlString = null;
this._msgIdToHtml = {};
const xml = new XmlParser().parse(xliff, url);
this._errors = xml.errors;
visitAll$1(this, xml.rootNodes, null);
return {
msgIdToHtml: this._msgIdToHtml,
errors: this._errors,
locale: this._locale,
};
}
visitElement(element, context) {
switch (element.name) {
case _UNIT_TAG:
this._unitMlString = null;
const idAttr = element.attrs.find((attr) => attr.name === 'id');
if (!idAttr) {
this._addError(element, `<${_UNIT_TAG}> misses the "id" attribute`);
}
else {
const id = idAttr.value;
if (this._msgIdToHtml.hasOwnProperty(id)) {
this._addError(element, `Duplicated translations for msg ${id}`);
}
else {
visitAll$1(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$1:
case _SEGMENT_SOURCE_TAG:
case _ALT_TRANS_TAG:
break;
case _TARGET_TAG:
const innerTextStart = element.startSourceSpan.end.offset;
const innerTextEnd = element.endSourceSpan.start.offset;
const content = element.startSourceSpan.start.file.content;
const innerText = content.slice(innerTextStart, innerTextEnd);
this._unitMlString = innerText;
break;
case _FILE_TAG:
const localeAttr = element.attrs.find((attr) => attr.name === 'target-language');
if (localeAttr) {
this._locale = localeAttr.value;
}
visitAll$1(this, element.children, null);
break;
default:
// TODO(vicb): assert file structure, xliff version
// For now only recurse on unhandled nodes
visitAll$1(this, element.children, null);
}
}
visitAttribute(attribute, context) { }
visitText(text, context) { }
visitComment(comment, context) { }
visitExpansion(expansion, context) { }
visitExpansionCase(expansionCase, context) { }
_addError(node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
}
}
// Convert ml nodes (xliff syntax) to i18n nodes
class XmlToI18n {
convert(message, url) {
const xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
this._errors = xmlIcu.errors;
const i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
[] :
[].concat(...visitAll$1(this, xmlIcu.rootNodes));
return {
i18nNodes: i18nNodes,
errors: this._errors,
};
}
visitText(text, context) {
return new Text$1(text.value, text.sourceSpan);
}
visitElement(el, context) {
if (el.name === _PLACEHOLDER_TAG$1) {
const nameAttr = el.attrs.find((attr) => attr.name === 'id');
if (nameAttr) {
return new Placeholder('', nameAttr.value, el.sourceSpan);
}
this._addError(el, `<${_PLACEHOLDER_TAG$1}> misses the "id" attribute`);
return null;
}
if (el.name === _MARKER_TAG) {
return [].concat(...visitAll$1(this, el.children));
}
this._addError(el, `Unexpected tag`);
return null;
}
visitExpansion(icu, context) {
const caseMap = {};
visitAll$1(this, icu.cases).forEach((c) => {
caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
});
return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
}
visitExpansionCase(icuCase, context) {
return {
value: icuCase.value,
nodes: visitAll$1(this, icuCase.expression),
};
}
visitComment(comment, context) { }
visitAttribute(attribute, context) { }
_addError(node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
}
}
function getCtypeForTag(tag) {
switch (tag.toLowerCase()) {
case 'br':
return 'lb';
case 'img':
return 'image';
default:
return `x-${tag}`;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const _VERSION$1 = '2.0';
const _XMLNS$1 = 'urn:oasis:names:tc:xliff:document:2.0';
// TODO(vicb): make this a param (s/_/-/)
const _DEFAULT_SOURCE_LANG$1 = 'en';
const _PLACEHOLDER_TAG$2 = 'ph';
const _PLACEHOLDER_SPANNING_TAG = 'pc';
const _MARKER_TAG$1 = 'mrk';
const _XLIFF_TAG = 'xliff';
const _SOURCE_TAG$2 = 'source';
const _TARGET_TAG$1 = 'target';
const _UNIT_TAG$1 = 'unit';
// https://docs.oasis-open.org/xliff/xliff-core/v2.0/os/xliff-core-v2.0-os.html
class Xliff2 extends Serializer {
write(messages, locale) {
const visitor = new _WriteVisitor$1();
const units = [];
messages.forEach(message => {
const unit = new Tag(_UNIT_TAG$1, { id: message.id });
const 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((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);
const segment = new Tag('segment');
segment.children.push(new CR(8), new Tag(_SOURCE_TAG$2, {}, visitor.serialize(message.nodes)), new CR(6));
unit.children.push(new CR(6), segment, new CR(4));
units.push(new CR(4), unit);
});
const file = new Tag('file', { 'original': 'ng.template', id: 'ngi18n' }, [...units, new CR(2)]);
const 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()
]);
}
load(content, url) {
// xliff to xml nodes
const xliff2Parser = new Xliff2Parser();
const { locale, msgIdToHtml, errors } = xliff2Parser.parse(content, url);
// xml nodes to i18n nodes
const i18nNodesByMsgId = {};
const converter = new XmlToI18n$1();
Object.keys(msgIdToHtml).forEach(msgId => {
const { i18nNodes, errors: e } = converter.convert(msgIdToHtml[msgId], url);
errors.push(...e);
i18nNodesByMsgId[msgId] = i18nNodes;
});
if (errors.length) {
throw new Error(`xliff2 parse errors:\n${errors.join('\n')}`);
}
return { locale: locale, i18nNodesByMsgId };
}
digest(message) {
return decimalDigest(message);
}
}
class _WriteVisitor$1 {
visitText(text, context) {
return [new Text$2(text.value)];
}
visitContainer(container, context) {
const nodes = [];
container.children.forEach((node) => nodes.push(...node.visit(this)));
return nodes;
}
visitIcu(icu, context) {
const nodes = [new Text$2(`{${icu.expressionPlaceholder}, ${icu.type}, `)];
Object.keys(icu.cases).forEach((c) => {
nodes.push(new Text$2(`${c} {`), ...icu.cases[c].visit(this), new Text$2(`} `));
});
nodes.push(new Text$2(`}`));
return nodes;
}
visitTagPlaceholder(ph, context) {
const type = getTypeForTag(ph.tag);
if (ph.isVoid) {
const tagPh = new Tag(_PLACEHOLDER_TAG$2, {
id: (this._nextPlaceholderId++).toString(),
equiv: ph.startName,
type: type,
disp: `<${ph.tag}/>`,
});
return [tagPh];
}
const tagPc = new Tag(_PLACEHOLDER_SPANNING_TAG, {
id: (this._nextPlaceholderId++).toString(),
equivStart: ph.startName,
equivEnd: ph.closeName,
type: type,
dispStart: `<${ph.tag}>`,
dispEnd: `</${ph.tag}>`,
});
const nodes = [].concat(...ph.children.map(node => node.visit(this)));
if (nodes.length) {
nodes.forEach((node) => tagPc.children.push(node));
}
else {
tagPc.children.push(new Text$2(''));
}
return [tagPc];
}
visitPlaceholder(ph, context) {
const idStr = (this._nextPlaceholderId++).toString();
return [new Tag(_PLACEHOLDER_TAG$2, {
id: idStr,
equiv: ph.name,
disp: `{{${ph.value}}}`,
})];
}
visitIcuPlaceholder(ph, context) {
const cases = Object.keys(ph.value.cases).map((value) => value + ' {...}').join(' ');
const idStr = (this._nextPlaceholderId++).toString();
return [new Tag(_PLACEHOLDER_TAG$2, { id: idStr, equiv: ph.name, disp: `{${ph.value.expression}, ${ph.value.type}, ${cases}}` })];
}
serialize(nodes) {
this._nextPlaceholderId = 0;
return [].concat(...nodes.map(node => node.visit(this)));
}
}
// Extract messages as xml nodes from the xliff file
class Xliff2Parser {
constructor() {
this._locale = null;
}
parse(xliff, url) {
this._unitMlString = null;
this._msgIdToHtml = {};
const xml = new XmlParser().parse(xliff, url);
this._errors = xml.errors;
visitAll$1(this, xml.rootNodes, null);
return {
msgIdToHtml: this._msgIdToHtml,
errors: this._errors,
locale: this._locale,
};
}
visitElement(element, context) {
switch (element.name) {
case _UNIT_TAG$1:
this._unitMlString = null;
const idAttr = element.attrs.find((attr) => attr.name === 'id');
if (!idAttr) {
this._addError(element, `<${_UNIT_TAG$1}> misses the "id" attribute`);
}
else {
const id = idAttr.value;
if (this._msgIdToHtml.hasOwnProperty(id)) {
this._addError(element, `Duplicated translations for msg ${id}`);
}
else {
visitAll$1(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$2:
// ignore source message
break;
case _TARGET_TAG$1:
const innerTextStart = element.startSourceSpan.end.offset;
const innerTextEnd = element.endSourceSpan.start.offset;
const content = element.startSourceSpan.start.file.content;
const innerText = content.slice(innerTextStart, innerTextEnd);
this._unitMlString = innerText;
break;
case _XLIFF_TAG:
const localeAttr = element.attrs.find((attr) => attr.name === 'trgLang');
if (localeAttr) {
this._locale = localeAttr.value;
}
const versionAttr = element.attrs.find((attr) => attr.name === 'version');
if (versionAttr) {
const 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$1(this, element.children, null);
}
}
break;
default:
visitAll$1(this, element.children, null);
}
}
visitAttribute(attribute, context) { }
visitText(text, context) { }
visitComment(comment, context) { }
visitExpansion(expansion, context) { }
visitExpansionCase(expansionCase, context) { }
_addError(node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
}
}
// Convert ml nodes (xliff syntax) to i18n nodes
class XmlToI18n$1 {
convert(message, url) {
const xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
this._errors = xmlIcu.errors;
const i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
[] :
[].concat(...visitAll$1(this, xmlIcu.rootNodes));
return {
i18nNodes,
errors: this._errors,
};
}
visitText(text, context) {
return new Text$1(text.value, text.sourceSpan);
}
visitElement(el, context) {
switch (el.name) {
case _PLACEHOLDER_TAG$2:
const nameAttr = el.attrs.find((attr) => attr.name === 'equiv');
if (nameAttr) {
return [new Placeholder('', nameAttr.value, el.sourceSpan)];
}
this._addError(el, `<${_PLACEHOLDER_TAG$2}> misses the "equiv" attribute`);
break;
case _PLACEHOLDER_SPANNING_TAG:
const startAttr = el.attrs.find((attr) => attr.name === 'equivStart');
const endAttr = el.attrs.find((attr) => attr.name === 'equivEnd');
if (!startAttr) {
this._addError(el, `<${_PLACEHOLDER_TAG$2}> misses the "equivStart" attribute`);
}
else if (!endAttr) {
this._addError(el, `<${_PLACEHOLDER_TAG$2}> misses the "equivEnd" attribute`);
}
else {
const startId = startAttr.value;
const endId = endAttr.value;
const nodes = [];
return nodes.concat(new Placeholder('', startId, el.sourceSpan), ...el.children.map(node => node.visit(this, null)), new Placeholder('', endId, el.sourceSpan));
}
break;
case _MARKER_TAG$1:
return [].concat(...visitAll$1(this, el.children));
default:
this._addError(el, `Unexpected tag`);
}
return null;
}
visitExpansion(icu, context) {
const caseMap = {};
visitAll$1(this, icu.cases).forEach((c) => {
caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
});
return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
}
visitExpansionCase(icuCase, context) {
return {
value: icuCase.value,
nodes: [].concat(...visitAll$1(this, icuCase.expression)),
};
}
visitComment(comment, context) { }
visitAttribute(attribute, context) { }
_addError(node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
}
}
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 LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const _TRANSLATIONS_TAG = 'translationbundle';
const _TRANSLATION_TAG = 'translation';
const _PLACEHOLDER_TAG$3 = 'ph';
class Xtb extends Serializer {
write(messages, locale) {
throw new Error('Unsupported');
}
load(content, url) {
// xtb to xml nodes
const xtbParser = new XtbParser();
const { locale, msgIdToHtml, errors } = xtbParser.parse(content, url);
// xml nodes to i18n nodes
const i18nNodesByMsgId = {};
const 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(msgId => {
const valueFn = function () {
const { i18nNodes, errors } = converter.convert(msgIdToHtml[msgId], url);
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 };
}
digest(message) {
return digest$1(message);
}
createNameMapper(message) {
return new SimplePlaceholderMapper(message, toPublicName);
}
}
function createLazyProperty(messages, id, valueFn) {
Object.defineProperty(messages, id, {
configurable: true,
enumerable: true,
get: function () {
const value = valueFn();
Object.defineProperty(messages, id, { enumerable: true, value });
return value;
},
set: _ => {
throw new Error('Could not overwrite an XTB translation');
},
});
}
// Extract messages as xml nodes from the xtb file
class XtbParser {
constructor() {
this._locale = null;
}
parse(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.
const xml = new XmlParser().parse(xtb, url);
this._errors = xml.errors;
visitAll$1(this, xml.rootNodes);
return {
msgIdToHtml: this._msgIdToHtml,
errors: this._errors,
locale: this._locale,
};
}
visitElement(element, context) {
switch (element.name) {
case _TRANSLATIONS_TAG:
this._bundleDepth++;
if (this._bundleDepth > 1) {
this._addError(element, `<${_TRANSLATIONS_TAG}> elements can not be nested`);
}
const langAttr = element.attrs.find((attr) => attr.name === 'lang');
if (langAttr) {
this._locale = langAttr.value;
}
visitAll$1(this, element.children, null);
this._bundleDepth--;
break;
case _TRANSLATION_TAG:
const idAttr = element.attrs.find((attr) => attr.name === 'id');
if (!idAttr) {
this._addError(element, `<${_TRANSLATION_TAG}> misses the "id" attribute`);
}
else {
const id = idAttr.value;
if (this._msgIdToHtml.hasOwnProperty(id)) {
this._addError(element, `Duplicated translations for msg ${id}`);
}
else {
const innerTextStart = element.startSourceSpan.end.offset;
const innerTextEnd = element.endSourceSpan.start.offset;
const content = element.startSourceSpan.start.file.content;
const innerText = content.slice(innerTextStart, innerTextEnd);
this._msgIdToHtml[id] = innerText;
}
}
break;
default:
this._addError(element, 'Unexpected tag');
}
}
visitAttribute(attribute, context) { }
visitText(text, context) { }
visitComment(comment, context) { }
visitExpansion(expansion, context) { }
visitExpansionCase(expansionCase, context) { }
_addError(node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
}
}
// Convert ml nodes (xtb syntax) to i18n nodes
class XmlToI18n$2 {
convert(message, url) {
const xmlIcu = new XmlParser().parse(message, url, { tokenizeExpansionForms: true });
this._errors = xmlIcu.errors;
const i18nNodes = this._errors.length > 0 || xmlIcu.rootNodes.length == 0 ?
[] :
visitAll$1(this, xmlIcu.rootNodes);
return {
i18nNodes,
errors: this._errors,
};
}
visitText(text, context) {
return new Text$1(text.value, text.sourceSpan);
}
visitExpansion(icu, context) {
const caseMap = {};
visitAll$1(this, icu.cases).forEach(c => {
caseMap[c.value] = new Container(c.nodes, icu.sourceSpan);
});
return new Icu$1(icu.switchValue, icu.type, caseMap, icu.sourceSpan);
}
visitExpansionCase(icuCase, context) {
return {
value: icuCase.value,
nodes: visitAll$1(this, icuCase.expression),
};
}
visitElement(el, context) {
if (el.name === _PLACEHOLDER_TAG$3) {
const nameAttr = el.attrs.find((attr) => 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;
}
visitComment(comment, context) { }
visitAttribute(attribute, context) { }
_addError(node, message) {
this._errors.push(new I18nError(node.sourceSpan, message));
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A container for translated messages
*/
class TranslationBundle {
constructor(_i18nNodesByMsgId = {}, locale, digest, mapperFactory, missingTranslationStrategy = MissingTranslationStrategy.Warning, console) {
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`.
static load(content, url, serializer, missingTranslationStrategy, console) {
const { locale, i18nNodesByMsgId } = serializer.load(content, url);
const digestFn = (m) => serializer.digest(m);
const mapperFactory = (m) => serializer.createNameMapper(m);
return new TranslationBundle(i18nNodesByMsgId, locale, digestFn, mapperFactory, missingTranslationStrategy, console);
}
// Returns the translation as HTML nodes from the given source message.
get(srcMsg) {
const html = this._i18nToHtml.convert(srcMsg);
if (html.errors.length) {
throw new Error(html.errors.join('\n'));
}
return html.nodes;
}
has(srcMsg) {
return this.digest(srcMsg) in this._i18nNodesByMsgId;
}
}
class I18nToHtmlVisitor {
constructor(_i18nNodesByMsgId = {}, _locale, _digest, _mapperFactory, _missingTranslationStrategy, _console) {
this._i18nNodesByMsgId = _i18nNodesByMsgId;
this._locale = _locale;
this._digest = _digest;
this._mapperFactory = _mapperFactory;
this._missingTranslationStrategy = _missingTranslationStrategy;
this._console = _console;
this._contextStack = [];
this._errors = [];
}
convert(srcMsg) {
this._contextStack.length = 0;
this._errors.length = 0;
// i18n to text
const text = this._convertToText(srcMsg);
// text to html
const url = srcMsg.nodes[0].sourceSpan.start.file.url;
const html = new HtmlParser().parse(text, url, { tokenizeExpansionForms: true });
return {
nodes: html.rootNodes,
errors: [...this._errors, ...html.errors],
};
}
visitText(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);
}
visitContainer(container, context) {
return container.children.map(n => n.visit(this)).join('');
}
visitIcu(icu, context) {
const cases = Object.keys(icu.cases).map(k => `${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
const exp = this._srcMsg.placeholders.hasOwnProperty(icu.expression) ?
this._srcMsg.placeholders[icu.expression].text :
icu.expression;
return `{${exp}, ${icu.type}, ${cases.join(' ')}}`;
}
visitPlaceholder(ph, context) {
const phName = this._mapper(ph.name);
if (this._srcMsg.placeholders.hasOwnProperty(phName)) {
return this._srcMsg.placeholders[phName].text;
}
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
visitTagPlaceholder(ph, context) {
const tag = `${ph.tag}`;
const attrs = Object.keys(ph.attrs).map(name => `${name}="${ph.attrs[name]}"`).join(' ');
if (ph.isVoid) {
return `<${tag} ${attrs}/>`;
}
const children = ph.children.map((c) => 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
visitIcuPlaceholder(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.
*/
_convertToText(srcMsg) {
const id = this._digest(srcMsg);
const mapper = this._mapperFactory ? this._mapperFactory(srcMsg) : null;
let 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 = (name) => 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) {
const 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) {
const ctx = this._locale ? ` for locale "${this._locale}"` : '';
this._console.warn(`Missing translation for message "${id}"${ctx}`);
}
nodes = srcMsg.nodes;
this._mapper = (name) => name;
}
const text = nodes.map(node => node.visit(this)).join('');
const context = this._contextStack.pop();
this._srcMsg = context.msg;
this._mapper = context.mapper;
return text;
}
_addError(el, msg) {
this._errors.push(new I18nError(el.sourceSpan, msg));
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class I18NHtmlParser {
constructor(_htmlParser, translations, translationsFormat, missingTranslation = MissingTranslationStrategy.Warning, console) {
this._htmlParser = _htmlParser;
if (translations) {
const serializer = createSerializer(translationsFormat);
this._translationBundle =
TranslationBundle.load(translations, 'i18n', serializer, missingTranslation, console);
}
else {
this._translationBundle =
new TranslationBundle({}, null, digest, undefined, missingTranslation, console);
}
}
parse(source, url, options = {}) {
const interpolationConfig = options.interpolationConfig || DEFAULT_INTERPOLATION_CONFIG;
const parseResult = this._htmlParser.parse(source, url, Object.assign({ interpolationConfig }, options));
if (parseResult.errors.length) {
return new ParseTreeResult(parseResult.rootNodes, parseResult.errors);
}
return mergeTranslations(parseResult.rootNodes, this._translationBundle, interpolationConfig, [], {});
}
}
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 LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const QUOTED_KEYS = '$quoted$';
function convertValueToOutputAst(ctx, value, type = null) {
return visitValue(value, new _ValueOutputAstTransformer(ctx), type);
}
class _ValueOutputAstTransformer {
constructor(ctx) {
this.ctx = ctx;
}
visitArray(arr, type) {
const values = [];
// Note Array.map() must not be used to convert the values because it will
// skip over empty elements in arrays constructed using `new Array(length)`,
// resulting in `undefined` elements. This breaks the type guarantee that
// all values in `o.LiteralArrayExpr` are of type `o.Expression`.
// See test case in `value_util_spec.ts`.
for (let i = 0; i < arr.length; ++i) {
values.push(visitValue(arr[i], this, null /* context */));
}
return literalArr(values, type);
}
visitStringMap(map, type) {
const entries = [];
const quotedSet = new Set(map && map[QUOTED_KEYS]);
Object.keys(map).forEach(key => {
entries.push(new LiteralMapEntry(key, visitValue(map[key], this, null), quotedSet.has(key)));
});
return new LiteralMapExpr(entries, type);
}
visitPrimitive(value, type) {
return literal(value, type);
}
visitOther(value, type) {
if (value instanceof Expression) {
return value;
}
else {
return this.ctx.importExpr(value);
}
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function mapEntry$1(key, value) {
return { key, value, quoted: false };
}
class InjectableCompiler {
constructor(reflector, alwaysGenerateDef) {
this.reflector = reflector;
this.alwaysGenerateDef = alwaysGenerateDef;
this.tokenInjector = reflector.resolveExternalReference(Identifiers.Injector);
}
depsArray(deps, ctx) {
return deps.map(dep => {
let token = dep;
let args = [token];
let flags = 0 /* Default */;
if (Array.isArray(dep)) {
for (let i = 0; i < dep.length; i++) {
const 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;
}
}
}
}
let 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);
});
}
factoryFor(injectable, ctx) {
let retValue;
if (injectable.useExisting) {
retValue = importExpr(Identifiers.inject).callFn([ctx.importExpr(injectable.useExisting)]);
}
else if (injectable.useFactory) {
const 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 {
const clazz = injectable.useClass || injectable.symbol;
const 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');
}
injectableDef(injectable, ctx) {
let 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);
}
}
const def = [
mapEntry$1('factory', this.factoryFor(injectable, ctx)),
mapEntry$1('token', ctx.importExpr(injectable.type.reference)),
mapEntry$1('providedIn', providedIn),
];
return importExpr(Identifiers.ɵɵdefineInjectable).callFn([literalMap(def)]);
}
compile(injectable, ctx) {
if (this.alwaysGenerateDef || injectable.providedIn !== undefined) {
const className = identifierName(injectable.type);
const clazz = new ClassStmt(className, null, [
new ClassField('ɵprov', INFERRED_TYPE, [StmtModifier.Static], this.injectableDef(injectable, ctx)),
], [], new ClassMethod(null, [], []), []);
ctx.statements.push(clazz);
}
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const STRIP_SRC_FILE_SUFFIXES = /(\.ts|\.d\.ts|\.js|\.jsx|\.tsx)$/;
const GENERATED_FILE = /\.ngfactory\.|\.ngsummary\./;
const JIT_SUMMARY_FILE = /\.ngsummary\./;
const JIT_SUMMARY_NAME = /NgSummary$/;
function ngfactoryFilePath(filePath, forceSourceFile = false) {
const 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 = false) {
if (path.endsWith('.d.ts')) {
return [path.slice(0, -5), forceSourceFile ? '.ts' : '.d.ts'];
}
const 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) {
const fileNameWithoutSuffix = fileName.replace(STRIP_SRC_FILE_SUFFIXES, '');
return `${fileNameWithoutSuffix}.ngsummary.json`;
}
function summaryForJitFileName(fileName, forceSourceFile = false) {
const 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, '');
}
const LOWERED_SYMBOL = /\u0275\d+/;
function isLoweredSymbol(name) {
return LOWERED_SYMBOL.test(name);
}
function createLoweredSymbol(id) {
return `\u0275${id}`;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.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 = {}));
const 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(hook => 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';
default:
// This default case is not needed by TypeScript compiler, as the switch is exhaustive.
// However Closure Compiler does not understand that and reports an error in typed mode.
// The `throw new Error` below works around the problem, and the unexpected: never variable
// makes sure tsc still checks this code is unreachable.
const unexpected = hook;
throw new Error(`unexpected ${unexpected}`);
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const ERROR_COMPONENT_TYPE = 'ngComponentType';
const MISSING_NG_MODULE_METADATA_ERROR_DATA = 'ngMissingNgModuleMetadataErrorData';
function getMissingNgModuleMetadataErrorData(error) {
var _a;
return (_a = error[MISSING_NG_MODULE_METADATA_ERROR_DATA]) !== null && _a !== void 0 ? _a : null;
}
// 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.
class CompileMetadataResolver {
constructor(_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();
}
getReflector() {
return this._reflector;
}
clearCacheFor(type) {
const 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);
}
}
clearCache() {
this._directiveCache.clear();
this._nonNormalizedDirectiveCache.clear();
this._summaryCache.clear();
this._pipeCache.clear();
this._ngModuleCache.clear();
this._ngModuleOfTypes.clear();
this._directiveNormalizer.clearCache();
}
_createProxyClass(baseType, name) {
let delegate = null;
const 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 = (d) => {
delegate = d;
proxyClass.prototype = d.prototype;
};
// Make stringify work correctly
proxyClass.overriddenName = name;
return proxyClass;
}
getGeneratedClass(dirType, name) {
if (dirType instanceof StaticSymbol) {
return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), name);
}
else {
return this._createProxyClass(dirType, name);
}
}
getComponentViewClass(dirType) {
return this.getGeneratedClass(dirType, viewClassName(dirType, 0));
}
getHostComponentViewClass(dirType) {
return this.getGeneratedClass(dirType, hostViewClassName(dirType));
}
getHostComponentType(dirType) {
const name = `${identifierName({ reference: dirType })}_Host`;
if (dirType instanceof StaticSymbol) {
return this._staticSymbolCache.get(dirType.filePath, name);
}
return this._createProxyClass(dirType, name);
}
getRendererType(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 {};
}
}
getComponentFactory(selector, dirType, inputs, outputs) {
if (dirType instanceof StaticSymbol) {
return this._staticSymbolCache.get(ngfactoryFilePath(dirType.filePath), componentFactoryName(dirType));
}
else {
const hostView = this.getHostComponentViewClass(dirType);
// Note: ngContentSelectors will be filled later once the template is
// loaded.
const createComponentFactory = this._reflector.resolveExternalReference(Identifiers.createComponentFactory);
return createComponentFactory(selector, dirType, hostView, inputs, outputs, []);
}
}
initComponentFactory(factory, ngContentSelectors) {
if (!(factory instanceof StaticSymbol)) {
factory.ngContentSelectors.push(...ngContentSelectors);
}
}
_loadSummary(type, kind) {
let typeSummary = this._summaryCache.get(type);
if (!typeSummary) {
const summary = this._summaryResolver.resolveSummary(type);
typeSummary = summary ? summary.type : null;
this._summaryCache.set(type, typeSummary || null);
}
return typeSummary && typeSummary.summaryKind === kind ? typeSummary : null;
}
getHostComponentMetadata(compMeta, hostViewType) {
const 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.
const template = CssSelector.parse(compMeta.selector)[0].getMatchingElementTemplate();
const templateUrl = '';
const htmlAst = this._htmlParser.parse(template, templateUrl);
return CompileDirectiveMetadata.create({
isHost: true,
type: { reference: hostType, diDeps: [], lifecycleHooks: [] },
template: new CompileTemplateMetadata({
encapsulation: ViewEncapsulation.None,
template,
templateUrl,
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
});
}
loadDirectiveMetadata(ngModuleType, directiveType, isSync) {
if (this._directiveCache.has(directiveType)) {
return null;
}
directiveType = resolveForwardRef(directiveType);
const { annotation, metadata } = this.getNonNormalizedDirectiveMetadata(directiveType);
const createDirectiveMetadata = (templateMetadata) => {
const 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) {
const template = metadata.template;
const templateMeta = this._directiveNormalizer.normalizeTemplate({
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;
}
}
getNonNormalizedDirectiveMetadata(directiveType) {
directiveType = resolveForwardRef(directiveType);
if (!directiveType) {
return null;
}
let cacheEntry = this._nonNormalizedDirectiveCache.get(directiveType);
if (cacheEntry) {
return cacheEntry;
}
const dirMeta = this._directiveResolver.resolve(directiveType, false);
if (!dirMeta) {
return null;
}
let nonNormalizedTemplateMetadata = undefined;
if (createComponent.isTypeOf(dirMeta)) {
// component
const compMeta = dirMeta;
assertArrayOfStrings('styles', compMeta.styles);
assertArrayOfStrings('styleUrls', compMeta.styleUrls);
assertInterpolationSymbols('interpolation', compMeta.interpolation);
const 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),
});
}
let changeDetectionStrategy = null;
let viewProviders = [];
let entryComponentMetadata = [];
let selector = dirMeta.selector;
if (createComponent.isTypeOf(dirMeta)) {
// Component
const 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((type) => this._getEntryComponentMetadata(type))
.concat(entryComponentMetadata);
}
if (!selector) {
selector = this._schemaRegistry.getDefaultComponentElementName();
}
}
else {
// Directive
if (!selector) {
selector = null;
}
}
let providers = [];
if (dirMeta.providers != null) {
providers = this._getProvidersMetadata(dirMeta.providers, entryComponentMetadata, `providers for "${stringifyType(directiveType)}"`, [], directiveType);
}
let queries = [];
let viewQueries = [];
if (dirMeta.queries != null) {
queries = this._getQueriesMetadata(dirMeta.queries, false, directiveType);
viewQueries = this._getQueriesMetadata(dirMeta.queries, true, directiveType);
}
const 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, annotation: dirMeta };
this._nonNormalizedDirectiveCache.set(directiveType, cacheEntry);
return cacheEntry;
}
/**
* Gets the metadata for the given directive.
* This assumes `loadNgModuleDirectiveAndPipeMetadata` has been called first.
*/
getDirectiveMetadata(directiveType) {
const 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;
}
getDirectiveSummary(dirType) {
const 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;
}
isDirective(type) {
return !!this._loadSummary(type, CompileSummaryKind.Directive) ||
this._directiveResolver.isDirective(type);
}
isAbstractDirective(type) {
const summary = this._loadSummary(type, CompileSummaryKind.Directive);
if (summary && !summary.isComponent) {
return !summary.selector;
}
const meta = this._directiveResolver.resolve(type, false);
if (meta && !createComponent.isTypeOf(meta)) {
return !meta.selector;
}
return false;
}
isPipe(type) {
return !!this._loadSummary(type, CompileSummaryKind.Pipe) ||
this._pipeResolver.isPipe(type);
}
isNgModule(type) {
return !!this._loadSummary(type, CompileSummaryKind.NgModule) ||
this._ngModuleResolver.isNgModule(type);
}
getNgModuleSummary(moduleType, alreadyCollecting = null) {
let moduleSummary = this._loadSummary(moduleType, CompileSummaryKind.NgModule);
if (!moduleSummary) {
const 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.
*/
loadNgModuleDirectiveAndPipeMetadata(moduleType, isSync, throwIfNotFound = true) {
const ngModule = this.getNgModuleMetadata(moduleType, throwIfNotFound);
const loading = [];
if (ngModule) {
ngModule.declaredDirectives.forEach((id) => {
const promise = this.loadDirectiveMetadata(moduleType, id.reference, isSync);
if (promise) {
loading.push(promise);
}
});
ngModule.declaredPipes.forEach((id) => this._loadPipeMetadata(id.reference));
}
return Promise.all(loading);
}
getShallowModuleMetadata(moduleType) {
let compileMeta = this._shallowModuleCache.get(moduleType);
if (compileMeta) {
return compileMeta;
}
const 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;
}
getNgModuleMetadata(moduleType, throwIfNotFound = true, alreadyCollecting = null) {
moduleType = resolveForwardRef(moduleType);
let compileMeta = this._ngModuleCache.get(moduleType);
if (compileMeta) {
return compileMeta;
}
const meta = this._ngModuleResolver.resolve(moduleType, throwIfNotFound);
if (!meta) {
return null;
}
const declaredDirectives = [];
const exportedNonModuleIdentifiers = [];
const declaredPipes = [];
const importedModules = [];
const exportedModules = [];
const providers = [];
const entryComponents = [];
const bootstrapComponents = [];
const schemas = [];
if (meta.imports) {
flattenAndDedupeArray(meta.imports).forEach((importedType) => {
let importedModuleType = undefined;
if (isValidType(importedType)) {
importedModuleType = importedType;
}
else if (importedType && importedType.ngModule) {
const moduleWithProviders = importedType;
importedModuleType = moduleWithProviders.ngModule;
if (moduleWithProviders.providers) {
providers.push(...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);
const importedModuleSummary = this.getNgModuleSummary(importedModuleType, alreadyCollecting);
alreadyCollecting.delete(importedModuleType);
if (!importedModuleSummary) {
const err = syntaxError(`Unexpected ${this._getTypeDescriptor(importedType)} '${stringifyType(importedType)}' imported by the module '${stringifyType(moduleType)}'. Please add a @NgModule annotation.`);
// If possible, record additional context for this error to enable more useful
// diagnostics on the compiler side.
if (importedType instanceof StaticSymbol) {
err[MISSING_NG_MODULE_METADATA_ERROR_DATA] = {
fileName: importedType.filePath,
className: importedType.name,
};
}
this._reportError(err, 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((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);
const 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!
const transitiveModule = this._getTransitiveNgModuleMetadata(importedModules, exportedModules);
if (meta.declarations) {
flattenAndDedupeArray(meta.declarations).forEach((declaredType) => {
if (!isValidType(declaredType)) {
this._reportError(syntaxError(`Unexpected value '${stringifyType(declaredType)}' declared by the module '${stringifyType(moduleType)}'`), moduleType);
return;
}
const declaredIdentifier = this._getIdentifierMetadata(declaredType);
if (this.isDirective(declaredType)) {
if (this.isAbstractDirective(declaredType)) {
this._reportError(syntaxError(`Directive ${stringifyType(declaredType)} has no selector, please add it!`), 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;
}
});
}
const exportedDirectives = [];
const exportedPipes = [];
exportedNonModuleIdentifiers.forEach((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(...this._getProvidersMetadata(meta.providers, entryComponents, `provider for the NgModule '${stringifyType(moduleType)}'`, [], moduleType));
}
if (meta.entryComponents) {
entryComponents.push(...flattenAndDedupeArray(meta.entryComponents)
.map(type => this._getEntryComponentMetadata(type)));
}
if (meta.bootstrap) {
flattenAndDedupeArray(meta.bootstrap).forEach(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(...bootstrapComponents.map(type => this._getEntryComponentMetadata(type.reference)));
if (meta.schemas) {
schemas.push(...flattenAndDedupeArray(meta.schemas));
}
compileMeta = new CompileNgModuleMetadata({
type: this._getTypeMetadata(moduleType),
providers,
entryComponents,
bootstrapComponents,
schemas,
declaredDirectives,
exportedDirectives,
declaredPipes,
exportedPipes,
importedModules,
exportedModules,
transitiveModule,
id: meta.id || null,
});
entryComponents.forEach((id) => transitiveModule.addEntryComponent(id));
providers.forEach((provider) => transitiveModule.addProvider(provider, compileMeta.type));
transitiveModule.addModule(compileMeta.type);
this._ngModuleCache.set(moduleType, compileMeta);
return compileMeta;
}
_checkSelfImport(moduleType, importedModuleType) {
if (moduleType === importedModuleType) {
this._reportError(syntaxError(`'${stringifyType(moduleType)}' module can't import itself`), moduleType);
return true;
}
return false;
}
_getTypeDescriptor(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';
}
_addTypeToModule(type, moduleType) {
const 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);
}
_getTransitiveNgModuleMetadata(importedModules, exportedModules) {
// collect `providers` / `entryComponents` from all imported and all exported modules
const result = new TransitiveCompileNgModuleMetadata();
const modulesByToken = new Map();
importedModules.concat(exportedModules).forEach((modSummary) => {
modSummary.modules.forEach((mod) => result.addModule(mod));
modSummary.entryComponents.forEach((comp) => result.addEntryComponent(comp));
const addedTokens = new Set();
modSummary.providers.forEach((entry) => {
const tokenRef = tokenReference(entry.provider.token);
let prevModules = modulesByToken.get(tokenRef);
if (!prevModules) {
prevModules = new Set();
modulesByToken.set(tokenRef, prevModules);
}
const 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((modSummary) => {
modSummary.exportedDirectives.forEach((id) => result.addExportedDirective(id));
modSummary.exportedPipes.forEach((id) => result.addExportedPipe(id));
});
importedModules.forEach((modSummary) => {
modSummary.exportedDirectives.forEach((id) => result.addDirective(id));
modSummary.exportedPipes.forEach((id) => result.addPipe(id));
});
return result;
}
_getIdentifierMetadata(type) {
type = resolveForwardRef(type);
return { reference: type };
}
isInjectable(type) {
const annotations = this._reflector.tryAnnotations(type);
return annotations.some(ann => createInjectable.isTypeOf(ann));
}
getInjectableSummary(type) {
return {
summaryKind: CompileSummaryKind.Injectable,
type: this._getTypeMetadata(type, null, false)
};
}
getInjectableMetadata(type, dependencies = null, throwOnUnknownDeps = true) {
const typeSummary = this._loadSummary(type, CompileSummaryKind.Injectable);
const typeMetadata = typeSummary ?
typeSummary.type :
this._getTypeMetadata(type, dependencies, throwOnUnknownDeps);
const annotations = this._reflector.annotations(type).filter(ann => createInjectable.isTypeOf(ann));
if (annotations.length === 0) {
return null;
}
const 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,
};
}
_getTypeMetadata(type, dependencies = null, throwOnUnknownDeps = true) {
const identifier = this._getIdentifierMetadata(type);
return {
reference: identifier.reference,
diDeps: this._getDependenciesMetadata(identifier.reference, dependencies, throwOnUnknownDeps),
lifecycleHooks: getAllLifecycleHooks(this._reflector, identifier.reference),
};
}
_getFactoryMetadata(factory, 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.
*/
getPipeMetadata(pipeType) {
const 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;
}
getPipeSummary(pipeType) {
const 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;
}
getOrLoadPipeMetadata(pipeType) {
let pipeMeta = this._pipeCache.get(pipeType);
if (!pipeMeta) {
pipeMeta = this._loadPipeMetadata(pipeType);
}
return pipeMeta;
}
_loadPipeMetadata(pipeType) {
pipeType = resolveForwardRef(pipeType);
const pipeAnnotation = this._pipeResolver.resolve(pipeType);
const 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;
}
_getDependenciesMetadata(typeOrFunc, dependencies, throwOnUnknownDeps = true) {
let hasUnknownDeps = false;
const params = dependencies || this._reflector.parameters(typeOrFunc) || [];
const dependenciesMetadata = params.map((param) => {
let isAttribute = false;
let isHost = false;
let isSelf = false;
let isSkipSelf = false;
let isOptional = false;
let token = null;
if (Array.isArray(param)) {
param.forEach((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 {};
}
return {
isAttribute,
isHost,
isSelf,
isSkipSelf,
isOptional,
token: this._getTokenMetadata(token)
};
});
if (hasUnknownDeps) {
const depsTokens = dependenciesMetadata.map((dep) => dep.token ? stringifyType(dep.token) : '?').join(', ');
const message = `Can't resolve all parameters for ${stringifyType(typeOrFunc)}: (${depsTokens}).`;
if (throwOnUnknownDeps || this._config.strictInjectionParameters) {
this._reportError(syntaxError(message), typeOrFunc);
}
}
return dependenciesMetadata;
}
_getTokenMetadata(token) {
token = resolveForwardRef(token);
let compileToken;
if (typeof token === 'string') {
compileToken = { value: token };
}
else {
compileToken = { identifier: { reference: token } };
}
return compileToken;
}
_getProvidersMetadata(providers, targetEntryComponents, debugInfo, compileProviders = [], type) {
providers.forEach((provider, providerIdx) => {
if (Array.isArray(provider)) {
this._getProvidersMetadata(provider, targetEntryComponents, debugInfo, compileProviders);
}
else {
provider = resolveForwardRef(provider);
let 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 {
const providersInfo = providers
.reduce((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(...this._getEntryComponentsFromProvider(providerMeta, type));
}
else {
compileProviders.push(this.getProviderMetadata(providerMeta));
}
}
});
return compileProviders;
}
_validateProvider(provider) {
if (provider.hasOwnProperty('useClass') && provider.useClass == null) {
this._reportError(syntaxError(`Invalid provider for ${stringifyType(provider.provide)}. useClass cannot be ${provider.useClass}.
Usually it happens when:
1. There's a circular dependency (might be caused by using index.ts (barrel) files).
2. Class was used before it was declared. Use forwardRef in this case.`));
}
}
_getEntryComponentsFromProvider(provider, type) {
const components = [];
const 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((identifier) => {
const entry = this._getEntryComponentMetadata(identifier.reference, false);
if (entry) {
components.push(entry);
}
});
return components;
}
_getEntryComponentMetadata(dirType, throwIfNotFound = true) {
const dirMeta = this.getNonNormalizedDirectiveMetadata(dirType);
if (dirMeta && dirMeta.metadata.isComponent) {
return { componentType: dirType, componentFactory: dirMeta.metadata.componentFactory };
}
const 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;
}
_getInjectableTypeMetadata(type, dependencies = null) {
const typeSummary = this._loadSummary(type, CompileSummaryKind.Injectable);
if (typeSummary) {
return typeSummary.type;
}
return this._getTypeMetadata(type, dependencies);
}
getProviderMetadata(provider) {
let compileDeps = undefined;
let compileTypeMetadata = null;
let compileFactoryMetadata = null;
let 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
};
}
_getQueriesMetadata(queries, isViewQuery, directiveType) {
const res = [];
Object.keys(queries).forEach((propertyName) => {
const query = queries[propertyName];
if (query.isViewQuery === isViewQuery) {
res.push(this._getQueryMetadata(query, propertyName, directiveType));
}
});
return res;
}
_queryVarBindings(selector) {
return selector.split(/\s*,\s*/);
}
_getQueryMetadata(q, propertyName, typeOrFunc) {
let selectors;
if (typeof q.selector === 'string') {
selectors =
this._queryVarBindings(q.selector).map(varName => 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,
first: q.first,
descendants: q.descendants,
emitDistinctChangesOnly: q.emitDistinctChangesOnly,
propertyName,
read: q.read ? this._getTokenMetadata(q.read) : null,
static: q.static
};
}
_reportError(error, type, otherType) {
if (this._errorCollector) {
this._errorCollector(error, type);
if (otherType) {
this._errorCollector(error, otherType);
}
}
else {
throw error;
}
}
}
function flattenArray(tree, out = []) {
if (tree) {
for (let i = 0; i < tree.length; i++) {
const 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);
}
class _CompileValueConverter extends ValueTransformer {
visitOther(value, targetIdentifiers) {
targetIdentifiers.push({ reference: value });
}
}
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) {
const error = Error(`Can't compile synchronously as ${stringify(compType)} is still being loaded!`);
error[ERROR_COMPONENT_TYPE] = compType;
return error;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function providerDef(ctx, providerAst) {
let flags = 0 /* None */;
if (!providerAst.eager) {
flags |= 4096 /* LazyProvider */;
}
if (providerAst.providerType === ProviderAstType.PrivateService) {
flags |= 8192 /* PrivateProvider */;
}
if (providerAst.isModule) {
flags |= 1073741824 /* TypeModuleProvider */;
}
providerAst.lifecycleHooks.forEach((lifecycleHook) => {
// for regular providers, we only support ngOnDestroy
if (lifecycleHook === LifecycleHooks.OnDestroy ||
providerAst.providerType === ProviderAstType.Directive ||
providerAst.providerType === ProviderAstType.Component) {
flags |= lifecycleHookToNodeFlag(lifecycleHook);
}
});
const { providerExpr, flags: providerFlags, depsExpr } = providerAst.multiProvider ?
multiProviderDef(ctx, flags, providerAst.providers) :
singleProviderDef(ctx, flags, providerAst.providerType, providerAst.providers[0]);
return {
providerExpr,
flags: providerFlags,
depsExpr,
tokenExpr: tokenExpr(ctx, providerAst.token),
};
}
function multiProviderDef(ctx, flags, providers) {
const allDepDefs = [];
const allParams = [];
const exprs = providers.map((provider, providerIndex) => {
let expr;
if (provider.useClass) {
const depExprs = convertDeps(providerIndex, provider.deps || provider.useClass.diDeps);
expr = ctx.importExpr(provider.useClass.reference).instantiate(depExprs);
}
else if (provider.useFactory) {
const depExprs = convertDeps(providerIndex, provider.deps || provider.useFactory.diDeps);
expr = ctx.importExpr(provider.useFactory.reference).callFn(depExprs);
}
else if (provider.useExisting) {
const depExprs = convertDeps(providerIndex, [{ token: provider.useExisting }]);
expr = depExprs[0];
}
else {
expr = convertValueToOutputAst(ctx, provider.useValue);
}
return expr;
});
const providerExpr = fn(allParams, [new ReturnStatement(literalArr(exprs))], INFERRED_TYPE);
return {
providerExpr,
flags: flags | 1024 /* TypeFactoryProvider */,
depsExpr: literalArr(allDepDefs)
};
function convertDeps(providerIndex, deps) {
return deps.map((dep, depIndex) => {
const 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) {
let providerExpr;
let 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 = [];
}
}
const depsExpr = literalArr(deps.map(dep => depDef(ctx, dep)));
return { providerExpr, flags, 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
const expr = dep.isValue ? convertValueToOutputAst(ctx, dep.value) : tokenExpr(ctx, dep.token);
let flags = 0 /* None */;
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) {
let nodeFlag = 0 /* None */;
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) {
const entryComponentFactories = entryComponents.map((entryComponent) => ctx.importExpr(entryComponent.componentFactory));
const token = createTokenForExternalReference(reflector, Identifiers.ComponentFactoryResolver);
const classMeta = {
diDeps: [
{ isValue: true, value: literalArr(entryComponentFactories) },
{ token: token, isSkipSelf: true, isOptional: true },
{ token: createTokenForExternalReference(reflector, Identifiers.NgModuleRef) },
],
lifecycleHooks: [],
reference: reflector.resolveExternalReference(Identifiers.CodegenComponentFactoryResolver)
};
const { providerExpr, flags: providerFlags, depsExpr } = singleProviderDef(ctx, flags, ProviderAstType.PrivateService, {
token,
multi: false,
useClass: classMeta,
});
return { providerExpr, flags: providerFlags, depsExpr, tokenExpr: tokenExpr(ctx, token) };
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class NgModuleCompileResult {
constructor(ngModuleFactoryVar) {
this.ngModuleFactoryVar = ngModuleFactoryVar;
}
}
const LOG_VAR = variable('_l');
class NgModuleCompiler {
constructor(reflector) {
this.reflector = reflector;
}
compile(ctx, ngModuleMeta, extraProviders) {
const sourceSpan = typeSourceSpan('NgModule', ngModuleMeta.type);
const entryComponentFactories = ngModuleMeta.transitiveModule.entryComponents;
const bootstrapComponents = ngModuleMeta.bootstrapComponents;
const providerParser = new NgModuleProviderAnalyzer(this.reflector, ngModuleMeta, extraProviders, sourceSpan);
const providerDefs = [componentFactoryResolverProviderDef(this.reflector, ctx, 0 /* None */, entryComponentFactories)]
.concat(providerParser.parse().map((provider) => providerDef(ctx, provider)))
.map(({ providerExpr, depsExpr, flags, tokenExpr }) => {
return importExpr(Identifiers.moduleProviderDef).callFn([
literal(flags), tokenExpr, providerExpr, depsExpr
]);
});
const ngModuleDef = importExpr(Identifiers.moduleDef).callFn([literalArr(providerDefs)]);
const ngModuleDefFactory = fn([new FnParam(LOG_VAR.name)], [new ReturnStatement(ngModuleDef)], INFERRED_TYPE);
const ngModuleFactoryVar = `${identifierName(ngModuleMeta.type)}NgFactory`;
this._createNgModuleFactory(ctx, ngModuleMeta.type.reference, importExpr(Identifiers.createModuleFactory).callFn([
ctx.importExpr(ngModuleMeta.type.reference),
literalArr(bootstrapComponents.map(id => ctx.importExpr(id.reference))),
ngModuleDefFactory
]));
if (ngModuleMeta.id) {
const id = typeof ngModuleMeta.id === 'string' ? literal(ngModuleMeta.id) :
ctx.importExpr(ngModuleMeta.id);
const registerFactoryStmt = importExpr(Identifiers.RegisterModuleFactoryFn)
.callFn([id, variable(ngModuleFactoryVar)])
.toStmt();
ctx.statements.push(registerFactoryStmt);
}
return new NgModuleCompileResult(ngModuleFactoryVar);
}
createStub(ctx, ngModuleReference) {
this._createNgModuleFactory(ctx, ngModuleReference, NULL_EXPR);
}
_createNgModuleFactory(ctx, reference, value) {
const ngModuleFactoryVar = `${identifierName({ reference: reference })}NgFactory`;
const ngModuleFactoryStmt = variable(ngModuleFactoryVar)
.set(value)
.toDeclStmt(importType(Identifiers.NgModuleFactory, [expressionType(ctx.importExpr(reference))], [TypeModifier.Const]), [StmtModifier.Final, StmtModifier.Exported]);
ctx.statements.push(ngModuleFactoryStmt);
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Resolves types to {@link NgModule}.
*/
class NgModuleResolver {
constructor(_reflector) {
this._reflector = _reflector;
}
isNgModule(type) {
return this._reflector.annotations(type).some(createNgModule.isTypeOf);
}
resolve(type, throwIfNotFound = true) {
const 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;
}
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function debugOutputAstAsTypeScript(ast) {
const converter = new _TsEmitterVisitor();
const ctx = EmitterVisitorContext.createRoot();
const asts = Array.isArray(ast) ? ast : [ast];
asts.forEach((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();
}
class TypeScriptEmitter {
emitStatementsAndContext(genFilePath, stmts, preamble = '', emitSourceMaps = true, referenceFilter, importFilter) {
const converter = new _TsEmitterVisitor(referenceFilter, importFilter);
const ctx = EmitterVisitorContext.createRoot();
converter.visitAllStatements(stmts, ctx);
const preambleLines = preamble ? preamble.split('\n') : [];
converter.reexports.forEach((reexports, exportedModuleName) => {
const reexportsCode = reexports.map(reexport => `${reexport.name} as ${reexport.as}`).join(',');
preambleLines.push(`export {${reexportsCode}} from '${exportedModuleName}';`);
});
converter.importsWithPrefixes.forEach((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}';`);
});
const sm = emitSourceMaps ?
ctx.toSourceMapGenerator(genFilePath, preambleLines.length).toJsComment() :
'';
const lines = [...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 };
}
emitStatements(genFilePath, stmts, preamble = '') {
return this.emitStatementsAndContext(genFilePath, stmts, preamble).sourceText;
}
}
class _TsEmitterVisitor extends AbstractEmitterVisitor {
constructor(referenceFilter, importFilter) {
super(false);
this.referenceFilter = referenceFilter;
this.importFilter = importFilter;
this.typeExpression = 0;
this.importsWithPrefixes = new Map();
this.reexports = new Map();
}
visitType(t, ctx, defaultType = 'any') {
if (t) {
this.typeExpression++;
t.visitType(this, ctx);
this.typeExpression--;
}
else {
ctx.print(null, defaultType);
}
}
visitLiteralExpr(ast, ctx) {
const value = ast.value;
if (value == null && ast.type != INFERRED_TYPE) {
ctx.print(ast, `(${value} as any)`);
return null;
}
return super.visitLiteralExpr(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
visitLiteralArrayExpr(ast, ctx) {
if (ast.entries.length === 0) {
ctx.print(ast, '(');
}
const result = super.visitLiteralArrayExpr(ast, ctx);
if (ast.entries.length === 0) {
ctx.print(ast, ' as any[])');
}
return result;
}
visitExternalExpr(ast, ctx) {
this._visitIdentifier(ast.value, ast.typeParams, ctx);
return null;
}
visitAssertNotNullExpr(ast, ctx) {
const result = super.visitAssertNotNullExpr(ast, ctx);
ctx.print(ast, '!');
return result;
}
visitDeclareVarStmt(stmt, ctx) {
if (stmt.hasModifier(StmtModifier.Exported) && stmt.value instanceof ExternalExpr &&
!stmt.type) {
// check for a reexport
const { name, moduleName } = stmt.value.value;
if (moduleName) {
let reexports = this.reexports.get(moduleName);
if (!reexports) {
reexports = [];
this.reexports.set(moduleName, reexports);
}
reexports.push({ name: name, 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;
}
visitWrappedNodeExpr(ast, ctx) {
throw new Error('Cannot visit a WrappedNodeExpr when outputting Typescript.');
}
visitCastExpr(ast, ctx) {
ctx.print(ast, `(<`);
ast.type.visitType(this, ctx);
ctx.print(ast, `>`);
ast.value.visitExpression(this, ctx);
ctx.print(ast, `)`);
return null;
}
visitInstantiateExpr(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;
}
visitDeclareClassStmt(stmt, ctx) {
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((field) => this._visitClassField(field, ctx));
if (stmt.constructorMethod != null) {
this._visitClassConstructor(stmt, ctx);
}
stmt.getters.forEach((getter) => this._visitClassGetter(getter, ctx));
stmt.methods.forEach((method) => this._visitClassMethod(method, ctx));
ctx.decIndent();
ctx.println(stmt, `}`);
ctx.popClass();
return null;
}
_visitClassField(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, `;`);
}
_visitClassGetter(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, `}`);
}
_visitClassConstructor(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, `}`);
}
_visitClassMethod(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, `}`);
}
visitFunctionExpr(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;
}
visitDeclareFunctionStmt(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;
}
visitTryCatchStmt(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();
const 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;
}
visitBuiltinType(type, ctx) {
let 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;
case BuiltinTypeName.None:
typeStr = 'never';
break;
default:
throw new Error(`Unsupported builtin type ${type.name}`);
}
ctx.print(null, typeStr);
return null;
}
visitExpressionType(ast, ctx) {
ast.value.visitExpression(this, ctx);
if (ast.typeParams !== null) {
ctx.print(null, '<');
this.visitAllObjects(type => this.visitType(type, ctx), ast.typeParams, ctx, ',');
ctx.print(null, '>');
}
return null;
}
visitArrayType(type, ctx) {
this.visitType(type.of, ctx);
ctx.print(null, `[]`);
return null;
}
visitMapType(type, ctx) {
ctx.print(null, `{[key: string]:`);
this.visitType(type.valueType, ctx);
ctx.print(null, `}`);
return null;
}
getBuiltinMethodName(method) {
let 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;
}
_visitParams(params, ctx) {
this.visitAllObjects(param => {
ctx.print(null, param.name);
this._printColonType(param.type, ctx);
}, params, ctx, ',');
}
_visitIdentifier(value, typeParams, ctx) {
const { name, moduleName } = value;
if (this.referenceFilter && this.referenceFilter(value)) {
ctx.print(null, '(null as any)');
return;
}
if (moduleName && (!this.importFilter || !this.importFilter(value))) {
let 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.
const suppliedParameters = typeParams || [];
if (suppliedParameters.length > 0) {
ctx.print(null, `<`);
this.visitAllObjects(type => type.visitType(this, ctx), typeParams, ctx, ',');
ctx.print(null, `>`);
}
}
}
_printColonType(type, ctx, defaultType) {
if (type !== INFERRED_TYPE) {
ctx.print(null, ':');
this.visitType(type, ctx, defaultType);
}
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Resolve a `Type` for {@link Pipe}.
*
* This interface can be overridden by the application developer to create custom behavior.
*
* See {@link Compiler}
*/
class PipeResolver {
constructor(_reflector) {
this._reflector = _reflector;
}
isPipe(type) {
const typeMetadata = this._reflector.annotations(resolveForwardRef(type));
return typeMetadata && typeMetadata.some(createPipe.isTypeOf);
}
/**
* Return {@link Pipe} for a given `Type`.
*/
resolve(type, throwIfNotFound = true) {
const metas = this._reflector.annotations(resolveForwardRef(type));
if (metas) {
const annotation = findLast(metas, createPipe.isTypeOf);
if (annotation) {
return annotation;
}
}
if (throwIfNotFound) {
throw new Error(`No Pipe decorator found on ${stringify(type)}`);
}
return null;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Generates code that is used to type check templates.
*/
class TypeCheckCompiler {
constructor(options, reflector) {
this.options = options;
this.reflector = reflector;
}
/**
* Important notes:
* - This must not produce new `import` statements, but only refer to types outside
* of the file via the variables provided via externalReferenceVars.
* This allows Typescript to reuse the old program's structure as no imports have changed.
* - This must not produce any exports, as this would pollute the .d.ts file
* and also violate the point above.
*/
compileComponent(componentId, component, template, usedPipes, externalReferenceVars, ctx) {
const pipes = new Map();
usedPipes.forEach(p => pipes.set(p.name, p.type.reference));
let embeddedViewCount = 0;
const viewBuilderFactory = (parent, guards) => {
const embeddedViewIndex = embeddedViewCount++;
return new ViewBuilder(this.options, this.reflector, externalReferenceVars, parent, component.type.reference, component.isHost, embeddedViewIndex, pipes, guards, ctx, viewBuilderFactory);
};
const visitor = viewBuilderFactory(null, []);
visitor.visitAll([], template);
return visitor.build(componentId);
}
}
const DYNAMIC_VAR_NAME = '_any';
class TypeCheckLocalResolver {
notifyImplicitReceiverUse() { }
getLocal(name) {
if (name === EventHandlerVars.event.name) {
// References to the event should not be type-checked.
// TODO(chuckj): determine a better type for the event.
return variable(DYNAMIC_VAR_NAME);
}
return null;
}
}
const defaultResolver = new TypeCheckLocalResolver();
class ViewBuilder {
constructor(options, reflector, externalReferenceVars, parent, component, isHostComponent, embeddedViewIndex, pipes, guards, ctx, viewBuilderFactory) {
this.options = options;
this.reflector = reflector;
this.externalReferenceVars = externalReferenceVars;
this.parent = parent;
this.component = component;
this.isHostComponent = isHostComponent;
this.embeddedViewIndex = embeddedViewIndex;
this.pipes = pipes;
this.guards = guards;
this.ctx = ctx;
this.viewBuilderFactory = viewBuilderFactory;
this.refOutputVars = new Map();
this.variables = [];
this.children = [];
this.updates = [];
this.actions = [];
}
getOutputVar(type) {
let varName;
if (type === this.component && this.isHostComponent) {
varName = DYNAMIC_VAR_NAME;
}
else if (type instanceof StaticSymbol) {
varName = this.externalReferenceVars.get(type);
}
else {
varName = DYNAMIC_VAR_NAME;
}
if (!varName) {
throw new Error(`Illegal State: referring to a type without a variable ${JSON.stringify(type)}`);
}
return varName;
}
getTypeGuardExpressions(ast) {
const result = [...this.guards];
for (let directive of ast.directives) {
for (let input of directive.inputs) {
const guard = directive.directive.guards[input.directiveName];
if (guard) {
const useIf = guard === 'UseIf';
result.push({
guard,
useIf,
expression: {
context: this.component,
value: input.value,
sourceSpan: input.sourceSpan,
},
});
}
}
}
return result;
}
visitAll(variables, astNodes) {
this.variables = variables;
templateVisitAll(this, astNodes);
}
build(componentId, targetStatements = []) {
this.children.forEach((child) => child.build(componentId, targetStatements));
let viewStmts = [variable(DYNAMIC_VAR_NAME).set(NULL_EXPR).toDeclStmt(DYNAMIC_TYPE)];
let bindingCount = 0;
this.updates.forEach((expression) => {
const { sourceSpan, context, value } = this.preprocessUpdateExpression(expression);
const bindingId = `${bindingCount++}`;
const nameResolver = context === this.component ? this : defaultResolver;
const { stmts, currValExpr } = convertPropertyBinding(nameResolver, variable(this.getOutputVar(context)), value, bindingId, BindingForm.General);
stmts.push(new ExpressionStatement(currValExpr));
viewStmts.push(...stmts.map((stmt) => applySourceSpanToStatementIfNeeded(stmt, sourceSpan)));
});
this.actions.forEach(({ sourceSpan, context, value }) => {
const bindingId = `${bindingCount++}`;
const nameResolver = context === this.component ? this : defaultResolver;
const { stmts } = convertActionBinding(nameResolver, variable(this.getOutputVar(context)), value, bindingId);
viewStmts.push(...stmts.map((stmt) => applySourceSpanToStatementIfNeeded(stmt, sourceSpan)));
});
if (this.guards.length) {
let guardExpression = undefined;
for (const guard of this.guards) {
const { context, value } = this.preprocessUpdateExpression(guard.expression);
const bindingId = `${bindingCount++}`;
const nameResolver = context === this.component ? this : defaultResolver;
// We only support support simple expressions and ignore others as they
// are unlikely to affect type narrowing.
const { stmts, currValExpr } = convertPropertyBinding(nameResolver, variable(this.getOutputVar(context)), value, bindingId, BindingForm.TrySimple);
if (stmts.length == 0) {
const guardClause = guard.useIf ? currValExpr : this.ctx.importExpr(guard.guard).callFn([currValExpr]);
guardExpression = guardExpression ? guardExpression.and(guardClause) : guardClause;
}
}
if (guardExpression) {
viewStmts = [new IfStmt(guardExpression, viewStmts)];
}
}
const viewName = `_View_${componentId}_${this.embeddedViewIndex}`;
const viewFactory = new DeclareFunctionStmt(viewName, [], viewStmts);
targetStatements.push(viewFactory);
return targetStatements;
}
visitBoundText(ast, context) {
const astWithSource = ast.value;
const inter = astWithSource.ast;
inter.expressions.forEach((expr) => this.updates.push({ context: this.component, value: expr, sourceSpan: ast.sourceSpan }));
}
visitEmbeddedTemplate(ast, context) {
this.visitElementOrTemplate(ast);
// Note: The old view compiler used to use an `any` type
// for the context in any embedded view.
// We keep this behaivor behind a flag for now.
if (this.options.fullTemplateTypeCheck) {
// Find any applicable type guards. For example, NgIf has a type guard on ngIf
// (see NgIf.ngIfTypeGuard) that can be used to indicate that a template is only
// stamped out if ngIf is truthy so any bindings in the template can assume that,
// if a nullable type is used for ngIf, that expression is not null or undefined.
const guards = this.getTypeGuardExpressions(ast);
const childVisitor = this.viewBuilderFactory(this, guards);
this.children.push(childVisitor);
childVisitor.visitAll(ast.variables, ast.children);
}
}
visitElement(ast, context) {
this.visitElementOrTemplate(ast);
let inputDefs = [];
let updateRendererExpressions = [];
let outputDefs = [];
ast.inputs.forEach((inputAst) => {
this.updates.push({ context: this.component, value: inputAst.value, sourceSpan: inputAst.sourceSpan });
});
templateVisitAll(this, ast.children);
}
visitElementOrTemplate(ast) {
ast.directives.forEach((dirAst) => {
this.visitDirective(dirAst);
});
ast.references.forEach((ref) => {
let outputVarType = null;
// Note: The old view compiler used to use an `any` type
// for directives exposed via `exportAs`.
// We keep this behaivor behind a flag for now.
if (ref.value && ref.value.identifier && this.options.fullTemplateTypeCheck) {
outputVarType = ref.value.identifier.reference;
}
else {
outputVarType = BuiltinTypeName.Dynamic;
}
this.refOutputVars.set(ref.name, outputVarType);
});
ast.outputs.forEach((outputAst) => {
this.actions.push({ context: this.component, value: outputAst.handler, sourceSpan: outputAst.sourceSpan });
});
}
visitDirective(dirAst) {
const dirType = dirAst.directive.type.reference;
dirAst.inputs.forEach((input) => this.updates.push({ context: this.component, value: input.value, sourceSpan: input.sourceSpan }));
// Note: The old view compiler used to use an `any` type
// for expressions in host properties / events.
// We keep this behaivor behind a flag for now.
if (this.options.fullTemplateTypeCheck) {
dirAst.hostProperties.forEach((inputAst) => this.updates.push({ context: dirType, value: inputAst.value, sourceSpan: inputAst.sourceSpan }));
dirAst.hostEvents.forEach((hostEventAst) => this.actions.push({
context: dirType,
value: hostEventAst.handler,
sourceSpan: hostEventAst.sourceSpan
}));
}
}
notifyImplicitReceiverUse() { }
getLocal(name) {
if (name == EventHandlerVars.event.name) {
return variable(this.getOutputVar(BuiltinTypeName.Dynamic));
}
for (let currBuilder = this; currBuilder; currBuilder = currBuilder.parent) {
let outputVarType;
// check references
outputVarType = currBuilder.refOutputVars.get(name);
if (outputVarType == null) {
// check variables
const varAst = currBuilder.variables.find((varAst) => varAst.name === name);
if (varAst) {
outputVarType = BuiltinTypeName.Dynamic;
}
}
if (outputVarType != null) {
return variable(this.getOutputVar(outputVarType));
}
}
return null;
}
pipeOutputVar(name) {
const pipe = this.pipes.get(name);
if (!pipe) {
throw new Error(`Illegal State: Could not find pipe ${name} in template of ${this.component}`);
}
return this.getOutputVar(pipe);
}
preprocessUpdateExpression(expression) {
return {
sourceSpan: expression.sourceSpan,
context: expression.context,
value: convertPropertyBindingBuiltins({
createLiteralArrayConverter: (argCount) => (args) => {
const arr = literalArr(args);
// Note: The old view compiler used to use an `any` type
// for arrays.
return this.options.fullTemplateTypeCheck ? arr : arr.cast(DYNAMIC_TYPE);
},
createLiteralMapConverter: (keys) => (values) => {
const entries = keys.map((k, i) => ({
key: k.key,
value: values[i],
quoted: k.quoted,
}));
const map = literalMap(entries);
// Note: The old view compiler used to use an `any` type
// for maps.
return this.options.fullTemplateTypeCheck ? map : map.cast(DYNAMIC_TYPE);
},
createPipeConverter: (name, argCount) => (args) => {
// Note: The old view compiler used to use an `any` type
// for pipes.
const pipeExpr = this.options.fullTemplateTypeCheck ?
variable(this.pipeOutputVar(name)) :
variable(this.getOutputVar(BuiltinTypeName.Dynamic));
return pipeExpr.callMethod('transform', args);
},
}, expression.value)
};
}
visitNgContent(ast, context) { }
visitText(ast, context) { }
visitDirectiveProperty(ast, context) { }
visitReference(ast, context) { }
visitVariable(ast, context) { }
visitEvent(ast, context) { }
visitElementProperty(ast, context) { }
visitAttr(ast, context) { }
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const CLASS_ATTR$1 = 'class';
const STYLE_ATTR = 'style';
const IMPLICIT_TEMPLATE_VAR = '\$implicit';
class ViewCompileResult {
constructor(viewClassVar, rendererTypeVar) {
this.viewClassVar = viewClassVar;
this.rendererTypeVar = rendererTypeVar;
}
}
class ViewCompiler {
constructor(_reflector) {
this._reflector = _reflector;
}
compileComponent(outputCtx, component, template, styles, usedPipes) {
let embeddedViewCount = 0;
let renderComponentVarName = undefined;
if (!component.isHost) {
const template = component.template;
const customRenderData = [];
if (template.animations && template.animations.length) {
customRenderData.push(new LiteralMapEntry('animation', convertValueToOutputAst(outputCtx, template.animations), true));
}
const renderComponentVar = variable(rendererTypeName(component.type.reference));
renderComponentVarName = renderComponentVar.name;
outputCtx.statements.push(renderComponentVar
.set(importExpr(Identifiers.createRendererType2).callFn([new LiteralMapExpr([
new LiteralMapEntry('encapsulation', literal(template.encapsulation), false),
new LiteralMapEntry('styles', styles, false),
new LiteralMapEntry('data', new LiteralMapExpr(customRenderData), false)
])]))
.toDeclStmt(importType(Identifiers.RendererType2), [StmtModifier.Final, StmtModifier.Exported]));
}
const viewBuilderFactory = (parent) => {
const embeddedViewIndex = embeddedViewCount++;
return new ViewBuilder$1(this._reflector, outputCtx, parent, component, embeddedViewIndex, usedPipes, viewBuilderFactory);
};
const visitor = viewBuilderFactory(null);
visitor.visitAll([], template);
outputCtx.statements.push(...visitor.build());
return new ViewCompileResult(visitor.viewName, renderComponentVarName);
}
}
const LOG_VAR$1 = variable('_l');
const VIEW_VAR = variable('_v');
const CHECK_VAR = variable('_ck');
const COMP_VAR = variable('_co');
const EVENT_NAME_VAR = variable('en');
const ALLOW_DEFAULT_VAR = variable(`ad`);
class ViewBuilder$1 {
constructor(reflector, outputCtx, parent, component, embeddedViewIndex, usedPipes, viewBuilderFactory) {
this.reflector = reflector;
this.outputCtx = outputCtx;
this.parent = parent;
this.component = component;
this.embeddedViewIndex = embeddedViewIndex;
this.usedPipes = usedPipes;
this.viewBuilderFactory = viewBuilderFactory;
this.nodes = [];
this.purePipeNodeIndices = Object.create(null);
// Need Object.create so that we don't have builtin values...
this.refNodeIndices = Object.create(null);
this.variables = [];
this.children = [];
// TODO(tbosch): The old view compiler used to use an `any` type
// for the context in any embedded view. We keep this behaivor for now
// to be able to introduce the new view compiler without too many errors.
this.compType = this.embeddedViewIndex > 0 ?
DYNAMIC_TYPE :
expressionType(outputCtx.importExpr(this.component.type.reference));
this.viewName = viewClassName(this.component.type.reference, this.embeddedViewIndex);
}
visitAll(variables, astNodes) {
this.variables = variables;
// create the pipes for the pure pipes immediately, so that we know their indices.
if (!this.parent) {
this.usedPipes.forEach((pipe) => {
if (pipe.pure) {
this.purePipeNodeIndices[pipe.name] = this._createPipe(null, pipe);
}
});
}
if (!this.parent) {
this.component.viewQueries.forEach((query, queryIndex) => {
// Note: queries start with id 1 so we can use the number in a Bloom filter!
const queryId = queryIndex + 1;
const bindingType = query.first ? 0 /* First */ : 1 /* All */;
const flags = 134217728 /* TypeViewQuery */ | calcQueryFlags(query);
this.nodes.push(() => ({
sourceSpan: null,
nodeFlags: flags,
nodeDef: importExpr(Identifiers.queryDef).callFn([
literal(flags), literal(queryId),
new LiteralMapExpr([new LiteralMapEntry(query.propertyName, literal(bindingType), false)])
])
}));
});
}
templateVisitAll(this, astNodes);
if (this.parent && (astNodes.length === 0 || needsAdditionalRootNode(astNodes))) {
// if the view is an embedded view, then we need to add an additional root node in some cases
this.nodes.push(() => ({
sourceSpan: null,
nodeFlags: 1 /* TypeElement */,
nodeDef: importExpr(Identifiers.anchorDef).callFn([
literal(0 /* None */), NULL_EXPR, NULL_EXPR, literal(0)
])
}));
}
}
build(targetStatements = []) {
this.children.forEach((child) => child.build(targetStatements));
const { updateRendererStmts, updateDirectivesStmts, nodeDefExprs } = this._createNodeExpressions();
const updateRendererFn = this._createUpdateFn(updateRendererStmts);
const updateDirectivesFn = this._createUpdateFn(updateDirectivesStmts);
let viewFlags = 0 /* None */;
if (!this.parent && this.component.changeDetection === ChangeDetectionStrategy.OnPush) {
viewFlags |= 2 /* OnPush */;
}
const viewFactory = new DeclareFunctionStmt(this.viewName, [new FnParam(LOG_VAR$1.name)], [new ReturnStatement(importExpr(Identifiers.viewDef).callFn([
literal(viewFlags),
literalArr(nodeDefExprs),
updateDirectivesFn,
updateRendererFn,
]))], importType(Identifiers.ViewDefinition), this.embeddedViewIndex === 0 ? [StmtModifier.Exported] : []);
targetStatements.push(viewFactory);
return targetStatements;
}
_createUpdateFn(updateStmts) {
let updateFn;
if (updateStmts.length > 0) {
const preStmts = [];
if (!this.component.isHost && findReadVarNames(updateStmts).has(COMP_VAR.name)) {
preStmts.push(COMP_VAR.set(VIEW_VAR.prop('component')).toDeclStmt(this.compType));
}
updateFn = fn([
new FnParam(CHECK_VAR.name, INFERRED_TYPE),
new FnParam(VIEW_VAR.name, INFERRED_TYPE)
], [...preStmts, ...updateStmts], INFERRED_TYPE);
}
else {
updateFn = NULL_EXPR;
}
return updateFn;
}
visitNgContent(ast, context) {
// ngContentDef(ngContentIndex: number, index: number): NodeDef;
this.nodes.push(() => ({
sourceSpan: ast.sourceSpan,
nodeFlags: 8 /* TypeNgContent */,
nodeDef: importExpr(Identifiers.ngContentDef)
.callFn([literal(ast.ngContentIndex), literal(ast.index)])
}));
}
visitText(ast, context) {
// Static text nodes have no check function
const checkIndex = -1;
this.nodes.push(() => ({
sourceSpan: ast.sourceSpan,
nodeFlags: 2 /* TypeText */,
nodeDef: importExpr(Identifiers.textDef).callFn([
literal(checkIndex),
literal(ast.ngContentIndex),
literalArr([literal(ast.value)]),
])
}));
}
visitBoundText(ast, context) {
const nodeIndex = this.nodes.length;
// reserve the space in the nodeDefs array
this.nodes.push(null);
const astWithSource = ast.value;
const inter = astWithSource.ast;
const updateRendererExpressions = inter.expressions.map((expr, bindingIndex) => this._preprocessUpdateExpression({ nodeIndex, bindingIndex, sourceSpan: ast.sourceSpan, context: COMP_VAR, value: expr }));
// Check index is the same as the node index during compilation
// They might only differ at runtime
const checkIndex = nodeIndex;
this.nodes[nodeIndex] = () => ({
sourceSpan: ast.sourceSpan,
nodeFlags: 2 /* TypeText */,
nodeDef: importExpr(Identifiers.textDef).callFn([
literal(checkIndex),
literal(ast.ngContentIndex),
literalArr(inter.strings.map(s => literal(s))),
]),
updateRenderer: updateRendererExpressions
});
}
visitEmbeddedTemplate(ast, context) {
const nodeIndex = this.nodes.length;
// reserve the space in the nodeDefs array
this.nodes.push(null);
const { flags, queryMatchesExpr, hostEvents } = this._visitElementOrTemplate(nodeIndex, ast);
const childVisitor = this.viewBuilderFactory(this);
this.children.push(childVisitor);
childVisitor.visitAll(ast.variables, ast.children);
const childCount = this.nodes.length - nodeIndex - 1;
// anchorDef(
// flags: NodeFlags, matchedQueries: [string, QueryValueType][], ngContentIndex: number,
// childCount: number, handleEventFn?: ElementHandleEventFn, templateFactory?:
// ViewDefinitionFactory): NodeDef;
this.nodes[nodeIndex] = () => ({
sourceSpan: ast.sourceSpan,
nodeFlags: 1 /* TypeElement */ | flags,
nodeDef: importExpr(Identifiers.anchorDef).callFn([
literal(flags),
queryMatchesExpr,
literal(ast.ngContentIndex),
literal(childCount),
this._createElementHandleEventFn(nodeIndex, hostEvents),
variable(childVisitor.viewName),
])
});
}
visitElement(ast, context) {
const nodeIndex = this.nodes.length;
// reserve the space in the nodeDefs array so we can add children
this.nodes.push(null);
// Using a null element name creates an anchor.
const elName = isNgContainer(ast.name) ? null : ast.name;
const { flags, usedEvents, queryMatchesExpr, hostBindings: dirHostBindings, hostEvents } = this._visitElementOrTemplate(nodeIndex, ast);
let inputDefs = [];
let updateRendererExpressions = [];
let outputDefs = [];
if (elName) {
const hostBindings = ast.inputs
.map((inputAst) => ({
context: COMP_VAR,
inputAst,
dirAst: null,
}))
.concat(dirHostBindings);
if (hostBindings.length) {
updateRendererExpressions =
hostBindings.map((hostBinding, bindingIndex) => this._preprocessUpdateExpression({
context: hostBinding.context,
nodeIndex,
bindingIndex,
sourceSpan: hostBinding.inputAst.sourceSpan,
value: hostBinding.inputAst.value
}));
inputDefs = hostBindings.map(hostBinding => elementBindingDef(hostBinding.inputAst, hostBinding.dirAst));
}
outputDefs = usedEvents.map(([target, eventName]) => literalArr([literal(target), literal(eventName)]));
}
templateVisitAll(this, ast.children);
const childCount = this.nodes.length - nodeIndex - 1;
const compAst = ast.directives.find(dirAst => dirAst.directive.isComponent);
let compRendererType = NULL_EXPR;
let compView = NULL_EXPR;
if (compAst) {
compView = this.outputCtx.importExpr(compAst.directive.componentViewType);
compRendererType = this.outputCtx.importExpr(compAst.directive.rendererType);
}
// Check index is the same as the node index during compilation
// They might only differ at runtime
const checkIndex = nodeIndex;
this.nodes[nodeIndex] = () => ({
sourceSpan: ast.sourceSpan,
nodeFlags: 1 /* TypeElement */ | flags,
nodeDef: importExpr(Identifiers.elementDef).callFn([
literal(checkIndex),
literal(flags),
queryMatchesExpr,
literal(ast.ngContentIndex),
literal(childCount),
literal(elName),
elName ? fixedAttrsDef(ast) : NULL_EXPR,
inputDefs.length ? literalArr(inputDefs) : NULL_EXPR,
outputDefs.length ? literalArr(outputDefs) : NULL_EXPR,
this._createElementHandleEventFn(nodeIndex, hostEvents),
compView,
compRendererType,
]),
updateRenderer: updateRendererExpressions
});
}
_visitElementOrTemplate(nodeIndex, ast) {
let flags = 0 /* None */;
if (ast.hasViewContainer) {
flags |= 16777216 /* EmbeddedViews */;
}
const usedEvents = new Map();
ast.outputs.forEach((event) => {
const { name, target } = elementEventNameAndTarget(event, null);
usedEvents.set(elementEventFullName(target, name), [target, name]);
});
ast.directives.forEach((dirAst) => {
dirAst.hostEvents.forEach((event) => {
const { name, target } = elementEventNameAndTarget(event, dirAst);
usedEvents.set(elementEventFullName(target, name), [target, name]);
});
});
const hostBindings = [];
const hostEvents = [];
this._visitComponentFactoryResolverProvider(ast.directives);
ast.providers.forEach(providerAst => {
let dirAst = undefined;
ast.directives.forEach(localDirAst => {
if (localDirAst.directive.type.reference === tokenReference(providerAst.token)) {
dirAst = localDirAst;
}
});
if (dirAst) {
const { hostBindings: dirHostBindings, hostEvents: dirHostEvents } = this._visitDirective(providerAst, dirAst, ast.references, ast.queryMatches, usedEvents);
hostBindings.push(...dirHostBindings);
hostEvents.push(...dirHostEvents);
}
else {
this._visitProvider(providerAst, ast.queryMatches);
}
});
let queryMatchExprs = [];
ast.queryMatches.forEach((match) => {
let valueType = undefined;
if (tokenReference(match.value) ===
this.reflector.resolveExternalReference(Identifiers.ElementRef)) {
valueType = 0 /* ElementRef */;
}
else if (tokenReference(match.value) ===
this.reflector.resolveExternalReference(Identifiers.ViewContainerRef)) {
valueType = 3 /* ViewContainerRef */;
}
else if (tokenReference(match.value) ===
this.reflector.resolveExternalReference(Identifiers.TemplateRef)) {
valueType = 2 /* TemplateRef */;
}
if (valueType != null) {
queryMatchExprs.push(literalArr([literal(match.queryId), literal(valueType)]));
}
});
ast.references.forEach((ref) => {
let valueType = undefined;
if (!ref.value) {
valueType = 1 /* RenderElement */;
}
else if (tokenReference(ref.value) ===
this.reflector.resolveExternalReference(Identifiers.TemplateRef)) {
valueType = 2 /* TemplateRef */;
}
if (valueType != null) {
this.refNodeIndices[ref.name] = nodeIndex;
queryMatchExprs.push(literalArr([literal(ref.name), literal(valueType)]));
}
});
ast.outputs.forEach((outputAst) => {
hostEvents.push({ context: COMP_VAR, eventAst: outputAst, dirAst: null });
});
return {
flags,
usedEvents: Array.from(usedEvents.values()),
queryMatchesExpr: queryMatchExprs.length ? literalArr(queryMatchExprs) : NULL_EXPR,
hostBindings,
hostEvents: hostEvents
};
}
_visitDirective(providerAst, dirAst, refs, queryMatches, usedEvents) {
const nodeIndex = this.nodes.length;
// reserve the space in the nodeDefs array so we can add children
this.nodes.push(null);
dirAst.directive.queries.forEach((query, queryIndex) => {
const queryId = dirAst.contentQueryStartId + queryIndex;
const flags = 67108864 /* TypeContentQuery */ | calcQueryFlags(query);
const bindingType = query.first ? 0 /* First */ : 1 /* All */;
this.nodes.push(() => ({
sourceSpan: dirAst.sourceSpan,
nodeFlags: flags,
nodeDef: importExpr(Identifiers.queryDef).callFn([
literal(flags), literal(queryId),
new LiteralMapExpr([new LiteralMapEntry(query.propertyName, literal(bindingType), false)])
]),
}));
});
// Note: the operation below might also create new nodeDefs,
// but we don't want them to be a child of a directive,
// as they might be a provider/pipe on their own.
// I.e. we only allow queries as children of directives nodes.
const childCount = this.nodes.length - nodeIndex - 1;
let { flags, queryMatchExprs, providerExpr, depsExpr } = this._visitProviderOrDirective(providerAst, queryMatches);
refs.forEach((ref) => {
if (ref.value && tokenReference(ref.value) === tokenReference(providerAst.token)) {
this.refNodeIndices[ref.name] = nodeIndex;
queryMatchExprs.push(literalArr([literal(ref.name), literal(4 /* Provider */)]));
}
});
if (dirAst.directive.isComponent) {
flags |= 32768 /* Component */;
}
const inputDefs = dirAst.inputs.map((inputAst, inputIndex) => {
const mapValue = literalArr([literal(inputIndex), literal(inputAst.directiveName)]);
// Note: it's important to not quote the key so that we can capture renames by minifiers!
return new LiteralMapEntry(inputAst.directiveName, mapValue, false);
});
const outputDefs = [];
const dirMeta = dirAst.directive;
Object.keys(dirMeta.outputs).forEach((propName) => {
const eventName = dirMeta.outputs[propName];
if (usedEvents.has(eventName)) {
// Note: it's important to not quote the key so that we can capture renames by minifiers!
outputDefs.push(new LiteralMapEntry(propName, literal(eventName), false));
}
});
let updateDirectiveExpressions = [];
if (dirAst.inputs.length || (flags & (262144 /* DoCheck */ | 65536 /* OnInit */)) > 0) {
updateDirectiveExpressions =
dirAst.inputs.map((input, bindingIndex) => this._preprocessUpdateExpression({
nodeIndex,
bindingIndex,
sourceSpan: input.sourceSpan,
context: COMP_VAR,
value: input.value
}));
}
const dirContextExpr = importExpr(Identifiers.nodeValue).callFn([VIEW_VAR, literal(nodeIndex)]);
const hostBindings = dirAst.hostProperties.map((inputAst) => ({
context: dirContextExpr,
dirAst,
inputAst,
}));
const hostEvents = dirAst.hostEvents.map((hostEventAst) => ({
context: dirContextExpr,
eventAst: hostEventAst,
dirAst,
}));
// Check index is the same as the node index during compilation
// They might only differ at runtime
const checkIndex = nodeIndex;
this.nodes[nodeIndex] = () => ({
sourceSpan: dirAst.sourceSpan,
nodeFlags: 16384 /* TypeDirective */ | flags,
nodeDef: importExpr(Identifiers.directiveDef).callFn([
literal(checkIndex),
literal(flags),
queryMatchExprs.length ? literalArr(queryMatchExprs) : NULL_EXPR,
literal(childCount),
providerExpr,
depsExpr,
inputDefs.length ? new LiteralMapExpr(inputDefs) : NULL_EXPR,
outputDefs.length ? new LiteralMapExpr(outputDefs) : NULL_EXPR,
]),
updateDirectives: updateDirectiveExpressions,
directive: dirAst.directive.type,
});
return { hostBindings, hostEvents };
}
_visitProvider(providerAst, queryMatches) {
this._addProviderNode(this._visitProviderOrDirective(providerAst, queryMatches));
}
_visitComponentFactoryResolverProvider(directives) {
const componentDirMeta = directives.find(dirAst => dirAst.directive.isComponent);
if (componentDirMeta && componentDirMeta.directive.entryComponents.length) {
const { providerExpr, depsExpr, flags, tokenExpr } = componentFactoryResolverProviderDef(this.reflector, this.outputCtx, 8192 /* PrivateProvider */, componentDirMeta.directive.entryComponents);
this._addProviderNode({
providerExpr,
depsExpr,
flags,
tokenExpr,
queryMatchExprs: [],
sourceSpan: componentDirMeta.sourceSpan
});
}
}
_addProviderNode(data) {
// providerDef(
// flags: NodeFlags, matchedQueries: [string, QueryValueType][], token:any,
// value: any, deps: ([DepFlags, any] | any)[]): NodeDef;
this.nodes.push(() => ({
sourceSpan: data.sourceSpan,
nodeFlags: data.flags,
nodeDef: importExpr(Identifiers.providerDef).callFn([
literal(data.flags),
data.queryMatchExprs.length ? literalArr(data.queryMatchExprs) : NULL_EXPR,
data.tokenExpr, data.providerExpr, data.depsExpr
])
}));
}
_visitProviderOrDirective(providerAst, queryMatches) {
let flags = 0 /* None */;
let queryMatchExprs = [];
queryMatches.forEach((match) => {
if (tokenReference(match.value) === tokenReference(providerAst.token)) {
queryMatchExprs.push(literalArr([literal(match.queryId), literal(4 /* Provider */)]));
}
});
const { providerExpr, depsExpr, flags: providerFlags, tokenExpr } = providerDef(this.outputCtx, providerAst);
return {
flags: flags | providerFlags,
queryMatchExprs,
providerExpr,
depsExpr,
tokenExpr,
sourceSpan: providerAst.sourceSpan
};
}
getLocal(name) {
if (name == EventHandlerVars.event.name) {
return EventHandlerVars.event;
}
let currViewExpr = VIEW_VAR;
for (let currBuilder = this; currBuilder; currBuilder = currBuilder.parent,
currViewExpr = currViewExpr.prop('parent').cast(DYNAMIC_TYPE)) {
// check references
const refNodeIndex = currBuilder.refNodeIndices[name];
if (refNodeIndex != null) {
return importExpr(Identifiers.nodeValue).callFn([currViewExpr, literal(refNodeIndex)]);
}
// check variables
const varAst = currBuilder.variables.find((varAst) => varAst.name === name);
if (varAst) {
const varValue = varAst.value || IMPLICIT_TEMPLATE_VAR;
return currViewExpr.prop('context').prop(varValue);
}
}
return null;
}
notifyImplicitReceiverUse() {
// Not needed in View Engine as View Engine walks through the generated
// expressions to figure out if the implicit receiver is used and needs
// to be generated as part of the pre-update statements.
}
_createLiteralArrayConverter(sourceSpan, argCount) {
if (argCount === 0) {
const valueExpr = importExpr(Identifiers.EMPTY_ARRAY);
return () => valueExpr;
}
const checkIndex = this.nodes.length;
this.nodes.push(() => ({
sourceSpan,
nodeFlags: 32 /* TypePureArray */,
nodeDef: importExpr(Identifiers.pureArrayDef).callFn([
literal(checkIndex),
literal(argCount),
])
}));
return (args) => callCheckStmt(checkIndex, args);
}
_createLiteralMapConverter(sourceSpan, keys) {
if (keys.length === 0) {
const valueExpr = importExpr(Identifiers.EMPTY_MAP);
return () => valueExpr;
}
const map = literalMap(keys.map((e, i) => (Object.assign(Object.assign({}, e), { value: literal(i) }))));
const checkIndex = this.nodes.length;
this.nodes.push(() => ({
sourceSpan,
nodeFlags: 64 /* TypePureObject */,
nodeDef: importExpr(Identifiers.pureObjectDef).callFn([
literal(checkIndex),
map,
])
}));
return (args) => callCheckStmt(checkIndex, args);
}
_createPipeConverter(expression, name, argCount) {
const pipe = this.usedPipes.find((pipeSummary) => pipeSummary.name === name);
if (pipe.pure) {
const checkIndex = this.nodes.length;
this.nodes.push(() => ({
sourceSpan: expression.sourceSpan,
nodeFlags: 128 /* TypePurePipe */,
nodeDef: importExpr(Identifiers.purePipeDef).callFn([
literal(checkIndex),
literal(argCount),
])
}));
// find underlying pipe in the component view
let compViewExpr = VIEW_VAR;
let compBuilder = this;
while (compBuilder.parent) {
compBuilder = compBuilder.parent;
compViewExpr = compViewExpr.prop('parent').cast(DYNAMIC_TYPE);
}
const pipeNodeIndex = compBuilder.purePipeNodeIndices[name];
const pipeValueExpr = importExpr(Identifiers.nodeValue).callFn([compViewExpr, literal(pipeNodeIndex)]);
return (args) => callUnwrapValue(expression.nodeIndex, expression.bindingIndex, callCheckStmt(checkIndex, [pipeValueExpr].concat(args)));
}
else {
const nodeIndex = this._createPipe(expression.sourceSpan, pipe);
const nodeValueExpr = importExpr(Identifiers.nodeValue).callFn([VIEW_VAR, literal(nodeIndex)]);
return (args) => callUnwrapValue(expression.nodeIndex, expression.bindingIndex, nodeValueExpr.callMethod('transform', args));
}
}
_createPipe(sourceSpan, pipe) {
const nodeIndex = this.nodes.length;
let flags = 0 /* None */;
pipe.type.lifecycleHooks.forEach((lifecycleHook) => {
// for pipes, we only support ngOnDestroy
if (lifecycleHook === LifecycleHooks.OnDestroy) {
flags |= lifecycleHookToNodeFlag(lifecycleHook);
}
});
const depExprs = pipe.type.diDeps.map((diDep) => depDef(this.outputCtx, diDep));
// function pipeDef(
// flags: NodeFlags, ctor: any, deps: ([DepFlags, any] | any)[]): NodeDef
this.nodes.push(() => ({
sourceSpan,
nodeFlags: 16 /* TypePipe */,
nodeDef: importExpr(Identifiers.pipeDef).callFn([
literal(flags), this.outputCtx.importExpr(pipe.type.reference), literalArr(depExprs)
])
}));
return nodeIndex;
}
/**
* For the AST in `UpdateExpression.value`:
* - create nodes for pipes, literal arrays and, literal maps,
* - update the AST to replace pipes, literal arrays and, literal maps with calls to check fn.
*
* WARNING: This might create new nodeDefs (for pipes and literal arrays and literal maps)!
*/
_preprocessUpdateExpression(expression) {
return {
nodeIndex: expression.nodeIndex,
bindingIndex: expression.bindingIndex,
sourceSpan: expression.sourceSpan,
context: expression.context,
value: convertPropertyBindingBuiltins({
createLiteralArrayConverter: (argCount) => this._createLiteralArrayConverter(expression.sourceSpan, argCount),
createLiteralMapConverter: (keys) => this._createLiteralMapConverter(expression.sourceSpan, keys),
createPipeConverter: (name, argCount) => this._createPipeConverter(expression, name, argCount)
}, expression.value)
};
}
_createNodeExpressions() {
const self = this;
let updateBindingCount = 0;
const updateRendererStmts = [];
const updateDirectivesStmts = [];
const nodeDefExprs = this.nodes.map((factory, nodeIndex) => {
const { nodeDef, nodeFlags, updateDirectives, updateRenderer, sourceSpan } = factory();
if (updateRenderer) {
updateRendererStmts.push(...createUpdateStatements(nodeIndex, sourceSpan, updateRenderer, false));
}
if (updateDirectives) {
updateDirectivesStmts.push(...createUpdateStatements(nodeIndex, sourceSpan, updateDirectives, (nodeFlags & (262144 /* DoCheck */ | 65536 /* OnInit */)) > 0));
}
// We use a comma expression to call the log function before
// the nodeDef function, but still use the result of the nodeDef function
// as the value.
// Note: We only add the logger to elements / text nodes,
// so we don't generate too much code.
const logWithNodeDef = nodeFlags & 3 /* CatRenderNode */ ?
new CommaExpr([LOG_VAR$1.callFn([]).callFn([]), nodeDef]) :
nodeDef;
return applySourceSpanToExpressionIfNeeded(logWithNodeDef, sourceSpan);
});
return { updateRendererStmts, updateDirectivesStmts, nodeDefExprs };
function createUpdateStatements(nodeIndex, sourceSpan, expressions, allowEmptyExprs) {
const updateStmts = [];
const exprs = expressions.map(({ sourceSpan, context, value }) => {
const bindingId = `${updateBindingCount++}`;
const nameResolver = context === COMP_VAR ? self : null;
const { stmts, currValExpr } = convertPropertyBinding(nameResolver, context, value, bindingId, BindingForm.General);
updateStmts.push(...stmts.map((stmt) => applySourceSpanToStatementIfNeeded(stmt, sourceSpan)));
return applySourceSpanToExpressionIfNeeded(currValExpr, sourceSpan);
});
if (expressions.length || allowEmptyExprs) {
updateStmts.push(applySourceSpanToStatementIfNeeded(callCheckStmt(nodeIndex, exprs).toStmt(), sourceSpan));
}
return updateStmts;
}
}
_createElementHandleEventFn(nodeIndex, handlers) {
const handleEventStmts = [];
let handleEventBindingCount = 0;
handlers.forEach(({ context, eventAst, dirAst }) => {
const bindingId = `${handleEventBindingCount++}`;
const nameResolver = context === COMP_VAR ? this : null;
const { stmts, allowDefault } = convertActionBinding(nameResolver, context, eventAst.handler, bindingId);
const trueStmts = stmts;
if (allowDefault) {
trueStmts.push(ALLOW_DEFAULT_VAR.set(allowDefault.and(ALLOW_DEFAULT_VAR)).toStmt());
}
const { target: eventTarget, name: eventName } = elementEventNameAndTarget(eventAst, dirAst);
const fullEventName = elementEventFullName(eventTarget, eventName);
handleEventStmts.push(applySourceSpanToStatementIfNeeded(new IfStmt(literal(fullEventName).identical(EVENT_NAME_VAR), trueStmts), eventAst.sourceSpan));
});
let handleEventFn;
if (handleEventStmts.length > 0) {
const preStmts = [ALLOW_DEFAULT_VAR.set(literal(true)).toDeclStmt(BOOL_TYPE)];
if (!this.component.isHost && findReadVarNames(handleEventStmts).has(COMP_VAR.name)) {
preStmts.push(COMP_VAR.set(VIEW_VAR.prop('component')).toDeclStmt(this.compType));
}
handleEventFn = fn([
new FnParam(VIEW_VAR.name, INFERRED_TYPE),
new FnParam(EVENT_NAME_VAR.name, INFERRED_TYPE),
new FnParam(EventHandlerVars.event.name, INFERRED_TYPE)
], [...preStmts, ...handleEventStmts, new ReturnStatement(ALLOW_DEFAULT_VAR)], INFERRED_TYPE);
}
else {
handleEventFn = NULL_EXPR;
}
return handleEventFn;
}
visitDirective(ast, context) { }
visitDirectiveProperty(ast, context) { }
visitReference(ast, context) { }
visitVariable(ast, context) { }
visitEvent(ast, context) { }
visitElementProperty(ast, context) { }
visitAttr(ast, context) { }
}
function needsAdditionalRootNode(astNodes) {
const lastAstNode = astNodes[astNodes.length - 1];
if (lastAstNode instanceof EmbeddedTemplateAst) {
return lastAstNode.hasViewContainer;
}
if (lastAstNode instanceof ElementAst) {
if (isNgContainer(lastAstNode.name) && lastAstNode.children.length) {
return needsAdditionalRootNode(lastAstNode.children);
}
return lastAstNode.hasViewContainer;
}
return lastAstNode instanceof NgContentAst;
}
function elementBindingDef(inputAst, dirAst) {
const inputType = inputAst.type;
switch (inputType) {
case 1 /* Attribute */:
return literalArr([
literal(1 /* TypeElementAttribute */), literal(inputAst.name),
literal(inputAst.securityContext)
]);
case 0 /* Property */:
return literalArr([
literal(8 /* TypeProperty */), literal(inputAst.name),
literal(inputAst.securityContext)
]);
case 4 /* Animation */:
const bindingType = 8 /* TypeProperty */ |
(dirAst && dirAst.directive.isComponent ? 32 /* SyntheticHostProperty */ :
16 /* SyntheticProperty */);
return literalArr([
literal(bindingType), literal('@' + inputAst.name), literal(inputAst.securityContext)
]);
case 2 /* Class */:
return literalArr([literal(2 /* TypeElementClass */), literal(inputAst.name), NULL_EXPR]);
case 3 /* Style */:
return literalArr([
literal(4 /* TypeElementStyle */), literal(inputAst.name), literal(inputAst.unit)
]);
default:
// This default case is not needed by TypeScript compiler, as the switch is exhaustive.
// However Closure Compiler does not understand that and reports an error in typed mode.
// The `throw new Error` below works around the problem, and the unexpected: never variable
// makes sure tsc still checks this code is unreachable.
const unexpected = inputType;
throw new Error(`unexpected ${unexpected}`);
}
}
function fixedAttrsDef(elementAst) {
const mapResult = Object.create(null);
elementAst.attrs.forEach(attrAst => {
mapResult[attrAst.name] = attrAst.value;
});
elementAst.directives.forEach(dirAst => {
Object.keys(dirAst.directive.hostAttributes).forEach(name => {
const value = dirAst.directive.hostAttributes[name];
const prevValue = mapResult[name];
mapResult[name] = prevValue != null ? mergeAttributeValue(name, prevValue, value) : value;
});
});
// Note: We need to sort to get a defined output order
// for tests and for caching generated artifacts...
return literalArr(Object.keys(mapResult).sort().map((attrName) => literalArr([literal(attrName), literal(mapResult[attrName])])));
}
function mergeAttributeValue(attrName, attrValue1, attrValue2) {
if (attrName == CLASS_ATTR$1 || attrName == STYLE_ATTR) {
return `${attrValue1} ${attrValue2}`;
}
else {
return attrValue2;
}
}
function callCheckStmt(nodeIndex, exprs) {
if (exprs.length > 10) {
return CHECK_VAR.callFn([VIEW_VAR, literal(nodeIndex), literal(1 /* Dynamic */), literalArr(exprs)]);
}
else {
return CHECK_VAR.callFn([VIEW_VAR, literal(nodeIndex), literal(0 /* Inline */), ...exprs]);
}
}
function callUnwrapValue(nodeIndex, bindingIdx, expr) {
return importExpr(Identifiers.unwrapValue).callFn([
VIEW_VAR, literal(nodeIndex), literal(bindingIdx), expr
]);
}
function elementEventNameAndTarget(eventAst, dirAst) {
if (eventAst.isAnimation) {
return {
name: `@${eventAst.name}.${eventAst.phase}`,
target: dirAst && dirAst.directive.isComponent ? 'component' : null
};
}
else {
return eventAst;
}
}
function calcQueryFlags(query) {
let flags = 0 /* None */;
// Note: We only make queries static that query for a single item and the user specifically
// set the to be static. This is because of backwards compatibility with the old view compiler...
if (query.first && query.static) {
flags |= 268435456 /* StaticQuery */;
}
else {
flags |= 536870912 /* DynamicQuery */;
}
if (query.emitDistinctChangesOnly) {
flags |= -2147483648 /* EmitDistinctChangesOnly */;
}
return flags;
}
function elementEventFullName(target, name) {
return target ? `${target}:${name}` : name;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* A container for message extracted from the templates.
*/
class MessageBundle {
constructor(_htmlParser, _implicitTags, _implicitAttrs, _locale = null) {
this._htmlParser = _htmlParser;
this._implicitTags = _implicitTags;
this._implicitAttrs = _implicitAttrs;
this._locale = _locale;
this._messages = [];
}
updateFromTemplate(html, url, interpolationConfig) {
const htmlParserResult = this._htmlParser.parse(html, url, { tokenizeExpansionForms: true, interpolationConfig });
if (htmlParserResult.errors.length) {
return htmlParserResult.errors;
}
const i18nParserResult = extractMessages(htmlParserResult.rootNodes, interpolationConfig, this._implicitTags, this._implicitAttrs);
if (i18nParserResult.errors.length) {
return i18nParserResult.errors;
}
this._messages.push(...i18nParserResult.messages);
return [];
}
// Return the message in the internal format
// The public (serialized) format might be different, see the `write` method.
getMessages() {
return this._messages;
}
write(serializer, filterSources) {
const messages = {};
const mapperVisitor = new MapPlaceholderNames();
// Deduplicate messages based on their ID
this._messages.forEach(message => {
const id = serializer.digest(message);
if (!messages.hasOwnProperty(id)) {
messages[id] = message;
}
else {
messages[id].sources.push(...message.sources);
}
});
// Transform placeholder names using the serializer mapping
const msgList = Object.keys(messages).map(id => {
const mapper = serializer.createNameMapper(messages[id]);
const src = messages[id];
const nodes = mapper ? mapperVisitor.convert(src.nodes, mapper) : src.nodes;
let transformedMessage = new Message(nodes, {}, {}, src.meaning, src.description, id);
transformedMessage.sources = src.sources;
if (filterSources) {
transformedMessage.sources.forEach((source) => source.filePath = filterSources(source.filePath));
}
return transformedMessage;
});
return serializer.write(msgList, this._locale);
}
}
// Transform an i18n AST by renaming the placeholder nodes with the given mapper
class MapPlaceholderNames extends CloneVisitor {
convert(nodes, mapper) {
return mapper ? nodes.map(n => n.visit(this, mapper)) : nodes;
}
visitTagPlaceholder(ph, mapper) {
const startName = mapper.toPublicName(ph.startName);
const closeName = ph.closeName ? mapper.toPublicName(ph.closeName) : ph.closeName;
const children = ph.children.map(n => n.visit(this, mapper));
return new TagPlaceholder(ph.tag, ph.attrs, startName, closeName, children, ph.isVoid, ph.sourceSpan, ph.startSourceSpan, ph.endSourceSpan);
}
visitPlaceholder(ph, mapper) {
return new Placeholder(ph.value, mapper.toPublicName(ph.name), ph.sourceSpan);
}
visitIcuPlaceholder(ph, mapper) {
return new IcuPlaceholder(ph.value, mapper.toPublicName(ph.name), ph.sourceSpan);
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class GeneratedFile {
constructor(srcFileUrl, genFileUrl, sourceOrStmts) {
this.srcFileUrl = srcFileUrl;
this.genFileUrl = genFileUrl;
if (typeof sourceOrStmts === 'string') {
this.source = sourceOrStmts;
this.stmts = null;
}
else {
this.source = null;
this.stmts = sourceOrStmts;
}
}
isEquivalent(other) {
if (this.genFileUrl !== other.genFileUrl) {
return false;
}
if (this.source) {
return this.source === other.source;
}
if (other.stmts == null) {
return false;
}
// Note: the constructor guarantees that if this.source is not filled,
// then this.stmts is.
return areAllEquivalent(this.stmts, other.stmts);
}
}
function toTypeScript(file, preamble = '') {
if (!file.stmts) {
throw new Error(`Illegal state: No stmts present on GeneratedFile ${file.genFileUrl}`);
}
return new TypeScriptEmitter().emitStatements(file.genFileUrl, file.stmts, preamble);
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function listLazyRoutes(moduleMeta, reflector) {
const allLazyRoutes = [];
for (const { provider, module } of moduleMeta.transitiveModule.providers) {
if (tokenReference(provider.token) === reflector.ROUTES) {
const loadChildren = _collectLoadChildren(provider.useValue);
for (const route of loadChildren) {
allLazyRoutes.push(parseLazyRoute(route, reflector, module.reference));
}
}
}
return allLazyRoutes;
}
function _collectLoadChildren(routes, target = []) {
if (typeof routes === 'string') {
target.push(routes);
}
else if (Array.isArray(routes)) {
for (const route of routes) {
_collectLoadChildren(route, target);
}
}
else if (routes.loadChildren) {
_collectLoadChildren(routes.loadChildren, target);
}
else if (routes.children) {
_collectLoadChildren(routes.children, target);
}
return target;
}
function parseLazyRoute(route, reflector, module) {
const [routePath, routeName] = route.split('#');
const referencedModule = reflector.resolveExternalReference({
moduleName: routePath,
name: routeName,
}, module ? module.filePath : undefined);
return { route: route, module: module || referencedModule, referencedModule };
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const TS = /^(?!.*\.d\.ts$).*\.ts$/;
class ResolvedStaticSymbol {
constructor(symbol, metadata) {
this.symbol = symbol;
this.metadata = metadata;
}
}
const SUPPORTED_SCHEMA_VERSION = 4;
/**
* This class is responsible for loading metadata per symbol,
* and normalizing references between symbols.
*
* Internally, it only uses symbols without members,
* and deduces the values for symbols with members based
* on these symbols.
*/
class StaticSymbolResolver {
constructor(host, staticSymbolCache, summaryResolver, errorRecorder) {
this.host = host;
this.staticSymbolCache = staticSymbolCache;
this.summaryResolver = summaryResolver;
this.errorRecorder = errorRecorder;
this.metadataCache = new Map();
// Note: this will only contain StaticSymbols without members!
this.resolvedSymbols = new Map();
// Note: this will only contain StaticSymbols without members!
this.importAs = new Map();
this.symbolResourcePaths = new Map();
this.symbolFromFile = new Map();
this.knownFileNameToModuleNames = new Map();
}
resolveSymbol(staticSymbol) {
if (staticSymbol.members.length > 0) {
return this._resolveSymbolMembers(staticSymbol);
}
// Note: always ask for a summary first,
// as we might have read shallow metadata via a .d.ts file
// for the symbol.
const resultFromSummary = this._resolveSymbolFromSummary(staticSymbol);
if (resultFromSummary) {
return resultFromSummary;
}
const resultFromCache = this.resolvedSymbols.get(staticSymbol);
if (resultFromCache) {
return resultFromCache;
}
// Note: Some users use libraries that were not compiled with ngc, i.e. they don't
// have summaries, only .d.ts files. So we always need to check both, the summary
// and metadata.
this._createSymbolsOf(staticSymbol.filePath);
return this.resolvedSymbols.get(staticSymbol);
}
/**
* getImportAs produces a symbol that can be used to import the given symbol.
* The import might be different than the symbol if the symbol is exported from
* a library with a summary; in which case we want to import the symbol from the
* ngfactory re-export instead of directly to avoid introducing a direct dependency
* on an otherwise indirect dependency.
*
* @param staticSymbol the symbol for which to generate a import symbol
*/
getImportAs(staticSymbol, useSummaries = true) {
if (staticSymbol.members.length) {
const baseSymbol = this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name);
const baseImportAs = this.getImportAs(baseSymbol, useSummaries);
return baseImportAs ?
this.getStaticSymbol(baseImportAs.filePath, baseImportAs.name, staticSymbol.members) :
null;
}
const summarizedFileName = stripSummaryForJitFileSuffix(staticSymbol.filePath);
if (summarizedFileName !== staticSymbol.filePath) {
const summarizedName = stripSummaryForJitNameSuffix(staticSymbol.name);
const baseSymbol = this.getStaticSymbol(summarizedFileName, summarizedName, staticSymbol.members);
const baseImportAs = this.getImportAs(baseSymbol, useSummaries);
return baseImportAs ? this.getStaticSymbol(summaryForJitFileName(baseImportAs.filePath), summaryForJitName(baseImportAs.name), baseSymbol.members) :
null;
}
let result = (useSummaries && this.summaryResolver.getImportAs(staticSymbol)) || null;
if (!result) {
result = this.importAs.get(staticSymbol);
}
return result;
}
/**
* getResourcePath produces the path to the original location of the symbol and should
* be used to determine the relative location of resource references recorded in
* symbol metadata.
*/
getResourcePath(staticSymbol) {
return this.symbolResourcePaths.get(staticSymbol) || staticSymbol.filePath;
}
/**
* getTypeArity returns the number of generic type parameters the given symbol
* has. If the symbol is not a type the result is null.
*/
getTypeArity(staticSymbol) {
// If the file is a factory/ngsummary file, don't resolve the symbol as doing so would
// cause the metadata for an factory/ngsummary file to be loaded which doesn't exist.
// All references to generated classes must include the correct arity whenever
// generating code.
if (isGeneratedFile(staticSymbol.filePath)) {
return null;
}
let resolvedSymbol = unwrapResolvedMetadata(this.resolveSymbol(staticSymbol));
while (resolvedSymbol && resolvedSymbol.metadata instanceof StaticSymbol) {
resolvedSymbol = unwrapResolvedMetadata(this.resolveSymbol(resolvedSymbol.metadata));
}
return (resolvedSymbol && resolvedSymbol.metadata && resolvedSymbol.metadata.arity) || null;
}
getKnownModuleName(filePath) {
return this.knownFileNameToModuleNames.get(filePath) || null;
}
recordImportAs(sourceSymbol, targetSymbol) {
sourceSymbol.assertNoMembers();
targetSymbol.assertNoMembers();
this.importAs.set(sourceSymbol, targetSymbol);
}
recordModuleNameForFileName(fileName, moduleName) {
this.knownFileNameToModuleNames.set(fileName, moduleName);
}
/**
* Invalidate all information derived from the given file and return the
* static symbols contained in the file.
*
* @param fileName the file to invalidate
*/
invalidateFile(fileName) {
this.metadataCache.delete(fileName);
const symbols = this.symbolFromFile.get(fileName);
if (!symbols) {
return [];
}
this.symbolFromFile.delete(fileName);
for (const symbol of symbols) {
this.resolvedSymbols.delete(symbol);
this.importAs.delete(symbol);
this.symbolResourcePaths.delete(symbol);
}
return symbols;
}
/** @internal */
ignoreErrorsFor(cb) {
const recorder = this.errorRecorder;
this.errorRecorder = () => { };
try {
return cb();
}
finally {
this.errorRecorder = recorder;
}
}
_resolveSymbolMembers(staticSymbol) {
const members = staticSymbol.members;
const baseResolvedSymbol = this.resolveSymbol(this.getStaticSymbol(staticSymbol.filePath, staticSymbol.name));
if (!baseResolvedSymbol) {
return null;
}
let baseMetadata = unwrapResolvedMetadata(baseResolvedSymbol.metadata);
if (baseMetadata instanceof StaticSymbol) {
return new ResolvedStaticSymbol(staticSymbol, this.getStaticSymbol(baseMetadata.filePath, baseMetadata.name, members));
}
else if (baseMetadata && baseMetadata.__symbolic === 'class') {
if (baseMetadata.statics && members.length === 1) {
return new ResolvedStaticSymbol(staticSymbol, baseMetadata.statics[members[0]]);
}
}
else {
let value = baseMetadata;
for (let i = 0; i < members.length && value; i++) {
value = value[members[i]];
}
return new ResolvedStaticSymbol(staticSymbol, value);
}
return null;
}
_resolveSymbolFromSummary(staticSymbol) {
const summary = this.summaryResolver.resolveSummary(staticSymbol);
return summary ? new ResolvedStaticSymbol(staticSymbol, summary.metadata) : null;
}
/**
* getStaticSymbol produces a Type whose metadata is known but whose implementation is not loaded.
* All types passed to the StaticResolver should be pseudo-types returned by this method.
*
* @param declarationFile the absolute path of the file where the symbol is declared
* @param name the name of the type.
* @param members a symbol for a static member of the named type
*/
getStaticSymbol(declarationFile, name, members) {
return this.staticSymbolCache.get(declarationFile, name, members);
}
/**
* hasDecorators checks a file's metadata for the presence of decorators without evaluating the
* metadata.
*
* @param filePath the absolute path to examine for decorators.
* @returns true if any class in the file has a decorator.
*/
hasDecorators(filePath) {
const metadata = this.getModuleMetadata(filePath);
if (metadata['metadata']) {
return Object.keys(metadata['metadata']).some((metadataKey) => {
const entry = metadata['metadata'][metadataKey];
return entry && entry.__symbolic === 'class' && entry.decorators;
});
}
return false;
}
getSymbolsOf(filePath) {
const summarySymbols = this.summaryResolver.getSymbolsOf(filePath);
if (summarySymbols) {
return summarySymbols;
}
// Note: Some users use libraries that were not compiled with ngc, i.e. they don't
// have summaries, only .d.ts files, but `summaryResolver.isLibraryFile` returns true.
this._createSymbolsOf(filePath);
return this.symbolFromFile.get(filePath) || [];
}
_createSymbolsOf(filePath) {
if (this.symbolFromFile.has(filePath)) {
return;
}
const resolvedSymbols = [];
const metadata = this.getModuleMetadata(filePath);
if (metadata['importAs']) {
// Index bundle indices should use the importAs module name defined
// in the bundle.
this.knownFileNameToModuleNames.set(filePath, metadata['importAs']);
}
// handle the symbols in one of the re-export location
if (metadata['exports']) {
for (const moduleExport of metadata['exports']) {
// handle the symbols in the list of explicitly re-exported symbols.
if (moduleExport.export) {
moduleExport.export.forEach((exportSymbol) => {
let symbolName;
if (typeof exportSymbol === 'string') {
symbolName = exportSymbol;
}
else {
symbolName = exportSymbol.as;
}
symbolName = unescapeIdentifier(symbolName);
let symName = symbolName;
if (typeof exportSymbol !== 'string') {
symName = unescapeIdentifier(exportSymbol.name);
}
const resolvedModule = this.resolveModule(moduleExport.from, filePath);
if (resolvedModule) {
const targetSymbol = this.getStaticSymbol(resolvedModule, symName);
const sourceSymbol = this.getStaticSymbol(filePath, symbolName);
resolvedSymbols.push(this.createExport(sourceSymbol, targetSymbol));
}
});
}
else {
// Handle the symbols loaded by 'export *' directives.
const resolvedModule = this.resolveModule(moduleExport.from, filePath);
if (resolvedModule && resolvedModule !== filePath) {
const nestedExports = this.getSymbolsOf(resolvedModule);
nestedExports.forEach((targetSymbol) => {
const sourceSymbol = this.getStaticSymbol(filePath, targetSymbol.name);
resolvedSymbols.push(this.createExport(sourceSymbol, targetSymbol));
});
}
}
}
}
// handle the actual metadata. Has to be after the exports
// as there might be collisions in the names, and we want the symbols
// of the current module to win ofter reexports.
if (metadata['metadata']) {
// handle direct declarations of the symbol
const topLevelSymbolNames = new Set(Object.keys(metadata['metadata']).map(unescapeIdentifier));
const origins = metadata['origins'] || {};
Object.keys(metadata['metadata']).forEach((metadataKey) => {
const symbolMeta = metadata['metadata'][metadataKey];
const name = unescapeIdentifier(metadataKey);
const symbol = this.getStaticSymbol(filePath, name);
const origin = origins.hasOwnProperty(metadataKey) && origins[metadataKey];
if (origin) {
// If the symbol is from a bundled index, use the declaration location of the
// symbol so relative references (such as './my.html') will be calculated
// correctly.
const originFilePath = this.resolveModule(origin, filePath);
if (!originFilePath) {
this.reportError(new Error(`Couldn't resolve original symbol for ${origin} from ${this.host.getOutputName(filePath)}`));
}
else {
this.symbolResourcePaths.set(symbol, originFilePath);
}
}
resolvedSymbols.push(this.createResolvedSymbol(symbol, filePath, topLevelSymbolNames, symbolMeta));
});
}
const uniqueSymbols = new Set();
for (const resolvedSymbol of resolvedSymbols) {
this.resolvedSymbols.set(resolvedSymbol.symbol, resolvedSymbol);
uniqueSymbols.add(resolvedSymbol.symbol);
}
this.symbolFromFile.set(filePath, Array.from(uniqueSymbols));
}
createResolvedSymbol(sourceSymbol, topLevelPath, topLevelSymbolNames, metadata) {
// For classes that don't have Angular summaries / metadata,
// we only keep their arity, but nothing else
// (e.g. their constructor parameters).
// We do this to prevent introducing deep imports
// as we didn't generate .ngfactory.ts files with proper reexports.
const isTsFile = TS.test(sourceSymbol.filePath);
if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) && !isTsFile && metadata &&
metadata['__symbolic'] === 'class') {
const transformedMeta = { __symbolic: 'class', arity: metadata.arity };
return new ResolvedStaticSymbol(sourceSymbol, transformedMeta);
}
let _originalFileMemo;
const getOriginalName = () => {
if (!_originalFileMemo) {
// Guess what the original file name is from the reference. If it has a `.d.ts` extension
// replace it with `.ts`. If it already has `.ts` just leave it in place. If it doesn't have
// .ts or .d.ts, append `.ts'. Also, if it is in `node_modules`, trim the `node_module`
// location as it is not important to finding the file.
_originalFileMemo =
this.host.getOutputName(topLevelPath.replace(/((\.ts)|(\.d\.ts)|)$/, '.ts')
.replace(/^.*node_modules[/\\]/, ''));
}
return _originalFileMemo;
};
const self = this;
class ReferenceTransformer extends ValueTransformer {
visitStringMap(map, functionParams) {
const symbolic = map['__symbolic'];
if (symbolic === 'function') {
const oldLen = functionParams.length;
functionParams.push(...(map['parameters'] || []));
const result = super.visitStringMap(map, functionParams);
functionParams.length = oldLen;
return result;
}
else if (symbolic === 'reference') {
const module = map['module'];
const name = map['name'] ? unescapeIdentifier(map['name']) : map['name'];
if (!name) {
return null;
}
let filePath;
if (module) {
filePath = self.resolveModule(module, sourceSymbol.filePath);
if (!filePath) {
return {
__symbolic: 'error',
message: `Could not resolve ${module} relative to ${self.host.getMetadataFor(sourceSymbol.filePath)}.`,
line: map['line'],
character: map['character'],
fileName: getOriginalName()
};
}
return {
__symbolic: 'resolved',
symbol: self.getStaticSymbol(filePath, name),
line: map['line'],
character: map['character'],
fileName: getOriginalName()
};
}
else if (functionParams.indexOf(name) >= 0) {
// reference to a function parameter
return { __symbolic: 'reference', name: name };
}
else {
if (topLevelSymbolNames.has(name)) {
return self.getStaticSymbol(topLevelPath, name);
}
// ambient value
null;
}
}
else if (symbolic === 'error') {
return Object.assign(Object.assign({}, map), { fileName: getOriginalName() });
}
else {
return super.visitStringMap(map, functionParams);
}
}
}
const transformedMeta = visitValue(metadata, new ReferenceTransformer(), []);
let unwrappedTransformedMeta = unwrapResolvedMetadata(transformedMeta);
if (unwrappedTransformedMeta instanceof StaticSymbol) {
return this.createExport(sourceSymbol, unwrappedTransformedMeta);
}
return new ResolvedStaticSymbol(sourceSymbol, transformedMeta);
}
createExport(sourceSymbol, targetSymbol) {
sourceSymbol.assertNoMembers();
targetSymbol.assertNoMembers();
if (this.summaryResolver.isLibraryFile(sourceSymbol.filePath) &&
this.summaryResolver.isLibraryFile(targetSymbol.filePath)) {
// This case is for an ng library importing symbols from a plain ts library
// transitively.
// Note: We rely on the fact that we discover symbols in the direction
// from source files to library files
this.importAs.set(targetSymbol, this.getImportAs(sourceSymbol) || sourceSymbol);
}
return new ResolvedStaticSymbol(sourceSymbol, targetSymbol);
}
reportError(error, context, path) {
if (this.errorRecorder) {
this.errorRecorder(error, (context && context.filePath) || path);
}
else {
throw error;
}
}
/**
* @param module an absolute path to a module file.
*/
getModuleMetadata(module) {
let moduleMetadata = this.metadataCache.get(module);
if (!moduleMetadata) {
const moduleMetadatas = this.host.getMetadataFor(module);
if (moduleMetadatas) {
let maxVersion = -1;
moduleMetadatas.forEach((md) => {
if (md && md['version'] > maxVersion) {
maxVersion = md['version'];
moduleMetadata = md;
}
});
}
if (!moduleMetadata) {
moduleMetadata =
{ __symbolic: 'module', version: SUPPORTED_SCHEMA_VERSION, module: module, metadata: {} };
}
if (moduleMetadata['version'] != SUPPORTED_SCHEMA_VERSION) {
const errorMessage = moduleMetadata['version'] == 2 ?
`Unsupported metadata version ${moduleMetadata['version']} for module ${module}. This module should be compiled with a newer version of ngc` :
`Metadata version mismatch for module ${this.host.getOutputName(module)}, found version ${moduleMetadata['version']}, expected ${SUPPORTED_SCHEMA_VERSION}`;
this.reportError(new Error(errorMessage));
}
this.metadataCache.set(module, moduleMetadata);
}
return moduleMetadata;
}
getSymbolByModule(module, symbolName, containingFile) {
const filePath = this.resolveModule(module, containingFile);
if (!filePath) {
this.reportError(new Error(`Could not resolve module ${module}${containingFile ? ' relative to ' + this.host.getOutputName(containingFile) : ''}`));
return this.getStaticSymbol(`ERROR:${module}`, symbolName);
}
return this.getStaticSymbol(filePath, symbolName);
}
resolveModule(module, containingFile) {
try {
return this.host.moduleNameToFileName(module, containingFile);
}
catch (e) {
console.error(`Could not resolve module '${module}' relative to file ${containingFile}`);
this.reportError(e, undefined, containingFile);
}
return null;
}
}
// Remove extra underscore from escaped identifier.
// See https://github.com/Microsoft/TypeScript/blob/master/src/compiler/utilities.ts
function unescapeIdentifier(identifier) {
return identifier.startsWith('___') ? identifier.substr(1) : identifier;
}
function unwrapResolvedMetadata(metadata) {
if (metadata && metadata.__symbolic === 'resolved') {
return metadata.symbol;
}
return metadata;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function serializeSummaries(srcFileName, forJitCtx, summaryResolver, symbolResolver, symbols, types, createExternalSymbolReexports = false) {
const toJsonSerializer = new ToJsonSerializer(symbolResolver, summaryResolver, srcFileName);
// for symbols, we use everything except for the class metadata itself
// (we keep the statics though), as the class metadata is contained in the
// CompileTypeSummary.
symbols.forEach((resolvedSymbol) => toJsonSerializer.addSummary({ symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata }));
// Add type summaries.
types.forEach(({ summary, metadata }) => {
toJsonSerializer.addSummary({ symbol: summary.type.reference, metadata: undefined, type: summary });
});
const { json, exportAs } = toJsonSerializer.serialize(createExternalSymbolReexports);
if (forJitCtx) {
const forJitSerializer = new ForJitSerializer(forJitCtx, symbolResolver, summaryResolver);
types.forEach(({ summary, metadata }) => {
forJitSerializer.addSourceType(summary, metadata);
});
toJsonSerializer.unprocessedSymbolSummariesBySymbol.forEach((summary) => {
if (summaryResolver.isLibraryFile(summary.symbol.filePath) && summary.type) {
forJitSerializer.addLibType(summary.type);
}
});
forJitSerializer.serialize(exportAs);
}
return { json, exportAs };
}
function deserializeSummaries(symbolCache, summaryResolver, libraryFileName, json) {
const deserializer = new FromJsonDeserializer(symbolCache, summaryResolver);
return deserializer.deserialize(libraryFileName, json);
}
function createForJitStub(outputCtx, reference) {
return createSummaryForJitFunction(outputCtx, reference, NULL_EXPR);
}
function createSummaryForJitFunction(outputCtx, reference, value) {
const fnName = summaryForJitName(reference.name);
outputCtx.statements.push(fn([], [new ReturnStatement(value)], new ArrayType(DYNAMIC_TYPE)).toDeclStmt(fnName, [
StmtModifier.Final, StmtModifier.Exported
]));
}
class ToJsonSerializer extends ValueTransformer {
constructor(symbolResolver, summaryResolver, srcFileName) {
super();
this.symbolResolver = symbolResolver;
this.summaryResolver = summaryResolver;
this.srcFileName = srcFileName;
// Note: This only contains symbols without members.
this.symbols = [];
this.indexBySymbol = new Map();
this.reexportedBy = new Map();
// This now contains a `__symbol: number` in the place of
// StaticSymbols, but otherwise has the same shape as the original objects.
this.processedSummaryBySymbol = new Map();
this.processedSummaries = [];
this.unprocessedSymbolSummariesBySymbol = new Map();
this.moduleName = symbolResolver.getKnownModuleName(srcFileName);
}
addSummary(summary) {
let unprocessedSummary = this.unprocessedSymbolSummariesBySymbol.get(summary.symbol);
let processedSummary = this.processedSummaryBySymbol.get(summary.symbol);
if (!unprocessedSummary) {
unprocessedSummary = { symbol: summary.symbol, metadata: undefined };
this.unprocessedSymbolSummariesBySymbol.set(summary.symbol, unprocessedSummary);
processedSummary = { symbol: this.processValue(summary.symbol, 0 /* None */) };
this.processedSummaries.push(processedSummary);
this.processedSummaryBySymbol.set(summary.symbol, processedSummary);
}
if (!unprocessedSummary.metadata && summary.metadata) {
let metadata = summary.metadata || {};
if (metadata.__symbolic === 'class') {
// For classes, we keep everything except their class decorators.
// We need to keep e.g. the ctor args, method names, method decorators
// so that the class can be extended in another compilation unit.
// We don't keep the class decorators as
// 1) they refer to data
// that should not cause a rebuild of downstream compilation units
// (e.g. inline templates of @Component, or @NgModule.declarations)
// 2) their data is already captured in TypeSummaries, e.g. DirectiveSummary.
const clone = {};
Object.keys(metadata).forEach((propName) => {
if (propName !== 'decorators') {
clone[propName] = metadata[propName];
}
});
metadata = clone;
}
else if (isCall(metadata)) {
if (!isFunctionCall(metadata) && !isMethodCallOnVariable(metadata)) {
// Don't store complex calls as we won't be able to simplify them anyways later on.
metadata = {
__symbolic: 'error',
message: 'Complex function calls are not supported.',
};
}
}
// Note: We need to keep storing ctor calls for e.g.
// `export const x = new InjectionToken(...)`
unprocessedSummary.metadata = metadata;
processedSummary.metadata = this.processValue(metadata, 1 /* ResolveValue */);
if (metadata instanceof StaticSymbol &&
this.summaryResolver.isLibraryFile(metadata.filePath)) {
const declarationSymbol = this.symbols[this.indexBySymbol.get(metadata)];
if (!isLoweredSymbol(declarationSymbol.name)) {
// Note: symbols that were introduced during codegen in the user file can have a reexport
// if a user used `export *`. However, we can't rely on this as tsickle will change
// `export *` into named exports, using only the information from the typechecker.
// As we introduce the new symbols after typecheck, Tsickle does not know about them,
// and omits them when expanding `export *`.
// So we have to keep reexporting these symbols manually via .ngfactory files.
this.reexportedBy.set(declarationSymbol, summary.symbol);
}
}
}
if (!unprocessedSummary.type && summary.type) {
unprocessedSummary.type = summary.type;
// Note: We don't add the summaries of all referenced symbols as for the ResolvedSymbols,
// as the type summaries already contain the transitive data that they require
// (in a minimal way).
processedSummary.type = this.processValue(summary.type, 0 /* None */);
// except for reexported directives / pipes, so we need to store
// their summaries explicitly.
if (summary.type.summaryKind === CompileSummaryKind.NgModule) {
const ngModuleSummary = summary.type;
ngModuleSummary.exportedDirectives.concat(ngModuleSummary.exportedPipes).forEach((id) => {
const symbol = id.reference;
if (this.summaryResolver.isLibraryFile(symbol.filePath) &&
!this.unprocessedSymbolSummariesBySymbol.has(symbol)) {
const summary = this.summaryResolver.resolveSummary(symbol);
if (summary) {
this.addSummary(summary);
}
}
});
}
}
}
/**
* @param createExternalSymbolReexports Whether external static symbols should be re-exported.
* This can be enabled if external symbols should be re-exported by the current module in
* order to avoid dynamically generated module dependencies which can break strict dependency
* enforcements (as in Google3). Read more here: https://github.com/angular/angular/issues/25644
*/
serialize(createExternalSymbolReexports) {
const exportAs = [];
const json = JSON.stringify({
moduleName: this.moduleName,
summaries: this.processedSummaries,
symbols: this.symbols.map((symbol, index) => {
symbol.assertNoMembers();
let importAs = undefined;
if (this.summaryResolver.isLibraryFile(symbol.filePath)) {
const reexportSymbol = this.reexportedBy.get(symbol);
if (reexportSymbol) {
// In case the given external static symbol is already manually exported by the
// user, we just proxy the external static symbol reference to the manual export.
// This ensures that the AOT compiler imports the external symbol through the
// user export and does not introduce another dependency which is not needed.
importAs = this.indexBySymbol.get(reexportSymbol);
}
else if (createExternalSymbolReexports) {
// In this case, the given external static symbol is *not* manually exported by
// the user, and we manually create a re-export in the factory file so that we
// don't introduce another module dependency. This is useful when running within
// Bazel so that the AOT compiler does not introduce any module dependencies
// which can break the strict dependency enforcement. (e.g. as in Google3)
// Read more about this here: https://github.com/angular/angular/issues/25644
const summary = this.unprocessedSymbolSummariesBySymbol.get(symbol);
if (!summary || !summary.metadata || summary.metadata.__symbolic !== 'interface') {
importAs = `${symbol.name}_${index}`;
exportAs.push({ symbol, exportAs: importAs });
}
}
}
return {
__symbol: index,
name: symbol.name,
filePath: this.summaryResolver.toSummaryFileName(symbol.filePath, this.srcFileName),
importAs: importAs
};
})
});
return { json, exportAs };
}
processValue(value, flags) {
return visitValue(value, this, flags);
}
visitOther(value, context) {
if (value instanceof StaticSymbol) {
let baseSymbol = this.symbolResolver.getStaticSymbol(value.filePath, value.name);
const index = this.visitStaticSymbol(baseSymbol, context);
return { __symbol: index, members: value.members };
}
}
/**
* Strip line and character numbers from ngsummaries.
* Emitting them causes white spaces changes to retrigger upstream
* recompilations in bazel.
* TODO: find out a way to have line and character numbers in errors without
* excessive recompilation in bazel.
*/
visitStringMap(map, context) {
if (map['__symbolic'] === 'resolved') {
return visitValue(map['symbol'], this, context);
}
if (map['__symbolic'] === 'error') {
delete map['line'];
delete map['character'];
}
return super.visitStringMap(map, context);
}
/**
* Returns null if the options.resolveValue is true, and the summary for the symbol
* resolved to a type or could not be resolved.
*/
visitStaticSymbol(baseSymbol, flags) {
let index = this.indexBySymbol.get(baseSymbol);
let summary = null;
if (flags & 1 /* ResolveValue */ &&
this.summaryResolver.isLibraryFile(baseSymbol.filePath)) {
if (this.unprocessedSymbolSummariesBySymbol.has(baseSymbol)) {
// the summary for this symbol was already added
// -> nothing to do.
return index;
}
summary = this.loadSummary(baseSymbol);
if (summary && summary.metadata instanceof StaticSymbol) {
// The summary is a reexport
index = this.visitStaticSymbol(summary.metadata, flags);
// reset the summary as it is just a reexport, so we don't want to store it.
summary = null;
}
}
else if (index != null) {
// Note: == on purpose to compare with undefined!
// No summary and the symbol is already added -> nothing to do.
return index;
}
// Note: == on purpose to compare with undefined!
if (index == null) {
index = this.symbols.length;
this.symbols.push(baseSymbol);
}
this.indexBySymbol.set(baseSymbol, index);
if (summary) {
this.addSummary(summary);
}
return index;
}
loadSummary(symbol) {
let summary = this.summaryResolver.resolveSummary(symbol);
if (!summary) {
// some symbols might originate from a plain typescript library
// that just exported .d.ts and .metadata.json files, i.e. where no summary
// files were created.
const resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
if (resolvedSymbol) {
summary = { symbol: resolvedSymbol.symbol, metadata: resolvedSymbol.metadata };
}
}
return summary;
}
}
class ForJitSerializer {
constructor(outputCtx, symbolResolver, summaryResolver) {
this.outputCtx = outputCtx;
this.symbolResolver = symbolResolver;
this.summaryResolver = summaryResolver;
this.data = [];
}
addSourceType(summary, metadata) {
this.data.push({ summary, metadata, isLibrary: false });
}
addLibType(summary) {
this.data.push({ summary, metadata: null, isLibrary: true });
}
serialize(exportAsArr) {
const exportAsBySymbol = new Map();
for (const { symbol, exportAs } of exportAsArr) {
exportAsBySymbol.set(symbol, exportAs);
}
const ngModuleSymbols = new Set();
for (const { summary, metadata, isLibrary } of this.data) {
if (summary.summaryKind === CompileSummaryKind.NgModule) {
// collect the symbols that refer to NgModule classes.
// Note: we can't just rely on `summary.type.summaryKind` to determine this as
// we don't add the summaries of all referenced symbols when we serialize type summaries.
// See serializeSummaries for details.
ngModuleSymbols.add(summary.type.reference);
const modSummary = summary;
for (const mod of modSummary.modules) {
ngModuleSymbols.add(mod.reference);
}
}
if (!isLibrary) {
const fnName = summaryForJitName(summary.type.reference.name);
createSummaryForJitFunction(this.outputCtx, summary.type.reference, this.serializeSummaryWithDeps(summary, metadata));
}
}
ngModuleSymbols.forEach((ngModuleSymbol) => {
if (this.summaryResolver.isLibraryFile(ngModuleSymbol.filePath)) {
let exportAs = exportAsBySymbol.get(ngModuleSymbol) || ngModuleSymbol.name;
const jitExportAsName = summaryForJitName(exportAs);
this.outputCtx.statements.push(variable(jitExportAsName)
.set(this.serializeSummaryRef(ngModuleSymbol))
.toDeclStmt(null, [StmtModifier.Exported]));
}
});
}
serializeSummaryWithDeps(summary, metadata) {
const expressions = [this.serializeSummary(summary)];
let providers = [];
if (metadata instanceof CompileNgModuleMetadata) {
expressions.push(...
// For directives / pipes, we only add the declared ones,
// and rely on transitively importing NgModules to get the transitive
// summaries.
metadata.declaredDirectives.concat(metadata.declaredPipes)
.map(type => type.reference)
// For modules,
// we also add the summaries for modules
// from libraries.
// This is ok as we produce reexports for all transitive modules.
.concat(metadata.transitiveModule.modules.map(type => type.reference)
.filter(ref => ref !== metadata.type.reference))
.map((ref) => this.serializeSummaryRef(ref)));
// Note: We don't use `NgModuleSummary.providers`, as that one is transitive,
// and we already have transitive modules.
providers = metadata.providers;
}
else if (summary.summaryKind === CompileSummaryKind.Directive) {
const dirSummary = summary;
providers = dirSummary.providers.concat(dirSummary.viewProviders);
}
// Note: We can't just refer to the `ngsummary.ts` files for `useClass` providers (as we do for
// declaredDirectives / declaredPipes), as we allow
// providers without ctor arguments to skip the `@Injectable` decorator,
// i.e. we didn't generate .ngsummary.ts files for these.
expressions.push(...providers.filter(provider => !!provider.useClass).map(provider => this.serializeSummary({
summaryKind: CompileSummaryKind.Injectable,
type: provider.useClass
})));
return literalArr(expressions);
}
serializeSummaryRef(typeSymbol) {
const jitImportedSymbol = this.symbolResolver.getStaticSymbol(summaryForJitFileName(typeSymbol.filePath), summaryForJitName(typeSymbol.name));
return this.outputCtx.importExpr(jitImportedSymbol);
}
serializeSummary(data) {
const outputCtx = this.outputCtx;
class Transformer {
visitArray(arr, context) {
return literalArr(arr.map(entry => visitValue(entry, this, context)));
}
visitStringMap(map, context) {
return new LiteralMapExpr(Object.keys(map).map((key) => new LiteralMapEntry(key, visitValue(map[key], this, context), false)));
}
visitPrimitive(value, context) {
return literal(value);
}
visitOther(value, context) {
if (value instanceof StaticSymbol) {
return outputCtx.importExpr(value);
}
else {
throw new Error(`Illegal State: Encountered value ${value}`);
}
}
}
return visitValue(data, new Transformer(), null);
}
}
class FromJsonDeserializer extends ValueTransformer {
constructor(symbolCache, summaryResolver) {
super();
this.symbolCache = symbolCache;
this.summaryResolver = summaryResolver;
}
deserialize(libraryFileName, json) {
const data = JSON.parse(json);
const allImportAs = [];
this.symbols = data.symbols.map((serializedSymbol) => this.symbolCache.get(this.summaryResolver.fromSummaryFileName(serializedSymbol.filePath, libraryFileName), serializedSymbol.name));
data.symbols.forEach((serializedSymbol, index) => {
const symbol = this.symbols[index];
const importAs = serializedSymbol.importAs;
if (typeof importAs === 'number') {
allImportAs.push({ symbol, importAs: this.symbols[importAs] });
}
else if (typeof importAs === 'string') {
allImportAs.push({ symbol, importAs: this.symbolCache.get(ngfactoryFilePath(libraryFileName), importAs) });
}
});
const summaries = visitValue(data.summaries, this, null);
return { moduleName: data.moduleName, summaries, importAs: allImportAs };
}
visitStringMap(map, context) {
if ('__symbol' in map) {
const baseSymbol = this.symbols[map['__symbol']];
const members = map['members'];
return members.length ? this.symbolCache.get(baseSymbol.filePath, baseSymbol.name, members) :
baseSymbol;
}
else {
return super.visitStringMap(map, context);
}
}
}
function isCall(metadata) {
return metadata && metadata.__symbolic === 'call';
}
function isFunctionCall(metadata) {
return isCall(metadata) && unwrapResolvedMetadata(metadata.expression) instanceof StaticSymbol;
}
function isMethodCallOnVariable(metadata) {
return isCall(metadata) && metadata.expression && metadata.expression.__symbolic === 'select' &&
unwrapResolvedMetadata(metadata.expression.expression) instanceof StaticSymbol;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class AotCompiler {
constructor(_config, _options, _host, reflector, _metadataResolver, _templateParser, _styleCompiler, _viewCompiler, _typeCheckCompiler, _ngModuleCompiler, _injectableCompiler, _outputEmitter, _summaryResolver, _symbolResolver) {
this._config = _config;
this._options = _options;
this._host = _host;
this.reflector = reflector;
this._metadataResolver = _metadataResolver;
this._templateParser = _templateParser;
this._styleCompiler = _styleCompiler;
this._viewCompiler = _viewCompiler;
this._typeCheckCompiler = _typeCheckCompiler;
this._ngModuleCompiler = _ngModuleCompiler;
this._injectableCompiler = _injectableCompiler;
this._outputEmitter = _outputEmitter;
this._summaryResolver = _summaryResolver;
this._symbolResolver = _symbolResolver;
this._templateAstCache = new Map();
this._analyzedFiles = new Map();
this._analyzedFilesForInjectables = new Map();
}
clearCache() {
this._metadataResolver.clearCache();
}
analyzeModulesSync(rootFiles) {
const analyzeResult = analyzeAndValidateNgModules(rootFiles, this._host, this._symbolResolver, this._metadataResolver);
analyzeResult.ngModules.forEach(ngModule => this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, true));
return analyzeResult;
}
analyzeModulesAsync(rootFiles) {
const analyzeResult = analyzeAndValidateNgModules(rootFiles, this._host, this._symbolResolver, this._metadataResolver);
return Promise
.all(analyzeResult.ngModules.map(ngModule => this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false)))
.then(() => analyzeResult);
}
_analyzeFile(fileName) {
let analyzedFile = this._analyzedFiles.get(fileName);
if (!analyzedFile) {
analyzedFile =
analyzeFile(this._host, this._symbolResolver, this._metadataResolver, fileName);
this._analyzedFiles.set(fileName, analyzedFile);
}
return analyzedFile;
}
_analyzeFileForInjectables(fileName) {
let analyzedFile = this._analyzedFilesForInjectables.get(fileName);
if (!analyzedFile) {
analyzedFile = analyzeFileForInjectables(this._host, this._symbolResolver, this._metadataResolver, fileName);
this._analyzedFilesForInjectables.set(fileName, analyzedFile);
}
return analyzedFile;
}
findGeneratedFileNames(fileName) {
const genFileNames = [];
const file = this._analyzeFile(fileName);
// Make sure we create a .ngfactory if we have a injectable/directive/pipe/NgModule
// or a reference to a non source file.
// Note: This is overestimating the required .ngfactory files as the real calculation is harder.
// Only do this for StubEmitFlags.Basic, as adding a type check block
// does not change this file (as we generate type check blocks based on NgModules).
if (this._options.allowEmptyCodegenFiles || file.directives.length || file.pipes.length ||
file.injectables.length || file.ngModules.length || file.exportsNonSourceFiles) {
genFileNames.push(ngfactoryFilePath(file.fileName, true));
if (this._options.enableSummariesForJit) {
genFileNames.push(summaryForJitFileName(file.fileName, true));
}
}
const fileSuffix = normalizeGenFileSuffix(splitTypescriptSuffix(file.fileName, true)[1]);
file.directives.forEach((dirSymbol) => {
const compMeta = this._metadataResolver.getNonNormalizedDirectiveMetadata(dirSymbol).metadata;
if (!compMeta.isComponent) {
return;
}
// Note: compMeta is a component and therefore template is non null.
compMeta.template.styleUrls.forEach((styleUrl) => {
const normalizedUrl = this._host.resourceNameToFileName(styleUrl, file.fileName);
if (!normalizedUrl) {
throw syntaxError(`Couldn't resolve resource ${styleUrl} relative to ${file.fileName}`);
}
const needsShim = (compMeta.template.encapsulation ||
this._config.defaultEncapsulation) === ViewEncapsulation.Emulated;
genFileNames.push(_stylesModuleUrl(normalizedUrl, needsShim, fileSuffix));
if (this._options.allowEmptyCodegenFiles) {
genFileNames.push(_stylesModuleUrl(normalizedUrl, !needsShim, fileSuffix));
}
});
});
return genFileNames;
}
emitBasicStub(genFileName, originalFileName) {
const outputCtx = this._createOutputContext(genFileName);
if (genFileName.endsWith('.ngfactory.ts')) {
if (!originalFileName) {
throw new Error(`Assertion error: require the original file for .ngfactory.ts stubs. File: ${genFileName}`);
}
const originalFile = this._analyzeFile(originalFileName);
this._createNgFactoryStub(outputCtx, originalFile, 1 /* Basic */);
}
else if (genFileName.endsWith('.ngsummary.ts')) {
if (this._options.enableSummariesForJit) {
if (!originalFileName) {
throw new Error(`Assertion error: require the original file for .ngsummary.ts stubs. File: ${genFileName}`);
}
const originalFile = this._analyzeFile(originalFileName);
_createEmptyStub(outputCtx);
originalFile.ngModules.forEach(ngModule => {
// create exports that user code can reference
createForJitStub(outputCtx, ngModule.type.reference);
});
}
}
else if (genFileName.endsWith('.ngstyle.ts')) {
_createEmptyStub(outputCtx);
}
// Note: for the stubs, we don't need a property srcFileUrl,
// as later on in emitAllImpls we will create the proper GeneratedFiles with the
// correct srcFileUrl.
// This is good as e.g. for .ngstyle.ts files we can't derive
// the url of components based on the genFileUrl.
return this._codegenSourceModule('unknown', outputCtx);
}
emitTypeCheckStub(genFileName, originalFileName) {
const originalFile = this._analyzeFile(originalFileName);
const outputCtx = this._createOutputContext(genFileName);
if (genFileName.endsWith('.ngfactory.ts')) {
this._createNgFactoryStub(outputCtx, originalFile, 2 /* TypeCheck */);
}
return outputCtx.statements.length > 0 ?
this._codegenSourceModule(originalFile.fileName, outputCtx) :
null;
}
loadFilesAsync(fileNames, tsFiles) {
const files = fileNames.map(fileName => this._analyzeFile(fileName));
const loadingPromises = [];
files.forEach(file => file.ngModules.forEach(ngModule => loadingPromises.push(this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false))));
const analyzedInjectables = tsFiles.map(tsFile => this._analyzeFileForInjectables(tsFile));
return Promise.all(loadingPromises).then(_ => ({
analyzedModules: mergeAndValidateNgFiles(files),
analyzedInjectables: analyzedInjectables,
}));
}
loadFilesSync(fileNames, tsFiles) {
const files = fileNames.map(fileName => this._analyzeFile(fileName));
files.forEach(file => file.ngModules.forEach(ngModule => this._metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, true)));
const analyzedInjectables = tsFiles.map(tsFile => this._analyzeFileForInjectables(tsFile));
return {
analyzedModules: mergeAndValidateNgFiles(files),
analyzedInjectables: analyzedInjectables,
};
}
_createNgFactoryStub(outputCtx, file, emitFlags) {
let componentId = 0;
file.ngModules.forEach((ngModuleMeta, ngModuleIndex) => {
// Note: the code below needs to executed for StubEmitFlags.Basic and StubEmitFlags.TypeCheck,
// so we don't change the .ngfactory file too much when adding the type-check block.
// create exports that user code can reference
this._ngModuleCompiler.createStub(outputCtx, ngModuleMeta.type.reference);
// add references to the symbols from the metadata.
// These can be used by the type check block for components,
// and they also cause TypeScript to include these files into the program too,
// which will make them part of the analyzedFiles.
const externalReferences = [
// Add references that are available from all the modules and imports.
...ngModuleMeta.transitiveModule.directives.map(d => d.reference),
...ngModuleMeta.transitiveModule.pipes.map(d => d.reference),
...ngModuleMeta.importedModules.map(m => m.type.reference),
...ngModuleMeta.exportedModules.map(m => m.type.reference),
// Add references that might be inserted by the template compiler.
...this._externalIdentifierReferences([Identifiers.TemplateRef, Identifiers.ElementRef]),
];
const externalReferenceVars = new Map();
externalReferences.forEach((ref, typeIndex) => {
externalReferenceVars.set(ref, `_decl${ngModuleIndex}_${typeIndex}`);
});
externalReferenceVars.forEach((varName, reference) => {
outputCtx.statements.push(variable(varName)
.set(NULL_EXPR.cast(DYNAMIC_TYPE))
.toDeclStmt(expressionType(outputCtx.importExpr(reference, /* typeParams */ null, /* useSummaries */ false))));
});
if (emitFlags & 2 /* TypeCheck */) {
// add the type-check block for all components of the NgModule
ngModuleMeta.declaredDirectives.forEach((dirId) => {
const compMeta = this._metadataResolver.getDirectiveMetadata(dirId.reference);
if (!compMeta.isComponent) {
return;
}
componentId++;
this._createTypeCheckBlock(outputCtx, `${compMeta.type.reference.name}_Host_${componentId}`, ngModuleMeta, this._metadataResolver.getHostComponentMetadata(compMeta), [compMeta.type], externalReferenceVars);
this._createTypeCheckBlock(outputCtx, `${compMeta.type.reference.name}_${componentId}`, ngModuleMeta, compMeta, ngModuleMeta.transitiveModule.directives, externalReferenceVars);
});
}
});
if (outputCtx.statements.length === 0) {
_createEmptyStub(outputCtx);
}
}
_externalIdentifierReferences(references) {
const result = [];
for (let reference of references) {
const token = createTokenForExternalReference(this.reflector, reference);
if (token.identifier) {
result.push(token.identifier.reference);
}
}
return result;
}
_createTypeCheckBlock(ctx, componentId, moduleMeta, compMeta, directives, externalReferenceVars) {
const { template: parsedTemplate, pipes: usedPipes } = this._parseTemplate(compMeta, moduleMeta, directives);
ctx.statements.push(...this._typeCheckCompiler.compileComponent(componentId, compMeta, parsedTemplate, usedPipes, externalReferenceVars, ctx));
}
emitMessageBundle(analyzeResult, locale) {
const errors = [];
const htmlParser = new HtmlParser();
// TODO(vicb): implicit tags & attributes
const messageBundle = new MessageBundle(htmlParser, [], {}, locale);
analyzeResult.files.forEach(file => {
const compMetas = [];
file.directives.forEach(directiveType => {
const dirMeta = this._metadataResolver.getDirectiveMetadata(directiveType);
if (dirMeta && dirMeta.isComponent) {
compMetas.push(dirMeta);
}
});
compMetas.forEach(compMeta => {
const html = compMeta.template.template;
// Template URL points to either an HTML or TS file depending on whether
// the file is used with `templateUrl:` or `template:`, respectively.
const templateUrl = compMeta.template.templateUrl;
const interpolationConfig = InterpolationConfig.fromArray(compMeta.template.interpolation);
errors.push(...messageBundle.updateFromTemplate(html, templateUrl, interpolationConfig));
});
});
if (errors.length) {
throw new Error(errors.map(e => e.toString()).join('\n'));
}
return messageBundle;
}
emitAllPartialModules2(files) {
// Using reduce like this is a select many pattern (where map is a select pattern)
return files.reduce((r, file) => {
r.push(...this._emitPartialModule2(file.fileName, file.injectables));
return r;
}, []);
}
_emitPartialModule2(fileName, injectables) {
const context = this._createOutputContext(fileName);
injectables.forEach(injectable => this._injectableCompiler.compile(injectable, context));
if (context.statements && context.statements.length > 0) {
return [{ fileName, statements: [...context.constantPool.statements, ...context.statements] }];
}
return [];
}
emitAllImpls(analyzeResult) {
const { ngModuleByPipeOrDirective, files } = analyzeResult;
const sourceModules = files.map(file => this._compileImplFile(file.fileName, ngModuleByPipeOrDirective, file.directives, file.pipes, file.ngModules, file.injectables));
return flatten(sourceModules);
}
_compileImplFile(srcFileUrl, ngModuleByPipeOrDirective, directives, pipes, ngModules, injectables) {
const fileSuffix = normalizeGenFileSuffix(splitTypescriptSuffix(srcFileUrl, true)[1]);
const generatedFiles = [];
const outputCtx = this._createOutputContext(ngfactoryFilePath(srcFileUrl, true));
generatedFiles.push(...this._createSummary(srcFileUrl, directives, pipes, ngModules, injectables, outputCtx));
// compile all ng modules
ngModules.forEach((ngModuleMeta) => this._compileModule(outputCtx, ngModuleMeta));
// compile components
directives.forEach((dirType) => {
const compMeta = this._metadataResolver.getDirectiveMetadata(dirType);
if (!compMeta.isComponent) {
return;
}
const ngModule = ngModuleByPipeOrDirective.get(dirType);
if (!ngModule) {
throw new Error(`Internal Error: cannot determine the module for component ${identifierName(compMeta.type)}!`);
}
// compile styles
const componentStylesheet = this._styleCompiler.compileComponent(outputCtx, compMeta);
// Note: compMeta is a component and therefore template is non null.
compMeta.template.externalStylesheets.forEach((stylesheetMeta) => {
// Note: fill non shim and shim style files as they might
// be shared by component with and without ViewEncapsulation.
const shim = this._styleCompiler.needsStyleShim(compMeta);
generatedFiles.push(this._codegenStyles(srcFileUrl, compMeta, stylesheetMeta, shim, fileSuffix));
if (this._options.allowEmptyCodegenFiles) {
generatedFiles.push(this._codegenStyles(srcFileUrl, compMeta, stylesheetMeta, !shim, fileSuffix));
}
});
// compile components
const compViewVars = this._compileComponent(outputCtx, compMeta, ngModule, ngModule.transitiveModule.directives, componentStylesheet, fileSuffix);
this._compileComponentFactory(outputCtx, compMeta, ngModule, fileSuffix);
});
if (outputCtx.statements.length > 0 || this._options.allowEmptyCodegenFiles) {
const srcModule = this._codegenSourceModule(srcFileUrl, outputCtx);
generatedFiles.unshift(srcModule);
}
return generatedFiles;
}
_createSummary(srcFileName, directives, pipes, ngModules, injectables, ngFactoryCtx) {
const symbolSummaries = this._symbolResolver.getSymbolsOf(srcFileName)
.map(symbol => this._symbolResolver.resolveSymbol(symbol));
const typeData = [
...ngModules.map(meta => ({
summary: this._metadataResolver.getNgModuleSummary(meta.type.reference),
metadata: this._metadataResolver.getNgModuleMetadata(meta.type.reference)
})),
...directives.map(ref => ({
summary: this._metadataResolver.getDirectiveSummary(ref),
metadata: this._metadataResolver.getDirectiveMetadata(ref)
})),
...pipes.map(ref => ({
summary: this._metadataResolver.getPipeSummary(ref),
metadata: this._metadataResolver.getPipeMetadata(ref)
})),
...injectables.map(ref => ({
summary: this._metadataResolver.getInjectableSummary(ref.symbol),
metadata: this._metadataResolver.getInjectableSummary(ref.symbol).type
}))
];
const forJitOutputCtx = this._options.enableSummariesForJit ?
this._createOutputContext(summaryForJitFileName(srcFileName, true)) :
null;
const { json, exportAs } = serializeSummaries(srcFileName, forJitOutputCtx, this._summaryResolver, this._symbolResolver, symbolSummaries, typeData, this._options.createExternalSymbolFactoryReexports);
exportAs.forEach((entry) => {
ngFactoryCtx.statements.push(variable(entry.exportAs).set(ngFactoryCtx.importExpr(entry.symbol)).toDeclStmt(null, [
StmtModifier.Exported
]));
});
const summaryJson = new GeneratedFile(srcFileName, summaryFileName(srcFileName), json);
const result = [summaryJson];
if (forJitOutputCtx) {
result.push(this._codegenSourceModule(srcFileName, forJitOutputCtx));
}
return result;
}
_compileModule(outputCtx, ngModule) {
const providers = [];
if (this._options.locale) {
const normalizedLocale = this._options.locale.replace(/_/g, '-');
providers.push({
token: createTokenForExternalReference(this.reflector, Identifiers.LOCALE_ID),
useValue: normalizedLocale,
});
}
if (this._options.i18nFormat) {
providers.push({
token: createTokenForExternalReference(this.reflector, Identifiers.TRANSLATIONS_FORMAT),
useValue: this._options.i18nFormat
});
}
this._ngModuleCompiler.compile(outputCtx, ngModule, providers);
}
_compileComponentFactory(outputCtx, compMeta, ngModule, fileSuffix) {
const hostMeta = this._metadataResolver.getHostComponentMetadata(compMeta);
const hostViewFactoryVar = this._compileComponent(outputCtx, hostMeta, ngModule, [compMeta.type], null, fileSuffix)
.viewClassVar;
const compFactoryVar = componentFactoryName(compMeta.type.reference);
const inputsExprs = [];
for (let propName in compMeta.inputs) {
const templateName = compMeta.inputs[propName];
// Don't quote so that the key gets minified...
inputsExprs.push(new LiteralMapEntry(propName, literal(templateName), false));
}
const outputsExprs = [];
for (let propName in compMeta.outputs) {
const templateName = compMeta.outputs[propName];
// Don't quote so that the key gets minified...
outputsExprs.push(new LiteralMapEntry(propName, literal(templateName), false));
}
outputCtx.statements.push(variable(compFactoryVar)
.set(importExpr(Identifiers.createComponentFactory).callFn([
literal(compMeta.selector), outputCtx.importExpr(compMeta.type.reference),
variable(hostViewFactoryVar), new LiteralMapExpr(inputsExprs),
new LiteralMapExpr(outputsExprs),
literalArr(compMeta.template.ngContentSelectors.map(selector => literal(selector)))
]))
.toDeclStmt(importType(Identifiers.ComponentFactory, [expressionType(outputCtx.importExpr(compMeta.type.reference))], [TypeModifier.Const]), [StmtModifier.Final, StmtModifier.Exported]));
}
_compileComponent(outputCtx, compMeta, ngModule, directiveIdentifiers, componentStyles, fileSuffix) {
const { template: parsedTemplate, pipes: usedPipes } = this._parseTemplate(compMeta, ngModule, directiveIdentifiers);
const stylesExpr = componentStyles ? variable(componentStyles.stylesVar) : literalArr([]);
const viewResult = this._viewCompiler.compileComponent(outputCtx, compMeta, parsedTemplate, stylesExpr, usedPipes);
if (componentStyles) {
_resolveStyleStatements(this._symbolResolver, componentStyles, this._styleCompiler.needsStyleShim(compMeta), fileSuffix);
}
return viewResult;
}
_parseTemplate(compMeta, ngModule, directiveIdentifiers) {
if (this._templateAstCache.has(compMeta.type.reference)) {
return this._templateAstCache.get(compMeta.type.reference);
}
const preserveWhitespaces = compMeta.template.preserveWhitespaces;
const directives = directiveIdentifiers.map(dir => this._metadataResolver.getDirectiveSummary(dir.reference));
const pipes = ngModule.transitiveModule.pipes.map(pipe => this._metadataResolver.getPipeSummary(pipe.reference));
const result = this._templateParser.parse(compMeta, compMeta.template.htmlAst, directives, pipes, ngModule.schemas, templateSourceUrl(ngModule.type, compMeta, compMeta.template), preserveWhitespaces);
this._templateAstCache.set(compMeta.type.reference, result);
return result;
}
_createOutputContext(genFilePath) {
const importExpr$1 = (symbol, typeParams = null, useSummaries = true) => {
if (!(symbol instanceof StaticSymbol)) {
throw new Error(`Internal error: unknown identifier ${JSON.stringify(symbol)}`);
}
const arity = this._symbolResolver.getTypeArity(symbol) || 0;
const { filePath, name, members } = this._symbolResolver.getImportAs(symbol, useSummaries) || symbol;
const importModule = this._fileNameToModuleName(filePath, genFilePath);
// It should be good enough to compare filePath to genFilePath and if they are equal
// there is a self reference. However, ngfactory files generate to .ts but their
// symbols have .d.ts so a simple compare is insufficient. They should be canonical
// and is tracked by #17705.
const selfReference = this._fileNameToModuleName(genFilePath, genFilePath);
const moduleName = importModule === selfReference ? null : importModule;
// 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.
const suppliedTypeParams = typeParams || [];
const missingTypeParamsCount = arity - suppliedTypeParams.length;
const allTypeParams = suppliedTypeParams.concat(newArray(missingTypeParamsCount, DYNAMIC_TYPE));
return members.reduce((expr, memberName) => expr.prop(memberName), importExpr(new ExternalReference(moduleName, name, null), allTypeParams));
};
return { statements: [], genFilePath, importExpr: importExpr$1, constantPool: new ConstantPool() };
}
_fileNameToModuleName(importedFilePath, containingFilePath) {
return this._summaryResolver.getKnownModuleName(importedFilePath) ||
this._symbolResolver.getKnownModuleName(importedFilePath) ||
this._host.fileNameToModuleName(importedFilePath, containingFilePath);
}
_codegenStyles(srcFileUrl, compMeta, stylesheetMetadata, isShimmed, fileSuffix) {
const outputCtx = this._createOutputContext(_stylesModuleUrl(stylesheetMetadata.moduleUrl, isShimmed, fileSuffix));
const compiledStylesheet = this._styleCompiler.compileStyles(outputCtx, compMeta, stylesheetMetadata, isShimmed);
_resolveStyleStatements(this._symbolResolver, compiledStylesheet, isShimmed, fileSuffix);
return this._codegenSourceModule(srcFileUrl, outputCtx);
}
_codegenSourceModule(srcFileUrl, ctx) {
return new GeneratedFile(srcFileUrl, ctx.genFilePath, ctx.statements);
}
listLazyRoutes(entryRoute, analyzedModules) {
const self = this;
if (entryRoute) {
const symbol = parseLazyRoute(entryRoute, this.reflector).referencedModule;
return visitLazyRoute(symbol);
}
else if (analyzedModules) {
const allLazyRoutes = [];
for (const ngModule of analyzedModules.ngModules) {
const lazyRoutes = listLazyRoutes(ngModule, this.reflector);
for (const lazyRoute of lazyRoutes) {
allLazyRoutes.push(lazyRoute);
}
}
return allLazyRoutes;
}
else {
throw new Error(`Either route or analyzedModules has to be specified!`);
}
function visitLazyRoute(symbol, seenRoutes = new Set(), allLazyRoutes = []) {
// Support pointing to default exports, but stop recursing there,
// as the StaticReflector does not yet support default exports.
if (seenRoutes.has(symbol) || !symbol.name) {
return allLazyRoutes;
}
seenRoutes.add(symbol);
const lazyRoutes = listLazyRoutes(self._metadataResolver.getNgModuleMetadata(symbol, true), self.reflector);
for (const lazyRoute of lazyRoutes) {
allLazyRoutes.push(lazyRoute);
visitLazyRoute(lazyRoute.referencedModule, seenRoutes, allLazyRoutes);
}
return allLazyRoutes;
}
}
}
function _createEmptyStub(outputCtx) {
// Note: We need to produce at least one import statement so that
// TypeScript knows that the file is an es6 module. Otherwise our generated
// exports / imports won't be emitted properly by TypeScript.
outputCtx.statements.push(importExpr(Identifiers.ComponentFactory).toStmt());
}
function _resolveStyleStatements(symbolResolver, compileResult, needsShim, fileSuffix) {
compileResult.dependencies.forEach((dep) => {
dep.setValue(symbolResolver.getStaticSymbol(_stylesModuleUrl(dep.moduleUrl, needsShim, fileSuffix), dep.name));
});
}
function _stylesModuleUrl(stylesheetUrl, shim, suffix) {
return `${stylesheetUrl}${shim ? '.shim' : ''}.ngstyle${suffix}`;
}
function analyzeNgModules(fileNames, host, staticSymbolResolver, metadataResolver) {
const files = _analyzeFilesIncludingNonProgramFiles(fileNames, host, staticSymbolResolver, metadataResolver);
return mergeAnalyzedFiles(files);
}
function analyzeAndValidateNgModules(fileNames, host, staticSymbolResolver, metadataResolver) {
return validateAnalyzedModules(analyzeNgModules(fileNames, host, staticSymbolResolver, metadataResolver));
}
function validateAnalyzedModules(analyzedModules) {
if (analyzedModules.symbolsMissingModule && analyzedModules.symbolsMissingModule.length) {
const messages = analyzedModules.symbolsMissingModule.map(s => `Cannot determine the module for class ${s.name} in ${s.filePath}! Add ${s.name} to the NgModule to fix it.`);
throw syntaxError(messages.join('\n'));
}
return analyzedModules;
}
// Analyzes all of the program files,
// including files that are not part of the program
// but are referenced by an NgModule.
function _analyzeFilesIncludingNonProgramFiles(fileNames, host, staticSymbolResolver, metadataResolver) {
const seenFiles = new Set();
const files = [];
const visitFile = (fileName) => {
if (seenFiles.has(fileName) || !host.isSourceFile(fileName)) {
return false;
}
seenFiles.add(fileName);
const analyzedFile = analyzeFile(host, staticSymbolResolver, metadataResolver, fileName);
files.push(analyzedFile);
analyzedFile.ngModules.forEach(ngModule => {
ngModule.transitiveModule.modules.forEach(modMeta => visitFile(modMeta.reference.filePath));
});
};
fileNames.forEach((fileName) => visitFile(fileName));
return files;
}
function analyzeFile(host, staticSymbolResolver, metadataResolver, fileName) {
const abstractDirectives = [];
const directives = [];
const pipes = [];
const injectables = [];
const ngModules = [];
const hasDecorators = staticSymbolResolver.hasDecorators(fileName);
let exportsNonSourceFiles = false;
const isDeclarationFile = fileName.endsWith('.d.ts');
// Don't analyze .d.ts files that have no decorators as a shortcut
// to speed up the analysis. This prevents us from
// resolving the references in these files.
// Note: exportsNonSourceFiles is only needed when compiling with summaries,
// which is not the case when .d.ts files are treated as input files.
if (!isDeclarationFile || hasDecorators) {
staticSymbolResolver.getSymbolsOf(fileName).forEach((symbol) => {
const resolvedSymbol = staticSymbolResolver.resolveSymbol(symbol);
const symbolMeta = resolvedSymbol.metadata;
if (!symbolMeta || symbolMeta.__symbolic === 'error') {
return;
}
let isNgSymbol = false;
if (symbolMeta.__symbolic === 'class') {
if (metadataResolver.isDirective(symbol)) {
isNgSymbol = true;
// This directive either has a selector or doesn't. Selector-less directives get tracked
// in abstractDirectives, not directives. The compiler doesn't deal with selector-less
// directives at all, really, other than to persist their metadata. This is done so that
// apps will have an easier time migrating to Ivy, which requires the selector-less
// annotations to be applied.
if (!metadataResolver.isAbstractDirective(symbol)) {
// The directive is an ordinary directive.
directives.push(symbol);
}
else {
// The directive has no selector and is an "abstract" directive, so track it
// accordingly.
abstractDirectives.push(symbol);
}
}
else if (metadataResolver.isPipe(symbol)) {
isNgSymbol = true;
pipes.push(symbol);
}
else if (metadataResolver.isNgModule(symbol)) {
const ngModule = metadataResolver.getNgModuleMetadata(symbol, false);
if (ngModule) {
isNgSymbol = true;
ngModules.push(ngModule);
}
}
else if (metadataResolver.isInjectable(symbol)) {
isNgSymbol = true;
const injectable = metadataResolver.getInjectableMetadata(symbol, null, false);
if (injectable) {
injectables.push(injectable);
}
}
}
if (!isNgSymbol) {
exportsNonSourceFiles =
exportsNonSourceFiles || isValueExportingNonSourceFile(host, symbolMeta);
}
});
}
return {
fileName,
directives,
abstractDirectives,
pipes,
ngModules,
injectables,
exportsNonSourceFiles,
};
}
function analyzeFileForInjectables(host, staticSymbolResolver, metadataResolver, fileName) {
const injectables = [];
const shallowModules = [];
if (staticSymbolResolver.hasDecorators(fileName)) {
staticSymbolResolver.getSymbolsOf(fileName).forEach((symbol) => {
const resolvedSymbol = staticSymbolResolver.resolveSymbol(symbol);
const symbolMeta = resolvedSymbol.metadata;
if (!symbolMeta || symbolMeta.__symbolic === 'error') {
return;
}
if (symbolMeta.__symbolic === 'class') {
if (metadataResolver.isInjectable(symbol)) {
const injectable = metadataResolver.getInjectableMetadata(symbol, null, false);
if (injectable) {
injectables.push(injectable);
}
}
else if (metadataResolver.isNgModule(symbol)) {
const module = metadataResolver.getShallowModuleMetadata(symbol);
if (module) {
shallowModules.push(module);
}
}
}
});
}
return { fileName, injectables, shallowModules };
}
function isValueExportingNonSourceFile(host, metadata) {
let exportsNonSourceFiles = false;
class Visitor {
visitArray(arr, context) {
arr.forEach(v => visitValue(v, this, context));
}
visitStringMap(map, context) {
Object.keys(map).forEach((key) => visitValue(map[key], this, context));
}
visitPrimitive(value, context) { }
visitOther(value, context) {
if (value instanceof StaticSymbol && !host.isSourceFile(value.filePath)) {
exportsNonSourceFiles = true;
}
}
}
visitValue(metadata, new Visitor(), null);
return exportsNonSourceFiles;
}
function mergeAnalyzedFiles(analyzedFiles) {
const allNgModules = [];
const ngModuleByPipeOrDirective = new Map();
const allPipesAndDirectives = new Set();
analyzedFiles.forEach(af => {
af.ngModules.forEach(ngModule => {
allNgModules.push(ngModule);
ngModule.declaredDirectives.forEach(d => ngModuleByPipeOrDirective.set(d.reference, ngModule));
ngModule.declaredPipes.forEach(p => ngModuleByPipeOrDirective.set(p.reference, ngModule));
});
af.directives.forEach(d => allPipesAndDirectives.add(d));
af.pipes.forEach(p => allPipesAndDirectives.add(p));
});
const symbolsMissingModule = [];
allPipesAndDirectives.forEach(ref => {
if (!ngModuleByPipeOrDirective.has(ref)) {
symbolsMissingModule.push(ref);
}
});
return {
ngModules: allNgModules,
ngModuleByPipeOrDirective,
symbolsMissingModule,
files: analyzedFiles
};
}
function mergeAndValidateNgFiles(files) {
return validateAnalyzedModules(mergeAnalyzedFiles(files));
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const FORMATTED_MESSAGE = 'ngFormattedMessage';
function indentStr(level) {
if (level <= 0)
return '';
if (level < 6)
return ['', ' ', ' ', ' ', ' ', ' '][level];
const half = indentStr(Math.floor(level / 2));
return half + half + (level % 2 === 1 ? ' ' : '');
}
function formatChain(chain, indent = 0) {
if (!chain)
return '';
const position = chain.position ?
`${chain.position.fileName}(${chain.position.line + 1},${chain.position.column + 1})` :
'';
const prefix = position && indent === 0 ? `${position}: ` : '';
const postfix = position && indent !== 0 ? ` at ${position}` : '';
let message = `${prefix}${chain.message}${postfix}`;
if (chain.next) {
for (const kid of chain.next) {
message += '\n' + formatChain(kid, indent + 2);
}
}
return `${indentStr(indent)}${message}`;
}
function formattedError(chain) {
const message = formatChain(chain) + '.';
const error = syntaxError(message);
error[FORMATTED_MESSAGE] = true;
error.chain = chain;
error.position = chain.position;
return error;
}
function isFormattedError(error) {
return !!error[FORMATTED_MESSAGE];
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
const ANGULAR_CORE = '@angular/core';
const ANGULAR_ROUTER = '@angular/router';
const HIDDEN_KEY = /^\$.*\$$/;
const IGNORE = {
__symbolic: 'ignore'
};
const USE_VALUE$1 = 'useValue';
const PROVIDE = 'provide';
const REFERENCE_SET = new Set([USE_VALUE$1, 'useFactory', 'data', 'id', 'loadChildren']);
const TYPEGUARD_POSTFIX = 'TypeGuard';
const USE_IF = 'UseIf';
function shouldIgnore(value) {
return value && value.__symbolic == 'ignore';
}
/**
* A static reflector implements enough of the Reflector API that is necessary to compile
* templates statically.
*/
class StaticReflector {
constructor(summaryResolver, symbolResolver, knownMetadataClasses = [], knownMetadataFunctions = [], errorRecorder) {
this.summaryResolver = summaryResolver;
this.symbolResolver = symbolResolver;
this.errorRecorder = errorRecorder;
this.annotationCache = new Map();
this.shallowAnnotationCache = new Map();
this.propertyCache = new Map();
this.parameterCache = new Map();
this.methodCache = new Map();
this.staticCache = new Map();
this.conversionMap = new Map();
this.resolvedExternalReferences = new Map();
this.annotationForParentClassWithSummaryKind = new Map();
this.initializeConversionMap();
knownMetadataClasses.forEach((kc) => this._registerDecoratorOrConstructor(this.getStaticSymbol(kc.filePath, kc.name), kc.ctor));
knownMetadataFunctions.forEach((kf) => this._registerFunction(this.getStaticSymbol(kf.filePath, kf.name), kf.fn));
this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Directive, [createDirective, createComponent]);
this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Pipe, [createPipe]);
this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.NgModule, [createNgModule]);
this.annotationForParentClassWithSummaryKind.set(CompileSummaryKind.Injectable, [createInjectable, createPipe, createDirective, createComponent, createNgModule]);
}
componentModuleUrl(typeOrFunc) {
const staticSymbol = this.findSymbolDeclaration(typeOrFunc);
return this.symbolResolver.getResourcePath(staticSymbol);
}
/**
* Invalidate the specified `symbols` on program change.
* @param symbols
*/
invalidateSymbols(symbols) {
for (const symbol of symbols) {
this.annotationCache.delete(symbol);
this.shallowAnnotationCache.delete(symbol);
this.propertyCache.delete(symbol);
this.parameterCache.delete(symbol);
this.methodCache.delete(symbol);
this.staticCache.delete(symbol);
this.conversionMap.delete(symbol);
}
}
resolveExternalReference(ref, containingFile) {
let key = undefined;
if (!containingFile) {
key = `${ref.moduleName}:${ref.name}`;
const declarationSymbol = this.resolvedExternalReferences.get(key);
if (declarationSymbol)
return declarationSymbol;
}
const refSymbol = this.symbolResolver.getSymbolByModule(ref.moduleName, ref.name, containingFile);
const declarationSymbol = this.findSymbolDeclaration(refSymbol);
if (!containingFile) {
this.symbolResolver.recordModuleNameForFileName(refSymbol.filePath, ref.moduleName);
this.symbolResolver.recordImportAs(declarationSymbol, refSymbol);
}
if (key) {
this.resolvedExternalReferences.set(key, declarationSymbol);
}
return declarationSymbol;
}
findDeclaration(moduleUrl, name, containingFile) {
return this.findSymbolDeclaration(this.symbolResolver.getSymbolByModule(moduleUrl, name, containingFile));
}
tryFindDeclaration(moduleUrl, name, containingFile) {
return this.symbolResolver.ignoreErrorsFor(() => this.findDeclaration(moduleUrl, name, containingFile));
}
findSymbolDeclaration(symbol) {
const resolvedSymbol = this.symbolResolver.resolveSymbol(symbol);
if (resolvedSymbol) {
let resolvedMetadata = resolvedSymbol.metadata;
if (resolvedMetadata && resolvedMetadata.__symbolic === 'resolved') {
resolvedMetadata = resolvedMetadata.symbol;
}
if (resolvedMetadata instanceof StaticSymbol) {
return this.findSymbolDeclaration(resolvedSymbol.metadata);
}
}
return symbol;
}
tryAnnotations(type) {
const originalRecorder = this.errorRecorder;
this.errorRecorder = (error, fileName) => { };
try {
return this.annotations(type);
}
finally {
this.errorRecorder = originalRecorder;
}
}
annotations(type) {
return this._annotations(type, (type, decorators) => this.simplify(type, decorators), this.annotationCache);
}
shallowAnnotations(type) {
return this._annotations(type, (type, decorators) => this.simplify(type, decorators, true), this.shallowAnnotationCache);
}
_annotations(type, simplify, annotationCache) {
let annotations = annotationCache.get(type);
if (!annotations) {
annotations = [];
const classMetadata = this.getTypeMetadata(type);
const parentType = this.findParentType(type, classMetadata);
if (parentType) {
const parentAnnotations = this.annotations(parentType);
annotations.push(...parentAnnotations);
}
let ownAnnotations = [];
if (classMetadata['decorators']) {
ownAnnotations = simplify(type, classMetadata['decorators']);
if (ownAnnotations) {
annotations.push(...ownAnnotations);
}
}
if (parentType && !this.summaryResolver.isLibraryFile(type.filePath) &&
this.summaryResolver.isLibraryFile(parentType.filePath)) {
const summary = this.summaryResolver.resolveSummary(parentType);
if (summary && summary.type) {
const requiredAnnotationTypes = this.annotationForParentClassWithSummaryKind.get(summary.type.summaryKind);
const typeHasRequiredAnnotation = requiredAnnotationTypes.some((requiredType) => ownAnnotations.some(ann => requiredType.isTypeOf(ann)));
if (!typeHasRequiredAnnotation) {
this.reportError(formatMetadataError(metadataError(`Class ${type.name} in ${type.filePath} extends from a ${CompileSummaryKind[summary.type.summaryKind]} in another compilation unit without duplicating the decorator`,
/* summary */ undefined, `Please add a ${requiredAnnotationTypes.map((type) => type.ngMetadataName)
.join(' or ')} decorator to the class`), type), type);
}
}
}
annotationCache.set(type, annotations.filter(ann => !!ann));
}
return annotations;
}
propMetadata(type) {
let propMetadata = this.propertyCache.get(type);
if (!propMetadata) {
const classMetadata = this.getTypeMetadata(type);
propMetadata = {};
const parentType = this.findParentType(type, classMetadata);
if (parentType) {
const parentPropMetadata = this.propMetadata(parentType);
Object.keys(parentPropMetadata).forEach((parentProp) => {
propMetadata[parentProp] = parentPropMetadata[parentProp];
});
}
const members = classMetadata['members'] || {};
Object.keys(members).forEach((propName) => {
const propData = members[propName];
const prop = propData
.find(a => a['__symbolic'] == 'property' || a['__symbolic'] == 'method');
const decorators = [];
// hasOwnProperty() is used here to make sure we do not look up methods
// on `Object.prototype`.
if (propMetadata === null || propMetadata === void 0 ? void 0 : propMetadata.hasOwnProperty(propName)) {
decorators.push(...propMetadata[propName]);
}
propMetadata[propName] = decorators;
if (prop && prop['decorators']) {
decorators.push(...this.simplify(type, prop['decorators']));
}
});
this.propertyCache.set(type, propMetadata);
}
return propMetadata;
}
parameters(type) {
if (!(type instanceof StaticSymbol)) {
this.reportError(new Error(`parameters received ${JSON.stringify(type)} which is not a StaticSymbol`), type);
return [];
}
try {
let parameters = this.parameterCache.get(type);
if (!parameters) {
const classMetadata = this.getTypeMetadata(type);
const parentType = this.findParentType(type, classMetadata);
const members = classMetadata ? classMetadata['members'] : null;
const ctorData = members ? members['__ctor__'] : null;
if (ctorData) {
const ctor = ctorData.find(a => a['__symbolic'] == 'constructor');
const rawParameterTypes = ctor['parameters'] || [];
const parameterDecorators = this.simplify(type, ctor['parameterDecorators'] || []);
parameters = [];
rawParameterTypes.forEach((rawParamType, index) => {
const nestedResult = [];
const paramType = this.trySimplify(type, rawParamType);
if (paramType)
nestedResult.push(paramType);
const decorators = parameterDecorators ? parameterDecorators[index] : null;
if (decorators) {
nestedResult.push(...decorators);
}
parameters.push(nestedResult);
});
}
else if (parentType) {
parameters = this.parameters(parentType);
}
if (!parameters) {
parameters = [];
}
this.parameterCache.set(type, parameters);
}
return parameters;
}
catch (e) {
console.error(`Failed on type ${JSON.stringify(type)} with error ${e}`);
throw e;
}
}
_methodNames(type) {
let methodNames = this.methodCache.get(type);
if (!methodNames) {
const classMetadata = this.getTypeMetadata(type);
methodNames = {};
const parentType = this.findParentType(type, classMetadata);
if (parentType) {
const parentMethodNames = this._methodNames(parentType);
Object.keys(parentMethodNames).forEach((parentProp) => {
methodNames[parentProp] = parentMethodNames[parentProp];
});
}
const members = classMetadata['members'] || {};
Object.keys(members).forEach((propName) => {
const propData = members[propName];
const isMethod = propData.some(a => a['__symbolic'] == 'method');
methodNames[propName] = methodNames[propName] || isMethod;
});
this.methodCache.set(type, methodNames);
}
return methodNames;
}
_staticMembers(type) {
let staticMembers = this.staticCache.get(type);
if (!staticMembers) {
const classMetadata = this.getTypeMetadata(type);
const staticMemberData = classMetadata['statics'] || {};
staticMembers = Object.keys(staticMemberData);
this.staticCache.set(type, staticMembers);
}
return staticMembers;
}
findParentType(type, classMetadata) {
const parentType = this.trySimplify(type, classMetadata['extends']);
if (parentType instanceof StaticSymbol) {
return parentType;
}
}
hasLifecycleHook(type, lcProperty) {
if (!(type instanceof StaticSymbol)) {
this.reportError(new Error(`hasLifecycleHook received ${JSON.stringify(type)} which is not a StaticSymbol`), type);
}
try {
return !!this._methodNames(type)[lcProperty];
}
catch (e) {
console.error(`Failed on type ${JSON.stringify(type)} with error ${e}`);
throw e;
}
}
guards(type) {
if (!(type instanceof StaticSymbol)) {
this.reportError(new Error(`guards received ${JSON.stringify(type)} which is not a StaticSymbol`), type);
return {};
}
const staticMembers = this._staticMembers(type);
const result = {};
for (let name of staticMembers) {
if (name.endsWith(TYPEGUARD_POSTFIX)) {
let property = name.substr(0, name.length - TYPEGUARD_POSTFIX.length);
let value;
if (property.endsWith(USE_IF)) {
property = name.substr(0, property.length - USE_IF.length);
value = USE_IF;
}
else {
value = this.getStaticSymbol(type.filePath, type.name, [name]);
}
result[property] = value;
}
}
return result;
}
_registerDecoratorOrConstructor(type, ctor) {
this.conversionMap.set(type, (context, args) => new ctor(...args));
}
_registerFunction(type, fn) {
this.conversionMap.set(type, (context, args) => fn.apply(undefined, args));
}
initializeConversionMap() {
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Injectable'), createInjectable);
this.injectionToken = this.findDeclaration(ANGULAR_CORE, 'InjectionToken');
this.opaqueToken = this.findDeclaration(ANGULAR_CORE, 'OpaqueToken');
this.ROUTES = this.tryFindDeclaration(ANGULAR_ROUTER, 'ROUTES');
this.ANALYZE_FOR_ENTRY_COMPONENTS =
this.findDeclaration(ANGULAR_CORE, 'ANALYZE_FOR_ENTRY_COMPONENTS');
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), createHost);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), createSelf);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), createSkipSelf);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Inject'), createInject);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Optional'), createOptional);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Attribute'), createAttribute);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ContentChild'), createContentChild);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ContentChildren'), createContentChildren);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ViewChild'), createViewChild);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'ViewChildren'), createViewChildren);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Input'), createInput);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Output'), createOutput);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Pipe'), createPipe);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'HostBinding'), createHostBinding);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'HostListener'), createHostListener);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Directive'), createDirective);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Component'), createComponent);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'NgModule'), createNgModule);
// Note: Some metadata classes can be used directly with Provider.deps.
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Host'), createHost);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Self'), createSelf);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'SkipSelf'), createSkipSelf);
this._registerDecoratorOrConstructor(this.findDeclaration(ANGULAR_CORE, 'Optional'), createOptional);
}
/**
* getStaticSymbol produces a Type whose metadata is known but whose implementation is not loaded.
* All types passed to the StaticResolver should be pseudo-types returned by this method.
*
* @param declarationFile the absolute path of the file where the symbol is declared
* @param name the name of the type.
*/
getStaticSymbol(declarationFile, name, members) {
return this.symbolResolver.getStaticSymbol(declarationFile, name, members);
}
/**
* Simplify but discard any errors
*/
trySimplify(context, value) {
const originalRecorder = this.errorRecorder;
this.errorRecorder = (error, fileName) => { };
const result = this.simplify(context, value);
this.errorRecorder = originalRecorder;
return result;
}
/** @internal */
simplify(context, value, lazy = false) {
const self = this;
let scope = BindingScope$1.empty;
const calling = new Map();
const rootContext = context;
function simplifyInContext(context, value, depth, references) {
function resolveReferenceValue(staticSymbol) {
const resolvedSymbol = self.symbolResolver.resolveSymbol(staticSymbol);
return resolvedSymbol ? resolvedSymbol.metadata : null;
}
function simplifyEagerly(value) {
return simplifyInContext(context, value, depth, 0);
}
function simplifyLazily(value) {
return simplifyInContext(context, value, depth, references + 1);
}
function simplifyNested(nestedContext, value) {
if (nestedContext === context) {
// If the context hasn't changed let the exception propagate unmodified.
return simplifyInContext(nestedContext, value, depth + 1, references);
}
try {
return simplifyInContext(nestedContext, value, depth + 1, references);
}
catch (e) {
if (isMetadataError(e)) {
// Propagate the message text up but add a message to the chain that explains how we got
// here.
// e.chain implies e.symbol
const summaryMsg = e.chain ? 'references \'' + e.symbol.name + '\'' : errorSummary(e);
const summary = `'${nestedContext.name}' ${summaryMsg}`;
const chain = { message: summary, position: e.position, next: e.chain };
// TODO(chuckj): retrieve the position information indirectly from the collectors node
// map if the metadata is from a .ts file.
self.error({
message: e.message,
advise: e.advise,
context: e.context,
chain,
symbol: nestedContext
}, context);
}
else {
// It is probably an internal error.
throw e;
}
}
}
function simplifyCall(functionSymbol, targetFunction, args, targetExpression) {
if (targetFunction && targetFunction['__symbolic'] == 'function') {
if (calling.get(functionSymbol)) {
self.error({
message: 'Recursion is not supported',
summary: `called '${functionSymbol.name}' recursively`,
value: targetFunction
}, functionSymbol);
}
try {
const value = targetFunction['value'];
if (value && (depth != 0 || value.__symbolic != 'error')) {
const parameters = targetFunction['parameters'];
const defaults = targetFunction.defaults;
args = args.map(arg => simplifyNested(context, arg))
.map(arg => shouldIgnore(arg) ? undefined : arg);
if (defaults && defaults.length > args.length) {
args.push(...defaults.slice(args.length).map((value) => simplify(value)));
}
calling.set(functionSymbol, true);
const functionScope = BindingScope$1.build();
for (let i = 0; i < parameters.length; i++) {
functionScope.define(parameters[i], args[i]);
}
const oldScope = scope;
let result;
try {
scope = functionScope.done();
result = simplifyNested(functionSymbol, value);
}
finally {
scope = oldScope;
}
return result;
}
}
finally {
calling.delete(functionSymbol);
}
}
if (depth === 0) {
// If depth is 0 we are evaluating the top level expression that is describing element
// decorator. In this case, it is a decorator we don't understand, such as a custom
// non-angular decorator, and we should just ignore it.
return IGNORE;
}
let position = undefined;
if (targetExpression && targetExpression.__symbolic == 'resolved') {
const line = targetExpression.line;
const character = targetExpression.character;
const fileName = targetExpression.fileName;
if (fileName != null && line != null && character != null) {
position = { fileName, line, column: character };
}
}
self.error({
message: FUNCTION_CALL_NOT_SUPPORTED,
context: functionSymbol,
value: targetFunction,
position
}, context);
}
function simplify(expression) {
if (isPrimitive(expression)) {
return expression;
}
if (Array.isArray(expression)) {
const result = [];
for (const item of expression) {
// Check for a spread expression
if (item && item.__symbolic === 'spread') {
// We call with references as 0 because we require the actual value and cannot
// tolerate a reference here.
const spreadArray = simplifyEagerly(item.expression);
if (Array.isArray(spreadArray)) {
for (const spreadItem of spreadArray) {
result.push(spreadItem);
}
continue;
}
}
const value = simplify(item);
if (shouldIgnore(value)) {
continue;
}
result.push(value);
}
return result;
}
if (expression instanceof StaticSymbol) {
// Stop simplification at builtin symbols or if we are in a reference context and
// the symbol doesn't have members.
if (expression === self.injectionToken || self.conversionMap.has(expression) ||
(references > 0 && !expression.members.length)) {
return expression;
}
else {
const staticSymbol = expression;
const declarationValue = resolveReferenceValue(staticSymbol);
if (declarationValue != null) {
return simplifyNested(staticSymbol, declarationValue);
}
else {
return staticSymbol;
}
}
}
if (expression) {
if (expression['__symbolic']) {
let staticSymbol;
switch (expression['__symbolic']) {
case 'binop':
let left = simplify(expression['left']);
if (shouldIgnore(left))
return left;
let right = simplify(expression['right']);
if (shouldIgnore(right))
return right;
switch (expression['operator']) {
case '&&':
return left && right;
case '||':
return left || right;
case '|':
return left | right;
case '^':
return left ^ right;
case '&':
return left & right;
case '==':
return left == right;
case '!=':
return left != right;
case '===':
return left === right;
case '!==':
return left !== right;
case '<':
return left < right;
case '>':
return left > right;
case '<=':
return left <= right;
case '>=':
return left >= right;
case '<<':
return left << right;
case '>>':
return left >> right;
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
case '%':
return left % right;
}
return null;
case 'if':
let condition = simplify(expression['condition']);
return condition ? simplify(expression['thenExpression']) :
simplify(expression['elseExpression']);
case 'pre':
let operand = simplify(expression['operand']);
if (shouldIgnore(operand))
return operand;
switch (expression['operator']) {
case '+':
return operand;
case '-':
return -operand;
case '!':
return !operand;
case '~':
return ~operand;
}
return null;
case 'index':
let indexTarget = simplifyEagerly(expression['expression']);
let index = simplifyEagerly(expression['index']);
if (indexTarget && isPrimitive(index))
return indexTarget[index];
return null;
case 'select':
const member = expression['member'];
let selectContext = context;
let selectTarget = simplify(expression['expression']);
if (selectTarget instanceof StaticSymbol) {
const members = selectTarget.members.concat(member);
selectContext =
self.getStaticSymbol(selectTarget.filePath, selectTarget.name, members);
const declarationValue = resolveReferenceValue(selectContext);
if (declarationValue != null) {
return simplifyNested(selectContext, declarationValue);
}
else {
return selectContext;
}
}
if (selectTarget && isPrimitive(member))
return simplifyNested(selectContext, selectTarget[member]);
return null;
case 'reference':
// Note: This only has to deal with variable references, as symbol references have
// been converted into 'resolved'
// in the StaticSymbolResolver.
const name = expression['name'];
const localValue = scope.resolve(name);
if (localValue != BindingScope$1.missing) {
return localValue;
}
break;
case 'resolved':
try {
return simplify(expression.symbol);
}
catch (e) {
// If an error is reported evaluating the symbol record the position of the
// reference in the error so it can
// be reported in the error message generated from the exception.
if (isMetadataError(e) && expression.fileName != null &&
expression.line != null && expression.character != null) {
e.position = {
fileName: expression.fileName,
line: expression.line,
column: expression.character
};
}
throw e;
}
case 'class':
return context;
case 'function':
return context;
case 'new':
case 'call':
// Determine if the function is a built-in conversion
staticSymbol = simplifyInContext(context, expression['expression'], depth + 1, /* references */ 0);
if (staticSymbol instanceof StaticSymbol) {
if (staticSymbol === self.injectionToken || staticSymbol === self.opaqueToken) {
// if somebody calls new InjectionToken, don't create an InjectionToken,
// but rather return the symbol to which the InjectionToken is assigned to.
// OpaqueToken is supported too as it is required by the language service to
// support v4 and prior versions of Angular.
return context;
}
const argExpressions = expression['arguments'] || [];
let converter = self.conversionMap.get(staticSymbol);
if (converter) {
const args = argExpressions.map(arg => simplifyNested(context, arg))
.map(arg => shouldIgnore(arg) ? undefined : arg);
return converter(context, args);
}
else {
// Determine if the function is one we can simplify.
const targetFunction = resolveReferenceValue(staticSymbol);
return simplifyCall(staticSymbol, targetFunction, argExpressions, expression['expression']);
}
}
return IGNORE;
case 'error':
let message = expression.message;
if (expression['line'] != null) {
self.error({
message,
context: expression.context,
value: expression,
position: {
fileName: expression['fileName'],
line: expression['line'],
column: expression['character']
}
}, context);
}
else {
self.error({ message, context: expression.context }, context);
}
return IGNORE;
case 'ignore':
return expression;
}
return null;
}
return mapStringMap(expression, (value, name) => {
if (REFERENCE_SET.has(name)) {
if (name === USE_VALUE$1 && PROVIDE in expression) {
// If this is a provider expression, check for special tokens that need the value
// during analysis.
const provide = simplify(expression.provide);
if (provide === self.ROUTES || provide == self.ANALYZE_FOR_ENTRY_COMPONENTS) {
return simplify(value);
}
}
return simplifyLazily(value);
}
return simplify(value);
});
}
return IGNORE;
}
return simplify(value);
}
let result;
try {
result = simplifyInContext(context, value, 0, lazy ? 1 : 0);
}
catch (e) {
if (this.errorRecorder) {
this.reportError(e, context);
}
else {
throw formatMetadataError(e, context);
}
}
if (shouldIgnore(result)) {
return undefined;
}
return result;
}
getTypeMetadata(type) {
const resolvedSymbol = this.symbolResolver.resolveSymbol(type);
return resolvedSymbol && resolvedSymbol.metadata ? resolvedSymbol.metadata :
{ __symbolic: 'class' };
}
reportError(error, context, path) {
if (this.errorRecorder) {
this.errorRecorder(formatMetadataError(error, context), (context && context.filePath) || path);
}
else {
throw error;
}
}
error({ message, summary, advise, position, context, value, symbol, chain }, reportingContext) {
this.reportError(metadataError(message, summary, advise, position, symbol, context, chain), reportingContext);
}
}
const METADATA_ERROR = 'ngMetadataError';
function metadataError(message, summary, advise, position, symbol, context, chain) {
const error = syntaxError(message);
error[METADATA_ERROR] = true;
if (advise)
error.advise = advise;
if (position)
error.position = position;
if (summary)
error.summary = summary;
if (context)
error.context = context;
if (chain)
error.chain = chain;
if (symbol)
error.symbol = symbol;
return error;
}
function isMetadataError(error) {
return !!error[METADATA_ERROR];
}
const REFERENCE_TO_NONEXPORTED_CLASS = 'Reference to non-exported class';
const VARIABLE_NOT_INITIALIZED = 'Variable not initialized';
const DESTRUCTURE_NOT_SUPPORTED = 'Destructuring not supported';
const COULD_NOT_RESOLVE_TYPE = 'Could not resolve type';
const FUNCTION_CALL_NOT_SUPPORTED = 'Function call not supported';
const REFERENCE_TO_LOCAL_SYMBOL = 'Reference to a local symbol';
const LAMBDA_NOT_SUPPORTED = 'Lambda not supported';
function expandedMessage(message, context) {
switch (message) {
case REFERENCE_TO_NONEXPORTED_CLASS:
if (context && context.className) {
return `References to a non-exported class are not supported in decorators but ${context.className} was referenced.`;
}
break;
case VARIABLE_NOT_INITIALIZED:
return 'Only initialized variables and constants can be referenced in decorators because the value of this variable is needed by the template compiler';
case DESTRUCTURE_NOT_SUPPORTED:
return 'Referencing an exported destructured variable or constant is not supported in decorators and this value is needed by the template compiler';
case COULD_NOT_RESOLVE_TYPE:
if (context && context.typeName) {
return `Could not resolve type ${context.typeName}`;
}
break;
case FUNCTION_CALL_NOT_SUPPORTED:
if (context && context.name) {
return `Function calls are not supported in decorators but '${context.name}' was called`;
}
return 'Function calls are not supported in decorators';
case REFERENCE_TO_LOCAL_SYMBOL:
if (context && context.name) {
return `Reference to a local (non-exported) symbols are not supported in decorators but '${context.name}' was referenced`;
}
break;
case LAMBDA_NOT_SUPPORTED:
return `Function expressions are not supported in decorators`;
}
return message;
}
function messageAdvise(message, context) {
switch (message) {
case REFERENCE_TO_NONEXPORTED_CLASS:
if (context && context.className) {
return `Consider exporting '${context.className}'`;
}
break;
case DESTRUCTURE_NOT_SUPPORTED:
return 'Consider simplifying to avoid destructuring';
case REFERENCE_TO_LOCAL_SYMBOL:
if (context && context.name) {
return `Consider exporting '${context.name}'`;
}
break;
case LAMBDA_NOT_SUPPORTED:
return `Consider changing the function expression into an exported function`;
}
return undefined;
}
function errorSummary(error) {
if (error.summary) {
return error.summary;
}
switch (error.message) {
case REFERENCE_TO_NONEXPORTED_CLASS:
if (error.context && error.context.className) {
return `references non-exported class ${error.context.className}`;
}
break;
case VARIABLE_NOT_INITIALIZED:
return 'is not initialized';
case DESTRUCTURE_NOT_SUPPORTED:
return 'is a destructured variable';
case COULD_NOT_RESOLVE_TYPE:
return 'could not be resolved';
case FUNCTION_CALL_NOT_SUPPORTED:
if (error.context && error.context.name) {
return `calls '${error.context.name}'`;
}
return `calls a function`;
case REFERENCE_TO_LOCAL_SYMBOL:
if (error.context && error.context.name) {
return `references local variable ${error.context.name}`;
}
return `references a local variable`;
}
return 'contains the error';
}
function mapStringMap(input, transform) {
if (!input)
return {};
const result = {};
Object.keys(input).forEach((key) => {
const value = transform(input[key], key);
if (!shouldIgnore(value)) {
if (HIDDEN_KEY.test(key)) {
Object.defineProperty(result, key, { enumerable: false, configurable: true, value: value });
}
else {
result[key] = value;
}
}
});
return result;
}
function isPrimitive(o) {
return o === null || (typeof o !== 'function' && typeof o !== 'object');
}
class BindingScope$1 {
static build() {
const current = new Map();
return {
define: function (name, value) {
current.set(name, value);
return this;
},
done: function () {
return current.size > 0 ? new PopulatedScope(current) : BindingScope$1.empty;
}
};
}
}
BindingScope$1.missing = {};
BindingScope$1.empty = { resolve: name => BindingScope$1.missing };
class PopulatedScope extends BindingScope$1 {
constructor(bindings) {
super();
this.bindings = bindings;
}
resolve(name) {
return this.bindings.has(name) ? this.bindings.get(name) : BindingScope$1.missing;
}
}
function formatMetadataMessageChain(chain, advise) {
const expanded = expandedMessage(chain.message, chain.context);
const nesting = chain.symbol ? ` in '${chain.symbol.name}'` : '';
const message = `${expanded}${nesting}`;
const position = chain.position;
const next = chain.next ?
formatMetadataMessageChain(chain.next, advise) :
advise ? { message: advise } : undefined;
return { message, position, next: next ? [next] : undefined };
}
function formatMetadataError(e, context) {
if (isMetadataError(e)) {
// Produce a formatted version of the and leaving enough information in the original error
// to recover the formatting information to eventually produce a diagnostic error message.
const position = e.position;
const chain = {
message: `Error during template compile of '${context.name}'`,
position: position,
next: { message: e.message, next: e.chain, context: e.context, symbol: e.symbol }
};
const advise = e.advise || messageAdvise(e.message, e.context);
return formattedError(formatMetadataMessageChain(chain, advise));
}
return e;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class AotSummaryResolver {
constructor(host, staticSymbolCache) {
this.host = host;
this.staticSymbolCache = staticSymbolCache;
// Note: this will only contain StaticSymbols without members!
this.summaryCache = new Map();
this.loadedFilePaths = new Map();
// Note: this will only contain StaticSymbols without members!
this.importAs = new Map();
this.knownFileNameToModuleNames = new Map();
}
isLibraryFile(filePath) {
// Note: We need to strip the .ngfactory. file path,
// so this method also works for generated files
// (for which host.isSourceFile will always return false).
return !this.host.isSourceFile(stripGeneratedFileSuffix(filePath));
}
toSummaryFileName(filePath, referringSrcFileName) {
return this.host.toSummaryFileName(filePath, referringSrcFileName);
}
fromSummaryFileName(fileName, referringLibFileName) {
return this.host.fromSummaryFileName(fileName, referringLibFileName);
}
resolveSummary(staticSymbol) {
const rootSymbol = staticSymbol.members.length ?
this.staticSymbolCache.get(staticSymbol.filePath, staticSymbol.name) :
staticSymbol;
let summary = this.summaryCache.get(rootSymbol);
if (!summary) {
this._loadSummaryFile(staticSymbol.filePath);
summary = this.summaryCache.get(staticSymbol);
}
return (rootSymbol === staticSymbol && summary) || null;
}
getSymbolsOf(filePath) {
if (this._loadSummaryFile(filePath)) {
return Array.from(this.summaryCache.keys()).filter((symbol) => symbol.filePath === filePath);
}
return null;
}
getImportAs(staticSymbol) {
staticSymbol.assertNoMembers();
return this.importAs.get(staticSymbol);
}
/**
* Converts a file path to a module name that can be used as an `import`.
*/
getKnownModuleName(importedFilePath) {
return this.knownFileNameToModuleNames.get(importedFilePath) || null;
}
addSummary(summary) {
this.summaryCache.set(summary.symbol, summary);
}
_loadSummaryFile(filePath) {
let hasSummary = this.loadedFilePaths.get(filePath);
if (hasSummary != null) {
return hasSummary;
}
let json = null;
if (this.isLibraryFile(filePath)) {
const summaryFilePath = summaryFileName(filePath);
try {
json = this.host.loadSummary(summaryFilePath);
}
catch (e) {
console.error(`Error loading summary file ${summaryFilePath}`);
throw e;
}
}
hasSummary = json != null;
this.loadedFilePaths.set(filePath, hasSummary);
if (json) {
const { moduleName, summaries, importAs } = deserializeSummaries(this.staticSymbolCache, this, filePath, json);
summaries.forEach((summary) => this.summaryCache.set(summary.symbol, summary));
if (moduleName) {
this.knownFileNameToModuleNames.set(filePath, moduleName);
}
importAs.forEach((importAs) => {
this.importAs.set(importAs.symbol, importAs.importAs);
});
}
return hasSummary;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
function createAotUrlResolver(host) {
return {
resolve: (basePath, url) => {
const filePath = host.resourceNameToFileName(url, basePath);
if (!filePath) {
throw syntaxError(`Couldn't resolve resource ${url} from ${basePath}`);
}
return filePath;
}
};
}
/**
* Creates a new AotCompiler based on options and a host.
*/
function createAotCompiler(compilerHost, options, errorCollector) {
let translations = options.translations || '';
const urlResolver = createAotUrlResolver(compilerHost);
const symbolCache = new StaticSymbolCache();
const summaryResolver = new AotSummaryResolver(compilerHost, symbolCache);
const symbolResolver = new StaticSymbolResolver(compilerHost, symbolCache, summaryResolver);
const staticReflector = new StaticReflector(summaryResolver, symbolResolver, [], [], errorCollector);
let htmlParser;
if (!!options.enableIvy) {
// Ivy handles i18n at the compiler level so we must use a regular parser
htmlParser = new HtmlParser();
}
else {
htmlParser = new I18NHtmlParser(new HtmlParser(), translations, options.i18nFormat, options.missingTranslation, console);
}
const config = new CompilerConfig({
defaultEncapsulation: ViewEncapsulation.Emulated,
useJit: false,
missingTranslation: options.missingTranslation,
preserveWhitespaces: options.preserveWhitespaces,
strictInjectionParameters: options.strictInjectionParameters,
});
const normalizer = new DirectiveNormalizer({ get: (url) => compilerHost.loadResource(url) }, urlResolver, htmlParser, config);
const expressionParser = new Parser$1(new Lexer());
const elementSchemaRegistry = new DomElementSchemaRegistry();
const tmplParser = new TemplateParser(config, staticReflector, expressionParser, elementSchemaRegistry, htmlParser, console, []);
const resolver = new CompileMetadataResolver(config, htmlParser, new NgModuleResolver(staticReflector), new DirectiveResolver(staticReflector), new PipeResolver(staticReflector), summaryResolver, elementSchemaRegistry, normalizer, console, symbolCache, staticReflector, errorCollector);
// TODO(vicb): do not pass options.i18nFormat here
const viewCompiler = new ViewCompiler(staticReflector);
const typeCheckCompiler = new TypeCheckCompiler(options, staticReflector);
const compiler = new AotCompiler(config, options, compilerHost, staticReflector, resolver, tmplParser, new StyleCompiler(urlResolver), viewCompiler, typeCheckCompiler, new NgModuleCompiler(staticReflector), new InjectableCompiler(staticReflector, !!options.enableIvy), new TypeScriptEmitter(), summaryResolver, symbolResolver);
return { compiler, reflector: staticReflector };
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class SummaryResolver {
}
class JitSummaryResolver {
constructor() {
this._summaries = new Map();
}
isLibraryFile() {
return false;
}
toSummaryFileName(fileName) {
return fileName;
}
fromSummaryFileName(fileName) {
return fileName;
}
resolveSummary(reference) {
return this._summaries.get(reference) || null;
}
getSymbolsOf() {
return [];
}
getImportAs(reference) {
return reference;
}
getKnownModuleName(fileName) {
return null;
}
addSummary(summary) {
this._summaries.set(summary.symbol, summary);
}
}
function interpretStatements(statements, reflector) {
const ctx = new _ExecutionContext(null, null, null, new Map());
const visitor = new StatementInterpreter(reflector);
visitor.visitAllStatements(statements, ctx);
const result = {};
ctx.exports.forEach((exportName) => {
result[exportName] = ctx.vars.get(exportName);
});
return result;
}
function _executeFunctionStatements(varNames, varValues, statements, ctx, visitor) {
const childCtx = ctx.createChildWihtLocalVars();
for (let i = 0; i < varNames.length; i++) {
childCtx.vars.set(varNames[i], varValues[i]);
}
const result = visitor.visitAllStatements(statements, childCtx);
return result ? result.value : null;
}
class _ExecutionContext {
constructor(parent, instance, className, vars) {
this.parent = parent;
this.instance = instance;
this.className = className;
this.vars = vars;
this.exports = [];
}
createChildWihtLocalVars() {
return new _ExecutionContext(this, this.instance, this.className, new Map());
}
}
class ReturnValue {
constructor(value) {
this.value = value;
}
}
function createDynamicClass(_classStmt, _ctx, _visitor) {
const propertyDescriptors = {};
_classStmt.getters.forEach((getter) => {
// Note: use `function` instead of arrow function to capture `this`
propertyDescriptors[getter.name] = {
configurable: false,
get: function () {
const instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
return _executeFunctionStatements([], [], getter.body, instanceCtx, _visitor);
}
};
});
_classStmt.methods.forEach(function (method) {
const paramNames = method.params.map(param => param.name);
// Note: use `function` instead of arrow function to capture `this`
propertyDescriptors[method.name] = {
writable: false,
configurable: false,
value: function (...args) {
const instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
return _executeFunctionStatements(paramNames, args, method.body, instanceCtx, _visitor);
}
};
});
const ctorParamNames = _classStmt.constructorMethod.params.map(param => param.name);
// Note: use `function` instead of arrow function to capture `this`
const ctor = function (...args) {
const instanceCtx = new _ExecutionContext(_ctx, this, _classStmt.name, _ctx.vars);
_classStmt.fields.forEach((field) => {
this[field.name] = undefined;
});
_executeFunctionStatements(ctorParamNames, args, _classStmt.constructorMethod.body, instanceCtx, _visitor);
};
const superClass = _classStmt.parent ? _classStmt.parent.visitExpression(_visitor, _ctx) : Object;
ctor.prototype = Object.create(superClass.prototype, propertyDescriptors);
return ctor;
}
class StatementInterpreter {
constructor(reflector) {
this.reflector = reflector;
}
debugAst(ast) {
return debugOutputAstAsTypeScript(ast);
}
visitDeclareVarStmt(stmt, ctx) {
const initialValue = stmt.value ? stmt.value.visitExpression(this, ctx) : undefined;
ctx.vars.set(stmt.name, initialValue);
if (stmt.hasModifier(StmtModifier.Exported)) {
ctx.exports.push(stmt.name);
}
return null;
}
visitWriteVarExpr(expr, ctx) {
const value = expr.value.visitExpression(this, ctx);
let currCtx = ctx;
while (currCtx != null) {
if (currCtx.vars.has(expr.name)) {
currCtx.vars.set(expr.name, value);
return value;
}
currCtx = currCtx.parent;
}
throw new Error(`Not declared variable ${expr.name}`);
}
visitWrappedNodeExpr(ast, ctx) {
throw new Error('Cannot interpret a WrappedNodeExpr.');
}
visitTypeofExpr(ast, ctx) {
throw new Error('Cannot interpret a TypeofExpr');
}
visitReadVarExpr(ast, ctx) {
let varName = ast.name;
if (ast.builtin != null) {
switch (ast.builtin) {
case BuiltinVar.Super:
return Object.getPrototypeOf(ctx.instance);
case BuiltinVar.This:
return ctx.instance;
case BuiltinVar.CatchError:
varName = CATCH_ERROR_VAR$2;
break;
case BuiltinVar.CatchStack:
varName = CATCH_STACK_VAR$2;
break;
default:
throw new Error(`Unknown builtin variable ${ast.builtin}`);
}
}
let currCtx = ctx;
while (currCtx != null) {
if (currCtx.vars.has(varName)) {
return currCtx.vars.get(varName);
}
currCtx = currCtx.parent;
}
throw new Error(`Not declared variable ${varName}`);
}
visitWriteKeyExpr(expr, ctx) {
const receiver = expr.receiver.visitExpression(this, ctx);
const index = expr.index.visitExpression(this, ctx);
const value = expr.value.visitExpression(this, ctx);
receiver[index] = value;
return value;
}
visitWritePropExpr(expr, ctx) {
const receiver = expr.receiver.visitExpression(this, ctx);
const value = expr.value.visitExpression(this, ctx);
receiver[expr.name] = value;
return value;
}
visitInvokeMethodExpr(expr, ctx) {
const receiver = expr.receiver.visitExpression(this, ctx);
const args = this.visitAllExpressions(expr.args, ctx);
let result;
if (expr.builtin != null) {
switch (expr.builtin) {
case BuiltinMethod.ConcatArray:
result = receiver.concat(...args);
break;
case BuiltinMethod.SubscribeObservable:
result = receiver.subscribe({ next: args[0] });
break;
case BuiltinMethod.Bind:
result = receiver.bind(...args);
break;
default:
throw new Error(`Unknown builtin method ${expr.builtin}`);
}
}
else {
result = receiver[expr.name].apply(receiver, args);
}
return result;
}
visitInvokeFunctionExpr(stmt, ctx) {
const args = this.visitAllExpressions(stmt.args, ctx);
const fnExpr = stmt.fn;
if (fnExpr instanceof ReadVarExpr && fnExpr.builtin === BuiltinVar.Super) {
ctx.instance.constructor.prototype.constructor.apply(ctx.instance, args);
return null;
}
else {
const fn = stmt.fn.visitExpression(this, ctx);
return fn.apply(null, args);
}
}
visitTaggedTemplateExpr(expr, ctx) {
const templateElements = expr.template.elements.map((e) => e.text);
Object.defineProperty(templateElements, 'raw', { value: expr.template.elements.map((e) => e.rawText) });
const args = this.visitAllExpressions(expr.template.expressions, ctx);
args.unshift(templateElements);
const tag = expr.tag.visitExpression(this, ctx);
return tag.apply(null, args);
}
visitReturnStmt(stmt, ctx) {
return new ReturnValue(stmt.value.visitExpression(this, ctx));
}
visitDeclareClassStmt(stmt, ctx) {
const clazz = createDynamicClass(stmt, ctx, this);
ctx.vars.set(stmt.name, clazz);
if (stmt.hasModifier(StmtModifier.Exported)) {
ctx.exports.push(stmt.name);
}
return null;
}
visitExpressionStmt(stmt, ctx) {
return stmt.expr.visitExpression(this, ctx);
}
visitIfStmt(stmt, ctx) {
const condition = stmt.condition.visitExpression(this, ctx);
if (condition) {
return this.visitAllStatements(stmt.trueCase, ctx);
}
else if (stmt.falseCase != null) {
return this.visitAllStatements(stmt.falseCase, ctx);
}
return null;
}
visitTryCatchStmt(stmt, ctx) {
try {
return this.visitAllStatements(stmt.bodyStmts, ctx);
}
catch (e) {
const childCtx = ctx.createChildWihtLocalVars();
childCtx.vars.set(CATCH_ERROR_VAR$2, e);
childCtx.vars.set(CATCH_STACK_VAR$2, e.stack);
return this.visitAllStatements(stmt.catchStmts, childCtx);
}
}
visitThrowStmt(stmt, ctx) {
throw stmt.error.visitExpression(this, ctx);
}
visitInstantiateExpr(ast, ctx) {
const args = this.visitAllExpressions(ast.args, ctx);
const clazz = ast.classExpr.visitExpression(this, ctx);
return new clazz(...args);
}
visitLiteralExpr(ast, ctx) {
return ast.value;
}
visitLocalizedString(ast, context) {
return null;
}
visitExternalExpr(ast, ctx) {
return this.reflector.resolveExternalReference(ast.value);
}
visitConditionalExpr(ast, ctx) {
if (ast.condition.visitExpression(this, ctx)) {
return ast.trueCase.visitExpression(this, ctx);
}
else if (ast.falseCase != null) {
return ast.falseCase.visitExpression(this, ctx);
}
return null;
}
visitNotExpr(ast, ctx) {
return !ast.condition.visitExpression(this, ctx);
}
visitAssertNotNullExpr(ast, ctx) {
return ast.condition.visitExpression(this, ctx);
}
visitCastExpr(ast, ctx) {
return ast.value.visitExpression(this, ctx);
}
visitFunctionExpr(ast, ctx) {
const paramNames = ast.params.map((param) => param.name);
return _declareFn(paramNames, ast.statements, ctx, this);
}
visitDeclareFunctionStmt(stmt, ctx) {
const paramNames = stmt.params.map((param) => param.name);
ctx.vars.set(stmt.name, _declareFn(paramNames, stmt.statements, ctx, this));
if (stmt.hasModifier(StmtModifier.Exported)) {
ctx.exports.push(stmt.name);
}
return null;
}
visitUnaryOperatorExpr(ast, ctx) {
const rhs = () => ast.expr.visitExpression(this, ctx);
switch (ast.operator) {
case UnaryOperator.Plus:
return +rhs();
case UnaryOperator.Minus:
return -rhs();
default:
throw new Error(`Unknown operator ${ast.operator}`);
}
}
visitBinaryOperatorExpr(ast, ctx) {
const lhs = () => ast.lhs.visitExpression(this, ctx);
const rhs = () => ast.rhs.visitExpression(this, ctx);
switch (ast.operator) {
case BinaryOperator.Equals:
return lhs() == rhs();
case BinaryOperator.Identical:
return lhs() === rhs();
case BinaryOperator.NotEquals:
return lhs() != rhs();
case BinaryOperator.NotIdentical:
return lhs() !== rhs();
case BinaryOperator.And:
return lhs() && rhs();
case BinaryOperator.Or:
return lhs() || rhs();
case BinaryOperator.Plus:
return lhs() + rhs();
case BinaryOperator.Minus:
return lhs() - rhs();
case BinaryOperator.Divide:
return lhs() / rhs();
case BinaryOperator.Multiply:
return lhs() * rhs();
case BinaryOperator.Modulo:
return lhs() % rhs();
case BinaryOperator.Lower:
return lhs() < rhs();
case BinaryOperator.LowerEquals:
return lhs() <= rhs();
case BinaryOperator.Bigger:
return lhs() > rhs();
case BinaryOperator.BiggerEquals:
return lhs() >= rhs();
default:
throw new Error(`Unknown operator ${ast.operator}`);
}
}
visitReadPropExpr(ast, ctx) {
let result;
const receiver = ast.receiver.visitExpression(this, ctx);
result = receiver[ast.name];
return result;
}
visitReadKeyExpr(ast, ctx) {
const receiver = ast.receiver.visitExpression(this, ctx);
const prop = ast.index.visitExpression(this, ctx);
return receiver[prop];
}
visitLiteralArrayExpr(ast, ctx) {
return this.visitAllExpressions(ast.entries, ctx);
}
visitLiteralMapExpr(ast, ctx) {
const result = {};
ast.entries.forEach(entry => result[entry.key] = entry.value.visitExpression(this, ctx));
return result;
}
visitCommaExpr(ast, context) {
const values = this.visitAllExpressions(ast.parts, context);
return values[values.length - 1];
}
visitAllExpressions(expressions, ctx) {
return expressions.map((expr) => expr.visitExpression(this, ctx));
}
visitAllStatements(statements, ctx) {
for (let i = 0; i < statements.length; i++) {
const stmt = statements[i];
const val = stmt.visitStatement(this, ctx);
if (val instanceof ReturnValue) {
return val;
}
}
return null;
}
}
function _declareFn(varNames, statements, ctx, visitor) {
return (...args) => _executeFunctionStatements(varNames, args, statements, ctx, visitor);
}
const CATCH_ERROR_VAR$2 = 'error';
const CATCH_STACK_VAR$2 = 'stack';
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* An internal module of the Angular compiler that begins with component types,
* extracts templates, and eventually produces a compiled version of the component
* ready for linking into an application.
*
* @security When compiling templates at runtime, you must ensure that the entire template comes
* from a trusted source. Attacker-controlled data introduced by a template could expose your
* application to XSS risks. For more detail, see the [Security Guide](https://g.co/ng/security).
*/
class JitCompiler {
constructor(_metadataResolver, _templateParser, _styleCompiler, _viewCompiler, _ngModuleCompiler, _summaryResolver, _reflector, _jitEvaluator, _compilerConfig, _console, getExtraNgModuleProviders) {
this._metadataResolver = _metadataResolver;
this._templateParser = _templateParser;
this._styleCompiler = _styleCompiler;
this._viewCompiler = _viewCompiler;
this._ngModuleCompiler = _ngModuleCompiler;
this._summaryResolver = _summaryResolver;
this._reflector = _reflector;
this._jitEvaluator = _jitEvaluator;
this._compilerConfig = _compilerConfig;
this._console = _console;
this.getExtraNgModuleProviders = getExtraNgModuleProviders;
this._compiledTemplateCache = new Map();
this._compiledHostTemplateCache = new Map();
this._compiledDirectiveWrapperCache = new Map();
this._compiledNgModuleCache = new Map();
this._sharedStylesheetCount = 0;
this._addedAotSummaries = new Set();
}
compileModuleSync(moduleType) {
return SyncAsync.assertSync(this._compileModuleAndComponents(moduleType, true));
}
compileModuleAsync(moduleType) {
return Promise.resolve(this._compileModuleAndComponents(moduleType, false));
}
compileModuleAndAllComponentsSync(moduleType) {
return SyncAsync.assertSync(this._compileModuleAndAllComponents(moduleType, true));
}
compileModuleAndAllComponentsAsync(moduleType) {
return Promise.resolve(this._compileModuleAndAllComponents(moduleType, false));
}
getComponentFactory(component) {
const summary = this._metadataResolver.getDirectiveSummary(component);
return summary.componentFactory;
}
loadAotSummaries(summaries) {
this.clearCache();
this._addAotSummaries(summaries);
}
_addAotSummaries(fn) {
if (this._addedAotSummaries.has(fn)) {
return;
}
this._addedAotSummaries.add(fn);
const summaries = fn();
for (let i = 0; i < summaries.length; i++) {
const entry = summaries[i];
if (typeof entry === 'function') {
this._addAotSummaries(entry);
}
else {
const summary = entry;
this._summaryResolver.addSummary({ symbol: summary.type.reference, metadata: null, type: summary });
}
}
}
hasAotSummary(ref) {
return !!this._summaryResolver.resolveSummary(ref);
}
_filterJitIdentifiers(ids) {
return ids.map(mod => mod.reference).filter((ref) => !this.hasAotSummary(ref));
}
_compileModuleAndComponents(moduleType, isSync) {
return SyncAsync.then(this._loadModules(moduleType, isSync), () => {
this._compileComponents(moduleType, null);
return this._compileModule(moduleType);
});
}
_compileModuleAndAllComponents(moduleType, isSync) {
return SyncAsync.then(this._loadModules(moduleType, isSync), () => {
const componentFactories = [];
this._compileComponents(moduleType, componentFactories);
return {
ngModuleFactory: this._compileModule(moduleType),
componentFactories: componentFactories
};
});
}
_loadModules(mainModule, isSync) {
const loading = [];
const mainNgModule = this._metadataResolver.getNgModuleMetadata(mainModule);
// Note: for runtime compilation, we want to transitively compile all modules,
// so we also need to load the declared directives / pipes for all nested modules.
this._filterJitIdentifiers(mainNgModule.transitiveModule.modules).forEach((nestedNgModule) => {
// getNgModuleMetadata only returns null if the value passed in is not an NgModule
const moduleMeta = this._metadataResolver.getNgModuleMetadata(nestedNgModule);
this._filterJitIdentifiers(moduleMeta.declaredDirectives).forEach((ref) => {
const promise = this._metadataResolver.loadDirectiveMetadata(moduleMeta.type.reference, ref, isSync);
if (promise) {
loading.push(promise);
}
});
this._filterJitIdentifiers(moduleMeta.declaredPipes)
.forEach((ref) => this._metadataResolver.getOrLoadPipeMetadata(ref));
});
return SyncAsync.all(loading);
}
_compileModule(moduleType) {
let ngModuleFactory = this._compiledNgModuleCache.get(moduleType);
if (!ngModuleFactory) {
const moduleMeta = this._metadataResolver.getNgModuleMetadata(moduleType);
// Always provide a bound Compiler
const extraProviders = this.getExtraNgModuleProviders(moduleMeta.type.reference);
const outputCtx = createOutputContext();
const compileResult = this._ngModuleCompiler.compile(outputCtx, moduleMeta, extraProviders);
ngModuleFactory = this._interpretOrJit(ngModuleJitUrl(moduleMeta), outputCtx.statements)[compileResult.ngModuleFactoryVar];
this._compiledNgModuleCache.set(moduleMeta.type.reference, ngModuleFactory);
}
return ngModuleFactory;
}
/**
* @internal
*/
_compileComponents(mainModule, allComponentFactories) {
const ngModule = this._metadataResolver.getNgModuleMetadata(mainModule);
const moduleByJitDirective = new Map();
const templates = new Set();
const transJitModules = this._filterJitIdentifiers(ngModule.transitiveModule.modules);
transJitModules.forEach((localMod) => {
const localModuleMeta = this._metadataResolver.getNgModuleMetadata(localMod);
this._filterJitIdentifiers(localModuleMeta.declaredDirectives).forEach((dirRef) => {
moduleByJitDirective.set(dirRef, localModuleMeta);
const dirMeta = this._metadataResolver.getDirectiveMetadata(dirRef);
if (dirMeta.isComponent) {
templates.add(this._createCompiledTemplate(dirMeta, localModuleMeta));
if (allComponentFactories) {
const template = this._createCompiledHostTemplate(dirMeta.type.reference, localModuleMeta);
templates.add(template);
allComponentFactories.push(dirMeta.componentFactory);
}
}
});
});
transJitModules.forEach((localMod) => {
const localModuleMeta = this._metadataResolver.getNgModuleMetadata(localMod);
this._filterJitIdentifiers(localModuleMeta.declaredDirectives).forEach((dirRef) => {
const dirMeta = this._metadataResolver.getDirectiveMetadata(dirRef);
if (dirMeta.isComponent) {
dirMeta.entryComponents.forEach((entryComponentType) => {
const moduleMeta = moduleByJitDirective.get(entryComponentType.componentType);
templates.add(this._createCompiledHostTemplate(entryComponentType.componentType, moduleMeta));
});
}
});
localModuleMeta.entryComponents.forEach((entryComponentType) => {
if (!this.hasAotSummary(entryComponentType.componentType)) {
const moduleMeta = moduleByJitDirective.get(entryComponentType.componentType);
templates.add(this._createCompiledHostTemplate(entryComponentType.componentType, moduleMeta));
}
});
});
templates.forEach((template) => this._compileTemplate(template));
}
clearCacheFor(type) {
this._compiledNgModuleCache.delete(type);
this._metadataResolver.clearCacheFor(type);
this._compiledHostTemplateCache.delete(type);
const compiledTemplate = this._compiledTemplateCache.get(type);
if (compiledTemplate) {
this._compiledTemplateCache.delete(type);
}
}
clearCache() {
// Note: don't clear the _addedAotSummaries, as they don't change!
this._metadataResolver.clearCache();
this._compiledTemplateCache.clear();
this._compiledHostTemplateCache.clear();
this._compiledNgModuleCache.clear();
}
_createCompiledHostTemplate(compType, ngModule) {
if (!ngModule) {
throw new Error(`Component ${stringify(compType)} is not part of any NgModule or the module has not been imported into your module.`);
}
let compiledTemplate = this._compiledHostTemplateCache.get(compType);
if (!compiledTemplate) {
const compMeta = this._metadataResolver.getDirectiveMetadata(compType);
assertComponent(compMeta);
const hostMeta = this._metadataResolver.getHostComponentMetadata(compMeta, compMeta.componentFactory.viewDefFactory);
compiledTemplate =
new CompiledTemplate(true, compMeta.type, hostMeta, ngModule, [compMeta.type]);
this._compiledHostTemplateCache.set(compType, compiledTemplate);
}
return compiledTemplate;
}
_createCompiledTemplate(compMeta, ngModule) {
let compiledTemplate = this._compiledTemplateCache.get(compMeta.type.reference);
if (!compiledTemplate) {
assertComponent(compMeta);
compiledTemplate = new CompiledTemplate(false, compMeta.type, compMeta, ngModule, ngModule.transitiveModule.directives);
this._compiledTemplateCache.set(compMeta.type.reference, compiledTemplate);
}
return compiledTemplate;
}
_compileTemplate(template) {
if (template.isCompiled) {
return;
}
const compMeta = template.compMeta;
const externalStylesheetsByModuleUrl = new Map();
const outputContext = createOutputContext();
const componentStylesheet = this._styleCompiler.compileComponent(outputContext, compMeta);
compMeta.template.externalStylesheets.forEach((stylesheetMeta) => {
const compiledStylesheet = this._styleCompiler.compileStyles(createOutputContext(), compMeta, stylesheetMeta);
externalStylesheetsByModuleUrl.set(stylesheetMeta.moduleUrl, compiledStylesheet);
});
this._resolveStylesCompileResult(componentStylesheet, externalStylesheetsByModuleUrl);
const pipes = template.ngModule.transitiveModule.pipes.map(pipe => this._metadataResolver.getPipeSummary(pipe.reference));
const { template: parsedTemplate, pipes: usedPipes } = this._parseTemplate(compMeta, template.ngModule, template.directives);
const compileResult = this._viewCompiler.compileComponent(outputContext, compMeta, parsedTemplate, variable(componentStylesheet.stylesVar), usedPipes);
const evalResult = this._interpretOrJit(templateJitUrl(template.ngModule.type, template.compMeta), outputContext.statements);
const viewClass = evalResult[compileResult.viewClassVar];
const rendererType = evalResult[compileResult.rendererTypeVar];
template.compiled(viewClass, rendererType);
}
_parseTemplate(compMeta, ngModule, directiveIdentifiers) {
// Note: ! is ok here as components always have a template.
const preserveWhitespaces = compMeta.template.preserveWhitespaces;
const directives = directiveIdentifiers.map(dir => this._metadataResolver.getDirectiveSummary(dir.reference));
const pipes = ngModule.transitiveModule.pipes.map(pipe => this._metadataResolver.getPipeSummary(pipe.reference));
return this._templateParser.parse(compMeta, compMeta.template.htmlAst, directives, pipes, ngModule.schemas, templateSourceUrl(ngModule.type, compMeta, compMeta.template), preserveWhitespaces);
}
_resolveStylesCompileResult(result, externalStylesheetsByModuleUrl) {
result.dependencies.forEach((dep, i) => {
const nestedCompileResult = externalStylesheetsByModuleUrl.get(dep.moduleUrl);
const nestedStylesArr = this._resolveAndEvalStylesCompileResult(nestedCompileResult, externalStylesheetsByModuleUrl);
dep.setValue(nestedStylesArr);
});
}
_resolveAndEvalStylesCompileResult(result, externalStylesheetsByModuleUrl) {
this._resolveStylesCompileResult(result, externalStylesheetsByModuleUrl);
return this._interpretOrJit(sharedStylesheetJitUrl(result.meta, this._sharedStylesheetCount++), result.outputCtx.statements)[result.stylesVar];
}
_interpretOrJit(sourceUrl, statements) {
if (!this._compilerConfig.useJit) {
return interpretStatements(statements, this._reflector);
}
else {
return this._jitEvaluator.evaluateStatements(sourceUrl, statements, this._reflector, this._compilerConfig.jitDevMode);
}
}
}
class CompiledTemplate {
constructor(isHost, compType, compMeta, ngModule, directives) {
this.isHost = isHost;
this.compType = compType;
this.compMeta = compMeta;
this.ngModule = ngModule;
this.directives = directives;
this._viewClass = null;
this.isCompiled = false;
}
compiled(viewClass, rendererType) {
this._viewClass = viewClass;
this.compMeta.componentViewType.setDelegate(viewClass);
for (let prop in rendererType) {
this.compMeta.rendererType[prop] = rendererType[prop];
}
this.isCompiled = true;
}
}
function assertComponent(meta) {
if (!meta.isComponent) {
throw new Error(`Could not compile '${identifierName(meta.type)}' because it is not a component.`);
}
}
function createOutputContext() {
const importExpr$1 = (symbol) => importExpr({ name: identifierName(symbol), moduleName: null, runtime: symbol });
return { statements: [], genFilePath: '', importExpr: importExpr$1, constantPool: new ConstantPool() };
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Provides access to reflection data about symbols that the compiler needs.
*/
class CompileReflector {
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Create a {@link UrlResolver} with no package prefix.
*/
function createUrlResolverWithoutPackagePrefix() {
return new UrlResolver();
}
function createOfflineCompileUrlResolver() {
return new UrlResolver('.');
}
const UrlResolver = class UrlResolverImpl {
constructor(_packagePrefix = null) {
this._packagePrefix = _packagePrefix;
}
/**
* Resolves the `url` given the `baseUrl`:
* - when the `url` is null, the `baseUrl` is returned,
* - if `url` is relative ('path/to/here', './path/to/here'), the resolved url is a combination of
* `baseUrl` and `url`,
* - if `url` is absolute (it has a scheme: 'http://', 'https://' or start with '/'), the `url` is
* returned as is (ignoring the `baseUrl`)
*/
resolve(baseUrl, url) {
let resolvedUrl = url;
if (baseUrl != null && baseUrl.length > 0) {
resolvedUrl = _resolveUrl(baseUrl, resolvedUrl);
}
const resolvedParts = _split(resolvedUrl);
let prefix = this._packagePrefix;
if (prefix != null && resolvedParts != null &&
resolvedParts[_ComponentIndex.Scheme] == 'package') {
let path = resolvedParts[_ComponentIndex.Path];
prefix = prefix.replace(/\/+$/, '');
path = path.replace(/^\/+/, '');
return `${prefix}/${path}`;
}
return resolvedUrl;
}
};
/**
* Extract the scheme of a URL.
*/
function getUrlScheme(url) {
const match = _split(url);
return (match && match[_ComponentIndex.Scheme]) || '';
}
// The code below is adapted from Traceur:
// https://github.com/google/traceur-compiler/blob/9511c1dafa972bf0de1202a8a863bad02f0f95a8/src/runtime/url.js
/**
* Builds a URI string from already-encoded parts.
*
* No encoding is performed. Any component may be omitted as either null or
* undefined.
*
* @param opt_scheme The scheme such as 'http'.
* @param opt_userInfo The user name before the '@'.
* @param opt_domain The domain such as 'www.google.com', already
* URI-encoded.
* @param opt_port The port number.
* @param opt_path The path, already URI-encoded. If it is not
* empty, it must begin with a slash.
* @param opt_queryData The URI-encoded query data.
* @param opt_fragment The URI-encoded fragment identifier.
* @return The fully combined URI.
*/
function _buildFromEncodedParts(opt_scheme, opt_userInfo, opt_domain, opt_port, opt_path, opt_queryData, opt_fragment) {
const out = [];
if (opt_scheme != null) {
out.push(opt_scheme + ':');
}
if (opt_domain != null) {
out.push('//');
if (opt_userInfo != null) {
out.push(opt_userInfo + '@');
}
out.push(opt_domain);
if (opt_port != null) {
out.push(':' + opt_port);
}
}
if (opt_path != null) {
out.push(opt_path);
}
if (opt_queryData != null) {
out.push('?' + opt_queryData);
}
if (opt_fragment != null) {
out.push('#' + opt_fragment);
}
return out.join('');
}
/**
* A regular expression for breaking a URI into its component parts.
*
* {@link https://tools.ietf.org/html/rfc3986#appendix-B} says
* As the "first-match-wins" algorithm is identical to the "greedy"
* disambiguation method used by POSIX regular expressions, it is natural and
* commonplace to use a regular expression for parsing the potential five
* components of a URI reference.
*
* The following line is the regular expression for breaking-down a
* well-formed URI reference into its components.
*
* <pre>
* ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
* 12 3 4 5 6 7 8 9
* </pre>
*
* The numbers in the second line above are only to assist readability; they
* indicate the reference points for each subexpression (i.e., each paired
* parenthesis). We refer to the value matched for subexpression <n> as $<n>.
* For example, matching the above expression to
* <pre>
* http://www.ics.uci.edu/pub/ietf/uri/#Related
* </pre>
* results in the following subexpression matches:
* <pre>
* $1 = http:
* $2 = http
* $3 = //www.ics.uci.edu
* $4 = www.ics.uci.edu
* $5 = /pub/ietf/uri/
* $6 = <undefined>
* $7 = <undefined>
* $8 = #Related
* $9 = Related
* </pre>
* where <undefined> indicates that the component is not present, as is the
* case for the query component in the above example. Therefore, we can
* determine the value of the five components as
* <pre>
* scheme = $2
* authority = $4
* path = $5
* query = $7
* fragment = $9
* </pre>
*
* The regular expression has been modified slightly to expose the
* userInfo, domain, and port separately from the authority.
* The modified version yields
* <pre>
* $1 = http scheme
* $2 = <undefined> userInfo -\
* $3 = www.ics.uci.edu domain | authority
* $4 = <undefined> port -/
* $5 = /pub/ietf/uri/ path
* $6 = <undefined> query without ?
* $7 = Related fragment without #
* </pre>
* @internal
*/
const _splitRe = new RegExp('^' +
'(?:' +
'([^:/?#.]+)' + // scheme - ignore special characters
// used by other URL parts such as :,
// ?, /, #, and .
':)?' +
'(?://' +
'(?:([^/?#]*)@)?' + // userInfo
'([\\w\\d\\-\\u0100-\\uffff.%]*)' + // domain - restrict to letters,
// digits, dashes, dots, percent
// escapes, and unicode characters.
'(?::([0-9]+))?' + // port
')?' +
'([^?#]+)?' + // path
'(?:\\?([^#]*))?' + // query
'(?:#(.*))?' + // fragment
'$');
/**
* The index of each URI component in the return value of goog.uri.utils.split.
* @enum {number}
*/
var _ComponentIndex;
(function (_ComponentIndex) {
_ComponentIndex[_ComponentIndex["Scheme"] = 1] = "Scheme";
_ComponentIndex[_ComponentIndex["UserInfo"] = 2] = "UserInfo";
_ComponentIndex[_ComponentIndex["Domain"] = 3] = "Domain";
_ComponentIndex[_ComponentIndex["Port"] = 4] = "Port";
_ComponentIndex[_ComponentIndex["Path"] = 5] = "Path";
_ComponentIndex[_ComponentIndex["QueryData"] = 6] = "QueryData";
_ComponentIndex[_ComponentIndex["Fragment"] = 7] = "Fragment";
})(_ComponentIndex || (_ComponentIndex = {}));
/**
* Splits a URI into its component parts.
*
* Each component can be accessed via the component indices; for example:
* <pre>
* goog.uri.utils.split(someStr)[goog.uri.utils.CompontentIndex.QUERY_DATA];
* </pre>
*
* @param uri The URI string to examine.
* @return Each component still URI-encoded.
* Each component that is present will contain the encoded value, whereas
* components that are not present will be undefined or empty, depending
* on the browser's regular expression implementation. Never null, since
* arbitrary strings may still look like path names.
*/
function _split(uri) {
return uri.match(_splitRe);
}
/**
* Removes dot segments in given path component, as described in
* RFC 3986, section 5.2.4.
*
* @param path A non-empty path component.
* @return Path component with removed dot segments.
*/
function _removeDotSegments(path) {
if (path == '/')
return '/';
const leadingSlash = path[0] == '/' ? '/' : '';
const trailingSlash = path[path.length - 1] === '/' ? '/' : '';
const segments = path.split('/');
const out = [];
let up = 0;
for (let pos = 0; pos < segments.length; pos++) {
const segment = segments[pos];
switch (segment) {
case '':
case '.':
break;
case '..':
if (out.length > 0) {
out.pop();
}
else {
up++;
}
break;
default:
out.push(segment);
}
}
if (leadingSlash == '') {
while (up-- > 0) {
out.unshift('..');
}
if (out.length === 0)
out.push('.');
}
return leadingSlash + out.join('/') + trailingSlash;
}
/**
* Takes an array of the parts from split and canonicalizes the path part
* and then joins all the parts.
*/
function _joinAndCanonicalizePath(parts) {
let path = parts[_ComponentIndex.Path];
path = path == null ? '' : _removeDotSegments(path);
parts[_ComponentIndex.Path] = path;
return _buildFromEncodedParts(parts[_ComponentIndex.Scheme], parts[_ComponentIndex.UserInfo], parts[_ComponentIndex.Domain], parts[_ComponentIndex.Port], path, parts[_ComponentIndex.QueryData], parts[_ComponentIndex.Fragment]);
}
/**
* Resolves a URL.
* @param base The URL acting as the base URL.
* @param to The URL to resolve.
*/
function _resolveUrl(base, url) {
const parts = _split(encodeURI(url));
const baseParts = _split(base);
if (parts[_ComponentIndex.Scheme] != null) {
return _joinAndCanonicalizePath(parts);
}
else {
parts[_ComponentIndex.Scheme] = baseParts[_ComponentIndex.Scheme];
}
for (let i = _ComponentIndex.Scheme; i <= _ComponentIndex.Port; i++) {
if (parts[i] == null) {
parts[i] = baseParts[i];
}
}
if (parts[_ComponentIndex.Path][0] == '/') {
return _joinAndCanonicalizePath(parts);
}
let path = baseParts[_ComponentIndex.Path];
if (path == null)
path = '/';
const index = path.lastIndexOf('/');
path = path.substring(0, index + 1) + parts[_ComponentIndex.Path];
parts[_ComponentIndex.Path] = path;
return _joinAndCanonicalizePath(parts);
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
class Extractor {
constructor(host, staticSymbolResolver, messageBundle, metadataResolver) {
this.host = host;
this.staticSymbolResolver = staticSymbolResolver;
this.messageBundle = messageBundle;
this.metadataResolver = metadataResolver;
}
extract(rootFiles) {
const { files, ngModules } = analyzeAndValidateNgModules(rootFiles, this.host, this.staticSymbolResolver, this.metadataResolver);
return Promise
.all(ngModules.map(ngModule => this.metadataResolver.loadNgModuleDirectiveAndPipeMetadata(ngModule.type.reference, false)))
.then(() => {
const errors = [];
files.forEach(file => {
const compMetas = [];
file.directives.forEach(directiveType => {
const dirMeta = this.metadataResolver.getDirectiveMetadata(directiveType);
if (dirMeta && dirMeta.isComponent) {
compMetas.push(dirMeta);
}
});
compMetas.forEach(compMeta => {
const html = compMeta.template.template;
// Template URL points to either an HTML or TS file depending on
// whether the file is used with `templateUrl:` or `template:`,
// respectively.
const templateUrl = compMeta.template.templateUrl;
const interpolationConfig = InterpolationConfig.fromArray(compMeta.template.interpolation);
errors.push(...this.messageBundle.updateFromTemplate(html, templateUrl, interpolationConfig));
});
});
if (errors.length) {
throw new Error(errors.map(e => e.toString()).join('\n'));
}
return this.messageBundle;
});
}
static create(host, locale) {
const htmlParser = new HtmlParser();
const urlResolver = createAotUrlResolver(host);
const symbolCache = new StaticSymbolCache();
const summaryResolver = new AotSummaryResolver(host, symbolCache);
const staticSymbolResolver = new StaticSymbolResolver(host, symbolCache, summaryResolver);
const staticReflector = new StaticReflector(summaryResolver, staticSymbolResolver);
const config = new CompilerConfig({ defaultEncapsulation: ViewEncapsulation.Emulated, useJit: false });
const normalizer = new DirectiveNormalizer({ get: (url) => host.loadResource(url) }, urlResolver, htmlParser, config);
const elementSchemaRegistry = new DomElementSchemaRegistry();
const resolver = new CompileMetadataResolver(config, htmlParser, new NgModuleResolver(staticReflector), new DirectiveResolver(staticReflector), new PipeResolver(staticReflector), summaryResolver, elementSchemaRegistry, normalizer, console, symbolCache, staticReflector);
// TODO(vicb): implicit tags & attributes
const messageBundle = new MessageBundle(htmlParser, [], {}, locale);
const extractor = new Extractor(host, staticSymbolResolver, messageBundle, resolver);
return { extractor, staticReflector };
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Processes `Target`s with a given set of directives and performs a binding operation, which
* returns an object similar to TypeScript's `ts.TypeChecker` that contains knowledge about the
* target.
*/
class R3TargetBinder {
constructor(directiveMatcher) {
this.directiveMatcher = directiveMatcher;
}
/**
* Perform a binding operation on the given `Target` and return a `BoundTarget` which contains
* metadata about the types referenced in the template.
*/
bind(target) {
if (!target.template) {
// TODO(alxhub): handle targets which contain things like HostBindings, etc.
throw new Error('Binding without a template not yet supported');
}
// First, parse the template into a `Scope` structure. This operation captures the syntactic
// scopes in the template and makes them available for later use.
const scope = Scope.apply(target.template);
// Use the `Scope` to extract the entities present at every level of the template.
const templateEntities = extractTemplateEntities(scope);
// Next, perform directive matching on the template using the `DirectiveBinder`. This returns:
// - directives: Map of nodes (elements & ng-templates) to the directives on them.
// - bindings: Map of inputs, outputs, and attributes to the directive/element that claims
// them. TODO(alxhub): handle multiple directives claiming an input/output/etc.
// - references: Map of #references to their targets.
const { directives, bindings, references } = DirectiveBinder.apply(target.template, this.directiveMatcher);
// Finally, run the TemplateBinder to bind references, variables, and other entities within the
// template. This extracts all the metadata that doesn't depend on directive matching.
const { expressions, symbols, nestingLevel, usedPipes } = TemplateBinder.apply(target.template, scope);
return new R3BoundTarget(target, directives, bindings, references, expressions, symbols, nestingLevel, templateEntities, usedPipes);
}
}
/**
* Represents a binding scope within a template.
*
* Any variables, references, or other named entities declared within the template will
* be captured and available by name in `namedEntities`. Additionally, child templates will
* be analyzed and have their child `Scope`s available in `childScopes`.
*/
class Scope {
constructor(parentScope, template) {
this.parentScope = parentScope;
this.template = template;
/**
* Named members of the `Scope`, such as `Reference`s or `Variable`s.
*/
this.namedEntities = new Map();
/**
* Child `Scope`s for immediately nested `Template`s.
*/
this.childScopes = new Map();
}
static newRootScope() {
return new Scope(null, null);
}
/**
* Process a template (either as a `Template` sub-template with variables, or a plain array of
* template `Node`s) and construct its `Scope`.
*/
static apply(template) {
const scope = Scope.newRootScope();
scope.ingest(template);
return scope;
}
/**
* Internal method to process the template and populate the `Scope`.
*/
ingest(template) {
if (template instanceof Template) {
// Variables on an <ng-template> are defined in the inner scope.
template.variables.forEach(node => this.visitVariable(node));
// Process the nodes of the template.
template.children.forEach(node => node.visit(this));
}
else {
// No overarching `Template` instance, so process the nodes directly.
template.forEach(node => node.visit(this));
}
}
visitElement(element) {
// `Element`s in the template may have `Reference`s which are captured in the scope.
element.references.forEach(node => this.visitReference(node));
// Recurse into the `Element`'s children.
element.children.forEach(node => node.visit(this));
}
visitTemplate(template) {
// References on a <ng-template> are defined in the outer scope, so capture them before
// processing the template's child scope.
template.references.forEach(node => this.visitReference(node));
// Next, create an inner scope and process the template within it.
const scope = new Scope(this, template);
scope.ingest(template);
this.childScopes.set(template, scope);
}
visitVariable(variable) {
// Declare the variable if it's not already.
this.maybeDeclare(variable);
}
visitReference(reference) {
// Declare the variable if it's not already.
this.maybeDeclare(reference);
}
// Unused visitors.
visitContent(content) { }
visitBoundAttribute(attr) { }
visitBoundEvent(event) { }
visitBoundText(text) { }
visitText(text) { }
visitTextAttribute(attr) { }
visitIcu(icu) { }
maybeDeclare(thing) {
// Declare something with a name, as long as that name isn't taken.
if (!this.namedEntities.has(thing.name)) {
this.namedEntities.set(thing.name, thing);
}
}
/**
* Look up a variable within this `Scope`.
*
* This can recurse into a parent `Scope` if it's available.
*/
lookup(name) {
if (this.namedEntities.has(name)) {
// Found in the local scope.
return this.namedEntities.get(name);
}
else if (this.parentScope !== null) {
// Not in the local scope, but there's a parent scope so check there.
return this.parentScope.lookup(name);
}
else {
// At the top level and it wasn't found.
return null;
}
}
/**
* Get the child scope for a `Template`.
*
* This should always be defined.
*/
getChildScope(template) {
const res = this.childScopes.get(template);
if (res === undefined) {
throw new Error(`Assertion error: child scope for ${template} not found`);
}
return res;
}
}
/**
* Processes a template and matches directives on nodes (elements and templates).
*
* Usually used via the static `apply()` method.
*/
class DirectiveBinder {
constructor(matcher, directives, bindings, references) {
this.matcher = matcher;
this.directives = directives;
this.bindings = bindings;
this.references = references;
}
/**
* Process a template (list of `Node`s) and perform directive matching against each node.
*
* @param template the list of template `Node`s to match (recursively).
* @param selectorMatcher a `SelectorMatcher` containing the directives that are in scope for
* this template.
* @returns three maps which contain information about directives in the template: the
* `directives` map which lists directives matched on each node, the `bindings` map which
* indicates which directives claimed which bindings (inputs, outputs, etc), and the `references`
* map which resolves #references (`Reference`s) within the template to the named directive or
* template node.
*/
static apply(template, selectorMatcher) {
const directives = new Map();
const bindings = new Map();
const references = new Map();
const matcher = new DirectiveBinder(selectorMatcher, directives, bindings, references);
matcher.ingest(template);
return { directives, bindings, references };
}
ingest(template) {
template.forEach(node => node.visit(this));
}
visitElement(element) {
this.visitElementOrTemplate(element.name, element);
}
visitTemplate(template) {
this.visitElementOrTemplate('ng-template', template);
}
visitElementOrTemplate(elementName, node) {
// First, determine the HTML shape of the node for the purpose of directive matching.
// Do this by building up a `CssSelector` for the node.
const cssSelector = createCssSelector(elementName, getAttrsForDirectiveMatching(node));
// Next, use the `SelectorMatcher` to get the list of directives on the node.
const directives = [];
this.matcher.match(cssSelector, (_, directive) => directives.push(directive));
if (directives.length > 0) {
this.directives.set(node, directives);
}
// Resolve any references that are created on this node.
node.references.forEach(ref => {
let dirTarget = null;
// If the reference expression is empty, then it matches the "primary" directive on the node
// (if there is one). Otherwise it matches the host node itself (either an element or
// <ng-template> node).
if (ref.value.trim() === '') {
// This could be a reference to a component if there is one.
dirTarget = directives.find(dir => dir.isComponent) || null;
}
else {
// This should be a reference to a directive exported via exportAs.
dirTarget =
directives.find(dir => dir.exportAs !== null && dir.exportAs.some(value => value === ref.value)) ||
null;
// Check if a matching directive was found.
if (dirTarget === null) {
// No matching directive was found - this reference points to an unknown target. Leave it
// unmapped.
return;
}
}
if (dirTarget !== null) {
// This reference points to a directive.
this.references.set(ref, { directive: dirTarget, node });
}
else {
// This reference points to the node itself.
this.references.set(ref, node);
}
});
const setAttributeBinding = (attribute, ioType) => {
const dir = directives.find(dir => dir[ioType].hasBindingPropertyName(attribute.name));
const binding = dir !== undefined ? dir : node;
this.bindings.set(attribute, binding);
};
// Node inputs (bound attributes) and text attributes can be bound to an
// input on a directive.
node.inputs.forEach(input => setAttributeBinding(input, 'inputs'));
node.attributes.forEach(attr => setAttributeBinding(attr, 'inputs'));
if (node instanceof Template) {
node.templateAttrs.forEach(attr => setAttributeBinding(attr, 'inputs'));
}
// Node outputs (bound events) can be bound to an output on a directive.
node.outputs.forEach(output => setAttributeBinding(output, 'outputs'));
// Recurse into the node's children.
node.children.forEach(child => child.visit(this));
}
// Unused visitors.
visitContent(content) { }
visitVariable(variable) { }
visitReference(reference) { }
visitTextAttribute(attribute) { }
visitBoundAttribute(attribute) { }
visitBoundEvent(attribute) { }
visitBoundAttributeOrEvent(node) { }
visitText(text) { }
visitBoundText(text) { }
visitIcu(icu) { }
}
/**
* Processes a template and extract metadata about expressions and symbols within.
*
* This is a companion to the `DirectiveBinder` that doesn't require knowledge of directives matched
* within the template in order to operate.
*
* Expressions are visited by the superclass `RecursiveAstVisitor`, with custom logic provided
* by overridden methods from that visitor.
*/
class TemplateBinder extends RecursiveAstVisitor$1 {
constructor(bindings, symbols, usedPipes, nestingLevel, scope, template, level) {
super();
this.bindings = bindings;
this.symbols = symbols;
this.usedPipes = usedPipes;
this.nestingLevel = nestingLevel;
this.scope = scope;
this.template = template;
this.level = level;
this.pipesUsed = [];
// Save a bit of processing time by constructing this closure in advance.
this.visitNode = (node) => node.visit(this);
}
// This method is defined to reconcile the type of TemplateBinder since both
// RecursiveAstVisitor and Visitor define the visit() method in their
// interfaces.
visit(node, context) {
if (node instanceof AST) {
node.visit(this, context);
}
else {
node.visit(this);
}
}
/**
* Process a template and extract metadata about expressions and symbols within.
*
* @param template the nodes of the template to process
* @param scope the `Scope` of the template being processed.
* @returns three maps which contain metadata about the template: `expressions` which interprets
* special `AST` nodes in expressions as pointing to references or variables declared within the
* template, `symbols` which maps those variables and references to the nested `Template` which
* declares them, if any, and `nestingLevel` which associates each `Template` with a integer
* nesting level (how many levels deep within the template structure the `Template` is), starting
* at 1.
*/
static apply(template, scope) {
const expressions = new Map();
const symbols = new Map();
const nestingLevel = new Map();
const usedPipes = new Set();
// The top-level template has nesting level 0.
const binder = new TemplateBinder(expressions, symbols, usedPipes, nestingLevel, scope, template instanceof Template ? template : null, 0);
binder.ingest(template);
return { expressions, symbols, nestingLevel, usedPipes };
}
ingest(template) {
if (template instanceof Template) {
// For <ng-template>s, process only variables and child nodes. Inputs, outputs, templateAttrs,
// and references were all processed in the scope of the containing template.
template.variables.forEach(this.visitNode);
template.children.forEach(this.visitNode);
// Set the nesting level.
this.nestingLevel.set(template, this.level);
}
else {
// Visit each node from the top-level template.
template.forEach(this.visitNode);
}
}
visitElement(element) {
// Visit the inputs, outputs, and children of the element.
element.inputs.forEach(this.visitNode);
element.outputs.forEach(this.visitNode);
element.children.forEach(this.visitNode);
}
visitTemplate(template) {
// First, visit inputs, outputs and template attributes of the template node.
template.inputs.forEach(this.visitNode);
template.outputs.forEach(this.visitNode);
template.templateAttrs.forEach(this.visitNode);
// References are also evaluated in the outer context.
template.references.forEach(this.visitNode);
// Next, recurse into the template using its scope, and bumping the nesting level up by one.
const childScope = this.scope.getChildScope(template);
const binder = new TemplateBinder(this.bindings, this.symbols, this.usedPipes, this.nestingLevel, childScope, template, this.level + 1);
binder.ingest(template);
}
visitVariable(variable) {
// Register the `Variable` as a symbol in the current `Template`.
if (this.template !== null) {
this.symbols.set(variable, this.template);
}
}
visitReference(reference) {
// Register the `Reference` as a symbol in the current `Template`.
if (this.template !== null) {
this.symbols.set(reference, this.template);
}
}
// Unused template visitors
visitText(text) { }
visitContent(content) { }
visitTextAttribute(attribute) { }
visitIcu(icu) {
Object.keys(icu.vars).forEach(key => icu.vars[key].visit(this));
Object.keys(icu.placeholders).forEach(key => icu.placeholders[key].visit(this));
}
// The remaining visitors are concerned with processing AST expressions within template bindings
visitBoundAttribute(attribute) {
attribute.value.visit(this);
}
visitBoundEvent(event) {
event.handler.visit(this);
}
visitBoundText(text) {
text.value.visit(this);
}
visitPipe(ast, context) {
this.usedPipes.add(ast.name);
return super.visitPipe(ast, context);
}
// These five types of AST expressions can refer to expression roots, which could be variables
// or references in the current scope.
visitPropertyRead(ast, context) {
this.maybeMap(context, ast, ast.name);
return super.visitPropertyRead(ast, context);
}
visitSafePropertyRead(ast, context) {
this.maybeMap(context, ast, ast.name);
return super.visitSafePropertyRead(ast, context);
}
visitPropertyWrite(ast, context) {
this.maybeMap(context, ast, ast.name);
return super.visitPropertyWrite(ast, context);
}
visitMethodCall(ast, context) {
this.maybeMap(context, ast, ast.name);
return super.visitMethodCall(ast, context);
}
visitSafeMethodCall(ast, context) {
this.maybeMap(context, ast, ast.name);
return super.visitSafeMethodCall(ast, context);
}
maybeMap(scope, ast, name) {
// If the receiver of the expression isn't the `ImplicitReceiver`, this isn't the root of an
// `AST` expression that maps to a `Variable` or `Reference`.
if (!(ast.receiver instanceof ImplicitReceiver)) {
return;
}
// Check whether the name exists in the current scope. If so, map it. Otherwise, the name is
// probably a property on the top-level component context.
let target = this.scope.lookup(name);
if (target !== null) {
this.bindings.set(ast, target);
}
}
}
/**
* Metadata container for a `Target` that allows queries for specific bits of metadata.
*
* See `BoundTarget` for documentation on the individual methods.
*/
class R3BoundTarget {
constructor(target, directives, bindings, references, exprTargets, symbols, nestingLevel, templateEntities, usedPipes) {
this.target = target;
this.directives = directives;
this.bindings = bindings;
this.references = references;
this.exprTargets = exprTargets;
this.symbols = symbols;
this.nestingLevel = nestingLevel;
this.templateEntities = templateEntities;
this.usedPipes = usedPipes;
}
getEntitiesInTemplateScope(template) {
var _a;
return (_a = this.templateEntities.get(template)) !== null && _a !== void 0 ? _a : new Set();
}
getDirectivesOfNode(node) {
return this.directives.get(node) || null;
}
getReferenceTarget(ref) {
return this.references.get(ref) || null;
}
getConsumerOfBinding(binding) {
return this.bindings.get(binding) || null;
}
getExpressionTarget(expr) {
return this.exprTargets.get(expr) || null;
}
getTemplateOfSymbol(symbol) {
return this.symbols.get(symbol) || null;
}
getNestingLevel(template) {
return this.nestingLevel.get(template) || 0;
}
getUsedDirectives() {
const set = new Set();
this.directives.forEach(dirs => dirs.forEach(dir => set.add(dir)));
return Array.from(set.values());
}
getUsedPipes() {
return Array.from(this.usedPipes);
}
}
function extractTemplateEntities(rootScope) {
const entityMap = new Map();
function extractScopeEntities(scope) {
if (entityMap.has(scope.template)) {
return entityMap.get(scope.template);
}
const currentEntities = scope.namedEntities;
let templateEntities;
if (scope.parentScope !== null) {
templateEntities = new Map([...extractScopeEntities(scope.parentScope), ...currentEntities]);
}
else {
templateEntities = new Map(currentEntities);
}
entityMap.set(scope.template, templateEntities);
return templateEntities;
}
const scopesToProcess = [rootScope];
while (scopesToProcess.length > 0) {
const scope = scopesToProcess.pop();
for (const childScope of scope.childScopes.values()) {
scopesToProcess.push(childScope);
}
extractScopeEntities(scope);
}
const templateEntities = new Map();
for (const [template, entities] of entityMap) {
templateEntities.set(template, new Set(entities.values()));
}
return templateEntities;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Creates an array literal expression from the given array, mapping all values to an expression
* using the provided mapping function. If the array is empty or null, then null is returned.
*
* @param values The array to transfer into literal array expression.
* @param mapper The logic to use for creating an expression for the array's values.
* @returns An array literal expression representing `values`, or null if `values` is empty or
* is itself null.
*/
function toOptionalLiteralArray(values, mapper) {
if (values === null || values.length === 0) {
return null;
}
return literalArr(values.map(value => mapper(value)));
}
/**
* Creates an object literal expression from the given object, mapping all values to an expression
* using the provided mapping function. If the object has no keys, then null is returned.
*
* @param object The object to transfer into an object literal expression.
* @param mapper The logic to use for creating an expression for the object's values.
* @returns An object literal expression representing `object`, or null if `object` does not have
* any keys.
*/
function toOptionalLiteralMap(object, mapper) {
const entries = Object.keys(object).map(key => {
const value = object[key];
return { key, value: mapper(value), quoted: true };
});
if (entries.length > 0) {
return literalMap(entries);
}
else {
return null;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Compile a directive declaration defined by the `R3DirectiveMetadata`.
*/
function compileDeclareDirectiveFromMetadata(meta) {
const definitionMap = createDirectiveDefinitionMap(meta);
const expression = importExpr(Identifiers$1.declareDirective).callFn([definitionMap.toLiteralMap()]);
const type = createDirectiveType(meta);
return { expression, type };
}
/**
* Gathers the declaration fields for a directive into a `DefinitionMap`. This allows for reusing
* this logic for components, as they extend the directive metadata.
*/
function createDirectiveDefinitionMap(meta) {
const definitionMap = new DefinitionMap();
definitionMap.set('version', literal('11.2.14'));
// e.g. `type: MyDirective`
definitionMap.set('type', meta.internalType);
// e.g. `selector: 'some-dir'`
if (meta.selector !== null) {
definitionMap.set('selector', literal(meta.selector));
}
definitionMap.set('inputs', conditionallyCreateMapObjectLiteral(meta.inputs, true));
definitionMap.set('outputs', conditionallyCreateMapObjectLiteral(meta.outputs));
definitionMap.set('host', compileHostMetadata(meta.host));
definitionMap.set('providers', meta.providers);
if (meta.queries.length > 0) {
definitionMap.set('queries', literalArr(meta.queries.map(compileQuery)));
}
if (meta.viewQueries.length > 0) {
definitionMap.set('viewQueries', literalArr(meta.viewQueries.map(compileQuery)));
}
if (meta.exportAs !== null) {
definitionMap.set('exportAs', asLiteral(meta.exportAs));
}
if (meta.usesInheritance) {
definitionMap.set('usesInheritance', literal(true));
}
if (meta.lifecycle.usesOnChanges) {
definitionMap.set('usesOnChanges', literal(true));
}
definitionMap.set('ngImport', importExpr(Identifiers$1.core));
return definitionMap;
}
/**
* Compiles the metadata of a single query into its partial declaration form as declared
* by `R3DeclareQueryMetadata`.
*/
function compileQuery(query) {
const meta = new DefinitionMap();
meta.set('propertyName', literal(query.propertyName));
if (query.first) {
meta.set('first', literal(true));
}
meta.set('predicate', Array.isArray(query.predicate) ? asLiteral(query.predicate) : query.predicate);
if (!query.emitDistinctChangesOnly) {
// `emitDistinctChangesOnly` is special because in future we expect it to be `true`. For this
// reason the absence should be interpreted as `true`.
meta.set('emitDistinctChangesOnly', literal(false));
}
if (query.descendants) {
meta.set('descendants', literal(true));
}
meta.set('read', query.read);
if (query.static) {
meta.set('static', literal(true));
}
return meta.toLiteralMap();
}
/**
* Compiles the host metadata into its partial declaration form as declared
* in `R3DeclareDirectiveMetadata['host']`
*/
function compileHostMetadata(meta) {
const hostMetadata = new DefinitionMap();
hostMetadata.set('attributes', toOptionalLiteralMap(meta.attributes, expression => expression));
hostMetadata.set('listeners', toOptionalLiteralMap(meta.listeners, literal));
hostMetadata.set('properties', toOptionalLiteralMap(meta.properties, literal));
if (meta.specialAttributes.styleAttr) {
hostMetadata.set('styleAttribute', literal(meta.specialAttributes.styleAttr));
}
if (meta.specialAttributes.classAttr) {
hostMetadata.set('classAttribute', literal(meta.specialAttributes.classAttr));
}
if (hostMetadata.values.length > 0) {
return hostMetadata.toLiteralMap();
}
else {
return null;
}
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Compile a component declaration defined by the `R3ComponentMetadata`.
*/
function compileDeclareComponentFromMetadata(meta, template) {
const definitionMap = createComponentDefinitionMap(meta, template);
const expression = importExpr(Identifiers$1.declareComponent).callFn([definitionMap.toLiteralMap()]);
const type = createComponentType(meta);
return { expression, type };
}
/**
* Gathers the declaration fields for a component into a `DefinitionMap`.
*/
function createComponentDefinitionMap(meta, template) {
const definitionMap = createDirectiveDefinitionMap(meta);
definitionMap.set('template', getTemplateExpression(template));
if (template.isInline) {
definitionMap.set('isInline', literal(true));
}
definitionMap.set('styles', toOptionalLiteralArray(meta.styles, literal));
definitionMap.set('directives', compileUsedDirectiveMetadata(meta));
definitionMap.set('pipes', compileUsedPipeMetadata(meta));
definitionMap.set('viewProviders', meta.viewProviders);
definitionMap.set('animations', meta.animations);
if (meta.changeDetection !== undefined) {
definitionMap.set('changeDetection', importExpr(Identifiers$1.ChangeDetectionStrategy)
.prop(ChangeDetectionStrategy[meta.changeDetection]));
}
if (meta.encapsulation !== ViewEncapsulation.Emulated) {
definitionMap.set('encapsulation', importExpr(Identifiers$1.ViewEncapsulation).prop(ViewEncapsulation[meta.encapsulation]));
}
if (meta.interpolation !== DEFAULT_INTERPOLATION_CONFIG) {
definitionMap.set('interpolation', literalArr([literal(meta.interpolation.start), literal(meta.interpolation.end)]));
}
if (template.preserveWhitespaces === true) {
definitionMap.set('preserveWhitespaces', literal(true));
}
return definitionMap;
}
function getTemplateExpression(template) {
if (typeof template.template === 'string') {
if (template.isInline) {
// The template is inline but not a simple literal string, so give up with trying to
// source-map it and just return a simple literal here.
return literal(template.template);
}
else {
// The template is external so we must synthesize an expression node with the appropriate
// source-span.
const contents = template.template;
const file = new ParseSourceFile(contents, template.templateUrl);
const start = new ParseLocation(file, 0, 0, 0);
const end = computeEndLocation(file, contents);
const span = new ParseSourceSpan(start, end);
return literal(contents, null, span);
}
}
else {
// The template is inline so we can just reuse the current expression node.
return template.template;
}
}
function computeEndLocation(file, contents) {
const length = contents.length;
let lineStart = 0;
let lastLineStart = 0;
let line = 0;
do {
lineStart = contents.indexOf('\n', lastLineStart);
if (lineStart !== -1) {
lastLineStart = lineStart + 1;
line++;
}
} while (lineStart !== -1);
return new ParseLocation(file, length, line, length - lastLineStart);
}
/**
* Compiles the directives as registered in the component metadata into an array literal of the
* individual directives. If the component does not use any directives, then null is returned.
*/
function compileUsedDirectiveMetadata(meta) {
const wrapType = meta.declarationListEmitMode !== 0 /* Direct */ ?
generateForwardRef :
(expr) => expr;
return toOptionalLiteralArray(meta.directives, directive => {
const dirMeta = new DefinitionMap();
dirMeta.set('type', wrapType(directive.type));
dirMeta.set('selector', literal(directive.selector));
dirMeta.set('inputs', toOptionalLiteralArray(directive.inputs, literal));
dirMeta.set('outputs', toOptionalLiteralArray(directive.outputs, literal));
dirMeta.set('exportAs', toOptionalLiteralArray(directive.exportAs, literal));
return dirMeta.toLiteralMap();
});
}
/**
* Compiles the pipes as registered in the component metadata into an object literal, where the
* pipe's name is used as key and a reference to its type as value. If the component does not use
* any pipes, then null is returned.
*/
function compileUsedPipeMetadata(meta) {
if (meta.pipes.size === 0) {
return null;
}
const wrapType = meta.declarationListEmitMode !== 0 /* Direct */ ?
generateForwardRef :
(expr) => expr;
const entries = [];
for (const [name, pipe] of meta.pipes) {
entries.push({ key: name, value: wrapType(pipe), quoted: true });
}
return literalMap(entries);
}
function generateForwardRef(expr) {
return importExpr(Identifiers$1.forwardRef).callFn([fn([], [new ReturnStatement(expr)])]);
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* Compile a Pipe declaration defined by the `R3PipeMetadata`.
*/
function compileDeclarePipeFromMetadata(meta) {
const definitionMap = createPipeDefinitionMap(meta);
const expression = importExpr(Identifiers$1.declarePipe).callFn([definitionMap.toLiteralMap()]);
const type = createPipeType(meta);
return { expression, type };
}
/**
* Gathers the declaration fields for a Pipe into a `DefinitionMap`. This allows for reusing
* this logic for components, as they extend the Pipe metadata.
*/
function createPipeDefinitionMap(meta) {
const definitionMap = new DefinitionMap();
definitionMap.set('version', literal('11.2.14'));
definitionMap.set('ngImport', importExpr(Identifiers$1.core));
// e.g. `type: MyPipe`
definitionMap.set('type', meta.internalType);
// e.g. `name: "myPipe"`
definitionMap.set('name', literal(meta.pipeName));
if (meta.pure === false) {
// e.g. `pure: false`
definitionMap.set('pure', literal(meta.pure));
}
return definitionMap;
}
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// This file only reexports content of the `src` folder. Keep it that way.
// This function call has a global side effects and publishes the compiler into global namespace for
// the late binding of the Compiler to the @angular/core for jit compilation.
publishFacade(_global);
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// This file only reexports content of the `src` folder. Keep it that way.
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
export { AST, ASTWithName, ASTWithSource, AbsoluteSourceSpan, AotCompiler, AotSummaryResolver, ArrayType, AssertNotNull, AstMemoryEfficientTransformer, AstPath, AstTransformer$1 as AstTransformer, AttrAst, Attribute, Binary, BinaryOperator, BinaryOperatorExpr, BindingPipe, BoundDirectivePropertyAst, BoundElementProperty, BoundElementPropertyAst, BoundEventAst, BoundTextAst, BuiltinMethod, BuiltinType, BuiltinTypeName, BuiltinVar, CONTENT_ATTR, CUSTOM_ELEMENTS_SCHEMA, CastExpr, Chain, ClassField, ClassMethod, ClassStmt, CommaExpr, Comment$1 as Comment, CompileDirectiveMetadata, CompileMetadataResolver, CompileNgModuleMetadata, CompilePipeMetadata, CompileReflector, CompileShallowModuleMetadata, CompileStylesheetMetadata, CompileSummaryKind, CompileTemplateMetadata, CompiledStylesheet, CompilerConfig, Conditional, ConditionalExpr, ConstantPool, CssSelector, DEFAULT_INTERPOLATION_CONFIG, DYNAMIC_TYPE, DeclareFunctionStmt, DeclareVarStmt, DirectiveAst, DirectiveNormalizer, DirectiveResolver, DomElementSchemaRegistry, EOF, ERROR_COMPONENT_TYPE, Element$1 as Element, ElementAst, ElementSchemaRegistry, EmbeddedTemplateAst, EmitterVisitorContext, EmptyExpr, Expansion, ExpansionCase, Expression, ExpressionBinding, ExpressionStatement, ExpressionType, ExternalExpr, ExternalReference, Extractor, FunctionCall, FunctionExpr, GeneratedFile, HOST_ATTR, HtmlParser, HtmlTagDefinition, I18NHtmlParser, Identifiers, IfStmt, ImplicitReceiver, InstantiateExpr, Interpolation, InterpolationConfig, InvokeFunctionExpr, InvokeMethodExpr, IvyParser, JSDocComment, JitCompiler, JitEvaluator, JitSummaryResolver, KeyedRead, KeyedWrite, LeadingComment, Lexer, LiteralArray, LiteralArrayExpr, LiteralExpr, LiteralMap, LiteralMapExpr, LiteralPrimitive, LocalizedString, MapType, MessageBundle, MethodCall, NAMED_ENTITIES, NGSP_UNICODE, NONE_TYPE, NO_ERRORS_SCHEMA, NgContentAst, NgModuleCompiler, NgModuleResolver, NodeWithI18n, NonNullAssert, NotExpr, NullTemplateVisitor, ParseError, ParseErrorLevel, ParseLocation, ParseSourceFile, ParseSourceSpan, ParseSpan, ParseTreeResult, ParsedEvent, ParsedProperty, ParsedPropertyType, ParsedVariable, Parser$1 as Parser, ParserError, PipeResolver, PrefixNot, PropertyRead, PropertyWrite, ProviderAst, ProviderAstType, ProviderMeta, Quote, R3BoundTarget, R3FactoryTarget, Identifiers$1 as R3Identifiers, R3ResolvedDependencyType, R3TargetBinder, ReadKeyExpr, ReadPropExpr, ReadVarExpr, RecursiveAstVisitor$1 as RecursiveAstVisitor, RecursiveTemplateAstVisitor, RecursiveVisitor$1 as RecursiveVisitor, ReferenceAst, ResolvedStaticSymbol, ResourceLoader, ReturnStatement, STRING_TYPE, SafeMethodCall, SafePropertyRead, SelectorContext, SelectorListContext, SelectorMatcher, Serializer, SplitInterpolation, Statement, StaticReflector, StaticSymbol, StaticSymbolCache, StaticSymbolResolver, StmtModifier, StyleCompiler, StylesCompileDependency, SummaryResolver, TagContentType, TaggedTemplateExpr, TemplateBindingParseResult, TemplateLiteral, TemplateLiteralElement, TemplateParseError, TemplateParseResult, TemplateParser, Text$3 as Text, TextAst, ThisReceiver, ThrowStmt, BoundAttribute as TmplAstBoundAttribute, BoundEvent as TmplAstBoundEvent, BoundText as TmplAstBoundText, Content as TmplAstContent, Element as TmplAstElement, Icu as TmplAstIcu, RecursiveVisitor as TmplAstRecursiveVisitor, Reference as TmplAstReference, Template as TmplAstTemplate, Text as TmplAstText, TextAttribute as TmplAstTextAttribute, Variable as TmplAstVariable, Token$1 as Token, TokenType$1 as TokenType, TransitiveCompileNgModuleMetadata, TreeError, TryCatchStmt, Type$1 as Type, TypeScriptEmitter, TypeofExpr, Unary, UnaryOperator, UnaryOperatorExpr, UrlResolver, VERSION$1 as VERSION, VariableAst, VariableBinding, Version, ViewCompiler, WrappedNodeExpr, WriteKeyExpr, WritePropExpr, WriteVarExpr, Xliff, Xliff2, Xmb, XmlParser, Xtb, _ParseAST, analyzeAndValidateNgModules, analyzeFile, analyzeFileForInjectables, analyzeNgModules, collectExternalReferences, compileComponentFromMetadata, compileDeclareComponentFromMetadata, compileDeclareDirectiveFromMetadata, compileDeclarePipeFromMetadata, compileDirectiveFromMetadata, compileFactoryFunction, compileInjectable, compileInjector, compileNgModule, compilePipeFromMetadata, componentFactoryName, computeMsgId, core, createAotCompiler, createAotUrlResolver, createElementCssSelector, createLoweredSymbol, createOfflineCompileUrlResolver, createUrlResolverWithoutPackagePrefix, debugOutputAstAsTypeScript, devOnlyGuardedExpression, findNode, flatten, formattedError, getHtmlTagDefinition, getMissingNgModuleMetadataErrorData, getNsPrefix, getParseErrors, getSafePropertyAccessString, getUrlScheme, hostViewClassName, identifierModuleUrl, identifierName, isEmptyExpression, isFormattedError, isIdentifier, isLoweredSymbol, isNgContainer, isNgContent, isNgTemplate, isQuote, isSyntaxError, jsDocComment, leadingComment, literalMap, makeBindingParser, mergeAnalyzedFiles, mergeNsAndName, ngModuleJitUrl, parseHostBindings, parseTemplate, preserveWhitespacesDefault, publishFacade, r3JitTypeSourceSpan, removeSummaryDuplicates, rendererTypeName, sanitizeIdentifier, sharedStylesheetJitUrl, splitClasses, splitNsName, syntaxError, templateJitUrl, templateSourceUrl, templateVisitAll, toTypeScript, tokenName, tokenReference, typeSourceSpan, unescapeIdentifier, unwrapResolvedMetadata, verifyHostBindings, viewClassName, visitAll$1 as visitAll };
//# sourceMappingURL=compiler.js.map