How to use provider method in synthetixio-synpress

Best JavaScript code snippet using synthetixio-synpress

ValueProviderFactory.js

Source:ValueProviderFactory.js Github

copy

Full Screen

1///////////////////////////////////////////////////////////////////////////2// Copyright © 2014 - 2018 Esri. All Rights Reserved.3//4// Licensed under the Apache License Version 2.0 (the "License");5// you may not use this file except in compliance with the License.6// You may obtain a copy of the License at7//8// http://www.apache.org/licenses/LICENSE-2.09//10// Unless required by applicable law or agreed to in writing, software11// distributed under the License is distributed on an "AS IS" BASIS,12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13// See the License for the specific language governing permissions and14// limitations under the License.15///////////////////////////////////////////////////////////////////////////16define([17 'dojo/_base/lang',18 'dojo/_base/array',19 'dojo/_base/declare',20 './BlankValueProvider',21 './SimpleValueProvider',22 './TwoNumbersValueProvider',23 './TwoDatesValueProvider',24 './ListValueProvider',25 './AdvancedListValueProvider',26 './PredefinedValueProvider',27 './NumberListValueProvider',28 './DateIsInValueProvider',29 'jimu/utils',30 'jimu/LayerInfos/LayerInfos'31],32 function(lang, array, declare, BlankValueProvider, SimpleValueProvider, TwoNumbersValueProvider,33 TwoDatesValueProvider,34 ListValueProvider,35 AdvancedListValueProvider,36 PredefinedValueProvider,37 NumberListValueProvider, DateIsInValueProvider, jimuUtils, LayerInfos) {38 var BLANK_VALUE_PROVIDER = "BLANK_VALUE_PROVIDER";39 var SIMPLE_VALUE_PROVIDER = "SIMPLE_VALUE_PROVIDER";40 var TWO_NUMBERS_VALUE_PROVIDER = "TWO_NUMBERS_VALUE_PROVIDER";41 var TWO_DATES_VALUE_PROVIDER = "TWO_DATES_VALUE_PROVIDER";42 var LIST_VALUE_PROVIDER = "LIST_VALUE_PROVIDER";43 var NUMBER_LIST_VALUE_PROVIDER = "NUMBER_LIST_VALUE_PROVIDER";44 var DATE_IS_IN_VALUE_PROVIDER = "DATE_IS_IN_VALUE_PROVIDER";45 var ADVANCED_LIST_VALUE_PROVIDER = "ADVANCED_LIST_VALUE_PROVIDER";46 var UNIQUE_PREDEFINED_VALUE_PROVIDER = "UNIQUE_PREDEFINED_VALUE_PROVIDER";47 var MULTIPLE_PREDEFINED_VALUE_PROVIDER = "MULTIPLE_PREDEFINED_VALUE_PROVIDER";48 //operator + type => value provider49 var relationship = {50 //string51 stringOperatorIs: {52 value: {53 normalProviderType: SIMPLE_VALUE_PROVIDER,54 codedValueProviderType: LIST_VALUE_PROVIDER,55 supportAskForValue: true,56 supportCaseSensitive: true57 },58 field: {59 normalProviderType: LIST_VALUE_PROVIDER60 },61 unique: {62 normalProviderType: LIST_VALUE_PROVIDER,63 supportAskForValue: true,64 filterCodedValueIfPossible: true65 },66 uniquePredefined:{67 normalProviderType: UNIQUE_PREDEFINED_VALUE_PROVIDER,68 supportAskForValue: true,69 supportCaseSensitive: true70 }71 },72 stringOperatorIsNot: {73 value: {74 normalProviderType: SIMPLE_VALUE_PROVIDER,75 codedValueProviderType: LIST_VALUE_PROVIDER,76 supportAskForValue: true,77 supportCaseSensitive: true78 },79 field: {80 normalProviderType: LIST_VALUE_PROVIDER81 },82 unique: {83 normalProviderType: LIST_VALUE_PROVIDER,84 supportAskForValue: true,85 filterCodedValueIfPossible: true86 },87 uniquePredefined:{88 normalProviderType: UNIQUE_PREDEFINED_VALUE_PROVIDER,89 supportAskForValue: true,90 supportCaseSensitive: true91 }92 },93 stringOperatorStartsWith: {94 value: {95 normalProviderType: SIMPLE_VALUE_PROVIDER,96 supportAskForValue: true,97 supportCaseSensitive: true98 },99 values:{100 normalProviderType: SIMPLE_VALUE_PROVIDER101 },102 uniquePredefined:{103 normalProviderType: UNIQUE_PREDEFINED_VALUE_PROVIDER,104 supportAskForValue: true,105 supportCaseSensitive: true106 },107 multiplePredefined:{108 normalProviderType: MULTIPLE_PREDEFINED_VALUE_PROVIDER,109 supportAskForValue: true,110 supportCaseSensitive: true111 }112 },113 stringOperatorEndsWith: {114 value: {115 normalProviderType: SIMPLE_VALUE_PROVIDER,116 supportAskForValue: true,117 supportCaseSensitive: true118 },119 values:{120 normalProviderType: SIMPLE_VALUE_PROVIDER121 },122 uniquePredefined:{123 normalProviderType: UNIQUE_PREDEFINED_VALUE_PROVIDER,124 supportAskForValue: true,125 supportCaseSensitive: true126 },127 multiplePredefined:{128 normalProviderType: MULTIPLE_PREDEFINED_VALUE_PROVIDER,129 supportAskForValue: true,130 supportCaseSensitive: true131 }132 },133 stringOperatorContains: {134 value: {135 normalProviderType: SIMPLE_VALUE_PROVIDER,136 supportAskForValue: true,137 supportCaseSensitive: true138 },139 values:{140 normalProviderType: SIMPLE_VALUE_PROVIDER141 },142 uniquePredefined:{143 normalProviderType: UNIQUE_PREDEFINED_VALUE_PROVIDER,144 supportAskForValue: true,145 supportCaseSensitive: true146 },147 multiplePredefined:{148 normalProviderType: MULTIPLE_PREDEFINED_VALUE_PROVIDER,149 supportAskForValue: true,150 supportCaseSensitive: true151 }152 },153 stringOperatorDoesNotContain: {154 value: {155 normalProviderType: SIMPLE_VALUE_PROVIDER,156 supportAskForValue: true,157 supportCaseSensitive: true158 },159 values:{160 normalProviderType: SIMPLE_VALUE_PROVIDER161 },162 uniquePredefined:{163 normalProviderType: UNIQUE_PREDEFINED_VALUE_PROVIDER,164 supportAskForValue: true,165 supportCaseSensitive: true166 },167 multiplePredefined:{168 normalProviderType: MULTIPLE_PREDEFINED_VALUE_PROVIDER,169 supportAskForValue: true,170 supportCaseSensitive: true171 }172 },173 stringOperatorIsAnyOf: {174 values:{175 normalProviderType: SIMPLE_VALUE_PROVIDER176 },177 multiple:{178 normalProviderType: ADVANCED_LIST_VALUE_PROVIDER,179 supportAskForValue: true,180 filterCodedValueIfPossible: true181 },182 multiplePredefined:{183 normalProviderType: MULTIPLE_PREDEFINED_VALUE_PROVIDER,184 supportAskForValue: true185 }186 },187 stringOperatorIsNoneOf: {188 values:{189 normalProviderType: SIMPLE_VALUE_PROVIDER190 },191 multiple:{192 normalProviderType: ADVANCED_LIST_VALUE_PROVIDER,193 supportAskForValue: true,194 filterCodedValueIfPossible: true195 },196 multiplePredefined:{197 normalProviderType: MULTIPLE_PREDEFINED_VALUE_PROVIDER,198 supportAskForValue: true199 }200 },201 stringOperatorIsBlank: {202 value: {203 normalProviderType: BLANK_VALUE_PROVIDER204 }205 },206 stringOperatorIsNotBlank: {207 value: {208 normalProviderType: BLANK_VALUE_PROVIDER209 }210 },211 //number212 numberOperatorIs: {213 value: {214 normalProviderType: SIMPLE_VALUE_PROVIDER,215 codedValueProviderType: LIST_VALUE_PROVIDER,216 supportAskForValue: true217 },218 field: {219 normalProviderType: LIST_VALUE_PROVIDER220 },221 unique: {222 normalProviderType: LIST_VALUE_PROVIDER,223 supportAskForValue: true,224 filterCodedValueIfPossible: true225 },226 uniquePredefined:{227 normalProviderType: UNIQUE_PREDEFINED_VALUE_PROVIDER,228 supportAskForValue: true229 }230 },231 numberOperatorIsNot: {232 value: {233 normalProviderType: SIMPLE_VALUE_PROVIDER,234 codedValueProviderType: LIST_VALUE_PROVIDER,235 supportAskForValue: true236 },237 field: {238 normalProviderType: LIST_VALUE_PROVIDER239 },240 unique: {241 normalProviderType: LIST_VALUE_PROVIDER,242 supportAskForValue: true,243 filterCodedValueIfPossible: true244 },245 uniquePredefined:{246 normalProviderType: UNIQUE_PREDEFINED_VALUE_PROVIDER,247 supportAskForValue: true248 }249 },250 numberOperatorIsAtLeast: {251 value: {252 normalProviderType: SIMPLE_VALUE_PROVIDER,253 supportAskForValue: true254 },255 field: {256 normalProviderType: LIST_VALUE_PROVIDER257 },258 unique: {259 normalProviderType: LIST_VALUE_PROVIDER,260 supportAskForValue: true,261 filterCodedValueIfPossible: true262 },263 uniquePredefined:{264 normalProviderType: UNIQUE_PREDEFINED_VALUE_PROVIDER,265 supportAskForValue: true266 }267 },268 numberOperatorIsLessThan: {269 value: {270 normalProviderType: SIMPLE_VALUE_PROVIDER,271 supportAskForValue: true272 },273 field: {274 normalProviderType: LIST_VALUE_PROVIDER275 },276 unique: {277 normalProviderType: LIST_VALUE_PROVIDER,278 supportAskForValue: true,279 filterCodedValueIfPossible: true280 },281 uniquePredefined:{282 normalProviderType: UNIQUE_PREDEFINED_VALUE_PROVIDER,283 supportAskForValue: true284 }285 },286 numberOperatorIsAtMost: {287 value: {288 normalProviderType: SIMPLE_VALUE_PROVIDER,289 supportAskForValue: true290 },291 field: {292 normalProviderType: LIST_VALUE_PROVIDER293 },294 unique: {295 normalProviderType: LIST_VALUE_PROVIDER,296 supportAskForValue: true,297 filterCodedValueIfPossible: true298 },299 uniquePredefined:{300 normalProviderType: UNIQUE_PREDEFINED_VALUE_PROVIDER,301 supportAskForValue: true302 }303 },304 numberOperatorIsGreaterThan: {305 value: {306 normalProviderType: SIMPLE_VALUE_PROVIDER,307 supportAskForValue: true308 },309 field: {310 normalProviderType: LIST_VALUE_PROVIDER311 },312 unique: {313 normalProviderType: LIST_VALUE_PROVIDER,314 supportAskForValue: true,315 filterCodedValueIfPossible: true316 },317 uniquePredefined:{318 normalProviderType: UNIQUE_PREDEFINED_VALUE_PROVIDER,319 supportAskForValue: true320 }321 },322 numberOperatorIsAnyOf: {323 values:{324 normalProviderType: SIMPLE_VALUE_PROVIDER325 },326 multiple:{327 normalProviderType: ADVANCED_LIST_VALUE_PROVIDER,328 supportAskForValue: true329 },330 multiplePredefined:{331 normalProviderType: MULTIPLE_PREDEFINED_VALUE_PROVIDER,332 supportAskForValue: true333 }334 },335 numberOperatorIsNoneOf: {336 values:{337 normalProviderType: SIMPLE_VALUE_PROVIDER338 },339 multiple:{340 normalProviderType: ADVANCED_LIST_VALUE_PROVIDER,341 supportAskForValue: true342 },343 multiplePredefined:{344 normalProviderType: MULTIPLE_PREDEFINED_VALUE_PROVIDER,345 supportAskForValue: true346 }347 },348 numberOperatorIsBetween: {349 value: {350 normalProviderType: TWO_NUMBERS_VALUE_PROVIDER,351 supportAskForValue: true352 }353 },354 numberOperatorIsNotBetween: {355 value: {356 normalProviderType: TWO_NUMBERS_VALUE_PROVIDER,357 supportAskForValue: true358 }359 },360 numberOperatorIsBlank: {361 value: {362 normalProviderType: BLANK_VALUE_PROVIDER363 }364 },365 numberOperatorIsNotBlank: {366 value: {367 normalProviderType: BLANK_VALUE_PROVIDER368 }369 },370 //date371 dateOperatorIsOn: {372 value: {373 normalProviderType: SIMPLE_VALUE_PROVIDER,374 supportAskForValue: true375 },376 field: {377 normalProviderType: LIST_VALUE_PROVIDER378 }379 // Unique type can work already but we set it hidden in UI just right now.380 // ,381 // unique: {382 // normalProviderType: LIST_VALUE_PROVIDER,383 // supportAskForValue: true,384 // filterCodedValueIfPossible: true385 // }386 },387 dateOperatorIsNotOn: {388 value: {389 normalProviderType: SIMPLE_VALUE_PROVIDER,390 supportAskForValue: true391 },392 field: {393 normalProviderType: LIST_VALUE_PROVIDER394 }395 // Unique type can work already but we set it hidden in UI just right now.396 // ,397 // unique: {398 // normalProviderType: LIST_VALUE_PROVIDER,399 // supportAskForValue: true,400 // filterCodedValueIfPossible: true401 // }402 },403 dateOperatorIsIn: {404 value: {405 normalProviderType: DATE_IS_IN_VALUE_PROVIDER,406 supportAskForValue: true407 }408 },409 dateOperatorIsNotIn: {410 value: {411 normalProviderType: DATE_IS_IN_VALUE_PROVIDER,412 supportAskForValue: true413 }414 },415 dateOperatorIsBefore: {416 value: {417 normalProviderType: SIMPLE_VALUE_PROVIDER,418 supportAskForValue: true419 },420 field: {421 normalProviderType: LIST_VALUE_PROVIDER422 }423 },424 dateOperatorIsAfter: {425 value: {426 normalProviderType: SIMPLE_VALUE_PROVIDER,427 supportAskForValue: true428 },429 field: {430 normalProviderType: LIST_VALUE_PROVIDER431 }432 },433 dateOperatorIsOnOrBefore: {434 value: {435 normalProviderType: SIMPLE_VALUE_PROVIDER,436 supportAskForValue: true437 },438 field: {439 normalProviderType: LIST_VALUE_PROVIDER440 }441 },442 dateOperatorIsOnOrAfter: {443 value: {444 normalProviderType: SIMPLE_VALUE_PROVIDER,445 supportAskForValue: true446 },447 field: {448 normalProviderType: LIST_VALUE_PROVIDER449 }450 },451 dateOperatorInTheLast: {452 value: {453 normalProviderType: NUMBER_LIST_VALUE_PROVIDER,454 supportAskForValue: true455 }456 },457 dateOperatorNotInTheLast: {458 value: {459 normalProviderType: NUMBER_LIST_VALUE_PROVIDER,460 supportAskForValue: true461 }462 },463 dateOperatorIsBetween: {464 value: {465 normalProviderType: TWO_DATES_VALUE_PROVIDER,466 supportAskForValue: true467 }468 },469 dateOperatorIsNotBetween: {470 value: {471 normalProviderType: TWO_DATES_VALUE_PROVIDER,472 supportAskForValue: true473 }474 },475 dateOperatorIsBlank: {476 value: {477 normalProviderType: BLANK_VALUE_PROVIDER478 }479 },480 dateOperatorIsNotBlank: {481 value: {482 normalProviderType: BLANK_VALUE_PROVIDER483 }484 }485 };486 var clazz = declare([], {487 nls: null,488 layerInfo: null,//jimu/LayerInfos/LayerInfo, maybe null489 popupInfo: null,//webmap popupInfo, maybe null490 //options:491 url: null,//required492 layerDefinition: null,//required493 featureLayerId: null,//required494 constructor: function(options){495 //{url,layerDefinition}496 lang.mixin(this, options);497 this.nls = window.jimuNls.filterBuilder;498 var layerInfosObj = LayerInfos.getInstanceSync();499 if(this.featureLayerId){500 this.layerInfo = layerInfosObj.getLayerOrTableInfoById(this.featureLayerId);501 if(this.layerInfo){502 this.popupInfo = this.layerInfo.getPopupInfo();503 }504 }505 },506 getSupportedValueTypes: function(fieldName, operator){507 var valueTypes = [];//["value","field","unique"]508 var operatorInfo = relationship[operator];509 if(operatorInfo){510 // var version = parseFloat(this.layerDefinition.currentVersion);511 if(operatorInfo.value){512 valueTypes.push("value");513 }514 if(operatorInfo.field){515 var fieldNames = this._getSameShortTypeFieldNames(fieldName);516 if(fieldNames.length > 0){517 valueTypes.push("field");518 }519 }520 if(operatorInfo.unique){521 if(this.url){522 if(!this._isStreamServer(this.url)){523 // if(version >= 10.1){524 valueTypes.push("unique");525 // }526 }527 }528 }529 if(operatorInfo.multiple){530 if(this.url){531 if(!this._isStreamServer(this.url)){532 // if(version >= 10.1){ //version, for query params533 valueTypes.push("multiple");534 // }535 }536 }537 }538 // if(operatorInfo.values){ //hide values in UI539 // valueTypes.push("values");540 // }541 if(operatorInfo.uniquePredefined){542 if(this.url){543 if(!this._isStreamServer(this.url)){544 // if(version >= 10.1){545 valueTypes.push("uniquePredefined");546 // }547 }548 }549 }550 if(operatorInfo.multiplePredefined){551 if(this.url){552 if(!this._isStreamServer(this.url)){553 // if(version >= 10.1){554 valueTypes.push("multiplePredefined");555 // }556 }557 }558 }559 }560 return valueTypes;561 },562 _isStreamServer: function(url){563 url = url || "";564 url = url.replace(/\/*$/g, '');565 var reg = /\/StreamServer$/gi;566 return reg.test(url);567 },568 _getSameShortTypeFieldNames: function(fieldName){569 var fieldNames = [];570 var info = this._getFieldInfo(this.layerDefinition, fieldName);571 var shortType = clazz.getShortTypeByEsriType(info.type);572 array.forEach(this.layerDefinition.fields, lang.hitch(this, function(fieldInfo){573 if(fieldInfo.name !== fieldName){574 if(clazz.getShortTypeByEsriType(fieldInfo.type) === shortType){575 fieldNames.push(fieldInfo.name);576 }577 }578 }));579 return fieldNames;580 },581 _getSameShortTypeFieldNameLabels: function(fieldName){582 var fieldNameLabels = [];583 var info = this._getFieldInfo(this.layerDefinition, fieldName);584 var shortType = clazz.getShortTypeByEsriType(info.type);585 array.forEach(this.layerDefinition.fields, lang.hitch(this, function(fieldInfo){586 if(fieldInfo.name !== fieldName){587 if(clazz.getShortTypeByEsriType(fieldInfo.type) === shortType){588 fieldNameLabels.push({value: fieldInfo.name, label: fieldInfo.alias});589 }590 }591 }));592 return fieldNameLabels;593 },594 getValueProvider: function(partObj, runtime){595 /*{596 "fieldObj": {597 "name": "OBJECTID",598 "label": "OBJECTID",599 "shortType": "number",600 "type": "esriFieldTypeOID"601 },602 "operator": "numberOperatorIs",603 "valueObj": {604 "isValid": true,605 "type": "value",606 "value": 123607 },608 "interactiveObj": "",609 "caseSensitive": false,610 "expr": "OBJECTID = 123"611 }*/612 //partObj.valueObj.type must be set613 //partObj.valueObj.value, partObj.valueObj.value1 and partObj.valueObj.value2 are optional614 var valueProvider = null;615 var operator = partObj.operator;616 var operatorInfo = lang.clone(relationship[operator]);617 if(operatorInfo){618 var valueType = partObj.valueObj.type;619 var fieldName = partObj.fieldObj.name;620 var fieldInfo = this._getFieldInfo(this.layerDefinition, fieldName);621 var valueTypeInfo = operatorInfo[valueType];622 var valueProviderType = valueTypeInfo.normalProviderType;623 var staticValues = null;624 //for codedValues625 var codedValues = jimuUtils.getCodedValueListForCodedValueOrSubTypes(this.layerDefinition, fieldName);626 if(valueType === 'field'){//display with alias and query with name.#14620627 var otherFieldNameLabels = this._getSameShortTypeFieldNameLabels(fieldName);628 if(otherFieldNameLabels.length > 0){629 staticValues = otherFieldNameLabels;630 }631 }else{632 if(codedValues && codedValues.length > 0 && valueTypeInfo.codedValueProviderType){633 valueProviderType = valueTypeInfo.codedValueProviderType;634 }635 }636 var filterCodedValueIfPossible = !!valueTypeInfo.filterCodedValueIfPossible;637 var args = {638 nls: this.nls,639 url: this.url,640 layerDefinition: this.layerDefinition,641 partObj: partObj,642 fieldInfo: fieldInfo,643 codedValues: codedValues,644 staticValues: staticValues,645 layerInfo: this.layerInfo,646 popupInfo: this.popupInfo,647 operatorInfo: operatorInfo,648 filterCodedValueIfPossible: filterCodedValueIfPossible,649 runtime: runtime650 };651 if(valueProviderType === BLANK_VALUE_PROVIDER){652 valueProvider = new BlankValueProvider(args);653 } else if(valueProviderType === SIMPLE_VALUE_PROVIDER){654 valueProvider = new SimpleValueProvider(args);655 }else if(valueProviderType === TWO_NUMBERS_VALUE_PROVIDER){656 valueProvider = new TwoNumbersValueProvider(args);657 }else if(valueProviderType === TWO_DATES_VALUE_PROVIDER){658 valueProvider = new TwoDatesValueProvider(args);659 }else if(valueProviderType === LIST_VALUE_PROVIDER){660 // if(operator === "stringOperatorIs" ||661 // operator === "stringOperatorIsNot" ||662 // operator === "numberOperatorIs" ||663 // operator === "numberOperatorIsNot"){664 // args.showNullValues = true;665 // }else{666 // args.showNullValues = false;667 // }668 args.showNullValues = false;669 if(valueType === 'value' || valueType === 'field'){670 // || args.fieldInfo.type === 'esriFieldTypeDate'){671 valueProvider = new ListValueProvider(args);//origin unique provider672 }else{673 args.providerType = valueProviderType;674 args.selectUI = 'dropdown';675 // if(valueType === 'field'){676 // args.isNumberField = false; //field's name is a string677 // }678 valueProvider = new AdvancedListValueProvider(args);679 }680 }else if(valueProviderType === NUMBER_LIST_VALUE_PROVIDER){681 valueProvider = new NumberListValueProvider(args);682 }else if(valueProviderType === DATE_IS_IN_VALUE_PROVIDER){683 valueProvider = new DateIsInValueProvider(args);684 }685 else if(valueProviderType === ADVANCED_LIST_VALUE_PROVIDER){ //mutiple---setting&runtime686 args.providerType = valueProviderType;687 args.selectUI = 'dropdown';688 valueProvider = new AdvancedListValueProvider(args);689 }690 else if(valueProviderType === UNIQUE_PREDEFINED_VALUE_PROVIDER ||691 valueProviderType === MULTIPLE_PREDEFINED_VALUE_PROVIDER){692 args.providerType = valueProviderType;693 args.selectUI = args.partObj.valueObj ? args.partObj.valueObj.selectUI : null;694 if(runtime){695 valueProvider = new AdvancedListValueProvider(args);696 }else{697 valueProvider = new PredefinedValueProvider(args);698 }699 }700 }701 return valueProvider;702 },703 _getFieldInfo: function(layerDefinition, fieldName){704 var fieldInfos = layerDefinition.fields;705 for(var i = 0;i < fieldInfos.length; i++){706 var fieldInfo = fieldInfos[i];707 if(fieldName === fieldInfo.name){708 return fieldInfo;709 }710 }711 return null;712 }713 });714 clazz.getOperatorInfo = function(operator) {715 var operatorInfo = lang.clone(relationship[operator]);716 return operatorInfo;717 };718 clazz.getOperatorsByShortType = function(shortType, isHosted){719 var operators = [];720 if(shortType === 'string'){721 operators = [722 "stringOperatorIs",723 "stringOperatorIsNot",724 "stringOperatorStartsWith",725 "stringOperatorEndsWith",726 "stringOperatorContains",727 "stringOperatorDoesNotContain",728 "stringOperatorIsAnyOf",729 "stringOperatorIsNoneOf",730 "stringOperatorIsBlank",731 "stringOperatorIsNotBlank"732 ];733 }else if(shortType === 'number'){734 operators = [735 "numberOperatorIs",736 "numberOperatorIsNot",737 "numberOperatorIsAtLeast",738 "numberOperatorIsAtMost",739 "numberOperatorIsLessThan",740 "numberOperatorIsGreaterThan",741 "numberOperatorIsAnyOf",742 "numberOperatorIsNoneOf",743 "numberOperatorIsBetween",744 "numberOperatorIsNotBetween",745 "numberOperatorIsBlank",746 "numberOperatorIsNotBlank"747 ];748 }else if(shortType === 'date'){749 operators = [750 "dateOperatorIsOn",751 "dateOperatorIsNotOn",752 "dateOperatorIsIn",753 "dateOperatorIsNotIn",754 "dateOperatorIsBefore",755 "dateOperatorIsAfter",756 "dateOperatorIsOnOrBefore",757 "dateOperatorIsOnOrAfter",758 "dateOperatorIsBetween",759 "dateOperatorIsNotBetween",760 "dateOperatorIsBlank",761 "dateOperatorIsNotBlank"762 ];763 if(isHosted){764 operators.splice(8,0,"dateOperatorInTheLast","dateOperatorNotInTheLast");765 }766 }767 return operators;768 };769 clazz.getShortTypeByEsriType = function(esriFieldType){770 var shortType = null;771 if(esriFieldType === 'esriFieldTypeString'){772 shortType = 'string';773 }else if(esriFieldType === 'esriFieldTypeDate'){774 shortType = 'date';775 }else{776 var numberTypes = ['esriFieldTypeOID',777 'esriFieldTypeSmallInteger',778 'esriFieldTypeInteger',779 'esriFieldTypeSingle',780 'esriFieldTypeDouble'];781 if(numberTypes.indexOf(esriFieldType) >= 0){782 shortType = 'number';783 }784 }785 return shortType;786 };787 return clazz;...

