getBindingAtIndex(index: number): any {
    if (index == 0) return this._binding0;
    if (index == 1) return this._binding1;
    if (index == 2) return this._binding2;
    if (index == 3) return this._binding3;
    if (index == 4) return this._binding4;
    if (index == 5) return this._binding5;
    if (index == 6) return this._binding6;
    if (index == 7) return this._binding7;
    if (index == 8) return this._binding8;
    if (index == 9) return this._binding9;
    throw new OutOfBoundsAccess(index);
  }


createElementInjectorStrategy(ei: ElementInjector): _ElementInjectorStrategy {
    return new ElementInjectorInlineStrategy(this, ei);
  }


hasBindings(): boolean { return isPresent(this._bindings[0]); }


getBindingAtIndex(index: number): any {
    if (index < 0 || index >= this._bindings.length) {
      throw new OutOfBoundsAccess(index);
    }

    return this._bindings[index];
  }


createElementInjectorStrategy(ei: ElementInjector) {
    return new ElementInjectorDynamicStrategy(this, ei);
  }


dehydrate(): void {
    this._host = null;
    this._preBuiltObjects = null;
    this._lightDomAppInjector = null;
    this._shadowDomAppInjector = null;

    this._strategy.callOnDestroy();

    if (isPresent(this._dynamicallyCreatedComponentBinding) &&
        this._dynamicallyCreatedComponentBinding.callOnDestroy) {
      this._dynamicallyCreatedComponent.onDestroy();
    }

    this._strategy.clearInstances();

    this._dynamicallyCreatedComponent = null;
    this._dynamicallyCreatedComponentBinding = null;

    this._constructionCounter = 0;
  }


hydrate(injector: Injector, host: ElementInjector, preBuiltObjects: PreBuiltObjects): void {
    var p = this._proto;

    this._host = host;
    this._lightDomAppInjector = injector;
    this._preBuiltObjects = preBuiltObjects;

    if (p._firstBindingIsComponent) {
      this._shadowDomAppInjector =
          this._createShadowDomAppInjector(this._strategy.getComponentBinding(), injector);
    }

    this._checkShadowDomAppInjector(this._shadowDomAppInjector);

    this._strategy.hydrate();
  }


private _createShadowDomAppInjector(componentDirective: DirectiveBinding,
                                      appInjector: Injector): Injector {
    if (!ListWrapper.isEmpty(componentDirective.resolvedAppInjectables)) {
      return appInjector.createChildFromResolved(componentDirective.resolvedAppInjectables);
    } else {
      return appInjector;
    }
  }


dynamicallyCreateComponent(componentDirective: DirectiveBinding, parentInjector: Injector): any {
    this._shadowDomAppInjector =
        this._createShadowDomAppInjector(componentDirective, parentInjector);
    this._dynamicallyCreatedComponentBinding = componentDirective;
    this._dynamicallyCreatedComponent = this._new(this._dynamicallyCreatedComponentBinding);
    return this._dynamicallyCreatedComponent;
  }


private _checkShadowDomAppInjector(shadowDomAppInjector: Injector): void {
    if (this._proto._firstBindingIsComponent && isBlank(shadowDomAppInjector)) {
      throw new BaseException(
          'A shadowDomAppInjector is required as this ElementInjector contains a component');
    } else if (!this._proto._firstBindingIsComponent && isPresent(shadowDomAppInjector)) {
      throw new BaseException(
          'No shadowDomAppInjector allowed as there is not component stored in this ElementInjector');
    }
  }


get(token): any {
    if (this._isDynamicallyLoadedComponent(token)) {
      return this._dynamicallyCreatedComponent;
    }

    return this._getByKey(Key.get(token), self, false, null);
  }


private _isDynamicallyLoadedComponent(token): boolean {
    return isPresent(this._dynamicallyCreatedComponentBinding) &&
           Key.get(token) === this._dynamicallyCreatedComponentBinding.key;
  }


hasDirective(type: Type): boolean {
    return this._strategy.getObjByKeyId(Key.get(type).id, LIGHT_DOM_AND_SHADOW_DOM) !== _undefined;
  }


getEventEmitterAccessors(): List<List<EventEmitterAccessor>> {
    return this._proto.eventEmitterAccessors;
  }


getHostActionAccessors(): List<List<HostActionAccessor>> {
    return this._proto.hostActionAccessors;
  }


getComponent(): any { return this._strategy.getComponent(); }


getElementRef(): ElementRef {
    return new ElementRef(new ViewRef(this._preBuiltObjects.view), this._proto.index);
  }


getViewContainerRef(): ViewContainerRef {
    return new ViewContainerRef(this._preBuiltObjects.viewManager, this.getElementRef());
  }


getDynamicallyLoadedComponent(): any { return this._dynamicallyCreatedComponent; }


directParent(): ElementInjector { return this._proto.distanceToParent < 2 ? this.parent : null; }


private _isComponentKey(key: Key): boolean { return this._strategy.isComponentKey(key); }


private _isDynamicallyLoadedComponentKey(key: Key): boolean {
    return isPresent(this._dynamicallyCreatedComponentBinding) &&
           key.id === this._dynamicallyCreatedComponentBinding.key.id;
  }


_new(binding: ResolvedBinding): any {
    if (this._constructionCounter++ > this._strategy.getMaxDirectives()) {
      throw new CyclicDependencyError(binding.key);
    }

    var factory = binding.factory;
    var deps = <List<DirectiveDependency>>binding.dependencies;
    var length = deps.length;

    var d0, d1, d2, d3, d4, d5, d6, d7, d8, d9;
    try {
      d0 = length > 0 ? this._getByDependency(deps[0], binding.key) : null;
      d1 = length > 1 ? this._getByDependency(deps[1], binding.key) : null;
      d2 = length > 2 ? this._getByDependency(deps[2], binding.key) : null;
      d3 = length > 3 ? this._getByDependency(deps[3], binding.key) : null;
      d4 = length > 4 ? this._getByDependency(deps[4], binding.key) : null;
      d5 = length > 5 ? this._getByDependency(deps[5], binding.key) : null;
      d6 = length > 6 ? this._getByDependency(deps[6], binding.key) : null;
      d7 = length > 7 ? this._getByDependency(deps[7], binding.key) : null;
      d8 = length > 8 ? this._getByDependency(deps[8], binding.key) : null;
      d9 = length > 9 ? this._getByDependency(deps[9], binding.key) : null;
    } catch (e) {
      if (e instanceof AbstractBindingError) e.addKey(binding.key);
      throw e;
    }

    var obj;
    switch (length) {
      case 0:
        obj = factory();
        break;
      case 1:
        obj = factory(d0);
        break;
      case 2:
        obj = factory(d0, d1);
        break;
      case 3:
        obj = factory(d0, d1, d2);
        break;
      case 4:
        obj = factory(d0, d1, d2, d3);
        break;
      case 5:
        obj = factory(d0, d1, d2, d3, d4);
        break;
      case 6:
        obj = factory(d0, d1, d2, d3, d4, d5);
        break;
      case 7:
        obj = factory(d0, d1, d2, d3, d4, d5, d6);
        break;
      case 8:
        obj = factory(d0, d1, d2, d3, d4, d5, d6, d7);
        break;
      case 9:
        obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8);
        break;
      case 10:
        obj = factory(d0, d1, d2, d3, d4, d5, d6, d7, d8, d9);
        break;
    }

    this._addToQueries(obj, binding.key.token);

    return obj;
  }


private _getByDependency(dep: DependencyWithVisibility, requestor: Key): any {
    if (!(dep instanceof DirectiveDependency)) {
      return this._getByKey(dep.key, dep.visibility, dep.optional, requestor);
    }

    var dirDep = <DirectiveDependency>dep;

    if (isPresent(dirDep.attributeName)) return this._buildAttribute(dirDep);
    if (isPresent(dirDep.queryDirective)) return this._findQuery(dirDep.queryDirective).list;
    if (dirDep.key.id === StaticKeys.instance().changeDetectorRefId) {
      var componentView = this._preBuiltObjects.view.componentChildViews[this._proto.index];
      return componentView.changeDetector.ref;
    }
    if (dirDep.key.id === StaticKeys.instance().elementRefId) {
      return this.getElementRef();
    }
    if (dirDep.key.id === StaticKeys.instance().viewContainerId) {
      return this.getViewContainerRef();
    }
    if (dirDep.key.id === StaticKeys.instance().protoViewId) {
      if (isBlank(this._preBuiltObjects.protoView)) {
        if (dirDep.optional) {
          return null;
        }

        throw new NoBindingError(dirDep.key);
      }
      return new ProtoViewRef(this._preBuiltObjects.protoView);
    }
    return this._getByKey(dirDep.key, dirDep.visibility, dirDep.optional, requestor);
  }


private _buildAttribute(dep: DirectiveDependency): string {
    var attributes = this._proto.attributes;
    if (isPresent(attributes) && MapWrapper.contains(attributes, dep.attributeName)) {
      return MapWrapper.get(attributes, dep.attributeName);
    } else {
      return null;
    }
  }


_buildQueriesForDeps(deps: List<DirectiveDependency>): void {
    for (var i = 0; i < deps.length; i++) {
      var dep = deps[i];
      if (isPresent(dep.queryDirective)) {
        this._createQueryRef(dep.queryDirective);
      }
    }
  }


private _createQueryRef(directive): void {
    var queryList = new QueryList<any>();
    if (isBlank(this._query0)) {
      this._query0 = new QueryRef(directive, queryList, this);
    } else if (isBlank(this._query1)) {
      this._query1 = new QueryRef(directive, queryList, this);
    } else if (isBlank(this._query2)) {
      this._query2 = new QueryRef(directive, queryList, this);
    } else
      throw new QueryError();
  }


private _addToQueries(obj, token): void {
    if (isPresent(this._query0) && (this._query0.directive === token)) {
      this._query0.list.add(obj);
    }
    if (isPresent(this._query1) && (this._query1.directive === token)) {
      this._query1.list.add(obj);
    }
    if (isPresent(this._query2) && (this._query2.directive === token)) {
      this._query2.list.add(obj);
    }
  }


// TODO(rado): unify with _addParentQueries.
private _inheritQueries(parent: ElementInjector): void {
    if (isBlank(parent)) return;
    if (isPresent(parent._query0)) {
      this._query0 = parent._query0;
    }
    if (isPresent(parent._query1)) {
      this._query1 = parent._query1;
    }
    if (isPresent(parent._query2)) {
      this._query2 = parent._query2;
    }
  }


private _buildQueries(): void {
    if (isPresent(this._proto)) {
      this._strategy.buildQueries();
    }
  }


private _findQuery(token): QueryRef {
    if (isPresent(this._query0) && this._query0.directive === token) {
      return this._query0;
    }
    if (isPresent(this._query1) && this._query1.directive === token) {
      return this._query1;
    }
    if (isPresent(this._query2) && this._query2.directive === token) {
      return this._query2;
    }
    throw new BaseException(`Cannot find query for directive ${token}.`);
  }


link(parent: ElementInjector): void {
    parent.addChild(this);
    this._addParentQueries();
  }


linkAfter(parent: ElementInjector, prevSibling: ElementInjector): void {
    parent.addChildAfter(this, prevSibling);
    this._addParentQueries();
  }


private _addParentQueries(): void {
    if (isPresent(this.parent._query0)) {
      this._addQueryToTree(this.parent._query0);
      this.parent._query0.update();
    }
    if (isPresent(this.parent._query1)) {
      this._addQueryToTree(this.parent._query1);
      this.parent._query1.update();
    }
    if (isPresent(this.parent._query2)) {
      this._addQueryToTree(this.parent._query2);
      this.parent._query2.update();
    }
  }


unlink(): void {
    var queriesToUpDate = [];
    if (isPresent(this.parent._query0)) {
      this._pruneQueryFromTree(this.parent._query0);
      ListWrapper.push(queriesToUpDate, this.parent._query0);
    }
    if (isPresent(this.parent._query1)) {
      this._pruneQueryFromTree(this.parent._query1);
      ListWrapper.push(queriesToUpDate, this.parent._query1);
    }
    if (isPresent(this.parent._query2)) {
      this._pruneQueryFromTree(this.parent._query2);
      ListWrapper.push(queriesToUpDate, this.parent._query2);
    }

    this.remove();

    ListWrapper.forEach(queriesToUpDate, (q) => q.update());
  }


private _pruneQueryFromTree(query: QueryRef): void {
    this._removeQueryRef(query);

    var child = this._head;
    while (isPresent(child)) {
      child._pruneQueryFromTree(query);
      child = child._next;
    }
  }


private _addQueryToTree(query: QueryRef): void {
    this._assignQueryRef(query);

    var child = this._head;
    while (isPresent(child)) {
      child._addQueryToTree(query);
      child = child._next;
    }
  }


private _assignQueryRef(query: QueryRef): void {
    if (isBlank(this._query0)) {
      this._query0 = query;
      return;
    } else if (isBlank(this._query1)) {
      this._query1 = query;
      return;
    } else if (isBlank(this._query2)) {
      this._query2 = query;
      return;
    }
    throw new QueryError();
  }


private _removeQueryRef(query: QueryRef): void {
    if (this._query0 == query) this._query0 = null;
    if (this._query1 == query) this._query1 = null;
    if (this._query2 == query) this._query2 = null;
  }


private _getByKey(key: Key, visibility: Visibility, optional: boolean, requestor: Key): any {
    var ei = this;

    var currentVisibility = this._isComponentKey(requestor) ?
                                LIGHT_DOM_AND_SHADOW_DOM :  // component can access both shadow dom
                                                            // and light dom dependencies
                                LIGHT_DOM;

    var depth = visibility.depth;

    if (!visibility.includeSelf) {
      depth -= ei._proto.distanceToParent;

      if (isPresent(ei._parent)) {
        ei = ei._parent;
      } else {
        ei = ei._host;
        currentVisibility = visibility.crossComponentBoundaries ? LIGHT_DOM : SHADOW_DOM;
      }
    }

    while (ei != null && depth >= 0) {
      var preBuiltObj = ei._getPreBuiltObjectByKeyId(key.id);
      if (preBuiltObj !== _undefined) return preBuiltObj;

      var dir = ei._getObjByKeyId(key.id, currentVisibility);
      if (dir !== _undefined) return dir;

      depth -= ei._proto.distanceToParent;

      // we check only one mode with the SHADOW_DOM visibility
      if (currentVisibility === SHADOW_DOM) break;

      if (isPresent(ei._parent)) {
        ei = ei._parent;
      } else {
        ei = ei._host;
        currentVisibility = visibility.crossComponentBoundaries ? LIGHT_DOM : SHADOW_DOM;
      }
    }

    if (isPresent(this._host) && this._host._isComponentKey(key)) {
      return this._host.getComponent();
    } else if (isPresent(this._host) && this._host._isDynamicallyLoadedComponentKey(key)) {
      return this._host.getDynamicallyLoadedComponent();
    } else if (optional) {
      return this._appInjector(requestor).getOptional(key);
    } else {
      return this._appInjector(requestor).get(key);
    }
  }


private _appInjector(requestor: Key): Injector {
    if (isPresent(requestor) &&
        (this._isComponentKey(requestor) || this._isDynamicallyLoadedComponentKey(requestor))) {
      return this._shadowDomAppInjector;
    } else {
      return this._lightDomAppInjector;
    }
  }


private _getPreBuiltObjectByKeyId(keyId: number): any {
    var staticKeys = StaticKeys.instance();
    if (keyId === staticKeys.viewManagerId) return this._preBuiltObjects.viewManager;

    return _undefined;
  }


private _getObjByKeyId(keyId: number, visibility: number) {
    return this._strategy.getObjByKeyId(keyId, visibility);
  }


getDirectiveAtIndex(index: number) { return this._strategy.getDirectiveAtIndex(index); }


hasInstances(): boolean { return this._constructionCounter > 0; }


/** Gets whether this element is exporting a component instance as $implicit. */
isExportingComponent(): boolean { return this._proto.exportComponent; }


/** Gets whether this element is exporting its element as $implicit. */
isExportingElement(): boolean { return this._proto.exportElement; }


/** Get the name to which this element's $implicit is to be assigned. */
getExportImplicitName(): string { return this._proto.exportImplicitName; }


getLightDomAppInjector(): Injector { return this._lightDomAppInjector; }


getShadowDomAppInjector(): Injector { return this._shadowDomAppInjector; }


getHost(): ElementInjector { return this._host; }


getBoundElementIndex(): number { return this._proto.index; }


callOnDestroy(): void {
    var p = this._protoStrategy;

    if (p._binding0 instanceof DirectiveBinding && (<DirectiveBinding>p._binding0).callOnDestroy) {
      this._obj0.onDestroy();
    }
    if (p._binding1 instanceof DirectiveBinding && (<DirectiveBinding>p._binding1).callOnDestroy) {
      this._obj1.onDestroy();
    }
    if (p._binding2 instanceof DirectiveBinding && (<DirectiveBinding>p._binding2).callOnDestroy) {
      this._obj2.onDestroy();
    }
    if (p._binding3 instanceof DirectiveBinding && (<DirectiveBinding>p._binding3).callOnDestroy) {
      this._obj3.onDestroy();
    }
    if (p._binding4 instanceof DirectiveBinding && (<DirectiveBinding>p._binding4).callOnDestroy) {
      this._obj4.onDestroy();
    }
    if (p._binding5 instanceof DirectiveBinding && (<DirectiveBinding>p._binding5).callOnDestroy) {
      this._obj5.onDestroy();
    }
    if (p._binding6 instanceof DirectiveBinding && (<DirectiveBinding>p._binding6).callOnDestroy) {
      this._obj6.onDestroy();
    }
    if (p._binding7 instanceof DirectiveBinding && (<DirectiveBinding>p._binding7).callOnDestroy) {
      this._obj7.onDestroy();
    }
    if (p._binding8 instanceof DirectiveBinding && (<DirectiveBinding>p._binding8).callOnDestroy) {
      this._obj8.onDestroy();
    }
    if (p._binding9 instanceof DirectiveBinding && (<DirectiveBinding>p._binding9).callOnDestroy) {
      this._obj9.onDestroy();
    }
  }


clearInstances(): void {
    this._obj0 = null;
    this._obj1 = null;
    this._obj2 = null;
    this._obj3 = null;
    this._obj4 = null;
    this._obj5 = null;
    this._obj6 = null;
    this._obj7 = null;
    this._obj8 = null;
    this._obj9 = null;
  }


hydrate(): void {
    var p = this._protoStrategy;

    if (isPresent(p._keyId0)) this.getObjByKeyId(p._keyId0, LIGHT_DOM_AND_SHADOW_DOM);
    if (isPresent(p._keyId1)) this.getObjByKeyId(p._keyId1, LIGHT_DOM_AND_SHADOW_DOM);
    if (isPresent(p._keyId2)) this.getObjByKeyId(p._keyId2, LIGHT_DOM_AND_SHADOW_DOM);
    if (isPresent(p._keyId3)) this.getObjByKeyId(p._keyId3, LIGHT_DOM_AND_SHADOW_DOM);
    if (isPresent(p._keyId4)) this.getObjByKeyId(p._keyId4, LIGHT_DOM_AND_SHADOW_DOM);
    if (isPresent(p._keyId5)) this.getObjByKeyId(p._keyId5, LIGHT_DOM_AND_SHADOW_DOM);
    if (isPresent(p._keyId6)) this.getObjByKeyId(p._keyId6, LIGHT_DOM_AND_SHADOW_DOM);
    if (isPresent(p._keyId7)) this.getObjByKeyId(p._keyId7, LIGHT_DOM_AND_SHADOW_DOM);
    if (isPresent(p._keyId8)) this.getObjByKeyId(p._keyId8, LIGHT_DOM_AND_SHADOW_DOM);
    if (isPresent(p._keyId9)) this.getObjByKeyId(p._keyId9, LIGHT_DOM_AND_SHADOW_DOM);
  }


getComponent(): any { return this._obj0; }


isComponentKey(key: Key): boolean {
    return this._ei._proto._firstBindingIsComponent && isPresent(key) &&
           key.id === this._protoStrategy._keyId0;
  }


buildQueries(): void {
    var p = this._protoStrategy;
    if (p._binding0 instanceof DirectiveBinding) {
      this._ei._buildQueriesForDeps(<List<DirectiveDependency>>p._binding0.dependencies);
    }
    if (p._binding1 instanceof DirectiveBinding) {
      this._ei._buildQueriesForDeps(<List<DirectiveDependency>>p._binding1.dependencies);
    }
    if (p._binding2 instanceof DirectiveBinding) {
      this._ei._buildQueriesForDeps(<List<DirectiveDependency>>p._binding2.dependencies);
    }
    if (p._binding3 instanceof DirectiveBinding) {
      this._ei._buildQueriesForDeps(<List<DirectiveDependency>>p._binding3.dependencies);
    }
    if (p._binding4 instanceof DirectiveBinding) {
      this._ei._buildQueriesForDeps(<List<DirectiveDependency>>p._binding4.dependencies);
    }
    if (p._binding5 instanceof DirectiveBinding) {
      this._ei._buildQueriesForDeps(<List<DirectiveDependency>>p._binding5.dependencies);
    }
    if (p._binding6 instanceof DirectiveBinding) {
      this._ei._buildQueriesForDeps(<List<DirectiveDependency>>p._binding6.dependencies);
    }
    if (p._binding7 instanceof DirectiveBinding) {
      this._ei._buildQueriesForDeps(<List<DirectiveDependency>>p._binding7.dependencies);
    }
    if (p._binding8 instanceof DirectiveBinding) {
      this._ei._buildQueriesForDeps(<List<DirectiveDependency>>p._binding8.dependencies);
    }
    if (p._binding9 instanceof DirectiveBinding) {
      this._ei._buildQueriesForDeps(<List<DirectiveDependency>>p._binding9.dependencies);
    }
  }


getObjByKeyId(keyId: number, visibility: number): any {
    var p = this._protoStrategy;

    if (p._keyId0 === keyId && (p._visibility0 & visibility) > 0) {
      if (isBlank(this._obj0)) {
        this._obj0 = this._ei._new(p._binding0);
      }
      return this._obj0;
    }
    if (p._keyId1 === keyId && (p._visibility1 & visibility) > 0) {
      if (isBlank(this._obj1)) {
        this._obj1 = this._ei._new(p._binding1);
      }
      return this._obj1;
    }
    if (p._keyId2 === keyId && (p._visibility2 & visibility) > 0) {
      if (isBlank(this._obj2)) {
        this._obj2 = this._ei._new(p._binding2);
      }
      return this._obj2;
    }
    if (p._keyId3 === keyId && (p._visibility3 & visibility) > 0) {
      if (isBlank(this._obj3)) {
        this._obj3 = this._ei._new(p._binding3);
      }
      return this._obj3;
    }
    if (p._keyId4 === keyId && (p._visibility4 & visibility) > 0) {
      if (isBlank(this._obj4)) {
        this._obj4 = this._ei._new(p._binding4);
      }
      return this._obj4;
    }
    if (p._keyId5 === keyId && (p._visibility5 & visibility) > 0) {
      if (isBlank(this._obj5)) {
        this._obj5 = this._ei._new(p._binding5);
      }
      return this._obj5;
    }
    if (p._keyId6 === keyId && (p._visibility6 & visibility) > 0) {
      if (isBlank(this._obj6)) {
        this._obj6 = this._ei._new(p._binding6);
      }
      return this._obj6;
    }
    if (p._keyId7 === keyId && (p._visibility7 & visibility) > 0) {
      if (isBlank(this._obj7)) {
        this._obj7 = this._ei._new(p._binding7);
      }
      return this._obj7;
    }
    if (p._keyId8 === keyId && (p._visibility8 & visibility) > 0) {
      if (isBlank(this._obj8)) {
        this._obj8 = this._ei._new(p._binding8);
      }
      return this._obj8;
    }
    if (p._keyId9 === keyId && (p._visibility9 & visibility) > 0) {
      if (isBlank(this._obj9)) {
        this._obj9 = this._ei._new(p._binding9);
      }
      return this._obj9;
    }

    return _undefined;
  }


getDirectiveAtIndex(index: number) {
    if (index == 0) return this._obj0;
    if (index == 1) return this._obj1;
    if (index == 2) return this._obj2;
    if (index == 3) return this._obj3;
    if (index == 4) return this._obj4;
    if (index == 5) return this._obj5;
    if (index == 6) return this._obj6;
    if (index == 7) return this._obj7;
    if (index == 8) return this._obj8;
    if (index == 9) return this._obj9;
    throw new OutOfBoundsAccess(index);
  }


getComponentBinding(): DirectiveBinding {
    return <DirectiveBinding>this._protoStrategy._binding0;
  }


getMaxDirectives(): number { return _MAX_DIRECTIVE_CONSTRUCTION_COUNTER; }


callOnDestroy(): void {
    var p = this._protoStrategy;

    for (var i = 0; i < p._bindings.length; i++) {
      if (p._bindings[i] instanceof DirectiveBinding &&
                                        (<DirectiveBinding>p._bindings[i]).callOnDestroy) {
        this._objs[i].onDestroy();
      }
    }
  }


clearInstances(): void { ListWrapper.fill(this._objs, null); }


hydrate(): void {
    var p = this._protoStrategy;

    for (var i = 0; i < p._keyIds.length; i++) {
      if (isPresent(p._keyIds[i])) {
        this.getObjByKeyId(p._keyIds[i], LIGHT_DOM_AND_SHADOW_DOM);
      }
    }
  }


getComponent(): any { return this._objs[0]; }


isComponentKey(key: Key): boolean {
    return this._ei._proto._firstBindingIsComponent && isPresent(key) &&
           key.id === this._protoStrategy._keyIds[0];
  }


buildQueries(): void {
    var p = this._protoStrategy;

    for (var i = 0; i < p._bindings.length; i++) {
      if (p._bindings[i] instanceof DirectiveBinding) {
        this._ei._buildQueriesForDeps(<List<DirectiveDependency>>p._bindings[i].dependencies);
      }
    }
  }


getObjByKeyId(keyId: number, visibility: number): any {
    var p = this._protoStrategy;

    // TODO(vicb): optimize lookup ?
    for (var i = 0; i < p._keyIds.length; i++) {
      if (p._keyIds[i] === keyId && (p._visibilities[i] & visibility) > 0) {
        if (isBlank(this._objs[i])) {
          this._objs[i] = this._ei._new(p._bindings[i]);
        }

        return this._objs[i];
      }
    }

    return _undefined;
  }


getDirectiveAtIndex(index: number): any {
    if (index < 0 || index >= this._objs.length) {
      throw new OutOfBoundsAccess(index);
    }

    return this._objs[index];
  }


getComponentBinding(): DirectiveBinding {
    return <DirectiveBinding>this._protoStrategy._bindings[0];
  }


getMaxDirectives(): number { return this._objs.length; }


update(): void {
    var aggregator = [];
    this.visit(this.originator, aggregator);
    this.list.reset(aggregator);
  }


visit(inj: ElementInjector, aggregator): void {
    if (isBlank(inj)) return;
    if (inj.hasDirective(this.directive)) {
      ListWrapper.push(aggregator, inj.get(this.directive));
    }
    var child = inj._head;
    while (isPresent(child)) {
      this.visit(child, aggregator);
      child = child._next;
    }
  }


@NgModule({
  declarations: [
    ProfileComponent,
    BankComponent,
    CollateralComponent,
    FamilyComponent,
    InstallmentComponent,
    WorkComponent,
    BusinessComponent,

    OtherIncomeComponent,
    OtherIncomeOneComponent,
    OtherIncomeTwoComponent,

    PersonalComponent,
    SupportComponent
  ],
  imports: [
    CommonModule,
    HttpModule,
    FormsModule,
    RouterModule.forChild(routes),
  ],providers: [ ]
})

export default class ProfileModule {
  static routes = routes;
}


function createComponent(): ReactWrapper<{}, IKeyboardContext> {
        return mount(
            <KeyboardManager>

Hello - I am a child component

            </KeyboardManager>,
        );
    }


() => {
    const registrationManagerMock = KeyboardRegistrationManager as jest.Mocked<typeof KeyboardRegistrationManager>;
    let wrapper: ReactWrapper<{}, IKeyboardContext> = null;
    let addEventListenerSpy: jest.SpyInstance = null;
    let removeEventListenerSpy: jest.SpyInstance = null;

    function createComponent(): ReactWrapper<{}, IKeyboardContext> {
        return mount(
            <KeyboardManager>

Hello - I am a child component

            </KeyboardManager>,
        );
    }

    beforeEach(() => {
        (registrationManagerMock.prototype.invokeHandler as any).mockClear();
        addEventListenerSpy = jest.spyOn(window, "addEventListener");
        removeEventListenerSpy = jest.spyOn(window, "removeEventListener");
        wrapper = createComponent();
    });

    it("is defined", () => {
        expect(wrapper).not.toBeNull();
    });

    it("initial state is defined", () => {
        expect(wrapper.state().keyboard).toBeInstanceOf(KeyboardRegistrationManager);
    });

    it("registers event handlers for keydown events", () => {
        expect(addEventListenerSpy).toBeCalled();
        expect(removeEventListenerSpy).toBeCalled();
    });

    it("renders all child components", () => {
        expect(wrapper.find(".child").exists()).toBe(true);
    });

    it("listens for CmdOrCtrl+ keydown events and invokes handlers", () => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyDown, {
                ctrlKey: true,
                key: "1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyDown, "CmdOrCtrl+1", keyboardEvent);
    });

    it("listens for CmdOrCtrl+ keyup events and invokes handlers", () => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyUp, {
                ctrlKey: true,
                key: "1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyUp, "CmdOrCtrl+1", keyboardEvent);
    });

    it("listens for CmdOrCtrl+ keypress events and invokes handlers", () => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyPress, {
                ctrlKey: true,
                key: "1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyPress, "CmdOrCtrl+1", keyboardEvent);
    });

    it("listens for Alt+ keydown events and invokes handlers", () => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyDown, {
                ctrlKey: false,
                altKey: true,
                key: "1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyDown, "Alt+1", keyboardEvent);
    });

    it("listens for Alt+ keyup events and invokes handlers", () => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyUp, {
                ctrlKey: false,
                altKey: true,
                key: "1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyUp, "Alt+1", keyboardEvent);
    });

    it("listens for Alt+ keypress events and invokes handlers", () => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyPress, {
                ctrlKey: false,
                altKey: true,
                key: "1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyPress, "Alt+1", keyboardEvent);
    });

    it("listens for keydown events and invokes handlers", () => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyDown, {
                ctrlKey: false,
                altKey: false,
                key: "F1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyDown, "F1", keyboardEvent);
    });

    it("listens for keyup events and invokes handlers", () => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyUp, {
                ctrlKey: false,
                altKey: false,
                key: "F1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyUp, "F1", keyboardEvent);
    });

    it("listens for keypress events and invokes handlers", () => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyPress, {
                ctrlKey: false,
                altKey: false,
                key: "F1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyPress, "F1", keyboardEvent);
    });

    describe("Disabling keyboard manager", () => {
        it("ignores keyboard events when UI is focused on an input element", () => {
            const keyboardEvent = new KeyboardEvent(
                KeyEventType.KeyPress, {
                    ctrlKey: false,
                    altKey: false,
                    key: "a",
                });

            Object.defineProperty(document, "activeElement", {
                get: jest.fn(() => document.createElement("input")),
                configurable: true,
            });

            window.dispatchEvent(keyboardEvent);

            expect(registrationManagerMock.prototype.invokeHandler).not.toBeCalled();
        });

        it("ignores keyboard events when UI is focused on an textarea element", () => {
            const keyboardEvent = new KeyboardEvent(
                KeyEventType.KeyPress, {
                    ctrlKey: false,
                    altKey: false,
                    key: "a",
                });

            Object.defineProperty(document, "activeElement", {
                get: jest.fn(() => document.createElement("textarea")),
                configurable: true,
            });

            window.dispatchEvent(keyboardEvent);

            expect(registrationManagerMock.prototype.invokeHandler).not.toBeCalled();
        });

        it("ignores keyboard events when UI is focused on select elements", () => {
            const keyboardEvent = new KeyboardEvent(
                KeyEventType.KeyPress, {
                    ctrlKey: false,
                    altKey: false,
                    key: "a",
                });

            Object.defineProperty(document, "activeElement", {
                get: jest.fn(() => document.createElement("select")),
                configurable: true,
            });

            window.dispatchEvent(keyboardEvent);

            expect(registrationManagerMock.prototype.invokeHandler).not.toBeCalled();
        });

        it("does not ignore keyboard events when UI is focused on other form elements", () => {
            const keyboardEvent = new KeyboardEvent(
                KeyEventType.KeyPress, {
                    ctrlKey: false,
                    altKey: false,
                    key: "a",
                });

            Object.defineProperty(document, "activeElement", {
                get: jest.fn(() => document.createElement("button")),
                configurable: true,
            });

            window.dispatchEvent(keyboardEvent);

            expect(registrationManagerMock.prototype.invokeHandler).toBeCalled();
        });
    });
}


() => {
        (registrationManagerMock.prototype.invokeHandler as any).mockClear();
        addEventListenerSpy = jest.spyOn(window, "addEventListener");
        removeEventListenerSpy = jest.spyOn(window, "removeEventListener");
        wrapper = createComponent();
    }


() => {
        expect(wrapper).not.toBeNull();
    }


() => {
        expect(wrapper.state().keyboard).toBeInstanceOf(KeyboardRegistrationManager);
    }


() => {
        expect(addEventListenerSpy).toBeCalled();
        expect(removeEventListenerSpy).toBeCalled();
    }


() => {
        expect(wrapper.find(".child").exists()).toBe(true);
    }


() => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyDown, {
                ctrlKey: true,
                key: "1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyDown, "CmdOrCtrl+1", keyboardEvent);
    }


() => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyUp, {
                ctrlKey: true,
                key: "1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyUp, "CmdOrCtrl+1", keyboardEvent);
    }


() => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyPress, {
                ctrlKey: true,
                key: "1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyPress, "CmdOrCtrl+1", keyboardEvent);
    }


() => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyDown, {
                ctrlKey: false,
                altKey: true,
                key: "1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyDown, "Alt+1", keyboardEvent);
    }


() => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyUp, {
                ctrlKey: false,
                altKey: true,
                key: "1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyUp, "Alt+1", keyboardEvent);
    }


() => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyPress, {
                ctrlKey: false,
                altKey: true,
                key: "1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyPress, "Alt+1", keyboardEvent);
    }


() => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyDown, {
                ctrlKey: false,
                altKey: false,
                key: "F1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyDown, "F1", keyboardEvent);
    }


() => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyUp, {
                ctrlKey: false,
                altKey: false,
                key: "F1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyUp, "F1", keyboardEvent);
    }


() => {
        const keyboardEvent = new KeyboardEvent(
            KeyEventType.KeyPress, {
                ctrlKey: false,
                altKey: false,
                key: "F1",
            });

        window.dispatchEvent(keyboardEvent);

        expect(registrationManagerMock.prototype.invokeHandler)
            .toBeCalledWith(KeyEventType.KeyPress, "F1", keyboardEvent);
    }


() => {
        it("ignores keyboard events when UI is focused on an input element", () => {
            const keyboardEvent = new KeyboardEvent(
                KeyEventType.KeyPress, {
                    ctrlKey: false,
                    altKey: false,
                    key: "a",
                });

            Object.defineProperty(document, "activeElement", {
                get: jest.fn(() => document.createElement("input")),
                configurable: true,
            });

            window.dispatchEvent(keyboardEvent);

            expect(registrationManagerMock.prototype.invokeHandler).not.toBeCalled();
        });

        it("ignores keyboard events when UI is focused on an textarea element", () => {
            const keyboardEvent = new KeyboardEvent(
                KeyEventType.KeyPress, {
                    ctrlKey: false,
                    altKey: false,
                    key: "a",
                });

            Object.defineProperty(document, "activeElement", {
                get: jest.fn(() => document.createElement("textarea")),
                configurable: true,
            });

            window.dispatchEvent(keyboardEvent);

            expect(registrationManagerMock.prototype.invokeHandler).not.toBeCalled();
        });

        it("ignores keyboard events when UI is focused on select elements", () => {
            const keyboardEvent = new KeyboardEvent(
                KeyEventType.KeyPress, {
                    ctrlKey: false,
                    altKey: false,
                    key: "a",
                });

            Object.defineProperty(document, "activeElement", {
                get: jest.fn(() => document.createElement("select")),
                configurable: true,
            });

            window.dispatchEvent(keyboardEvent);

            expect(registrationManagerMock.prototype.invokeHandler).not.toBeCalled();
        });

        it("does not ignore keyboard events when UI is focused on other form elements", () => {
            const keyboardEvent = new KeyboardEvent(
                KeyEventType.KeyPress, {
                    ctrlKey: false,
                    altKey: false,
                    key: "a",
                });

            Object.defineProperty(document, "activeElement", {
                get: jest.fn(() => document.createElement("button")),
                configurable: true,
            });

            window.dispatchEvent(keyboardEvent);

            expect(registrationManagerMock.prototype.invokeHandler).toBeCalled();
        });
    }


() => {
            const keyboardEvent = new KeyboardEvent(
                KeyEventType.KeyPress, {
                    ctrlKey: false,
                    altKey: false,
                    key: "a",
                });

            Object.defineProperty(document, "activeElement", {
                get: jest.fn(() => document.createElement("input")),
                configurable: true,
            });

            window.dispatchEvent(keyboardEvent);

            expect(registrationManagerMock.prototype.invokeHandler).not.toBeCalled();
        }


() => document.createElement("input")


() => {
            const keyboardEvent = new KeyboardEvent(
                KeyEventType.KeyPress, {
                    ctrlKey: false,
                    altKey: false,
                    key: "a",
                });

            Object.defineProperty(document, "activeElement", {
                get: jest.fn(() => document.createElement("textarea")),
                configurable: true,
            });

            window.dispatchEvent(keyboardEvent);

            expect(registrationManagerMock.prototype.invokeHandler).not.toBeCalled();
        }


() => document.createElement("textarea")


() => {
            const keyboardEvent = new KeyboardEvent(
                KeyEventType.KeyPress, {
                    ctrlKey: false,
                    altKey: false,
                    key: "a",
                });

            Object.defineProperty(document, "activeElement", {
                get: jest.fn(() => document.createElement("select")),
                configurable: true,
            });

            window.dispatchEvent(keyboardEvent);

            expect(registrationManagerMock.prototype.invokeHandler).not.toBeCalled();
        }


() => document.createElement("select")


() => {
            const keyboardEvent = new KeyboardEvent(
                KeyEventType.KeyPress, {
                    ctrlKey: false,
                    altKey: false,
                    key: "a",
                });

            Object.defineProperty(document, "activeElement", {
                get: jest.fn(() => document.createElement("button")),
                configurable: true,
            });

            window.dispatchEvent(keyboardEvent);

            expect(registrationManagerMock.prototype.invokeHandler).toBeCalled();
        }


() => document.createElement("button")


function TeacherList() {
    const [teachers, setTeachers] = useState([]);
    const [subject, setSubject] = useState("");
    const [week_day, setWeek_day] = useState("");
    const [time, setTime] = useState("");

    async function searchTeachers(e: FormEvent) {
        e.preventDefault();

        const response = await api.get("classes", {
            params: {
                subject,
                week_day,
                time,
            },
        });

        setTeachers(response.data);
    }

    return (
        <div id="page-teacher-list" className="container">
            <PageHeader title="Estes são os proffys disponíveis!">
                <form id="search-teachers" onSubmit={searchTeachers}>
                    <Select
                        name="subject"
                        label="Matéria"
                        value={subject}
                        onChange={(e) => {
                            setSubject(e.target.value);
                        }}


async function searchTeachers(e: FormEvent) {
        e.preventDefault();

        const response = await api.get("classes", {
            params: {
                subject,
                week_day,
                time,
            },
        });

        setTeachers(response.data);
    }


(teacher: Teacher) => {
                    return <TeacherItem key={teacher.id} teacher={teacher} />;
                }


/* tslint:disable:jsx-no-multiline-js jsx-no-lambda no-string-literal */
export class AppGridPage extends MapComponent<IAppGridPageProps, IAppGridPageState> {
    constructor(props: IAppGridPageProps, context?: any) {
        super(props, context);

        this.state = {
            hidden: false
        };
    }

    render() {
        return (

                        <Button type="default">
                            <Icon type="left" style={{ color: 'rgb(228, 228, 228)' }}


// tslint:disable-next-line:no-empty-interface
export interface IAppGridPageProps extends IBaseProps {
}


// tslint:disable-next-line:no-empty-interface
export interface IAppGridPageState extends IBaseState {
}


render() {
        return (

                        <Button type="default">
                            <Icon type="left" style={{ color: 'rgb(228, 228, 228)' }}


@Injectable({ providedIn: 'root' })
export class NgLodgingsDoorwaysEpics extends RecordEpicsBase<LodgingDoorway, LodgingDoorwayKey> {
    constructor(
        protected requests: NgLodgingsDoorwaysRequests,
        protected notifications: NgLodgingsDoorwaysNotifications,
        private lodgingsStore: NgLodgingsStore,
        private lodgingsActions: NgLodgingsActions,
        private doorwaysStore: NgDoorwaysStore,
        private doorwaysActions: NgDoorwaysActions,
        private skysmackStore: NgSkysmackStore
    ) {
        super(requests, LODGINGS_DOORWAYS_REDUX_KEY, notifications);

        this.epics = this.epics.concat([
            ...getReadDependencies({
                prefix: LODGINGS_DOORWAYS_REDUX_KEY,
                relationIdSelector: 'lodgingId',
                rsqlIdSelector: 'id',
                skysmackStore: this.skysmackStore,
                store: this.lodgingsStore,
                actions: this.lodgingsActions,
                dependencyIndexes: [0]
            }),
            ...getReadDependencies({
                prefix: LODGINGS_DOORWAYS_REDUX_KEY,
                relationIdSelector: 'doorwayId',
                rsqlIdSelector: 'id',
                skysmackStore: this.skysmackStore,
                store: this.doorwaysStore,
                actions: this.doorwaysActions,
                dependencyIndexes: [1]
            })
        ]);
    }
}


async () => {
                    await this.modelToViewModel(model, viewModel, bindingContext);
                    this.eventManager.dispatchEvent("onContentUpdate", model.key.replace("files/", "popups/"));
                }


export class PopupViewModelBinder implements ViewModelBinder<PopupModel, PopupViewModel> {
    constructor(
        private readonly viewModelBinderSelector: ViewModelBinderSelector,
        private readonly eventManager: EventManager,
        private readonly styleCompiler: StyleCompiler
    ) { }

    public async modelToViewModel(model: PopupModel, viewModel?: PopupViewModel, bindingContext?: Bag<any>): Promise<PopupViewModel> {
        if (!viewModel) {
            viewModel = new PopupViewModel();
        }

        const widgetViewModels = [];

        for (const widgetModel of model.widgets) {
            const widgetViewModelBinder = this.viewModelBinderSelector.getViewModelBinderByModel(widgetModel);

            if (widgetViewModelBinder.createWidgetBinding) {
                const binding = await widgetViewModelBinder.createWidgetBinding<any>(widgetModel, bindingContext);
                widgetViewModels.push(binding);
            }
            else {
                const widgetViewModel = await widgetViewModelBinder.modelToViewModel(widgetModel, null, bindingContext);
                widgetViewModels.push(widgetViewModel);
            }
        }

        if (widgetViewModels.length === 0) {
            widgetViewModels.push(new PlaceholderViewModel("Popup content"));
        }

        if (model.styles) {
            viewModel.styles(await this.styleCompiler.getStyleModelAsync(model.styles, bindingContext?.styleManager));
        }

        viewModel.identifier(model.key.replace("files/", "popups"));
        viewModel.widgets(widgetViewModels);
        viewModel.backdrop(model.backdrop);

        if (!viewModel["widgetBinding"]) {
            const binding: IWidgetBinding<PopupModel, PopupViewModel> = {
                name: "popup",
                displayName: "Popup",
                readonly: bindingContext ? bindingContext.readonly : false,
                flow: "block",
                model: model,
                draggable: true,
                editor: "popup-editor",
                handler: PopupHandlers,
                applyChanges: async () => {
                    await this.modelToViewModel(model, viewModel, bindingContext);
                    this.eventManager.dispatchEvent("onContentUpdate", model.key.replace("files/", "popups/"));
                }
            };

            viewModel["widgetBinding"] = binding;
        }

        return viewModel;
    }

    public canHandleModel(model: PopupModel): boolean {
        return model instanceof PopupModel;
    }
}


public async modelToViewModel(model: PopupModel, viewModel?: PopupViewModel, bindingContext?: Bag<any>): Promise<PopupViewModel> {
        if (!viewModel) {
            viewModel = new PopupViewModel();
        }

        const widgetViewModels = [];

        for (const widgetModel of model.widgets) {
            const widgetViewModelBinder = this.viewModelBinderSelector.getViewModelBinderByModel(widgetModel);

            if (widgetViewModelBinder.createWidgetBinding) {
                const binding = await widgetViewModelBinder.createWidgetBinding<any>(widgetModel, bindingContext);
                widgetViewModels.push(binding);
            }
            else {
                const widgetViewModel = await widgetViewModelBinder.modelToViewModel(widgetModel, null, bindingContext);
                widgetViewModels.push(widgetViewModel);
            }
        }

        if (widgetViewModels.length === 0) {
            widgetViewModels.push(new PlaceholderViewModel("Popup content"));
        }

        if (model.styles) {
            viewModel.styles(await this.styleCompiler.getStyleModelAsync(model.styles, bindingContext?.styleManager));
        }

        viewModel.identifier(model.key.replace("files/", "popups"));
        viewModel.widgets(widgetViewModels);
        viewModel.backdrop(model.backdrop);

        if (!viewModel["widgetBinding"]) {
            const binding: IWidgetBinding<PopupModel, PopupViewModel> = {
                name: "popup",
                displayName: "Popup",
                readonly: bindingContext ? bindingContext.readonly : false,
                flow: "block",
                model: model,
                draggable: true,
                editor: "popup-editor",
                handler: PopupHandlers,
                applyChanges: async () => {
                    await this.modelToViewModel(model, viewModel, bindingContext);
                    this.eventManager.dispatchEvent("onContentUpdate", model.key.replace("files/", "popups/"));
                }
            };

            viewModel["widgetBinding"] = binding;
        }

        return viewModel;
    }


public canHandleModel(model: PopupModel): boolean {
        return model instanceof PopupModel;
    }


// Type definitions for dogapi 2.8
// Project: https://github.com/brettlangdon/node-dogapi#readme
// Definitions by: olebedev <https://github.com/olebedev>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 3.2
export function initialize(opts: { api_key: string; app_key: string; api_host?: string | undefined }): void;


interface event {
    create(title: string, text: string, callback: (err: Error | null, res: EventCreateResponse) => void): void;
    create(
        title: string,
        text: string,
        properties: {
            date_happened?: number | undefined;
            priority?: 'normal' | 'low' | undefined;
            host?: string | undefined;
            tags?: ReadonlyArray<string> | undefined;
            alert_type?: 'error' | 'warning' | 'info' | 'success' | undefined;
            aggregation_key?: string | undefined;
            source_type_name?:
                | 'nagios'
                | 'hudson'
                | 'jenkins'
                | 'user'
                | 'my apps'
                | 'feed'
                | 'chef'
                | 'puppet'
                | 'git'
                | 'bitbucket'
                | 'fabric'
                | 'capistrano' | undefined;
        },
        callback: (err: Error | null, res: EventCreateResponse) => void,
    ): void;
}


interface metric {
    send(metric: string, points: number | number[], callback: (err: Error | null, res: 'ok') => void): void;
    send(
        metric: string,
        points: number | number[],
        extra: {
            type?: 'gauge' | 'rate' | 'count' | undefined;
            metric_type?: 'gauge' | 'count' | undefined;
            host?: string | undefined;
            tags?: ReadonlyArray<string> | undefined;
        },
        callback: (err: Error | null, res: 'ok') => void,
    ): void;
    send_all(
        metrics: Array<{
            metric: string;
            points: number | number[] | Array<[string, number]>;
            tags?: string[] | undefined;
            type?: string | undefined;
            metric_type?: string | undefined;
        }>,
        callback: (err: Error | null, res: EventCreateResponse) => void,
    ): void;
}


export interface EventCreateResponse {
    ok: boolean;
    event: {
        date_happened: number;
        handle: any;
        id: bigint;
        priority: 'normal' | 'low';
        related_event_id: number | null;
        tags: ReadonlyArray<string>;
        text: string;
        title: string;
        url: string;
    };
    status: 'ok';
}


/**
 * Flattens an array.
 * Use this function to keep support for node 10
 * @param array
 */
declare function arrayFlat<T>(array: T[][]): T[];


/**
 * Filters an array returning only defined items
 * @param array
 */
declare function arrayDefined<T>(array: (T | undefined)[]): T[];


function getId(manifest: IExtensionManifest, withVersion?: boolean): string {
	if (withVersion) {
		return `${manifest.publisher}.${manifest.name}@${manifest.version}`;
	} else {
		return `${manifest.publisher}.${manifest.name}`;
	}
}


export function getIdAndVersion(id: string): [string, string | undefined] {
	const matches = EXTENSION_ID_REGEX.exec(id);
	if (matches && matches[1]) {
		return [adoptToGalleryExtensionId(matches[1]), matches[2]];
	}
	return [adoptToGalleryExtensionId(id), undefined];
}


async function getExtensionId(extensionDescription: string): Promise<string> {
			if (!/\.vsix$/i.test(extensionDescription)) {
				return extensionDescription;
			}

			const zipPath = path.isAbsolute(extensionDescription) ? extensionDescription : path.join(process.cwd(), extensionDescription);
			const manifest = await getManifest(zipPath);
			return getId(manifest);
		}


export async function main(argv: NativeParsedArgs): Promise<void> {
	const services = new ServiceCollection();
	const disposables = new DisposableStore();

	const environmentService = new NativeEnvironmentService(argv);
	const logService: ILogService = new SpdLogService('cli', environmentService.logsPath, getLogLevel(environmentService));
	process.once('exit', () => logService.dispose());
	logService.info('main', argv);

	await Promise.all<void | undefined>([environmentService.appSettingsHome.fsPath, environmentService.extensionsPath]
		.map((path): undefined | Promise<void> => path ? mkdirp(path) : undefined));

	// Files
	const fileService = new FileService(logService);
	disposables.add(fileService);
	services.set(IFileService, fileService);

	const diskFileSystemProvider = new DiskFileSystemProvider(logService);
	disposables.add(diskFileSystemProvider);
	fileService.registerProvider(Schemas.file, diskFileSystemProvider);

	const configurationService = new ConfigurationService(environmentService.settingsResource, fileService);
	disposables.add(configurationService);
	await configurationService.initialize();

	services.set(IEnvironmentService, environmentService);
	services.set(INativeEnvironmentService, environmentService);

	services.set(ILogService, logService);
	services.set(IConfigurationService, configurationService);
	services.set(IStateService, new SyncDescriptor(StateService));
	services.set(IProductService, { _serviceBrand: undefined, ...product });

	const instantiationService: IInstantiationService = new InstantiationService(services);

	return instantiationService.invokeFunction(async accessor => {
		const stateService = accessor.get(IStateService);

		const { appRoot, extensionsPath, extensionDevelopmentLocationURI, isBuilt, installSourcePath } = environmentService;

		const services = new ServiceCollection();
		services.set(IRequestService, new SyncDescriptor(RequestService));
		services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService));
		services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService));

		const appenders: AppInsightsAppender[] = [];
		if (isBuilt && !extensionDevelopmentLocationURI && !environmentService.disableTelemetry && product.enableTelemetry) {
			if (product.aiConfig && product.aiConfig.asimovKey) {
				appenders.push(new AppInsightsAppender(eventPrefix, null, product.aiConfig.asimovKey));
			}

			const config: ITelemetryServiceConfig = {
				appender: combinedAppender(...appenders),
				sendErrorTelemetry: false,
				commonProperties: resolveCommonProperties(product.commit, product.version, stateService.getItem('telemetry.machineId'), product.msftInternalDomains, installSourcePath),
				piiPaths: extensionsPath ? [appRoot, extensionsPath] : [appRoot]
			};

			services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));

		} else {
			services.set(ITelemetryService, NullTelemetryService);
		}

		const instantiationService2 = instantiationService.createChild(services);
		const main = instantiationService2.createInstance(Main);

		try {
			await main.run(argv);

			// Flush the remaining data in AI adapter.
			// If it does not complete in 1 second, exit the process.
			await raceTimeout(combinedAppender(...appenders).flush(), 1000);
		} finally {
			disposables.dispose();
		}
	});
}


(id: string) => localize('notFound', "Extension '{0}' not found.", id)


(id: string) => localize('notInstalled', "Extension '{0}' is not installed.", id)


c => c.toLowerCase()


e => {
				if (e.manifest.categories) {
					const lowerCaseCategories: string[] = e.manifest.categories.map(c => c.toLowerCase());
					return lowerCaseCategories.indexOf(category.toLowerCase()) > -1;
				}
				return false;
			}


category => {
				console.log(category);
			}


e => console.log(getId(e.manifest, showVersions))


async vsix => {
				try {
					const manifest = await this.installVSIX(vsix, force);
					if (manifest) {
						installedExtensionsManifests.push(manifest);
					}
				} catch (err) {
					console.error(err.message || err.stack || err);
					failed.push(vsix);
				}
			}


async extensionInfo => {
				const gallery = galleryExtensions.get(extensionInfo.id.toLowerCase());
				if (gallery) {
					try {
						const manifest = await this.installFromGallery(extensionInfo, gallery, installed, force);
						if (manifest) {
							installedExtensionsManifests.push(manifest);
						}
					} catch (err) {
						console.error(err.message || err.stack || err);
						failed.push(extensionInfo.id);
					}
				} else {
					console.error(`${notFound(extensionInfo.version ? `${extensionInfo.id}@${extensionInfo.version}` : extensionInfo.id)}\n${useId}`);
					failed.push(extensionInfo.id);
				}
			}


manifest => isLanguagePackExtension(manifest)


({ version }) => version === undefined


({ version }) => version !== undefined


async () => {
				const result = await this.extensionGalleryService.getExtensions(extensionIds, CancellationToken.None);
				result.forEach(extension => galleryExtensions.set(extension.identifier.id.toLowerCase(), extension));
			}


extension => galleryExtensions.set(extension.identifier.id.toLowerCase(), extension)


async ({ id, version }) => {
				const extension = await this.extensionGalleryService.getCompatibleExtension({ id }, version);
				if (extension) {
					galleryExtensions.set(extension.identifier.id.toLowerCase(), extension);
				}
			}


e => areSameExtensions(e.identifier, galleryExtension.identifier)


local => areSameExtensions(extensionIdentifier, local.identifier) && semver.gt(local.manifest.version, manifest.version)


e => areSameExtensions(e.identifier, { id })


e => isLanguagePackExtension(e.manifest)


e => {
			installed.forEach(i => {
				if (i.identifier.id === e) {
					if (i.location.scheme === Schemas.file) {
						console.log(i.location.fsPath);
						return;
					}
				}
			});
		}


i => {
				if (i.identifier.id === e) {
					if (i.location.scheme === Schemas.file) {
						console.log(i.location.fsPath);
						return;
					}
				}
			}


() => logService.dispose()


(path): undefined | Promise<void> => path ? mkdirp(path) : undefined


async accessor => {
		const stateService = accessor.get(IStateService);

		const { appRoot, extensionsPath, extensionDevelopmentLocationURI, isBuilt, installSourcePath } = environmentService;

		const services = new ServiceCollection();
		services.set(IRequestService, new SyncDescriptor(RequestService));
		services.set(IExtensionManagementService, new SyncDescriptor(ExtensionManagementService));
		services.set(IExtensionGalleryService, new SyncDescriptor(ExtensionGalleryService));

		const appenders: AppInsightsAppender[] = [];
		if (isBuilt && !extensionDevelopmentLocationURI && !environmentService.disableTelemetry && product.enableTelemetry) {
			if (product.aiConfig && product.aiConfig.asimovKey) {
				appenders.push(new AppInsightsAppender(eventPrefix, null, product.aiConfig.asimovKey));
			}

			const config: ITelemetryServiceConfig = {
				appender: combinedAppender(...appenders),
				sendErrorTelemetry: false,
				commonProperties: resolveCommonProperties(product.commit, product.version, stateService.getItem('telemetry.machineId'), product.msftInternalDomains, installSourcePath),
				piiPaths: extensionsPath ? [appRoot, extensionsPath] : [appRoot]
			};

			services.set(ITelemetryService, new SyncDescriptor(TelemetryService, [config]));

		} else {
			services.set(ITelemetryService, NullTelemetryService);
		}

		const instantiationService2 = instantiationService.createChild(services);
		const main = instantiationService2.createInstance(Main);

		try {
			await main.run(argv);

			// Flush the remaining data in AI adapter.
			// If it does not complete in 1 second, exit the process.
			await raceTimeout(combinedAppender(...appenders).flush(), 1000);
		} finally {
			disposables.dispose();
		}
	}


type InstallExtensionInfo = { id: string, version?: string, installOptions: InstallOptions };


async run(argv: NativeParsedArgs): Promise<void> {
		if (argv['install-source']) {
			await this.setInstallSource(argv['install-source']);
		} else if (argv['list-extensions']) {
			await this.listExtensions(!!argv['show-versions'], argv['category']);
		} else if (argv['install-extension'] || argv['install-builtin-extension']) {
			await this.installExtensions(argv['install-extension'] || [], argv['install-builtin-extension'] || [], !!argv['do-not-sync'], !!argv['force']);
		} else if (argv['uninstall-extension']) {
			await this.uninstallExtension(argv['uninstall-extension'], !!argv['force']);
		} else if (argv['locate-extension']) {
			await this.locateExtension(argv['locate-extension']);
		} else if (argv['telemetry']) {
			console.log(buildTelemetryMessage(this.environmentService.appRoot, this.environmentService.extensionsPath ? this.environmentService.extensionsPath : undefined));
		}
	}


private setInstallSource(installSource: string): Promise<void> {
		return writeFile(this.environmentService.installSourcePath, installSource.slice(0, 30));
	}


private async listExtensions(showVersions: boolean, category?: string): Promise<void> {
		let extensions = await this.extensionManagementService.getInstalled(ExtensionType.User);
		const categories = EXTENSION_CATEGORIES.map(c => c.toLowerCase());
		if (category && category !== '') {
			if (categories.indexOf(category.toLowerCase()) < 0) {
				console.log('Invalid category please enter a valid category. To list valid categories run --category without a category specified');
				return;
			}
			extensions = extensions.filter(e => {
				if (e.manifest.categories) {
					const lowerCaseCategories: string[] = e.manifest.categories.map(c => c.toLowerCase());
					return lowerCaseCategories.indexOf(category.toLowerCase()) > -1;
				}
				return false;
			});
		} else if (category === '') {
			console.log('Possible Categories: ');
			categories.forEach(category => {
				console.log(category);
			});
			return;
		}
		extensions.forEach(e => console.log(getId(e.manifest, showVersions)));
	}


private async installExtensions(extensions: string[], builtinExtensionIds: string[], isMachineScoped: boolean, force: boolean): Promise<void> {
		const failed: string[] = [];
		const installedExtensionsManifests: IExtensionManifest[] = [];
		if (extensions.length) {
			console.log(localize('installingExtensions', "Installing extensions..."));
		}

		const vsixs: string[] = [];
		const installExtensionInfos: InstallExtensionInfo[] = [];
		for (const extension of extensions) {
			if (/\.vsix$/i.test(extension)) {
				vsixs.push(extension);
			} else {
				const [id, version] = getIdAndVersion(extension);
				installExtensionInfos.push({ id, version, installOptions: { isBuiltin: false, isMachineScoped } });
			}
		}
		for (const extension of builtinExtensionIds) {
			const [id, version] = getIdAndVersion(extension);
			installExtensionInfos.push({ id, version, installOptions: { isBuiltin: true, isMachineScoped: false } });
		}

		if (vsixs.length) {
			await Promise.all(vsixs.map(async vsix => {
				try {
					const manifest = await this.installVSIX(vsix, force);
					if (manifest) {
						installedExtensionsManifests.push(manifest);
					}
				} catch (err) {
					console.error(err.message || err.stack || err);
					failed.push(vsix);
				}
			}));
		}

		if (installExtensionInfos.length) {

			const [galleryExtensions, installed] = await Promise.all([
				this.getGalleryExtensions(installExtensionInfos),
				this.extensionManagementService.getInstalled(ExtensionType.User)
			]);

			await Promise.all(installExtensionInfos.map(async extensionInfo => {
				const gallery = galleryExtensions.get(extensionInfo.id.toLowerCase());
				if (gallery) {
					try {
						const manifest = await this.installFromGallery(extensionInfo, gallery, installed, force);
						if (manifest) {
							installedExtensionsManifests.push(manifest);
						}
					} catch (err) {
						console.error(err.message || err.stack || err);
						failed.push(extensionInfo.id);
					}
				} else {
					console.error(`${notFound(extensionInfo.version ? `${extensionInfo.id}@${extensionInfo.version}` : extensionInfo.id)}\n${useId}`);
					failed.push(extensionInfo.id);
				}
			}));

		}

		if (installedExtensionsManifests.some(manifest => isLanguagePackExtension(manifest))) {
			await this.updateLocalizationsCache();
		}

		if (failed.length) {
			throw new Error(localize('installation failed', "Failed Installing Extensions: {0}", failed.join(', ')));
		}
	}


private async installVSIX(vsix: string, force: boolean): Promise<IExtensionManifest | null> {
		vsix = path.isAbsolute(vsix) ? vsix : path.join(process.cwd(), vsix);
		const manifest = await getManifest(vsix);
		const valid = await this.validate(manifest, force);
		if (valid) {
			try {
				await this.extensionManagementService.install(URI.file(vsix));
				console.log(localize('successVsixInstall', "Extension '{0}' was successfully installed.", getBaseLabel(vsix)));
				return manifest;
			} catch (error) {
				if (isPromiseCanceledError(error)) {
					console.log(localize('cancelVsixInstall', "Cancelled installing extension '{0}'.", getBaseLabel(vsix)));
					return null;
				} else {
					throw error;
				}
			}
		}
		return null;
	}


private async getGalleryExtensions(extensions: InstallExtensionInfo[]): Promise<Map<string, IGalleryExtension>> {
		const extensionIds = extensions.filter(({ version }) => version === undefined).map(({ id }) => id);
		const extensionsWithIdAndVersion = extensions.filter(({ version }) => version !== undefined);

		const galleryExtensions = new Map<string, IGalleryExtension>();
		await Promise.all([
			(async () => {
				const result = await this.extensionGalleryService.getExtensions(extensionIds, CancellationToken.None);
				result.forEach(extension => galleryExtensions.set(extension.identifier.id.toLowerCase(), extension));
			})(),
			Promise.all(extensionsWithIdAndVersion.map(async ({ id, version }) => {
				const extension = await this.extensionGalleryService.getCompatibleExtension({ id }, version);
				if (extension) {
					galleryExtensions.set(extension.identifier.id.toLowerCase(), extension);
				}
			}))
		]);

		return galleryExtensions;
	}


private async installFromGallery({ id, version, installOptions }: InstallExtensionInfo, galleryExtension: IGalleryExtension, installed: ILocalExtension[], force: boolean): Promise<IExtensionManifest | null> {
		const manifest = await this.extensionGalleryService.getManifest(galleryExtension, CancellationToken.None);
		const installedExtension = installed.find(e => areSameExtensions(e.identifier, galleryExtension.identifier));
		if (installedExtension) {
			if (galleryExtension.version === installedExtension.manifest.version) {
				console.log(localize('alreadyInstalled', "Extension '{0}' is already installed.", version ? `${id}@${version}` : id));
				return null;
			}
			if (!version && !force) {
				console.log(localize('forceUpdate', "Extension '{0}' v{1} is already installed, but a newer version {2} is available in the marketplace. Use '--force' option to update to newer version.", id, installedExtension.manifest.version, galleryExtension.version));
				return null;
			}
			console.log(localize('updateMessage', "Updating the extension '{0}' to the version {1}", id, galleryExtension.version));
		}

		try {
			if (installOptions.isBuiltin) {
				console.log(localize('installing builtin ', "Installing builtin extension '{0}' v{1}...", id, galleryExtension.version));
			} else {
				console.log(localize('installing', "Installing extension '{0}' v{1}...", id, galleryExtension.version));
			}
			await this.extensionManagementService.installFromGallery(galleryExtension, installOptions);
			console.log(localize('successInstall', "Extension '{0}' v{1} was successfully installed.", id, galleryExtension.version));
			return manifest;
		} catch (error) {
			if (isPromiseCanceledError(error)) {
				console.log(localize('cancelInstall', "Cancelled installing extension '{0}'.", id));
				return null;
			} else {
				throw error;
			}
		}
	}


private async validate(manifest: IExtensionManifest, force: boolean): Promise<boolean> {
		if (!manifest) {
			throw new Error('Invalid vsix');
		}

		const extensionIdentifier = { id: getGalleryExtensionId(manifest.publisher, manifest.name) };
		const installedExtensions = await this.extensionManagementService.getInstalled(ExtensionType.User);
		const newer = installedExtensions.find(local => areSameExtensions(extensionIdentifier, local.identifier) && semver.gt(local.manifest.version, manifest.version));

		if (newer && !force) {
			console.log(localize('forceDowngrade', "A newer version of extension '{0}' v{1} is already installed. Use '--force' option to downgrade to older version.", newer.identifier.id, newer.manifest.version, manifest.version));
			return false;
		}

		return true;
	}


private async uninstallExtension(extensions: string[], force: boolean): Promise<void> {
		async function getExtensionId(extensionDescription: string): Promise<string> {
			if (!/\.vsix$/i.test(extensionDescription)) {
				return extensionDescription;
			}

			const zipPath = path.isAbsolute(extensionDescription) ? extensionDescription : path.join(process.cwd(), extensionDescription);
			const manifest = await getManifest(zipPath);
			return getId(manifest);
		}

		const uninstalledExtensions: ILocalExtension[] = [];
		for (const extension of extensions) {
			const id = await getExtensionId(extension);
			const installed = await this.extensionManagementService.getInstalled();
			const extensionToUninstall = installed.find(e => areSameExtensions(e.identifier, { id }));
			if (!extensionToUninstall) {
				throw new Error(`${notInstalled(id)}\n${useId}`);
			}
			if (extensionToUninstall.type === ExtensionType.System) {
				console.log(localize('builtin', "Extension '{0}' is a Built-in extension and cannot be installed", id));
				return;
			}
			if (extensionToUninstall.isBuiltin && !force) {
				console.log(localize('forceUninstall', "Extension '{0}' is marked as a Built-in extension by user. Please use '--force' option to uninstall it.", id));
				return;
			}
			console.log(localize('uninstalling', "Uninstalling {0}...", id));
			await this.extensionManagementService.uninstall(extensionToUninstall, true);
			uninstalledExtensions.push(extensionToUninstall);
			console.log(localize('successUninstall', "Extension '{0}' was successfully uninstalled!", id));
		}

		if (uninstalledExtensions.some(e => isLanguagePackExtension(e.manifest))) {
			await this.updateLocalizationsCache();
		}
	}


private async locateExtension(extensions: string[]): Promise<void> {
		const installed = await this.extensionManagementService.getInstalled();
		extensions.forEach(e => {
			installed.forEach(i => {
				if (i.identifier.id === e) {
					if (i.location.scheme === Schemas.file) {
						console.log(i.location.fsPath);
						return;
					}
				}
			});
		});
	}


private async updateLocalizationsCache(): Promise<void> {
		const localizationService = this.instantiationService.createInstance(LocalizationsService);
		await localizationService.update();
		localizationService.dispose();
	}


export function GroupBox({ children }: GroupBoxProps): JSX.Element {
    return (
        <Box bg="background.800" p="5" borderRadius="4px" minWidth="280px">
            {children}
        </Box>
    )
}


export type GroupBoxProps = {
    children: JSX.Element[]
}


(newVersion: RuntimeExtensionMajorVersions, oldVersion: RuntimeExtensionMajorVersions | null) => {
  if (oldVersion === RuntimeExtensionMajorVersions.custom || newVersion === RuntimeExtensionMajorVersions.custom) {
    // If the user is setting a customer version, we assume they know what they're doing.
    return true;
  }

  switch (oldVersion) {
    case RuntimeExtensionMajorVersions.v1:
      // For V1, changing major versions is not supported.
      return newVersion === RuntimeExtensionMajorVersions.v1;
    case RuntimeExtensionMajorVersions.v2:
    case RuntimeExtensionMajorVersions.v3:
      // For V2 and V3, switching between V2 and V3 is supported.
      return newVersion === RuntimeExtensionMajorVersions.v2 || newVersion === RuntimeExtensionMajorVersions.v3;
    case null:
      return true;
    default:
      return false;
  }
}


(): string => {
    if (waitingOnFunctionsApi && !hasCustomRuntimeVersion) {
      return t('loading');
    }

    if (failedToGetFunctions) {
      return t('loadingFailed');
    }

    return '';
  }


() => {
    let runtimeVersionInUse: RuntimeExtensionMajorVersions | null = null;

    if (
      asyncData.functionsHostStatus.loadingState === LoadingStates.complete &&
      asyncData.functionsHostStatus.value &&
      asyncData.functionsHostStatus.value.properties.state !== HostStates.error
    ) {
      // Try to get the current running major version from the result of the host status call.
      runtimeVersionInUse = FunctionsRuntimeVersionHelper.parseExactRuntimeVersion(asyncData.functionsHostStatus.value!.properties.version);
    }

    if (!runtimeVersionInUse) {
      // We weren't able to determine the major version because the host status call failed or returned a null/invalid value.
      // Try to get the intended major version based off of the FUNCTIONS_EXTENSION_VERSION value configured
      runtimeVersionInUse = FunctionsRuntimeVersionHelper.parseConfiguredRuntimeVersion(initialRuntimeVersion);
    }

    return runtimeVersionInUse;
  }


() => {
    return initialRuntimeMajorVersion !== RuntimeExtensionMajorVersions.v2;
  }


(): IDropdownOption[] => {
    if (hasCustomRuntimeVersion) {
      // NOTE(shimedh): When we move to using stacks API, this should be driven by the versions supported by a particular stack.
      if (shouldEnableForV4) {
        return [
          {
            key: RuntimeExtensionMajorVersions.v3,
            text: RuntimeExtensionMajorVersions.v3,
          },
          {
            key: RuntimeExtensionMajorVersions.custom,
            text: RuntimeExtensionMajorVersions.v4,
          },
        ];
      } else {
        return [
          {
            key: RuntimeExtensionMajorVersions.custom,
            text: runtimeVersion === RuntimeExtensionMajorVersions.v4 ? RuntimeExtensionMajorVersions.v4 : t('custom'),
          },
        ];
      }
    }

    return [
      {
        key: RuntimeExtensionMajorVersions.v1,
        text: RuntimeExtensionMajorVersions.v1,
        disabled: isLinuxApp(values.site),
      },
      {
        key: RuntimeExtensionMajorVersions.v2,
        text: RuntimeExtensionMajorVersions.v2,
        hidden: isV2Hidden(),
      },
      {
        key: RuntimeExtensionMajorVersions.v3,
        text: RuntimeExtensionMajorVersions.v3,
      },
    ];
  }


(): boolean => waitingOnFunctionsApi || failedToGetFunctions || (hasCustomRuntimeVersion && !shouldEnableForV4)


version => {
    switch (version) {
      case RuntimeExtensionMajorVersions.v2:
        return CommonConstants.NodeVersions.v2;
      case RuntimeExtensionMajorVersions.v3:
        return CommonConstants.NodeVersions.v3;
      default:
        return CommonConstants.NodeVersions.default;
    }
  }


(newVersion: RuntimeExtensionMajorVersions) =>
    hasFunctions && !isVersionChangeSafe(newVersion, getRuntimeVersionInUse())


(newVersion: RuntimeExtensionMajorVersions) => {
    setMovingFromV2Warning(undefined);
    if (isExistingFunctionsWarningNeeded(newVersion)) {
      setPendingVersion(newVersion);
    } else {
      if (newVersion === RuntimeExtensionMajorVersions.v3 && initialRuntimeMajorVersion === RuntimeExtensionMajorVersions.v2) {
        setMovingFromV2Warning(t('movingFromV2Warning'));
      }
      updateDropDownValue(newVersion);
    }
  }


() => {
    updateDropDownValue(pendingVersion!);
    setPendingVersion(undefined);
  }


() => {
    setPendingVersion(undefined);
  }


(newVersion: RuntimeExtensionMajorVersions) => {
    let appSettings: FormAppSetting[] = [...values.appSettings];

    // Remove AZUREJOBS_EXTENSION_VERSION app setting (if present)
    appSettings = removeFromAppSetting(values.appSettings, CommonConstants.AppSettingNames.azureJobsExtensionVersion);

    if (newVersion === RuntimeExtensionMajorVersions.v1) {
      // If functions extension version is V1, remove FUNCTIONS_WORKER_RUNTIME app setting (if present)
      appSettings = removeFromAppSetting(values.appSettings, CommonConstants.AppSettingNames.functionsWorkerRuntime);
    } else {
      // If functions extension version is not V1, restore the initial value for FUNCTIONS_WORKER_RUNTIME app setting (if present)
      const initialWorkerRuntime = findFormAppSettingValue(
        initialValues.appSettings,
        CommonConstants.AppSettingNames.functionsWorkerRuntime
      );
      if (initialWorkerRuntime) {
        appSettings = addOrUpdateFormAppSetting(
          values.appSettings,
          CommonConstants.AppSettingNames.functionsWorkerRuntime,
          initialWorkerRuntime
        );
      }
    }

    // Add or update WEBSITE_NODE_DEFAULT_VERSION app setting
    const nodeVersion = getNodeVersionForRuntime(newVersion);
    appSettings = addOrUpdateFormAppSetting(values.appSettings, CommonConstants.AppSettingNames.websiteNodeDefaultVersion, nodeVersion);

    // Add or update FUNCTIONS_EXTENSION_VERSION app setting
    // NOTE(shimedh): We need to make sure the version is set to ~4 instead of custom for all enabled cases so that the dropdown is not disabled after change.
    if (shouldEnableForV4 && newVersion === RuntimeExtensionMajorVersions.custom) {
      newVersion = RuntimeExtensionMajorVersions.v4;
    }
    appSettings = addOrUpdateFormAppSetting(values.appSettings, CommonConstants.AppSettingNames.functionsExtensionVersion, newVersion);

    setFieldValue('appSettings', appSettings);
  }


() => {
    setMovingFromV2Warning(undefined);

    // eslint-disable-next-line react-hooks/exhaustive-deps
  }


t('functionsRuntimeVersionExistingFunctionsConfirmationTitle')


t('functionsRuntimeVersionExistingFunctionsConfirmationMessage')


getOptions()


t('runtimeVersion')


async (resolve,reject) => {
      let realFile = path.resolve(this.file)

      if (await Utils.fs.exists(realFile) || this.buffer != null) {
        try {

          let image = null;

          if (this.buffer != null) {
            image = sharp(this.buffer,{ density: 500 });
          } else {
            image = sharp(realFile,{ density: 500 });
          }

          const metadata:sharp.Metadata = await image.metadata().catch(err => reject(err)) as sharp.Metadata;

          if (metadata.format !== "svg") {
            if (metadata.width != metadata.height) {
              return reject('width resolution must equal as height.');
            }

            if (metadata.width < 128) {
              return reject('file resolution is too small; minimum 128x128; recommended 1024x1024.');
            }
          }

          await this.createBuffers(image);
          this.createIcns(resolve,reject);

        } catch (exception) {
          throw 'Error when processing the image ' + exception;
        }

      } else {
        throw 'File not found';
      }

    }


err => reject(err)


export class IconCreatorSharp extends IconCreator {
  private useBuffer: boolean = false;
  private buffers: Map<string,Buffer> = new Map<string,Buffer>();
  private output?: string;
  private manipulation: ManipulationCallback = null;

  constructor(file: string | Buffer, output?: string) {
    super(file,output);

    if (output) {
      this.output = path.resolve(output);
    } else {
      this.useBuffer = true;
    }
  }

  public setImageManipulation(callback:ManipulationCallback) {
    this.manipulation = callback;
  }

  public convert(): Promise<string | Buffer> {
    return new Promise<string>(async (resolve,reject) => {
      let realFile = path.resolve(this.file)

      if (await Utils.fs.exists(realFile) || this.buffer != null) {
        try {

          let image = null;

          if (this.buffer != null) {
            image = sharp(this.buffer,{ density: 500 });
          } else {
            image = sharp(realFile,{ density: 500 });
          }

          const metadata:sharp.Metadata = await image.metadata().catch(err => reject(err)) as sharp.Metadata;

          if (metadata.format !== "svg") {
            if (metadata.width != metadata.height) {
              return reject('width resolution must equal as height.');
            }

            if (metadata.width < 128) {
              return reject('file resolution is too small; minimum 128x128; recommended 1024x1024.');
            }
          }

          await this.createBuffers(image);
          this.createIcns(resolve,reject);

        } catch (exception) {
          throw 'Error when processing the image ' + exception;
        }

      } else {
        throw 'File not found';
      }

    });
  }

  private async createIcns(resolve, reject) {
    let writer = new IconWriterNative(this.buffers,this.output);

    const res = await writer.write().catch(error => reject(error));

    if (res instanceof Buffer) {
      resolve(res);
    } else {
      resolve(this.output);
    }
  }

  private swapChannels(data:Buffer): Buffer {
    for (let i = 0; i < data.length; i += 4) {

      let tmp0 = data[i];
      let tmp1 = data[i+1];
      let tmp2 = data[i+2];
      let tmp3 = data[i+3];

      data[i] = tmp3; //A
      data[i+1] = tmp0; //R
      data[i+2] = tmp1; //G
      data[i+3] = tmp2; //B
    }

    return data;
  }

  private async createBuffers(image:sharp.SharpInstance) {

    for (let desc of IconDescriptor.createDescriptors()) {
      let scaledImage = image.clone().resize(desc.size,desc.size);
      if (this.manipulation !== null) {
        this.manipulation(scaledImage,desc.size);
      }
      if (desc.tag == "16x16" || desc.tag === "16x16@2x") {
        let buffer = await scaledImage.raw().toBuffer().catch(() => {}) as Buffer;
        this.buffers.set(desc.tag,ImageRLE.encodeRLE(this.swapChannels(buffer)));
      } else {
        let buffer = await scaledImage.png().toBuffer().catch(() => {}) as Buffer;
        this.buffers.set(desc.tag,buffer);
      }

    }
  }
}


export type ManipulationCallback = (image:sharp.SharpInstance,size?:number) => void;


public setImageManipulation(callback:ManipulationCallback) {
    this.manipulation = callback;
  }


public convert(): Promise<string | Buffer> {
    return new Promise<string>(async (resolve,reject) => {
      let realFile = path.resolve(this.file)

      if (await Utils.fs.exists(realFile) || this.buffer != null) {
        try {

          let image = null;

          if (this.buffer != null) {
            image = sharp(this.buffer,{ density: 500 });
          } else {
            image = sharp(realFile,{ density: 500 });
          }

          const metadata:sharp.Metadata = await image.metadata().catch(err => reject(err)) as sharp.Metadata;

          if (metadata.format !== "svg") {
            if (metadata.width != metadata.height) {
              return reject('width resolution must equal as height.');
            }

            if (metadata.width < 128) {
              return reject('file resolution is too small; minimum 128x128; recommended 1024x1024.');
            }
          }

          await this.createBuffers(image);
          this.createIcns(resolve,reject);

        } catch (exception) {
          throw 'Error when processing the image ' + exception;
        }

      } else {
        throw 'File not found';
      }

    });
  }


private async createIcns(resolve, reject) {
    let writer = new IconWriterNative(this.buffers,this.output);

    const res = await writer.write().catch(error => reject(error));

    if (res instanceof Buffer) {
      resolve(res);
    } else {
      resolve(this.output);
    }
  }


private swapChannels(data:Buffer): Buffer {
    for (let i = 0; i < data.length; i += 4) {

      let tmp0 = data[i];
      let tmp1 = data[i+1];
      let tmp2 = data[i+2];
      let tmp3 = data[i+3];

      data[i] = tmp3; //A
      data[i+1] = tmp0; //R
      data[i+2] = tmp1; //G
      data[i+3] = tmp2; //B
    }

    return data;
  }


private async createBuffers(image:sharp.SharpInstance) {

    for (let desc of IconDescriptor.createDescriptors()) {
      let scaledImage = image.clone().resize(desc.size,desc.size);
      if (this.manipulation !== null) {
        this.manipulation(scaledImage,desc.size);
      }
      if (desc.tag == "16x16" || desc.tag === "16x16@2x") {
        let buffer = await scaledImage.raw().toBuffer().catch(() => {}) as Buffer;
        this.buffers.set(desc.tag,ImageRLE.encodeRLE(this.swapChannels(buffer)));
      } else {
        let buffer = await scaledImage.png().toBuffer().catch(() => {}) as Buffer;
        this.buffers.set(desc.tag,buffer);
      }

    }
  }


() => {
  let component: MyDashboardComponent;
  let fixture: ComponentFixture<MyDashboardComponent>;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [MyDashboardComponent],
    }).compileComponents();
  });

  beforeEach(() => {
    fixture = TestBed.createComponent(MyDashboardComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
}


async () => {
    await TestBed.configureTestingModule({
      declarations: [MyDashboardComponent],
    }).compileComponents();
  }


() => {
    fixture = TestBed.createComponent(MyDashboardComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  }


(value: any) => {
    if (!value) {
        return value;
    }
    let isArray = Array.isArray(value);
    const shouldBeArray = value instanceof Array === false && isArray;
    if (shouldBeArray) {
        value = Array.from(value as any);
        isArray = true;
    }
    if (typeof value === "object" || isArray) {
        for (const k in value) {
            value[k] = transformArray(value[k]);
        }
    }
    return value;
}


async ({ field, value: storageValue }) => {
        if (!storageValue) {
            return storageValue;
        } else if (typeof storageValue !== "object") {
            throw new WebinyError(
                `RichText value received in "fromStorage" function is not an object in field "${field.fieldId}".`
            );
        }
        /**
         * This is to circumvent a bug introduced with 5.8.0 storage operations.
         * Do not remove.
         */
        if (storageValue.hasOwnProperty("compression") === false) {
            return storageValue;
        }
        const { compression, value } = storageValue;
        if (!compression) {
            throw new WebinyError(
                `Missing compression in "fromStorage" function in field "${
                    field.fieldId
                }": ${JSON.stringify(storageValue)}.`,
                "MISSING_COMPRESSION",
                {
                    value: storageValue
                }
            );
        }
        if (compression !== "jsonpack") {
            throw new WebinyError(
                `This plugin cannot transform something not packed with "jsonpack".`,
                "WRONG_COMPRESSION",
                {
                    compression
                }
            );
        }
        try {
            return jsonpack.unpack(value);
        } catch {
            return null;
        }
    }


async ({ value }) => {
        /**
         * There is a possibility that we are trying to compress already compressed value.
         * Introduced a bug with 5.8.0 storage operations, so just return the value to correct it.
         */
        if (value && value.hasOwnProperty("compression") === true) {
            return value as any;
        }
        value = transformArray(value);
        return {
            compression: "jsonpack",
            value: value ? jsonpack.pack(value) : value
        };
    }


() => {
    return plugin;
}


({ className }: any) => (

                Terms &amp


({ className }: any) => (

        Terms &amp


(props: any) =>
  <div className


interface on


interface to


interface is


interface must


interface other


export function HistoryControllerTest() {
  describe('HistoryController', () => {
    let historyController: HistoryController;
    let env: Mock.IMockEnvironment;

    beforeEach(() => {
      env = new Mock.MockEnvironmentBuilder().withLiveQueryStateModel().build();
      historyController = new HistoryController(env.root, Mock.mockWindow(), env.queryStateModel, env.queryController, env.usageAnalytics);
    });

    afterEach(() => {
      historyController = null;
      env = null;
    });

    it('should set the query state model representation on all event in the hash', () => {
      env.queryStateModel.attributes = {
        a: 'a',
        b: 'b',
        c: 'notDefault',
        d: [1, 2, 3]
      };

      env.queryStateModel.defaultAttributes = {
        a: 'a',
        b: 'b',
        c: 'c',
        d: [2, 3, 4]
      };

      $$(historyController.element).trigger('state:all');
      Defer.flush();
      expect(historyController.window.location.hash).toBe('#c=notDefault&d=[1,2,3]');
    });

    it('should listen to hashchange event', () => {
      expect(historyController.window.addEventListener).toHaveBeenCalledWith('hashchange', jasmine.any(Function));
    });

    it('should not throw when history controller does not have an analytics client and there is a hash change', () => {
      historyController = new HistoryController(env.root, Mock.mockWindow(), env.queryStateModel, env.queryController);
      historyController.setHashValues({ q: 'test' });
      expect(historyController.handleHashChange.bind(historyController)).not.toThrow();
    });

    it('should not set the hash when it has not changed on the first hash change', () => {
      $$(historyController.element).trigger(InitializationEvents.restoreHistoryState);
      expect(historyController.window.location.replace).not.toHaveBeenCalled();
    });

    it('should not update the model hen simply replacing the state from an old value', () => {
      historyController = new HistoryController(env.root, Mock.mockWindow(), env.queryStateModel, env.queryController);
      spyOn(env.queryStateModel, 'setMultiple');
      historyController.replaceState({ q: 'bar' });
      expect(env.queryStateModel.setMultiple).not.toHaveBeenCalled();
    });

    describe('with a fake HashUtilsModule', () => {
      let fakeHashUtils;
      beforeEach(() => {
        fakeHashUtils = {} as any;
        fakeHashUtils.getValue = jasmine.createSpy('getValue');
        fakeHashUtils.getHash = jasmine.createSpy('getHash').and.callFake(() => Mock.mockWindow().location.hash);
        fakeHashUtils.encodeValues = jasmine.createSpy('encodeValues');
        historyController.hashUtils = fakeHashUtils;
      });

      it('keeps parsing hash values after one fails to parse', () => {
        let threwError = false;
        env.queryStateModel.attributes = {
          a: 1,
          b: 2,
          c: 3
        };

        const throwsAnError = () => {
          if (!threwError) {
            threwError = true;
            throw new Error();
          }
        };

        historyController.hashUtils.getValue = jasmine.createSpy('getValue').and.callFake(throwsAnError);

        $$(env.root).trigger(InitializationEvents.restoreHistoryState);

        expect(historyController.hashUtils.getValue).toHaveBeenCalledTimes(_.size(env.queryStateModel.attributes));
      });

      describe('when logging analytics event', () => {
        beforeEach(() => {
          historyController = new HistoryController(env.root, window, env.queryStateModel, env.queryController, env.usageAnalytics);
          historyController.hashUtils = fakeHashUtils;
          $$(historyController.element).trigger(InitializationEvents.restoreHistoryState);
        });

        afterEach(() => {
          window.location.hash = '';
        });

        const simulateHashModule = (key, value) => {
          historyController.hashUtils.getValue = jasmine.createSpy('getValue').and.callFake((valueNeeded: string) => {
            if (valueNeeded == key) {
              return value;
            }
            return undefined;
          });
        };

        const assertFacetAnalyticsCall = (cause: IAnalyticsActionCause) => {
          expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(cause, {
            facetId: '@foo',
            facetField: '@foo',
            facetTitle: '@foo',
            facetValue: 'bar'
          } as IAnalyticsFacetMeta);
        };

        it('should log an analytics event when q changes', () => {
          simulateHashModule('q', 'foo');
          window.dispatchEvent(new Event('hashchange'));
          expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(analyticsActionCauseList.searchboxSubmit, {});
        });

        it('should log an analytics event when sort changes', () => {
          simulateHashModule('sort', 'date ascending');
          window.dispatchEvent(new Event('hashchange'));
          expect(historyController.usageAnalytics.logSearchEvent).toHaveBeenCalledWith(analyticsActionCauseList.resultsSort, {
            resultsSortBy: 'date ascending'
          } as IAnalyticsResultsSortMeta);
        });

        it('should log an analytics event when a facet changes to select a value', () => {
          historyController.queryStateModel.registerNewAttribute('f:@foo', []);
          simulateHashModule('f:@foo', ['bar']);
          window.dispatchEvent(new Event('hashchange'));
          assertFacetAnalyticsCall(analyticsActionCauseList.facetSelect);
        });

        it('should log an analytics event when a facet changes to deselect a value', () => {
          historyController.queryStateModel.registerNewAttribute('f:@foo', []);
          simulateHashModule('f:@foo', ['bar']);
          window.dispatchEvent(new Event('hashchange'));
          simulateHashModule('f:@foo', []);
          window.dispatchEvent(new Event('hashchange'));
          assertFacetAnalyticsCall(analyticsActionCauseList.facetDeselect);
        });

        it('should log an analytics event when a facet changes to exclude a value', () => {
          historyController.queryStateModel.registerNewAttribute('f:@foo:not', []);
          simulateHashModule('f:@foo:not', ['bar']);
          window.dispatchEvent(new Event('hashchange'));
          assertFacetAnalyticsCall(analyticsActionCauseList.facetExclude);
        });

        it('should log an analytics event when a facet changes to unexclude a value', () => {
          historyController.queryStateModel.registerNewAttribute('f:@foo:not', []);
          simulateHashModule('f:@foo:not', ['bar']);
          window.dispatchEvent(new Event('hashchange'));
          simulateHashModule('f:@foo:not', []);
          window.dispatchEvent(new Event('hashchange'));
          assertFacetAnalyticsCall(analyticsActionCauseList.facetUnexclude);
        });
      });
    });
  });
}