Full Screen

Full Screen

provider_analyzer.ts

Source:provider_analyzer.ts Github

copy

Full Screen

1/**2 * @license3 * Copyright Google Inc. All Rights Reserved.4 *5 * Use of this source code is governed by an MIT-style license that can be6 * found in the LICENSE file at https://angular.io/license7 */8import {CompileDiDependencyMetadata, CompileDirectiveMetadata, CompileDirectiveSummary, CompileNgModuleMetadata, CompileProviderMetadata, CompileQueryMetadata, CompileTokenMetadata, CompileTypeMetadata, tokenName, tokenReference} from './compile_metadata';9import {CompileReflector} from './compile_reflector';10import {Identifiers, createTokenForExternalReference} from './identifiers';11import {ParseError, ParseSourceSpan} from './parse_util';12import {AttrAst, DirectiveAst, ProviderAst, ProviderAstType, QueryMatch, ReferenceAst} from './template_parser/template_ast';13export class ProviderError extends ParseError {14 constructor(message: string, span: ParseSourceSpan) { super(span, message); }15}16export interface QueryWithId {17 meta: CompileQueryMetadata;18 queryId: number;19}20export class ProviderViewContext {21 /**22 * @internal23 */24 viewQueries: Map<any, QueryWithId[]>;25 /**26 * @internal27 */28 viewProviders: Map<any, boolean>;29 errors: ProviderError[] = [];30 constructor(public reflector: CompileReflector, public component: CompileDirectiveMetadata) {31 this.viewQueries = _getViewQueries(component);32 this.viewProviders = new Map<any, boolean>();33 component.viewProviders.forEach((provider) => {34 if (this.viewProviders.get(tokenReference(provider.token)) == null) {35 this.viewProviders.set(tokenReference(provider.token), true);36 }37 });38 }39}40export class ProviderElementContext {41 private _contentQueries: Map<any, QueryWithId[]>;42 private _transformedProviders = new Map<any, ProviderAst>();43 private _seenProviders = new Map<any, boolean>();44 private _allProviders: Map<any, ProviderAst>;45 private _attrs: {[key: string]: string};46 private _queriedTokens = new Map<any, QueryMatch[]>();47 public readonly transformedHasViewContainer: boolean = false;48 constructor(49 public viewContext: ProviderViewContext, private _parent: ProviderElementContext,50 private _isViewRoot: boolean, private _directiveAsts: DirectiveAst[], attrs: AttrAst[],51 refs: ReferenceAst[], isTemplate: boolean, contentQueryStartId: number,52 private _sourceSpan: ParseSourceSpan) {53 this._attrs = {};54 attrs.forEach((attrAst) => this._attrs[attrAst.name] = attrAst.value);55 const directivesMeta = _directiveAsts.map(directiveAst => directiveAst.directive);56 this._allProviders =57 _resolveProvidersFromDirectives(directivesMeta, _sourceSpan, viewContext.errors);58 this._contentQueries = _getContentQueries(contentQueryStartId, directivesMeta);59 Array.from(this._allProviders.values()).forEach((provider) => {60 this._addQueryReadsTo(provider.token, provider.token, this._queriedTokens);61 });62 if (isTemplate) {63 const templateRefId =64 createTokenForExternalReference(this.viewContext.reflector, Identifiers.TemplateRef);65 this._addQueryReadsTo(templateRefId, templateRefId, this._queriedTokens);66 }67 refs.forEach((refAst) => {68 let defaultQueryValue = refAst.value ||69 createTokenForExternalReference(this.viewContext.reflector, Identifiers.ElementRef);70 this._addQueryReadsTo({value: refAst.name}, defaultQueryValue, this._queriedTokens);71 });72 if (this._queriedTokens.get(73 this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef))) {74 this.transformedHasViewContainer = true;75 }76 // create the providers that we know are eager first77 Array.from(this._allProviders.values()).forEach((provider) => {78 const eager = provider.eager || this._queriedTokens.get(tokenReference(provider.token));79 if (eager) {80 this._getOrCreateLocalProvider(provider.providerType, provider.token, true);81 }82 });83 }84 afterElement() {85 // collect lazy providers86 Array.from(this._allProviders.values()).forEach((provider) => {87 this._getOrCreateLocalProvider(provider.providerType, provider.token, false);88 });89 }90 get transformProviders(): ProviderAst[] {91 // Note: Maps keep their insertion order.92 const lazyProviders: ProviderAst[] = [];93 const eagerProviders: ProviderAst[] = [];94 this._transformedProviders.forEach(provider => {95 if (provider.eager) {96 eagerProviders.push(provider);97 } else {98 lazyProviders.push(provider);99 }100 });101 return lazyProviders.concat(eagerProviders);102 }103 get transformedDirectiveAsts(): DirectiveAst[] {104 const sortedProviderTypes = this.transformProviders.map(provider => provider.token.identifier);105 const sortedDirectives = this._directiveAsts.slice();106 sortedDirectives.sort(107 (dir1, dir2) => sortedProviderTypes.indexOf(dir1.directive.type) -108 sortedProviderTypes.indexOf(dir2.directive.type));109 return sortedDirectives;110 }111 get queryMatches(): QueryMatch[] {112 const allMatches: QueryMatch[] = [];113 this._queriedTokens.forEach((matches: QueryMatch[]) => { allMatches.push(...matches); });114 return allMatches;115 }116 private _addQueryReadsTo(117 token: CompileTokenMetadata, defaultValue: CompileTokenMetadata,118 queryReadTokens: Map<any, QueryMatch[]>) {119 this._getQueriesFor(token).forEach((query) => {120 const queryValue = query.meta.read || defaultValue;121 const tokenRef = tokenReference(queryValue);122 let queryMatches = queryReadTokens.get(tokenRef);123 if (!queryMatches) {124 queryMatches = [];125 queryReadTokens.set(tokenRef, queryMatches);126 }127 queryMatches.push({queryId: query.queryId, value: queryValue});128 });129 }130 private _getQueriesFor(token: CompileTokenMetadata): QueryWithId[] {131 const result: QueryWithId[] = [];132 let currentEl: ProviderElementContext = this;133 let distance = 0;134 let queries: QueryWithId[]|undefined;135 while (currentEl !== null) {136 queries = currentEl._contentQueries.get(tokenReference(token));137 if (queries) {138 result.push(...queries.filter((query) => query.meta.descendants || distance <= 1));139 }140 if (currentEl._directiveAsts.length > 0) {141 distance++;142 }143 currentEl = currentEl._parent;144 }145 queries = this.viewContext.viewQueries.get(tokenReference(token));146 if (queries) {147 result.push(...queries);148 }149 return result;150 }151 private _getOrCreateLocalProvider(152 requestingProviderType: ProviderAstType, token: CompileTokenMetadata,153 eager: boolean): ProviderAst|null {154 const resolvedProvider = this._allProviders.get(tokenReference(token));155 if (!resolvedProvider || ((requestingProviderType === ProviderAstType.Directive ||156 requestingProviderType === ProviderAstType.PublicService) &&157 resolvedProvider.providerType === ProviderAstType.PrivateService) ||158 ((requestingProviderType === ProviderAstType.PrivateService ||159 requestingProviderType === ProviderAstType.PublicService) &&160 resolvedProvider.providerType === ProviderAstType.Builtin)) {161 return null;162 }163 let transformedProviderAst = this._transformedProviders.get(tokenReference(token));164 if (transformedProviderAst) {165 return transformedProviderAst;166 }167 if (this._seenProviders.get(tokenReference(token)) != null) {168 this.viewContext.errors.push(new ProviderError(169 `Cannot instantiate cyclic dependency! ${tokenName(token)}`, this._sourceSpan));170 return null;171 }172 this._seenProviders.set(tokenReference(token), true);173 const transformedProviders = resolvedProvider.providers.map((provider) => {174 let transformedUseValue = provider.useValue;175 let transformedUseExisting = provider.useExisting !;176 let transformedDeps: CompileDiDependencyMetadata[] = undefined !;177 if (provider.useExisting != null) {178 const existingDiDep = this._getDependency(179 resolvedProvider.providerType, {token: provider.useExisting}, eager) !;180 if (existingDiDep.token != null) {181 transformedUseExisting = existingDiDep.token;182 } else {183 transformedUseExisting = null !;184 transformedUseValue = existingDiDep.value;185 }186 } else if (provider.useFactory) {187 const deps = provider.deps || provider.useFactory.diDeps;188 transformedDeps =189 deps.map((dep) => this._getDependency(resolvedProvider.providerType, dep, eager) !);190 } else if (provider.useClass) {191 const deps = provider.deps || provider.useClass.diDeps;192 transformedDeps =193 deps.map((dep) => this._getDependency(resolvedProvider.providerType, dep, eager) !);194 }195 return _transformProvider(provider, {196 useExisting: transformedUseExisting,197 useValue: transformedUseValue,198 deps: transformedDeps199 });200 });201 transformedProviderAst =202 _transformProviderAst(resolvedProvider, {eager: eager, providers: transformedProviders});203 this._transformedProviders.set(tokenReference(token), transformedProviderAst);204 return transformedProviderAst;205 }206 private _getLocalDependency(207 requestingProviderType: ProviderAstType, dep: CompileDiDependencyMetadata,208 eager: boolean = false): CompileDiDependencyMetadata|null {209 if (dep.isAttribute) {210 const attrValue = this._attrs[dep.token !.value];211 return {isValue: true, value: attrValue == null ? null : attrValue};212 }213 if (dep.token != null) {214 // access builtints215 if ((requestingProviderType === ProviderAstType.Directive ||216 requestingProviderType === ProviderAstType.Component)) {217 if (tokenReference(dep.token) ===218 this.viewContext.reflector.resolveExternalReference(Identifiers.Renderer) ||219 tokenReference(dep.token) ===220 this.viewContext.reflector.resolveExternalReference(Identifiers.ElementRef) ||221 tokenReference(dep.token) ===222 this.viewContext.reflector.resolveExternalReference(223 Identifiers.ChangeDetectorRef) ||224 tokenReference(dep.token) ===225 this.viewContext.reflector.resolveExternalReference(Identifiers.TemplateRef)) {226 return dep;227 }228 if (tokenReference(dep.token) ===229 this.viewContext.reflector.resolveExternalReference(Identifiers.ViewContainerRef)) {230 (this as{transformedHasViewContainer: boolean}).transformedHasViewContainer = true;231 }232 }233 // access the injector234 if (tokenReference(dep.token) ===235 this.viewContext.reflector.resolveExternalReference(Identifiers.Injector)) {236 return dep;237 }238 // access providers239 if (this._getOrCreateLocalProvider(requestingProviderType, dep.token, eager) != null) {240 return dep;241 }242 }243 return null;244 }245 private _getDependency(246 requestingProviderType: ProviderAstType, dep: CompileDiDependencyMetadata,247 eager: boolean = false): CompileDiDependencyMetadata|null {248 let currElement: ProviderElementContext = this;249 let currEager: boolean = eager;250 let result: CompileDiDependencyMetadata|null = null;251 if (!dep.isSkipSelf) {252 result = this._getLocalDependency(requestingProviderType, dep, eager);253 }254 if (dep.isSelf) {255 if (!result && dep.isOptional) {256 result = {isValue: true, value: null};257 }258 } else {259 // check parent elements260 while (!result && currElement._parent) {261 const prevElement = currElement;262 currElement = currElement._parent;263 if (prevElement._isViewRoot) {264 currEager = false;265 }266 result = currElement._getLocalDependency(ProviderAstType.PublicService, dep, currEager);267 }268 // check @Host restriction269 if (!result) {270 if (!dep.isHost || this.viewContext.component.isHost ||271 this.viewContext.component.type.reference === tokenReference(dep.token !) ||272 this.viewContext.viewProviders.get(tokenReference(dep.token !)) != null) {273 result = dep;274 } else {275 result = dep.isOptional ? result = {isValue: true, value: null} : null;276 }277 }278 }279 if (!result) {280 this.viewContext.errors.push(281 new ProviderError(`No provider for ${tokenName(dep.token!)}`, this._sourceSpan));282 }283 return result;284 }285}286export class NgModuleProviderAnalyzer {287 private _transformedProviders = new Map<any, ProviderAst>();288 private _seenProviders = new Map<any, boolean>();289 private _allProviders: Map<any, ProviderAst>;290 private _errors: ProviderError[] = [];291 constructor(292 private reflector: CompileReflector, ngModule: CompileNgModuleMetadata,293 extraProviders: CompileProviderMetadata[], sourceSpan: ParseSourceSpan) {294 this._allProviders = new Map<any, ProviderAst>();295 ngModule.transitiveModule.modules.forEach((ngModuleType: CompileTypeMetadata) => {296 const ngModuleProvider = {token: {identifier: ngModuleType}, useClass: ngModuleType};297 _resolveProviders(298 [ngModuleProvider], ProviderAstType.PublicService, true, sourceSpan, this._errors,299 this._allProviders);300 });301 _resolveProviders(302 ngModule.transitiveModule.providers.map(entry => entry.provider).concat(extraProviders),303 ProviderAstType.PublicService, false, sourceSpan, this._errors, this._allProviders);304 }305 parse(): ProviderAst[] {306 Array.from(this._allProviders.values()).forEach((provider) => {307 this._getOrCreateLocalProvider(provider.token, provider.eager);308 });309 if (this._errors.length > 0) {310 const errorString = this._errors.join('\n');311 throw new Error(`Provider parse errors:\n${errorString}`);312 }313 // Note: Maps keep their insertion order.314 const lazyProviders: ProviderAst[] = [];315 const eagerProviders: ProviderAst[] = [];316 this._transformedProviders.forEach(provider => {317 if (provider.eager) {318 eagerProviders.push(provider);319 } else {320 lazyProviders.push(provider);321 }322 });323 return lazyProviders.concat(eagerProviders);324 }325 private _getOrCreateLocalProvider(token: CompileTokenMetadata, eager: boolean): ProviderAst|null {326 const resolvedProvider = this._allProviders.get(tokenReference(token));327 if (!resolvedProvider) {328 return null;329 }330 let transformedProviderAst = this._transformedProviders.get(tokenReference(token));331 if (transformedProviderAst) {332 return transformedProviderAst;333 }334 if (this._seenProviders.get(tokenReference(token)) != null) {335 this._errors.push(new ProviderError(336 `Cannot instantiate cyclic dependency! ${tokenName(token)}`,337 resolvedProvider.sourceSpan));338 return null;339 }340 this._seenProviders.set(tokenReference(token), true);341 const transformedProviders = resolvedProvider.providers.map((provider) => {342 let transformedUseValue = provider.useValue;343 let transformedUseExisting = provider.useExisting !;344 let transformedDeps: CompileDiDependencyMetadata[] = undefined !;345 if (provider.useExisting != null) {346 const existingDiDep =347 this._getDependency({token: provider.useExisting}, eager, resolvedProvider.sourceSpan);348 if (existingDiDep.token != null) {349 transformedUseExisting = existingDiDep.token;350 } else {351 transformedUseExisting = null !;352 transformedUseValue = existingDiDep.value;353 }354 } else if (provider.useFactory) {355 const deps = provider.deps || provider.useFactory.diDeps;356 transformedDeps =357 deps.map((dep) => this._getDependency(dep, eager, resolvedProvider.sourceSpan));358 } else if (provider.useClass) {359 const deps = provider.deps || provider.useClass.diDeps;360 transformedDeps =361 deps.map((dep) => this._getDependency(dep, eager, resolvedProvider.sourceSpan));362 }363 return _transformProvider(provider, {364 useExisting: transformedUseExisting,365 useValue: transformedUseValue,366 deps: transformedDeps367 });368 });369 transformedProviderAst =370 _transformProviderAst(resolvedProvider, {eager: eager, providers: transformedProviders});371 this._transformedProviders.set(tokenReference(token), transformedProviderAst);372 return transformedProviderAst;373 }374 private _getDependency(375 dep: CompileDiDependencyMetadata, eager: boolean = false,376 requestorSourceSpan: ParseSourceSpan): CompileDiDependencyMetadata {377 let foundLocal = false;378 if (!dep.isSkipSelf && dep.token != null) {379 // access the injector380 if (tokenReference(dep.token) ===381 this.reflector.resolveExternalReference(Identifiers.Injector) ||382 tokenReference(dep.token) ===383 this.reflector.resolveExternalReference(Identifiers.ComponentFactoryResolver)) {384 foundLocal = true;385 // access providers386 } else if (this._getOrCreateLocalProvider(dep.token, eager) != null) {387 foundLocal = true;388 }389 }390 let result: CompileDiDependencyMetadata = dep;391 if (dep.isSelf && !foundLocal) {392 if (dep.isOptional) {393 result = {isValue: true, value: null};394 } else {395 this._errors.push(396 new ProviderError(`No provider for ${tokenName(dep.token!)}`, requestorSourceSpan));397 }398 }399 return result;400 }401}402function _transformProvider(403 provider: CompileProviderMetadata,404 {useExisting, useValue, deps}:405 {useExisting: CompileTokenMetadata, useValue: any, deps: CompileDiDependencyMetadata[]}) {406 return {407 token: provider.token,408 useClass: provider.useClass,409 useExisting: useExisting,410 useFactory: provider.useFactory,411 useValue: useValue,412 deps: deps,413 multi: provider.multi414 };415}416function _transformProviderAst(417 provider: ProviderAst,418 {eager, providers}: {eager: boolean, providers: CompileProviderMetadata[]}): ProviderAst {419 return new ProviderAst(420 provider.token, provider.multiProvider, provider.eager || eager, providers,421 provider.providerType, provider.lifecycleHooks, provider.sourceSpan);422}423function _resolveProvidersFromDirectives(424 directives: CompileDirectiveSummary[], sourceSpan: ParseSourceSpan,425 targetErrors: ParseError[]): Map<any, ProviderAst> {426 const providersByToken = new Map<any, ProviderAst>();427 directives.forEach((directive) => {428 const dirProvider:429 CompileProviderMetadata = {token: {identifier: directive.type}, useClass: directive.type};430 _resolveProviders(431 [dirProvider],432 directive.isComponent ? ProviderAstType.Component : ProviderAstType.Directive, true,433 sourceSpan, targetErrors, providersByToken);434 });435 // Note: directives need to be able to overwrite providers of a component!436 const directivesWithComponentFirst =437 directives.filter(dir => dir.isComponent).concat(directives.filter(dir => !dir.isComponent));438 directivesWithComponentFirst.forEach((directive) => {439 _resolveProviders(440 directive.providers, ProviderAstType.PublicService, false, sourceSpan, targetErrors,441 providersByToken);442 _resolveProviders(443 directive.viewProviders, ProviderAstType.PrivateService, false, sourceSpan, targetErrors,444 providersByToken);445 });446 return providersByToken;447}448function _resolveProviders(449 providers: CompileProviderMetadata[], providerType: ProviderAstType, eager: boolean,450 sourceSpan: ParseSourceSpan, targetErrors: ParseError[],451 targetProvidersByToken: Map<any, ProviderAst>) {452 providers.forEach((provider) => {453 let resolvedProvider = targetProvidersByToken.get(tokenReference(provider.token));454 if (resolvedProvider != null && !!resolvedProvider.multiProvider !== !!provider.multi) {455 targetErrors.push(new ProviderError(456 `Mixing multi and non multi provider is not possible for token ${tokenName(resolvedProvider.token)}`,457 sourceSpan));458 }459 if (!resolvedProvider) {460 const lifecycleHooks = provider.token.identifier &&461 (<CompileTypeMetadata>provider.token.identifier).lifecycleHooks ?462 (<CompileTypeMetadata>provider.token.identifier).lifecycleHooks :463 [];464 const isUseValue = !(provider.useClass || provider.useExisting || provider.useFactory);465 resolvedProvider = new ProviderAst(466 provider.token, !!provider.multi, eager || isUseValue, [provider], providerType,467 lifecycleHooks, sourceSpan);468 targetProvidersByToken.set(tokenReference(provider.token), resolvedProvider);469 } else {470 if (!provider.multi) {471 resolvedProvider.providers.length = 0;472 }473 resolvedProvider.providers.push(provider);474 }475 });476}477function _getViewQueries(component: CompileDirectiveMetadata): Map<any, QueryWithId[]> {478 // Note: queries start with id 1 so we can use the number in a Bloom filter!479 let viewQueryId = 1;480 const viewQueries = new Map<any, QueryWithId[]>();481 if (component.viewQueries) {482 component.viewQueries.forEach(483 (query) => _addQueryToTokenMap(viewQueries, {meta: query, queryId: viewQueryId++}));484 }485 return viewQueries;486}487function _getContentQueries(488 contentQueryStartId: number, directives: CompileDirectiveSummary[]): Map<any, QueryWithId[]> {489 let contentQueryId = contentQueryStartId;490 const contentQueries = new Map<any, QueryWithId[]>();491 directives.forEach((directive, directiveIndex) => {492 if (directive.queries) {493 directive.queries.forEach(494 (query) => _addQueryToTokenMap(contentQueries, {meta: query, queryId: contentQueryId++}));495 }496 });497 return contentQueries;498}499function _addQueryToTokenMap(map: Map<any, QueryWithId[]>, query: QueryWithId) {500 query.meta.selectors.forEach((token: CompileTokenMetadata) => {501 let entry = map.get(tokenReference(token));502 if (!entry) {503 entry = [];504 map.set(tokenReference(token), entry);505 }506 entry.push(query);507 });...

Full Screen

Full Screen

provider_compiler.ts

Source:provider_compiler.ts Github

copy

Full Screen

1/**2 * @license3 * Copyright Google Inc. All Rights Reserved.4 *5 * Use of this source code is governed by an MIT-style license that can be6 * found in the LICENSE file at https://angular.io/license7 */8import {CompileDiDependencyMetadata, CompileEntryComponentMetadata, CompileProviderMetadata, CompileTokenMetadata} from '../compile_metadata';9import {CompileReflector} from '../compile_reflector';10import {DepFlags, NodeFlags} from '../core';11import {Identifiers, createTokenForExternalReference} from '../identifiers';12import {LifecycleHooks} from '../lifecycle_reflector';13import * as o from '../output/output_ast';14import {convertValueToOutputAst} from '../output/value_util';15import {ProviderAst, ProviderAstType} from '../template_parser/template_ast';16import {OutputContext} from '../util';17export function providerDef(ctx: OutputContext, providerAst: ProviderAst): {18 providerExpr: o.Expression,19 flags: NodeFlags,20 depsExpr: o.Expression,21 tokenExpr: o.Expression22} {23 let flags = NodeFlags.None;24 if (!providerAst.eager) {25 flags |= NodeFlags.LazyProvider;26 }27 if (providerAst.providerType === ProviderAstType.PrivateService) {28 flags |= NodeFlags.PrivateProvider;29 }30 providerAst.lifecycleHooks.forEach((lifecycleHook) => {31 // for regular providers, we only support ngOnDestroy32 if (lifecycleHook === LifecycleHooks.OnDestroy ||33 providerAst.providerType === ProviderAstType.Directive ||34 providerAst.providerType === ProviderAstType.Component) {35 flags |= lifecycleHookToNodeFlag(lifecycleHook);36 }37 });38 const {providerExpr, flags: providerFlags, depsExpr} = providerAst.multiProvider ?39 multiProviderDef(ctx, flags, providerAst.providers) :40 singleProviderDef(ctx, flags, providerAst.providerType, providerAst.providers[0]);41 return {42 providerExpr,43 flags: providerFlags, depsExpr,44 tokenExpr: tokenExpr(ctx, providerAst.token),45 };46}47function multiProviderDef(48 ctx: OutputContext, flags: NodeFlags, providers: CompileProviderMetadata[]):49 {providerExpr: o.Expression, flags: NodeFlags, depsExpr: o.Expression} {50 const allDepDefs: o.Expression[] = [];51 const allParams: o.FnParam[] = [];52 const exprs = providers.map((provider, providerIndex) => {53 let expr: o.Expression;54 if (provider.useClass) {55 const depExprs = convertDeps(providerIndex, provider.deps || provider.useClass.diDeps);56 expr = ctx.importExpr(provider.useClass.reference).instantiate(depExprs);57 } else if (provider.useFactory) {58 const depExprs = convertDeps(providerIndex, provider.deps || provider.useFactory.diDeps);59 expr = ctx.importExpr(provider.useFactory.reference).callFn(depExprs);60 } else if (provider.useExisting) {61 const depExprs = convertDeps(providerIndex, [{token: provider.useExisting}]);62 expr = depExprs[0];63 } else {64 expr = convertValueToOutputAst(ctx, provider.useValue);65 }66 return expr;67 });68 const providerExpr =69 o.fn(allParams, [new o.ReturnStatement(o.literalArr(exprs))], o.INFERRED_TYPE);70 return {71 providerExpr,72 flags: flags | NodeFlags.TypeFactoryProvider,73 depsExpr: o.literalArr(allDepDefs)74 };75 function convertDeps(providerIndex: number, deps: CompileDiDependencyMetadata[]) {76 return deps.map((dep, depIndex) => {77 const paramName = `p${providerIndex}_${depIndex}`;78 allParams.push(new o.FnParam(paramName, o.DYNAMIC_TYPE));79 allDepDefs.push(depDef(ctx, dep));80 return o.variable(paramName);81 });82 }83}84function singleProviderDef(85 ctx: OutputContext, flags: NodeFlags, providerType: ProviderAstType,86 providerMeta: CompileProviderMetadata):87 {providerExpr: o.Expression, flags: NodeFlags, depsExpr: o.Expression} {88 let providerExpr: o.Expression;89 let deps: CompileDiDependencyMetadata[];90 if (providerType === ProviderAstType.Directive || providerType === ProviderAstType.Component) {91 providerExpr = ctx.importExpr(providerMeta.useClass !.reference);92 flags |= NodeFlags.TypeDirective;93 deps = providerMeta.deps || providerMeta.useClass !.diDeps;94 } else {95 if (providerMeta.useClass) {96 providerExpr = ctx.importExpr(providerMeta.useClass.reference);97 flags |= NodeFlags.TypeClassProvider;98 deps = providerMeta.deps || providerMeta.useClass.diDeps;99 } else if (providerMeta.useFactory) {100 providerExpr = ctx.importExpr(providerMeta.useFactory.reference);101 flags |= NodeFlags.TypeFactoryProvider;102 deps = providerMeta.deps || providerMeta.useFactory.diDeps;103 } else if (providerMeta.useExisting) {104 providerExpr = o.NULL_EXPR;105 flags |= NodeFlags.TypeUseExistingProvider;106 deps = [{token: providerMeta.useExisting}];107 } else {108 providerExpr = convertValueToOutputAst(ctx, providerMeta.useValue);109 flags |= NodeFlags.TypeValueProvider;110 deps = [];111 }112 }113 const depsExpr = o.literalArr(deps.map(dep => depDef(ctx, dep)));114 return {providerExpr, flags, depsExpr};115}116function tokenExpr(ctx: OutputContext, tokenMeta: CompileTokenMetadata): o.Expression {117 return tokenMeta.identifier ? ctx.importExpr(tokenMeta.identifier.reference) :118 o.literal(tokenMeta.value);119}120export function depDef(ctx: OutputContext, dep: CompileDiDependencyMetadata): o.Expression {121 // Note: the following fields have already been normalized out by provider_analyzer:122 // - isAttribute, isSelf, isHost123 const expr = dep.isValue ? convertValueToOutputAst(ctx, dep.value) : tokenExpr(ctx, dep.token !);124 let flags = DepFlags.None;125 if (dep.isSkipSelf) {126 flags |= DepFlags.SkipSelf;127 }128 if (dep.isOptional) {129 flags |= DepFlags.Optional;130 }131 if (dep.isValue) {132 flags |= DepFlags.Value;133 }134 return flags === DepFlags.None ? expr : o.literalArr([o.literal(flags), expr]);135}136export function lifecycleHookToNodeFlag(lifecycleHook: LifecycleHooks): NodeFlags {137 let nodeFlag = NodeFlags.None;138 switch (lifecycleHook) {139 case LifecycleHooks.AfterContentChecked:140 nodeFlag = NodeFlags.AfterContentChecked;141 break;142 case LifecycleHooks.AfterContentInit:143 nodeFlag = NodeFlags.AfterContentInit;144 break;145 case LifecycleHooks.AfterViewChecked:146 nodeFlag = NodeFlags.AfterViewChecked;147 break;148 case LifecycleHooks.AfterViewInit:149 nodeFlag = NodeFlags.AfterViewInit;150 break;151 case LifecycleHooks.DoCheck:152 nodeFlag = NodeFlags.DoCheck;153 break;154 case LifecycleHooks.OnChanges:155 nodeFlag = NodeFlags.OnChanges;156 break;157 case LifecycleHooks.OnDestroy:158 nodeFlag = NodeFlags.OnDestroy;159 break;160 case LifecycleHooks.OnInit:161 nodeFlag = NodeFlags.OnInit;162 break;163 }164 return nodeFlag;165}166export function componentFactoryResolverProviderDef(167 reflector: CompileReflector, ctx: OutputContext, flags: NodeFlags,168 entryComponents: CompileEntryComponentMetadata[]): {169 providerExpr: o.Expression,170 flags: NodeFlags,171 depsExpr: o.Expression,172 tokenExpr: o.Expression173} {174 const entryComponentFactories =175 entryComponents.map((entryComponent) => ctx.importExpr(entryComponent.componentFactory));176 const token = createTokenForExternalReference(reflector, Identifiers.ComponentFactoryResolver);177 const classMeta = {178 diDeps: [179 {isValue: true, value: o.literalArr(entryComponentFactories)},180 {token: token, isSkipSelf: true, isOptional: true},181 {token: createTokenForExternalReference(reflector, Identifiers.NgModuleRef)},182 ],183 lifecycleHooks: [],184 reference: reflector.resolveExternalReference(Identifiers.CodegenComponentFactoryResolver)185 };186 const {providerExpr, flags: providerFlags, depsExpr} =187 singleProviderDef(ctx, flags, ProviderAstType.PrivateService, {188 token,189 multi: false,190 useClass: classMeta,191 });192 return {providerExpr, flags: providerFlags, depsExpr, tokenExpr: tokenExpr(ctx, token)};...

Full Screen

Full Screen

provider.js

Source:provider.js Github

copy

Full Screen

1var chai = require('chai');2var assert = chai.assert;3var net = require('net');4var Eth = require('../packages/web3-eth');5var Shh = require('../packages/web3-shh');6var Net = require('../packages/web3-net');7var Web3 = require('../packages/web3');8var tests = [{9 providerParams: ['http://localhost:8545'],10 providerType: 'HttpProvider',11 package: Web312},{13 providerParams: ['HTTP://localhost:8545'],14 providerType: 'HttpProvider',15 package: Web316},{17 providerParams: ['ws://localhost:8546'],18 providerType: 'WebsocketProvider',19 package: Web320},{21 providerParams: ['WS://localhost:8546'],22 providerType: 'WebsocketProvider',23 package: Web324},{25 providerParams: ['wss://user1:passw0rd@localhost:8546'],26 providerType: 'WebsocketProvider',27 package: Web328},{29 providerParams: ['/.ethereum/my/path/geth.ipc', net],30 providerType: 'IpcProvider',31 package: Web332},{33 providerParams: ['\\\\.\\pipe\\geth.ipc', net],34 providerType: 'IpcProvider',35 package: Web336},{37 providerParams: ['://hello.com:1234'],38 package: Web3,39 error: true40},41 {42 providerParams: ['http://localhost:8545'],43 providerType: 'HttpProvider',44 package: Net45 },{46 providerParams: ['HTTP://localhost:8545'],47 providerType: 'HttpProvider',48 package: Net49 },{50 providerParams: ['ws://localhost:8546'],51 providerType: 'WebsocketProvider',52 package: Net53 },{54 providerParams: ['WS://localhost:8546'],55 providerType: 'WebsocketProvider',56 package: Net57 },{58 providerParams: ['/.ethereum/my/path/geth.ipc', net],59 providerType: 'IpcProvider',60 package: Net61 },{62 providerParams: ['\\\\.\\pipe\\geth.ipc', net],63 providerType: 'IpcProvider',64 package: Net65 },{66 providerParams: ['://hello.com:1234'],67 package: Net,68 error: true69 },70 {71 providerParams: ['http://localhost:8545'],72 providerType: 'HttpProvider',73 package: Shh74 },{75 providerParams: ['HTTP://localhost:8545'],76 providerType: 'HttpProvider',77 package: Shh78 },{79 providerParams: ['ws://localhost:8546'],80 providerType: 'WebsocketProvider',81 package: Shh82 },{83 providerParams: ['WS://localhost:8546'],84 providerType: 'WebsocketProvider',85 package: Shh86 },{87 providerParams: ['/.ethereum/my/path/geth.ipc', net],88 providerType: 'IpcProvider',89 package: Shh90 },{91 providerParams: ['\\\\.\\pipe\\geth.ipc', net],92 providerType: 'IpcProvider',93 package: Shh94 },{95 providerParams: ['://hello.com:1234'],96 package: Shh,97 error: true98 },99 {100 providerParams: ['http://localhost:8545'],101 providerType: 'HttpProvider',102 package: Eth103 },{104 providerParams: ['HTTP://localhost:8545'],105 providerType: 'HttpProvider',106 package: Eth107 },{108 providerParams: ['ws://localhost:8546'],109 providerType: 'WebsocketProvider',110 package: Eth111 },{112 providerParams: ['WS://localhost:8546'],113 providerType: 'WebsocketProvider',114 package: Eth115 },{116 providerParams: ['/.ethereum/my/path/geth.ipc', net],117 providerType: 'IpcProvider',118 package: Eth119 },{120 providerParams: ['\\\\.\\pipe\\geth.ipc', net],121 providerType: 'IpcProvider',122 package: Eth123 },{124 providerParams: ['://hello.com:1234'],125 package: Eth,126 error: true127 }];128describe('web3', function () {129 describe('automatic provider selection', function () {130 tests.forEach(function (test, index) {131 if(!test.error) {132 it('initiates on package level', function () {133 var pkg = new test.package(test.providerParams[0], test.providerParams[1]);134 assert.equal(pkg.currentProvider.constructor.name, test.providerType);135 });136 it('initiates using setProvider', function () {137 var pkg = new test.package();138 assert.equal(pkg.currentProvider, null);139 pkg.setProvider.apply(pkg, test.providerParams);140 assert.equal(pkg.currentProvider.constructor.name, test.providerType);141 });142 } else {143 it('can\'t autodetect the provider', function () {144 assert.throws(function(){ new test.package(test.providerParams[0]); });145 });146 it('can\'t autodetect the provider when using setProvider', function () {147 var pkg = new test.package();148 assert.throws(function(){ pkg.setProvider(test.providerParams[0]); });149 });150 }151 });152 });...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const synthetixio = require('synthetixio-synpress');2const provider = synthetixio.provider();3const ethers = require('ethers');4const provider = ethers.getDefaultProvider('ropsten');5const Web3 = require('web3');6const HDWalletProvider = require('truffle-hdwallet-provider');7const PrivateKeyProvider = require('truffle-privatekey-provider');8const Provider = require('truffle-provider');9const Web3ProviderEngine = require('web3-provider-engine');10const provider = new Web3ProviderEngine();11const Web3ProviderEngine = require('web3-provider-engine');12const provider = new Web3ProviderEngine();13const Web3ProviderEngine = require('web3-provider-engine');14const provider = new Web3ProviderEngine();15const Web3ProviderEngine = require('web3-provider-engine');16const provider = new Web3ProviderEngine();17const Web3ProviderEngine = require('web3-provider-engine');18const provider = new Web3ProviderEngine();19const Web3ProviderEngine = require('web3-provider-engine');20const provider = new Web3ProviderEngine();21const Web3ProviderEngine = require('web3-provider-engine');22const provider = new Web3ProviderEngine();23const Web3ProviderEngine = require('web3-provider-engine');24const provider = new Web3ProviderEngine();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { provider } = require('synthetixio-synpress');2const { provider } = require('hardhat');3const { provider } = require('waffle');4const { provider } = require('ethers');5const { provider } = require('web3');6const { provider } = require('web3-eth');7const { provider } = require('web3-provider-engine');8const { provider } = require('web3-shh');9const { provider } = require('web3-bzz');10const { provider } = require('web3-eth-accounts');11const { provider } = require('web3-eth-ens');12const { provider } = require('web3-eth-iban');13const { provider } = require('web3-eth-personal');14const { provider } = require('web3-net');15const { provider } = require('web3-utils');16const { provider } = require('web3-core');17const { provider } = require('web3-core-helpers');18const { provider } = require('web3-core-method');19const { provider } = require('web3-core-subscriptions');20const { provider } = require('web3-core-requestmanager');21const { provider } = require('web3-core-promievent

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Synpress } = require('synthetixio-synpress');2const { SynthetixJs } = require('synthetixio-js');3const { ethers } = require('ethers');4async function init() {5 const synpress = new Synpress(provider);6 const synthetixJs = new SynthetixJs(provider);7 const accounts = await provider.listAccounts();8 const account = accounts[0];9 const balance = await synthetixJs.SynthetixJs.contractSettings.synthetixContract.balanceOf(account);10 console.log(balance);11}12init();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Synpress } = require('synthetixio-synpress');2const { ethers } = require('ethers');3const { SynthetixJs } = require('synthetix-js');4const synpress = new Synpress(provider);5const synthetixJs = new SynthetixJs({ networkId: 15 });6 .Synthetix.contractAddress;7 .Synthetix.abi;8const synthetixContract = new ethers.Contract(9);10const synthetixContractBalance = await synthetixContract.balanceOf(11);12const synthetixContractBalance = await synpress.callContractMethod(13);14const synthetixContractBalance = await synpress.callContractMethod(15);

Full Screen

Using AI Code Generation

copy

Full Screen

1const { SynpressProvider } = require('synthetixio-synpress');2const { Synpress } = require('synpress');3const provider = new SynpressProvider();4const synpress = new Synpress(provider);5synpress.test('Test 2', async () => {6});7synpress.run();8synpress.run({ browser: 'chrome' });9synpress.run({ browser: 'chrome', headless: true });10synpress.run({ browser: 'chrome', headless: true, viewport: { width: 1366, height: 768 } });11synpress.run({ browser: 'chrome', headless: true, viewport: { width: 1366, height: 768 }, slowMo: 50 });12synpress.run({ browser: 'chrome', headless: true, viewport: { width: 1366, height: 768 }, slowMo: 50, timeout: 10000 });13synpress.run({ browser: 'chrome', headless: true, viewport: { width: 1366, height: 768 }, slowMo: 50, timeout: 10000, browserPath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' });14synpress.run({ browser: 'chrome', headless: true, viewport: { width: 1366, height: 768 }, slowMo: 50, timeout: 10000, browserPath: '/Applications/Google Chrome.app/Contents/MacOS/

Full Screen

Using AI Code Generation

copy

Full Screen

1const Synpress = require('synpress');2const Provider = Synpress.provider;3provider.getAccounts().then(accounts => {4 console.log(accounts);5});6provider.getBalance('0x0').then(balance => {7 console.log(balance);8});9const Web3 = require('web3');10web3.eth.getAccounts().then(accounts => {11 console.log(accounts);12});13web3.eth.getBalance('0x0').then(balance => {14 console.log(balance);15});16const Web3 = require('web3');17web3.eth.getAccounts().then(accounts => {18 console.log(accounts);19});20web3.eth.getBalance('0x0').then(balance => {21 console.log(balance);22});23const Web3 = require('web3');24web3.eth.getAccounts().then(accounts => {25 console.log(accounts);26});27web3.eth.getBalance('0x0').then(balance => {28 console.log(balance);29});30const Web3 = require('web3');31web3.eth.getAccounts().then(accounts => {32 console.log(accounts);33});34web3.eth.getBalance('0x0').then(balance => {35 console.log(balance);36});37const Web3 = require('web3');38web3.eth.getAccounts().then(accounts => {39 console.log(accounts);40});41web3.eth.getBalance('0x0').then(balance => {42 console.log(balance);43});44const Web3 = require('web3');45web3.eth.getAccounts().then(accounts => {

Full Screen

Using AI Code Generation

copy

Full Screen

1const Synpress = require('synthetixio-synpress');2const provider = Synpress.provider();3const ethers = require('ethers');4const provider = new ethers.providers.JsonRpcProvider();5const wallet = new ethers.Wallet('0x...', provider);6const contract = new ethers.Contract(address, abi, provider);7const contractWithSigner = contract.connect(wallet);8const ethers = require('ethers');9const Synpress = require('synthetixio-synpress');10const provider = Synpress.provider();11const wallet = new ethers.Wallet('0x...', provider);12const contract = new ethers.Contract(address, abi, provider);13const contractWithSigner = contract.connect(wallet);14const Web3 = require('web3');15const Synpress = require('synthetixio-synpress');16const provider = Synpress.provider();17const web3 = new Web3(provider);18const wallet = web3.eth.accounts.wallet.add('0x...');19const contract = new web3.eth.Contract(abi, address);20const contractWithSigner = contract.methods.myMethod().send({ from: wallet.address });21const Synpress = require('synthetixio-synpress');22const provider = Synpress.provider();23const contract = new web3.eth.Contract(abi, address, { from: address });24const contractWithSigner = contract.methods.myMethod().send({ from: address });25const Synpress = require('synthetixio-synpress');26const provider = Synpress.provider();27const contract = new ethers.Contract(address, abi, provider);28const contractWithSigner = contract.connect(wallet);29const Web3 = require('web3');30const Synpress = require('synthetixio-synpress');31const provider = Synpress.provider();32const web3 = new Web3(provider);33const wallet = web3.eth.accounts.wallet.add('0x...');34const contract = new web3.eth.Contract(abi, address);35const contractWithSigner = contract.methods.myMethod().send({ from: wallet.address });36const Synpress = require('synthetixio-synpress');37const provider = Synpress.provider();38const contract = new web3.eth.Contract(abi, address, {

Full Screen

Using AI Code Generation

copy

Full Screen

1const Synpress = require("synthetixio-synpress");2const synpress = new Synpress();3const web3 = synpress.provider();4const contract = new web3.eth.Contract(5);6 .balanceOf(address)7 .call();8console.log(result);9const Synpress = require("synthetixio-synpress");10const synpress = new Synpress();11const snapshotId = await synpress.snapshot();12console.log(snapshotId);

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run synthetixio-synpress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful